game-networking-sockets-sys 0.2.0

Rust bindings for Valve GameNetworkingSockets library.
Documentation
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
//====== Copyright Valve Corporation, All rights reserved. ====================

#include "csteamnetworkingsockets.h"
#include "steamnetworkingsockets_lowlevel.h"
#include "steamnetworkingsockets_connections.h"
#include "steamnetworkingsockets_udp.h"
#include "../steamnetworkingsockets_certstore.h"
#include "crypto.h"

#ifdef STEAMNETWORKINGSOCKETS_STANDALONELIB
#include <steam/steamnetworkingsockets.h>
#endif

#ifdef STEAMNETWORKINGSOCKETS_ENABLE_STEAMNETWORKINGMESSAGES
#include "csteamnetworkingmessages.h"
#endif

#ifdef STEAMNETWORKINGSOCKETS_ENABLE_FAKEIP
#include <steam/steamnetworkingfakeip.h>
#endif

// Needed for the platform checks below
#if defined(__APPLE__)
	#include "AvailabilityMacros.h"
	#include "TargetConditionals.h"
#endif

// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"

ISteamNetworkingSockets::~ISteamNetworkingSockets() {}
ISteamNetworkingUtils::~ISteamNetworkingUtils() {}

// Put everything in a namespace, so we don't violate the one definition rule
namespace SteamNetworkingSocketsLib {

/////////////////////////////////////////////////////////////////////////////
//
// Configuration Variables
//
/////////////////////////////////////////////////////////////////////////////

DEFINE_GLOBAL_CONFIGVAL( float, FakePacketLoss_Send, 0.0f, 0.0f, 100.0f );
DEFINE_GLOBAL_CONFIGVAL( float, FakePacketLoss_Recv, 0.0f, 0.0f, 100.0f );
DEFINE_GLOBAL_CONFIGVAL( int32, FakePacketLag_Send, 0, 0, 5000 );
DEFINE_GLOBAL_CONFIGVAL( int32, FakePacketLag_Recv, 0, 0, 5000 );
DEFINE_GLOBAL_CONFIGVAL( float, FakePacketReorder_Send, 0.0f, 0.0f, 100.0f );
DEFINE_GLOBAL_CONFIGVAL( float, FakePacketReorder_Recv, 0.0f, 0.0f, 100.0f );
DEFINE_GLOBAL_CONFIGVAL( int32, FakePacketReorder_Time, 15, 0, 5000 );
DEFINE_GLOBAL_CONFIGVAL( float, FakePacketDup_Send, 0.0f, 0.0f, 100.0f );
DEFINE_GLOBAL_CONFIGVAL( float, FakePacketDup_Recv, 0.0f, 0.0f, 100.0f );
DEFINE_GLOBAL_CONFIGVAL( int32, FakePacketDup_TimeMax, 10, 0, 5000 );
DEFINE_GLOBAL_CONFIGVAL( int32, PacketTraceMaxBytes, -1, -1, 99999 );
DEFINE_GLOBAL_CONFIGVAL( int32, FakeRateLimit_Send_Rate, 0, 0, 1024*1024*1024 );
DEFINE_GLOBAL_CONFIGVAL( int32, FakeRateLimit_Send_Burst, 16*1024, 0, 1024*1024 );
DEFINE_GLOBAL_CONFIGVAL( int32, FakeRateLimit_Recv_Rate, 0, 0, 1024*1024*1024 );
DEFINE_GLOBAL_CONFIGVAL( int32, FakeRateLimit_Recv_Burst, 16*1024, 0, 1024*1024 );
DEFINE_GLOBAL_CONFIGVAL( int32, OutOfOrderCorrectionWindowMicroseconds, 1000, 0, 50*1000 );
DEFINE_GLOBAL_CONFIGVAL( float, FakePacketJitter_Send_Avg, 0.0f, 0.0f, 2000.0f );
DEFINE_GLOBAL_CONFIGVAL( float, FakePacketJitter_Send_Max, 100.0f, 0.0f, 5000.0f );
DEFINE_GLOBAL_CONFIGVAL( float, FakePacketJitter_Send_Pct, 75.0f, 0.0f, 100.0f );
DEFINE_GLOBAL_CONFIGVAL( float, FakePacketJitter_Recv_Avg, 0.0f, 0.0f, 2000.0f );
DEFINE_GLOBAL_CONFIGVAL( float, FakePacketJitter_Recv_Max, 100.0f, 0.0f, 5000.0f );
DEFINE_GLOBAL_CONFIGVAL( float, FakePacketJitter_Recv_Pct, 75.0f, 0.0f, 100.0f );

DEFINE_GLOBAL_CONFIGVAL( void *, Callback_AuthStatusChanged, nullptr );
#ifdef STEAMNETWORKINGSOCKETS_ENABLE_STEAMNETWORKINGMESSAGES
DEFINE_GLOBAL_CONFIGVAL( void*, Callback_MessagesSessionRequest, nullptr );
DEFINE_GLOBAL_CONFIGVAL( void*, Callback_MessagesSessionFailed, nullptr );
#endif
DEFINE_GLOBAL_CONFIGVAL( void *, Callback_CreateConnectionSignaling, nullptr );
#ifdef STEAMNETWORKINGSOCKETS_ENABLE_FAKEIP
DEFINE_GLOBAL_CONFIGVAL( void *, Callback_FakeIPResult, nullptr );
#endif

DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, TimeoutInitial, 10000, 0, INT32_MAX );
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, TimeoutConnected, 10000, 0, INT32_MAX );
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, SendBufferSize, 512*1024, 4*1024, 0x10000000 );
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, RecvBufferSize, 1024*1024, 4*1024, 0x10000000 );
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, RecvBufferMessages, 1000, 2, 0x10000000 );
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, RecvMaxMessageSize, 512*1024, 64, 0x10000000 );
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, RecvMaxSegmentsPerPacket, k_cbSteamNetworkingSocketsMaxUDPMsgLen, 1, k_cbSteamNetworkingSocketsMaxUDPMsgLen );
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int64, ConnectionUserData, -1 ); // no limits here
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, SendRateMin, 256*1024, 1024, 0x10000000 );
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, SendRateMax, 256*1024, 1024, 0x10000000 );
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, NagleTime, 5000, 0, 20000 );
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, MTU_PacketSize, 1300, k_cbSteamNetworkingSocketsMinMTUPacketSize, k_cbSteamNetworkingSocketsMaxUDPMsgLen );
#ifdef STEAMNETWORKINGSOCKETS_OPENSOURCE
	// We don't have a trusted third party, so allow this by default,
	// and don't warn about it
	DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, IP_AllowWithoutAuth, 2, 0, 2 );
	DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, IPLocalHost_AllowWithoutAuth, 2, 0, 2 );
#else
	DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, IP_AllowWithoutAuth, 0, 0, 2 );
	DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, IPLocalHost_AllowWithoutAuth, 0, 0, 2 );
#endif
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, Unencrypted, 0, 0, 3 );
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, SymmetricConnect, 0, 0, 1 );
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, LocalVirtualPort, -1, -1, INT32_MAX );
#ifdef STEAMNETWORKINGSOCKETS_ENABLE_DUALWIFI
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, DualWifi_Enable, 1, 0, k_nDualWifiEnable_MAX );
#endif
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, LogLevel_AckRTT, k_ESteamNetworkingSocketsDebugOutputType_Warning, k_ESteamNetworkingSocketsDebugOutputType_Error, k_ESteamNetworkingSocketsDebugOutputType_Everything );
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, LogLevel_PacketDecode, k_ESteamNetworkingSocketsDebugOutputType_Warning, k_ESteamNetworkingSocketsDebugOutputType_Error, k_ESteamNetworkingSocketsDebugOutputType_Everything );
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, LogLevel_Message, k_ESteamNetworkingSocketsDebugOutputType_Warning, k_ESteamNetworkingSocketsDebugOutputType_Error, k_ESteamNetworkingSocketsDebugOutputType_Everything );
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, LogLevel_PacketGaps, k_ESteamNetworkingSocketsDebugOutputType_Warning, k_ESteamNetworkingSocketsDebugOutputType_Error, k_ESteamNetworkingSocketsDebugOutputType_Everything );
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, LogLevel_P2PRendezvous, k_ESteamNetworkingSocketsDebugOutputType_Warning, k_ESteamNetworkingSocketsDebugOutputType_Error, k_ESteamNetworkingSocketsDebugOutputType_Everything );
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( void *, Callback_ConnectionStatusChanged, nullptr );
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, SendTimeSincePreviousPacket, -1, -1, 1 );

#ifdef STEAMNETWORKINGSOCKETS_ENABLE_DIAGNOSTICSUI
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, EnableDiagnosticsUI, 1, 0, 1 );
#endif

#ifdef STEAMNETWORKINGSOCKETS_ENABLE_ICE
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( std::string, P2P_STUN_ServerList, "" );
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( std::string, P2P_TURN_ServerList, "" );
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( std::string, P2P_TURN_UserList, "" );
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( std::string, P2P_TURN_PassList, "" );
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, P2P_Transport_ICE_Implementation, 0, 0, 2 );

COMPILE_TIME_ASSERT( k_nSteamNetworkingConfig_P2P_Transport_ICE_Enable_Default == -1 );
COMPILE_TIME_ASSERT( k_nSteamNetworkingConfig_P2P_Transport_ICE_Enable_Disable == 0 );
#ifdef STEAMNETWORKINGSOCKETS_OPENSOURCE
	// There is no such thing as "default" if we don't have some sort of platform
	DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, P2P_Transport_ICE_Enable, k_nSteamNetworkingConfig_P2P_Transport_ICE_Enable_All, k_nSteamNetworkingConfig_P2P_Transport_ICE_Enable_Disable, k_nSteamNetworkingConfig_P2P_Transport_ICE_Enable_All );
#else
	DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, P2P_Transport_ICE_Enable, k_nSteamNetworkingConfig_P2P_Transport_ICE_Enable_Default, k_nSteamNetworkingConfig_P2P_Transport_ICE_Enable_Default, k_nSteamNetworkingConfig_P2P_Transport_ICE_Enable_All );
#endif

DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, P2P_Transport_ICE_Penalty, 0, 0, INT_MAX );
#endif

#ifdef STEAMNETWORKINGSOCKETS_ENABLE_SDR
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( std::string, SDRClient_DevTicket, "" );
DEFINE_CONNECTON_DEFAULT_CONFIGVAL( int32, P2P_Transport_SDR_Penalty, 0, 0, INT_MAX );
#endif

#if PlatformCanSendECN()
DEFINE_GLOBAL_CONFIGVAL( int32, ECN, -1, -1, 2 );
#endif

static GlobalConfigValueEntry *s_pFirstGlobalConfigEntry = nullptr;
static bool s_bConfigValueTableInitted = false;
static std::vector<GlobalConfigValueEntry *> s_vecConfigValueTable; // Sorted by value
static std::vector<GlobalConfigValueEntry *> s_vecConnectionConfigValueTable; // Sorted by offset

GlobalConfigValueEntry::GlobalConfigValueEntry(
	ESteamNetworkingConfigValue eValue,
	const char *pszName,
	ESteamNetworkingConfigDataType eDataType,
	ESteamNetworkingConfigScope eScope,
	int cbOffsetOf
) : m_eValue{ eValue }
, m_pszName{ pszName }
, m_eDataType{ eDataType }
, m_eScope{ eScope }
, m_cbOffsetOf{cbOffsetOf}
, m_pNextEntry( s_pFirstGlobalConfigEntry )
{
	s_pFirstGlobalConfigEntry = this;
	AssertMsg( !s_bConfigValueTableInitted, "Attempt to register more config values after table is already initialized" );
	s_bConfigValueTableInitted = false;
}

static void EnsureConfigValueTableInitted()
{
	SteamNetworkingGlobalLock::AssertHeldByCurrentThread( "EnsureConfigValueTableInitted" );
	if ( s_bConfigValueTableInitted )
		return;

	for ( GlobalConfigValueEntry *p = s_pFirstGlobalConfigEntry ; p ; p = p->m_pNextEntry )
	{
		s_vecConfigValueTable.push_back( p );
		if ( p->m_eScope == k_ESteamNetworkingConfig_Connection )
			s_vecConnectionConfigValueTable.push_back( p );
	}

	// Sort in ascending order by value, so we can binary search
	std::sort( s_vecConfigValueTable.begin(), s_vecConfigValueTable.end(),
		[]( GlobalConfigValueEntry *a, GlobalConfigValueEntry *b ) { return a->m_eValue < b->m_eValue; } );

	// Sort by struct offset, so that ConnectionConfig::Init will access memory in a sane way.
	// This doesn't really matter, though.
	std::sort( s_vecConnectionConfigValueTable.begin(), s_vecConnectionConfigValueTable.end(),
		[]( GlobalConfigValueEntry *a, GlobalConfigValueEntry *b ) { return a->m_cbOffsetOf < b->m_cbOffsetOf; } );

	// Rebuild linked list, in order, and safety check for duplicates
	const int N = len( s_vecConfigValueTable );
	for ( int i = 1 ; i < N ; ++i )
	{
		s_vecConfigValueTable[i-1]->m_pNextEntry = s_vecConfigValueTable[i];
		AssertFatalMsg( s_vecConfigValueTable[i-1]->m_eValue < s_vecConfigValueTable[i]->m_eValue, "Registered duplicate config value %d", s_vecConfigValueTable[i]->m_eValue );
	}
	s_vecConfigValueTable[N-1]->m_pNextEntry = nullptr;

	s_pFirstGlobalConfigEntry = nullptr;
	s_bConfigValueTableInitted = true; // Set this flag LAST
}

