Files @ r19056:723de07a18e9
Branch filter:

Location: cpp/openttd-patchpack/source/src/network/network_server.cpp

rubidium
(svn r23924) -Fix [FS#5054]: [NoGo] "Some" news messages would cause an assertion to be triggered due to a missing proper location for the viewport of the news message, so only allow building when valid data for the viewport is provided or no viewport is used
   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
/* $Id$ */

/*
 * This file is part of OpenTTD.
 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
 */

/** @file network_server.cpp Server part of the network protocol. */

#ifdef ENABLE_NETWORK

#include "../stdafx.h"
#include "../strings_func.h"
#include "../date_func.h"
#include "network_admin.h"
#include "network_server.h"
#include "network_udp.h"
#include "network_base.h"
#include "../console_func.h"
#include "../company_base.h"
#include "../command_func.h"
#include "../saveload/saveload.h"
#include "../saveload/saveload_filter.h"
#include "../station_base.h"
#include "../genworld.h"
#include "../company_func.h"
#include "../company_gui.h"
#include "../roadveh.h"
#include "../order_backup.h"
#include "../core/pool_func.hpp"
#include "../core/random_func.hpp"
#include "../rev.h"


/* This file handles all the server-commands */

DECLARE_POSTFIX_INCREMENT(ClientID)
/** The identifier counter for new clients (is never decreased) */
static ClientID _network_client_id = CLIENT_ID_FIRST;

/** Make very sure the preconditions given in network_type.h are actually followed */
assert_compile(MAX_CLIENT_SLOTS > MAX_CLIENTS);
/** Yes... */
assert_compile(NetworkClientSocketPool::MAX_SIZE == MAX_CLIENT_SLOTS);

/** The pool with clients. */
NetworkClientSocketPool _networkclientsocket_pool("NetworkClientSocket");
INSTANTIATE_POOL_METHODS(NetworkClientSocket)

/** Instantiate the listen sockets. */
template SocketList TCPListenHandler<ServerNetworkGameSocketHandler, PACKET_SERVER_FULL, PACKET_SERVER_BANNED>::sockets;

/** Writing a savegame directly to a number of packets. */
struct PacketWriter : SaveFilter {
	ServerNetworkGameSocketHandler *cs; ///< Socket we are associated with.
	Packet *current;                    ///< The packet we're currently writing to.
	size_t total_size;                  ///< Total size of the compressed savegame.

	/**
	 * Create the packet writer.
	 * @param cs The socket handler we're making the packets for.
	 */
	PacketWriter(ServerNetworkGameSocketHandler *cs) : SaveFilter(NULL), cs(cs), current(NULL), total_size(0)
	{
		this->cs->savegame_mutex = ThreadMutex::New();
	}

	/** Make sure everything is cleaned up. */
	~PacketWriter()
	{
		/* Prevent double frees. */
		if (this->cs != NULL) {
			if (this->cs->savegame_mutex != NULL) this->cs->savegame_mutex->BeginCritical();
			this->cs->savegame = NULL;
			if (this->cs->savegame_mutex != NULL) this->cs->savegame_mutex->EndCritical();

			delete this->cs->savegame_mutex;
			this->cs->savegame_mutex = NULL;
		}

		delete this->current;
	}

	/** Append the current packet to the queue. */
	void AppendQueue()
	{
		if (this->current == NULL) return;

		Packet **p = &this->cs->savegame_packets;
		while (*p != NULL) {
			p = &(*p)->next;
		}
		*p = this->current;

		this->current = NULL;
	}

	/* virtual */ void Write(byte *buf, size_t size)
	{
		/* We want to abort the saving when the socket is closed. */
		if (this->cs == NULL) SlError(STR_NETWORK_ERROR_LOSTCONNECTION);

		if (this->current == NULL) this->current = new Packet(PACKET_SERVER_MAP_DATA);

		if (this->cs->savegame_mutex != NULL) this->cs->savegame_mutex->BeginCritical();

		byte *bufe = buf + size;
		while (buf != bufe) {
			size_t to_write = min(SEND_MTU - this->current->size, bufe - buf);
			memcpy(this->current->buffer + this->current->size, buf, to_write);
			this->current->size += (PacketSize)to_write;
			buf += to_write;

			if (this->current->size == SEND_MTU) {
				this->AppendQueue();
				if (buf != bufe) this->current = new Packet(PACKET_SERVER_MAP_DATA);
			}
		}

		if (this->cs->savegame_mutex != NULL) this->cs->savegame_mutex->EndCritical();

		this->total_size += size;
	}

	/* virtual */ void Finish()
	{
		/* We want to abort the saving when the socket is closed. */
		if (this->cs == NULL) SlError(STR_NETWORK_ERROR_LOSTCONNECTION);

		if (this->cs->savegame_mutex != NULL) this->cs->savegame_mutex->BeginCritical();

		/* Make sure the last packet is flushed. */
		this->AppendQueue();

		/* Add a packet stating that this is the end to the queue. */
		this->current = new Packet(PACKET_SERVER_MAP_DONE);
		this->AppendQueue();

		/* Fast-track the size to the client. */
		Packet *p = new Packet(PACKET_SERVER_MAP_SIZE);
		p->Send_uint32((uint32)this->total_size);
		this->cs->NetworkTCPSocketHandler::SendPacket(p);

		if (this->cs->savegame_mutex != NULL) this->cs->savegame_mutex->EndCritical();
	}
};


/**
 * Create a new socket for the server side of the game connection.
 * @param s The socket to connect with.
 */
ServerNetworkGameSocketHandler::ServerNetworkGameSocketHandler(SOCKET s) : NetworkGameSocketHandler(s)
{
	this->status = STATUS_INACTIVE;
	this->client_id = _network_client_id++;
	this->receive_limit = _settings_client.network.bytes_per_frame_burst;

	/* The Socket and Info pools need to be the same in size. After all,
	 * each Socket will be associated with at most one Info object. As
	 * such if the Socket was allocated the Info object can as well. */
	assert_compile(NetworkClientSocketPool::MAX_SIZE == NetworkClientInfoPool::MAX_SIZE);
}

/**
 * Clear everything related to this client.
 */
ServerNetworkGameSocketHandler::~ServerNetworkGameSocketHandler()
{
	if (_redirect_console_to_client == this->client_id) _redirect_console_to_client = INVALID_CLIENT_ID;
	OrderBackup::ResetUser(this->client_id);

	if (this->savegame_mutex != NULL) this->savegame_mutex->BeginCritical();
	if (this->savegame != NULL) this->savegame->cs = NULL;
	if (this->savegame_mutex != NULL) this->savegame_mutex->EndCritical();

	/* Make sure the saving is completely cancelled.
	 * Yes, we need to handle the save finish as well
	 * as the next connection in this "loop" might
	 * just be requesting the map and such. */
	WaitTillSaved();
	ProcessAsyncSaveFinish();

	while (this->savegame_packets != NULL) {
		Packet *p = this->savegame_packets->next;
		delete this->savegame_packets;
		this->savegame_packets = p;
	}

	delete this->savegame_mutex;
}

Packet *ServerNetworkGameSocketHandler::ReceivePacket()
{
	/* Only allow receiving when we have some buffer free; this value
	 * can go negative, but eventually it will become positive again. */
	if (this->receive_limit <= 0) return NULL;

	/* We can receive a packet, so try that and if needed account for
	 * the amount of received data. */
	Packet *p = this->NetworkTCPSocketHandler::ReceivePacket();
	if (p != NULL) this->receive_limit -= p->size;
	return p;
}

void ServerNetworkGameSocketHandler::SendPacket(Packet *packet)
{
	if (this->savegame_mutex != NULL) this->savegame_mutex->BeginCritical();
	this->NetworkTCPSocketHandler::SendPacket(packet);
	if (this->savegame_mutex != NULL) this->savegame_mutex->EndCritical();
}

NetworkRecvStatus ServerNetworkGameSocketHandler::CloseConnection(NetworkRecvStatus status)
{
	assert(status != NETWORK_RECV_STATUS_OKAY);
	/*
	 * Sending a message just before leaving the game calls cs->SendPackets.
	 * This might invoke this function, which means that when we close the
	 * connection after cs->SendPackets we will close an already closed
	 * connection. This handles that case gracefully without having to make
	 * that code any more complex or more aware of the validity of the socket.
	 */
	if (this->sock == INVALID_SOCKET) return status;

	if (status != NETWORK_RECV_STATUS_CONN_LOST && !this->HasClientQuit() && this->status >= STATUS_AUTHORIZED) {
		/* We did not receive a leave message from this client... */
		char client_name[NETWORK_CLIENT_NAME_LENGTH];
		NetworkClientSocket *new_cs;

		this->GetClientName(client_name, sizeof(client_name));

		NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, NULL, STR_NETWORK_ERROR_CLIENT_CONNECTION_LOST);

		/* Inform other clients of this... strange leaving ;) */
		FOR_ALL_CLIENT_SOCKETS(new_cs) {
			if (new_cs->status > STATUS_AUTHORIZED && this != new_cs) {
				new_cs->SendErrorQuit(this->client_id, NETWORK_ERROR_CONNECTION_LOST);
			}
		}
	}

	NetworkAdminClientError(this->client_id, NETWORK_ERROR_CONNECTION_LOST);
	DEBUG(net, 1, "Closed client connection %d", this->client_id);

	/* We just lost one client :( */
	if (this->status >= STATUS_AUTHORIZED) _network_game_info.clients_on--;
	extern byte _network_clients_connected;
	_network_clients_connected--;

	DeleteWindowById(WC_CLIENT_LIST_POPUP, this->client_id);
	SetWindowDirty(WC_CLIENT_LIST, 0);

	this->SendPackets(true);

	delete this->GetInfo();
	delete this;

	return status;
}

/**
 * Whether an connection is allowed or not at this moment.
 * @return true if the connection is allowed.
 */
