network/network_server.c
branchcustombridgeheads
changeset 5642 bfa6074e2833
equal deleted inserted replaced
5641:d4d00a16ef26 5642:bfa6074e2833
       
     1 /* $Id$ */
       
     2 
       
     3 #ifdef ENABLE_NETWORK
       
     4 
       
     5 #include "../stdafx.h"
       
     6 #include "../openttd.h" // XXX StringID
       
     7 #include "../debug.h"
       
     8 #include "../string.h"
       
     9 #include "../strings.h"
       
    10 #include "network_data.h"
       
    11 #include "core/tcp.h"
       
    12 #include "../train.h"
       
    13 #include "../date.h"
       
    14 #include "../table/strings.h"
       
    15 #include "../functions.h"
       
    16 #include "network_server.h"
       
    17 #include "network_udp.h"
       
    18 #include "../console.h"
       
    19 #include "../command.h"
       
    20 #include "../saveload.h"
       
    21 #include "../vehicle.h"
       
    22 #include "../station.h"
       
    23 #include "../variables.h"
       
    24 #include "../genworld.h"
       
    25 
       
    26 // This file handles all the server-commands
       
    27 
       
    28 static void NetworkHandleCommandQueue(NetworkClientState* cs);
       
    29 
       
    30 // **********
       
    31 // Sending functions
       
    32 //   DEF_SERVER_SEND_COMMAND has parameter: NetworkClientState *cs
       
    33 // **********
       
    34 
       
    35 DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_CLIENT_INFO)(NetworkClientState *cs, NetworkClientInfo *ci)
       
    36 {
       
    37 	//
       
    38 	// Packet: SERVER_CLIENT_INFO
       
    39 	// Function: Sends info about a client
       
    40 	// Data:
       
    41 	//    uint16:  The index of the client (always unique on a server. 1 = server)
       
    42 	//    uint8:  As which player the client is playing
       
    43 	//    String: The name of the client
       
    44 	//    String: The unique id of the client
       
    45 	//
       
    46 
       
    47 	if (ci->client_index != NETWORK_EMPTY_INDEX) {
       
    48 		Packet *p = NetworkSend_Init(PACKET_SERVER_CLIENT_INFO);
       
    49 		NetworkSend_uint16(p, ci->client_index);
       
    50 		NetworkSend_uint8 (p, ci->client_playas);
       
    51 		NetworkSend_string(p, ci->client_name);
       
    52 		NetworkSend_string(p, ci->unique_id);
       
    53 
       
    54 		NetworkSend_Packet(p, cs);
       
    55 	}
       
    56 }
       
    57 
       
    58 DEF_SERVER_SEND_COMMAND(PACKET_SERVER_COMPANY_INFO)
       
    59 {
       
    60 //
       
    61 	// Packet: SERVER_COMPANY_INFO
       
    62 	// Function: Sends info about the companies
       
    63 	// Data:
       
    64 	//
       
    65 
       
    66 	int i;
       
    67 
       
    68 	Player *player;
       
    69 	Packet *p;
       
    70 
       
    71 	byte active = ActivePlayerCount();
       
    72 
       
    73 	if (active == 0) {
       
    74 		p = NetworkSend_Init(PACKET_SERVER_COMPANY_INFO);
       
    75 
       
    76 		NetworkSend_uint8 (p, NETWORK_COMPANY_INFO_VERSION);
       
    77 		NetworkSend_uint8 (p, active);
       
    78 
       
    79 		NetworkSend_Packet(p, cs);
       
    80 		return;
       
    81 	}
       
    82 
       
    83 	NetworkPopulateCompanyInfo();
       
    84 
       
    85 	FOR_ALL_PLAYERS(player) {
       
    86 		if (!player->is_active) continue;
       
    87 
       
    88 		p = NetworkSend_Init(PACKET_SERVER_COMPANY_INFO);
       
    89 
       
    90 		NetworkSend_uint8 (p, NETWORK_COMPANY_INFO_VERSION);
       
    91 		NetworkSend_uint8 (p, active);
       
    92 		NetworkSend_uint8 (p, player->index);
       
    93 
       
    94 		NetworkSend_string(p, _network_player_info[player->index].company_name);
       
    95 		NetworkSend_uint32(p, _network_player_info[player->index].inaugurated_year);
       
    96 		NetworkSend_uint64(p, _network_player_info[player->index].company_value);
       
    97 		NetworkSend_uint64(p, _network_player_info[player->index].money);
       
    98 		NetworkSend_uint64(p, _network_player_info[player->index].income);
       
    99 		NetworkSend_uint16(p, _network_player_info[player->index].performance);
       
   100 
       
   101 		/* Send 1 if there is a passord for the company else send 0 */
       
   102 		if (_network_player_info[player->index].password[0] != '\0') {
       
   103 			NetworkSend_uint8(p, 1);
       
   104 		} else {
       
   105 			NetworkSend_uint8(p, 0);
       
   106 		}
       
   107 
       
   108 		for (i = 0; i < NETWORK_VEHICLE_TYPES; i++) {
       
   109 			NetworkSend_uint16(p, _network_player_info[player->index].num_vehicle[i]);
       
   110 		}
       
   111 
       
   112 		for (i = 0; i < NETWORK_STATION_TYPES; i++) {
       
   113 			NetworkSend_uint16(p, _network_player_info[player->index].num_station[i]);
       
   114 		}
       
   115 
       
   116 		if (_network_player_info[player->index].players[0] == '\0') {
       
   117 			NetworkSend_string(p, "<none>");
       
   118 		} else {
       
   119 			NetworkSend_string(p, _network_player_info[player->index].players);
       
   120 		}
       
   121 
       
   122 		NetworkSend_Packet(p, cs);
       
   123 	}
       
   124 
       
   125 	p = NetworkSend_Init(PACKET_SERVER_COMPANY_INFO);
       
   126 
       
   127 	NetworkSend_uint8 (p, NETWORK_COMPANY_INFO_VERSION);
       
   128 	NetworkSend_uint8 (p, 0);
       
   129 
       
   130 	NetworkSend_Packet(p, cs);
       
   131 }
       
   132 
       
   133 DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_ERROR)(NetworkClientState *cs, NetworkErrorCode error)
       
   134 {
       
   135 	//
       
   136 	// Packet: SERVER_ERROR
       
   137 	// Function: The client made an error
       
   138 	// Data:
       
   139 	//    uint8:  ErrorID (see network_data.h, NetworkErrorCode)
       
   140 	//
       
   141 
       
   142 	char str[100];
       
   143 	Packet *p = NetworkSend_Init(PACKET_SERVER_ERROR);
       
   144 
       
   145 	NetworkSend_uint8(p, error);
       
   146 	NetworkSend_Packet(p, cs);
       
   147 
       
   148 	GetNetworkErrorMsg(str, error, lastof(str));
       
   149 
       
   150 	// Only send when the current client was in game
       
   151 	if (cs->status > STATUS_AUTH) {
       
   152 		NetworkClientState *new_cs;
       
   153 		char client_name[NETWORK_CLIENT_NAME_LENGTH];
       
   154 
       
   155 		NetworkGetClientName(client_name, sizeof(client_name), cs);
       
   156 
       
   157 		DEBUG(net, 1, "'%s' made an error and has been disconnected. Reason: '%s'", client_name, str);
       
   158 
       
   159 		NetworkTextMessage(NETWORK_ACTION_LEAVE, 1, false, client_name, "%s", str);
       
   160 
       
   161 		FOR_ALL_CLIENTS(new_cs) {
       
   162 			if (new_cs->status > STATUS_AUTH && new_cs != cs) {
       
   163 				// Some errors we filter to a more general error. Clients don't have to know the real
       
   164 				//  reason a joining failed.
       
   165 				if (error == NETWORK_ERROR_NOT_AUTHORIZED || error == NETWORK_ERROR_NOT_EXPECTED || error == NETWORK_ERROR_WRONG_REVISION)
       
   166 					error = NETWORK_ERROR_ILLEGAL_PACKET;
       
   167 
       
   168 				SEND_COMMAND(PACKET_SERVER_ERROR_QUIT)(new_cs, cs->index, error);
       
   169 			}
       
   170 		}
       
   171 	} else {
       
   172 		DEBUG(net, 1, "Client %d made an error and has been disconnected. Reason: '%s'", cs->index, str);
       
   173 	}
       
   174 
       
   175 	cs->has_quit = true;
       
   176 
       
   177 	// Make sure the data get's there before we close the connection
       
   178 	NetworkSend_Packets(cs);
       
   179 
       
   180 	// The client made a mistake, so drop his connection now!
       
   181 	NetworkCloseClient(cs);
       
   182 }
       
   183 
       
   184 DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_NEED_PASSWORD)(NetworkClientState *cs, NetworkPasswordType type)
       
   185 {
       
   186 	//
       
   187 	// Packet: SERVER_NEED_PASSWORD
       
   188 	// Function: Indication to the client that the server needs a password
       
   189 	// Data:
       
   190 	//    uint8:  Type of password
       
   191 	//
       
   192 
       
   193 	Packet *p = NetworkSend_Init(PACKET_SERVER_NEED_PASSWORD);
       
   194 	NetworkSend_uint8(p, type);
       
   195 	NetworkSend_Packet(p, cs);
       
   196 }
       
   197 
       
   198 DEF_SERVER_SEND_COMMAND(PACKET_SERVER_WELCOME)
       
   199 {
       
   200 	//
       
   201 	// Packet: SERVER_WELCOME
       
   202 	// Function: The client is joined and ready to receive his map
       
   203 	// Data:
       
   204 	//    uint16:  Own ClientID
       
   205 	//
       
   206 
       
   207 	Packet *p;
       
   208 	const NetworkClientState *new_cs;
       
   209 
       
   210 	// Invalid packet when status is AUTH or higher
       
   211 	if (cs->status >= STATUS_AUTH) return;
       
   212 
       
   213 	cs->status = STATUS_AUTH;
       
   214 	_network_game_info.clients_on++;
       
   215 
       
   216 	p = NetworkSend_Init(PACKET_SERVER_WELCOME);
       
   217 	NetworkSend_uint16(p, cs->index);
       
   218 	NetworkSend_Packet(p, cs);
       
   219 
       
   220 		// Transmit info about all the active clients
       
   221 	FOR_ALL_CLIENTS(new_cs) {
       
   222 		if (new_cs != cs && new_cs->status > STATUS_AUTH)
       
   223 			SEND_COMMAND(PACKET_SERVER_CLIENT_INFO)(cs, DEREF_CLIENT_INFO(new_cs));
       
   224 	}
       
   225 	// Also send the info of the server
       
   226 	SEND_COMMAND(PACKET_SERVER_CLIENT_INFO)(cs, NetworkFindClientInfoFromIndex(NETWORK_SERVER_INDEX));
       
   227 }
       
   228 
       
   229 DEF_SERVER_SEND_COMMAND(PACKET_SERVER_WAIT)
       
   230 {
       
   231 	//
       
   232 	// Packet: PACKET_SERVER_WAIT
       
   233 	// Function: The client can not receive the map at the moment because
       
   234 	//             someone else is already receiving the map
       
   235 	// Data:
       
   236 	//    uint8:  Clients awaiting map
       
   237 	//
       
   238 	int waiting = 0;
       
   239 	NetworkClientState *new_cs;
       
   240 	Packet *p;
       
   241 
       
   242 	// Count how many players are waiting in the queue
       
   243 	FOR_ALL_CLIENTS(new_cs) {
       
   244 		if (new_cs->status == STATUS_MAP_WAIT) waiting++;
       
   245 	}
       
   246 
       
   247 	p = NetworkSend_Init(PACKET_SERVER_WAIT);
       
   248 	NetworkSend_uint8(p, waiting);
       
   249 	NetworkSend_Packet(p, cs);
       
   250 }
       
   251 
       
   252 // This sends the map to the client
       
   253 DEF_SERVER_SEND_COMMAND(PACKET_SERVER_MAP)
       
   254 {
       
   255 	//
       
   256 	// Packet: SERVER_MAP
       
   257 	// Function: Sends the map to the client, or a part of it (it is splitted in
       
   258 	//   a lot of multiple packets)
       
   259 	// Data:
       
   260 	//    uint8:  packet-type (MAP_PACKET_START, MAP_PACKET_NORMAL and MAP_PACKET_END)
       
   261 	//  if MAP_PACKET_START:
       
   262 	//    uint32: The current FrameCounter
       
   263 	//  if MAP_PACKET_NORMAL:
       
   264 	//    piece of the map (till max-size of packet)
       
   265 	//  if MAP_PACKET_END:
       
   266 	//    uint32: seed0 of player
       
   267 	//    uint32: seed1 of player
       
   268 	//      last 2 are repeated MAX_PLAYERS time
       
   269 	//
       
   270 
       
   271 	static FILE *file_pointer;
       
   272 	static uint sent_packets; // How many packets we did send succecfully last time
       
   273 
       
   274 	if (cs->status < STATUS_AUTH) {
       
   275 		// Illegal call, return error and ignore the packet
       
   276 		SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_AUTHORIZED);
       
   277 		return;
       
   278 	}
       
   279 
       
   280 	if (cs->status == STATUS_AUTH) {
       
   281 		char filename[256];
       
   282 		Packet *p;
       
   283 
       
   284 		// Make a dump of the current game
       
   285 		snprintf(filename, lengthof(filename), "%s%snetwork_server.tmp",  _paths.autosave_dir, PATHSEP);
       
   286 		if (SaveOrLoad(filename, SL_SAVE) != SL_OK) error("network savedump failed");
       
   287 
       
   288 		file_pointer = fopen(filename, "rb");
       
   289 		fseek(file_pointer, 0, SEEK_END);
       
   290 
       
   291 		// Now send the _frame_counter and how many packets are coming
       
   292 		p = NetworkSend_Init(PACKET_SERVER_MAP);
       
   293 		NetworkSend_uint8(p, MAP_PACKET_START);
       
   294 		NetworkSend_uint32(p, _frame_counter);
       
   295 		NetworkSend_uint32(p, ftell(file_pointer));
       
   296 		NetworkSend_Packet(p, cs);
       
   297 
       
   298 		fseek(file_pointer, 0, SEEK_SET);
       
   299 
       
   300 		sent_packets = 4; // We start with trying 4 packets
       
   301 
       
   302 		cs->status = STATUS_MAP;
       
   303 		/* Mark the start of download */
       
   304 		cs->last_frame = _frame_counter;
       
   305 		cs->last_frame_server = _frame_counter;
       
   306 	}
       
   307 
       
   308 	if (cs->status == STATUS_MAP) {
       
   309 		uint i;
       
   310 		int res;
       
   311 		for (i = 0; i < sent_packets; i++) {
       
   312 			Packet *p = NetworkSend_Init(PACKET_SERVER_MAP);
       
   313 			NetworkSend_uint8(p, MAP_PACKET_NORMAL);
       
   314 			res = (int)fread(p->buffer + p->size, 1, SEND_MTU - p->size, file_pointer);
       
   315 
       
   316 			if (ferror(file_pointer)) error("Error reading temporary network savegame!");
       
   317 
       
   318 			p->size += res;
       
   319 			NetworkSend_Packet(p, cs);
       
   320 			if (feof(file_pointer)) {
       
   321 				// Done reading!
       
   322 				Packet *p = NetworkSend_Init(PACKET_SERVER_MAP);
       
   323 				NetworkSend_uint8(p, MAP_PACKET_END);
       
   324 				NetworkSend_Packet(p, cs);
       
   325 
       
   326 				// Set the status to DONE_MAP, no we will wait for the client
       
   327 				//  to send it is ready (maybe that happens like never ;))
       
   328 				cs->status = STATUS_DONE_MAP;
       
   329 				fclose(file_pointer);
       
   330 
       
   331 				{
       
   332 					NetworkClientState *new_cs;
       
   333 					bool new_map_client = false;
       
   334 					// Check if there is a client waiting for receiving the map
       
   335 					//  and start sending him the map
       
   336 					FOR_ALL_CLIENTS(new_cs) {
       
   337 						if (new_cs->status == STATUS_MAP_WAIT) {
       
   338 							// Check if we already have a new client to send the map to
       
   339 							if (!new_map_client) {
       
   340 								// If not, this client will get the map
       
   341 								new_cs->status = STATUS_AUTH;
       
   342 								new_map_client = true;
       
   343 								SEND_COMMAND(PACKET_SERVER_MAP)(new_cs);
       
   344 							} else {
       
   345 								// Else, send the other clients how many clients are in front of them
       
   346 								SEND_COMMAND(PACKET_SERVER_WAIT)(new_cs);
       
   347 							}
       
   348 						}
       
   349 					}
       
   350 				}
       
   351 
       
   352 				// There is no more data, so break the for
       
   353 				break;
       
   354 			}
       
   355 		}
       
   356 
       
   357 		// Send all packets (forced) and check if we have send it all
       
   358 		NetworkSend_Packets(cs);
       
   359 		if (cs->packet_queue == NULL) {
       
   360 			// All are sent, increase the sent_packets
       
   361 			sent_packets *= 2;
       
   362 		} else {
       
   363 			// Not everything is sent, decrease the sent_packets
       
   364 			if (sent_packets > 1) sent_packets /= 2;
       
   365 		}
       
   366 	}
       
   367 }
       
   368 
       
   369 DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_JOIN)(NetworkClientState *cs, uint16 client_index)
       
   370 {
       
   371 	//
       
   372 	// Packet: SERVER_JOIN
       
   373 	// Function: A client is joined (all active clients receive this after a
       
   374 	//     PACKET_CLIENT_MAP_OK) Mostly what directly follows is a
       
   375 	//     PACKET_SERVER_CLIENT_INFO
       
   376 	// Data:
       
   377 	//    uint16:  Client-Index
       
   378 	//
       
   379 
       
   380 	Packet *p = NetworkSend_Init(PACKET_SERVER_JOIN);
       
   381 
       
   382 	NetworkSend_uint16(p, client_index);
       
   383 
       
   384 	NetworkSend_Packet(p, cs);
       
   385 }
       
   386 
       
   387 
       
   388 DEF_SERVER_SEND_COMMAND(PACKET_SERVER_FRAME)
       
   389 {
       
   390 	//
       
   391 	// Packet: SERVER_FRAME
       
   392 	// Function: Sends the current frame-counter to the client
       
   393 	// Data:
       
   394 	//    uint32: Frame Counter
       
   395 	//    uint32: Frame Counter Max (how far may the client walk before the server?)
       
   396 	//    [uint32: general-seed-1]
       
   397 	//    [uint32: general-seed-2]
       
   398 	//      (last two depends on compile-settings, and are not default settings)
       
   399 	//
       
   400 
       
   401 	Packet *p = NetworkSend_Init(PACKET_SERVER_FRAME);
       
   402 	NetworkSend_uint32(p, _frame_counter);
       
   403 	NetworkSend_uint32(p, _frame_counter_max);
       
   404 #ifdef ENABLE_NETWORK_SYNC_EVERY_FRAME
       
   405 	NetworkSend_uint32(p, _sync_seed_1);
       
   406 #ifdef NETWORK_SEND_DOUBLE_SEED
       
   407 	NetworkSend_uint32(p, _sync_seed_2);
       
   408 #endif
       
   409 #endif
       
   410 	NetworkSend_Packet(p, cs);
       
   411 }
       
   412 
       
   413 DEF_SERVER_SEND_COMMAND(PACKET_SERVER_SYNC)
       
   414 {
       
   415 	//
       
   416 	// Packet: SERVER_SYNC
       
   417 	// Function: Sends a sync-check to the client
       
   418 	// Data:
       
   419 	//    uint32: Frame Counter
       
   420 	//    uint32: General-seed-1
       
   421 	//    [uint32: general-seed-2]
       
   422 	//      (last one depends on compile-settings, and are not default settings)
       
   423 	//
       
   424 
       
   425 	Packet *p = NetworkSend_Init(PACKET_SERVER_SYNC);
       
   426 	NetworkSend_uint32(p, _frame_counter);
       
   427 	NetworkSend_uint32(p, _sync_seed_1);
       
   428 
       
   429 #ifdef NETWORK_SEND_DOUBLE_SEED
       
   430 	NetworkSend_uint32(p, _sync_seed_2);
       
   431 #endif
       
   432 	NetworkSend_Packet(p, cs);
       
   433 }
       
   434 
       
   435 DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_COMMAND)(NetworkClientState *cs, CommandPacket *cp)
       
   436 {
       
   437 	//
       
   438 	// Packet: SERVER_COMMAND
       
   439 	// Function: Sends a DoCommand to the client
       
   440 	// Data:
       
   441 	//    uint8:  PlayerID (0..MAX_PLAYERS-1)
       
   442 	//    uint32: CommandID (see command.h)
       
   443 	//    uint32: P1 (free variables used in DoCommand)
       
   444 	//    uint32: P2
       
   445 	//    uint32: Tile
       
   446 	//    string: text
       
   447 	//    uint8:  CallBackID (see callback_table.c)
       
   448 	//    uint32: Frame of execution
       
   449 	//
       
   450 
       
   451 	Packet *p = NetworkSend_Init(PACKET_SERVER_COMMAND);
       
   452 
       
   453 	NetworkSend_uint8(p, cp->player);
       
   454 	NetworkSend_uint32(p, cp->cmd);
       
   455 	NetworkSend_uint32(p, cp->p1);
       
   456 	NetworkSend_uint32(p, cp->p2);
       
   457 	NetworkSend_uint32(p, cp->tile);
       
   458 	NetworkSend_string(p, cp->text);
       
   459 	NetworkSend_uint8(p, cp->callback);
       
   460 	NetworkSend_uint32(p, cp->frame);
       
   461 
       
   462 	NetworkSend_Packet(p, cs);
       
   463 }
       
   464 
       
   465 DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_CHAT)(NetworkClientState *cs, NetworkAction action, uint16 client_index, bool self_send, const char *msg)
       
   466 {
       
   467 	//
       
   468 	// Packet: SERVER_CHAT
       
   469 	// Function: Sends a chat-packet to the client
       
   470 	// Data:
       
   471 	//    uint8:  ActionID (see network_data.h, NetworkAction)
       
   472 	//    uint16:  Client-index
       
   473 	//    String: Message (max MAX_TEXT_MSG_LEN)
       
   474 	//
       
   475 
       
   476 	Packet *p = NetworkSend_Init(PACKET_SERVER_CHAT);
       
   477 
       
   478 	NetworkSend_uint8(p, action);
       
   479 	NetworkSend_uint16(p, client_index);
       
   480 	NetworkSend_uint8(p, self_send);
       
   481 	NetworkSend_string(p, msg);
       
   482 
       
   483 	NetworkSend_Packet(p, cs);
       
   484 }
       
   485 
       
   486 DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_ERROR_QUIT)(NetworkClientState *cs, uint16 client_index, NetworkErrorCode errorno)
       
   487 {
       
   488 	//
       
   489 	// Packet: SERVER_ERROR_QUIT
       
   490 	// Function: One of the clients made an error and is quiting the game
       
   491 	//      This packet informs the other clients of that.
       
   492 	// Data:
       
   493 	//    uint16:  Client-index
       
   494 	//    uint8:  ErrorID (see network_data.h, NetworkErrorCode)
       
   495 	//
       
   496 
       
   497 	Packet *p = NetworkSend_Init(PACKET_SERVER_ERROR_QUIT);
       
   498 
       
   499 	NetworkSend_uint16(p, client_index);
       
   500 	NetworkSend_uint8(p, errorno);
       
   501 
       
   502 	NetworkSend_Packet(p, cs);
       
   503 }
       
   504 
       
   505 DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_QUIT)(NetworkClientState *cs, uint16 client_index, const char *leavemsg)
       
   506 {
       
   507 	//
       
   508 	// Packet: SERVER_ERROR_QUIT
       
   509 	// Function: A client left the game, and this packets informs the other clients
       
   510 	//      of that.
       
   511 	// Data:
       
   512 	//    uint16:  Client-index
       
   513 	//    String: leave-message
       
   514 	//
       
   515 
       
   516 	Packet *p = NetworkSend_Init(PACKET_SERVER_QUIT);
       
   517 
       
   518 	NetworkSend_uint16(p, client_index);
       
   519 	NetworkSend_string(p, leavemsg);
       
   520 
       
   521 	NetworkSend_Packet(p, cs);
       
   522 }
       
   523 
       
   524 DEF_SERVER_SEND_COMMAND(PACKET_SERVER_SHUTDOWN)
       
   525 {
       
   526 	//
       
   527 	// Packet: SERVER_SHUTDOWN
       
   528 	// Function: Let the clients know that the server is closing
       
   529 	// Data:
       
   530 	//     <none>
       
   531 	//
       
   532 
       
   533 	Packet *p = NetworkSend_Init(PACKET_SERVER_SHUTDOWN);
       
   534 	NetworkSend_Packet(p, cs);
       
   535 }
       
   536 
       
   537 DEF_SERVER_SEND_COMMAND(PACKET_SERVER_NEWGAME)
       
   538 {
       
   539 	//
       
   540 	// Packet: PACKET_SERVER_NEWGAME
       
   541 	// Function: Let the clients know that the server is loading a new map
       
   542 	// Data:
       
   543 	//     <none>
       
   544 	//
       
   545 
       
   546 	Packet *p = NetworkSend_Init(PACKET_SERVER_NEWGAME);
       
   547 	NetworkSend_Packet(p, cs);
       
   548 }
       
   549 
       
   550 DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_RCON)(NetworkClientState *cs, uint16 color, const char *command)
       
   551 {
       
   552 	Packet *p = NetworkSend_Init(PACKET_SERVER_RCON);
       
   553 
       
   554 	NetworkSend_uint16(p, color);
       
   555 	NetworkSend_string(p, command);
       
   556 	NetworkSend_Packet(p, cs);
       
   557 }
       
   558 
       
   559 // **********
       
   560 // Receiving functions
       
   561 //   DEF_SERVER_RECEIVE_COMMAND has parameter: NetworkClientState *cs, Packet *p
       
   562 // **********
       
   563 
       
   564 DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_COMPANY_INFO)
       
   565 {
       
   566 	SEND_COMMAND(PACKET_SERVER_COMPANY_INFO)(cs);
       
   567 }
       
   568 
       
   569 DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_JOIN)
       
   570 {
       
   571 	char name[NETWORK_CLIENT_NAME_LENGTH];
       
   572 	char unique_id[NETWORK_NAME_LENGTH];
       
   573 	NetworkClientInfo *ci;
       
   574 	byte playas;
       
   575 	NetworkLanguage client_lang;
       
   576 	char client_revision[NETWORK_REVISION_LENGTH];
       
   577 
       
   578 	NetworkRecv_string(cs, p, client_revision, sizeof(client_revision));
       
   579 
       
   580 #if defined(WITH_REV) || defined(WITH_REV_HACK)
       
   581 	// Check if the client has revision control enabled
       
   582 	if (strcmp(NOREV_STRING, client_revision) != 0 &&
       
   583 			strcmp(_network_game_info.server_revision, client_revision) != 0) {
       
   584 		// Different revisions!!
       
   585 		SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_WRONG_REVISION);
       
   586 		return;
       
   587 	}
       
   588 #endif
       
   589 
       
   590 	NetworkRecv_string(cs, p, name, sizeof(name));
       
   591 	playas = NetworkRecv_uint8(cs, p);
       
   592 	client_lang = NetworkRecv_uint8(cs, p);
       
   593 	NetworkRecv_string(cs, p, unique_id, sizeof(unique_id));
       
   594 
       
   595 	if (cs->has_quit) return;
       
   596 
       
   597 	// join another company does not affect these values
       
   598 	switch (playas) {
       
   599 		case PLAYER_NEW_COMPANY: /* New company */
       
   600 			if (ActivePlayerCount() >= _network_game_info.companies_max) {
       
   601 				SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_FULL);
       
   602 				return;
       
   603 			}
       
   604 			break;
       
   605 		case PLAYER_SPECTATOR: /* Spectator */
       
   606 			if (NetworkSpectatorCount() >= _network_game_info.spectators_max) {
       
   607 				SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_FULL);
       
   608 				return;
       
   609 			}
       
   610 			break;
       
   611 		default: /* Join another company (companies 1-8 (index 0-7)) */
       
   612 			if (!IsValidPlayer(playas)) {
       
   613 				SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_PLAYER_MISMATCH);
       
   614 				return;
       
   615 			}
       
   616 			break;
       
   617 	}
       
   618 
       
   619 	// We need a valid name.. make it Player
       
   620 	if (*name == '\0') ttd_strlcpy(name, "Player", sizeof(name));
       
   621 
       
   622 	if (!NetworkFindName(name)) { // Change name if duplicate
       
   623 		// We could not create a name for this player
       
   624 		SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NAME_IN_USE);
       
   625 		return;
       
   626 	}
       
   627 
       
   628 	ci = DEREF_CLIENT_INFO(cs);
       
   629 
       
   630 	ttd_strlcpy(ci->client_name, name, sizeof(ci->client_name));
       
   631 	ttd_strlcpy(ci->unique_id, unique_id, sizeof(ci->unique_id));
       
   632 	ci->client_playas = playas;
       
   633 	ci->client_lang = client_lang;
       
   634 
       
   635 	// We now want a password from the client
       
   636 	//  else we do not allow him in!
       
   637 	if (_network_game_info.use_password) {
       
   638 		SEND_COMMAND(PACKET_SERVER_NEED_PASSWORD)(cs, NETWORK_GAME_PASSWORD);
       
   639 	} else {
       
   640 		if (IsValidPlayer(ci->client_playas) && _network_player_info[ci->client_playas].password[0] != '\0') {
       
   641 			SEND_COMMAND(PACKET_SERVER_NEED_PASSWORD)(cs, NETWORK_COMPANY_PASSWORD);
       
   642 		} else {
       
   643 			SEND_COMMAND(PACKET_SERVER_WELCOME)(cs);
       
   644 		}
       
   645 	}
       
   646 
       
   647 	/* Make sure companies to which people try to join are not autocleaned */
       
   648 	if (IsValidPlayer(playas)) _network_player_info[playas].months_empty = 0;
       
   649 }
       
   650 
       
   651 DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_PASSWORD)
       
   652 {
       
   653 	NetworkPasswordType type;
       
   654 	char password[NETWORK_PASSWORD_LENGTH];
       
   655 	const NetworkClientInfo *ci;
       
   656 
       
   657 	type = NetworkRecv_uint8(cs, p);
       
   658 	NetworkRecv_string(cs, p, password, sizeof(password));
       
   659 
       
   660 	if (cs->status == STATUS_INACTIVE && type == NETWORK_GAME_PASSWORD) {
       
   661 		// Check game-password
       
   662 		if (strcmp(password, _network_game_info.server_password) != 0) {
       
   663 			// Password is invalid
       
   664 			SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_WRONG_PASSWORD);
       
   665 			return;
       
   666 		}
       
   667 
       
   668 		ci = DEREF_CLIENT_INFO(cs);
       
   669 
       
   670 		if (IsValidPlayer(ci->client_playas) && _network_player_info[ci->client_playas].password[0] != '\0') {
       
   671 			SEND_COMMAND(PACKET_SERVER_NEED_PASSWORD)(cs, NETWORK_COMPANY_PASSWORD);
       
   672 			return;
       
   673 		}
       
   674 
       
   675 		// Valid password, allow user
       
   676 		SEND_COMMAND(PACKET_SERVER_WELCOME)(cs);
       
   677 		return;
       
   678 	} else if (cs->status == STATUS_INACTIVE && type == NETWORK_COMPANY_PASSWORD) {
       
   679 		ci = DEREF_CLIENT_INFO(cs);
       
   680 
       
   681 		if (strcmp(password, _network_player_info[ci->client_playas].password) != 0) {
       
   682 			// Password is invalid
       
   683 			SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_WRONG_PASSWORD);
       
   684 			return;
       
   685 		}
       
   686 
       
   687 		SEND_COMMAND(PACKET_SERVER_WELCOME)(cs);
       
   688 		return;
       
   689 	}
       
   690 
       
   691 
       
   692 	SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_EXPECTED);
       
   693 	return;
       
   694 }
       
   695 
       
   696 DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_GETMAP)
       
   697 {
       
   698 	const NetworkClientState *new_cs;
       
   699 
       
   700 	// The client was never joined.. so this is impossible, right?
       
   701 	//  Ignore the packet, give the client a warning, and close his connection
       
   702 	if (cs->status < STATUS_AUTH || cs->has_quit) {
       
   703 		SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_AUTHORIZED);
       
   704 		return;
       
   705 	}
       
   706 
       
   707 	// Check if someone else is receiving the map
       
   708 	FOR_ALL_CLIENTS(new_cs) {
       
   709 		if (new_cs->status == STATUS_MAP) {
       
   710 			// Tell the new client to wait
       
   711 			cs->status = STATUS_MAP_WAIT;
       
   712 			SEND_COMMAND(PACKET_SERVER_WAIT)(cs);
       
   713 			return;
       
   714 		}
       
   715 	}
       
   716 
       
   717 	// We receive a request to upload the map.. give it to the client!
       
   718 	SEND_COMMAND(PACKET_SERVER_MAP)(cs);
       
   719 }
       
   720 
       
   721 DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_MAP_OK)
       
   722 {
       
   723 	// Client has the map, now start syncing
       
   724 	if (cs->status == STATUS_DONE_MAP && !cs->has_quit) {
       
   725 		char client_name[NETWORK_CLIENT_NAME_LENGTH];
       
   726 		NetworkClientState *new_cs;
       
   727 
       
   728 		NetworkGetClientName(client_name, sizeof(client_name), cs);
       
   729 
       
   730 		NetworkTextMessage(NETWORK_ACTION_JOIN, 1, false, client_name, "");
       
   731 
       
   732 		// Mark the client as pre-active, and wait for an ACK
       
   733 		//  so we know he is done loading and in sync with us
       
   734 		cs->status = STATUS_PRE_ACTIVE;
       
   735 		NetworkHandleCommandQueue(cs);
       
   736 		SEND_COMMAND(PACKET_SERVER_FRAME)(cs);
       
   737 		SEND_COMMAND(PACKET_SERVER_SYNC)(cs);
       
   738 
       
   739 		// This is the frame the client receives
       
   740 		//  we need it later on to make sure the client is not too slow
       
   741 		cs->last_frame = _frame_counter;
       
   742 		cs->last_frame_server = _frame_counter;
       
   743 
       
   744 		FOR_ALL_CLIENTS(new_cs) {
       
   745 			if (new_cs->status > STATUS_AUTH) {
       
   746 				SEND_COMMAND(PACKET_SERVER_CLIENT_INFO)(new_cs, DEREF_CLIENT_INFO(cs));
       
   747 				SEND_COMMAND(PACKET_SERVER_JOIN)(new_cs, cs->index);
       
   748 			}
       
   749 		}
       
   750 
       
   751 		if (_network_pause_on_join) {
       
   752 			/* Now pause the game till the client is in sync */
       
   753 			DoCommandP(0, 1, 0, NULL, CMD_PAUSE);
       
   754 
       
   755 			NetworkServer_HandleChat(NETWORK_ACTION_SERVER_MESSAGE, DESTTYPE_BROADCAST, 0, "Game paused (incoming client)", NETWORK_SERVER_INDEX);
       
   756 		}
       
   757 	} else {
       
   758 		// Wrong status for this packet, give a warning to client, and close connection
       
   759 		SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_EXPECTED);
       
   760 	}
       
   761 }
       
   762 
       
   763 /** Enforce the command flags.
       
   764  * Eg a server-only command can only be executed by a server, etc.
       
   765  * @param *cp the commandpacket that is going to be checked
       
   766  * @param *ci client information for debugging output to console
       
   767  */
       
   768 static bool CheckCommandFlags(const CommandPacket *cp, const NetworkClientInfo *ci)
       
   769 {
       
   770 	byte flags = GetCommandFlags(cp->cmd);
       
   771 
       
   772 	if (flags & CMD_SERVER && ci->client_index != NETWORK_SERVER_INDEX) {
       
   773 		IConsolePrintF(_icolour_err, "WARNING: server only command from client %d (IP: %s), kicking...", ci->client_index, GetPlayerIP(ci));
       
   774 		return false;
       
   775 	}
       
   776 
       
   777 	if (flags & CMD_OFFLINE) {
       
   778 		IConsolePrintF(_icolour_err, "WARNING: offline only command from client %d (IP: %s), kicking...", ci->client_index, GetPlayerIP(ci));
       
   779 		return false;
       
   780 	}
       
   781 
       
   782 	return true;
       
   783 }
       
   784 
       
   785 /** The client has done a command and wants us to handle it
       
   786  * @param *cs the connected client that has sent the command
       
   787  * @param *p the packet in which the command was sent
       
   788  */
       
   789 DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_COMMAND)
       
   790 {
       
   791 	NetworkClientState *new_cs;
       
   792 	const NetworkClientInfo *ci;
       
   793 	byte callback;
       
   794 
       
   795 	CommandPacket *cp = malloc(sizeof(CommandPacket));
       
   796 
       
   797 	// The client was never joined.. so this is impossible, right?
       
   798 	//  Ignore the packet, give the client a warning, and close his connection
       
   799 	if (cs->status < STATUS_DONE_MAP || cs->has_quit) {
       
   800 		SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_EXPECTED);
       
   801 		return;
       
   802 	}
       
   803 
       
   804 	cp->player = NetworkRecv_uint8(cs, p);
       
   805 	cp->cmd    = NetworkRecv_uint32(cs, p);
       
   806 	cp->p1     = NetworkRecv_uint32(cs, p);
       
   807 	cp->p2     = NetworkRecv_uint32(cs, p);
       
   808 	cp->tile   = NetworkRecv_uint32(cs, p);
       
   809 	NetworkRecv_string(cs, p, cp->text, lengthof(cp->text));
       
   810 
       
   811 	callback = NetworkRecv_uint8(cs, p);
       
   812 
       
   813 	if (cs->has_quit) return;
       
   814 
       
   815 	ci = DEREF_CLIENT_INFO(cs);
       
   816 
       
   817 	/* Check if cp->cmd is valid */
       
   818 	if (!IsValidCommand(cp->cmd)) {
       
   819 		IConsolePrintF(_icolour_err, "WARNING: invalid command from client %d (IP: %s).", ci->client_index, GetPlayerIP(ci));
       
   820 		SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_EXPECTED);
       
   821 		return;
       
   822 	}
       
   823 
       
   824 	if (!CheckCommandFlags(cp, ci)) {
       
   825 		SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_KICKED);
       
   826 		return;
       
   827 	}
       
   828 
       
   829 	/** Only CMD_PLAYER_CTRL is always allowed, for the rest, playas needs
       
   830 	 * to match the player in the packet. If it doesn't, the client has done
       
   831 	 * something pretty naughty (or a bug), and will be kicked
       
   832 	 */
       
   833 	if (!(cp->cmd == CMD_PLAYER_CTRL && cp->p1 == 0) && ci->client_playas != cp->player) {
       
   834 		IConsolePrintF(_icolour_err, "WARNING: player %d (IP: %s) tried to execute a command as player %d, kicking...",
       
   835 		               ci->client_playas + 1, GetPlayerIP(ci), cp->player + 1);
       
   836 		SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_PLAYER_MISMATCH);
       
   837 		return;
       
   838 	}
       
   839 
       
   840 	/** @todo CMD_PLAYER_CTRL with p1 = 0 announces a new player to the server. To give the
       
   841 	 * player the correct ID, the server injects p2 and executes the command. Any other p1
       
   842 	 * is prohibited. Pretty ugly and should be redone together with its function.
       
   843 	 * @see CmdPlayerCtrl() players.c:655
       
   844 	 */
       
   845 	if (cp->cmd == CMD_PLAYER_CTRL) {
       
   846 		if (cp->p1 != 0) {
       
   847 			SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_CHEATER);
       
   848 			return;
       
   849 		}
       
   850 
       
   851 		/* XXX - Execute the command as a valid player. Normally this would be done by a
       
   852 		 * spectator, but that is not allowed any commands. So do an impersonation. The drawback
       
   853 		 * of this is that the first company's last_built_tile is also updated... */
       
   854 		cp->player = 0;
       
   855 		cp->p2 = cs - _clients; // XXX - UGLY! p2 is mis-used to get the client-id in CmdPlayerCtrl
       
   856 	}
       
   857 
       
   858 	// The frame can be executed in the same frame as the next frame-packet
       
   859 	//  That frame just before that frame is saved in _frame_counter_max
       
   860 	cp->frame = _frame_counter_max + 1;
       
   861 	cp->next  = NULL;
       
   862 
       
   863 	// Queue the command for the clients (are send at the end of the frame
       
   864 	//   if they can handle it ;))
       
   865 	FOR_ALL_CLIENTS(new_cs) {
       
   866 		if (new_cs->status >= STATUS_MAP) {
       
   867 			// Callbacks are only send back to the client who sent them in the
       
   868 			//  first place. This filters that out.
       
   869 			cp->callback = (new_cs != cs) ? 0 : callback;
       
   870 			NetworkAddCommandQueue(new_cs, cp);
       
   871 		}
       
   872 	}
       
   873 
       
   874 	cp->callback = 0;
       
   875 	// Queue the command on the server
       
   876 	if (_local_command_queue == NULL) {
       
   877 		_local_command_queue = cp;
       
   878 	} else {
       
   879 		// Find last packet
       
   880 		CommandPacket *c = _local_command_queue;
       
   881 		while (c->next != NULL) c = c->next;
       
   882 		c->next = cp;
       
   883 	}
       
   884 }
       
   885 
       
   886 DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_ERROR)
       
   887 {
       
   888 	// This packets means a client noticed an error and is reporting this
       
   889 	//  to us. Display the error and report it to the other clients
       
   890 	NetworkClientState *new_cs;
       
   891 	char str[100];
       
   892 	char client_name[NETWORK_CLIENT_NAME_LENGTH];
       
   893 	NetworkErrorCode errorno = NetworkRecv_uint8(cs, p);
       
   894 
       
   895 	// The client was never joined.. thank the client for the packet, but ignore it
       
   896 	if (cs->status < STATUS_DONE_MAP || cs->has_quit) {
       
   897 		cs->has_quit = true;
       
   898 		return;
       
   899 	}
       
   900 
       
   901 	NetworkGetClientName(client_name, sizeof(client_name), cs);
       
   902 
       
   903 	GetNetworkErrorMsg(str, errorno, lastof(str));
       
   904 
       
   905 	DEBUG(net, 2, "'%s' reported an error and is closing its connection (%s)", client_name, str);
       
   906 
       
   907 	NetworkTextMessage(NETWORK_ACTION_LEAVE, 1, false, client_name, "%s", str);
       
   908 
       
   909 	FOR_ALL_CLIENTS(new_cs) {
       
   910 		if (new_cs->status > STATUS_AUTH) {
       
   911 			SEND_COMMAND(PACKET_SERVER_ERROR_QUIT)(new_cs, cs->index, errorno);
       
   912 		}
       
   913 	}
       
   914 
       
   915 	cs->has_quit = true;
       
   916 }
       
   917 
       
   918 DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_QUIT)
       
   919 {
       
   920 	// The client wants to leave. Display this and report it to the other
       
   921 	//  clients.
       
   922 	NetworkClientState *new_cs;
       
   923 	char str[100];
       
   924 	char client_name[NETWORK_CLIENT_NAME_LENGTH];
       
   925 
       
   926 	// The client was never joined.. thank the client for the packet, but ignore it
       
   927 	if (cs->status < STATUS_DONE_MAP || cs->has_quit) {
       
   928 		cs->has_quit = true;
       
   929 		return;
       
   930 	}
       
   931 
       
   932 	NetworkRecv_string(cs, p, str, lengthof(str));
       
   933 
       
   934 	NetworkGetClientName(client_name, sizeof(client_name), cs);
       
   935 
       
   936 	NetworkTextMessage(NETWORK_ACTION_LEAVE, 1, false, client_name, "%s", str);
       
   937 
       
   938 	FOR_ALL_CLIENTS(new_cs) {
       
   939 		if (new_cs->status > STATUS_AUTH) {
       
   940 			SEND_COMMAND(PACKET_SERVER_QUIT)(new_cs, cs->index, str);
       
   941 		}
       
   942 	}
       
   943 
       
   944 	cs->has_quit = true;
       
   945 }
       
   946 
       
   947 DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_ACK)
       
   948 {
       
   949 	uint32 frame = NetworkRecv_uint32(cs, p);
       
   950 
       
   951 	/* The client is trying to catch up with the server */
       
   952 	if (cs->status == STATUS_PRE_ACTIVE) {
       
   953 		/* The client is not yet catched up? */
       
   954 		if (frame + DAY_TICKS < _frame_counter) return;
       
   955 
       
   956 		/* Now he is! Unpause the game */
       
   957 		cs->status = STATUS_ACTIVE;
       
   958 
       
   959 		if (_network_pause_on_join) {
       
   960 			DoCommandP(0, 0, 0, NULL, CMD_PAUSE);
       
   961 			NetworkServer_HandleChat(NETWORK_ACTION_SERVER_MESSAGE, DESTTYPE_BROADCAST, 0, "Game unpaused (client connected)", NETWORK_SERVER_INDEX);
       
   962 		}
       
   963 
       
   964 		CheckMinPlayers();
       
   965 
       
   966 		/* Execute script for, e.g. MOTD */
       
   967 		IConsoleCmdExec("exec scripts/on_server_connect.scr 0");
       
   968 	}
       
   969 
       
   970 	// The client received the frame, make note of it
       
   971 	cs->last_frame = frame;
       
   972 	// With those 2 values we can calculate the lag realtime
       
   973 	cs->last_frame_server = _frame_counter;
       
   974 }
       
   975 
       
   976 
       
   977 
       
   978 void NetworkServer_HandleChat(NetworkAction action, DestType desttype, int dest, const char *msg, uint16 from_index)
       
   979 {
       
   980 	NetworkClientState *cs;
       
   981 	const NetworkClientInfo *ci, *ci_own, *ci_to;
       
   982 
       
   983 	switch (desttype) {
       
   984 	case DESTTYPE_CLIENT:
       
   985 		/* Are we sending to the server? */
       
   986 		if (dest == NETWORK_SERVER_INDEX) {
       
   987 			ci = NetworkFindClientInfoFromIndex(from_index);
       
   988 			/* Display the text locally, and that is it */
       
   989 			if (ci != NULL)
       
   990 				NetworkTextMessage(action, GetDrawStringPlayerColor(ci->client_playas), false, ci->client_name, "%s", msg);
       
   991 		} else {
       
   992 			/* Else find the client to send the message to */
       
   993 			FOR_ALL_CLIENTS(cs) {
       
   994 				if (cs->index == dest) {
       
   995 					SEND_COMMAND(PACKET_SERVER_CHAT)(cs, action, from_index, false, msg);
       
   996 					break;
       
   997 				}
       
   998 			}
       
   999 		}
       
  1000 
       
  1001 		// Display the message locally (so you know you have sent it)
       
  1002 		if (from_index != dest) {
       
  1003 			if (from_index == NETWORK_SERVER_INDEX) {
       
  1004 				ci = NetworkFindClientInfoFromIndex(from_index);
       
  1005 				ci_to = NetworkFindClientInfoFromIndex(dest);
       
  1006 				if (ci != NULL && ci_to != NULL)
       
  1007 					NetworkTextMessage(action, GetDrawStringPlayerColor(ci->client_playas), true, ci_to->client_name, "%s", msg);
       
  1008 			} else {
       
  1009 				FOR_ALL_CLIENTS(cs) {
       
  1010 					if (cs->index == from_index) {
       
  1011 						SEND_COMMAND(PACKET_SERVER_CHAT)(cs, action, dest, true, msg);
       
  1012 						break;
       
  1013 					}
       
  1014 				}
       
  1015 			}
       
  1016 		}
       
  1017 		break;
       
  1018 	case DESTTYPE_TEAM: {
       
  1019 		bool show_local = true; // If this is false, the message is already displayed
       
  1020 														// on the client who did sent it.
       
  1021 		/* Find all clients that belong to this player */
       
  1022 		ci_to = NULL;
       
  1023 		FOR_ALL_CLIENTS(cs) {
       
  1024 			ci = DEREF_CLIENT_INFO(cs);
       
  1025 			if (ci->client_playas == dest) {
       
  1026 				SEND_COMMAND(PACKET_SERVER_CHAT)(cs, action, from_index, false, msg);
       
  1027 				if (cs->index == from_index) show_local = false;
       
  1028 				ci_to = ci; // Remember a client that is in the company for company-name
       
  1029 			}
       
  1030 		}
       
  1031 
       
  1032 		ci = NetworkFindClientInfoFromIndex(from_index);
       
  1033 		ci_own = NetworkFindClientInfoFromIndex(NETWORK_SERVER_INDEX);
       
  1034 		if (ci != NULL && ci_own != NULL && ci_own->client_playas == dest) {
       
  1035 			NetworkTextMessage(action, GetDrawStringPlayerColor(ci->client_playas), false, ci->client_name, "%s", msg);
       
  1036 			if (from_index == NETWORK_SERVER_INDEX) show_local = false;
       
  1037 			ci_to = ci_own;
       
  1038 		}
       
  1039 
       
  1040 		/* There is no such player */
       
  1041 		if (ci_to == NULL) break;
       
  1042 
       
  1043 		// Display the message locally (so you know you have sent it)
       
  1044 		if (ci != NULL && show_local) {
       
  1045 			if (from_index == NETWORK_SERVER_INDEX) {
       
  1046 				char name[NETWORK_NAME_LENGTH];
       
  1047 				StringID str = IsValidPlayer(ci_to->client_playas) ? GetPlayer(ci_to->client_playas)->name_1 : STR_NETWORK_SPECTATORS;
       
  1048 				GetString(name, str, lastof(name));
       
  1049 				NetworkTextMessage(action, GetDrawStringPlayerColor(ci_own->client_playas), true, name, "%s", msg);
       
  1050 			} else {
       
  1051 				FOR_ALL_CLIENTS(cs) {
       
  1052 					if (cs->index == from_index) {
       
  1053 						SEND_COMMAND(PACKET_SERVER_CHAT)(cs, action, ci_to->client_index, true, msg);
       
  1054 					}
       
  1055 				}
       
  1056 			}
       
  1057 		}
       
  1058 		}
       
  1059 		break;
       
  1060 	default:
       
  1061 		DEBUG(net, 0, "[server] received unknown chat destination type %d. Doing broadcast instead", desttype);
       
  1062 		/* fall-through to next case */
       
  1063 	case DESTTYPE_BROADCAST:
       
  1064 		FOR_ALL_CLIENTS(cs) {
       
  1065 			SEND_COMMAND(PACKET_SERVER_CHAT)(cs, action, from_index, false, msg);
       
  1066 		}
       
  1067 		ci = NetworkFindClientInfoFromIndex(from_index);
       
  1068 		if (ci != NULL)
       
  1069 			NetworkTextMessage(action, GetDrawStringPlayerColor(ci->client_playas), false, ci->client_name, "%s", msg);
       
  1070 		break;
       
  1071 	}
       
  1072 }
       
  1073 
       
  1074 DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_CHAT)
       
  1075 {
       
  1076 	NetworkAction action = NetworkRecv_uint8(cs, p);
       
  1077 	DestType desttype = NetworkRecv_uint8(cs, p);
       
  1078 	int dest = NetworkRecv_uint8(cs, p);
       
  1079 	char msg[MAX_TEXT_MSG_LEN];
       
  1080 
       
  1081 	NetworkRecv_string(cs, p, msg, MAX_TEXT_MSG_LEN);
       
  1082 
       
  1083 	NetworkServer_HandleChat(action, desttype, dest, msg, cs->index);
       
  1084 }
       
  1085 
       
  1086 DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_SET_PASSWORD)
       
  1087 {
       
  1088 	char password[NETWORK_PASSWORD_LENGTH];
       
  1089 	const NetworkClientInfo *ci;
       
  1090 
       
  1091 	NetworkRecv_string(cs, p, password, sizeof(password));
       
  1092 	ci = DEREF_CLIENT_INFO(cs);
       
  1093 
       
  1094 	if (IsValidPlayer(ci->client_playas)) {
       
  1095 		ttd_strlcpy(_network_player_info[ci->client_playas].password, password, sizeof(_network_player_info[0].password));
       
  1096 	}
       
  1097 }
       
  1098 
       
  1099 DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_SET_NAME)
       
  1100 {
       
  1101 	char client_name[NETWORK_CLIENT_NAME_LENGTH];
       
  1102 	NetworkClientInfo *ci;
       
  1103 
       
  1104 	NetworkRecv_string(cs, p, client_name, sizeof(client_name));
       
  1105 	ci = DEREF_CLIENT_INFO(cs);
       
  1106 
       
  1107 	if (cs->has_quit) return;
       
  1108 
       
  1109 	if (ci != NULL) {
       
  1110 		// Display change
       
  1111 		if (NetworkFindName(client_name)) {
       
  1112 			NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, 1, false, ci->client_name, "%s", client_name);
       
  1113 			ttd_strlcpy(ci->client_name, client_name, sizeof(ci->client_name));
       
  1114 			NetworkUpdateClientInfo(ci->client_index);
       
  1115 		}
       
  1116 	}
       
  1117 }
       
  1118 
       
  1119 DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_RCON)
       
  1120 {
       
  1121 	char pass[NETWORK_PASSWORD_LENGTH];
       
  1122 	char command[NETWORK_RCONCOMMAND_LENGTH];
       
  1123 
       
  1124 	if (_network_game_info.rcon_password[0] == '\0') return;
       
  1125 
       
  1126 	NetworkRecv_string(cs, p, pass, sizeof(pass));
       
  1127 	NetworkRecv_string(cs, p, command, sizeof(command));
       
  1128 
       
  1129 	if (strcmp(pass, _network_game_info.rcon_password) != 0) {
       
  1130 		DEBUG(net, 0, "[rcon] wrong password from client-id %d", cs->index);
       
  1131 		return;
       
  1132 	}
       
  1133 
       
  1134 	DEBUG(net, 0, "[rcon] client-id %d executed: '%s'", cs->index, command);
       
  1135 
       
  1136 	_redirect_console_to_client = cs->index;
       
  1137 	IConsoleCmdExec(command);
       
  1138 	_redirect_console_to_client = 0;
       
  1139 	return;
       
  1140 }
       
  1141 
       
  1142 // The layout for the receive-functions by the server
       
  1143 typedef void NetworkServerPacket(NetworkClientState *cs, Packet *p);
       
  1144 
       
  1145 
       
  1146 // This array matches PacketType. At an incoming
       
  1147 //  packet it is matches against this array
       
  1148 //  and that way the right function to handle that
       
  1149 //  packet is found.
       
  1150 static NetworkServerPacket* const _network_server_packet[] = {
       
  1151 	NULL, /*PACKET_SERVER_FULL,*/
       
  1152 	NULL, /*PACKET_SERVER_BANNED,*/
       
  1153 	RECEIVE_COMMAND(PACKET_CLIENT_JOIN),
       
  1154 	NULL, /*PACKET_SERVER_ERROR,*/
       
  1155 	RECEIVE_COMMAND(PACKET_CLIENT_COMPANY_INFO),
       
  1156 	NULL, /*PACKET_SERVER_COMPANY_INFO,*/
       
  1157 	NULL, /*PACKET_SERVER_CLIENT_INFO,*/
       
  1158 	NULL, /*PACKET_SERVER_NEED_PASSWORD,*/
       
  1159 	RECEIVE_COMMAND(PACKET_CLIENT_PASSWORD),
       
  1160 	NULL, /*PACKET_SERVER_WELCOME,*/
       
  1161 	RECEIVE_COMMAND(PACKET_CLIENT_GETMAP),
       
  1162 	NULL, /*PACKET_SERVER_WAIT,*/
       
  1163 	NULL, /*PACKET_SERVER_MAP,*/
       
  1164 	RECEIVE_COMMAND(PACKET_CLIENT_MAP_OK),
       
  1165 	NULL, /*PACKET_SERVER_JOIN,*/
       
  1166 	NULL, /*PACKET_SERVER_FRAME,*/
       
  1167 	NULL, /*PACKET_SERVER_SYNC,*/
       
  1168 	RECEIVE_COMMAND(PACKET_CLIENT_ACK),
       
  1169 	RECEIVE_COMMAND(PACKET_CLIENT_COMMAND),
       
  1170 	NULL, /*PACKET_SERVER_COMMAND,*/
       
  1171 	RECEIVE_COMMAND(PACKET_CLIENT_CHAT),
       
  1172 	NULL, /*PACKET_SERVER_CHAT,*/
       
  1173 	RECEIVE_COMMAND(PACKET_CLIENT_SET_PASSWORD),
       
  1174 	RECEIVE_COMMAND(PACKET_CLIENT_SET_NAME),
       
  1175 	RECEIVE_COMMAND(PACKET_CLIENT_QUIT),
       
  1176 	RECEIVE_COMMAND(PACKET_CLIENT_ERROR),
       
  1177 	NULL, /*PACKET_SERVER_QUIT,*/
       
  1178 	NULL, /*PACKET_SERVER_ERROR_QUIT,*/
       
  1179 	NULL, /*PACKET_SERVER_SHUTDOWN,*/
       
  1180 	NULL, /*PACKET_SERVER_NEWGAME,*/
       
  1181 	NULL, /*PACKET_SERVER_RCON,*/
       
  1182 	RECEIVE_COMMAND(PACKET_CLIENT_RCON),
       
  1183 };
       
  1184 
       
  1185 // If this fails, check the array above with network_data.h
       
  1186 assert_compile(lengthof(_network_server_packet) == PACKET_END);
       
  1187 
       
  1188 // This update the company_info-stuff
       
  1189 void NetworkPopulateCompanyInfo(void)
       
  1190 {
       
  1191 	char password[NETWORK_PASSWORD_LENGTH];
       
  1192 	const Player *p;
       
  1193 	const Vehicle *v;
       
  1194 	const Station *s;
       
  1195 	const NetworkClientState *cs;
       
  1196 	const NetworkClientInfo *ci;
       
  1197 	uint i;
       
  1198 	uint16 months_empty;
       
  1199 
       
  1200 	FOR_ALL_PLAYERS(p) {
       
  1201 		if (!p->is_active) {
       
  1202 			memset(&_network_player_info[p->index], 0, sizeof(NetworkPlayerInfo));
       
  1203 			continue;
       
  1204 		}
       
  1205 
       
  1206 		// Clean the info but not the password
       
  1207 		ttd_strlcpy(password, _network_player_info[p->index].password, sizeof(password));
       
  1208 		months_empty = _network_player_info[p->index].months_empty;
       
  1209 		memset(&_network_player_info[p->index], 0, sizeof(NetworkPlayerInfo));
       
  1210 		_network_player_info[p->index].months_empty = months_empty;
       
  1211 		ttd_strlcpy(_network_player_info[p->index].password, password, sizeof(_network_player_info[p->index].password));
       
  1212 
       
  1213 		// Grap the company name
       
  1214 		SetDParam(0, p->name_1);
       
  1215 		SetDParam(1, p->name_2);
       
  1216 		GetString(_network_player_info[p->index].company_name, STR_JUST_STRING, lastof(_network_player_info[p->index].company_name));
       
  1217 
       
  1218 		// Check the income
       
  1219 		if (_cur_year - 1 == p->inaugurated_year) {
       
  1220 			// The player is here just 1 year, so display [2], else display[1]
       
  1221 			for (i = 0; i < lengthof(p->yearly_expenses[2]); i++) {
       
  1222 				_network_player_info[p->index].income -= p->yearly_expenses[2][i];
       
  1223 			}
       
  1224 		} else {
       
  1225 			for (i = 0; i < lengthof(p->yearly_expenses[1]); i++) {
       
  1226 				_network_player_info[p->index].income -= p->yearly_expenses[1][i];
       
  1227 			}
       
  1228 		}
       
  1229 
       
  1230 		// Set some general stuff
       
  1231 		_network_player_info[p->index].inaugurated_year = p->inaugurated_year;
       
  1232 		_network_player_info[p->index].company_value = p->old_economy[0].company_value;
       
  1233 		_network_player_info[p->index].money = p->money64;
       
  1234 		_network_player_info[p->index].performance = p->old_economy[0].performance_history;
       
  1235 	}
       
  1236 
       
  1237 	// Go through all vehicles and count the type of vehicles
       
  1238 	FOR_ALL_VEHICLES(v) {
       
  1239 		if (!IsValidPlayer(v->owner)) continue;
       
  1240 
       
  1241 		switch (v->type) {
       
  1242 			case VEH_Train:
       
  1243 				if (IsFrontEngine(v)) _network_player_info[v->owner].num_vehicle[0]++;
       
  1244 				break;
       
  1245 
       
  1246 			case VEH_Road:
       
  1247 				if (v->cargo_type != CT_PASSENGERS) {
       
  1248 					_network_player_info[v->owner].num_vehicle[1]++;
       
  1249 				} else {
       
  1250 					_network_player_info[v->owner].num_vehicle[2]++;
       
  1251 				}
       
  1252 				break;
       
  1253 
       
  1254 			case VEH_Aircraft:
       
  1255 				if (v->subtype <= 2) _network_player_info[v->owner].num_vehicle[3]++;
       
  1256 				break;
       
  1257 
       
  1258 			case VEH_Ship:
       
  1259 				_network_player_info[v->owner].num_vehicle[4]++;
       
  1260 				break;
       
  1261 
       
  1262 			case VEH_Special:
       
  1263 			case VEH_Disaster:
       
  1264 				break;
       
  1265 		}
       
  1266 	}
       
  1267 
       
  1268 	// Go through all stations and count the types of stations
       
  1269 	FOR_ALL_STATIONS(s) {
       
  1270 		if (IsValidPlayer(s->owner)) {
       
  1271 			NetworkPlayerInfo *npi = &_network_player_info[s->owner];
       
  1272 
       
  1273 			if (s->facilities & FACIL_TRAIN)      npi->num_station[0]++;
       
  1274 			if (s->facilities & FACIL_TRUCK_STOP) npi->num_station[1]++;
       
  1275 			if (s->facilities & FACIL_BUS_STOP)   npi->num_station[2]++;
       
  1276 			if (s->facilities & FACIL_AIRPORT)    npi->num_station[3]++;
       
  1277 			if (s->facilities & FACIL_DOCK)       npi->num_station[4]++;
       
  1278 		}
       
  1279 	}
       
  1280 
       
  1281 	ci = NetworkFindClientInfoFromIndex(NETWORK_SERVER_INDEX);
       
  1282 	// Register local player (if not dedicated)
       
  1283 	if (ci != NULL && IsValidPlayer(ci->client_playas))
       
  1284 		ttd_strlcpy(_network_player_info[ci->client_playas].players, ci->client_name, sizeof(_network_player_info[0].players));
       
  1285 
       
  1286 	FOR_ALL_CLIENTS(cs) {
       
  1287 		char client_name[NETWORK_CLIENT_NAME_LENGTH];
       
  1288 
       
  1289 		NetworkGetClientName(client_name, sizeof(client_name), cs);
       
  1290 
       
  1291 		ci = DEREF_CLIENT_INFO(cs);
       
  1292 		if (ci != NULL && IsValidPlayer(ci->client_playas)) {
       
  1293 			if (strlen(_network_player_info[ci->client_playas].players) != 0)
       
  1294 				ttd_strlcat(_network_player_info[ci->client_playas].players, ", ", lengthof(_network_player_info[0].players));
       
  1295 
       
  1296 			ttd_strlcat(_network_player_info[ci->client_playas].players, client_name, lengthof(_network_player_info[0].players));
       
  1297 		}
       
  1298 	}
       
  1299 }
       
  1300 
       
  1301 // Send a packet to all clients with updated info about this client_index
       
  1302 void NetworkUpdateClientInfo(uint16 client_index)
       
  1303 {
       
  1304 	NetworkClientState *cs;
       
  1305 	NetworkClientInfo *ci = NetworkFindClientInfoFromIndex(client_index);
       
  1306 
       
  1307 	if (ci == NULL) return;
       
  1308 
       
  1309 	FOR_ALL_CLIENTS(cs) {
       
  1310 		SEND_COMMAND(PACKET_SERVER_CLIENT_INFO)(cs, ci);
       
  1311 	}
       
  1312 }
       
  1313 
       
  1314 /* Check if we want to restart the map */
       
  1315 static void NetworkCheckRestartMap(void)
       
  1316 {
       
  1317 	if (_network_restart_game_year != 0 && _cur_year >= _network_restart_game_year) {
       
  1318 		DEBUG(net, 0, "Auto-restarting map. Year %d reached", _cur_year);
       
  1319 
       
  1320 		StartNewGameWithoutGUI(GENERATE_NEW_SEED);
       
  1321 	}
       
  1322 }
       
  1323 
       
  1324 /* Check if the server has autoclean_companies activated
       
  1325     Two things happen:
       
  1326       1) If a company is not protected, it is closed after 1 year (for example)
       
  1327       2) If a company is protected, protection is disabled after 3 years (for example)
       
  1328            (and item 1. happens a year later) */
       
  1329 static void NetworkAutoCleanCompanies(void)
       
  1330 {
       
  1331 	const NetworkClientState *cs;
       
  1332 	const NetworkClientInfo *ci;
       
  1333 	const Player *p;
       
  1334 	bool clients_in_company[MAX_PLAYERS];
       
  1335 
       
  1336 	if (!_network_autoclean_companies) return;
       
  1337 
       
  1338 	memset(clients_in_company, 0, sizeof(clients_in_company));
       
  1339 
       
  1340 	/* Detect the active companies */
       
  1341 	FOR_ALL_CLIENTS(cs) {
       
  1342 		ci = DEREF_CLIENT_INFO(cs);
       
  1343 		if (IsValidPlayer(ci->client_playas)) clients_in_company[ci->client_playas] = true;
       
  1344 	}
       
  1345 
       
  1346 	if (!_network_dedicated) {
       
  1347 		ci = NetworkFindClientInfoFromIndex(NETWORK_SERVER_INDEX);
       
  1348 		if (IsValidPlayer(ci->client_playas)) clients_in_company[ci->client_playas] = true;
       
  1349 	}
       
  1350 
       
  1351 	/* Go through all the comapnies */
       
  1352 	FOR_ALL_PLAYERS(p) {
       
  1353 		/* Skip the non-active once */
       
  1354 		if (!p->is_active || p->is_ai) continue;
       
  1355 
       
  1356 		if (!clients_in_company[p->index]) {
       
  1357 			/* The company is empty for one month more */
       
  1358 			_network_player_info[p->index].months_empty++;
       
  1359 
       
  1360 			/* Is the company empty for autoclean_unprotected-months, and is there no protection? */
       
  1361 			if (_network_player_info[p->index].months_empty > _network_autoclean_unprotected && _network_player_info[p->index].password[0] == '\0') {
       
  1362 				/* Shut the company down */
       
  1363 				DoCommandP(0, 2, p->index, NULL, CMD_PLAYER_CTRL);
       
  1364 				IConsolePrintF(_icolour_def, "Auto-cleaned company #%d", p->index + 1);
       
  1365 			}
       
  1366 			/* Is the compnay empty for autoclean_protected-months, and there is a protection? */
       
  1367 			if (_network_player_info[p->index].months_empty > _network_autoclean_protected && _network_player_info[p->index].password[0] != '\0') {
       
  1368 				/* Unprotect the company */
       
  1369 				_network_player_info[p->index].password[0] = '\0';
       
  1370 				IConsolePrintF(_icolour_def, "Auto-removed protection from company #%d", p->index+1);
       
  1371 				_network_player_info[p->index].months_empty = 0;
       
  1372 			}
       
  1373 		} else {
       
  1374 			/* It is not empty, reset the date */
       
  1375 			_network_player_info[p->index].months_empty = 0;
       
  1376 		}
       
  1377 	}
       
  1378 }
       
  1379 
       
  1380 // This function changes new_name to a name that is unique (by adding #1 ...)
       
  1381 //  and it returns true if that succeeded.
       
  1382 bool NetworkFindName(char new_name[NETWORK_CLIENT_NAME_LENGTH])
       
  1383 {
       
  1384 	NetworkClientState *new_cs;
       
  1385 	bool found_name = false;
       
  1386 	byte number = 0;
       
  1387 	char original_name[NETWORK_CLIENT_NAME_LENGTH];
       
  1388 
       
  1389 	// We use NETWORK_CLIENT_NAME_LENGTH in here, because new_name is really a pointer
       
  1390 	ttd_strlcpy(original_name, new_name, NETWORK_CLIENT_NAME_LENGTH);
       
  1391 
       
  1392 	while (!found_name) {
       
  1393 		const NetworkClientInfo *ci;
       
  1394 
       
  1395 		found_name = true;
       
  1396 		FOR_ALL_CLIENTS(new_cs) {
       
  1397 			ci = DEREF_CLIENT_INFO(new_cs);
       
  1398 			if (strcmp(ci->client_name, new_name) == 0) {
       
  1399 				// Name already in use
       
  1400 				found_name = false;
       
  1401 				break;
       
  1402 			}
       
  1403 		}
       
  1404 		// Check if it is the same as the server-name
       
  1405 		ci = NetworkFindClientInfoFromIndex(NETWORK_SERVER_INDEX);
       
  1406 		if (ci != NULL) {
       
  1407 			if (strcmp(ci->client_name, new_name) == 0) found_name = false; // name already in use
       
  1408 		}
       
  1409 
       
  1410 		if (!found_name) {
       
  1411 			// Try a new name (<name> #1, <name> #2, and so on)
       
  1412 
       
  1413 			// Stop if we tried for more than 50 times..
       
  1414 			if (number++ > 50) break;
       
  1415 			snprintf(new_name, NETWORK_CLIENT_NAME_LENGTH, "%s #%d", original_name, number);
       
  1416 		}
       
  1417 	}
       
  1418 
       
  1419 	return found_name;
       
  1420 }
       
  1421 
       
  1422 // Reads a packet from the stream
       
  1423 bool NetworkServer_ReadPackets(NetworkClientState *cs)
       
  1424 {
       
  1425 	Packet *p;
       
  1426 	NetworkRecvStatus res;
       
  1427 	while ((p = NetworkRecv_Packet(cs, &res)) != NULL) {
       
  1428 		byte type = NetworkRecv_uint8(cs, p);
       
  1429 		if (type < PACKET_END && _network_server_packet[type] != NULL && !cs->has_quit) {
       
  1430 			_network_server_packet[type](cs, p);
       
  1431 		} else {
       
  1432 			DEBUG(net, 0, "[server] received invalid packet type %d", type);
       
  1433 		}
       
  1434 		free(p);
       
  1435 	}
       
  1436 
       
  1437 	return true;
       
  1438 }
       
  1439 
       
  1440 // Handle the local command-queue
       
  1441 static void NetworkHandleCommandQueue(NetworkClientState* cs)
       
  1442 {
       
  1443 	CommandPacket *cp;
       
  1444 
       
  1445 	while ( (cp = cs->command_queue) != NULL) {
       
  1446 		SEND_COMMAND(PACKET_SERVER_COMMAND)(cs, cp);
       
  1447 
       
  1448 		cs->command_queue = cp->next;
       
  1449 		free(cp);
       
  1450 	}
       
  1451 }
       
  1452 
       
  1453 // This is called every tick if this is a _network_server
       
  1454 void NetworkServer_Tick(bool send_frame)
       
  1455 {
       
  1456 	NetworkClientState *cs;
       
  1457 #ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME
       
  1458 	bool send_sync = false;
       
  1459 #endif
       
  1460 
       
  1461 #ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME
       
  1462 	if (_frame_counter >= _last_sync_frame + _network_sync_freq) {
       
  1463 		_last_sync_frame = _frame_counter;
       
  1464 		send_sync = true;
       
  1465 	}
       
  1466 #endif
       
  1467 
       
  1468 	// Now we are done with the frame, inform the clients that they can
       
  1469 	//  do their frame!
       
  1470 	FOR_ALL_CLIENTS(cs) {
       
  1471 		// Check if the speed of the client is what we can expect from a client
       
  1472 		if (cs->status == STATUS_ACTIVE) {
       
  1473 			// 1 lag-point per day
       
  1474 			int lag = NetworkCalculateLag(cs) / DAY_TICKS;
       
  1475 			if (lag > 0) {
       
  1476 				if (lag > 3) {
       
  1477 					// Client did still not report in after 4 game-day, drop him
       
  1478 					//  (that is, the 3 of above, + 1 before any lag is counted)
       
  1479 					IConsolePrintF(_icolour_err,"Client #%d is dropped because the client did not respond for more than 4 game-days", cs->index);
       
  1480 					NetworkCloseClient(cs);
       
  1481 					continue;
       
  1482 				}
       
  1483 
       
  1484 				// Report once per time we detect the lag
       
  1485 				if (cs->lag_test == 0) {
       
  1486 					IConsolePrintF(_icolour_warn,"[%d] Client #%d is slow, try increasing *net_frame_freq to a higher value!", _frame_counter, cs->index);
       
  1487 					cs->lag_test = 1;
       
  1488 				}
       
  1489 			} else {
       
  1490 				cs->lag_test = 0;
       
  1491 			}
       
  1492 		} else if (cs->status == STATUS_PRE_ACTIVE) {
       
  1493 			int lag = NetworkCalculateLag(cs);
       
  1494 			if (lag > _network_max_join_time) {
       
  1495 				IConsolePrintF(_icolour_err,"Client #%d is dropped because it took longer than %d ticks for him to join", cs->index, _network_max_join_time);
       
  1496 				NetworkCloseClient(cs);
       
  1497 			}
       
  1498 		}
       
  1499 
       
  1500 		if (cs->status >= STATUS_PRE_ACTIVE) {
       
  1501 			// Check if we can send command, and if we have anything in the queue
       
  1502 			NetworkHandleCommandQueue(cs);
       
  1503 
       
  1504 			// Send an updated _frame_counter_max to the client
       
  1505 			if (send_frame) SEND_COMMAND(PACKET_SERVER_FRAME)(cs);
       
  1506 
       
  1507 #ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME
       
  1508 			// Send a sync-check packet
       
  1509 			if (send_sync) SEND_COMMAND(PACKET_SERVER_SYNC)(cs);
       
  1510 #endif
       
  1511 		}
       
  1512 	}
       
  1513 
       
  1514 	/* See if we need to advertise */
       
  1515 	NetworkUDPAdvertise();
       
  1516 }
       
  1517 
       
  1518 void NetworkServerYearlyLoop(void)
       
  1519 {
       
  1520 	NetworkCheckRestartMap();
       
  1521 }
       
  1522 
       
  1523 void NetworkServerMonthlyLoop(void)
       
  1524 {
       
  1525 	NetworkAutoCleanCompanies();
       
  1526 }
       
  1527 
       
  1528 #endif /* ENABLE_NETWORK */