static GlobalConfigValueEntry *FindConfigValueEntry( ESteamNetworkingConfigValue eSearchVal )
{
	Assert( s_bConfigValueTableInitted );

	// Binary search
	int l = 0;
	int r = len( s_vecConfigValueTable )-1;
	Assert( r > 0 ); // Order of operations -- table not initialized!
	while ( l <= r )
	{
		int m = (l+r)>>1;
		GlobalConfigValueEntry *mp = s_vecConfigValueTable[m];
		if ( eSearchVal < mp->m_eValue )
			r = m-1;
		else if ( eSearchVal > mp->m_eValue )
			l = m+1;
		else
			return mp;
	}

	// Not found
	return nullptr;
}

void ConnectionConfig::Init( ConnectionConfig *pInherit )
{
	Assert( s_bConfigValueTableInitted );

	for ( GlobalConfigValueEntry *pEntry : s_vecConnectionConfigValueTable )
	{
		ConfigValueBase *pVal = (ConfigValueBase *)((intptr_t)this + pEntry->m_cbOffsetOf );
		if ( pInherit )
		{
			pVal->m_pInherit = (ConfigValueBase *)((intptr_t)pInherit + pEntry->m_cbOffsetOf );
		}
		else
		{
			// Assume the relevant members are the same, no matter
			// what type T, so just use int32 arbitrarily
			pVal->m_pInherit = &( static_cast< GlobalConfigValueBase<int32> * >( pEntry ) )->m_value;
		}
	}
}

/////////////////////////////////////////////////////////////////////////////
//
// Table of active sockets
//
/////////////////////////////////////////////////////////////////////////////

CUtlHashMap<uint16, CSteamNetworkConnectionBase *, std::equal_to<uint16>, Identity<uint16> > g_mapConnections;
CUtlHashMap<int, CSteamNetworkPollGroup *, std::equal_to<int>, Identity<int> > g_mapPollGroups;
TableLock g_tables_lock;

// Table of active listen sockets.  Listen sockets and this table are protected
// by the global lock.
CUtlHashMap<int, CSteamNetworkListenSocketBase *, std::equal_to<int>, Identity<int> > g_mapListenSockets;

static bool BConnectionStateExistsToAPI( ESteamNetworkingConnectionState eState )
{
	switch ( eState )
	{
		default:
			Assert( false );
			return false;
		case k_ESteamNetworkingConnectionState_None:
		case k_ESteamNetworkingConnectionState_Dead:
		case k_ESteamNetworkingConnectionState_FinWait:
		case k_ESteamNetworkingConnectionState_Linger:
			return false;

		case k_ESteamNetworkingConnectionState_Connecting:
		case k_ESteamNetworkingConnectionState_FindingRoute:
		case k_ESteamNetworkingConnectionState_Connected:
		case k_ESteamNetworkingConnectionState_ClosedByPeer:
		case k_ESteamNetworkingConnectionState_ProblemDetectedLocally:
			return true;
	}

}

static CSteamNetworkConnectionBase *InternalGetConnectionByHandle( HSteamNetConnection sock, ConnectionScopeLock &scopeLock, const char *pszLockTag, bool bForAPI )
{
	if ( sock == 0 )
		return nullptr;

	// Take locks by "trying" and using a short timeout.  The table lock
	// should only be held by any one thread for an extremely short period
	// of time, so if we end up waiting/looping here, it should be blocked
	// on the connection lock.  In general we should very seldom need
	// to actually loop here, but doing this protects against a deadlock,
	// because in rare situations we do need to take the locks in the
	// opposite order.
	for (;;)
	{

		// First take the table lock
		TableScopeLock tableScopeLock;
		if ( !tableScopeLock.TryLock( g_tables_lock, 1, nullptr ) )
			continue;

		int idx = g_mapConnections.Find( uint16( sock ) );
		if ( idx == g_mapConnections.InvalidIndex() )
			break;
		CSteamNetworkConnectionBase *pResult = g_mapConnections[ idx ];
		if ( !pResult )
		{
			AssertMsg( false, "g_mapConnections corruption!" );
			break;
		}
		if ( uint16( pResult->m_hConnectionSelf ) != uint16( sock ) )
		{
			AssertMsg( false, "Connection map corruption!" );
			break;
		}

		// Fetch the state of the connection.  This is OK to do
		// even if we don't have the lock.  If the connection
		// is already dead we can avoid even trying to take
		// the lock.  That's good because cleaning up is one
		// of the rare cases where we take locks in the opposite
		// order, so we want to avoid that.
		ESteamNetworkingConnectionState s = pResult->GetState();
		if ( s == k_ESteamNetworkingConnectionState_Dead )
			break;
		if ( bForAPI )
		{
			if ( !BConnectionStateExistsToAPI( s ) )
				break;
		}

		// State looks good, try to lock the connection.
		// NOTE: we still (briefly) hold the table lock!
		// Taking the locks in this order (table, then connection)
		// is the most common case by far, but in very rare
		// cases we might need to take them in the opposite
		// order, hence the loop
		if ( !scopeLock.TryLock( *pResult->m_pLock, 1, pszLockTag ) )
			continue;

		// Re-check the connection state, in case something changed
		// while we were waiting on the lock
		s = pResult->GetState();
		if ( s != k_ESteamNetworkingConnectionState_Dead )
		{
			if ( !bForAPI || BConnectionStateExistsToAPI( s ) )
			{
				// NOTE: Exiting this scope will invoke TableScopeLock destructor,
				// which will unlock the table lock here, OUT OF ORDER of the order
				// that we took the locks.  That's intentional!  We don't need that
				// lock anymore, we have locked the connection that we want.
				return pResult;
			}
		}

		// Connection found in table, but should not be returned to the caller.
		// Go ahead and immediately unlock the connection lock, the caller should not
		// need it.
		scopeLock.Unlock();
		break;
	}

	return nullptr;
}

CSteamNetworkConnectionBase *GetConnectionByHandle( HSteamNetConnection sock, ConnectionScopeLock &scopeLock )
{
	SteamNetworkingGlobalLock::AssertHeldByCurrentThread();
	return InternalGetConnectionByHandle( sock, scopeLock, nullptr, false );
}

inline CSteamNetworkConnectionBase *GetConnectionByHandleForAPI( HSteamNetConnection sock, ConnectionScopeLock &scopeLock, const char *pszLockTag )
{
	return InternalGetConnectionByHandle( sock, scopeLock, pszLockTag, true );
}

static CSteamNetworkListenSocketBase *GetListenSocketByHandle( HSteamListenSocket sock )
{
	SteamNetworkingGlobalLock::AssertHeldByCurrentThread(); // listen sockets are protected by the global lock!
	if ( sock == k_HSteamListenSocket_Invalid )
		return nullptr;
	AssertMsg( !(sock & 0x80000000), "A poll group handle was used where a listen socket handle was expected" );
	int idx = sock & 0xffff;
	if ( !g_mapListenSockets.IsValidIndex( idx ) )
		return nullptr;
	CSteamNetworkListenSocketBase *pResult = g_mapListenSockets[ idx ];
	if ( pResult->m_hListenSocketSelf != sock )
	{
		// Slot was reused, but this handle is now invalid
		return nullptr;
	}
	return pResult;
}

CSteamNetworkPollGroup *GetPollGroupByHandle( HSteamNetPollGroup hPollGroup, PollGroupScopeLock &scopeLock, const char *pszLockTag )
{
	if ( hPollGroup == k_HSteamNetPollGroup_Invalid )
		return nullptr;
	AssertMsg( (hPollGroup & 0x80000000), "A listen socket handle was used where a poll group handle was expected" );
	int idx = hPollGroup & 0xffff;
	TableScopeLock tableScopeLock( g_tables_lock );
	if ( !g_mapPollGroups.IsValidIndex( idx ) )
		return nullptr;
	CSteamNetworkPollGroup *pResult = g_mapPollGroups[ idx ];

	// Make sure poll group is the one they really asked for, and also
	// handle deletion race condition
	while ( pResult->m_hPollGroupSelf == hPollGroup )
	{
		if ( scopeLock.TryLock( pResult->m_lock, 1, pszLockTag ) )
			return pResult;
	}

	// Slot was reused, but this handle is now invalid,
	// or poll group deleted race condition
	return nullptr;
}

/////////////////////////////////////////////////////////////////////////////
//
// CSteamSocketNetworkingBase
//
/////////////////////////////////////////////////////////////////////////////

std::vector<CSteamNetworkingSockets *> CSteamNetworkingSockets::s_vecSteamNetworkingSocketsInstances;

CSteamNetworkingSockets::CSteamNetworkingSockets( CSteamNetworkingUtils *pSteamNetworkingUtils )
: m_bHaveLowLevelRef( false )
, m_pSteamNetworkingUtils( pSteamNetworkingUtils )
#ifdef STEAMNETWORKINGSOCKETS_ENABLE_STEAMNETWORKINGMESSAGES
, m_pSteamNetworkingMessages( nullptr )
#endif
#ifdef STEAMNETWORKINGSOCKETS_CAN_REQUEST_CERT
, m_scheduleCheckRenewCert( this, &CSteamNetworkingSockets::CheckAuthenticationPrerequisites )
#endif
, m_bEverTriedToGetCert( false )
, m_bEverGotCert( false )
, m_mutexPendingCallbacks( "pending_callbacks", LockDebugInfo::k_nOrder_Max ) // Never take another lock while holding this
{
	m_connectionConfig.Init( nullptr );
	InternalClearIdentity();
}

void CSteamNetworkingSockets::InternalClearIdentity()
{
	m_identity.Clear();
	m_msgSignedCert.Clear();
	m_msgCert.Clear();
	m_keyPrivateKey.Wipe();

	#ifdef STEAMNETWORKINGSOCKETS_CAN_REQUEST_CERT
		m_CertStatus.m_eAvail = k_ESteamNetworkingAvailability_NeverTried;
		m_CertStatus.m_debugMsg[0] = '\0';
	#else
		m_CertStatus.m_eAvail = k_ESteamNetworkingAvailability_CannotTry;
		V_strcpy_safe( m_CertStatus.m_debugMsg, "No certificate authority" );
	#endif
	m_AuthenticationStatus = m_CertStatus;
	m_bEverTriedToGetCert = false;
	m_bEverGotCert = false;
}

void CSteamNetworkingSockets::InternalOnGotIdentity( int nIdentitySetFlags )
{
	// No base class action
}

CSteamNetworkingSockets::~CSteamNetworkingSockets()
{
	SteamNetworkingGlobalLock::AssertHeldByCurrentThread();
	Assert( !m_bHaveLowLevelRef ); // Called destructor directly?  Use Destroy()!
}

#ifdef STEAMNETWORKINGSOCKETS_OPENSOURCE
bool CSteamNetworkingSockets::BInitGameNetworkingSockets( const SteamNetworkingIdentity *pIdentity, SteamDatagramErrMsg &errMsg )
{
	AssertMsg( !m_bHaveLowLevelRef, "Initted interface twice?" );

	// Make sure low level socket support is ready
	if ( !BInitLowLevel( errMsg ) )
		return false;

	if ( pIdentity )
		m_identity = *pIdentity;
	else
		CacheIdentity();

	return true;
}
#endif

bool CSteamNetworkingSockets::BInitLowLevel( SteamNetworkingErrMsg &errMsg )
{
	if ( m_bHaveLowLevelRef )
		return true;
	if ( !BSteamNetworkingSocketsLowLevelAddRef( errMsg) )
		return false;

	// Add us to list of extant instances only after we have done some initialization
	if ( !has_element( s_vecSteamNetworkingSocketsInstances, this ) )
		s_vecSteamNetworkingSocketsInstances.push_back( this );

	m_bHaveLowLevelRef = true;
	return true;
}