/* static */ bool ServerNetworkGameSocketHandler::AllowConnection()
{
	extern byte _network_clients_connected;
	bool accept = _network_clients_connected < MAX_CLIENTS && _network_game_info.clients_on < _settings_client.network.max_clients;

	/* We can't go over the MAX_CLIENTS limit here. However, the
	 * pool must have place for all clients and ourself. */
	assert_compile(NetworkClientSocketPool::MAX_SIZE == MAX_CLIENTS + 1);
	assert(!accept || ServerNetworkGameSocketHandler::CanAllocateItem());
	return accept;
}

/** Send the packets for the server sockets. */
/* static */ void ServerNetworkGameSocketHandler::Send()
{
	NetworkClientSocket *cs;
	FOR_ALL_CLIENT_SOCKETS(cs) {
		if (cs->writable) {
			if (cs->SendPackets() != SPS_CLOSED && cs->status == STATUS_MAP) {
				/* This client is in the middle of a map-send, call the function for that */
				cs->SendMap();
			}
		}
	}
}

static void NetworkHandleCommandQueue(NetworkClientSocket *cs);

/***********
 * Sending functions
 *   DEF_SERVER_SEND_COMMAND has parameter: NetworkClientSocket *cs
 ************/

/**
 * Send the client information about a client.
 * @param ci The client to send information about.
 */
NetworkRecvStatus ServerNetworkGameSocketHandler::SendClientInfo(NetworkClientInfo *ci)
{
	if (ci->client_id != INVALID_CLIENT_ID) {
		Packet *p = new Packet(PACKET_SERVER_CLIENT_INFO);
		p->Send_uint32(ci->client_id);
		p->Send_uint8 (ci->client_playas);
		p->Send_string(ci->client_name);

		this->SendPacket(p);
	}
	return NETWORK_RECV_STATUS_OKAY;
}

/** Send the client information about the companies. */
NetworkRecvStatus ServerNetworkGameSocketHandler::SendCompanyInfo()
{
	/* Fetch the latest version of the stats */
	NetworkCompanyStats company_stats[MAX_COMPANIES];
	NetworkPopulateCompanyStats(company_stats);

	/* Make a list of all clients per company */
	char clients[MAX_COMPANIES][NETWORK_CLIENTS_LENGTH];
	NetworkClientSocket *csi;
	memset(clients, 0, sizeof(clients));

	/* Add the local player (if not dedicated) */
	const NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER);
	if (ci != NULL && Company::IsValidID(ci->client_playas)) {
		strecpy(clients[ci->client_playas], ci->client_name, lastof(clients[ci->client_playas]));
	}

	FOR_ALL_CLIENT_SOCKETS(csi) {
		char client_name[NETWORK_CLIENT_NAME_LENGTH];

		((ServerNetworkGameSocketHandler*)csi)->GetClientName(client_name, sizeof(client_name));

		ci = csi->GetInfo();
		if (ci != NULL && Company::IsValidID(ci->client_playas)) {
			if (!StrEmpty(clients[ci->client_playas])) {
				strecat(clients[ci->client_playas], ", ", lastof(clients[ci->client_playas]));
			}

			strecat(clients[ci->client_playas], client_name, lastof(clients[ci->client_playas]));
		}
	}

	/* Now send the data */

	Company *company;
	Packet *p;

	FOR_ALL_COMPANIES(company) {
		p = new Packet(PACKET_SERVER_COMPANY_INFO);

		p->Send_uint8 (NETWORK_COMPANY_INFO_VERSION);
		p->Send_bool  (true);
		this->SendCompanyInformation(p, company, &company_stats[company->index]);

		if (StrEmpty(clients[company->index])) {
			p->Send_string("<none>");
		} else {
			p->Send_string(clients[company->index]);
		}

		this->SendPacket(p);
	}

	p = new Packet(PACKET_SERVER_COMPANY_INFO);

	p->Send_uint8 (NETWORK_COMPANY_INFO_VERSION);
	p->Send_bool  (false);

	this->SendPacket(p);
	return NETWORK_RECV_STATUS_OKAY;
}

/**
 * Send an error to the client, and close its connection.
 * @param error The error to disconnect for.
 */
NetworkRecvStatus ServerNetworkGameSocketHandler::SendError(NetworkErrorCode error)
{
	char str[100];
	Packet *p = new Packet(PACKET_SERVER_ERROR);

	p->Send_uint8(error);
	this->SendPacket(p);

	StringID strid = GetNetworkErrorMsg(error);
	GetString(str, strid, lastof(str));

	/* Only send when the current client was in game */
	if (this->status > STATUS_AUTHORIZED) {
		NetworkClientSocket *new_cs;
		char client_name[NETWORK_CLIENT_NAME_LENGTH];

		this->GetClientName(client_name, sizeof(client_name));

		DEBUG(net, 1, "'%s' made an error and has been disconnected. Reason: '%s'", client_name, str);

		NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, NULL, strid);

		FOR_ALL_CLIENT_SOCKETS(new_cs) {
			if (new_cs->status > STATUS_AUTHORIZED && new_cs != this) {
				/* Some errors we filter to a more general error. Clients don't have to know the real
				 *  reason a joining failed. */
				if (error == NETWORK_ERROR_NOT_AUTHORIZED || error == NETWORK_ERROR_NOT_EXPECTED || error == NETWORK_ERROR_WRONG_REVISION) {
					error = NETWORK_ERROR_ILLEGAL_PACKET;
				}
				new_cs->SendErrorQuit(this->client_id, error);
			}
		}

		NetworkAdminClientError(this->client_id, error);
	} else {
		DEBUG(net, 1, "Client %d made an error and has been disconnected. Reason: '%s'", this->client_id, str);
	}

	/* The client made a mistake, so drop his connection now! */
	return this->CloseConnection(NETWORK_RECV_STATUS_SERVER_ERROR);
}

/** Send the check for the NewGRFs. */
NetworkRecvStatus ServerNetworkGameSocketHandler::SendNewGRFCheck()
{
	Packet *p = new Packet(PACKET_SERVER_CHECK_NEWGRFS);
	const GRFConfig *c;
	uint grf_count = 0;

	for (c = _grfconfig; c != NULL; c = c->next) {
		if (!HasBit(c->flags, GCF_STATIC)) grf_count++;
	}

	p->Send_uint8 (grf_count);
	for (c = _grfconfig; c != NULL; c = c->next) {
		if (!HasBit(c->flags, GCF_STATIC)) this->SendGRFIdentifier(p, &c->ident);
	}

	this->SendPacket(p);
	return NETWORK_RECV_STATUS_OKAY;
}

/** Request the game password. */
NetworkRecvStatus ServerNetworkGameSocketHandler::SendNeedGamePassword()
{
	/* Invalid packet when status is STATUS_AUTH_GAME or higher */
	if (this->status >= STATUS_AUTH_GAME) return this->CloseConnection(NETWORK_RECV_STATUS_MALFORMED_PACKET);

	this->status = STATUS_AUTH_GAME;

	Packet *p = new Packet(PACKET_SERVER_NEED_GAME_PASSWORD);
	this->SendPacket(p);
	return NETWORK_RECV_STATUS_OKAY;
}

/** Request the company password. */
NetworkRecvStatus ServerNetworkGameSocketHandler::SendNeedCompanyPassword()
{
	/* Invalid packet when status is STATUS_AUTH_COMPANY or higher */
	if (this->status >= STATUS_AUTH_COMPANY) return this->CloseConnection(NETWORK_RECV_STATUS_MALFORMED_PACKET);

	this->status = STATUS_AUTH_COMPANY;

	Packet *p = new Packet(PACKET_SERVER_NEED_COMPANY_PASSWORD);
	p->Send_uint32(_settings_game.game_creation.generation_seed);
	p->Send_string(_settings_client.network.network_id);
	this->SendPacket(p);
	return NETWORK_RECV_STATUS_OKAY;
}

/** Send the client a welcome message with some basic information. */
NetworkRecvStatus ServerNetworkGameSocketHandler::SendWelcome()
{
	Packet *p;
	NetworkClientSocket *new_cs;

	/* Invalid packet when status is AUTH or higher */
	if (this->status >= STATUS_AUTHORIZED) return this->CloseConnection(NETWORK_RECV_STATUS_MALFORMED_PACKET);

	this->status = STATUS_AUTHORIZED;
	_network_game_info.clients_on++;

	p = new Packet(PACKET_SERVER_WELCOME);
	p->Send_uint32(this->client_id);
	p->Send_uint32(_settings_game.game_creation.generation_seed);
	p->Send_string(_settings_client.network.network_id);
	this->SendPacket(p);

	/* Transmit info about all the active clients */
	FOR_ALL_CLIENT_SOCKETS(new_cs) {
		if (new_cs != this && new_cs->status > STATUS_AUTHORIZED) {
			this->SendClientInfo(new_cs->GetInfo());
		}
	}
	/* Also send the info of the server */
	return this->SendClientInfo(NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER));
}

/** Tell the client that its put in a waiting queue. */
NetworkRecvStatus ServerNetworkGameSocketHandler::SendWait()
{
	int waiting = 0;
	NetworkClientSocket *new_cs;
	Packet *p;

	/* Count how many clients are waiting in the queue, in front of you! */
	FOR_ALL_CLIENT_SOCKETS(new_cs) {
		if (new_cs->status != STATUS_MAP_WAIT) continue;
		if (new_cs->GetInfo()->join_date < this->GetInfo()->join_date || (new_cs->GetInfo()->join_date == this->GetInfo()->join_date && new_cs->client_id < this->client_id)) waiting++;
	}

	p = new Packet(PACKET_SERVER_WAIT);
	p->Send_uint8(waiting);
	this->SendPacket(p);
	return NETWORK_RECV_STATUS_OKAY;
}

