File: GameServer.cpp

package info (click to toggle)
spring 88.0%2Bdfsg1-1.1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 41,524 kB
  • sloc: cpp: 343,114; ansic: 38,414; python: 12,257; java: 12,203; awk: 5,748; sh: 1,204; xml: 997; perl: 405; objc: 192; makefile: 181; php: 134; sed: 2
file content (2491 lines) | stat: -rwxr-xr-x 82,857 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */

#include "System/Net/UDPListener.h"

#include "System/Net/UDPConnection.h"

#include <stdarg.h>
#include <ctime>
#include <boost/bind.hpp>
#include <boost/format.hpp>
#include <boost/version.hpp>
#include <boost/ptr_container/ptr_deque.hpp>
#include <boost/ptr_container/ptr_map.hpp>
#include <boost/shared_ptr.hpp>
#include <deque>
#if defined DEDICATED || defined DEBUG
	#include <iostream>
#endif
#include <stdlib.h> // why is this here?

#include "System/Net/Connection.h"
#include "System/mmgr.h"

#include "GameServer.h"

#include "GameSetup.h"
#include "Action.h"
#include "ChatMessage.h"
#include "CommandMessage.h"
#include "System/BaseNetProtocol.h"
#include "PlayerHandler.h"
#ifdef DEDICATED
	#include "System/LoadSave/DemoRecorder.h"
#endif
#include "System/AutohostInterface.h"
#include "System/Util.h"
#include "System/TdfParser.h"
#include "GlobalUnsynced.h" // for syncdebug
#include "Sim/Misc/GlobalConstants.h"

#include "Player.h"
#include "IVideoCapturing.h"
#include "Server/GameParticipant.h"
#include "Server/GameSkirmishAI.h"
// This undef is needed, as somewhere there is a type interface specified,
// which we need not!
// (would cause problems in ExternalAI/Interface/SAIInterfaceLibrary.h)
#ifdef interface
	#undef interface
#endif
#include "Server/MsgStrings.h"
#include "System/Config/ConfigHandler.h"
#include "System/GlobalConfig.h"
#include "System/Log/ILog.h"
#include "System/CRC.h"
#include "System/FileSystem/SimpleParser.h"
#include "System/Net/LocalConnection.h"
#include "System/Net/UnpackPacket.h"
#include "System/LoadSave/DemoReader.h"
#include "System/Platform/errorhandler.h"
#include "System/Platform/Threading.h"


#define PKTCACHE_VECSIZE 1000

using netcode::RawPacket;

CONFIG(int, SpeedControl).defaultValue(0);
CONFIG(bool, AllowAdditionalPlayers).defaultValue(false);
CONFIG(bool, WhiteListAdditionalPlayers).defaultValue(true);
CONFIG(std::string, AutohostIP).defaultValue("127.0.0.1");
CONFIG(int, AutohostPort).defaultValue(0);

/// frames until a syncchech will time out and a warning is given out
const unsigned SYNCCHECK_TIMEOUT = 300;

/// used to prevent msg spam
const unsigned SYNCCHECK_MSG_TIMEOUT = 400;

/// The time intervall in msec for sending player statistics to each client
const spring_duration playerInfoTime = spring_secs(2);

/// every n'th frame will be a keyframe (and contain the server's framenumber)
const unsigned serverKeyframeIntervall = 16;

/// players incoming bandwidth new allowance every X milliseconds
const unsigned playerBandwidthInterval = 100;

/// every 10 sec we'll broadcast current frame in a message that skips queue & cache
/// to let clients that are fast-forwarding to current point to know their loading %
const unsigned gameProgressFrameInterval = GAME_SPEED * 10;

const std::string commands[numCommands] = {
	"kick", "kickbynum", "setminspeed", "setmaxspeed",
	"nopause", "nohelp", "cheat", "godmode", "globallos",
	"nocost", "forcestart", "nospectatorchat", "nospecdraw",
	"skip", "reloadcob", "reloadcegs", "devlua", "editdefs",
	"singlestep"
};
using boost::format;

namespace {
void SetBoolArg(bool& value, const std::string& str)
{
	if (str.empty()) { // toggle
		value = !value;
	}
	else { // set
		const int num = atoi(str.c_str());
		value = (num != 0);
	}
}
}


CGameServer* gameServer = 0;

CGameServer::CGameServer(const std::string& hostIP, int hostPort, const GameData* const newGameData, const CGameSetup* const mysetup)
: setup(mysetup)
{
	assert(setup);
	serverStartTime = spring_gettime();
	lastUpdate = serverStartTime;
	lastPlayerInfo = serverStartTime;
	syncErrorFrame = 0;
	syncWarningFrame = 0;
	serverFrameNum = 0;
	timeLeft = 0;
	modGameTime = 0.0f;
	gameTime = 0.0f;
	startTime = 0.0f;
	quitServer=false;
	hasLocalClient = false;
	localClientNumber = 0;
	isPaused = false;
	userSpeedFactor = 1.0f;
	internalSpeed = 1.0f;
	gamePausable = true;
	noHelperAIs = false;
	canReconnect = false;
	allowSpecDraw = true;
	cheating = false;

	gameHasStarted = false;
	generatedGameID = false;

	gameEndTime = spring_notime;
	readyTime = spring_notime;

	medianCpu = 0.0f;
	medianPing = 0;
	curSpeedCtrl = 0;
	speedControl = configHandler->GetInt("SpeedControl");
	UpdateSpeedControl(--speedControl + 1);

	allowAdditionalPlayers = configHandler->GetBool("AllowAdditionalPlayers");
	whiteListAdditionalPlayers = configHandler->GetBool("WhiteListAdditionalPlayers");

	if (!setup->onlyLocal) {
		UDPNet.reset(new netcode::UDPListener(hostPort, hostIP));
	}

	std::string autohostip = configHandler->GetString("AutohostIP");
	if (StringToLower(autohostip) == "localhost") {
		// FIXME temporary hack: we do not support (host-)names.
		// "localhost" was the only name supported in the past.
		// added 7. January 2011, to be removed in ~ 1 year
		autohostip = "127.0.0.1";
	}
	const int autohostport = configHandler->GetInt("AutohostPort");

	if (autohostport > 0) {
		AddAutohostInterface(autohostip, autohostport);
	}

	rng.Seed(newGameData->GetSetup().length());
	Message(str(format(ServerStart) %hostPort), false);

	lastTick = spring_gettime();

	maxUserSpeed = setup->maxSpeed;
	minUserSpeed = setup->minSpeed;
	noHelperAIs = setup->noHelperAIs;

	{ // modify and save GameSetup text (remove passwords)
		TdfParser parser(newGameData->GetSetup().c_str(), newGameData->GetSetup().length());
		TdfParser::TdfSection* root = parser.GetRootSection();
		for (TdfParser::sectionsMap_t::iterator it = root->sections.begin(); it != root->sections.end(); ++it) {
			if (it->first.substr(0, 6) == "PLAYER")
				it->second->remove("Password");
		}
		std::ostringstream strbuf;
		parser.print(strbuf);
		std::string cleanedSetupText = strbuf.str();
		GameData* newData = new GameData(*newGameData);
		newData->SetSetup(cleanedSetupText);
		gameData.reset(newData);
	}

	if (setup->hostDemo) {
		Message(str(format(PlayingDemo) %setup->demoName));
		demoReader.reset(new CDemoReader(setup->demoName, modGameTime + 0.1f));
	}

	players.reserve(MAX_PLAYERS); // no reallocation please
	for (int i = 0; i < setup->playerStartingData.size(); ++i)
		players.push_back(GameParticipant());
	std::copy(setup->playerStartingData.begin(), setup->playerStartingData.end(), players.begin());
	UpdatePlayerNumberMap();

	const std::vector<SkirmishAIData> &said = setup->GetSkirmishAIs();
	for (size_t a = 0; a < said.size(); ++a) {
		const unsigned char skirmishAIId = ReserveNextAvailableSkirmishAIId();
		if (skirmishAIId == MAX_AIS) {
			Message(str(format("Too many AIs (%d) in game setup") %said.size()));
			break;
		}
		players[said[a].hostPlayer].linkData[skirmishAIId] = GameParticipant::PlayerLinkData();
		ais[skirmishAIId] = said[a];
	}

	teams.resize(setup->teamStartingData.size());
	std::copy(setup->teamStartingData.begin(), setup->teamStartingData.end(), teams.begin());

	commandBlacklist = std::set<std::string>(commands, commands+numCommands);

#ifdef DEDICATED
	demoRecorder.reset(new CDemoRecorder(setup->mapName, setup->modName));
	demoRecorder->WriteSetupText(gameData->GetSetup());
	const netcode::RawPacket* ret = gameData->Pack();
	demoRecorder->SaveToDemo(ret->data, ret->length, GetDemoTime());
	delete ret;
#endif
	// AIs do not join in here, so just set their teams as active
	for (std::map<unsigned char, GameSkirmishAI>::const_iterator ai = ais.begin(); ai != ais.end(); ++ai) {
		const int t = ai->second.team;
		teams[t].active = true;
		if (teams[t].leader < 0) { // CAUTION, default value is 0, not -1
			teams[t].leader = ai->second.hostPlayer;
		}
	}

	canReconnect = false;
	linkMinPacketSize = globalConfig->linkIncomingMaxPacketRate > 0 ? (globalConfig->linkIncomingSustainedBandwidth / globalConfig->linkIncomingMaxPacketRate) : 1;
	lastBandwidthUpdate = spring_gettime();

	thread = new boost::thread(boost::bind<void, CGameServer, CGameServer*>(&CGameServer::UpdateLoop, this));

#ifdef STREFLOP_H
	// Something in CGameServer::CGameServer borks the FPU control word
	// maybe the threading, or something in CNet::InitServer() ??
	// Set single precision floating point math.
	streflop_init<streflop::Simple>();
#endif
}

CGameServer::~CGameServer()
{
	quitServer=true;
	thread->join();
	delete thread;
#ifdef DEDICATED
	// TODO: move this to a method in CTeamHandler
	int numTeams = (int)setup->teamStartingData.size();
	if (setup->useLuaGaia && (numTeams > 0)) {
		--numTeams;
	}
	demoRecorder->SetTime(serverFrameNum / GAME_SPEED, spring_tomsecs(spring_gettime() - serverStartTime) / 1000);
	demoRecorder->InitializeStats(players.size(), numTeams);

	// Pass the winners to the CDemoRecorder.
	demoRecorder->SetWinningAllyTeams(winningAllyTeams);
	for (size_t i = 0; i < players.size(); ++i) {
		demoRecorder->SetPlayerStats(i, players[i].lastStats);
	}
	/*for (size_t i = 0; i < ais.size(); ++i) {
		demoRecorder->SetSkirmishAIStats(i, ais[i].lastStats);
	}*/
	/*for (int i = 0; i < numTeams; ++i) {
		record->SetTeamStats(i, teamHandler->Team(i)->statHistory);
	}*/ //TODO add
#endif // DEDICATED
}

void CGameServer::AddLocalClient(const std::string& myName, const std::string& myVersion)
{
	Threading::RecursiveScopedLock scoped_lock(gameServerMutex);
	assert(!hasLocalClient);
	hasLocalClient = true;
	localClientNumber = BindConnection(myName, "", myVersion, true, boost::shared_ptr<netcode::CConnection>(new netcode::CLocalConnection()));
}

void CGameServer::AddAutohostInterface(const std::string& autohostIP, const int autohostPort)
{
	if (!hostif) {
		hostif.reset(new AutohostInterface(autohostIP, autohostPort));
		if (hostif->IsInitialized()) {
			hostif->SendStart();
			Message(str(format(ConnectAutohost) %autohostPort), false);
		} else {
			// Quit if we are instructed to communicate with an auto-host,
			// but are unable to do so. As we do not want an auto-host running
			// a spring game that he has no control over. If we get here,
			// it suggests a configuration problem in the auto-host.
			hostif.reset();
			Message(str(format(ConnectAutohostFailed) %autohostIP %autohostPort), false);
			quitServer = true;
		}
	}
}