void CSteamNetworkingSockets::KillConnections()
{
	SteamNetworkingGlobalLock::AssertHeldByCurrentThread( "CSteamNetworkingSockets::KillConnections" );
	TableScopeLock tableScopeLock( g_tables_lock );

	// Nuke all messages endpoints.  We need to do this because the sessions hold
	// pointers to objects that we are about to destroy.
	#ifdef STEAMNETWORKINGSOCKETS_ENABLE_STEAMNETWORKINGMESSAGES
		FOR_EACH_HASHMAP( m_mapMessagesEndpointByVirtualPort, idx )
		{
			m_mapMessagesEndpointByVirtualPort[idx]->DestroyMessagesEndPoint();
			Assert( !m_mapMessagesEndpointByVirtualPort.IsValidIndex( idx ) ); // It should have removed itself from the map!
		}
		Assert( m_pSteamNetworkingMessages == nullptr );
		Assert( m_mapMessagesEndpointByVirtualPort.Count() == 0 );
		m_pSteamNetworkingMessages = nullptr; // Buuuuut we'll slam it, too, in case there's a bug
		m_mapMessagesEndpointByVirtualPort.Purge();
	#endif

	// Destroy all of my connections
	CSteamNetworkConnectionBase::ProcessDeletionList();
	FOR_EACH_HASHMAP( g_mapConnections, idx )
	{
		CSteamNetworkConnectionBase *pConn = g_mapConnections[idx];
		if ( pConn->m_pSteamNetworkingSocketsInterface == this )
		{
			ConnectionScopeLock connectionLock( *pConn );

			// Check if it was left open, then do what we can to clean it up.
			// (If we can fire off a quick cleanup packet to our peer, do that.)
			if ( pConn->BStateIsActive() )
			{
				SpewMsg( "[%s] Cleaning up open connection on system shutdown", pConn->GetDescription() );
				pConn->APICloseConnection( k_ESteamNetConnectionEnd_AppException_Max, "SteamNetworkingSockets shutdown", false );
			}

			pConn->ConnectionQueueDestroy();
		}
	}
	CSteamNetworkConnectionBase::ProcessDeletionList();

	// Destroy all of my listen sockets
	FOR_EACH_HASHMAP( g_mapListenSockets, idx )
	{
		CSteamNetworkListenSocketBase *pSock = g_mapListenSockets[idx];
		if ( pSock->m_pSteamNetworkingSocketsInterface == this )
		{
			DbgVerify( CloseListenSocket( pSock->m_hListenSocketSelf ) );
			Assert( !g_mapListenSockets.IsValidIndex( idx ) );
		}
	}

	// Destroy all of my poll groups
	FOR_EACH_HASHMAP( g_mapPollGroups, idx )
	{
		CSteamNetworkPollGroup *pPollGroup = g_mapPollGroups[idx];
		if ( pPollGroup->m_pSteamNetworkingSocketsInterface == this )
		{
			DbgVerify( DestroyPollGroup( pPollGroup->m_hPollGroupSelf ) );
			Assert( !g_mapPollGroups.IsValidIndex( idx ) );
		}
	}
}

void CSteamNetworkingSockets::Destroy()
{
	SteamNetworkingGlobalLock::AssertHeldByCurrentThread( "CSteamNetworkingSockets::Destroy" );

	FreeResources();

	// Remove from list of extant instances, if we are there
	find_and_remove_element( s_vecSteamNetworkingSocketsInstances, this );

	delete this;
}

void CSteamNetworkingSockets::FreeResources()
{

	KillConnections();

	// Clear identity and crypto stuff.
	// If we are re-initialized, we might get new ones
	InternalClearIdentity();

	// Mark us as no longer being setup
	if ( m_bHaveLowLevelRef )
	{
		m_bHaveLowLevelRef = false;
		SteamNetworkingSocketsLowLevelDecRef();
	}
}

bool CSteamNetworkingSockets::BHasAnyConnections() const
{
	TableScopeLock tableScopeLock( g_tables_lock );
	for ( CSteamNetworkConnectionBase *pConn: g_mapConnections.IterValues() )
	{
		if ( pConn->m_pSteamNetworkingSocketsInterface == this )
			return true;
	}
	return false;
}

bool CSteamNetworkingSockets::BHasAnyListenSockets() const
{
	TableScopeLock tableScopeLock( g_tables_lock );
	for ( CSteamNetworkListenSocketBase *pSock: g_mapListenSockets.IterValues() )
	{
		if ( pSock->m_pSteamNetworkingSocketsInterface == this )
			return true;
	}
	return false;
}

bool CSteamNetworkingSockets::GetIdentity( SteamNetworkingIdentity *pIdentity )
{
	SteamNetworkingGlobalLock scopeLock( "GetIdentity" );
	InternalGetIdentity();
	if ( pIdentity )
		*pIdentity = m_identity;
	return !m_identity.IsInvalid();
}

int CSteamNetworkingSockets::GetSecondsUntilCertExpiry() const
{
	if ( !m_msgSignedCert.has_cert() )
		return INT_MIN;

	Assert( m_msgSignedCert.has_ca_signature() ); // Connections may use unsigned certs in certain situations, but we never use them here
	Assert( m_msgCert.has_key_data() );
	Assert( m_msgCert.has_time_expiry() ); // We should never generate keys without an expiry!

	int nSeconduntilExpiry = (long)m_msgCert.time_expiry() - (long)m_pSteamNetworkingUtils->GetTimeSecure();
	return nSeconduntilExpiry;
}

bool CSteamNetworkingSockets::GetCertificateRequest( int *pcbBlob, void *pBlob, SteamNetworkingErrMsg &errMsg )
{
	SteamNetworkingGlobalLock scopeLock( "GetCertificateRequest" );

	// If we don't have a private key, generate one now.
	CECSigningPublicKey pubKey;
	if ( m_keyPrivateKey.IsValid() )
	{
		DbgVerify( m_keyPrivateKey.GetPublicKey( &pubKey ) );
	}
	else
	{
		CCrypto::GenerateSigningKeyPair( &pubKey, &m_keyPrivateKey );
	}

	// Fill out the request
	CMsgSteamDatagramCertificateRequest msgRequest;
	CMsgSteamDatagramCertificate &msgCert =*msgRequest.mutable_cert();

	// Our public key
	msgCert.set_key_type( CMsgSteamDatagramCertificate_EKeyType_ED25519 );
	DbgVerify( pubKey.GetRawDataAsStdString( msgCert.mutable_key_data() ) );

	// Our identity, if we know it
	InternalGetIdentity();
	if ( !m_identity.IsInvalid() && !m_identity.IsLocalHost() )
	{
		SteamNetworkingIdentityToProtobuf( m_identity, msgCert, identity_string, legacy_identity_binary, legacy_steam_id );
	}

	// Are we a hosted server running in a data center?
	// Then cert should be restricted to that PoP
	SteamNetworkingPOPID popid = GetHostedDedicatedServerPOPID();
	if ( popid )
		msgCert.add_gameserver_datacenter_ids( popid );

	// Check size
	int cb = ProtoMsgByteSize( msgRequest );
	if ( !pBlob )
	{
		*pcbBlob = cb;
		return true;
	}
	if ( cb > *pcbBlob )
	{
		*pcbBlob = cb;
		V_sprintf_safe( errMsg, "%d byte buffer not big enough; %d bytes required", *pcbBlob, cb );
		return false;
	}

	*pcbBlob = cb;
	uint8 *p = (uint8 *)pBlob;
	DbgVerify( msgRequest.SerializeWithCachedSizesToArray( p ) == p + cb );
	return true;
}

bool CSteamNetworkingSockets::SetCertificate( const void *pCertificate, int cbCertificate, SteamNetworkingErrMsg &errMsg )
{
	SteamNetworkingGlobalLock scopeLock( "SetCertificate" );
	int nIdentitySetFlags = 0; // Allowing any reading/writing to the durable cache as appropriate
	return InternalSetCertificate( pCertificate, cbCertificate, errMsg, nIdentitySetFlags );
}

bool CSteamNetworkingSockets::InternalSetCertificate( const void *pCertificate, int cbCertificate, SteamNetworkingErrMsg &errMsg, int nIdentitySetFlags )
{
 	SteamNetworkingGlobalLock::AssertHeldByCurrentThread( "InternalSetCertificate" );

	// Crack the blob
	CMsgSteamDatagramCertificateSigned msgCertSigned;
	if ( !msgCertSigned.ParseFromArray( pCertificate, cbCertificate ) )
	{
		V_strcpy_safe( errMsg, "CMsgSteamDatagramCertificateSigned failed protobuf parse" );
		return false;
	}

	// Crack the cert, and check the signature.  If *we* aren't even willing
	// to trust it, assume that our peers won't either
	CMsgSteamDatagramCertificate msgCert;
	time_t authTime = m_pSteamNetworkingUtils->GetTimeSecure();
	const CertAuthScope *pAuthScope = CertStore_CheckCert( msgCertSigned, msgCert, authTime, errMsg );
	if ( !pAuthScope )
	{
		SpewWarning( "SetCertificate: We are not currently able to verify our own cert!  %s.  Continuing anyway!", errMsg );
	}

	// Extract the identity from the cert
	SteamNetworkingErrMsg tempErrMsg;
	SteamNetworkingIdentity certIdentity;
	int r = SteamNetworkingIdentityFromCert( certIdentity, msgCert, tempErrMsg );
	if ( r < 0 )
	{
		V_sprintf_safe( errMsg, "Cert has invalid identity.  %s", tempErrMsg );
		return false;
	}

	// If we already have an identity, it must match the cert
	bool bSetIdentity = false;
	if ( m_identity.IsInvalid() || m_identity.IsLocalHost() )
	{
		bSetIdentity = true;
	}
	else if ( !( m_identity == certIdentity ) )
	{
		V_sprintf_safe( errMsg, "Cert is for identity '%s'.  We are '%s'", SteamNetworkingIdentityRender( certIdentity ).c_str(), SteamNetworkingIdentityRender( m_identity ).c_str() );
		return false;
	}

	// We currently only support one key type
	if ( msgCert.key_type() != CMsgSteamDatagramCertificate_EKeyType_ED25519 || msgCert.key_data().size() != 32 )
	{
		V_strcpy_safe( errMsg, "Cert has invalid public key" );
		return false;
	}

	// FIXME - should we check if we already have a newer, equivalent cert?

	// Does cert contain a private key?
	if ( msgCertSigned.has_private_key_data() )
	{
		// The degree to which the key is actually "private" is not
		// really known to us.  However there are some use cases where
		// we will accept a cert
		const std::string &private_key_data = msgCertSigned.private_key_data();
		if ( m_keyPrivateKey.IsValid() )
		{

			// We already chose a private key, so the cert must match.
			// For the most common use cases, we choose a private
			// key and it never leaves the current process.
			if ( !m_keyPrivateKey.BMatchesRawData( private_key_data.data(), private_key_data.length() ) )
			{
				V_strcpy_safe( errMsg, "Private key mismatch" );
				return false;
			}
		}
		else
		{
			// We haven't chosen a private key yet, so we'll accept this one.
			if ( !m_keyPrivateKey.SetRawDataFromStdString( private_key_data ) )
			{
				V_strcpy_safe( errMsg, "Invalid private key" );
				return false;
			}
		}
	}
	else if ( !m_keyPrivateKey.IsValid() )
	{
		// WAT
		V_strcpy_safe( errMsg, "Cannot set cert.  No private key?" );
		return false;
	}

	// Make sure the cert actually matches our public key.
	if ( memcmp( msgCert.key_data().c_str(), m_keyPrivateKey.GetPublicKeyRawData(), 32 ) != 0 )
	{
		V_strcpy_safe( errMsg, "Cert public key does not match our private key" );
		return false;
	}

	// Make sure the cert authorizes us for the App we think we are running
	AppId_t nAppID = m_pSteamNetworkingUtils->GetAppID();
	if ( !CheckCertAppID( msgCert, pAuthScope, nAppID, tempErrMsg ) )
	{
		V_sprintf_safe( errMsg, "Cert does not authorize us for App %u", nAppID );
		return false;
	}

	// If we don't know our identity, then set it now.  Otherwise,
	// it better match.
	if ( bSetIdentity )
	{
		m_identity = certIdentity;
		SpewMsg( "Local identity established from certificate.  We are '%s'\n", SteamNetworkingIdentityRender( m_identity ).c_str() );
	}

	// Save it off
	m_msgSignedCert = std::move( msgCertSigned );
	m_msgCert = std::move( msgCert );
	// If shouldn't already be expired.
	AssertMsg( GetSecondsUntilCertExpiry() > 0, "Cert already invalid / expired?" );

	// If we just got our identity, let derived classes take action.  But our caller is
	// setting a specific cert, so don't try to load any other cert from the cache
	if ( bSetIdentity )
		InternalOnGotIdentity( nIdentitySetFlags | k_nIdentitySetFlag_NoLoadCert );

	// We've got a valid cert
	SetCertStatus( k_ESteamNetworkingAvailability_Current, "OK" );

	// Make sure we have everything else we need to do authentication.
	// This will also make sure we have renewal scheduled
	AuthenticationNeeded();

	// OK
	return true;
}

void CSteamNetworkingSockets::ResetIdentity( const SteamNetworkingIdentity *pIdentity )
{
	SteamNetworkingGlobalLock scopeLock( "ResetIdentity" );
	KillConnections();
	InternalClearIdentity();
	if ( pIdentity )
	{
		m_identity = *pIdentity;
		if ( !m_identity.IsInvalid() && !m_identity.IsLocalHost() )
		{
			int nIdentitySetFlags = k_nIdentitySetFlag_NoSave; // Allow us to check the durable cache for any credentials, but we know we are empty, so don't save anything
			InternalOnGotIdentity( nIdentitySetFlags );
		}
	}
}

ESteamNetworkingAvailability CSteamNetworkingSockets::InitAuthentication()
{
	SteamNetworkingGlobalLock scopeLock( "InitAuthentication" );

	// Check/fetch prerequisites
	AuthenticationNeeded();

	// Return status
	return m_AuthenticationStatus.m_eAvail;
}