/** This sends the map to the client */
NetworkRecvStatus ServerNetworkGameSocketHandler::SendMap()
{
	static uint sent_packets; // How many packets we did send succecfully last time

	if (this->status < STATUS_AUTHORIZED) {
		/* Illegal call, return error and ignore the packet */
		return this->SendError(NETWORK_ERROR_NOT_AUTHORIZED);
	}

	if (this->status == STATUS_AUTHORIZED) {
		this->savegame = new PacketWriter(this);

		/* Now send the _frame_counter and how many packets are coming */
		Packet *p = new Packet(PACKET_SERVER_MAP_BEGIN);
		p->Send_uint32(_frame_counter);
		this->SendPacket(p);

		NetworkSyncCommandQueue(this);
		this->status = STATUS_MAP;
		/* Mark the start of download */
		this->last_frame = _frame_counter;
		this->last_frame_server = _frame_counter;

		sent_packets = 4; // We start with trying 4 packets

		/* Make a dump of the current game */
		if (SaveWithFilter(this->savegame, true) != SL_OK) usererror("network savedump failed");
	}

	if (this->status == STATUS_MAP) {
		if (this->savegame_mutex != NULL) this->savegame_mutex->BeginCritical();

		bool last_packet = false;

		for (uint i = 0; i < sent_packets && this->savegame_packets != NULL; i++) {
			Packet *p = this->savegame_packets;
			last_packet = p->buffer[2] == PACKET_SERVER_MAP_DONE;

			/* Remove the packet from the savegame queue and put it in the real queue. */
			this->savegame_packets = p->next;
			p->next = NULL;
			this->NetworkTCPSocketHandler::SendPacket(p);

			if (last_packet) {
				/* There is no more data, so break the for */
				break;
			}
		}

		if (this->savegame_mutex != NULL) this->savegame_mutex->EndCritical();

		if (last_packet) {
			/* Done reading, make sure saving is done as well */
			WaitTillSaved();

			/* Set the status to DONE_MAP, no we will wait for the client
			 *  to send it is ready (maybe that happens like never ;)) */
			this->status = STATUS_DONE_MAP;

			/* Find the best candidate for joining, i.e. the first joiner. */
			NetworkClientSocket *new_cs;
			NetworkClientSocket *best = NULL;
			FOR_ALL_CLIENT_SOCKETS(new_cs) {
				if (new_cs->status == STATUS_MAP_WAIT) {
					if (best == NULL || best->GetInfo()->join_date > new_cs->GetInfo()->join_date || (best->GetInfo()->join_date == new_cs->GetInfo()->join_date && best->client_id > new_cs->client_id)) {
						best = new_cs;
					}
				}
			}

			/* Is there someone else to join? */
			if (best != NULL) {
				/* Let the first start joining. */
				best->status = STATUS_AUTHORIZED;
				best->SendMap();

				/* And update the rest. */
				FOR_ALL_CLIENT_SOCKETS(new_cs) {
					if (new_cs->status == STATUS_MAP_WAIT) new_cs->SendWait();
				}
			}
		}

		switch (this->SendPackets()) {
			case SPS_CLOSED:
				return NETWORK_RECV_STATUS_CONN_LOST;

			case SPS_ALL_SENT:
				/* All are sent, increase the sent_packets */
				if (this->savegame_packets != NULL) sent_packets *= 2;
				break;

			case SPS_PARTLY_SENT:
				/* Only a part is sent; leave the transmission state. */
				break;

			case SPS_NONE_SENT:
				/* Not everything is sent, decrease the sent_packets */
				if (sent_packets > 1) sent_packets /= 2;
				break;
		}
	}
	return NETWORK_RECV_STATUS_OKAY;
}

/**
 * Tell that a client joined.
 * @param client_id The client that joined.
 */
NetworkRecvStatus ServerNetworkGameSocketHandler::SendJoin(ClientID client_id)
{
	Packet *p = new Packet(PACKET_SERVER_JOIN);

	p->Send_uint32(client_id);

	this->SendPacket(p);
	return NETWORK_RECV_STATUS_OKAY;
}

/** Tell the client that they may run to a particular frame. */
NetworkRecvStatus ServerNetworkGameSocketHandler::SendFrame()
{
	Packet *p = new Packet(PACKET_SERVER_FRAME);
	p->Send_uint32(_frame_counter);
	p->Send_uint32(_frame_counter_max);
#ifdef ENABLE_NETWORK_SYNC_EVERY_FRAME
	p->Send_uint32(_sync_seed_1);
#ifdef NETWORK_SEND_DOUBLE_SEED
	p->Send_uint32(_sync_seed_2);
#endif
#endif

	/* If token equals 0, we need to make a new token and send that. */
	if (this->last_token == 0) {
		this->last_token = InteractiveRandomRange(UINT8_MAX - 1) + 1;
		p->Send_uint8(this->last_token);
	}

	this->SendPacket(p);
	return NETWORK_RECV_STATUS_OKAY;
}

/** Request the client to sync. */
NetworkRecvStatus ServerNetworkGameSocketHandler::SendSync()
{
	Packet *p = new Packet(PACKET_SERVER_SYNC);
	p->Send_uint32(_frame_counter);
	p->Send_uint32(_sync_seed_1);

#ifdef NETWORK_SEND_DOUBLE_SEED
	p->Send_uint32(_sync_seed_2);
#endif
	this->SendPacket(p);
	return NETWORK_RECV_STATUS_OKAY;
}

/**
 * Send a command to the client to execute.
 * @param cp The command to send.
 */
NetworkRecvStatus ServerNetworkGameSocketHandler::SendCommand(const CommandPacket *cp)
{
	Packet *p = new Packet(PACKET_SERVER_COMMAND);

	this->NetworkGameSocketHandler::SendCommand(p, cp);
	p->Send_uint32(cp->frame);
	p->Send_bool  (cp->my_cmd);

	this->SendPacket(p);
	return NETWORK_RECV_STATUS_OKAY;
}

/**
 * Send a chat message.
 * @param action The action associated with the message.
 * @param client_id The origin of the chat message.
 * @param self_send Whether we did send the message.
 * @param msg The actual message.
 * @param data Arbitrary extra data.
 */
NetworkRecvStatus ServerNetworkGameSocketHandler::SendChat(NetworkAction action, ClientID client_id, bool self_send, const char *msg, int64 data)
{
	if (this->status != STATUS_ACTIVE) return NETWORK_RECV_STATUS_OKAY;

	Packet *p = new Packet(PACKET_SERVER_CHAT);

	p->Send_uint8 (action);
	p->Send_uint32(client_id);
	p->Send_bool  (self_send);
	p->Send_string(msg);
	p->Send_uint64(data);

	this->SendPacket(p);
	return NETWORK_RECV_STATUS_OKAY;
}

/**
 * Tell the client another client quit with an error.
 * @param client_id The client that quit.
 * @param errorno The reason the client quit.
 */
NetworkRecvStatus ServerNetworkGameSocketHandler::SendErrorQuit(ClientID client_id, NetworkErrorCode errorno)
{
	Packet *p = new Packet(PACKET_SERVER_ERROR_QUIT);

	p->Send_uint32(client_id);
	p->Send_uint8 (errorno);

	this->SendPacket(p);
	return NETWORK_RECV_STATUS_OKAY;
}

/**
 * Tell the client another client quit.
 * @param client_id The client that quit.
 */
NetworkRecvStatus ServerNetworkGameSocketHandler::SendQuit(ClientID client_id)
{
	Packet *p = new Packet(PACKET_SERVER_QUIT);

	p->Send_uint32(client_id);

	this->SendPacket(p);
	return NETWORK_RECV_STATUS_OKAY;
}

/** Tell the client we're shutting down. */
NetworkRecvStatus ServerNetworkGameSocketHandler::SendShutdown()
{
	Packet *p = new Packet(PACKET_SERVER_SHUTDOWN);
	this->SendPacket(p);
	return NETWORK_RECV_STATUS_OKAY;
}

/** Tell the client we're starting a new game. */
NetworkRecvStatus ServerNetworkGameSocketHandler::SendNewGame()
{
	Packet *p = new Packet(PACKET_SERVER_NEWGAME);
	this->SendPacket(p);
	return NETWORK_RECV_STATUS_OKAY;
}

/**
 * Send the result of a console action.
 * @param colour The colour of the result.
 * @param command The command that was executed.
 */
NetworkRecvStatus ServerNetworkGameSocketHandler::SendRConResult(uint16 colour, const char *command)
{
	Packet *p = new Packet(PACKET_SERVER_RCON);

	p->Send_uint16(colour);
	p->Send_string(command);
	this->SendPacket(p);
	return NETWORK_RECV_STATUS_OKAY;
}

/**
 * Tell that a client moved to another company.
 * @param client_id The client that moved.
 * @param company_id The company the client moved to.
 */
NetworkRecvStatus ServerNetworkGameSocketHandler::SendMove(ClientID client_id, CompanyID company_id)
{
	Packet *p = new Packet(PACKET_SERVER_MOVE);

	p->Send_uint32(client_id);
	p->Send_uint8(company_id);
	this->SendPacket(p);
	return NETWORK_RECV_STATUS_OKAY;
}

/** Send an update about the company password states. */
NetworkRecvStatus ServerNetworkGameSocketHandler::SendCompanyUpdate()
{
	Packet *p = new Packet(PACKET_SERVER_COMPANY_UPDATE);

	p->Send_uint16(_network_company_passworded);
	this->SendPacket(p);
	return NETWORK_RECV_STATUS_OKAY;
}

/** Send an update about the max company/spectator counts. */
NetworkRecvStatus ServerNetworkGameSocketHandler::SendConfigUpdate()
{
	Packet *p = new Packet(PACKET_SERVER_CONFIG_UPDATE);

	p->Send_uint8(_settings_client.network.max_companies);
	p->Send_uint8(_settings_client.network.max_spectators);
	this->SendPacket(p);
	return NETWORK_RECV_STATUS_OKAY;
}