void CGameServer::PostLoad(unsigned newlastTick, int newServerFrameNum)
{
	Threading::RecursiveScopedLock scoped_lock(gameServerMutex);
	lastTick = spring_msecs(newlastTick);
	serverFrameNum = newServerFrameNum;

	std::vector<GameParticipant>::iterator it;
	for (it = players.begin(); it != players.end(); ++it) {
		it->lastFrameResponse = newServerFrameNum;
	}
}

void CGameServer::SkipTo(int targetFrameNum)
{
	const bool wasPaused = isPaused;

	if (!gameHasStarted) { return; }
	if (serverFrameNum >= targetFrameNum) { return; }
	if (demoReader == NULL) { return; }

	CommandMessage startMsg(str(format("skip start %d") %targetFrameNum), SERVER_PLAYER);
	CommandMessage endMsg("skip end", SERVER_PLAYER);
	Broadcast(boost::shared_ptr<const netcode::RawPacket>(startMsg.Pack()));

	// fast-read and send demo data
	//
	// note that we must maintain <modGameTime> ourselves
	// since we do we NOT go through ::Update when skipping
	while (SendDemoData(targetFrameNum)) {
		gameTime = GetDemoTime();
		modGameTime = demoReader->GetModGameTime() + 0.001f;

		if (UDPNet == NULL) { continue; }
		if ((serverFrameNum % 20) != 0) { continue; }

		// send data every few frames, as otherwise packets would grow too big
		UDPNet->Update();
	}

	Broadcast(boost::shared_ptr<const netcode::RawPacket>(endMsg.Pack()));

	if (UDPNet) {
		UDPNet->Update();
	}

	lastUpdate = spring_gettime();
	isPaused = wasPaused;
}

std::string CGameServer::GetPlayerNames(const std::vector<int>& indices) const
{
	std::string playerstring;
	std::vector<int>::const_iterator p = indices.begin();
	for (; p != indices.end(); ++p) {
		if (!playerstring.empty())
			playerstring += ", ";
		playerstring += players[*p].name;
	}
	return playerstring;
}


void CGameServer::UpdatePlayerNumberMap() {
	unsigned char player = 0;
	for (int i = 0; i < 256; ++i, ++player) {
		if (i < players.size() && !players[i].isFromDemo)
			++player;
		playerNumberMap[i] = (i < MAX_PLAYERS) ? player : i; // ignore SERVER_PLAYER, ChatMessage::TO_XXX etc
	}
}


bool CGameServer::AdjustPlayerNumber(netcode::RawPacket* buf, int pos, int val) {
	if (buf->length <= pos) {
		Message(str(format("Warning: Discarding short packet in demo: ID %d, LEN %d") %buf->data[0] %buf->length));
		return false;
	}
	// spectators watching the demo will offset the demo spectators, compensate for this
	if (val < 0) {
		unsigned char player = playerNumberMap[buf->data[pos]];
		if (player >= players.size() && player < MAX_PLAYERS) { // ignore SERVER_PLAYER, ChatMessage::TO_XXX etc
			Message(str(format("Warning: Discarding packet with invalid player number in demo: ID %d, LEN %d") %buf->data[0] %buf->length));
			return false;
		}
		buf->data[pos] = player;
	}
	else {
		buf->data[pos] = val;
	}
	return true;
}


bool CGameServer::SendDemoData(int targetFrameNum)
{
	bool ret = false;
	netcode::RawPacket* buf = NULL;

	// if we reached EOS before, demoReader has become NULL
	if (demoReader == NULL)
		return ret;

	// get all packets from the stream up to <modGameTime>
	while ((buf = demoReader->GetData(modGameTime))) {
		boost::shared_ptr<const RawPacket> rpkt(buf);

		if (buf->length <= 0) {
			Message(str(format("Warning: Discarding zero size packet in demo")));
			continue;
		}

		const unsigned msgCode = buf->data[0];

		switch (msgCode) {
			case NETMSG_NEWFRAME:
			case NETMSG_KEYFRAME: {
				// we can't use CreateNewFrame() here
				lastTick = spring_gettime();
				serverFrameNum++;
#ifdef SYNCCHECK
				if (targetFrameNum == -1) {
					// not skipping
					outstandingSyncFrames.insert(serverFrameNum);
				}
				CheckSync();
#endif
				Broadcast(rpkt);
				break;
			}

			case NETMSG_AI_STATE_CHANGED: /* many of these messages are not likely to be sent by a spec, but there are cheats */
			case NETMSG_ALLIANCE:
			case NETMSG_CUSTOM_DATA:
			case NETMSG_DC_UPDATE:
			case NETMSG_DIRECT_CONTROL:
			case NETMSG_PATH_CHECKSUM:
			case NETMSG_PAUSE: /* this is a synced message and must not be excluded */
			case NETMSG_PLAYERINFO:
			case NETMSG_PLAYERLEFT:
			case NETMSG_PLAYERSTAT:
			case NETMSG_SETSHARE:
			case NETMSG_SHARE:
			case NETMSG_STARTPOS:
			case NETMSG_TEAM: {
				// TODO: more messages may need adjusted player numbers, or maybe there is a better solution
				if (!AdjustPlayerNumber(buf, 1))
					continue;
				Broadcast(rpkt);
				break;
			}

			case NETMSG_AI_CREATED:
			case NETMSG_MAPDRAW:
			case NETMSG_PLAYERNAME: {
				if (!AdjustPlayerNumber(buf, 2))
					continue;
				Broadcast(rpkt);
				break;
			}

			case NETMSG_CHAT: {
				if (!AdjustPlayerNumber(buf, 2) || !AdjustPlayerNumber(buf, 3))
					continue;
				Broadcast(rpkt);
				break;
			}

			case NETMSG_AICOMMAND:
			case NETMSG_AISHARE:
			case NETMSG_COMMAND:
			case NETMSG_LUAMSG:
			case NETMSG_SELECT:
			case NETMSG_SYSTEMMSG: {
				if (!AdjustPlayerNumber(buf ,3))
					continue;
				Broadcast(rpkt);
				break;
			}

			case NETMSG_CREATE_NEWPLAYER: {
				if (!AdjustPlayerNumber(buf, 3, players.size()))
					continue;
				try {
					netcode::UnpackPacket pckt(rpkt, 3);
					unsigned char spectator, team, playerNum;
					std::string name;
					pckt >> playerNum;
					pckt >> spectator;
					pckt >> team;
					pckt >> name;
					AddAdditionalUser(name, "", true,(bool)spectator,(int)team); // even though this is a demo, keep the players vector properly updated
				} catch (const netcode::UnpackPacketException& ex) {
					Message(str(format("Warning: Discarding invalid new player packet in demo: %s") %ex.what()));
					continue;
				}

				Broadcast(rpkt);
				break;
			}

			case NETMSG_GAMEDATA:
			case NETMSG_SETPLAYERNUM:
			case NETMSG_USER_SPEED:
			case NETMSG_INTERNAL_SPEED: {
				// never send these from demos
				break;
			}
			case NETMSG_CCOMMAND: {
				if (!AdjustPlayerNumber(buf ,3))
					continue;
				try {
					CommandMessage msg(rpkt);
					const Action& action = msg.GetAction();
					if (msg.GetPlayerID() == SERVER_PLAYER && action.command == "cheat")
						SetBoolArg(cheating, action.extra);
				} catch (const netcode::UnpackPacketException& ex) {
					Message(str(format("Warning: Discarding invalid command message packet in demo: %s") %ex.what()));
					continue;
				}
				Broadcast(rpkt);
				break;
			}
			default: {
				Broadcast(rpkt);
				break;
			}
		}
	}

	if (targetFrameNum > 0) {
		// skipping
		ret = (serverFrameNum < targetFrameNum);
	}

	if (demoReader->ReachedEnd()) {
		demoReader.reset();
		Message(DemoEnd);
		gameEndTime = spring_gettime();
		ret = false;
	}

	return ret;
}

void CGameServer::Broadcast(boost::shared_ptr<const netcode::RawPacket> packet)
{
	for (size_t p = 0; p < players.size(); ++p)
		players[p].SendData(packet);
	if (canReconnect || allowAdditionalPlayers || !gameHasStarted)
		AddToPacketCache(packet);
#ifdef DEDICATED
	if (demoRecorder)
		demoRecorder->SaveToDemo(packet->data, packet->length, GetDemoTime());
#endif
}

void CGameServer::Message(const std::string& message, bool broadcast)
{
	if (broadcast) {
		Broadcast(CBaseNetProtocol::Get().SendSystemMessage(SERVER_PLAYER, message));
	}
	else if (hasLocalClient) {
		// host should see
		players[localClientNumber].SendData(CBaseNetProtocol::Get().SendSystemMessage(SERVER_PLAYER, message));
	}
	if (hostif)
		hostif->Message(message);
#if defined DEDICATED
	std::cout << message << std::endl;
#endif
}

void CGameServer::PrivateMessage(int playerNum, const std::string& message) {
	players[playerNum].SendData(CBaseNetProtocol::Get().SendSystemMessage(SERVER_PLAYER, message));
}

void CGameServer::CheckSync()
{
#ifdef SYNCCHECK
	// Check sync
	std::set<int>::iterator f = outstandingSyncFrames.begin();
	while (f != outstandingSyncFrames.end()) {
		unsigned correctChecksum = 0;
		bool bGotCorrectChecksum = false;
		if (hasLocalClient) {
			// dictatorship
			std::map<int, unsigned>::iterator it = players[localClientNumber].syncResponse.find(*f);
			if (it != players[localClientNumber].syncResponse.end()) {
				correctChecksum = it->second;
				bGotCorrectChecksum = true;
			}
		}
		else {
			// democracy
			typedef std::vector< std::pair<unsigned, unsigned> > chkList;
			chkList checksums;
			unsigned checkMaxCount = 0;
			for (size_t a = 0; a < players.size(); ++a) {
				if (!players[a].link)
					continue;

				std::map<int, unsigned>::const_iterator it = players[a].syncResponse.find(*f);
				if (it != players[a].syncResponse.end()) {
					bool found = false;
					for (chkList::iterator it2 = checksums.begin(); it2 != checksums.end(); ++it2) {
						if (it2->first == it->second) {
							found = true;
							it2->second++;
							if (checkMaxCount < it2->second) {
								checkMaxCount = it2->second;
								correctChecksum = it2->first;
							}
						}
					}
					if (!found) {
						checksums.push_back(std::pair<unsigned, unsigned>(it->second, 1));
						if (checkMaxCount == 0) {
							checkMaxCount = 1;
							correctChecksum = it->second;
						}
					}
				}
			}
			bGotCorrectChecksum = (checkMaxCount > 0);
		}

		std::vector<int> noSyncResponse;
		// maps incorrect checksum to players with that checksum
		std::map<unsigned, std::vector<int> > desyncGroups;
		std::map<int, unsigned> desyncSpecs;
		bool bComplete = true;
		for (size_t a = 0; a < players.size(); ++a) {
			if (!players[a].link) {
				continue;
			}
			std::map<int, unsigned>::iterator it = players[a].syncResponse.find(*f);
			if (it == players[a].syncResponse.end()) {
				if (*f >= serverFrameNum - static_cast<int>(SYNCCHECK_TIMEOUT))
					bComplete = false;
				else if (*f < players[a].lastFrameResponse)
					noSyncResponse.push_back(a);
			} else {
				if (bGotCorrectChecksum && it->second != correctChecksum) {
					players[a].desynced = true;
					if (demoReader || !players[a].spectator)
						desyncGroups[it->second].push_back(a);
					else
						desyncSpecs[a] = it->second;
				}
				else
					players[a].desynced = false;
			}
		}

		if (!noSyncResponse.empty()) {
			if (!syncWarningFrame || (*f - syncWarningFrame > static_cast<int>(SYNCCHECK_MSG_TIMEOUT))) {
				syncWarningFrame = *f;

				std::string playernames = GetPlayerNames(noSyncResponse);
				Message(str(format(NoSyncResponse) %playernames %(*f)));
			}
		}

		// If anything's in it, we have a desync.
		// TODO take care of !bComplete case?
		// Should we start resync then immediately or wait for the missing packets (while paused)?
		if (/*bComplete && */ (!desyncGroups.empty() || !desyncSpecs.empty())) {
			if (!syncErrorFrame || (*f - syncErrorFrame > static_cast<int>(SYNCCHECK_MSG_TIMEOUT))) {
				syncErrorFrame = *f;

				// TODO enable this when we have resync
				//serverNet->SendPause(SERVER_PLAYER, true);
#ifdef SYNCDEBUG
				CSyncDebugger::GetInstance()->ServerTriggerSyncErrorHandling(serverFrameNum);
				if (demoReader) // pause is a synced message, thus demo spectators may not pause for real
					Message(str(format("%s paused the demo") %players[gu->myPlayerNum].name));
				else
					Broadcast(CBaseNetProtocol::Get().SendPause(gu->myPlayerNum, true));
				isPaused = true;
				Broadcast(CBaseNetProtocol::Get().SendSdCheckrequest(serverFrameNum));
#endif
				// For each group, output a message with list of player names in it.
				// TODO this should be linked to the resync system so it can roundrobin
				// the resync checksum request packets to multiple clients in the same group.
				std::map<unsigned, std::vector<int> >::const_iterator g = desyncGroups.begin();
				for (; g != desyncGroups.end(); ++g) {
					std::string playernames = GetPlayerNames(g->second);
					Message(str(format(SyncError) %playernames %(*f) %(g->first ^ correctChecksum)));
				}

				// send spectator desyncs as private messages to reduce spam
				for (std::map<int, unsigned>::const_iterator s = desyncSpecs.begin(); s != desyncSpecs.end(); ++s) {
					int playerNum = s->first;
					PrivateMessage(playerNum, str(format(SyncError) %players[playerNum].name %(*f) %(s->second ^ correctChecksum)));
				}
			}
		}

		// Remove complete sets (for which all player's checksums have been received).
		if (bComplete) {
			// Message(str (format("Succesfully purged outstanding sync frame %d from the deque") %(*f)));
			for (size_t a = 0; a < players.size(); ++a) {
				if (players[a].myState < GameParticipant::DISCONNECTED)
					players[a].syncResponse.erase(*f);
			}
			f = set_erase(outstandingSyncFrames, f);
		} else
			++f;
	}
#else
	// Make it clear this build isn't suitable for release.
	if (!syncErrorFrame || (serverFrameNum - syncErrorFrame > SYNCCHECK_MSG_TIMEOUT)) {
		syncErrorFrame = serverFrameNum;
		Message(NoSyncCheck);
	}
#endif
}