void CSteamNetworkingSockets::CheckAuthenticationPrerequisites( SteamNetworkingMicroseconds usecNow )
{
#ifdef STEAMNETWORKINGSOCKETS_CAN_REQUEST_CERT
	SteamNetworkingGlobalLock::AssertHeldByCurrentThread();

	if ( !BCanRequestCert() )
		return;

	// Make sure we don't infinitely recurse here.
	// We might have a cert, but it's expired, so we try to request a new cert.
	// That might immediately fail.   But we already have a cert,
	// so we might try to schedule the next check by calling this function.
	// Which will immediately try to request a new cert (since the one we have is
	// expired), which might immediately fail, .... etc
	static bool s_bRecursionCheck = false;
	if ( s_bRecursionCheck )
	{
		m_scheduleCheckRenewCert.EnsureMinScheduleTime( SteamNetworkingSockets_GetLocalTimestamp() + k_nMillion*10 );
		return;
	}
	s_bRecursionCheck = true;
	RunCodeAtScopeExit( s_bRecursionCheck = false );

	// Check if we're in flight already.
	bool bInFlight = BCertRequestInFlight();

	// Do we already have a cert?
	if ( m_msgSignedCert.has_cert() )
	{
		//Assert( m_CertStatus.m_eAvail == k_ESteamNetworkingAvailability_Current );

		// How much more life does it have in it?
		int nSeconduntilExpiry = GetSecondsUntilCertExpiry();
		if ( nSeconduntilExpiry < 0 )
		{

			// It's already expired, we might as well discard it now.
			SpewMsg( "Cert expired %d seconds ago.  Discarding and requesting another\n", -nSeconduntilExpiry );
			m_msgSignedCert.Clear();
			m_msgCert.Clear();
			m_keyPrivateKey.Wipe();

			// Update cert status
			SetCertStatus( k_ESteamNetworkingAvailability_Previously, "Expired" );
		}
		else
		{

			// If request is already active, don't do any of the work below, and don't spam while we wait, since this function may be called frequently.
			if ( bInFlight )
				return;

			// Check if it's time to renew
			int nSecondsUntilRenew = nSeconduntilExpiry - k_nSecCertExpirySeekRenew;
			if ( nSecondsUntilRenew > 0 )
			{

				// Schedule a wakeup
				constexpr SteamNetworkingMicroseconds kFudge = k_nMillion*3/2;
				SteamNetworkingMicroseconds usecTargetCheck = std::min( usecNow + nSecondsUntilRenew*k_nMillion + kFudge, usecNow + 600*k_nMillion );
				SteamNetworkingMicroseconds usecScheduledCheck = m_scheduleCheckRenewCert.GetScheduleTime();
				if ( usecScheduledCheck <= usecTargetCheck + kFudge*2 )
				{
					// Currently scheduled time is good enough.  Don't constantly update the schedule time,
					// that involves a (small amount) of work.  Just wait for it
				}
				else
				{
					// Schedule a check later
					m_scheduleCheckRenewCert.Schedule( usecTargetCheck );

					// !TEST! Spew cert expiry
					long long expiry = m_msgCert.time_expiry(); Assert( expiry > 0 );
					long long now = m_pSteamNetworkingUtils->GetTimeSecure();
					long long nSecondsUntilExpiry = expiry - now;
					SpewMsg( "Certificate expires in %lldh%02lldm at %lld (current time %lld), will renew in %dh%02dm\n",
						nSecondsUntilExpiry/3600, ( nSecondsUntilExpiry/60 ) % 60, expiry, now,
						nSecondsUntilRenew/3600, (nSecondsUntilRenew/60)%60 );
				}
				return;
			}

			// Currently valid, but it's time to renew.  Spew about this.
			SpewMsg( "Cert expires in %d seconds.  Requesting another, but keeping current cert in case request fails\n", nSeconduntilExpiry );
		}
	}

	// If a request is already active, then we just need to wait for it to complete
	if ( bInFlight )
		return;

	// Invoke platform code to begin fetching a cert
	BeginFetchCertAsync();
#endif
}

void CSteamNetworkingSockets::SetCertStatus( ESteamNetworkingAvailability eAvail, const char *pszFmt, ... )
{
	char msg[ sizeof(m_CertStatus.m_debugMsg) ];
	va_list ap;
	va_start( ap, pszFmt );
	V_vsprintf_safe( msg, pszFmt, ap );
	va_end( ap );

	// Mark success or an attempt
	if ( eAvail == k_ESteamNetworkingAvailability_Current )
		m_bEverGotCert = true;
	if ( eAvail == k_ESteamNetworkingAvailability_Attempting || eAvail == k_ESteamNetworkingAvailability_Retrying )
		m_bEverTriedToGetCert = true;

	// If we failed, but we previously succeeded, convert to "previously"
	if ( eAvail == k_ESteamNetworkingAvailability_Failed && m_bEverGotCert )
		eAvail = k_ESteamNetworkingAvailability_Previously;

	// No change?
	if ( m_CertStatus.m_eAvail == eAvail && V_stricmp( m_CertStatus.m_debugMsg, msg ) == 0 )
		return;

	// Update
	m_CertStatus.m_eAvail = eAvail;
	V_strcpy_safe( m_CertStatus.m_debugMsg, msg );

	// Check if our high level authentication status changed
	DeduceAuthenticationStatus();
}

void CSteamNetworkingSockets::DeduceAuthenticationStatus()
{
	// For the base class, the overall authentication status is identical to the status of
	// our cert.  (Derived classes may add additional criteria)
	SetAuthenticationStatus( m_CertStatus );
}

void CSteamNetworkingSockets::SetAuthenticationStatus( const SteamNetAuthenticationStatus_t &newStatus )
{
	SteamNetworkingGlobalLock::AssertHeldByCurrentThread();

	// No change?
	bool bStatusChanged = newStatus.m_eAvail != m_AuthenticationStatus.m_eAvail;
	if ( !bStatusChanged && V_strcmp( m_AuthenticationStatus.m_debugMsg, newStatus.m_debugMsg ) == 0 )
		return;

	// Update
	m_AuthenticationStatus = newStatus;

	// Re-cache identity
	InternalGetIdentity();

	// Post a callback, but only if the high level status changed.  Don't post a callback just
	// because the message changed
	if ( bStatusChanged )
	{
		// Spew
		SpewMsg( "AuthStatus (%s):  %s  (%s)",
			SteamNetworkingIdentityRender( m_identity ).c_str(),
			GetAvailabilityString( m_AuthenticationStatus.m_eAvail ), m_AuthenticationStatus.m_debugMsg );

		QueueCallback( m_AuthenticationStatus, GlobalConfig::Callback_AuthStatusChanged.Get() );
	}
}

#ifdef STEAMNETWORKINGSOCKETS_CAN_REQUEST_CERT
void CSteamNetworkingSockets::AsyncCertRequestFinished()
{
	SteamNetworkingGlobalLock::AssertHeldByCurrentThread( "AsyncCertRequestFinished" );

	Assert( m_msgSignedCert.has_cert() );
	SetCertStatus( k_ESteamNetworkingAvailability_Current, "OK" );

	// Setup renewal check (this will also spew how much time until cert expires)
	m_scheduleCheckRenewCert.Cancel();
	CheckAuthenticationPrerequisites( SteamNetworkingSockets_GetLocalTimestamp() );

	// Check for any connections that we own that are waiting on a cert
	TableScopeLock tableScopeLock( g_tables_lock );
	for ( CSteamNetworkConnectionBase *pConn: g_mapConnections.IterValues() )
	{
		if ( pConn->m_pSteamNetworkingSocketsInterface == this )
			pConn->InterfaceGotCert();
	}
}

void CSteamNetworkingSockets::CertRequestFailed( ESteamNetworkingAvailability eCertAvail, ESteamNetConnectionEnd nConnectionEndReason, const char *pszMsg )
{
	SteamNetworkingGlobalLock::AssertHeldByCurrentThread( "CertRequestFailed" );

	SpewWarning( "Cert request for %s failed with reason code %d.  %s\n", SteamNetworkingIdentityRender( InternalGetIdentity() ).c_str(), nConnectionEndReason, pszMsg );

	// Schedule a retry.  Note that if we have active connections that need for a cert,
	// we may end up retrying sooner.  If we don't have any active connections, spamming
	// retries way too frequently may be really bad; we might end up DoS-ing ourselves.
	// Do we need to make this configurable?
	m_scheduleCheckRenewCert.Schedule( SteamNetworkingSockets_GetLocalTimestamp() + k_nMillion*30 );

	if ( m_msgSignedCert.has_cert() )
	{
		SpewMsg( "But we still have a valid cert, continuing with that one\n" );
		AsyncCertRequestFinished();
		return;
	}

	// Set generic cert status, so we will post a callback
	SetCertStatus( eCertAvail, "%s", pszMsg );

	TableScopeLock tableScopeLock( g_tables_lock );
	for ( CSteamNetworkConnectionBase *pConn: g_mapConnections.IterValues() )
	{
		if ( pConn->m_pSteamNetworkingSocketsInterface == this )
			pConn->CertRequestFailed( nConnectionEndReason, pszMsg );
	}

	// FIXME If we have any listen sockets, we might need to let them know about this as well?
}
#endif

ESteamNetworkingAvailability CSteamNetworkingSockets::GetAuthenticationStatus( SteamNetAuthenticationStatus_t *pDetails )
{
	SteamNetworkingGlobalLock scopeLock; // !SPEED! We could protect this with a more tightly scoped lock, if we think this is eomthing people might be polling

	// Return details, if requested
	if ( pDetails )
		*pDetails = m_AuthenticationStatus;

	// Return status
	return m_AuthenticationStatus.m_eAvail;
}

HSteamListenSocket CSteamNetworkingSockets::CreateListenSocketIP( const SteamNetworkingIPAddr &localAddr, int nOptions, const SteamNetworkingConfigValue_t *pOptions )
{
	SteamNetworkingGlobalLock scopeLock( "CreateListenSocketIP" );
	SteamDatagramErrMsg errMsg;
	CSteamNetworkListenSocketBase *pResult = InternalCreateListenSocketIP( localAddr, nOptions, pOptions, errMsg );
	if ( pResult )
		return pResult->m_hListenSocketSelf;

	SpewError( "Cannot create listen socket.  %s", errMsg );
	return k_HSteamListenSocket_Invalid;
}

CSteamNetworkListenSocketBase *CSteamNetworkingSockets::InternalCreateListenSocketIP( const SteamNetworkingIPAddr &localAddr, int nOptions, const SteamNetworkingConfigValue_t *pOptions, SteamDatagramErrMsg &errMsg )
{

	CSteamNetworkListenSocketDirectUDP *pSock = new CSteamNetworkListenSocketDirectUDP( this );
	if ( !pSock )
	{
		V_strcpy_safe( errMsg, "new failed" );
		return nullptr;
	}
	if ( !pSock->BInit( localAddr, nOptions, pOptions, errMsg ) )
	{
		pSock->Destroy();
		return nullptr;
	}

	return pSock;
}

HSteamNetConnection CSteamNetworkingSockets::ConnectByIPAddress( const SteamNetworkingIPAddr &address, int nOptions, const SteamNetworkingConfigValue_t *pOptions )
{
	SteamNetworkingGlobalLock scopeLock( "ConnectByIPAddress" );
	ConnectionScopeLock connectionLock;

	// Check if the IP address is "fake" and this is really a P2P connection
	#ifdef STEAMNETWORKINGSOCKETS_ENABLE_FAKEIP
		if ( address.IsFakeIP() )
		{
			// Cannot specify a local port
			for ( int idxOpt = 0 ; idxOpt < nOptions ; ++idxOpt )
			{
				if ( pOptions[idxOpt].m_eValue == k_ESteamNetworkingConfig_LocalVirtualPort )
				{
					SpewBug( "Cannot specify LocalVirtualPort when connecting by FakeIP" );
					return k_HSteamNetConnection_Invalid;
				}
			}

			SteamNetworkingIdentity identityRemote;
			identityRemote.SetIPAddr( address );
			int nRemoveVirtualPort = -1; // Ignored, we multiplex in this case based on the fake port
			CSteamNetworkConnectionBase *pConn = InternalConnectP2PDefaultSignaling( identityRemote, nRemoveVirtualPort, nOptions, pOptions, connectionLock );
			if ( !pConn )
				return k_HSteamNetConnection_Invalid;
			return pConn->m_hConnectionSelf;
		}
	#endif

	CSteamNetworkConnectionUDP *pConn = new CSteamNetworkConnectionUDP( this, connectionLock );
	if ( !pConn )
		return k_HSteamNetConnection_Invalid;
	SteamDatagramErrMsg errMsg;
	if ( !pConn->BInitConnect( address, nOptions, pOptions, errMsg ) )
	{
		SpewError( "Cannot create IPv4 connection.  %s", errMsg );
		pConn->ConnectionQueueDestroy();
		return k_HSteamNetConnection_Invalid;
	}

	return pConn->m_hConnectionSelf;
}


EResult CSteamNetworkingSockets::AcceptConnection( HSteamNetConnection hConn )
{
	SteamNetworkingGlobalLock scopeLock( "AcceptConnection" ); // Take global lock, since this will lead to connection state transition
	ConnectionScopeLock connectionLock;
	CSteamNetworkConnectionBase *pConn = GetConnectionByHandleForAPI( hConn, connectionLock, nullptr );
	if ( !pConn )
	{
		SpewError( "Cannot accept connection #%u; invalid connection handle", hConn );
		return k_EResultInvalidParam;
	}

	// Accept it
	return pConn->APIAcceptConnection();
}