/***********
 * Receiving functions
 *   DEF_SERVER_RECEIVE_COMMAND has parameter: NetworkClientSocket *cs, Packet *p
 ************/

NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_COMPANY_INFO(Packet *p)
{
	return this->SendCompanyInfo();
}

NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_NEWGRFS_CHECKED(Packet *p)
{
	if (this->status != STATUS_NEWGRFS_CHECK) {
		/* Illegal call, return error and ignore the packet */
		return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
	}

	NetworkClientInfo *ci = this->GetInfo();

	/* We now want a password from the client else we do not allow him in! */
	if (!StrEmpty(_settings_client.network.server_password)) {
		return this->SendNeedGamePassword();
	}

	if (Company::IsValidID(ci->client_playas) && !StrEmpty(_network_company_states[ci->client_playas].password)) {
		return this->SendNeedCompanyPassword();
	}

	return this->SendWelcome();
}

NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_JOIN(Packet *p)
{
	if (this->status != STATUS_INACTIVE) {
		/* Illegal call, return error and ignore the packet */
		return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
	}

	char name[NETWORK_CLIENT_NAME_LENGTH];
	CompanyID playas;
	NetworkLanguage client_lang;
	char client_revision[NETWORK_REVISION_LENGTH];

	p->Recv_string(client_revision, sizeof(client_revision));
	uint32 newgrf_version = p->Recv_uint32();

	/* Check if the client has revision control enabled */
	if (!IsNetworkCompatibleVersion(client_revision) || _openttd_newgrf_version != newgrf_version) {
		/* Different revisions!! */
		return this->SendError(NETWORK_ERROR_WRONG_REVISION);
	}

	p->Recv_string(name, sizeof(name));
	playas = (Owner)p->Recv_uint8();
	client_lang = (NetworkLanguage)p->Recv_uint8();

	if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CONN_LOST;

	/* join another company does not affect these values */
	switch (playas) {
		case COMPANY_NEW_COMPANY: // New company
			if (Company::GetNumItems() >= _settings_client.network.max_companies) {
				return this->SendError(NETWORK_ERROR_FULL);
			}
			break;
		case COMPANY_SPECTATOR: // Spectator
			if (NetworkSpectatorCount() >= _settings_client.network.max_spectators) {
				return this->SendError(NETWORK_ERROR_FULL);
			}
			break;
		default: // Join another company (companies 1-8 (index 0-7))
			if (!Company::IsValidHumanID(playas)) {
				return this->SendError(NETWORK_ERROR_COMPANY_MISMATCH);
			}
			break;
	}

	/* We need a valid name.. make it Player */
	if (StrEmpty(name)) strecpy(name, "Player", lastof(name));

	if (!NetworkFindName(name)) { // Change name if duplicate
		/* We could not create a name for this client */
		return this->SendError(NETWORK_ERROR_NAME_IN_USE);
	}

	assert(NetworkClientInfo::CanAllocateItem());
	NetworkClientInfo *ci = new NetworkClientInfo(this->client_id);
	this->SetInfo(ci);
	ci->join_date = _date;
	strecpy(ci->client_name, name, lastof(ci->client_name));
	ci->client_playas = playas;
	ci->client_lang = client_lang;
	DEBUG(desync, 1, "client: %08x; %02x; %02x; %04x", _date, _date_fract, (int)ci->client_playas, ci->index);

	/* Make sure companies to which people try to join are not autocleaned */
	if (Company::IsValidID(playas)) _network_company_states[playas].months_empty = 0;

	this->status = STATUS_NEWGRFS_CHECK;

	if (_grfconfig == NULL) {
		/* Behave as if we received PACKET_CLIENT_NEWGRFS_CHECKED */
		return this->Receive_CLIENT_NEWGRFS_CHECKED(NULL);
	}

	return this->SendNewGRFCheck();
}

NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_GAME_PASSWORD(Packet *p)
{
	if (this->status != STATUS_AUTH_GAME) {
		return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
	}

	char password[NETWORK_PASSWORD_LENGTH];
	p->Recv_string(password, sizeof(password));

	/* Check game password. Allow joining if we cleared the password meanwhile */
	if (!StrEmpty(_settings_client.network.server_password) &&
			strcmp(password, _settings_client.network.server_password) != 0) {
		/* Password is invalid */
		return this->SendError(NETWORK_ERROR_WRONG_PASSWORD);
	}

	const NetworkClientInfo *ci = this->GetInfo();
	if (Company::IsValidID(ci->client_playas) && !StrEmpty(_network_company_states[ci->client_playas].password)) {
		return this->SendNeedCompanyPassword();
	}

	/* Valid password, allow user */
	return this->SendWelcome();
}

NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_COMPANY_PASSWORD(Packet *p)
{
	if (this->status != STATUS_AUTH_COMPANY) {
		return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
	}

	char password[NETWORK_PASSWORD_LENGTH];
	p->Recv_string(password, sizeof(password));

	/* Check company password. Allow joining if we cleared the password meanwhile.
	 * Also, check the company is still valid - client could be moved to spectators
	 * in the middle of the authorization process */
	CompanyID playas = this->GetInfo()->client_playas;
	if (Company::IsValidID(playas) && !StrEmpty(_network_company_states[playas].password) &&
			strcmp(password, _network_company_states[playas].password) != 0) {
		/* Password is invalid */
		return this->SendError(NETWORK_ERROR_WRONG_PASSWORD);
	}

	return this->SendWelcome();
}

NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_GETMAP(Packet *p)
{
	NetworkClientSocket *new_cs;
	/* The client was never joined.. so this is impossible, right?
	 *  Ignore the packet, give the client a warning, and close his connection */
	if (this->status < STATUS_AUTHORIZED || this->HasClientQuit()) {
		return this->SendError(NETWORK_ERROR_NOT_AUTHORIZED);
	}

	/* Check if someone else is receiving the map */
	FOR_ALL_CLIENT_SOCKETS(new_cs) {
		if (new_cs->status == STATUS_MAP) {
			/* Tell the new client to wait */
			this->status = STATUS_MAP_WAIT;
			return this->SendWait();
		}
	}

	/* We receive a request to upload the map.. give it to the client! */
	return this->SendMap();
}

NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_MAP_OK(Packet *p)
{
	/* Client has the map, now start syncing */
	if (this->status == STATUS_DONE_MAP && !this->HasClientQuit()) {
		char client_name[NETWORK_CLIENT_NAME_LENGTH];
		NetworkClientSocket *new_cs;

		this->GetClientName(client_name, sizeof(client_name));

		NetworkTextMessage(NETWORK_ACTION_JOIN, CC_DEFAULT, false, client_name, NULL, this->client_id);

		/* Mark the client as pre-active, and wait for an ACK
		 *  so we know he is done loading and in sync with us */
		this->status = STATUS_PRE_ACTIVE;
		NetworkHandleCommandQueue(this);
		this->SendFrame();
		this->SendSync();

		/* This is the frame the client receives
		 *  we need it later on to make sure the client is not too slow */
		this->last_frame = _frame_counter;
		this->last_frame_server = _frame_counter;

		FOR_ALL_CLIENT_SOCKETS(new_cs) {
			if (new_cs->status > STATUS_AUTHORIZED) {
				new_cs->SendClientInfo(this->GetInfo());
				new_cs->SendJoin(this->client_id);
			}
		}

		NetworkAdminClientInfo(this, true);

		/* also update the new client with our max values */
		this->SendConfigUpdate();

		/* quickly update the syncing client with company details */
		return this->SendCompanyUpdate();
	}

	/* Wrong status for this packet, give a warning to client, and close connection */
	return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
}

/**
 * The client has done a command and wants us to handle it
 * @param p the packet in which the command was sent
 */
NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_COMMAND(Packet *p)
{
	/* The client was never joined.. so this is impossible, right?
	 *  Ignore the packet, give the client a warning, and close his connection */
	if (this->status < STATUS_DONE_MAP || this->HasClientQuit()) {
		return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
	}

	if (this->incoming_queue.Count() >= _settings_client.network.max_commands_in_queue) {
		return this->SendError(NETWORK_ERROR_TOO_MANY_COMMANDS);
	}

	CommandPacket cp;
	const char *err = this->ReceiveCommand(p, &cp);

	if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CONN_LOST;

	NetworkClientInfo *ci = this->GetInfo();

	if (err != NULL) {
		IConsolePrintF(CC_ERROR, "WARNING: %s from client %d (IP: %s).", err, ci->client_id, this->GetClientIP());
		return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
	}


	if ((GetCommandFlags(cp.cmd) & CMD_SERVER) && ci->client_id != CLIENT_ID_SERVER) {
		IConsolePrintF(CC_ERROR, "WARNING: server only command from: client %d (IP: %s), kicking...", ci->client_id, this->GetClientIP());
		return this->SendError(NETWORK_ERROR_KICKED);
	}

	if ((GetCommandFlags(cp.cmd) & CMD_SPECTATOR) == 0 && !Company::IsValidID(cp.company) && ci->client_id != CLIENT_ID_SERVER) {
		IConsolePrintF(CC_ERROR, "WARNING: spectator issueing command from client %d (IP: %s), kicking...", ci->client_id, this->GetClientIP());
		return this->SendError(NETWORK_ERROR_KICKED);
	}

	/**
	 * Only CMD_COMPANY_CTRL is always allowed, for the rest, playas needs
	 * to match the company in the packet. If it doesn't, the client has done
	 * something pretty naughty (or a bug), and will be kicked
	 */
	if (!(cp.cmd == CMD_COMPANY_CTRL && cp.p1 == 0 && ci->client_playas == COMPANY_NEW_COMPANY) && ci->client_playas != cp.company) {
		IConsolePrintF(CC_ERROR, "WARNING: client %d (IP: %s) tried to execute a command as company %d, kicking...",
		               ci->client_playas + 1, this->GetClientIP(), cp.company + 1);
		return this->SendError(NETWORK_ERROR_COMPANY_MISMATCH);
	}

	if (cp.cmd == CMD_COMPANY_CTRL) {
		if (cp.p1 != 0 || cp.company != COMPANY_SPECTATOR) {
			return this->SendError(NETWORK_ERROR_CHEATER);
		}

		/* Check if we are full - else it's possible for spectators to send a CMD_COMPANY_CTRL and the company is created regardless of max_companies! */
		if (Company::GetNumItems() >= _settings_client.network.max_companies) {
			NetworkServerSendChat(NETWORK_ACTION_SERVER_MESSAGE, DESTTYPE_CLIENT, ci->client_id, "cannot create new company, server full", CLIENT_ID_SERVER);
			return NETWORK_RECV_STATUS_OKAY;
		}
	}

	if (GetCommandFlags(cp.cmd) & CMD_CLIENT_ID) cp.p2 = this->client_id;

	this->incoming_queue.Append(&cp);
	return NETWORK_RECV_STATUS_OKAY;
}

NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_ERROR(Packet *p)
{
	/* This packets means a client noticed an error and is reporting this
	 *  to us. Display the error and report it to the other clients */
	NetworkClientSocket *new_cs;
	char str[100];
	char client_name[NETWORK_CLIENT_NAME_LENGTH];
	NetworkErrorCode errorno = (NetworkErrorCode)p->Recv_uint8();

	/* The client was never joined.. thank the client for the packet, but ignore it */
	if (this->status < STATUS_DONE_MAP || this->HasClientQuit()) {
		return this->CloseConnection(NETWORK_RECV_STATUS_CONN_LOST);
	}

	this->GetClientName(client_name, sizeof(client_name));

	StringID strid = GetNetworkErrorMsg(errorno);
	GetString(str, strid, lastof(str));

	DEBUG(net, 2, "'%s' reported an error and is closing its connection (%s)", client_name, str);

	NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, NULL, strid);

	FOR_ALL_CLIENT_SOCKETS(new_cs) {
		if (new_cs->status > STATUS_AUTHORIZED) {
			new_cs->SendErrorQuit(this->client_id, errorno);
		}
	}

	NetworkAdminClientError(this->client_id, errorno);

	return this->CloseConnection(NETWORK_RECV_STATUS_CONN_LOST);
}

NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_QUIT(Packet *p)
{
	/* The client wants to leave. Display this and report it to the other
	 *  clients. */
	NetworkClientSocket *new_cs;
	char client_name[NETWORK_CLIENT_NAME_LENGTH];

	/* The client was never joined.. thank the client for the packet, but ignore it */
	if (this->status < STATUS_DONE_MAP || this->HasClientQuit()) {
		return this->CloseConnection(NETWORK_RECV_STATUS_CONN_LOST);
	}

	this->GetClientName(client_name, sizeof(client_name));

	NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, NULL, STR_NETWORK_MESSAGE_CLIENT_LEAVING);

	FOR_ALL_CLIENT_SOCKETS(new_cs) {
		if (new_cs->status > STATUS_AUTHORIZED && new_cs != this) {
			new_cs->SendQuit(this->client_id);
		}
	}

	NetworkAdminClientQuit(this->client_id);

	return this->CloseConnection(NETWORK_RECV_STATUS_CONN_LOST);
}

NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_ACK(Packet *p)
{
	if (this->status < STATUS_AUTHORIZED) {
		/* Illegal call, return error and ignore the packet */
		return this->SendError(NETWORK_ERROR_NOT_AUTHORIZED);
	}

	uint32 frame = p->Recv_uint32();

	/* The client is trying to catch up with the server */
	if (this->status == STATUS_PRE_ACTIVE) {
		/* The client is not yet catched up? */
		if (frame + DAY_TICKS < _frame_counter) return NETWORK_RECV_STATUS_OKAY;

		/* Now he is! Unpause the game */
		this->status = STATUS_ACTIVE;
		this->last_token_frame = _frame_counter;

		/* Execute script for, e.g. MOTD */
		IConsoleCmdExec("exec scripts/on_server_connect.scr 0");
	}

	/* Get, and validate the token. */
	uint8 token = p->Recv_uint8();
	if (token == this->last_token) {
		/* We differentiate between last_token_frame and last_frame so the lag
		 * test uses the actual lag of the client instead of the lag for getting
		 * the token back and forth; after all, the token is only sent every
		 * time we receive a PACKET_CLIENT_ACK, after which we will send a new
		 * token to the client. If the lag would be one day, then we would not
		 * be sending the new token soon enough for the new daily scheduled
		 * PACKET_CLIENT_ACK. This would then register the lag of the client as
		 * two days, even when it's only a single day. */
		this->last_token_frame = _frame_counter;
		/* Request a new token. */
		this->last_token = 0;
	}

	/* The client received the frame, make note of it */
	this->last_frame = frame;
	/* With those 2 values we can calculate the lag realtime */
	this->last_frame_server = _frame_counter;
	return NETWORK_RECV_STATUS_OKAY;
}


/**
 * Send an actual chat message.
 * @param action The action that's performed.
 * @param desttype The type of destination.
 * @param dest The actual destination index.
 * @param msg The actual message.
 * @param from_id The origin of the message.
 * @param data Arbitrary data.
 * @param from_admin Whether the origin is an admin or not.
 */
void NetworkServerSendChat(NetworkAction action, DestType desttype, int dest, const char *msg, ClientID from_id, int64 data, bool from_admin)
{
	NetworkClientSocket *cs;
	const NetworkClientInfo *ci, *ci_own, *ci_to;

	switch (desttype) {
		case DESTTYPE_CLIENT:
			/* Are we sending to the server? */
			if ((ClientID)dest == CLIENT_ID_SERVER) {
				ci = NetworkClientInfo::GetByClientID(from_id);
				/* Display the text locally, and that is it */
				if (ci != NULL) {
					NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), false, ci->client_name, msg, data);

					if (_settings_client.network.server_admin_chat) {
						NetworkAdminChat(action, desttype, from_id, msg, data, from_admin);
					}
				}
			} else {
				/* Else find the client to send the message to */
				FOR_ALL_CLIENT_SOCKETS(cs) {
					if (cs->client_id == (ClientID)dest) {
						cs->SendChat(action, from_id, false, msg, data);
						break;
					}
				}
			}

			/* Display the message locally (so you know you have sent it) */
			if (from_id != (ClientID)dest) {
				if (from_id == CLIENT_ID_SERVER) {
					ci = NetworkClientInfo::GetByClientID(from_id);
					ci_to = NetworkClientInfo::GetByClientID((ClientID)dest);
					if (ci != NULL && ci_to != NULL) {
						NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), true, ci_to->client_name, msg, data);
					}
				} else {
					FOR_ALL_CLIENT_SOCKETS(cs) {
						if (cs->client_id == from_id) {
							cs->SendChat(action, (ClientID)dest, true, msg, data);
							break;
						}
					}
				}
			}
			break;
		case DESTTYPE_TEAM: {
			/* If this is false, the message is already displayed on the client who sent it. */
			bool show_local = true;
			/* Find all clients that belong to this company */
			ci_to = NULL;
			FOR_ALL_CLIENT_SOCKETS(cs) {
				ci = cs->GetInfo();
				if (ci != NULL && ci->client_playas == (CompanyID)dest) {
					cs->SendChat(action, from_id, false, msg, data);
					if (cs->client_id == from_id) show_local = false;
					ci_to = ci; // Remember a client that is in the company for company-name
				}
			}

			/* if the server can read it, let the admin network read it, too. */
			if (_local_company == (CompanyID)dest && _settings_client.network.server_admin_chat) {
				NetworkAdminChat(action, desttype, from_id, msg, data, from_admin);
			}

			ci = NetworkClientInfo::GetByClientID(from_id);
			ci_own = NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER);
			if (ci != NULL && ci_own != NULL && ci_own->client_playas == dest) {
				NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), false, ci->client_name, msg, data);
				if (from_id == CLIENT_ID_SERVER) show_local = false;
				ci_to = ci_own;
			}

			/* There is no such client */
			if (ci_to == NULL) break;

			/* Display the message locally (so you know you have sent it) */
			if (ci != NULL && show_local) {
				if (from_id == CLIENT_ID_SERVER) {
					char name[NETWORK_NAME_LENGTH];
					StringID str = Company::IsValidID(ci_to->client_playas) ? STR_COMPANY_NAME : STR_NETWORK_SPECTATORS;
					SetDParam(0, ci_to->client_playas);
					GetString(name, str, lastof(name));
					NetworkTextMessage(action, GetDrawStringCompanyColour(ci_own->client_playas), true, name, msg, data);
				} else {
					FOR_ALL_CLIENT_SOCKETS(cs) {
						if (cs->client_id == from_id) {
							cs->SendChat(action, ci_to->client_id, true, msg, data);
						}
					}
				}
			}
			break;
		}
		default:
			DEBUG(net, 0, "[server] received unknown chat destination type %d. Doing broadcast instead", desttype);
			/* FALL THROUGH */
		case DESTTYPE_BROADCAST:
			FOR_ALL_CLIENT_SOCKETS(cs) {
				cs->SendChat(action, from_id, false, msg, data);
			}

			NetworkAdminChat(action, desttype, from_id, msg, data, from_admin);

			ci = NetworkClientInfo::GetByClientID(from_id);
			if (ci != NULL) {
				NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), false, ci->client_name, msg, data);
			}
			break;
	}
}

NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_CHAT(Packet *p)
{
	if (this->status < STATUS_AUTHORIZED) {
		/* Illegal call, return error and ignore the packet */
		return this->SendError(NETWORK_ERROR_NOT_AUTHORIZED);
	}

	NetworkAction action = (NetworkAction)p->Recv_uint8();
	DestType desttype = (DestType)p->Recv_uint8();
	int dest = p->Recv_uint32();
	char msg[NETWORK_CHAT_LENGTH];

	p->Recv_string(msg, NETWORK_CHAT_LENGTH);
	int64 data = p->Recv_uint64();

	NetworkClientInfo *ci = this->GetInfo();
	switch (action) {
		case NETWORK_ACTION_GIVE_MONEY:
			if (!Company::IsValidID(ci->client_playas)) break;
			/* FALL THROUGH */
		case NETWORK_ACTION_CHAT:
		case NETWORK_ACTION_CHAT_CLIENT:
		case NETWORK_ACTION_CHAT_COMPANY:
			NetworkServerSendChat(action, desttype, dest, msg, this->client_id, data);
			break;
		default:
			IConsolePrintF(CC_ERROR, "WARNING: invalid chat action from client %d (IP: %s).", ci->client_id, this->GetClientIP());
			return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
	}
	return NETWORK_RECV_STATUS_OKAY;
}

NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_SET_PASSWORD(Packet *p)
{
	if (this->status != STATUS_ACTIVE) {
		/* Illegal call, return error and ignore the packet */
		return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
	}

	char password[NETWORK_PASSWORD_LENGTH];
	const NetworkClientInfo *ci;

	p->Recv_string(password, sizeof(password));
	ci = this->GetInfo();

	NetworkServerSetCompanyPassword(ci->client_playas, password);
	return NETWORK_RECV_STATUS_OKAY;
}

NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_SET_NAME(Packet *p)
{
	if (this->status != STATUS_ACTIVE) {
		/* Illegal call, return error and ignore the packet */
		return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
	}

	char client_name[NETWORK_CLIENT_NAME_LENGTH];
	NetworkClientInfo *ci;

	p->Recv_string(client_name, sizeof(client_name));
	ci = this->GetInfo();

	if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CONN_LOST;

	if (ci != NULL) {
		/* Display change */
		if (NetworkFindName(client_name)) {
			NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, CC_DEFAULT, false, ci->client_name, client_name);
			strecpy(ci->client_name, client_name, lastof(ci->client_name));
			NetworkUpdateClientInfo(ci->client_id);
		}
	}
	return NETWORK_RECV_STATUS_OKAY;
}

NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_RCON(Packet *p)
{
	if (this->status != STATUS_ACTIVE) return this->SendError(NETWORK_ERROR_NOT_EXPECTED);

	char pass[NETWORK_PASSWORD_LENGTH];
	char command[NETWORK_RCONCOMMAND_LENGTH];

	if (StrEmpty(_settings_client.network.rcon_password)) return NETWORK_RECV_STATUS_OKAY;

	p->Recv_string(pass, sizeof(pass));
	p->Recv_string(command, sizeof(command));

	if (strcmp(pass, _settings_client.network.rcon_password) != 0) {
		DEBUG(net, 0, "[rcon] wrong password from client-id %d", this->client_id);
		return NETWORK_RECV_STATUS_OKAY;
	}

	DEBUG(net, 0, "[rcon] client-id %d executed: '%s'", this->client_id, command);

	_redirect_console_to_client = this->client_id;
	IConsoleCmdExec(command);
	_redirect_console_to_client = INVALID_CLIENT_ID;
	return NETWORK_RECV_STATUS_OKAY;
}

NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_MOVE(Packet *p)
{
	if (this->status != STATUS_ACTIVE) return this->SendError(NETWORK_ERROR_NOT_EXPECTED);

	CompanyID company_id = (Owner)p->Recv_uint8();

	/* Check if the company is valid, we don't allow moving to AI companies */
	if (company_id != COMPANY_SPECTATOR && !Company::IsValidHumanID(company_id)) return NETWORK_RECV_STATUS_OKAY;

	/* Check if we require a password for this company */
	if (company_id != COMPANY_SPECTATOR && !StrEmpty(_network_company_states[company_id].password)) {
		/* we need a password from the client - should be in this packet */
		char password[NETWORK_PASSWORD_LENGTH];
		p->Recv_string(password, sizeof(password));

		/* Incorrect password sent, return! */
		if (strcmp(password, _network_company_states[company_id].password) != 0) {
			DEBUG(net, 2, "[move] wrong password from client-id #%d for company #%d", this->client_id, company_id + 1);
			return NETWORK_RECV_STATUS_OKAY;
		}
	}

	/* if we get here we can move the client */
	NetworkServerDoMove(this->client_id, company_id);
	return NETWORK_RECV_STATUS_OKAY;
}

/**
 * Package some generic company information into a packet.
 * @param p       The packet that will contain the data.
 * @param c       The company to put the of into the packet.
 * @param stats   The statistics to put in the packet.
 * @param max_len The maximum length of the company name.
 */
void NetworkSocketHandler::SendCompanyInformation(Packet *p, const Company *c, const NetworkCompanyStats *stats, uint max_len)
{
	/* Grab the company name */
	char company_name[NETWORK_COMPANY_NAME_LENGTH];
	SetDParam(0, c->index);

	assert(max_len <= lengthof(company_name));
	GetString(company_name, STR_COMPANY_NAME, company_name + max_len - 1);

	/* Get the income */
	Money income = 0;
	if (_cur_year - 1 == c->inaugurated_year) {
		/* The company is here just 1 year, so display [2], else display[1] */
		for (uint i = 0; i < lengthof(c->yearly_expenses[2]); i++) {
			income -= c->yearly_expenses[2][i];
		}
	} else {
		for (uint i = 0; i < lengthof(c->yearly_expenses[1]); i++) {
			income -= c->yearly_expenses[1][i];
		}
	}

	/* Send the information */
	p->Send_uint8 (c->index);
	p->Send_string(company_name);
	p->Send_uint32(c->inaugurated_year);
	p->Send_uint64(c->old_economy[0].company_value);
	p->Send_uint64(c->money);
	p->Send_uint64(income);
	p->Send_uint16(c->old_economy[0].performance_history);

	/* Send 1 if there is a passord for the company else send 0 */
	p->Send_bool  (!StrEmpty(_network_company_states[c->index].password));

	for (uint i = 0; i < NETWORK_VEH_END; i++) {
		p->Send_uint16(stats->num_vehicle[i]);
	}

	for (uint i = 0; i < NETWORK_VEH_END; i++) {
		p->Send_uint16(stats->num_station[i]);
	}

	p->Send_bool(c->is_ai);
}

/**
 * Populate the company stats.
 * @param stats the stats to update
 */
void NetworkPopulateCompanyStats(NetworkCompanyStats *stats)
{
	const Vehicle *v;
	const Station *s;

	memset(stats, 0, sizeof(*stats) * MAX_COMPANIES);

	/* Go through all vehicles and count the type of vehicles */
	FOR_ALL_VEHICLES(v) {
		if (!Company::IsValidID(v->owner) || !v->IsPrimaryVehicle()) continue;
		byte type = 0;
		switch (v->type) {
			case VEH_TRAIN: type = NETWORK_VEH_TRAIN; break;
			case VEH_ROAD: type = RoadVehicle::From(v)->IsBus() ? NETWORK_VEH_BUS : NETWORK_VEH_LORRY; break;
			case VEH_AIRCRAFT: type = NETWORK_VEH_PLANE; break;
			case VEH_SHIP: type = NETWORK_VEH_SHIP; break;
			default: continue;
		}
		stats[v->owner].num_vehicle[type]++;
	}

	/* Go through all stations and count the types of stations */
	FOR_ALL_STATIONS(s) {
		if (Company::IsValidID(s->owner)) {
			NetworkCompanyStats *npi = &stats[s->owner];

			if (s->facilities & FACIL_TRAIN)      npi->num_station[NETWORK_VEH_TRAIN]++;
			if (s->facilities & FACIL_TRUCK_STOP) npi->num_station[NETWORK_VEH_LORRY]++;
			if (s->facilities & FACIL_BUS_STOP)   npi->num_station[NETWORK_VEH_BUS]++;
			if (s->facilities & FACIL_AIRPORT)    npi->num_station[NETWORK_VEH_PLANE]++;
			if (s->facilities & FACIL_DOCK)       npi->num_station[NETWORK_VEH_SHIP]++;
		}
	}
}

/**
 * Send updated client info of a particular client.
 * @param client_id The client to send it for.
 */
void NetworkUpdateClientInfo(ClientID client_id)
{
	NetworkClientSocket *cs;
	NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);

	if (ci == NULL) return;

	DEBUG(desync, 1, "client: %08x; %02x; %02x; %04x", _date, _date_fract, (int)ci->client_playas, client_id);

	FOR_ALL_CLIENT_SOCKETS(cs) {
		cs->SendClientInfo(ci);
	}

	NetworkAdminClientUpdate(ci);
}

/** Check if we want to restart the map */
static void NetworkCheckRestartMap()
{
	if (_settings_client.network.restart_game_year != 0 && _cur_year >= _settings_client.network.restart_game_year) {
		DEBUG(net, 0, "Auto-restarting map. Year %d reached", _cur_year);

		StartNewGameWithoutGUI(GENERATE_NEW_SEED);
	}
}

/** Check if the server has autoclean_companies activated
 * Two things happen:
 *     1) If a company is not protected, it is closed after 1 year (for example)
 *     2) If a company is protected, protection is disabled after 3 years (for example)
 *          (and item 1. happens a year later)
 */