float CGameServer::GetDemoTime() const {
	if (!gameHasStarted) return gameTime;
	return (startTime + serverFrameNum / float(GAME_SPEED));
}

void CGameServer::Update()
{
	const float tdif = spring_tomsecs(spring_gettime() - lastUpdate) * 0.001f;

	gameTime += tdif;
	lastUpdate = spring_gettime();

	if (!isPaused && gameHasStarted) {
		// if we are not playing a demo, or have no local client, or the
		// local client is less than <GAME_SPEED> frames behind, advance
		// <modGameTime>
		if (!demoReader || !hasLocalClient || (serverFrameNum - players[localClientNumber].lastFrameResponse) < GAME_SPEED)
			modGameTime += (tdif * internalSpeed);
	}

	if (lastPlayerInfo < (spring_gettime() - playerInfoTime)) {
		lastPlayerInfo = spring_gettime();

		if (serverFrameNum > 0) {
			//send info about the players
			std::vector<float> cpu;
			std::vector<int> ping;
			float refCpu = 0.0f;
			for (size_t a = 0; a < players.size(); ++a) {
				if (players[a].myState == GameParticipant::INGAME) {
					int curPing = (serverFrameNum - players[a].lastFrameResponse);
					if (players[a].isReconn && curPing < 2 * GAME_SPEED)
						players[a].isReconn = false;
					Broadcast(CBaseNetProtocol::Get().SendPlayerInfo(a, players[a].cpuUsage, curPing));
					float correctedCpu = players[a].isLocal ? players[a].cpuUsage :
						std::max(0.0f, std::min(players[a].cpuUsage - 0.0025f * (float)players[a].luaLockTime, 1.0f));
					if (demoReader ? !players[a].isFromDemo : !players[a].spectator) {
						if (!players[a].isReconn && correctedCpu > refCpu)
							refCpu = correctedCpu;
						cpu.push_back(correctedCpu);
						ping.push_back(curPing);
					}
				}
			}

			medianCpu = 0.0f;
			medianPing = 0;
			if (curSpeedCtrl > 0 && !cpu.empty()) {
				std::sort(cpu.begin(), cpu.end());
				std::sort(ping.begin(), ping.end());

				int midpos = cpu.size() / 2;
				medianCpu = cpu[midpos];
				medianPing = ping[midpos];
				if (midpos * 2 == cpu.size()) {
					medianCpu = (medianCpu + cpu[midpos - 1]) / 2.0f;
					medianPing = (medianPing + ping[midpos - 1]) / 2;
				}
				refCpu = medianCpu;
			}

			if (refCpu > 0.0f) {
				// aim for 60% cpu usage if median is used as reference and 75% cpu usage if max is the reference
				float wantedCpu = (curSpeedCtrl > 0) ? 0.6f + (1 - internalSpeed / userSpeedFactor) * 0.5f : 0.75f + (1 - internalSpeed / userSpeedFactor) * 0.5f;
				float newSpeed = internalSpeed * wantedCpu / refCpu;
//				float speedMod=1+wantedCpu-refCpu;
//				LOG_L(L_DEBUG, "Speed REF %f MED %f WANT %f SPEEDM %f NSPEED %f",refCpu,medianCpu,wantedCpu,speedMod,newSpeed);
				newSpeed = (newSpeed + internalSpeed) * 0.5f;
				newSpeed = std::max(newSpeed, (curSpeedCtrl > 0) ? userSpeedFactor * 0.8f : userSpeedFactor * 0.5f);
				if (newSpeed > userSpeedFactor)
					newSpeed = userSpeedFactor;
				if (newSpeed < 0.1f)
					newSpeed = 0.1f;
				if (newSpeed != internalSpeed)
					InternalSpeedChange(newSpeed);
			}
		}
		else {
			for (size_t a = 0; a < players.size(); ++a) {
				if (!players[a].isFromDemo) {
					if (players[a].myState == GameParticipant::CONNECTED) { // send pathing status
						if (players[a].cpuUsage > 0)
							Broadcast(CBaseNetProtocol::Get().SendPlayerInfo(a, players[a].cpuUsage, PATHING_FLAG));
					}
					else {
						Broadcast(CBaseNetProtocol::Get().SendPlayerInfo(a, 0, 0)); // reset status
					}
				}
			}
		}
	}

	if (!gameHasStarted)
		CheckForGameStart();
	else if (serverFrameNum > 0 || demoReader)
		CreateNewFrame(true, false);

	if (hostif) {
		std::string msg = hostif->GetChatMessage();

		if (!msg.empty()) {
			if (msg.at(0) != '/') { // normal chat message
				GotChatMessage(ChatMessage(SERVER_PLAYER, ChatMessage::TO_EVERYONE, msg));
			}
			else if (msg.at(0) == '/' && msg.size() > 1 && msg.at(1) == '/') { // chatmessage with prefixed '/'
				GotChatMessage(ChatMessage(SERVER_PLAYER, ChatMessage::TO_EVERYONE, msg.substr(1)));
			}
			else if (msg.size() > 1) { // command
				Action buf(msg.substr(1));
				PushAction(buf);
			}
		}
	}

	const bool pregameTimeoutReached = (spring_gettime() > serverStartTime + spring_secs(globalConfig->initialNetworkTimeout));
	if (pregameTimeoutReached || gameHasStarted) {
		bool hasPlayers = false;
		for (size_t i = 0; i < players.size(); ++i) {
			if (players[i].link) {
				hasPlayers = true;
				break;
			}
		}

		if (!hasPlayers) {
			Message(NoClientsExit);
			quitServer = true;
		}
	}
}


/// has to be consistent with Game.cpp/CPlayerHandler
static std::vector<int> getPlayersInTeam(const std::vector<GameParticipant>& players, const int teamId) {
	std::vector<int> playersInTeam;

	for (size_t p = 0; p < players.size(); ++p) {
		// do not count spectators, or demos will desync
		if (!players[p].spectator && (players[p].team == teamId))
			playersInTeam.push_back(p);
	}

	return playersInTeam;
}

/**
 * Duplicates functionality of CPlayerHandler::ActivePlayersInTeam(int teamId)
 * as playerHandler is not available on the server
 */
static int countNumPlayersInTeam(const std::vector<GameParticipant>& players, const int teamId) {
	return getPlayersInTeam(players, teamId).size();
}

/// has to be consistent with Game.cpp/CSkirmishAIHandler
static std::vector<unsigned char> getSkirmishAIIds(const std::map<unsigned char, GameSkirmishAI>& ais, const int teamId, const int hostPlayer = -2) {

	std::vector<unsigned char> skirmishAIIds;

	for (std::map<unsigned char, GameSkirmishAI>::const_iterator ai = ais.begin(); ai != ais.end(); ++ai) {
		if ((ai->second.team == teamId) && ((hostPlayer == -2) || (ai->second.hostPlayer == hostPlayer)))
			skirmishAIIds.push_back(ai->first);
	}

	return skirmishAIIds;
}

/**
 * Duplicates functionality of CSkirmishAIHandler::GetSkirmishAIsInTeam(const int teamId)
 * as skirmishAIHandler is not available on the server
 */
static int countNumSkirmishAIsInTeam(const std::map<unsigned char, GameSkirmishAI>& ais, const int teamId) {
	return getSkirmishAIIds(ais, teamId).size();
}