bool CSteamNetworkingSockets::CloseConnection( HSteamNetConnection hConn, int nReason, const char *pszDebug, bool bEnableLinger )
{
	SteamNetworkingGlobalLock scopeLock( "CloseConnection" ); // Take global lock, we are going to change connection state and/or destroy objects
	ConnectionScopeLock connectionLock;
	CSteamNetworkConnectionBase *pConn = GetConnectionByHandleForAPI( hConn, connectionLock, nullptr );
	if ( !pConn )
		return false;

	// Close it
	pConn->APICloseConnection( nReason, pszDebug, bEnableLinger );
	return true;
}

bool CSteamNetworkingSockets::CloseListenSocket( HSteamListenSocket hSocket )
{
	SteamNetworkingGlobalLock scopeLock( "CloseListenSocket" ); // Take global lock, we are going to destroy objects
	CSteamNetworkListenSocketBase *pSock = GetListenSocketByHandle( hSocket );
	if ( !pSock )
		return false;

	// Delete the socket itself
	// NOTE: If you change this, look at CSteamSocketNetworking::Kill()!
	pSock->Destroy();
	return true;
}

bool CSteamNetworkingSockets::SetConnectionUserData( HSteamNetConnection hPeer, int64 nUserData )
{
	//SteamNetworkingGlobalLock scopeLock( "SetConnectionUserData" ); // NO, not necessary!
	ConnectionScopeLock connectionLock;
	CSteamNetworkConnectionBase *pConn = GetConnectionByHandleForAPI( hPeer, connectionLock, "SetConnectionUserData" );
	if ( !pConn )
		return false;
	pConn->SetUserData( nUserData );
	return true;
}

int64 CSteamNetworkingSockets::GetConnectionUserData( HSteamNetConnection hPeer )
{
	//SteamNetworkingGlobalLock scopeLock( "GetConnectionUserData" ); // NO, not necessary!
	ConnectionScopeLock connectionLock;
	CSteamNetworkConnectionBase *pConn = GetConnectionByHandleForAPI( hPeer, connectionLock, "GetConnectionUserData" );
	if ( !pConn )
		return -1;
	return pConn->GetUserData();
}

void CSteamNetworkingSockets::SetConnectionName( HSteamNetConnection hPeer, const char *pszName )
{
	SteamNetworkingGlobalLock scopeLock( "SetConnectionName" ); // NOTE: Yes, we must take global lock for this.  See CSteamNetworkConnectionBase::SetDescription
	ConnectionScopeLock connectionLock;
	CSteamNetworkConnectionBase *pConn = GetConnectionByHandleForAPI( hPeer, connectionLock, nullptr );
	if ( !pConn )
		return;
	pConn->SetAppName( pszName );
}

bool CSteamNetworkingSockets::GetConnectionName( HSteamNetConnection hPeer, char *pszName, int nMaxLen )
{
	//SteamNetworkingGlobalLock scopeLock( "GetConnectionName" ); // NO, not necessary!
	ConnectionScopeLock connectionLock;
	CSteamNetworkConnectionBase *pConn = GetConnectionByHandleForAPI( hPeer, connectionLock, "GetConnectionName" );
	if ( !pConn )
		return false;
	V_strncpy( pszName, pConn->GetAppName(), nMaxLen );
	return true;
}

EResult CSteamNetworkingSockets::ConfigureConnectionLanes( HSteamNetConnection hConn, int nNumLanes, const int *pLanePriorities, const uint16 *pLaneWeights )
{
	//SteamNetworkingGlobalLock scopeLock( "ConfigureConnectionLanes" ); // NO, not necessary!
	ConnectionScopeLock connectionLock;
	CSteamNetworkConnectionBase *pConn = GetConnectionByHandleForAPI( hConn, connectionLock, "ConfigureConnectionLanes" );
	if ( !pConn )
		return k_EResultNoConnection;
	if ( !pConn->BStateIsActive() )
		return k_EResultInvalidState;
	return pConn->SNP_ConfigureLanes( nNumLanes, pLanePriorities, pLaneWeights );
}

EResult CSteamNetworkingSockets::SendMessageToConnection( HSteamNetConnection hConn, const void *pData, uint32 cbData, int nSendFlags, int64 *pOutMessageNumber )
{
	//SteamNetworkingGlobalLock scopeLock( "SendMessageToConnection" ); // NO, not necessary!
	ConnectionScopeLock connectionLock;
	CSteamNetworkConnectionBase *pConn = GetConnectionByHandleForAPI( hConn, connectionLock, "SendMessageToConnection" );
	if ( !pConn )
		return k_EResultInvalidParam;
	return pConn->APISendMessageToConnection( pData, cbData, nSendFlags, pOutMessageNumber );
}

void CSteamNetworkingSockets::SendMessages( int nMessages, SteamNetworkingMessage_t **pMessages, int64 *pOutMessageNumberOrResult, bool bDeleteFailedMessages )
{

	// Get list of messages, grouped by connection.
	// But within the connection, it is important that we
	// keep them in the same order!
	struct SortMsg_t
	{
		HSteamNetConnection m_hConn;
		int m_idx;
		inline bool operator<(const SortMsg_t &x ) const
		{
			if ( m_hConn < x.m_hConn ) return true;
			if ( m_hConn > x.m_hConn ) return false;
			return m_idx < x.m_idx;
		}
	};
	SortMsg_t *pSortMessages = (SortMsg_t *)alloca( nMessages * sizeof(SortMsg_t) );
	int nSortMessages = 0;

	for ( int i = 0 ; i < nMessages ; ++i )
	{

		// Sanity check that message is valid
		CSteamNetworkingMessage *pMsg = static_cast<CSteamNetworkingMessage*>( pMessages[i] );
		if ( !pMsg )
		{
			if ( pOutMessageNumberOrResult )
				pOutMessageNumberOrResult[i] = -k_EResultInvalidParam;
			continue;
		}

		if ( pMsg->m_conn == k_HSteamNetConnection_Invalid )
		{
			if ( pOutMessageNumberOrResult )
				pOutMessageNumberOrResult[i] = -k_EResultInvalidParam;
			if ( bDeleteFailedMessages )
				pMsg->Release();
			continue;
		}

		pSortMessages[ nSortMessages ].m_hConn = pMsg->m_conn;
		pSortMessages[ nSortMessages ].m_idx = i;
		++nSortMessages;
	}

	if ( nSortMessages < 1 )
		return;

	SortMsg_t *const pSortEnd = pSortMessages+nSortMessages;
	std::sort( pSortMessages, pSortEnd );

	// OK, we are ready to begin

	// SteamNetworkingGlobalLock scopeLock( "SendMessages" ); // NO, not necessary!
	SteamNetworkingMicroseconds usecNow = SteamNetworkingSockets_GetLocalTimestamp();

	CSteamNetworkConnectionBase *pConn = nullptr;
	HSteamNetConnection hConn = k_HSteamNetConnection_Invalid;
	ConnectionScopeLock connectionLock;
	bool bConnectionThinkImmediately = false;
	bool bCurrentConnectionFailed = false;
	for ( SortMsg_t *pSort = pSortMessages ; pSort < pSortEnd ; ++pSort )
	{

		// Switched to a different connection?
		if ( hConn != pSort->m_hConn )
		{

			// Flush out previous connection, if any
			if ( pConn )
			{
				if ( bConnectionThinkImmediately )
					pConn->CheckConnectionStateOrScheduleWakeUp( usecNow );
				connectionLock.Unlock();
				bConnectionThinkImmediately = false;
			}

			// Locate the connection
			hConn = pSort->m_hConn;
			pConn = GetConnectionByHandleForAPI( hConn, connectionLock, "SendMessages" );
			bCurrentConnectionFailed = false;
		}

		const int idx = pSort->m_idx;
		CSteamNetworkingMessage *pMsg = static_cast<CSteamNetworkingMessage*>( pMessages[idx] );

		// Once a message fails on a connection, subsequent messages to that connection
		// are not attempted.  Result stays 0 (set by the memset above).
		int64 result;
		if ( bCurrentConnectionFailed )
		{
			result = 0;
		}
		else if ( pConn )
		{

			// Attempt to send
			bool bThinkImmediately = false;
			result = pConn->APISendMessageToConnection( pMsg, usecNow, &bThinkImmediately );
			if ( bThinkImmediately )
				bConnectionThinkImmediately = true;
			if ( result > 0 )
			{
				// Successfully queued.  Clear pointer to let caller know, if
				// they requested this mode of operation.
				if ( !bDeleteFailedMessages )
					pMessages[idx] = nullptr;
			}
		}
		else
		{
			// Connection handle not found -- first message reports the error;
			// subsequent messages to the same connection get result=0 (not attempted).
			result = -k_EResultInvalidParam;
		}

		if ( result <= 0 )
		{
			bCurrentConnectionFailed = true;
			if ( bDeleteFailedMessages )
				pMsg->Release();
		}

		if ( pOutMessageNumberOrResult )
			pOutMessageNumberOrResult[idx] = result;
	}

	// Flush out last connection, if any
	if ( bConnectionThinkImmediately )
		pConn->CheckConnectionStateOrScheduleWakeUp( usecNow );
}

EResult CSteamNetworkingSockets::FlushMessagesOnConnection( HSteamNetConnection hConn )
{
	//SteamNetworkingGlobalLock scopeLock( "FlushMessagesOnConnection" ); // NO, not necessary!
	ConnectionScopeLock connectionLock;
	CSteamNetworkConnectionBase *pConn = GetConnectionByHandleForAPI( hConn, connectionLock, "FlushMessagesOnConnection" );
	if ( !pConn )
		return k_EResultInvalidParam;
	return pConn->APIFlushMessageOnConnection();
}

int CSteamNetworkingSockets::ReceiveMessagesOnConnection( HSteamNetConnection hConn, SteamNetworkingMessage_t **ppOutMessages, int nMaxMessages )
{
	//SteamNetworkingGlobalLock scopeLock( "ReceiveMessagesOnConnection" ); // NO, not necessary!
	ConnectionScopeLock connectionLock;
	CSteamNetworkConnectionBase *pConn = GetConnectionByHandleForAPI( hConn, connectionLock, "ReceiveMessagesOnConnection" );
	if ( !pConn )
		return -1;
	return pConn->APIReceiveMessages( ppOutMessages, nMaxMessages );
}

HSteamNetPollGroup CSteamNetworkingSockets::CreatePollGroup()
{
	SteamNetworkingGlobalLock scopeLock( "CreatePollGroup" ); // Take global lock, because we will be creating objects
	PollGroupScopeLock pollGroupScopeLock;
	CSteamNetworkPollGroup *pPollGroup = InternalCreatePollGroup( pollGroupScopeLock );
	return pPollGroup->m_hPollGroupSelf;
}

CSteamNetworkPollGroup *CSteamNetworkingSockets::InternalCreatePollGroup( PollGroupScopeLock &scopeLock )
{
	SteamNetworkingGlobalLock::AssertHeldByCurrentThread();
	TableScopeLock tableScopeLock( g_tables_lock );
	CSteamNetworkPollGroup *pPollGroup = new CSteamNetworkPollGroup( this );
	scopeLock.Lock( pPollGroup->m_lock );
	pPollGroup->AssignHandleAndAddToGlobalTable();
	return pPollGroup;
}

bool CSteamNetworkingSockets::DestroyPollGroup( HSteamNetPollGroup hPollGroup )
{
	SteamNetworkingGlobalLock scopeLock( "DestroyPollGroup" ); // Take global lock, since we'll be destroying objects
	TableScopeLock tableScopeLock( g_tables_lock ); // We'll need to be able to remove the poll group from the tables list
	PollGroupScopeLock pollGroupLock;
	CSteamNetworkPollGroup *pPollGroup = GetPollGroupByHandle( hPollGroup, pollGroupLock, nullptr );
	if ( !pPollGroup )
		return false;
	pollGroupLock.Abandon(); // We're about to destroy the lock itself.  The Destructor will unlock -- we don't want to do it again.
	delete pPollGroup;
	return true;
}

bool CSteamNetworkingSockets::SetConnectionPollGroup( HSteamNetConnection hConn, HSteamNetPollGroup hPollGroup )
{
	SteamNetworkingGlobalLock scopeLock( "SetConnectionPollGroup" ); // Take global lock, since we'll need to take multiple object locks
	ConnectionScopeLock connectionLock;
	CSteamNetworkConnectionBase *pConn = GetConnectionByHandleForAPI( hConn, connectionLock, nullptr );
	if ( !pConn )
		return false;

	// NOTE: We are allowed to take multiple locks here, in any order, because we have the global
	// lock.  Code that does not hold the global lock may only lock one object at a time

	// Special case for removing the poll group
	if ( hPollGroup == k_HSteamNetPollGroup_Invalid )
	{
		pConn->RemoveFromPollGroup();
		return true;
	}


	PollGroupScopeLock pollGroupLock;
	CSteamNetworkPollGroup *pPollGroup = GetPollGroupByHandle( hPollGroup, pollGroupLock, nullptr );
	if ( !pPollGroup )
		return false;

	pConn->SetPollGroup( pPollGroup );

	return true;
}

int CSteamNetworkingSockets::ReceiveMessagesOnPollGroup( HSteamNetPollGroup hPollGroup, SteamNetworkingMessage_t **ppOutMessages, int nMaxMessages )
{
	//SteamNetworkingGlobalLock scopeLock( "ReceiveMessagesOnPollGroup" ); // NO, not necessary!
	PollGroupScopeLock pollGroupLock;
	CSteamNetworkPollGroup *pPollGroup = GetPollGroupByHandle( hPollGroup, pollGroupLock, "ReceiveMessagesOnPollGroup" );
	if ( !pPollGroup )
		return -1;
	g_lockAllRecvMessageQueues.lock();
	int nMessagesReceived = pPollGroup->m_queueRecvMessages.RemoveMessages( ppOutMessages, nMaxMessages );
	g_lockAllRecvMessageQueues.unlock();
	return nMessagesReceived;
}