static void NetworkAutoCleanCompanies()
{
	const NetworkClientInfo *ci;
	const Company *c;
	bool clients_in_company[MAX_COMPANIES];
	int vehicles_in_company[MAX_COMPANIES];

	if (!_settings_client.network.autoclean_companies) return;

	memset(clients_in_company, 0, sizeof(clients_in_company));

	/* Detect the active companies */
	FOR_ALL_CLIENT_INFOS(ci) {
		if (Company::IsValidID(ci->client_playas)) clients_in_company[ci->client_playas] = true;
	}

	if (!_network_dedicated) {
		ci = NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER);
		if (Company::IsValidID(ci->client_playas)) clients_in_company[ci->client_playas] = true;
	}

	if (_settings_client.network.autoclean_novehicles != 0) {
		memset(vehicles_in_company, 0, sizeof(vehicles_in_company));

		const Vehicle *v;
		FOR_ALL_VEHICLES(v) {
			if (!Company::IsValidID(v->owner) || !v->IsPrimaryVehicle()) continue;
			vehicles_in_company[v->owner]++;
		}
	}

	/* Go through all the comapnies */
	FOR_ALL_COMPANIES(c) {
		/* Skip the non-active once */
		if (c->is_ai) continue;

		if (!clients_in_company[c->index]) {
			/* The company is empty for one month more */
			_network_company_states[c->index].months_empty++;

			/* Is the company empty for autoclean_unprotected-months, and is there no protection? */
			if (_settings_client.network.autoclean_unprotected != 0 && _network_company_states[c->index].months_empty > _settings_client.network.autoclean_unprotected && StrEmpty(_network_company_states[c->index].password)) {
				/* Shut the company down */
				DoCommandP(0, 2 | c->index << 16, CRR_AUTOCLEAN, CMD_COMPANY_CTRL);
				IConsolePrintF(CC_DEFAULT, "Auto-cleaned company #%d with no password", c->index + 1);
			}
			/* Is the company empty for autoclean_protected-months, and there is a protection? */
			if (_settings_client.network.autoclean_protected != 0 && _network_company_states[c->index].months_empty > _settings_client.network.autoclean_protected && !StrEmpty(_network_company_states[c->index].password)) {
				/* Unprotect the company */
				_network_company_states[c->index].password[0] = '\0';
				IConsolePrintF(CC_DEFAULT, "Auto-removed protection from company #%d", c->index + 1);
				_network_company_states[c->index].months_empty = 0;
				NetworkServerUpdateCompanyPassworded(c->index, false);
			}
			/* Is the company empty for autoclean_novehicles-months, and has no vehicles? */
			if (_settings_client.network.autoclean_novehicles != 0 && _network_company_states[c->index].months_empty > _settings_client.network.autoclean_novehicles && vehicles_in_company[c->index] == 0) {
				/* Shut the company down */
				DoCommandP(0, 2 | c->index << 16, CRR_AUTOCLEAN, CMD_COMPANY_CTRL);
				IConsolePrintF(CC_DEFAULT, "Auto-cleaned company #%d with no vehicles", c->index + 1);
			}
		} else {
			/* It is not empty, reset the date */
			_network_company_states[c->index].months_empty = 0;
		}
	}
}

/**
 * Check whether a name is unique, and otherwise try to make it unique.
 * @param new_name The name to check/modify.
 * @return True if an unique name was achieved.
 */
bool NetworkFindName(char new_name[NETWORK_CLIENT_NAME_LENGTH])
{
	bool found_name = false;
	uint number = 0;
	char original_name[NETWORK_CLIENT_NAME_LENGTH];

	/* We use NETWORK_CLIENT_NAME_LENGTH in here, because new_name is really a pointer */
	ttd_strlcpy(original_name, new_name, NETWORK_CLIENT_NAME_LENGTH);

	while (!found_name) {
		const NetworkClientInfo *ci;

		found_name = true;
		FOR_ALL_CLIENT_INFOS(ci) {
			if (strcmp(ci->client_name, new_name) == 0) {
				/* Name already in use */
				found_name = false;
				break;
			}
		}
		/* Check if it is the same as the server-name */
		ci = NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER);
		if (ci != NULL) {
			if (strcmp(ci->client_name, new_name) == 0) found_name = false; // name already in use
		}

		if (!found_name) {
			/* Try a new name (<name> #1, <name> #2, and so on) */

			/* Something's really wrong when there're more names than clients */
			if (number++ > MAX_CLIENTS) break;
			snprintf(new_name, NETWORK_CLIENT_NAME_LENGTH, "%s #%d", original_name, number);
		}
	}

	return found_name;
}

/**
 * Change the client name of the given client
 * @param client_id the client to change the name of
 * @param new_name the new name for the client
 * @return true iff the name was changed
 */
bool NetworkServerChangeClientName(ClientID client_id, const char *new_name)
{
	NetworkClientInfo *ci;
	/* Check if the name's already in use */
	FOR_ALL_CLIENT_INFOS(ci) {
		if (strcmp(ci->client_name, new_name) == 0) return false;
	}

	ci = NetworkClientInfo::GetByClientID(client_id);
	if (ci == NULL) return false;

	NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, CC_DEFAULT, true, ci->client_name, new_name);

	strecpy(ci->client_name, new_name, lastof(ci->client_name));

	NetworkUpdateClientInfo(client_id);
	return true;
}

/**
 * Set/Reset a company password on the server end.
 * @param company_id ID of the company the password should be changed for.
 * @param password The new password.
 * @param already_hashed Is the given password already hashed?
 */
void NetworkServerSetCompanyPassword(CompanyID company_id, const char *password, bool already_hashed)
{
	if (!Company::IsValidHumanID(company_id)) return;

	if (!already_hashed) {
		password = GenerateCompanyPasswordHash(password, _settings_client.network.network_id, _settings_game.game_creation.generation_seed);
	}

	strecpy(_network_company_states[company_id].password, password, lastof(_network_company_states[company_id].password));
	NetworkServerUpdateCompanyPassworded(company_id, !StrEmpty(_network_company_states[company_id].password));
}

/**
 * Handle the command-queue of a socket.
 * @param cs The socket to handle the queue for.
 */
static void NetworkHandleCommandQueue(NetworkClientSocket *cs)
{
	CommandPacket *cp;
	while ((cp = cs->outgoing_queue.Pop()) != NULL) {
		cs->SendCommand(cp);
		free(cp);
	}
}

/**
 * This is called every tick if this is a _network_server
 * @param send_frame Whether to send the frame to the clients.
 */
void NetworkServer_Tick(bool send_frame)
{
	NetworkClientSocket *cs;
#ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME
	bool send_sync = false;
#endif

#ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME
	if (_frame_counter >= _last_sync_frame + _settings_client.network.sync_freq) {
		_last_sync_frame = _frame_counter;
		send_sync = true;
	}
#endif

	/* Now we are done with the frame, inform the clients that they can
	 *  do their frame! */
	FOR_ALL_CLIENT_SOCKETS(cs) {
		/* We allow a number of bytes per frame, but only to the burst amount
		 * to be available for packet receiving at any particular time. */
		cs->receive_limit = min(cs->receive_limit + _settings_client.network.bytes_per_frame,
				_settings_client.network.bytes_per_frame_burst);

		/* Check if the speed of the client is what we can expect from a client */
		uint lag = NetworkCalculateLag(cs);
		switch (cs->status) {
			case NetworkClientSocket::STATUS_ACTIVE:
				if (lag > _settings_client.network.max_lag_time) {
					/* Client did still not report in within the specififed limit. */
					IConsolePrintF(CC_ERROR, cs->last_packet + lag * MILLISECONDS_PER_TICK > _realtime_tick ?
							/* A packet was received in the last three game days, so the client is likely lagging behind. */
								"Client #%d is dropped because the client's game state is more than %d ticks behind" :
							/* No packet was received in the last three game days; sounds like a lost connection. */
								"Client #%d is dropped because the client did not respond for more than %d ticks",
							cs->client_id, lag);
					cs->SendError(NETWORK_ERROR_TIMEOUT_COMPUTER);
					continue;
				}

				/* Report once per time we detect the lag, and only when we
				 * received a packet in the last 2000 milliseconds. If we
				 * did not receive a packet, then the client is not just
				 * slow, but the connection is likely severed. Mentioning
				 * frame_freq is not useful in this case. */
				if (lag > (uint)DAY_TICKS && cs->lag_test == 0 && cs->last_packet + 2000 > _realtime_tick) {
					IConsolePrintF(CC_WARNING, "[%d] Client #%d is slow, try increasing [network.]frame_freq to a higher value!", _frame_counter, cs->client_id);
					cs->lag_test = 1;
				}

				if (cs->last_frame_server - cs->last_token_frame >= _settings_client.network.max_lag_time) {
					/* This is a bad client! It didn't send the right token back within time. */
					IConsolePrintF(CC_ERROR, "Client #%d is dropped because it fails to send valid acks", cs->client_id);
					cs->SendError(NETWORK_ERROR_TIMEOUT_COMPUTER);
					continue;
				}
				break;

			case NetworkClientSocket::STATUS_INACTIVE:
			case NetworkClientSocket::STATUS_NEWGRFS_CHECK:
			case NetworkClientSocket::STATUS_AUTHORIZED:
				/* NewGRF check and authorized states should be handled almost instantly.
				 * So give them some lee-way, likewise for the query with inactive. */
				if (lag > _settings_client.network.max_init_time) {
					IConsolePrintF(CC_ERROR, "Client #%d is dropped because it took longer than %d ticks to start the joining process", cs->client_id, _settings_client.network.max_init_time);
					cs->SendError(NETWORK_ERROR_TIMEOUT_COMPUTER);
					continue;
				}
				break;

			case NetworkClientSocket::STATUS_MAP:
				/* Downloading the map... this is the amount of time since starting the saving. */
				if (lag > _settings_client.network.max_download_time) {
					IConsolePrintF(CC_ERROR, "Client #%d is dropped because it took longer than %d ticks to download the map", cs->client_id, _settings_client.network.max_download_time);
					cs->SendError(NETWORK_ERROR_TIMEOUT_MAP);
					continue;
				}
				break;

			case NetworkClientSocket::STATUS_DONE_MAP:
			case NetworkClientSocket::STATUS_PRE_ACTIVE:
				/* The map has been sent, so this is for loading the map and syncing up. */
				if (lag > _settings_client.network.max_join_time) {
					IConsolePrintF(CC_ERROR, "Client #%d is dropped because it took longer than %d ticks to join", cs->client_id, _settings_client.network.max_join_time);
					cs->SendError(NETWORK_ERROR_TIMEOUT_JOIN);
					continue;
				}
				break;

			case NetworkClientSocket::STATUS_AUTH_GAME:
			case NetworkClientSocket::STATUS_AUTH_COMPANY:
				/* These don't block? */
				if (lag > _settings_client.network.max_password_time) {
					IConsolePrintF(CC_ERROR, "Client #%d is dropped because it took longer than %d ticks to enter the password", cs->client_id, _settings_client.network.max_password_time);
					cs->SendError(NETWORK_ERROR_TIMEOUT_PASSWORD);
					continue;
				}
				break;

			case NetworkClientSocket::STATUS_MAP_WAIT:
				/* This is an internal state where we do not wait
				 * on the client to move to a different state. */
				break;

			case NetworkClientSocket::STATUS_END:
				/* Bad server/code. */
				NOT_REACHED();
		}

		if (cs->status >= NetworkClientSocket::STATUS_PRE_ACTIVE) {
			/* Check if we can send command, and if we have anything in the queue */
			NetworkHandleCommandQueue(cs);

			/* Send an updated _frame_counter_max to the client */
			if (send_frame) cs->SendFrame();

#ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME
			/* Send a sync-check packet */
			if (send_sync) cs->SendSync();
#endif
		}
	}

	/* See if we need to advertise */
	NetworkUDPAdvertise();
}