void CGameServer::ProcessPacket(const unsigned playerNum, boost::shared_ptr<const netcode::RawPacket> packet)
{
	const boost::uint8_t* inbuf = packet->data;
	const unsigned a = playerNum;
	unsigned msgCode = (unsigned) inbuf[0];

	switch (msgCode) {
		case NETMSG_KEYFRAME: {
			const int frameNum = *(int*)&inbuf[1];
			if (frameNum <= serverFrameNum && frameNum > players[a].lastFrameResponse)
				players[a].lastFrameResponse = frameNum;
			break;
		}

		case NETMSG_PAUSE:
			if (inbuf[1] != a) {
				Message(str(format(WrongPlayer) %msgCode %a %(unsigned)inbuf[1]));
				break;
			}
			if (!inbuf[2])  // reset sync checker
				syncErrorFrame = 0;
			if (gamePausable || players[a].isLocal) { // allow host to pause even if nopause is set
				if (!players[a].isLocal && players[a].spectator && !demoReader) {
					PrivateMessage(a, "Spectators cannot pause the game");
				}
				else if (curSpeedCtrl > 0 && !isPaused && !players[a].isLocal &&
					(players[a].spectator || (curSpeedCtrl > 0 &&
					(players[a].cpuUsage - medianCpu > std::min(0.2f, std::max(0.0f, 0.8f - medianCpu)) ||
					(serverFrameNum - players[a].lastFrameResponse) - medianPing > internalSpeed * GAME_SPEED / 2)))) {
						PrivateMessage(a, "Pausing rejected (cpu load or ping is too high)");
				}
				else {
					timeLeft=0;
					if ((isPaused != !!inbuf[2]) || demoReader)
						isPaused = !isPaused;
					if (demoReader) // pause is a synced message, thus demo spectators may not pause for real
						Message(str(format("%s %s the demo") %players[a].name %(isPaused ? "paused" : "unpaused")));
					else
						Broadcast(CBaseNetProtocol::Get().SendPause(a, inbuf[2]));
				}
			}
			break;

		case NETMSG_USER_SPEED: {
			if (!players[a].isLocal && players[a].spectator && !demoReader) {
				PrivateMessage(a, "Spectators cannot change game speed");
			}
			else {
				float speed = *((float*) &inbuf[2]);
				UserSpeedChange(speed, a);
			}
		} break;

		case NETMSG_CPU_USAGE:
			players[a].cpuUsage = *((float*)&inbuf[1]);
			break;

		case NETMSG_CUSTOM_DATA: {
			unsigned playerNum = inbuf[1];
			if (playerNum != a) {
				Message(str(format(WrongPlayer) %msgCode %a %playerNum));
				break;
			}
			const enum CustomData dataType = (enum CustomData)inbuf[2];
			switch (dataType) {
				case CUSTOM_DATA_SPEEDCONTROL:
					players[a].speedControl = *((int*)&inbuf[3]);
					UpdateSpeedControl(speedControl);
					break;
				case CUSTOM_DATA_LUADRAWTIME:
					players[a].luaLockTime = *((int*)&inbuf[3]);
					break;
				default:
					Message(str(format("Player %s sent invalid CustomData type %d") %players[a].name %dataType));
			}
			break;
		}

		case NETMSG_QUIT: {
			Message(str(format(PlayerLeft) %players[a].GetType() %players[a].name %" normal quit"));
			Broadcast(CBaseNetProtocol::Get().SendPlayerLeft(a, 1));
			players[a].Kill("User exited");
			UpdateSpeedControl(speedControl);
			if (hostif)
				hostif->SendPlayerLeft(a, 1);
			break;
		}

		case NETMSG_PLAYERNAME: {
			try {
				netcode::UnpackPacket pckt(packet, 2);
				unsigned char playerNum;
				pckt >> playerNum;
				if (playerNum != a) {
					Message(str(format(WrongPlayer) %msgCode %a %playerNum));
					break;
				}
				pckt >> players[playerNum].name;
				players[playerNum].myState = GameParticipant::INGAME;
				Broadcast(CBaseNetProtocol::Get().SendPlayerInfo(a, 0, 0)); // reset pathing display
				Message(str(format(PlayerJoined) %players[playerNum].GetType() %players[playerNum].name), false);
				Broadcast(CBaseNetProtocol::Get().SendPlayerName(playerNum, players[playerNum].name));
				if (hostif)
					hostif->SendPlayerJoined(playerNum, players[playerNum].name);
			} catch (const netcode::UnpackPacketException& ex) {
				Message(str(format("Player %d sent invalid PlayerName: %s") %a %ex.what()));
			}
			break;
		}

		case NETMSG_PATH_CHECKSUM: {
			const unsigned char playerNum = inbuf[1];
			const boost::uint32_t playerCheckSum = *(boost::uint32_t*) &inbuf[2];
			if (playerNum != a) {
				Message(str(format(WrongPlayer) %msgCode %a %playerNum));
				break;
			}
			Broadcast(CBaseNetProtocol::Get().SendPathCheckSum(playerNum, playerCheckSum));
		} break;

		case NETMSG_CHAT: {
			try {
				ChatMessage msg(packet);
				if (static_cast<unsigned>(msg.fromPlayer) != a) {
					Message(str(format(WrongPlayer) %msgCode %a %(unsigned)msg.fromPlayer));
					break;
				}
				GotChatMessage(msg);
			} catch (const netcode::UnpackPacketException& ex) {
				Message(str(format("Player %s sent invalid ChatMessage: %s") %players[a].name %ex.what()));
			}
			break;
		}
		case NETMSG_SYSTEMMSG:
			try {
				netcode::UnpackPacket pckt(packet, 3);
				unsigned char playerNum;
				pckt >> playerNum;
				std::string strmsg;
				pckt >> strmsg;
				if (playerNum != a) {
					Message(str(format(WrongPlayer) %msgCode %a %(unsigned)playerNum));
					break;
				}
				Broadcast(CBaseNetProtocol::Get().SendSystemMessage(playerNum, strmsg));
			} catch (const netcode::UnpackPacketException& ex) {
				Message(str(format("Player %d sent invalid SystemMessage: %s") %a %ex.what()));
			}
			break;

		case NETMSG_STARTPOS: {
			const unsigned player = inbuf[1];
			if (player != a) {
				Message(str(format(WrongPlayer) %msgCode %a %(unsigned)inbuf[1]));
				break;
			}
			if (setup->startPosType == CGameSetup::StartPos_ChooseInGame) {
				const unsigned team     = (unsigned)inbuf[2];
				if (team >= teams.size()) {
					Message(str(format("Invalid teamID %d in NETMSG_STARTPOS from player %d") %team %player));
				} else if (getSkirmishAIIds(ais, team, player).empty() && ((team != players[player].team) || (players[player].spectator))) {
					Message(str(format("Player %d sent spoofed NETMSG_STARTPOS with teamID %d") %player %team));
				} else {
					teams[team].startPos = float3(*((float*)&inbuf[4]), *((float*)&inbuf[8]), *((float*)&inbuf[12]));
					if (inbuf[3] == 1) {
						players[player].readyToStart = static_cast<bool>(inbuf[3]);
					}

					Broadcast(CBaseNetProtocol::Get().SendStartPos(inbuf[1],team, inbuf[3], *((float*)&inbuf[4]), *((float*)&inbuf[8]), *((float*)&inbuf[12]))); //forward data
					if (hostif)
						hostif->SendPlayerReady(a, inbuf[3]);
				}
			}
			else {
				Message(str(format(NoStartposChange) %a));
			}
			break;
		}

		case NETMSG_COMMAND:
			try {
				netcode::UnpackPacket pckt(packet, 3);
				unsigned char playerNum;
				pckt >> playerNum;
				if (playerNum != a) {
					Message(str(format(WrongPlayer) %msgCode %a %(unsigned)playerNum));
					break;
				}
				if (!demoReader)
					Broadcast(packet); //forward data
			} catch (const netcode::UnpackPacketException& ex) {
				Message(str(format("Player %s sent invalid Command: %s") %players[a].name %ex.what()));
			}
			break;

		case NETMSG_SELECT:
			try {
				netcode::UnpackPacket pckt(packet, 3);
				unsigned char playerNum;
				pckt >> playerNum;
				if (playerNum != a) {
					Message(str(format(WrongPlayer) %msgCode %a %(unsigned)playerNum));
					break;
				}
				if (!demoReader)
					Broadcast(packet); //forward data
			} catch (const netcode::UnpackPacketException& ex) {
				Message(str(format("Player %s sent invalid Select: %s") %players[a].name %ex.what()));
			}
			break;

		case NETMSG_AICOMMAND: {
			try {
				netcode::UnpackPacket pckt(packet, 3);
				unsigned char playerNum;
				pckt >> playerNum;
				if (playerNum != a) {
					Message(str(format(WrongPlayer) %msgCode  %a  %(unsigned) playerNum));
					break;
				}
				if (noHelperAIs)
					Message(str(format(NoHelperAI) %players[a].name %a));
				else if (!demoReader)
					Broadcast(packet); //forward data
			} catch (const netcode::UnpackPacketException& ex) {
				Message(str(format("Player %s sent invalid AICommand: %s") %players[a].name %ex.what()));
			}
		}
		break;

		case NETMSG_AICOMMANDS: {
			try {
				netcode::UnpackPacket pckt(packet, 3);
				unsigned char playerNum;
				pckt >> playerNum;
				if (playerNum != a) {
					Message(str(format(WrongPlayer) %msgCode  %a  %(unsigned) playerNum));
					break;
				}
				if (noHelperAIs)
					Message(str(format(NoHelperAI) %players[a].name %a));
				else if (!demoReader)
					Broadcast(packet); //forward data
			} catch (const netcode::UnpackPacketException& ex) {
				Message(str(format("Player %s sent invalid AICommands: %s") %players[a].name %ex.what()));
			}
		} break;

		case NETMSG_AISHARE: {
			try {
				netcode::UnpackPacket pckt(packet, 3);
				unsigned char playerNum;
				pckt >> playerNum;
				if (playerNum != a) {
					Message(str(format(WrongPlayer) %msgCode  %a  %(unsigned) playerNum));
					break;
				}
				if (noHelperAIs)
					Message(str(format(NoHelperAI) %players[a].name %a));
				else if (!demoReader)
					Broadcast(packet); //forward data
			} catch (const netcode::UnpackPacketException& ex) {
				Message(str(format("Player %s sent invalid AIShare: %s") %players[a].name %ex.what()));
			}
		} break;


		case NETMSG_LUAMSG: {
			try {
				netcode::UnpackPacket pckt(packet, 3);
				unsigned char playerNum;
				pckt >> playerNum;
				if (playerNum != a) {
					Message(str(format(WrongPlayer) %msgCode %a %(unsigned)playerNum));
					break;
				}
				if (!demoReader) {
					Broadcast(packet); //forward data
					if (hostif)
						hostif->SendLuaMsg(packet->data, packet->length);
				}
			} catch (const netcode::UnpackPacketException& ex) {
				Message(str(format("Player %s sent invalid LuaMsg: %s") %players[a].name %ex.what()));
			}
		} break;


		case NETMSG_SYNCRESPONSE: {
#ifdef SYNCCHECK
			netcode::UnpackPacket pckt(packet, 1);

			unsigned char playerNum; pckt >> playerNum;
			          int  frameNum; pckt >> frameNum;
			unsigned  int  checkSum; pckt >> checkSum;

			assert(a == playerNum);

			if (outstandingSyncFrames.find(frameNum) != outstandingSyncFrames.end())
				players[a].syncResponse[frameNum] = checkSum;

			// update player's ping (if !defined(SYNCCHECK) this is done in NETMSG_KEYFRAME)
			if (frameNum <= serverFrameNum && frameNum > players[a].lastFrameResponse)
				players[a].lastFrameResponse = frameNum;

#ifndef NDEBUG
			// send player <a>'s sync-response back to everybody
			// (the only purpose of this is to allow a client to
			// detect if it is desynced wrt. a demo-stream)
			if ((frameNum % GAME_SPEED) == 0) {
				Broadcast((CBaseNetProtocol::Get()).SendSyncResponse(playerNum, frameNum, checkSum));
			}
#endif
#endif
		} break;

		case NETMSG_SHARE:
			if (inbuf[1] != a) {
				Message(str(format(WrongPlayer) %msgCode %a %(unsigned)inbuf[1]));
				break;
			}
			if (!demoReader)
				Broadcast(CBaseNetProtocol::Get().SendShare(inbuf[1], inbuf[2], inbuf[3], *((float*)&inbuf[4]), *((float*)&inbuf[8])));
			break;

		case NETMSG_SETSHARE:
			if (inbuf[1] != a) {
				Message(str(format(WrongPlayer) %msgCode %a %(unsigned)inbuf[1]));
				break;
			}
			if (!demoReader)
				Broadcast(CBaseNetProtocol::Get().SendSetShare(inbuf[1], inbuf[2], *((float*)&inbuf[3]), *((float*)&inbuf[7])));
			break;

		case NETMSG_PLAYERSTAT:
			if (inbuf[1] != a) {
				Message(str(format(WrongPlayer) %msgCode %a %(unsigned)inbuf[1]));
				break;
			}
			players[a].lastStats = *(PlayerStatistics*)&inbuf[2];
			Broadcast(packet); //forward data
			break;

		case NETMSG_MAPDRAW:
			try {
				netcode::UnpackPacket pckt(packet, 2);
				unsigned char playerNum;
				pckt >> playerNum;
				if (playerNum != a) {
					Message(str(format(WrongPlayer) %msgCode %a %(unsigned)playerNum));
					break;
				}
				if (!players[playerNum].spectator || allowSpecDraw)
					Broadcast(packet); //forward data
			} catch (const netcode::UnpackPacketException& ex) {
				Message(str(format("Player %s sent invalid MapDraw: %s") %players[a].name %ex.what()));
			}
			break;

		case NETMSG_DIRECT_CONTROL:
			if (inbuf[1] != a) {
				Message(str(format(WrongPlayer) %msgCode %a %(unsigned)inbuf[1]));
				break;
			}
			if (!demoReader) {
				if (!players[inbuf[1]].spectator)
					Broadcast(CBaseNetProtocol::Get().SendDirectControl(inbuf[1]));
				else
					Message(str(format("Error: spectator %s tried direct-controlling a unit") %players[inbuf[1]].name));
			}
			break;

		case NETMSG_DC_UPDATE:
			if (inbuf[1] != a) {
				Message(str(format(WrongPlayer) %msgCode %a %(unsigned)inbuf[1]));
				break;
			}
			if (!demoReader)
				Broadcast(CBaseNetProtocol::Get().SendDirectControlUpdate(inbuf[1], inbuf[2], *((short*)&inbuf[3]), *((short*)&inbuf[5])));
			break;

		case NETMSG_STARTPLAYING: {
			if (players[a].isLocal && gameHasStarted)
				CheckForGameStart(true);
			break;
		}
		case NETMSG_TEAM: {
			//TODO update players[] and teams[] and send all to hostif
			const unsigned player = (unsigned)inbuf[1];
			if (player != a) {
				Message(str(format(WrongPlayer) %msgCode %a %(unsigned)player));
				break;
			}
			const unsigned action = inbuf[2];
			const unsigned fromTeam = players[player].team;

			switch (action) {
				case TEAMMSG_GIVEAWAY: {
					const unsigned toTeam                    = inbuf[3];
					// may be the players team or a team controlled by one of his AIs
					const unsigned fromTeam_g                = inbuf[4];

					if (toTeam >= teams.size()) {
						Message(str(format("Invalid teamID %d in TEAMMSG_GIVEAWAY from player %d") %toTeam %player));
						break;
					}
					if (fromTeam_g >= teams.size()) {
						Message(str(format("Invalid teamID %d in TEAMMSG_GIVEAWAY from player %d") %fromTeam_g %player));
						break;
					}

					const int numPlayersInTeam_g             = countNumPlayersInTeam(players, fromTeam_g);
					const std::vector<unsigned char> &totAIsInTeam_g = getSkirmishAIIds(ais, fromTeam_g);
					const std::vector<unsigned char> &myAIsInTeam_g  = getSkirmishAIIds(ais, fromTeam_g, player);
					const size_t numControllersInTeam_g      = numPlayersInTeam_g + totAIsInTeam_g.size();
					const bool isLeader_g                    = (teams[fromTeam_g].leader == player);
					const bool isOwnTeam_g                   = (fromTeam_g == fromTeam);
					const bool isSpec                        = players[player].spectator;
					const bool hasAIs_g                      = (!myAIsInTeam_g.empty());
					const bool isAllied_g                    = (teams[fromTeam_g].teamAllyteam == teams[fromTeam].teamAllyteam);
					const char* playerType                   = players[player].GetType();
					const bool isSinglePlayer                = (players.size() <= 1);

					if (!isSinglePlayer &&
						(isSpec ||
						(!isOwnTeam_g && !isLeader_g) ||
						(hasAIs_g && !isAllied_g && !cheating))) {
							Message(str(format("%s %s sent invalid team giveaway") %playerType %players[player].name), true);
							break;
					}
					Broadcast(CBaseNetProtocol::Get().SendGiveAwayEverything(player, toTeam, fromTeam_g));

					bool giveAwayOk = false;
					if (isOwnTeam_g) {
						// player is giving stuff from his own team
						giveAwayOk = true;
						//players[player].team = 0;
						players[player].spectator = true;
						if (hostif)
							hostif->SendPlayerDefeated(player);
					} else {
						// player is giving stuff from one of his AI teams
						if (numPlayersInTeam_g == 0) {
							// kill the first AI
							ais.erase(myAIsInTeam_g[0]);
							giveAwayOk = true;
						} else {
							Message(str(format("%s %s can not give away stuff of team %i (still has human players left)") %playerType %players[player].name %fromTeam_g), true);
						}
					}
					if (giveAwayOk && (numControllersInTeam_g == 1)) {
						// team has no controller left now
						teams[fromTeam_g].active = false;
						teams[fromTeam_g].leader = -1;
						std::ostringstream givenAwayMsg;
						givenAwayMsg << players[player].name << " gave everything to " << players[teams[toTeam].leader].name;
						Broadcast(CBaseNetProtocol::Get().SendSystemMessage(SERVER_PLAYER, givenAwayMsg.str()));
					}
					break;
				}
				case TEAMMSG_RESIGN: {
					const bool isSpec         = players[player].spectator;
					const bool isSinglePlayer = (players.size() <= 1);

					if (isSpec && !isSinglePlayer) {
						Message(str(format("Spectator %s sent invalid team resign") %players[player].name), true);
						break;
					}
					Broadcast(CBaseNetProtocol::Get().SendResign(player));

					//players[player].team = 0;
					players[player].spectator = true;
					// actualize all teams of which the player is leader
					for (size_t t = 0; t < teams.size(); ++t) {
						if (teams[t].leader == player) {
							const std::vector<int> &teamPlayers = getPlayersInTeam(players, t);
							const std::vector<unsigned char> &teamAIs  = getSkirmishAIIds(ais, t);
							if ((teamPlayers.size() + teamAIs.size()) == 0) {
								// no controllers left in team
								teams[t].active = false;
								teams[t].leader = -1;
							} else if (teamPlayers.empty()) {
								// no human player left in team
								teams[t].leader = ais[teamAIs[0]].hostPlayer;
							} else {
								// still human controllers left in team
								teams[t].leader = teamPlayers[0];
							}
						}
					}
					if (hostif)
						hostif->SendPlayerDefeated(player);
					break;
				}
				case TEAMMSG_JOIN_TEAM: {
					const unsigned newTeam    = inbuf[3];
					const bool isNewTeamValid = (newTeam < teams.size());
					const bool isSinglePlayer = (players.size() <= 1);

					if (isNewTeamValid && (isSinglePlayer || cheating)) {
						// joining the team is ok
					} else {
						Message(str(format(NoTeamChange) %players[player].name %player));
						break;
					}
					Broadcast(CBaseNetProtocol::Get().SendJoinTeam(player, newTeam));

					players[player].team      = newTeam;
					players[player].spectator = false;
					if (teams[newTeam].leader == -1) {
						teams[newTeam].leader = player;
					}
					break;
				}
				case TEAMMSG_TEAM_DIED: {
					const unsigned teamID = inbuf[3];
#ifndef DEDICATED
					if (players[player].isLocal) { // currently only host is allowed
#else
					if (!players[player].desynced) {
#endif

						if (teamID >= teams.size()) {
							Message(str(format("Invalid teamID %d in TEAMMSG_TEAM_DIED from player %d") %teamID %player));
							break;
						}

						teams[teamID].active = false;
						teams[teamID].leader = -1;
						// convert all the teams players to spectators
						for (size_t p = 0; p < players.size(); ++p) {
							if ((players[p].team == teamID) && !(players[p].spectator)) {
								// are now spectating if this was their team
								//players[p].team = 0;
								players[p].spectator = true;
								if (hostif)
									hostif->SendPlayerDefeated(p);
								Broadcast(CBaseNetProtocol::Get().SendTeamDied(player, teamID));
							}
						}
						// The teams Skirmish AIs destruction process
						// is being initialized from the client they
						// run on. No need to do anything here.
					}
					break;
				}
				default: {
					Message(str(format(UnknownTeammsg) %action %player));
				}
			}
			break;
		}
		case NETMSG_AI_CREATED: {
			try {
				netcode::UnpackPacket pckt(packet, 2);
				unsigned char playerId;
				pckt >> playerId;
				if (playerId != a) {
					Message(str(format(WrongPlayer) %msgCode %a %(unsigned)playerId));
					break;
				}
				unsigned char skirmishAIId_rec; // ignored, we have to create the real one
				pckt >> skirmishAIId_rec;
				unsigned char aiTeamId;
				pckt >> aiTeamId;
				std::string aiName;
				pckt >> aiName;

				if (aiTeamId >= teams.size()) {
					Message(str(format("Invalid teamID %d in NETMSG_AI_CREATED from player %d") %unsigned(aiTeamId) %unsigned(playerId)));
					break;
				}

				const unsigned char playerTeamId = players[playerId].team;
				GameTeam* tpl                    = &teams[playerTeamId];
				GameTeam* tai                    = &teams[aiTeamId];
				//const int numPlayersInAITeam     = countNumPlayersInTeam(players, aiTeam);
				//const int numAIsInAITeam         = countNumSkirmishAIsInTeam(ais, aiTeam);
				const bool weAreLeader           = (tai->leader == playerId);
				const bool weAreAllied           = (tpl->teamAllyteam == tai->teamAllyteam);
				const bool singlePlayer          = (players.size() <= 1);
				const bool noLeader              = (tai->leader == -1);

				if (weAreLeader || singlePlayer || (weAreAllied && (cheating || noLeader))) {
					// creating the AI is ok
				} else {
					Message(str(format(NoAICreated) %players[playerId].name %(int)playerId %(int)aiTeamId));
					break;
				}
				const unsigned char skirmishAIId = ReserveNextAvailableSkirmishAIId();
				if (skirmishAIId == MAX_AIS) {
					Message(str(format("Unable to create AI, limit reached (%d)") %(int)MAX_AIS));
					break;
				}
				players[playerId].linkData[skirmishAIId] = GameParticipant::PlayerLinkData();
				Broadcast(CBaseNetProtocol::Get().SendAICreated(playerId, skirmishAIId, aiTeamId, aiName));

/*
#ifdef SYNCDEBUG
			if (myId != skirmishAIId) {
				Message(str(format("Sync Error, Skirmish AI ID from player %s (%i) does not match the one on the server (%i).") %players[playerId].name %skirmishAIId %myId));
			}
#endif // SYNCDEBUG
*/
				ais[skirmishAIId].team = aiTeamId;
				ais[skirmishAIId].name = aiName;
				ais[skirmishAIId].hostPlayer = playerId;
				if (tai->leader == -1) {
					tai->leader = ais[skirmishAIId].hostPlayer;
					tai->active = true;
				}
			} catch (const netcode::UnpackPacketException& ex) {
				Message(str(format("Player %s sent invalid AICreated: %s") %players[a].name %ex.what()));
			}
			break;
		}
		case NETMSG_AI_STATE_CHANGED: {
			const unsigned char playerId     = inbuf[1];
			if (playerId != a) {
				Message(str(format(WrongPlayer) %msgCode %a %(unsigned)playerId));
				break;
			}
			const unsigned char skirmishAIId = inbuf[2];
			const ESkirmishAIStatus newState = (ESkirmishAIStatus) inbuf[3];

			const bool skirmishAIId_valid    = (ais.find(skirmishAIId) != ais.end());
			if (!skirmishAIId_valid) {
				Message(str(format(NoAIChangeState) %players[playerId].name %(int)playerId %skirmishAIId %(-1) %(int)newState));
				break;
			}

			const unsigned aiTeamId          = ais[skirmishAIId].team;
			const unsigned playerTeamId      = players[playerId].team;
			const size_t numPlayersInAITeam  = countNumPlayersInTeam(players, aiTeamId);
			const size_t numAIsInAITeam      = countNumSkirmishAIsInTeam(ais, aiTeamId);
			GameTeam* tpl                    = &teams[playerTeamId];
			GameTeam* tai                    = &teams[aiTeamId];
			const bool weAreAIHost           = (ais[skirmishAIId].hostPlayer == playerId);
			const bool weAreLeader           = (tai->leader == playerId);
			const bool weAreAllied           = (tpl->teamAllyteam == tai->teamAllyteam);
			const bool singlePlayer          = (players.size() <= 1);
			const ESkirmishAIStatus oldState = ais[skirmishAIId].status;

			if (!(weAreAIHost || weAreLeader || singlePlayer || (weAreAllied && cheating))) {
				Message(str(format(NoAIChangeState) %players[playerId].name %(int)playerId %skirmishAIId %(int)aiTeamId %(int)newState));
				break;
			}
			Broadcast(packet); // forward data

			ais[skirmishAIId].status = newState;
			if (newState == SKIRMAISTATE_DEAD) {
				if (oldState == SKIRMAISTATE_RELOADING) {
					// skip resetting this AIs management state,
					// as it will be reinitialized instantly
				} else {
					ais.erase(skirmishAIId);
					players[playerId].linkData.erase(skirmishAIId);
					FreeSkirmishAIId(skirmishAIId);
					if ((numPlayersInAITeam + numAIsInAITeam) == 1) {
						// team has no controller left now
						tai->active = false;
						tai->leader = -1;
					}
				}
			}
			break;
		}
		case NETMSG_ALLIANCE: {
			const unsigned char player = inbuf[1];
			const int whichAllyTeam = inbuf[2];
			const unsigned char allied = inbuf[3];
			if (player != a) {
				Message(str(format(WrongPlayer) %msgCode %a %(unsigned)player));
				break;
			}
			if (whichAllyTeam == teams[players[a].team].teamAllyteam) {
				Message(str(format("Player %s tried to send spoofed alliance message") %players[a].name));
			}
			else {
				if (!setup->fixedAllies) {
					Broadcast(CBaseNetProtocol::Get().SendSetAllied(player, whichAllyTeam, allied));
				}
				else { // not allowed
				}
			}
			break;
		}
		case NETMSG_CCOMMAND: {
			try {
				CommandMessage msg(packet);

				if (static_cast<unsigned>(msg.GetPlayerID()) == a) {
					if ((commandBlacklist.find(msg.GetAction().command) != commandBlacklist.end()) && players[a].isLocal) {
						// command is restricted to server but player is allowed to execute it
						PushAction(msg.GetAction());
					}
					else if (commandBlacklist.find(msg.GetAction().command) == commandBlacklist.end()) {
						// command is save
						Broadcast(packet);
					}
					else {
						// hack!
						Message(str(format(CommandNotAllowed) %msg.GetPlayerID() %msg.GetAction().command.c_str()));
					}
				}
			} catch (const netcode::UnpackPacketException& ex) {
				Message(str(format("Player %s sent invalid CommandMessage: %s") %players[a].name %ex.what()));
			}
			break;
		}

		case NETMSG_TEAMSTAT: {
			if (hostif)
				hostif->Send(packet->data, packet->length);
			break;
		}

		case NETMSG_GAMEOVER: {
			try {
				// msgCode + msgSize + playerNum (all uchar's)
				const unsigned char fixedSize = 3 * sizeof(unsigned char);

				netcode::UnpackPacket pckt(packet, 1);

				unsigned char totalSize; pckt >> totalSize;
				unsigned char playerNum; pckt >> playerNum;

				if (playerNum != a) {
					Message(str(format(WrongPlayer) %msgCode %a %(unsigned)playerNum));
					break;
				}

				if (totalSize > fixedSize) {
					// if empty, the game has no defined winner(s)
					winningAllyTeams.resize(totalSize - fixedSize);
					pckt >> winningAllyTeams;
				}

				if (hostif)
					hostif->SendGameOver(playerNum, winningAllyTeams);
				Broadcast(CBaseNetProtocol::Get().SendGameOver(playerNum, winningAllyTeams));

				gameEndTime = spring_gettime();
			} catch (const netcode::UnpackPacketException& ex) {
				Message(str(format("Player %s sent invalid GameOver: %s") %players[a].name %ex.what()));
			}
			break;
		}

#ifdef SYNCDEBUG
		case NETMSG_SD_CHKRESPONSE:
		case NETMSG_SD_BLKRESPONSE:
			CSyncDebugger::GetInstance()->ServerReceived(inbuf);
			break;
		case NETMSG_SD_CHKREQUEST:
		case NETMSG_SD_BLKREQUEST:
		case NETMSG_SD_RESET:
			Broadcast(packet);
			break;
#endif
		// CGameServer should never get these messages
		//case NETMSG_GAMEID:
		//case NETMSG_INTERNAL_SPEED:
		//case NETMSG_ATTEMPTCONNECT:
		//case NETMSG_GAMEDATA:
		//case NETMSG_RANDSEED:
		default: {
			Message(str(format(UnknownNetmsg) %msgCode %a));
		}
		break;
	}
}

void CGameServer::ServerReadNet()
{
	// handle new connections
	while (UDPNet && UDPNet->HasIncomingConnections()) {
		boost::shared_ptr<netcode::UDPConnection> prev = UDPNet->PreviewConnection().lock();
		boost::shared_ptr<const RawPacket> packet = prev->GetData();

		if (packet && packet->length >= 3 && packet->data[0] == NETMSG_ATTEMPTCONNECT) {
			try {
				netcode::UnpackPacket msg(packet, 3);
				std::string name, passwd, version;
				unsigned char reconnect, netloss;
				unsigned short netversion;
				msg >> netversion;
				if (netversion != NETWORK_VERSION)
					throw netcode::UnpackPacketException("Wrong network version");
				msg >> name;
				msg >> passwd;
				msg >> version;
				msg >> reconnect;
				msg >> netloss;
				BindConnection(name, passwd, version, false, UDPNet->AcceptConnection(), reconnect, netloss);
			} catch (const netcode::UnpackPacketException& ex) {
				Message(str(format(ConnectionReject) %ex.what() %packet->data[0] %packet->data[2] %packet->length));
				UDPNet->RejectConnection();
			}
		}
		else {
			if (packet && packet->length >= 3)
				Message(str(format(ConnectionReject) %"Invalid message ID" %packet->data[0] %packet->data[2] %packet->length));
			else
				Message("Connection attempt rejected: Packet too short");
			UDPNet->RejectConnection();
		}
	}

	const float updateBandwidth = spring_tomsecs(spring_gettime() - lastBandwidthUpdate) / (float)playerBandwidthInterval;
	if (updateBandwidth >= 1.0f)
		lastBandwidthUpdate = spring_gettime();

	for (size_t a = 0; a < players.size(); ++a) {
		GameParticipant &player = players[a];
		boost::shared_ptr<netcode::CConnection> &plink = player.link;
		if (!plink)
			continue; // player not connected
		if (plink->CheckTimeout(0, !gameHasStarted)) {
			Message(str(format(PlayerLeft) %player.GetType() %player.name %" timeout")); //this must happen BEFORE the reset!
			Broadcast(CBaseNetProtocol::Get().SendPlayerLeft(a, 0));
			player.Kill("User timeout");
			UpdateSpeedControl(speedControl);
			if (hostif)
				hostif->SendPlayerLeft(a, 0);
			continue;
		}

		std::map<unsigned char, GameParticipant::PlayerLinkData> &pld = player.linkData;
		boost::shared_ptr<const RawPacket> packet;
		while ((packet = plink->GetData())) {  // relay all the packets to separate connections for the player and AIs
			unsigned char aiID = MAX_AIS;
			int cID = -1;
			if (packet->length >= 5) {
				cID = packet->data[0];
				if (cID == NETMSG_AICOMMAND || cID == NETMSG_AICOMMAND_TRACKED || cID == NETMSG_AICOMMANDS || cID == NETMSG_AISHARE)
					aiID = packet->data[4];
			}
			std::map<unsigned char, GameParticipant::PlayerLinkData>::iterator liit = pld.find(aiID);
			if (liit != pld.end())
				liit->second.link->SendData(packet);
			else
				Message(str(format("Player %s sent invalid AI ID %d in AICOMMAND %d") %player.name %(int)aiID %cID));
		}

		for (std::map<unsigned char, GameParticipant::PlayerLinkData>::iterator lit = pld.begin(); lit != pld.end(); ++lit) {
			int &bandwidthUsage = lit->second.bandwidthUsage;
			boost::shared_ptr<netcode::CConnection> &link = lit->second.link;

			bool bwLimitWasReached = (globalConfig->linkIncomingPeakBandwidth > 0 && bandwidthUsage > globalConfig->linkIncomingPeakBandwidth);
			if (updateBandwidth >= 1.0f && globalConfig->linkIncomingSustainedBandwidth > 0)
				bandwidthUsage = std::max(0, bandwidthUsage - std::max(1, (int)((float)globalConfig->linkIncomingSustainedBandwidth / (1000.0f / (playerBandwidthInterval * updateBandwidth)))));

			int numDropped = 0;
			boost::shared_ptr<const RawPacket> packet;

			bool dropPacket = globalConfig->linkIncomingMaxWaitingPackets > 0 && (globalConfig->linkIncomingPeakBandwidth <= 0 || bwLimitWasReached);
			int ahead = 0;
			bool bwLimitIsReached = globalConfig->linkIncomingPeakBandwidth > 0 && bandwidthUsage > globalConfig->linkIncomingPeakBandwidth;
			while (link) {
				if (dropPacket)
					dropPacket = (packet = link->Peek(globalConfig->linkIncomingMaxWaitingPackets));
				packet = (!bwLimitIsReached || dropPacket) ? link->GetData() : link->Peek(ahead++);
				if (!packet)
					break;

				bool droppablePacket = (packet->length <= 0 || (packet->data[0] != NETMSG_SYNCRESPONSE && packet->data[0] != NETMSG_KEYFRAME));
				if (dropPacket && droppablePacket)
					++numDropped;
				else if (!bwLimitIsReached || !droppablePacket) {
					ProcessPacket(a, packet); // non droppable packets may be processed more than once, but this does no harm
					if (globalConfig->linkIncomingPeakBandwidth > 0 && droppablePacket) {
						bandwidthUsage += std::max((unsigned)linkMinPacketSize, packet->length);
						if (!bwLimitIsReached)
							bwLimitIsReached = (bandwidthUsage > globalConfig->linkIncomingPeakBandwidth);
					}
				}
			}
			if (numDropped > 0) {
				if (lit->first == MAX_AIS)
					PrivateMessage(a, str(format("Warning: Waiting packet limit was reached for %s [packets dropped]") %player.name));
				else
					PrivateMessage(a, str(format("Warning: Waiting packet limit was reached for %s AI #%d [packets dropped]") %player.name %(int)lit->first));
			}

			if (!bwLimitWasReached && bwLimitIsReached) {
				if (lit->first == MAX_AIS)
					PrivateMessage(a, str(format("Warning: Bandwidth limit was reached for %s [packets delayed]") %player.name));
				else
					PrivateMessage(a, str(format("Warning: Bandwidth limit was reached for %s AI #%d [packets delayed]") %player.name %(int)lit->first));
			}
		}
	}

#ifdef SYNCDEBUG
	CSyncDebugger::GetInstance()->ServerHandlePendingBlockRequests();
#endif
}


void CGameServer::GenerateAndSendGameID()
{
	// This is where we'll store the ID temporarily.
	union {
		unsigned char charArray[16];
		unsigned int intArray[4];
	} gameID;

	// First and second dword are time based (current time and load time).
	gameID.intArray[0] = (unsigned) time(NULL);
	for (int i = 4; i < 12; ++i)
		gameID.charArray[i] = rng();

	// Third dword is CRC of setupText.
	CRC crc;
	crc.Update(setup->gameSetupText.c_str(), setup->gameSetupText.length());
	gameID.intArray[2] = crc.GetDigest();

	CRC entropy;
	entropy.Update(spring_tomsecs(lastTick-serverStartTime));
	gameID.intArray[3] = entropy.GetDigest();

	Broadcast(CBaseNetProtocol::Get().SendGameID(gameID.charArray));
#ifdef DEDICATED
	demoRecorder->SetGameID(gameID.charArray);
#endif

	generatedGameID = true;
}

void CGameServer::CheckForGameStart(bool forced)
{
	assert(!gameHasStarted);
	bool allReady = true;

	for (size_t a = static_cast<size_t>(setup->numDemoPlayers); a < players.size(); a++) {
		if (players[a].myState == GameParticipant::UNCONNECTED && serverStartTime + spring_secs(30) < spring_gettime()) {
			// autostart the game when 45 seconds have passed and everyone who managed to connect is ready
			continue;
		}
		else if (players[a].myState < GameParticipant::INGAME) {
			allReady = false;
			break;
		} else if (!players[a].spectator && teams[players[a].team].active && !players[a].readyToStart && !demoReader) {
			allReady = false;
			break;
		}
	}

	// msecs to wait until the game starts after all players are ready
	const spring_duration gameStartDelay = spring_secs(setup->gameStartDelay);

	if (allReady || forced) {
		if (!spring_istime(readyTime)) {
			readyTime = spring_gettime();
			rng.Seed(spring_tomsecs(readyTime-serverStartTime));
			// we have to wait at least 1 msec, because 0 is a special case
			const unsigned countdown = std::max(1, spring_tomsecs(gameStartDelay));
			Broadcast(CBaseNetProtocol::Get().SendStartPlaying(countdown));
		}
	}
	if (spring_istime(readyTime) && ((spring_gettime() - readyTime) > gameStartDelay)) {
		StartGame();
	}
}

void CGameServer::StartGame()
{
	assert(!gameHasStarted);
	gameHasStarted = true;
	startTime = gameTime;
	if (!canReconnect && !allowAdditionalPlayers)
		packetCache.clear(); // free memory

	if (UDPNet && !canReconnect && !allowAdditionalPlayers)
		UDPNet->SetAcceptingConnections(false); // do not accept new connections

	// make sure initial game speed is within allowed range and sent a new speed if not
	UserSpeedChange(userSpeedFactor, SERVER_PLAYER);

	if (demoReader) {
		// the client told us to start a demo
		// no need to send startPos and startplaying since its in the demo
		Message(DemoStart);
		return;
	}

	GenerateAndSendGameID();

	std::vector<bool> teamStartPosSent(teams.size(), false);

	// send start position for player controlled teams
	for (size_t a = 0; a < players.size(); ++a) {
		if (!players[a].spectator) {
			const unsigned aTeam = players[a].team;
			Broadcast(CBaseNetProtocol::Get().SendStartPos(a, (int)aTeam, players[a].readyToStart, teams[aTeam].startPos.x, teams[aTeam].startPos.y, teams[aTeam].startPos.z));
			teamStartPosSent[aTeam] = true;
		}
	}

	// send start position for all other teams
	for (size_t a = 0; a < teams.size(); ++a) {
		if (!teamStartPosSent[a]) {
			// teams which aren't player controlled are always ready
			Broadcast(CBaseNetProtocol::Get().SendStartPos(SERVER_PLAYER, a, true, teams[a].startPos.x, teams[a].startPos.y, teams[a].startPos.z));
		}
	}

	Broadcast(CBaseNetProtocol::Get().SendRandSeed(rng()));
	Broadcast(CBaseNetProtocol::Get().SendStartPlaying(0));
	if (hostif)
		hostif->SendStartPlaying();
	timeLeft=0;
	lastTick = spring_gettime() - spring_msecs(1);
	CreateNewFrame(true, false);
}

void CGameServer::SetGamePausable(const bool arg)
{
	gamePausable = arg;
}

void CGameServer::PushAction(const Action& action)
{
	if (action.command == "kickbynum") {
		if (!action.extra.empty()) {
			const int playerNum = atoi(action.extra.c_str());
			KickPlayer(playerNum);
		}
	}
	else if (action.command == "kick") {
		if (!action.extra.empty()) {
			std::string name = action.extra;
			StringToLowerInPlace(name);
			for (size_t a=0; a < players.size();++a) {
				std::string playerLower = StringToLower(players[a].name);
				if (playerLower.find(name)==0) {	// can kick on substrings of name
					if (!players[a].isLocal) // do not kick host
						KickPlayer(a);
				}
			}
		}
	}
	else if (action.command == "nopause") {
		SetBoolArg(gamePausable, action.extra);
	}
	else if (action.command == "nohelp") {
		SetBoolArg(noHelperAIs, action.extra);
		// sent it because clients have to do stuff when this changes
		CommandMessage msg(action, SERVER_PLAYER);
		Broadcast(boost::shared_ptr<const RawPacket>(msg.Pack()));
	}
	else if (action.command == "nospecdraw") {
		SetBoolArg(allowSpecDraw, action.extra);
		// sent it because clients have to do stuff when this changes
		CommandMessage msg(action, SERVER_PLAYER);
		Broadcast(boost::shared_ptr<const RawPacket>(msg.Pack()));
	}
	else if (action.command == "setmaxspeed" && !action.extra.empty()) {
		float newUserSpeed = std::max(static_cast<float>(atof(action.extra.c_str())), minUserSpeed);
		if (newUserSpeed > 0.2) {
			maxUserSpeed = newUserSpeed;
			UserSpeedChange(userSpeedFactor, SERVER_PLAYER);
		}
	}
	else if (action.command == "setminspeed" && !action.extra.empty()) {
		minUserSpeed = std::min(static_cast<float>(atof(action.extra.c_str())), maxUserSpeed);
		UserSpeedChange(userSpeedFactor, SERVER_PLAYER);
	}
	else if (action.command == "forcestart") {
		if (!gameHasStarted)
			CheckForGameStart(true);
	}
	else if (action.command == "skip") {
		if (demoReader) {
			std::string timeStr = action.extra;

			// parse the skip time

			// skip in seconds
			bool skipFrames = false;
			if (timeStr[0] == 'f') {
				// skip in frame
				skipFrames = true;
				timeStr.erase(0, 1); // remove first char
			}

			// skip to absolute game-second/-frame
			bool skipRelative = false;
			if (timeStr[0] == '+') {
				// skip to relative game-second/-frame
				skipRelative = true;
				timeStr.erase(0, 1); // remove first char
			}

			// amount of frames/seconds to skip (to)
			const int amount = atoi(timeStr.c_str());

			// the absolute frame to skip to
			int endFrame;

			if (skipFrames)
				endFrame = amount;
			else
				endFrame = GAME_SPEED * amount;

			if (skipRelative)
				endFrame += serverFrameNum;

			SkipTo(endFrame);
		}
	}
	else if (action.command == "cheat") {
		SetBoolArg(cheating, action.extra);
		CommandMessage msg(action, SERVER_PLAYER);
		Broadcast(boost::shared_ptr<const RawPacket>(msg.Pack()));
	}
	else if (action.command == "singlestep") {
		if (isPaused) {
			if (demoReader) {
				// we only want to advance one frame at most, so
				// the next time-index must be "close enough" not
				// to move past more than 1 NETMSG_NEWFRAME
				modGameTime = demoReader->GetModGameTime() + 0.001f;
			}

			CreateNewFrame(true, true);
		}
	}
	else if (action.command == "adduser") {
		if (!action.extra.empty() && whiteListAdditionalPlayers) {
			// split string by whitespaces
			const std::vector<std::string> &tokens = CSimpleParser::Tokenize(action.extra);

			if (tokens.size() > 1) {
				const std::string& name = tokens[0];
				const std::string& password = tokens[1];
				int team = 0;
				bool spectator = true;
				if ( tokens.size() > 2 ) {
					spectator = (tokens[2] == "0") ? false : true;
				}
				if ( tokens.size() > 3 ) {
					team = atoi(tokens[3].c_str());
				}
				// note: this must only compare by name
				std::vector<GameParticipant>::iterator participantIter =
						std::find_if( players.begin(), players.end(), bind( &GameParticipant::name, _1 ) == name );

				if (participantIter != players.end()) {
					const GameParticipant::customOpts &opts = participantIter->GetAllValues();
					GameParticipant::customOpts::const_iterator it;
					if ((it = opts.find("origpass")) == opts.end() || it->second == "") {
						it = opts.find("password");
						if(it != opts.end())
							participantIter->SetValue("origpass", it->second);
					}
					participantIter->SetValue("password", password);
					LOG("Changed player/spectator password: \"%s\" \"%s\"", name.c_str(), password.c_str());
				} else {
					AddAdditionalUser(name, password, false, spectator, team);
					std::string logstring = "Added ";
					if ( spectator ) logstring = logstring + "spectator";
					else logstring = logstring + "player";
					logstring = logstring + " \"%s\" with password \"%s\", to team %d";
					LOG(logstring.c_str(), name.c_str(), password.c_str(),team);
				}
			} else {
				LOG_L(L_WARNING, "Failed to add player/spectator password. usage: /adduser <player-name> <password> [spectator] [team]");
			}
		}
	}
	else if (action.command == "kill") {
		quitServer = true;
	}
	else if (action.command == "pause") {
		bool newPausedState = isPaused;
		if (action.extra.empty()) {
			// if no param is given, toggle paused state
			newPausedState = !isPaused;
		} else {
			// if a param is given, interpret it as "bool setPaused"
			SetBoolArg(newPausedState, action.extra);
		}
		if (newPausedState != isPaused) {
			// the state changed
			isPaused = newPausedState;
		}
	}
	else {
		// only forward to players (send over network)
		CommandMessage msg(action, SERVER_PLAYER);
		Broadcast(boost::shared_ptr<const RawPacket>(msg.Pack()));
	}
}

bool CGameServer::HasFinished() const
{
	Threading::RecursiveScopedLock scoped_lock(gameServerMutex);
	return quitServer;
}

void CGameServer::CreateNewFrame(bool fromServerThread, bool fixedFrameTime)
{
	if (!demoReader) {
		// use NEWFRAME_MSGes from demo otherwise
		Threading::RecursiveScopedLock(gameServerMutex, !fromServerThread);

		CheckSync();
		int newFrames = 1;

		if (!fixedFrameTime) {
			spring_time currentTick = spring_gettime();
			spring_duration timeElapsed = currentTick - lastTick;

			if (timeElapsed > spring_msecs(200))
				timeElapsed = spring_msecs(200);

			timeLeft += GAME_SPEED * internalSpeed * float(spring_tomsecs(timeElapsed)) * 0.001f;
			lastTick=currentTick;
			newFrames = (timeLeft > 0)? int(ceil(timeLeft)): 0;
			timeLeft -= newFrames;

			if (hasLocalClient) {
				// needs to set lastTick and stuff, otherwise we will get all the left out NEWFRAME's at once when client has catched up
				if (players[localClientNumber].lastFrameResponse + GAME_SPEED*2 <= serverFrameNum)
					return;
			}
		}

		const bool rec = videoCapturing->IsCapturing();
		const bool normalFrame = !isPaused && !rec;
		const bool videoFrame = !isPaused && fixedFrameTime;
		const bool singleStep = fixedFrameTime && !rec;

		if (normalFrame || videoFrame || singleStep) {
			for (int i=0; i < newFrames; ++i) {
				assert(!demoReader);
				++serverFrameNum;
				// Send out new frame messages.
				if ((serverFrameNum % serverKeyframeIntervall) == 0)
					Broadcast(CBaseNetProtocol::Get().SendKeyFrame(serverFrameNum));
				else
					Broadcast(CBaseNetProtocol::Get().SendNewFrame());

				// every gameProgressFrameInterval, we broadcast current frame in a special message that doesn't get cached and skips normal queue, to let players know their loading %
				if ((serverFrameNum%gameProgressFrameInterval) == 0) {
					CBaseNetProtocol::PacketType progressPacket = CBaseNetProtocol::Get().SendCurrentFrameProgress(serverFrameNum);
					// we cannot use broadcast here, since we want to skip caching
					for (size_t p = 0; p < players.size(); ++p)
						players[p].SendData(progressPacket);
				}
#ifdef SYNCCHECK
				outstandingSyncFrames.insert(serverFrameNum);
#endif
			}
		}
	} else {
		CheckSync();
		SendDemoData(-1);
	}
}

void CGameServer::UpdateSpeedControl(int speedCtrl) {
	if (speedControl != speedCtrl) {
		speedControl = speedCtrl;
		curSpeedCtrl = (speedControl == 1 || speedControl == -1) ? 1 : 0;
	}
	if (speedControl >= 0) {
		int oldSpeedCtrl = curSpeedCtrl;
		int avgVotes = 0;
		int maxVotes = 0;
		for (size_t i = 0; i < players.size(); ++i) {
			if (players[i].link) {
				int sc = players[i].speedControl;
				if (sc == 1 || sc == -1)
					++avgVotes;
				else if (sc == 2 || sc == -2)
					++maxVotes;
			}
		}

		if (avgVotes > maxVotes)
			curSpeedCtrl = 1;
		else if (avgVotes < maxVotes)
			curSpeedCtrl = 0;
		else
			curSpeedCtrl = (speedControl == 1) ? 1 : 0;

		if (curSpeedCtrl != oldSpeedCtrl) {
			Message(str(format("Server speed control: %s CPU [%d/%d]")
					%(curSpeedCtrl ? "Average" : "Maximum")
					%(curSpeedCtrl ? avgVotes : maxVotes)
					%(avgVotes + maxVotes)));
		}
	}
}

std::string CGameServer::SpeedControlToString(int speedCtrl) {

	std::string desc;
	if (speedCtrl == 0) {
		desc = "Default";
	} else if ((speedCtrl == 1) || (speedCtrl == -1)) {
		desc = "Average CPU";
	} else if ((speedCtrl == 2) || (speedCtrl == -2)) {
		desc = "Maximum CPU";
	} else {
		desc = "<invalid>";
	}

	if (speedCtrl < 0) {
		desc += " (server voting disabled)";
	}

	return desc;
}

void CGameServer::UpdateLoop()
{
	try {
		Threading::SetThreadName("netcode");

		while (!quitServer) {
			spring_sleep(spring_msecs(10));

			if (UDPNet)
				UDPNet->Update();

			Threading::RecursiveScopedLock scoped_lock(gameServerMutex);
			ServerReadNet();
			Update();
		}

		if (hostif)
			hostif->SendQuit();
		Broadcast(CBaseNetProtocol::Get().SendQuit("Server shutdown"));

		// flush the quit messages to reduce ugly network error messages on the client side
		spring_sleep(spring_msecs(1000)); // this is to make sure the Flush has any effect at all (we don't want a forced flush)
		for (size_t i = 0; i < players.size(); ++i) {
			if (players[i].link)
				players[i].link->Flush();
		}
		spring_sleep(spring_msecs(1000)); // now let clients close their connections
	} CATCH_SPRING_ERRORS
}

bool CGameServer::WaitsOnCon() const
{
	return (UDPNet && UDPNet->IsAcceptingConnections());
}

void CGameServer::KickPlayer(const int playerNum)
{
	if (players[playerNum].link) { // only kick connected players
		Message(str(format(PlayerLeft) %players[playerNum].GetType() %players[playerNum].name %"kicked"));
		Broadcast(CBaseNetProtocol::Get().SendPlayerLeft(playerNum, 2));
		players[playerNum].Kill("Kicked from the battle");
		UpdateSpeedControl(speedControl);
		if (hostif)
			hostif->SendPlayerLeft(playerNum, 2);
	}
	else
		Message(str(format("Attempt to kick player %d who is not connected") %playerNum));

}


void CGameServer::AddAdditionalUser(const std::string& name, const std::string& passwd, bool fromDemo, bool spectator, int team)
{
	GameParticipant buf;
	buf.isFromDemo = fromDemo;
	buf.name = name;
	buf.spectator = spectator;
	buf.team = team;
	buf.isMidgameJoin = true;
	if (passwd.size() > 0)
		buf.SetValue("password",passwd);
	players.push_back(buf);
	UpdatePlayerNumberMap();
	if (!fromDemo)
		Broadcast(CBaseNetProtocol::Get().SendCreateNewPlayer(players.size() -1, buf.spectator, buf.team, buf.name)); // inform all the players of the newcomer
}


unsigned CGameServer::BindConnection(std::string name, const std::string& passwd, const std::string& version, bool isLocal, boost::shared_ptr<netcode::CConnection> link, bool reconnect, int netloss)
{
	Message(str(format("%s attempt from %s") %(reconnect ? "Reconnection" : "Connection") %name));
	Message(str(format(" -> Version: %s") %version));
	Message(str(format(" -> Address: %s") %link->GetFullAddress()), false);
	size_t newPlayerNumber = players.size();

	if (link->CanReconnect())
		canReconnect = true;

	std::string errmsg = "";
	bool terminate = false;

	for (size_t i = 0; i < players.size(); ++i) {
		if (name == players[i].name) {
			if (!players[i].isFromDemo) {
				if (!players[i].link) {
					if (reconnect)
						errmsg = "User is not ingame";
					else if (canReconnect || !gameHasStarted)
						newPlayerNumber = i;
					else
						errmsg = "Game has already started";
					break;
				}
				else {
					bool reconnectAllowed = canReconnect && players[i].link->CheckTimeout(-1);
					if (!reconnect && reconnectAllowed) {
						newPlayerNumber = i;
						terminate = true;
					}
					else if (reconnect && reconnectAllowed && players[i].link->GetFullAddress() != link->GetFullAddress())
						newPlayerNumber = i;
					else
						errmsg = "User is already ingame";
					break;
				}
			}
			else {
				errmsg = "User name duplicated in the demo";
			}
		}
	}

	if (newPlayerNumber >= players.size() && errmsg == "") {
		if (demoReader || allowAdditionalPlayers)
			AddAdditionalUser(name, passwd);
		else
			errmsg = "User name not authorized to connect";
	}

	// check for user's password
	if (errmsg == "" && !isLocal) {
		if (newPlayerNumber < players.size()) {
			const GameParticipant::customOpts &opts = players[newPlayerNumber].GetAllValues();
			GameParticipant::customOpts::const_iterator it;
			if ((it = opts.find("password")) != opts.end() && passwd != it->second) {
				if ((!reconnect || (it = opts.find("origpass")) == opts.end() || it->second == "" || passwd != it->second))
					errmsg = "Incorrect password";
			}
			else if (!reconnect) // forget about origpass whenever a real mid-game join succeeds
				players[newPlayerNumber].SetValue("origpass", "");
		}
	}

	if(!reconnect) // don't respond before we are sure we want to do it
		link->Unmute(); // never respond to reconnection attempts, it could interfere with the protocol and desync

	if (newPlayerNumber >= players.size() || errmsg != "") {
		Message(str(format(" -> %s") %errmsg));
		link->SendData(CBaseNetProtocol::Get().SendQuit(str(format("Connection rejected: %s") %errmsg)));
		return 0;
	}

	GameParticipant& newPlayer = players[newPlayerNumber];

	if (terminate) {
		Message(str(format(PlayerLeft) %newPlayer.GetType() %newPlayer.name %" terminating existing connection"));
		Broadcast(CBaseNetProtocol::Get().SendPlayerLeft(newPlayerNumber, 0));
		newPlayer.link.reset(); // prevent sending a quit message since this might kill the new connection
		newPlayer.Kill("Terminating connection");
		UpdateSpeedControl(speedControl);
		if (hostif)
			hostif->SendPlayerLeft(newPlayerNumber, 0);
	}

	if (newPlayer.isMidgameJoin) {
		link->SendData(CBaseNetProtocol::Get().SendCreateNewPlayer(newPlayerNumber, newPlayer.spectator, newPlayer.team, newPlayer.name)); // inform the player about himself if it's a midgame join
	}

	newPlayer.isReconn = gameHasStarted;

	if (newPlayer.link) {
		newPlayer.link->ReconnectTo(*link);
		if (UDPNet)
			UDPNet->UpdateConnections();
		Message(str(format(" -> Connection reestablished (id %i)") %newPlayerNumber));
		newPlayer.link->SetLossFactor(netloss);
		newPlayer.link->Flush(!gameHasStarted);
		return newPlayerNumber;
	}

	newPlayer.Connected(link, isLocal);
	newPlayer.SendData(boost::shared_ptr<const RawPacket>(gameData->Pack()));
	newPlayer.SendData(CBaseNetProtocol::Get().SendSetPlayerNum((unsigned char)newPlayerNumber));

	// after gamedata and playerNum, the player can start loading
	for (std::list< std::vector<boost::shared_ptr<const netcode::RawPacket> > >::const_iterator lit = packetCache.begin(); lit != packetCache.end(); ++lit)
		for (std::vector<boost::shared_ptr<const netcode::RawPacket> >::const_iterator vit = lit->begin(); vit != lit->end(); ++vit)
			newPlayer.SendData(*vit); // throw at him all stuff he missed until now

	if (!demoReader || setup->demoName.empty()) { // gamesetup from demo?
		if (!newPlayer.spectator) {
			unsigned newPlayerTeam = newPlayer.team;
			if (!teams[newPlayerTeam].active) { // create new team
				newPlayer.readyToStart = (setup->startPosType != CGameSetup::StartPos_ChooseInGame);
				teams[newPlayerTeam].active = true;
			}
			Broadcast(CBaseNetProtocol::Get().SendJoinTeam(newPlayerNumber, newPlayerTeam));
		}
	}

	Message(str(format(" -> Connection established (given id %i)") %newPlayerNumber));

	link->SetLossFactor(netloss);
	link->Flush(!gameHasStarted);
	return newPlayerNumber;
}

void CGameServer::GotChatMessage(const ChatMessage& msg)
{
	if (!msg.msg.empty()) { // silently drop empty chat messages
		Broadcast(boost::shared_ptr<const RawPacket>(msg.Pack()));
		if (hostif && msg.fromPlayer >= 0 && static_cast<unsigned int>(msg.fromPlayer) != SERVER_PLAYER) {
			// do not echo packets to the autohost
			hostif->SendPlayerChat(msg.fromPlayer, msg.destination,  msg.msg);
		}
	}
}

void CGameServer::InternalSpeedChange(float newSpeed)
{
	if (internalSpeed == newSpeed) {
		// TODO some error here
	}
	Broadcast(CBaseNetProtocol::Get().SendInternalSpeed(newSpeed));
	internalSpeed = newSpeed;
}

void CGameServer::UserSpeedChange(float newSpeed, int player)
{
	if (curSpeedCtrl > 0 &&
		player >= 0 && static_cast<unsigned int>(player) != SERVER_PLAYER &&
		!players[player].isLocal && !isPaused &&
		(players[player].spectator || (curSpeedCtrl > 0 &&
		(players[player].cpuUsage - medianCpu > std::min(0.2f, std::max(0.0f, 0.8f - medianCpu)) ||
		(serverFrameNum - players[player].lastFrameResponse) - medianPing > internalSpeed * GAME_SPEED / 2)))) {
		PrivateMessage(player, "Speed change rejected (cpu load or ping is too high)");
		return; // disallow speed change by players who cannot keep up gamespeed
	}

	newSpeed = std::min(maxUserSpeed, std::max(newSpeed, minUserSpeed));

	if (userSpeedFactor != newSpeed) {
		if (internalSpeed > newSpeed || internalSpeed == userSpeedFactor) // insta-raise speed when not slowed down
			InternalSpeedChange(newSpeed);

		Broadcast(CBaseNetProtocol::Get().SendUserSpeed(player, newSpeed));
		userSpeedFactor = newSpeed;
	}
}

unsigned char CGameServer::ReserveNextAvailableSkirmishAIId() {

	if (usedSkirmishAIIds.size() >= MAX_AIS)
		return MAX_AIS; // no available IDs

	unsigned char skirmishAIId = 0;
	// find a free id
	std::list<unsigned char>::iterator it;
	for (it = usedSkirmishAIIds.begin(); it != usedSkirmishAIIds.end(); ++it, skirmishAIId++) {
		if (*it != skirmishAIId)
			break;
	}

	usedSkirmishAIIds.insert(it, skirmishAIId);

	return skirmishAIId;
}

void CGameServer::FreeSkirmishAIId(const unsigned char skirmishAIId) {
	usedSkirmishAIIds.remove(skirmishAIId);
}

void CGameServer::AddToPacketCache(boost::shared_ptr<const netcode::RawPacket> &pckt) {
	if (packetCache.empty() || packetCache.back().size() >= PKTCACHE_VECSIZE) {
		packetCache.push_back(std::vector<boost::shared_ptr<const netcode::RawPacket> >());
		packetCache.back().reserve(PKTCACHE_VECSIZE);
	}
	packetCache.back().push_back(pckt);
}