#ifdef STEAMNETWORKINGSOCKETS_STEAMCLIENT
int CSteamNetworkingSockets::ReceiveMessagesOnListenSocketLegacyPollGroup( HSteamListenSocket hSocket, SteamNetworkingMessage_t **ppOutMessages, int nMaxMessages )
{
	SteamNetworkingGlobalLock scopeLock( "ReceiveMessagesOnListenSocket" );
	CSteamNetworkListenSocketBase *pSock = GetListenSocketByHandle( hSocket );
	if ( !pSock )
		return -1;
	if ( !pSock->m_pLegacyPollGroup )
		return 0;
	g_lockAllRecvMessageQueues.lock();
	int nMessagesReceived = pSock->m_pLegacyPollGroup->m_queueRecvMessages.RemoveMessages( ppOutMessages, nMaxMessages );
	g_lockAllRecvMessageQueues.unlock();
	return nMessagesReceived;
}
#endif

bool CSteamNetworkingSockets::GetConnectionInfo( HSteamNetConnection hConn, SteamNetConnectionInfo_t *pInfo )
{
	//SteamNetworkingGlobalLock scopeLock( "GetConnectionInfo" ); // NO, not necessary!
	ConnectionScopeLock connectionLock;
	CSteamNetworkConnectionBase *pConn = GetConnectionByHandleForAPI( hConn, connectionLock, "GetConnectionInfo" );
	if ( !pConn )
		return false;
	if ( pInfo )
		pConn->ConnectionPopulateInfo( *pInfo );
	return true;
}

EResult CSteamNetworkingSockets::GetConnectionRealTimeStatus(
	HSteamNetConnection hConn,
	SteamNetConnectionRealTimeStatus_t *pStatus,
	int nLanes, SteamNetConnectionRealTimeLaneStatus_t *pLanes
) {
	//SteamNetworkingGlobalLock scopeLock( "GetQuickConnectionStatus" ); // NO, not necessary!
	ConnectionScopeLock connectionLock;
	CSteamNetworkConnectionBase *pConn = GetConnectionByHandleForAPI( hConn, connectionLock, "GetConnectionRealTimeStatus" );
	if ( !pConn )
		return k_EResultNoConnection;
	return pConn->APIGetRealTimeStatus( pStatus, nLanes, pLanes );
}

int CSteamNetworkingSockets::GetDetailedConnectionStatus( HSteamNetConnection hConn, char *pszBuf, int cbBuf )
{
	SteamNetworkingDetailedConnectionStatus stats;

	// Only hold the lock for as long as we need.
	{
		SteamNetworkingGlobalLock scopeLock( "GetDetailedConnectionStatus" ); // In some use cases (SDR), we need to touch some shared data structures.  It's easier to just protect this with the global lock than to try to sort that out
		ConnectionScopeLock connectionLock;
		CSteamNetworkConnectionBase *pConn = GetConnectionByHandleForAPI( hConn, connectionLock, nullptr );
		if ( !pConn )
			return -1;

		pConn->APIGetDetailedConnectionStatus( stats, SteamNetworkingSockets_GetLocalTimestamp() );

	} // Release lock.  We don't need it, and printing can take a while!
	int r = stats.Print( pszBuf, cbBuf );

	/// If just asking for buffer size, pad it a bunch
	/// because connection status can change at any moment.
	if ( r > 0 )
		r += 1024;
	return r;
}

bool CSteamNetworkingSockets::GetListenSocketAddress( HSteamListenSocket hSocket, SteamNetworkingIPAddr *pAddress )
{
	SteamNetworkingGlobalLock scopeLock( "GetListenSocketAddress" );
	CSteamNetworkListenSocketBase *pSock = GetListenSocketByHandle( hSocket );
	if ( !pSock )
		return false;
	return pSock->APIGetAddress( pAddress );
}

bool CSteamNetworkingSockets::CreateSocketPair( HSteamNetConnection *pOutConnection1, HSteamNetConnection *pOutConnection2, bool bUseNetworkLoopback, const SteamNetworkingIdentity *pPeerIdentity1, const SteamNetworkingIdentity *pPeerIdentity2 )
{
	SteamNetworkingGlobalLock scopeLock( "CreateSocketPair" );

	// Assume failure
	*pOutConnection1 = k_HSteamNetConnection_Invalid;
	*pOutConnection2 = k_HSteamNetConnection_Invalid;
	SteamNetworkingIdentity peerIdentity[ 2 ] = {};
	if ( pPeerIdentity1 )
		peerIdentity[0] = *pPeerIdentity1;
	else
		peerIdentity[0].SetLocalHost();
	if ( pPeerIdentity2 )
		peerIdentity[1] = *pPeerIdentity2;
	else
		peerIdentity[1].SetLocalHost();

	// Create network connections?
	if ( bUseNetworkLoopback )
	{
		// Create two connection objects
		CSteamNetworkConnectionlocalhostLoopback *pConn[2];
		if ( !CSteamNetworkConnectionlocalhostLoopback::APICreateSocketPair( this, pConn, peerIdentity ) )
			return false;

		// Return their handles
		*pOutConnection1 = pConn[0]->m_hConnectionSelf;
		*pOutConnection2 = pConn[1]->m_hConnectionSelf;
	}
	else
	{
		// Create two connection objects
		CSteamNetworkConnectionPipe *pConn[2];
		if ( !CSteamNetworkConnectionPipe::APICreateSocketPair( this, pConn, peerIdentity ) )
			return false;

		// Return their handles
		*pOutConnection1 = pConn[0]->m_hConnectionSelf;
		*pOutConnection2 = pConn[1]->m_hConnectionSelf;
	}
	return true;
}

bool CSteamNetworkingSockets::BCertHasIdentity() const
{
	// We should actually have a cert, otherwise this question cannot be answered
	Assert( m_msgSignedCert.has_cert() );
	Assert( m_msgCert.has_key_data() );
	return m_msgCert.has_identity_string() || m_msgCert.has_legacy_identity_binary() || m_msgCert.has_legacy_steam_id();
}

bool CSteamNetworkingSockets::BMatchesIdentity( const SteamNetworkingIdentity &identity )
{
	if ( identity == InternalGetIdentity() )
		return true;

	#ifdef STEAMNETWORKINGSOCKETS_ENABLE_FAKEIP
		if ( identity.IsFakeIP() )
		{
			if ( GetFakePortIndex( identity.m_ip ) >= 0 )
				return true;
		}
	#endif

	return false;
}

bool CSteamNetworkingSockets::SetCertificateAndPrivateKey( const void *pCert, int cbCert, void *pPrivateKey, int cbPrivateKey )
{
	SteamNetworkingGlobalLock::AssertHeldByCurrentThread( "SetCertificateAndPrivateKey" );

	m_msgCert.Clear();
	m_msgSignedCert.Clear();
	m_keyPrivateKey.Wipe();

	//
	// Decode the private key
	//
	if ( !m_keyPrivateKey.LoadFromAndWipeBuffer( pPrivateKey, cbPrivateKey ) )
	{
		SetCertStatus( k_ESteamNetworkingAvailability_Failed, "Invalid private key" );
		return false;
	}

	//
	// Decode the cert
	//
	SteamNetworkingErrMsg parseErrMsg;
	if ( !ParseCertFromPEM( pCert, cbCert, m_msgSignedCert, parseErrMsg ) )
	{
		SetCertStatus( k_ESteamNetworkingAvailability_Failed, parseErrMsg );
		return false;
	}

	if (
		!m_msgSignedCert.has_cert()
		|| !m_msgCert.ParseFromString( m_msgSignedCert.cert() )
		|| !m_msgCert.has_time_expiry()
		|| !m_msgCert.has_key_data()
	) {
		SetCertStatus( k_ESteamNetworkingAvailability_Failed, "Invalid cert" );
		return false;
	}
	if ( m_msgCert.key_type() != CMsgSteamDatagramCertificate_EKeyType_ED25519 )
	{
		SetCertStatus( k_ESteamNetworkingAvailability_Failed, "Invalid cert or unsupported public key type" );
		return false;
	}

	//
	// Make sure that the private key and the cert match!
	//

	CECSigningPublicKey pubKey;
	if ( !pubKey.SetRawDataWithoutWipingInput( m_msgCert.key_data().c_str(), m_msgCert.key_data().length() ) )
	{
		SetCertStatus( k_ESteamNetworkingAvailability_Failed, "Invalid public key" );
		return false;
	}
	if ( !m_keyPrivateKey.MatchesPublicKey( pubKey ) )
	{
		SetCertStatus( k_ESteamNetworkingAvailability_Failed, "Private key doesn't match public key from cert" );
		return false;
	}

	SetCertStatus( k_ESteamNetworkingAvailability_Current, "OK" );

	return true;
}

int CSteamNetworkingSockets::GetP2P_Transport_ICE_Enable( const SteamNetworkingIdentity &identityRemote, int *pOutUserFlags )
{
	// We really shouldn't get here, because this is only a question that makes sense
	// to ask if we have also overridden this function in a derived class, or slammed
	// it before making the connection
	Assert( false );
	if ( pOutUserFlags )
		*pOutUserFlags = 0;
	return k_nSteamNetworkingConfig_P2P_Transport_ICE_Enable_Disable;
}

void CSteamNetworkingSockets::RunCallbacks()
{

	// Swap into a temp, so that we only hold lock for
	// a brief period.
	std_vector<QueuedCallback> listTemp;
	m_mutexPendingCallbacks.lock();
	listTemp.swap( m_vecPendingCallbacks );
	m_mutexPendingCallbacks.unlock();

	// Dispatch the callbacks
	for ( QueuedCallback &x: listTemp )
	{
		// NOTE: this switch statement is probably not necessary, if we are willing to make
		// some (almost certainly reasonable in practice) assumptions about the parameter
		// passing ABI.  All of these function calls basically have the same signature except
		// for the actual type of the argument being pointed to.

		#define DISPATCH_CALLBACK( structType, fnType ) \
			case structType::k_iCallback: \
				COMPILE_TIME_ASSERT( sizeof(structType) <= sizeof(x.data) ); \
				((fnType)x.fnCallback)( (structType*)x.data ); \
				break; \

		switch ( x.nCallback )
		{
			DISPATCH_CALLBACK( SteamNetConnectionStatusChangedCallback_t, FnSteamNetConnectionStatusChanged )
		#ifdef STEAMNETWORKINGSOCKETS_ENABLE_SDR
			DISPATCH_CALLBACK( SteamNetAuthenticationStatus_t, FnSteamNetAuthenticationStatusChanged )
			DISPATCH_CALLBACK( SteamRelayNetworkStatus_t, FnSteamRelayNetworkStatusChanged )
		#endif
		#ifdef STEAMNETWORKINGSOCKETS_ENABLE_STEAMNETWORKINGMESSAGES
			DISPATCH_CALLBACK( SteamNetworkingMessagesSessionRequest_t, FnSteamNetworkingMessagesSessionRequest )
			DISPATCH_CALLBACK( SteamNetworkingMessagesSessionFailed_t, FnSteamNetworkingMessagesSessionFailed )
		#endif
		#ifdef STEAMNETWORKINGSOCKETS_ENABLE_FAKEIP
			DISPATCH_CALLBACK( SteamNetworkingFakeIPResult_t, FnSteamNetworkingFakeIPResult )
		#endif
			default:
				AssertMsg1( false, "Unknown callback type %d!", x.nCallback );
		}

		#undef DISPATCH_CALLBACK
	}
}

void CSteamNetworkingSockets::InternalQueueCallback( int nCallback, int cbCallback, const void *pvCallback, void *fnRegisteredFunctionPtr )
{
	SteamNetworkingGlobalLock::AssertHeldByCurrentThread();

	if ( !fnRegisteredFunctionPtr )
		return;
	if ( cbCallback > sizeof( ((QueuedCallback*)0)->data ) )
	{
		AssertMsg( false, "Callback doesn't fit!" );
		return;
	}
	m_mutexPendingCallbacks.lock();
	AssertMsg( len( m_vecPendingCallbacks ) < 100, "Callbacks backing up and not being checked.  Need to check them more frequently!" );
	QueuedCallback &q = *push_back_get_ptr( m_vecPendingCallbacks );
	q.nCallback = nCallback;
	q.fnCallback = fnRegisteredFunctionPtr;
	memcpy( q.data, pvCallback, cbCallback );
	m_mutexPendingCallbacks.unlock();
}

#ifndef STEAMNETWORKINGSOCKETS_ENABLE_FAKEIP
bool CSteamNetworkingSockets::BeginAsyncRequestFakeIP( int nNumPorts )
{
	AssertMsg( false, "FakeIP allocation requires Steam" );
	return false;
}

void CSteamNetworkingSockets::GetFakeIP( int idxFirstPort, SteamNetworkingFakeIPResult_t *pInfo )
{
// Bleh, I don't want to ship the header to people who don't need it.
// This would be the right thing to do.
//	// Not supported by base class
//	if ( pInfo )
//	{
//		memset( pInfo, 0, sizeof(*pInfo) );
//		GetIdentity( &pInfo->m_identity );
//		pInfo->m_eResult = k_EResultDisabled;
//	}

	AssertMsg( false, "FakeIP allocation requires Steam" );
}