/** Yearly "callback". Called whenever the year changes. */
void NetworkServerYearlyLoop()
{
	NetworkCheckRestartMap();
	NetworkAdminUpdate(ADMIN_FREQUENCY_ANUALLY);
}

/** Monthly "callback". Called whenever the month changes. */
void NetworkServerMonthlyLoop()
{
	NetworkAutoCleanCompanies();
	NetworkAdminUpdate(ADMIN_FREQUENCY_MONTHLY);
	if ((_cur_month % 3) == 0) NetworkAdminUpdate(ADMIN_FREQUENCY_QUARTERLY);
}

/** Daily "callback". Called whenever the date changes. */
void NetworkServerDailyLoop()
{
	NetworkAdminUpdate(ADMIN_FREQUENCY_DAILY);
	if ((_date % 7) == 3) NetworkAdminUpdate(ADMIN_FREQUENCY_WEEKLY);
}

/**
 * Get the IP address/hostname of the connected client.
 * @return The IP address.
 */
const char *ServerNetworkGameSocketHandler::GetClientIP()
{
	return this->client_address.GetHostname();
}

/** Show the status message of all clients on the console. */
void NetworkServerShowStatusToConsole()
{
	static const char * const stat_str[] = {
		"inactive",
		"checking NewGRFs",
		"authorizing (server password)",
		"authorizing (company password)",
		"authorized",
		"waiting",
		"loading map",
		"map done",
		"ready",
		"active"
	};
	assert_compile(lengthof(stat_str) == NetworkClientSocket::STATUS_END);

	NetworkClientSocket *cs;
	FOR_ALL_CLIENT_SOCKETS(cs) {
		NetworkClientInfo *ci = cs->GetInfo();
		if (ci == NULL) continue;
		uint lag = NetworkCalculateLag(cs);
		const char *status;

		status = (cs->status < (ptrdiff_t)lengthof(stat_str) ? stat_str[cs->status] : "unknown");
		IConsolePrintF(CC_INFO, "Client #%1d  name: '%s'  status: '%s'  frame-lag: %3d  company: %1d  IP: %s",
			cs->client_id, ci->client_name, status, lag,
			ci->client_playas + (Company::IsValidID(ci->client_playas) ? 1 : 0),
			cs->GetClientIP());
	}
}

/**
 * Send Config Update
 */
void NetworkServerSendConfigUpdate()
{
	NetworkClientSocket *cs;

	FOR_ALL_CLIENT_SOCKETS(cs) {
		if (cs->status >= NetworkClientSocket::STATUS_PRE_ACTIVE) cs->SendConfigUpdate();
	}
}

/**
 * Tell that a particular company is (not) passworded.
 * @param company_id The company that got/removed the password.
 * @param passworded Whether the password was received or removed.
 */
void NetworkServerUpdateCompanyPassworded(CompanyID company_id, bool passworded)
{
	if (NetworkCompanyIsPassworded(company_id) == passworded) return;

	SB(_network_company_passworded, company_id, 1, !!passworded);
	SetWindowClassesDirty(WC_COMPANY);

	NetworkClientSocket *cs;
	FOR_ALL_CLIENT_SOCKETS(cs) {
		if (cs->status >= NetworkClientSocket::STATUS_PRE_ACTIVE) cs->SendCompanyUpdate();
	}

	NetworkAdminCompanyUpdate(Company::GetIfValid(company_id));
}

/**
 * Handle the tid-bits of moving a client from one company to another.
 * @param client_id id of the client we want to move.
 * @param company_id id of the company we want to move the client to.
 * @return void
 */
void NetworkServerDoMove(ClientID client_id, CompanyID company_id)
{
	/* Only allow non-dedicated servers and normal clients to be moved */
	if (client_id == CLIENT_ID_SERVER && _network_dedicated) return;

	NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);

	/* No need to waste network resources if the client is in the company already! */
	if (ci->client_playas == company_id) return;

	ci->client_playas = company_id;

	if (client_id == CLIENT_ID_SERVER) {
		SetLocalCompany(company_id);
	} else {
		NetworkClientSocket *cs = NetworkClientSocket::GetByClientID(client_id);
		/* When the company isn't authorized we can't move them yet. */
		if (cs->status < NetworkClientSocket::STATUS_AUTHORIZED) return;
		cs->SendMove(client_id, company_id);
	}

	/* announce the client's move */
	NetworkUpdateClientInfo(client_id);

	NetworkAction action = (company_id == COMPANY_SPECTATOR) ? NETWORK_ACTION_COMPANY_SPECTATOR : NETWORK_ACTION_COMPANY_JOIN;
	NetworkServerSendChat(action, DESTTYPE_BROADCAST, 0, "", client_id, company_id + 1);
}

/**
 * Send an rcon reply to the client.
 * @param client_id The identifier of the client.
 * @param colour_code The colour of the text.
 * @param string The actual reply.
 */
void NetworkServerSendRcon(ClientID client_id, TextColour colour_code, const char *string)
{
	NetworkClientSocket::GetByClientID(client_id)->SendRConResult(colour_code, string);
}

/**
 * Kick a single client.
 * @param client_id The client to kick.
 */
void NetworkServerKickClient(ClientID client_id)
{
	if (client_id == CLIENT_ID_SERVER) return;
	NetworkClientSocket::GetByClientID(client_id)->SendError(NETWORK_ERROR_KICKED);
}

/**
 * Ban, or kick, everyone joined from the given client's IP.
 * @param client_id The client to check for.
 * @param ban Whether to ban or kick.
 */
uint NetworkServerKickOrBanIP(ClientID client_id, bool ban)
{
	return NetworkServerKickOrBanIP(NetworkClientSocket::GetByClientID(client_id)->GetClientIP(), ban);
}

/**
 * Kick or ban someone based on an IP address.
 * @param ip The IP address/range to ban/kick.
 * @param ban Whether to ban or just kick.
 */
uint NetworkServerKickOrBanIP(const char *ip, bool ban)
{
	/* Add address to ban-list */
	if (ban) *_network_ban_list.Append() = strdup(ip);

	uint n = 0;

	/* There can be multiple clients with the same IP, kick them all */
	NetworkClientSocket *cs;
	FOR_ALL_CLIENT_SOCKETS(cs) {
		if (cs->client_id == CLIENT_ID_SERVER) continue;
		if (cs->client_address.IsInNetmask(const_cast<char *>(ip))) {
			NetworkServerKickClient(cs->client_id);
			n++;
		}
	}

	return n;
}

/**
 * Check whether a particular company has clients.
 * @param company The company to check.
 * @return True if at least one client is joined to the company.
 */
bool NetworkCompanyHasClients(CompanyID company)
{
	const NetworkClientInfo *ci;
	FOR_ALL_CLIENT_INFOS(ci) {
		if (ci->client_playas == company) return true;
	}
	return false;
}


/**
 * Get the name of the client, if the user did not send it yet, Client #<no> is used.
 * @param client_name The variable to write the name to.
 * @param size        The amount of bytes we can write.
 */
void ServerNetworkGameSocketHandler::GetClientName(char *client_name, size_t size) const
{
	const NetworkClientInfo *ci = this->GetInfo();

	if (ci == NULL || StrEmpty(ci->client_name)) {
		snprintf(client_name, size, "Client #%4d", this->client_id);
	} else {
		ttd_strlcpy(client_name, ci->client_name, size);
	}
}

/**
 * Print all the clients to the console
 */
void NetworkPrintClients()
{
	NetworkClientInfo *ci;
	FOR_ALL_CLIENT_INFOS(ci) {
		IConsolePrintF(CC_INFO, _network_server ? "Client #%1d  name: '%s'  company: %1d  IP: %s" : "Client #%1d  name: '%s'  company: %1d",
				ci->client_id,
				ci->client_name,
				ci->client_playas + (Company::IsValidID(ci->client_playas) ? 1 : 0),
				_network_server ? (ci->client_id == CLIENT_ID_SERVER ? "server" : NetworkClientSocket::GetByClientID(ci->client_id)->GetClientIP()) : "");
	}
}

#endif /* ENABLE_NETWORK */