ISteamNetworkingFakeUDPPort *CSteamNetworkingSockets::CreateFakeUDPPort( int idxFakeServerPort )
{
	AssertMsg( false, "FakeIP system requires Steam" );
	return nullptr;
}
#endif

EResult CSteamNetworkingSockets::GetRemoteFakeIPForConnection( HSteamNetConnection hConn, SteamNetworkingIPAddr *pOutAddr )
{
	ConnectionScopeLock connectionLock;
	CSteamNetworkConnectionBase *pConn = GetConnectionByHandleForAPI( hConn, connectionLock, "GetRemoteFakeIPForConnection" );
	if ( !pConn )
		return k_EResultInvalidParam;

	#ifdef STEAMNETWORKINGSOCKETS_ENABLE_FAKEIP
		if ( pConn->m_identityRemote.IsFakeIP() )
		{
			if ( pOutAddr )
				*pOutAddr = pConn->m_identityRemote.m_ip;
			return k_EResultOK;
		}

		if ( pConn->m_fakeIPRefRemote.GetInfo( nullptr, pOutAddr ) )
			return k_EResultOK;
	#endif

	return k_EResultIPNotFound;
}

/////////////////////////////////////////////////////////////////////////////
//
// CSteamNetworkingUtils
//
/////////////////////////////////////////////////////////////////////////////

CSteamNetworkingUtils::CSteamNetworkingUtils()
{
	SteamNetworkingGlobalLock::AssertHeldByCurrentThread( "CSteamNetworkingUtils::CSteamNetworkingUtils" );
	EnsureConfigValueTableInitted();
}

CSteamNetworkingUtils::~CSteamNetworkingUtils() {}

SteamNetworkingMessage_t *CSteamNetworkingUtils::AllocateMessage( int cbAllocateBuffer )
{
	return CSteamNetworkingMessage::New( cbAllocateBuffer );
}

SteamNetworkingMicroseconds CSteamNetworkingUtils::GetLocalTimestamp()
{
	return SteamNetworkingSockets_GetLocalTimestamp();
}

void CSteamNetworkingUtils::SetDebugOutputFunction( ESteamNetworkingSocketsDebugOutputType eDetailLevel, FSteamNetworkingSocketsDebugOutput pfnFunc )
{
	SteamNetworkingSockets_SetDebugOutputFunction( eDetailLevel, pfnFunc );
}


template<typename T>
static ConfigValue<T> *GetConnectionVar( const GlobalConfigValueEntry *pEntry, ConnectionConfig *pConnectionConfig )
{
	Assert( pEntry->m_eScope == k_ESteamNetworkingConfig_Connection );
	intptr_t ptr = intptr_t( pConnectionConfig );
	return (ConfigValue<T> *)( ptr + pEntry->m_cbOffsetOf );
}

template<typename T>
static ConfigValue<T> *EvaluateScopeConfigValue( GlobalConfigValueEntry *pEntry,
	ESteamNetworkingConfigScope eScopeType,
	intptr_t scopeObj,
	ConnectionScopeLock &connectionLock // Lock this, if it's a connection
)
{
	switch ( eScopeType )
	{
		case k_ESteamNetworkingConfig_Global:
		{
			auto *pGlobalVal = static_cast< GlobalConfigValueBase<T> * >( pEntry );
			return &pGlobalVal->m_value;
		}

		case k_ESteamNetworkingConfig_SocketsInterface:
		{
			CSteamNetworkingSockets *pInterface = (CSteamNetworkingSockets *)scopeObj;
			if ( pEntry->m_eScope == k_ESteamNetworkingConfig_Connection )
			{
				return GetConnectionVar<T>( pEntry, &pInterface->m_connectionConfig );
			}
			break;
		}

		case k_ESteamNetworkingConfig_ListenSocket:
		{
			CSteamNetworkListenSocketBase *pSock = GetListenSocketByHandle( HSteamListenSocket( scopeObj ) );
			if ( pSock )
			{
				if ( pEntry->m_eScope == k_ESteamNetworkingConfig_Connection )
				{
					return GetConnectionVar<T>( pEntry, &pSock->m_connectionConfig );
				}
			}
			break;
		}

		case k_ESteamNetworkingConfig_Connection:
		{
			// NOTE: Not using GetConnectionByHandleForAPI here.  In a few places in the code,
			// we need to be able to set config options for connections that are being created.
			// Really, we ought to plumb through these calls to an internal interface, so that
			// we would know that they should be given access.  Right now they are coming in
			// the "front door".  So this means if the app tries to set a config option on a
			// connection that technically no longer exists, we will actually allow that, when
			// we probably should fail the call.
			CSteamNetworkConnectionBase *pConn = GetConnectionByHandle( HSteamNetConnection( scopeObj ), connectionLock );
			if ( pConn )
			{
				if ( pEntry->m_eScope == k_ESteamNetworkingConfig_Connection )
				{
					return GetConnectionVar<T>( pEntry, &pConn->m_connectionConfig );
				}
			}
			break;
		}

	}

	// Bad scope argument
	return nullptr;
}

static bool AssignConfigValueTyped( int32 *pVal, ESteamNetworkingConfigDataType eDataType, const void *pArg )
{
	switch ( eDataType )
	{
		case k_ESteamNetworkingConfig_Int32:
			*pVal = *(int32*)pArg;
			break;

		case k_ESteamNetworkingConfig_Int64:
		{
			int64 arg = *(int64*)pArg;
			if ( (int32)arg != arg )
				return false; // Cannot truncate!
			*pVal = (int32)arg;
			break;
		}

		case k_ESteamNetworkingConfig_Float:
			*pVal = (int32)floor( *(float*)pArg + .5f );
			break;

		case k_ESteamNetworkingConfig_String:
		{
			int x;
			if ( sscanf( (const char *)pArg, "%d", &x ) != 1 )
				return false;
			*pVal = x;
			break;
		}

		default:
			return false;
	}

	return true;
}

static bool AssignConfigValueTyped( int64 *pVal, ESteamNetworkingConfigDataType eDataType, const void *pArg )
{
	switch ( eDataType )
	{
		case k_ESteamNetworkingConfig_Int32:
			*pVal = *(int32*)pArg;
			break;

		case k_ESteamNetworkingConfig_Int64:
		{
			*pVal = *(int64*)pArg;
			break;
		}

		case k_ESteamNetworkingConfig_Float:
			*pVal = (int64)floor( *(float*)pArg + .5f );
			break;

		case k_ESteamNetworkingConfig_String:
		{
			long long x;
			if ( sscanf( (const char *)pArg, "%lld", &x ) != 1 )
				return false;
			*pVal = (int64)x;
			break;
		}

		default:
			return false;
	}

	return true;
}

static bool AssignConfigValueTyped( float *pVal, ESteamNetworkingConfigDataType eDataType, const void *pArg )
{
	switch ( eDataType )
	{
		case k_ESteamNetworkingConfig_Int32:
			*pVal = (float)( *(int32*)pArg );
			break;

		case k_ESteamNetworkingConfig_Int64:
		{
			*pVal = (float)( *(int64*)pArg );
			break;
		}

		case k_ESteamNetworkingConfig_Float:
			*pVal = *(float*)pArg;
			break;

		case k_ESteamNetworkingConfig_String:
		{
			float x;
			if ( sscanf( (const char *)pArg, "%f", &x ) != 1 )
				return false;
			*pVal = x;
			break;
		}

		default:
			return false;
	}

	return true;
}

static bool AssignConfigValueTyped( std::string *pVal, ESteamNetworkingConfigDataType eDataType, const void *pArg )
{
	char temp[64];

	switch ( eDataType )
	{
		case k_ESteamNetworkingConfig_Int32:
			V_sprintf_safe( temp, "%d", *(int32*)pArg );
			*pVal = temp;
			break;

		case k_ESteamNetworkingConfig_Int64:
			V_sprintf_safe( temp, "%lld", (long long)*(int64*)pArg );
			*pVal = temp;
			break;

		case k_ESteamNetworkingConfig_Float:
			V_sprintf_safe( temp, "%g", *(float*)pArg );
			*pVal = temp;
			break;

		case k_ESteamNetworkingConfig_String:
			*pVal = (const char *)pArg;
			break;

		default:
			return false;
	}

	return true;
}

static bool AssignConfigValueTyped( void **pVal, ESteamNetworkingConfigDataType eDataType, const void *pArg )
{
	switch ( eDataType )
	{
		case k_ESteamNetworkingConfig_Ptr:
			*pVal = *(void **)pArg;
			break;

		default:
			return false;
	}

	return true;
}

template<typename T>
bool SetConfigValueTyped(
	GlobalConfigValueEntry *pEntry,
	ESteamNetworkingConfigScope eScopeType,
	intptr_t scopeObj,
	ESteamNetworkingConfigDataType eDataType,
	const void *pArg
) {
	ConnectionScopeLock connectionLock;
	ConfigValue<T> *pVal = EvaluateScopeConfigValue<T>( pEntry, eScopeType, scopeObj, connectionLock );
	if ( !pVal )
		return false;

	// Locked values cannot be changed
	if ( pVal->IsLocked() )
		return false;

	// Clearing the value?
	if ( pArg == nullptr )
	{
		if ( eScopeType == k_ESteamNetworkingConfig_Global )
		{
			auto *pGlobal = (typename GlobalConfigValueBase<T>::Value *)( pVal );
			Assert( pGlobal->m_pInherit == nullptr );
			Assert( pGlobal->IsSet() );
			pGlobal->m_data = pGlobal->m_defaultValue;
		}
		else if ( eScopeType == k_ESteamNetworkingConfig_Connection && pEntry->m_eValue == k_ESteamNetworkingConfig_ConnectionUserData )
		{
			// Once this is set, we cannot clear it or inherit it.
			SpewError( "Cannot clear connection user data\n" );
			return false;
		}
		else
		{
			Assert( pVal->m_pInherit );
			pVal->m_eState = ConfigValueBase::kENotSet;
		}
		return true;
	}

	// Call type-specific method to set it
	if ( !AssignConfigValueTyped( &pVal->m_data, eDataType, pArg ) )
		return false;

	// Mark it as set
	pVal->m_eState = ConfigValueBase::kESet;

	// Apply limits
	pEntry->Clamp<T>( pVal->m_data );

	// OK
	return true;
}

template<typename T>
ESteamNetworkingGetConfigValueResult ReturnConfigValueTyped( const T &data, void *pData, size_t *cbData )
{
	ESteamNetworkingGetConfigValueResult eResult;
	if ( !pData || *cbData < sizeof(T) )
	{
		eResult = k_ESteamNetworkingGetConfigValue_BufferTooSmall;
	}
	else
	{
		*(T*)pData = data;
		eResult = k_ESteamNetworkingGetConfigValue_OK;
	}
	*cbData = sizeof(T);
	return eResult;
}

template<>
ESteamNetworkingGetConfigValueResult ReturnConfigValueTyped<std::string>( const std::string &data, void *pData, size_t *cbData )
{
	size_t l = data.length() + 1;
	ESteamNetworkingGetConfigValueResult eResult;
	if ( !pData || *cbData < l )
	{
		eResult = k_ESteamNetworkingGetConfigValue_BufferTooSmall;
	}
	else
	{
		memcpy( pData, data.c_str(), l );
		eResult = k_ESteamNetworkingGetConfigValue_OK;
	}
	*cbData = l;
	return eResult;
}

template<typename T>
ESteamNetworkingGetConfigValueResult GetConfigValueTyped(
	GlobalConfigValueEntry *pEntry,
	ESteamNetworkingConfigScope eScopeType,
	intptr_t scopeObj,
	void *pResult, size_t *cbResult
) {
	ConnectionScopeLock connectionLock;
	ConfigValue<T> *pVal = EvaluateScopeConfigValue<T>( pEntry, eScopeType, scopeObj, connectionLock );
	if ( !pVal )
	{
		*cbResult = 0;
		return k_ESteamNetworkingGetConfigValue_BadScopeObj;
	}

	// Remember if it was set at this level
	bool bValWasSet = pVal->IsSet();

	// Find the place where the actual value comes from
	while ( !pVal->IsSet() )
	{
		Assert( pVal->m_pInherit );
		pVal = static_cast<ConfigValue<T> *>( pVal->m_pInherit );
	}

	// Call type-specific method to return it
	ESteamNetworkingGetConfigValueResult eResult = ReturnConfigValueTyped( pVal->m_data, pResult, cbResult );
	if ( eResult == k_ESteamNetworkingGetConfigValue_OK && !bValWasSet )
		eResult = k_ESteamNetworkingGetConfigValue_OKInherited;
	return eResult;
}

bool CSteamNetworkingUtils::SetConfigValue( ESteamNetworkingConfigValue eValue,
	ESteamNetworkingConfigScope eScopeType, intptr_t scopeObj,
	ESteamNetworkingConfigDataType eDataType, const void *pValue )
{

	// Check for special values
	switch ( eValue )
	{
		case k_ESteamNetworkingConfig_MTU_DataSize:
			SpewWarning( "MTU_DataSize is readonly" );
			return false;

		case k_ESteamNetworkingConfig_ConnectionUserData:
		{

			// We only need special handling when modifying a connection
			if ( eScopeType != k_ESteamNetworkingConfig_Connection )
				break;

			// Process the user argument, maybe performing type conversion
			int64 newData;
			if ( !AssignConfigValueTyped( &newData, eDataType, pValue ) )
				return false;

			// Lookup the connection
			ConnectionScopeLock connectionLock;
			CSteamNetworkConnectionBase *pConn = GetConnectionByHandle( HSteamNetConnection( scopeObj ), connectionLock );
			if ( !pConn )
				return false;

			// Set the data, possibly fixing up existing queued messages, etc
			pConn->SetUserData( newData );
			return true;
		}

	}

	GlobalConfigValueEntry *pEntry = FindConfigValueEntry( eValue );
	if ( pEntry == nullptr )
		return false;

	SteamNetworkingGlobalLock scopeLock( "SetConfigValue" );

	switch ( pEntry->m_eDataType )
	{
		case k_ESteamNetworkingConfig_Int32: return SetConfigValueTyped<int32>( pEntry, eScopeType, scopeObj, eDataType, pValue );
		case k_ESteamNetworkingConfig_Int64: return SetConfigValueTyped<int64>( pEntry, eScopeType, scopeObj, eDataType, pValue );
		case k_ESteamNetworkingConfig_Float: return SetConfigValueTyped<float>( pEntry, eScopeType, scopeObj, eDataType, pValue );
		case k_ESteamNetworkingConfig_String: return SetConfigValueTyped<std::string>( pEntry, eScopeType, scopeObj, eDataType, pValue );
		case k_ESteamNetworkingConfig_Ptr: return SetConfigValueTyped<void *>( pEntry, eScopeType, scopeObj, eDataType, pValue );
	}

	Assert( false );
	return false;
}

ESteamNetworkingGetConfigValueResult CSteamNetworkingUtils::GetConfigValue(
	ESteamNetworkingConfigValue eValue, ESteamNetworkingConfigScope eScopeType,
	intptr_t scopeObj, ESteamNetworkingConfigDataType *pOutDataType,
	void *pResult, size_t *cbResult )
{
	// Take the global lock.
	SteamNetworkingGlobalLock scopeLock( "GetConfigValue" );

	if ( eValue == k_ESteamNetworkingConfig_MTU_DataSize )
	{
		int32 MTU_packetsize;
		size_t cbMTU_packetsize = sizeof(MTU_packetsize);
		ESteamNetworkingGetConfigValueResult rFetch = GetConfigValueTyped<int32>( &GlobalConfig::MTU_PacketSize, eScopeType, scopeObj, &MTU_packetsize, &cbMTU_packetsize );
		if ( rFetch < 0 )
			return rFetch;

		int32 MTU_DataSize = std::max( 0, MTU_packetsize - k_cbSteamNetworkingSocketsNoFragmentHeaderReserve );
		ESteamNetworkingGetConfigValueResult rStore = ReturnConfigValueTyped<int32>( MTU_DataSize, pResult, cbResult );
		if ( rStore != k_ESteamNetworkingGetConfigValue_OK )
			return rStore;
		return rFetch;
	}

	GlobalConfigValueEntry *pEntry = FindConfigValueEntry( eValue );
	if ( pEntry == nullptr )
		return k_ESteamNetworkingGetConfigValue_BadValue;

	if ( pOutDataType )
		*pOutDataType = pEntry->m_eDataType;

	switch ( pEntry->m_eDataType )
	{
		case k_ESteamNetworkingConfig_Int32: return GetConfigValueTyped<int32>( pEntry, eScopeType, scopeObj, pResult, cbResult );
		case k_ESteamNetworkingConfig_Int64: return GetConfigValueTyped<int64>( pEntry, eScopeType, scopeObj, pResult, cbResult );
		case k_ESteamNetworkingConfig_Float: return GetConfigValueTyped<float>( pEntry, eScopeType, scopeObj, pResult, cbResult );
		case k_ESteamNetworkingConfig_String: return GetConfigValueTyped<std::string>( pEntry, eScopeType, scopeObj, pResult, cbResult );
		case k_ESteamNetworkingConfig_Ptr: return GetConfigValueTyped<void *>( pEntry, eScopeType, scopeObj, pResult, cbResult );
	}

	Assert( false ); // FIXME
	return k_ESteamNetworkingGetConfigValue_BadValue;
}

static bool BEnumerateConfigValue( const GlobalConfigValueEntry *pVal, bool bEnumerateDevVars )
{
	if ( pVal->m_eDataType == k_ESteamNetworkingConfig_Ptr )
		return false;

	switch  ( pVal->m_eValue )
	{
		// Never enumerate these
		case k_ESteamNetworkingConfig_SymmetricConnect:
		case k_ESteamNetworkingConfig_LocalVirtualPort:
		case k_ESteamNetworkingConfig_ConnectionUserData:
		//case k_ESteamNetworkingConfig_EnumerateDevVars:
			return false;

		// Dev var?
		case k_ESteamNetworkingConfig_IP_AllowWithoutAuth:
		case k_ESteamNetworkingConfig_Unencrypted:
		case k_ESteamNetworkingConfig_SDRClient_FakeClusterPing:
			return bEnumerateDevVars;
	}

	return true;
}

const char *CSteamNetworkingUtils::GetConfigValueInfo( ESteamNetworkingConfigValue eValue, ESteamNetworkingConfigDataType *pOutDataType, ESteamNetworkingConfigScope *pOutScope )
{
	const GlobalConfigValueEntry *pVal = FindConfigValueEntry( eValue );
	if ( pVal == nullptr )
		return nullptr;

	if ( pOutDataType )
		*pOutDataType = pVal->m_eDataType;
	if ( pOutScope )
		*pOutScope = pVal->m_eScope;

	return pVal->m_pszName;
}

ESteamNetworkingConfigValue CSteamNetworkingUtils::IterateGenericEditableConfigValues( ESteamNetworkingConfigValue eCurrent, bool bEnumerateDevVars )
{
	const GlobalConfigValueEntry *p;
	if ( eCurrent == k_ESteamNetworkingConfig_Invalid )
	{
		p = s_vecConfigValueTable[0];
	}
	else
	{
		p = FindConfigValueEntry( eCurrent );
		if ( p )
			p = p->m_pNextEntry;
	}

	while ( p )
	{
		if ( BEnumerateConfigValue( p, bEnumerateDevVars ) )
			return p->m_eValue;
		p = p->m_pNextEntry;
	}
	return k_ESteamNetworkingConfig_Invalid;
}


void CSteamNetworkingUtils::SteamNetworkingIPAddr_ToString( const SteamNetworkingIPAddr &addr, char *buf, size_t cbBuf, bool bWithPort )
{
	::SteamNetworkingIPAddr_ToString( &addr, buf, cbBuf, bWithPort );
}

bool CSteamNetworkingUtils::SteamNetworkingIPAddr_ParseString( SteamNetworkingIPAddr *pAddr, const char *pszStr )
{
	return ::SteamNetworkingIPAddr_ParseString( pAddr, pszStr );
}

void CSteamNetworkingUtils::SteamNetworkingIdentity_ToString( const SteamNetworkingIdentity &identity, char *buf, size_t cbBuf )
{
	return ::SteamNetworkingIdentity_ToString( &identity, buf, cbBuf );
}

bool CSteamNetworkingUtils::SteamNetworkingIdentity_ParseString( SteamNetworkingIdentity *pIdentity, const char *pszStr )
{
	return ::SteamNetworkingIdentity_ParseString( pIdentity, sizeof(SteamNetworkingIdentity), pszStr );
}

ESteamNetworkingFakeIPType CSteamNetworkingUtils::GetIPv4FakeIPType( uint32 nIPv4 )
{
	return SteamNetworkingSocketsLib::GetIPv4FakeIPType( nIPv4 );
}

EResult CSteamNetworkingUtils::GetRealIdentityForFakeIP( const SteamNetworkingIPAddr &fakeIP, SteamNetworkingIdentity *pOutRealIdentity )
{
	// Not supported without Steam
	return k_EResultDisabled;
}

ESteamNetworkingFakeIPType CSteamNetworkingUtils::SteamNetworkingIPAddr_GetFakeIPType( const SteamNetworkingIPAddr &addr )
{
	#ifdef STEAMNETWORKINGSOCKETS_ENABLE_FAKEIP
		return ::SteamNetworkingIPAddr_GetFakeIPType( &addr );
	#else
		return k_ESteamNetworkingFakeIPType_NotFake;
	#endif
}

AppId_t CSteamNetworkingUtils::GetAppID()
{
	return m_nAppID;
}

void CSteamNetworkingUtils::TEST_ResetSelf()
{
	m_nAppID = 0;
}

time_t CSteamNetworkingUtils::GetTimeSecure()
{
	// Trusting local user's clock!
	return time(nullptr);
}

const char *CSteamNetworkingUtils::GetBuildString()
{
	#if defined( STEAMNETWORKINGSOCKETS_OPENSOURCE )
		return "opensource " __DATE__ " " __TIME__;
	#elif defined( STEAMNETWORKINGSOCKETS_STANDALONELIB )
		return "lib " __DATE__ " " __TIME__;
	#elif defined( STEAMNETWORKINGSOCKETS_STEAMCLIENT )
		return "steam "
		#ifdef BRANCH_MAIN
			"(main) "
		#elif !defined( BRANCH_REL_CLIENT )
			"(branch?) "
		#endif
		__DATE__ " " __TIME__;
	#elif defined( STEAMNETWORKINGSOCKETS_STREAMINGCLIENT )
		return "stream "
		#ifdef BRANCH_MAIN
			"(main) "
		#elif !defined( BRANCH_REL_CLIENT )
			"(branch?) "
		#endif
		__DATE__ " " __TIME__;
	#else
		#error "Huh?"
	#endif
}

const char *CSteamNetworkingUtils::GetPlatformString()
{
	#if IsNintendoSwitch()
		return "nswitch";
	#elif IsXboxScarlett()
		return "scarlett";
	#elif defined( _STADIA )
		// Not sure if this works.
		return "stadia";
	#elif IsXboxOne()
		return "xbone";
	#elif IsPS4()
		return "ps4";
	#elif IsPS5()
		return "ps5";
	#elif IsTVOS()
		return "tvos";
	#elif IsIOS()
		return "ios";
	#elif IsOSX()
		return "osx";
	#elif IsAndroid()
		return "android";
	#elif defined( _WINDOWS )
		return "windows";
	#elif IsLinux()
		return "linux";
	#elif IsFreeBSD()
		return "freebsd";
	#elif IsOpenBSD()
		return "openbsd";
	#else
		#error "Unknown platform"
	#endif
}

} // namespace SteamNetworkingSocketsLib
using namespace SteamNetworkingSocketsLib;

/////////////////////////////////////////////////////////////////////////////
//
// Global API interface
//
/////////////////////////////////////////////////////////////////////////////

#ifdef STEAMNETWORKINGSOCKETS_OPENSOURCE

static CSteamNetworkingSockets *s_pSteamNetworkingSockets = nullptr;

STEAMNETWORKINGSOCKETS_INTERFACE bool GameNetworkingSockets_Init( const SteamNetworkingIdentity *pIdentity, SteamNetworkingErrMsg &errMsg )
{
	SteamNetworkingGlobalLock lock( "GameNetworkingSockets_Init" );

	// Already initted?
	if ( s_pSteamNetworkingSockets )
	{
		AssertMsg( false, "GameNetworkingSockets_init called multiple times?" );
		return true;
	}

	// Init basic functionality
	CSteamNetworkingSockets *pSteamNetworkingSockets = new CSteamNetworkingSockets( ( CSteamNetworkingUtils *)SteamNetworkingUtils() );
	if ( !pSteamNetworkingSockets->BInitGameNetworkingSockets( pIdentity, errMsg ) )
	{
		pSteamNetworkingSockets->Destroy();
		return false;
	}

	s_pSteamNetworkingSockets = pSteamNetworkingSockets;
	return true;
}

STEAMNETWORKINGSOCKETS_INTERFACE void GameNetworkingSockets_Kill()
{
	SteamNetworkingGlobalLock lock( "GameNetworkingSockets_Kill" );
	if ( s_pSteamNetworkingSockets )
	{
		s_pSteamNetworkingSockets->Destroy();
		s_pSteamNetworkingSockets = nullptr;
	}
}

STEAMNETWORKINGSOCKETS_INTERFACE ISteamNetworkingSockets *SteamNetworkingSockets_LibV12()
{
	return s_pSteamNetworkingSockets;
}

STEAMNETWORKINGSOCKETS_INTERFACE ISteamNetworkingUtils *SteamNetworkingUtils_LibV4()
{
	static CSteamNetworkingUtils s_utils;
	return &s_utils;
}

#ifdef STEAMNETWORKINGSOCKETS_ENABLE_STEAMNETWORKINGMESSAGES

STEAMNETWORKINGSOCKETS_INTERFACE ISteamNetworkingMessages* SteamNetworkingMessages_LibV2()
{
	if ( !s_pSteamNetworkingSockets )
		return nullptr;

	return s_pSteamNetworkingSockets->GetSteamNetworkingMessages();
}

#endif//STEAMNETWORKINGSOCKETS_ENABLE_STEAMNETWORKINGMESSAGES

#endif