Changeset - r2235:5593fd36d118
[Not reviewed]
master
0 3 0
ludde - 19 years ago 2005-07-29 21:55:49
ludde@openttd.org
(svn r2755) Fix: Fix a desync issue with autoreplace
3 files changed with 10 insertions and 10 deletions:
0 comments (0 inline, 0 general)
network.c
Show inline comments
 
@@ -440,932 +440,939 @@ static NetworkClientState *NetworkAllocC
 
	byte client_no;
 

	
 
	client_no = 0;
 

	
 
	if (_network_server) {
 
		// Can we handle a new client?
 
		if (_network_clients_connected >= MAX_CLIENTS)
 
			return NULL;
 

	
 
		if (_network_game_info.clients_on >= _network_game_info.clients_max)
 
			return NULL;
 

	
 
		// Register the login
 
		client_no = _network_clients_connected++;
 
	}
 

	
 
	cs = &_clients[client_no];
 
	memset(cs, 0, sizeof(*cs));
 
	cs->socket = s;
 
	cs->last_frame = 0;
 
	cs->quited = false;
 

	
 
	cs->last_frame = _frame_counter;
 
	cs->last_frame_server = _frame_counter;
 

	
 
	if (_network_server) {
 
		ci = DEREF_CLIENT_INFO(cs);
 
		memset(ci, 0, sizeof(*ci));
 

	
 
		cs->index = _network_client_index++;
 
		ci->client_index = cs->index;
 
		ci->join_date = _date;
 

	
 
		InvalidateWindow(WC_CLIENT_LIST, 0);
 
	}
 

	
 
	return cs;
 
}
 

	
 
// Close a connection
 
void NetworkCloseClient(NetworkClientState *cs)
 
{
 
	NetworkClientInfo *ci;
 
	// Socket is already dead
 
	if (cs->socket == INVALID_SOCKET) {
 
		cs->quited = true;
 
		return;
 
	}
 

	
 
	DEBUG(net, 1) ("[NET] Closed client connection");
 

	
 
	if (!cs->quited && _network_server && cs->status > STATUS_INACTIVE) {
 
		// We did not receive a leave message from this client...
 
		NetworkErrorCode errorno = NETWORK_ERROR_CONNECTION_LOST;
 
		char str[100];
 
		char client_name[NETWORK_NAME_LENGTH];
 
		NetworkClientState *new_cs;
 

	
 
		NetworkGetClientName(client_name, sizeof(client_name), cs);
 

	
 
		GetString(str, STR_NETWORK_ERR_CLIENT_GENERAL + errorno);
 

	
 
		NetworkTextMessage(NETWORK_ACTION_LEAVE, 1, false, client_name, str);
 

	
 
		// Inform other clients of this... strange leaving ;)
 
		FOR_ALL_CLIENTS(new_cs) {
 
			if (new_cs->status > STATUS_AUTH && cs != new_cs) {
 
				SEND_COMMAND(PACKET_SERVER_ERROR_QUIT)(new_cs, cs->index, errorno);
 
			}
 
		}
 
	}
 

	
 
	/* When the client was PRE_ACTIVE, the server was in pause mode, so unpause */
 
	if (cs->status == STATUS_PRE_ACTIVE && _network_pause_on_join) {
 
		DoCommandP(0, 0, 0, NULL, CMD_PAUSE);
 
		NetworkServer_HandleChat(NETWORK_ACTION_CHAT, DESTTYPE_BROADCAST, 0, "Game unpaused", NETWORK_SERVER_INDEX);
 
	}
 

	
 
	closesocket(cs->socket);
 
	cs->writable = false;
 
	cs->quited = true;
 

	
 
	// Free all pending and partially received packets
 
	while (cs->packet_queue != NULL) {
 
		Packet *p = cs->packet_queue->next;
 
		free(cs->packet_queue);
 
		cs->packet_queue = p;
 
	}
 
	free(cs->packet_recv);
 
	cs->packet_recv = NULL;
 

	
 
	while (cs->command_queue != NULL) {
 
		CommandPacket *p = cs->command_queue->next;
 
		free(cs->command_queue);
 
		cs->command_queue = p;
 
	}
 

	
 
	// Close the gap in the client-list
 
	ci = DEREF_CLIENT_INFO(cs);
 

	
 
	if (_network_server) {
 
		// We just lost one client :(
 
		if (cs->status > STATUS_INACTIVE)
 
			_network_game_info.clients_on--;
 
		_network_clients_connected--;
 

	
 
		while ((cs + 1) != DEREF_CLIENT(MAX_CLIENTS) && (cs + 1)->socket != INVALID_SOCKET) {
 
			*cs = *(cs + 1);
 
			*ci = *(ci + 1);
 
			cs++;
 
			ci++;
 
		}
 

	
 
		InvalidateWindow(WC_CLIENT_LIST, 0);
 
	}
 

	
 
	// Reset the status of the last socket
 
	cs->socket = INVALID_SOCKET;
 
	cs->status = STATUS_INACTIVE;
 
	cs->index = NETWORK_EMPTY_INDEX;
 
	ci->client_index = NETWORK_EMPTY_INDEX;
 
}
 

	
 
// A client wants to connect to a server
 
static bool NetworkConnect(const char *hostname, int port)
 
{
 
	SOCKET s;
 
	struct sockaddr_in sin;
 

	
 
	DEBUG(net, 1) ("[NET] Connecting to %s %d", hostname, port);
 

	
 
	s = socket(AF_INET, SOCK_STREAM, 0);
 
	if (s == INVALID_SOCKET) {
 
		ClientStartError("socket() failed");
 
		return false;
 
	}
 

	
 
	if (!SetNoDelay(s))
 
		DEBUG(net, 1)("[NET] Setting TCP_NODELAY failed");
 

	
 
	sin.sin_family = AF_INET;
 
	sin.sin_addr.s_addr = NetworkResolveHost(hostname);
 
	sin.sin_port = htons(port);
 
	_network_last_host_ip = sin.sin_addr.s_addr;
 

	
 
	if (connect(s, (struct sockaddr*) &sin, sizeof(sin)) != 0) {
 
		// We failed to connect for which reason what so ever
 
		return false;
 
	}
 

	
 
	if (!SetNonBlocking(s))
 
		DEBUG(net, 0)("[NET] Setting non-blocking failed"); // XXX should this be an error?
 

	
 
	// in client mode, only the first client field is used. it's pointing to the server.
 
	NetworkAllocClient(s);
 

	
 
	ShowJoinStatusWindow();
 

	
 
	memcpy(&network_tmp_patches, &_patches, sizeof(_patches));
 

	
 
	return true;
 
}
 

	
 
// For the server, to accept new clients
 
static void NetworkAcceptClients(void)
 
{
 
	struct sockaddr_in sin;
 
	SOCKET s;
 
	NetworkClientState *cs;
 
	uint i;
 
	bool banned;
 

	
 
	// Should never ever happen.. is it possible??
 
	assert(_listensocket != INVALID_SOCKET);
 

	
 
	for (;;) {
 
		socklen_t sin_len;
 

	
 
		sin_len = sizeof(sin);
 
		s = accept(_listensocket, (struct sockaddr*)&sin, &sin_len);
 
		if (s == INVALID_SOCKET) return;
 

	
 
		SetNonBlocking(s); // XXX error handling?
 

	
 
		DEBUG(net, 1) ("[NET] Client connected from %s on frame %d", inet_ntoa(sin.sin_addr), _frame_counter);
 

	
 
		SetNoDelay(s); // XXX error handling?
 

	
 
		/* Check if the client is banned */
 
		banned = false;
 
		for (i = 0; i < lengthof(_network_ban_list); i++) {
 
			if (_network_ban_list[i] == NULL)
 
				continue;
 

	
 
			if (sin.sin_addr.s_addr == inet_addr(_network_ban_list[i])) {
 
				Packet *p = NetworkSend_Init(PACKET_SERVER_BANNED);
 

	
 
				DEBUG(net, 1)("[NET] Banned ip tried to join (%s), refused", _network_ban_list[i]);
 

	
 
				p->buffer[0] = p->size & 0xFF;
 
				p->buffer[1] = p->size >> 8;
 

	
 
				send(s, p->buffer, p->size, 0);
 
				closesocket(s);
 

	
 
				free(p);
 

	
 
				banned = true;
 
				break;
 
			}
 
		}
 
		/* If this client is banned, continue with next client */
 
		if (banned)
 
			continue;
 

	
 
		cs = NetworkAllocClient(s);
 
		if (cs == NULL) {
 
			// no more clients allowed?
 
			// Send to the client that we are full!
 
			Packet *p = NetworkSend_Init(PACKET_SERVER_FULL);
 

	
 
			p->buffer[0] = p->size & 0xFF;
 
			p->buffer[1] = p->size >> 8;
 

	
 
			send(s, p->buffer, p->size, 0);
 
			closesocket(s);
 

	
 
			free(p);
 

	
 
			continue;
 
		}
 

	
 
		// a new client has connected. We set him at inactive for now
 
		//  maybe he is only requesting server-info. Till he has sent a PACKET_CLIENT_MAP_OK
 
		//  the client stays inactive
 
		cs->status = STATUS_INACTIVE;
 

	
 
		{
 
			// Save the IP of the client
 
			NetworkClientInfo *ci;
 
			ci = DEREF_CLIENT_INFO(cs);
 
			ci->client_ip = sin.sin_addr.s_addr;
 
		}
 
	}
 
}
 

	
 
// Set up the listen socket for the server
 
static bool NetworkListen(void)
 
{
 
	SOCKET ls;
 
	struct sockaddr_in sin;
 
	int port;
 

	
 
	port = _network_server_port;
 

	
 
	DEBUG(net, 1) ("[NET] Listening on %s:%d", _network_server_bind_ip_host, port);
 

	
 
	ls = socket(AF_INET, SOCK_STREAM, 0);
 
	if (ls == INVALID_SOCKET) {
 
		ServerStartError("socket() on listen socket failed");
 
		return false;
 
	}
 

	
 
	{ // reuse the socket
 
		int reuse = 1;
 
		// The (const char*) cast is needed for windows!!
 
		if (setsockopt(ls, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuse, sizeof(reuse)) == -1) {
 
			ServerStartError("setsockopt() on listen socket failed");
 
			return false;
 
		}
 
	}
 

	
 
	if (!SetNonBlocking(ls))
 
		DEBUG(net, 0)("[NET] Setting non-blocking failed"); // XXX should this be an error?
 

	
 
	sin.sin_family = AF_INET;
 
	sin.sin_addr.s_addr = _network_server_bind_ip;
 
	sin.sin_port = htons(port);
 

	
 
	if (bind(ls, (struct sockaddr*)&sin, sizeof(sin)) != 0) {
 
		ServerStartError("bind() failed");
 
		return false;
 
	}
 

	
 
	if (listen(ls, 1) != 0) {
 
		ServerStartError("listen() failed");
 
		return false;
 
	}
 

	
 
	_listensocket = ls;
 

	
 
	return true;
 
}
 

	
 
// Close all current connections
 
static void NetworkClose(void)
 
{
 
	NetworkClientState *cs;
 

	
 
	FOR_ALL_CLIENTS(cs) {
 
		if (!_network_server) {
 
			SEND_COMMAND(PACKET_CLIENT_QUIT)("leaving");
 
			NetworkSend_Packets(cs);
 
		}
 
		NetworkCloseClient(cs);
 
	}
 

	
 
	if (_network_server) {
 
		// We are a server, also close the listensocket
 
		closesocket(_listensocket);
 
		_listensocket = INVALID_SOCKET;
 
		DEBUG(net, 1) ("[NET] Closed listener");
 
		NetworkUDPClose();
 
	}
 
}
 

	
 
// Inits the network (cleans sockets and stuff)
 
static void NetworkInitialize(void)
 
{
 
	NetworkClientState *cs;
 

	
 
	_local_command_queue = NULL;
 

	
 
	// Clean all client-sockets
 
	memset(_clients, 0, sizeof(_clients));
 
	for (cs = _clients; cs != &_clients[MAX_CLIENTS]; cs++) {
 
		cs->socket = INVALID_SOCKET;
 
		cs->status = STATUS_INACTIVE;
 
		cs->command_queue = NULL;
 
	}
 

	
 
	// Clean the client_info memory
 
	memset(_network_client_info, 0, sizeof(_network_client_info));
 
	memset(_network_player_info, 0, sizeof(_network_player_info));
 
	_network_lobby_company_count = 0;
 

	
 
	_sync_frame = 0;
 
	_network_first_time = true;
 

	
 
	_network_reconnect = 0;
 

	
 
	NetworkUDPInitialize();
 
}
 

	
 
// Query a server to fetch his game-info
 
//  If game_info is true, only the gameinfo is fetched,
 
//   else only the client_info is fetched
 
NetworkGameList *NetworkQueryServer(const char* host, unsigned short port, bool game_info)
 
{
 
	if (!_network_available) return NULL;
 

	
 
	NetworkDisconnect();
 

	
 
	if (game_info) {
 
		return NetworkUDPQueryServer(host, port);
 
	}
 

	
 
	NetworkInitialize();
 

	
 
	_network_server = false;
 

	
 
	// Try to connect
 
	_networking = NetworkConnect(host, port);
 

	
 
//	ttd_strlcpy(_network_last_host, host, sizeof(_network_last_host));
 
//	_network_last_port = port;
 

	
 
	// We are connected
 
	if (_networking) {
 
		SEND_COMMAND(PACKET_CLIENT_COMPANY_INFO)();
 
		return NULL;
 
	}
 

	
 
	// No networking, close everything down again
 
	NetworkDisconnect();
 
	return NULL;
 
}
 

	
 
/* Validates an address entered as a string and adds the server to
 
 * the list. If you use this functions, the games will be marked
 
 * as manually added. */
 
void NetworkAddServer(const char *b)
 
{
 
	if (*b != '\0') {
 
		NetworkGameList *item;
 
		const char *port = NULL;
 
		const char *player = NULL;
 
		char host[NETWORK_HOSTNAME_LENGTH];
 
		uint16 rport;
 

	
 
		ttd_strlcpy(host, b, lengthof(host));
 

	
 
		ttd_strlcpy(_network_default_ip, b, lengthof(_network_default_ip));
 
		rport = NETWORK_DEFAULT_PORT;
 

	
 
		ParseConnectionString(&player, &port, host);
 

	
 
		if (player != NULL) _network_playas = atoi(player);
 
		if (port != NULL) rport = atoi(port);
 

	
 
		item = NetworkQueryServer(host, rport, true);
 
		item->manually = true;
 
	}
 
}
 

	
 
/* Generates the list of manually added hosts from NetworkGameList and
 
 * dumps them into the array _network_host_list. This array is needed
 
 * by the function that generates the config file. */
 
void NetworkRebuildHostList(void)
 
{
 
	uint i = 0;
 
	NetworkGameList *item = _network_game_list;
 
	while (item != NULL && i != lengthof(_network_host_list)) {
 
		if (item->manually)
 
			_network_host_list[i++] = str_fmt("%s:%i", item->info.hostname, item->port);
 
		item = item->next;
 
	}
 

	
 
	for (; i < lengthof(_network_host_list); i++) {
 
		_network_host_list[i] = strdup("");
 
	}
 
}
 

	
 
// Used by clients, to connect to a server
 
bool NetworkClientConnectGame(const char* host, unsigned short port)
 
{
 
	if (!_network_available) return false;
 

	
 
	if (port == 0) return false;
 

	
 
	ttd_strlcpy(_network_last_host, host, sizeof(_network_last_host));
 
	_network_last_port = port;
 

	
 
	NetworkDisconnect();
 
	NetworkUDPClose();
 
	NetworkInitialize();
 

	
 
	// Try to connect
 
	_networking = NetworkConnect(host, port);
 

	
 
	// We are connected
 
	if (_networking) {
 
		IConsoleCmdExec("exec scripts/on_client.scr 0");
 
		NetworkClient_Connected();
 
	} else {
 
		// Connecting failed
 
		NetworkError(STR_NETWORK_ERR_NOCONNECTION);
 
	}
 

	
 
	return _networking;
 
}
 

	
 
static void NetworkInitGameInfo(void)
 
{
 
	NetworkClientInfo *ci;
 

	
 
	ttd_strlcpy(_network_game_info.server_name, _network_server_name, sizeof(_network_game_info.server_name));
 
	ttd_strlcpy(_network_game_info.server_password, _network_server_password, sizeof(_network_server_password));
 
	ttd_strlcpy(_network_game_info.rcon_password, _network_rcon_password, sizeof(_network_rcon_password));
 
	if (_network_game_info.server_name[0] == '\0')
 
		snprintf(_network_game_info.server_name, sizeof(_network_game_info.server_name), "Unnamed Server");
 

	
 
	// The server is a client too ;)
 
	if (_network_dedicated) {
 
		_network_game_info.clients_on = 0;
 
		_network_game_info.dedicated = true;
 
	} else {
 
		_network_game_info.clients_on = 1;
 
		_network_game_info.dedicated = false;
 
	}
 
	ttd_strlcpy(_network_game_info.server_revision, _openttd_revision, sizeof(_network_game_info.server_revision));
 
	_network_game_info.spectators_on = 0;
 
	_network_game_info.game_date = _date;
 
	_network_game_info.start_date = ConvertIntDate(_patches.starting_date);
 
	_network_game_info.map_width = MapSizeX();
 
	_network_game_info.map_height = MapSizeY();
 
	_network_game_info.map_set = _opt.landscape;
 

	
 
	_network_game_info.use_password = (_network_server_password[0] != '\0');
 

	
 
	// We use _network_client_info[MAX_CLIENT_INFO - 1] to store the server-data in it
 
	//  The index is NETWORK_SERVER_INDEX ( = 1)
 
	ci = &_network_client_info[MAX_CLIENT_INFO - 1];
 
	memset(ci, 0, sizeof(*ci));
 

	
 
	ci->client_index = NETWORK_SERVER_INDEX;
 
	if (_network_dedicated)
 
		ci->client_playas = OWNER_SPECTATOR;
 
	else
 
		ci->client_playas = _local_player + 1;
 
	ttd_strlcpy(ci->client_name, _network_player_name, sizeof(ci->client_name));
 
	ttd_strlcpy(ci->unique_id, _network_unique_id, sizeof(ci->unique_id));
 
}
 

	
 
bool NetworkServerStart(void)
 
{
 
	if (!_network_available) return false;
 

	
 
	/* Call the pre-scripts */
 
	IConsoleCmdExec("exec scripts/pre_server.scr 0");
 
	if (_network_dedicated) IConsoleCmdExec("exec scripts/pre_dedicated.scr 0");
 

	
 
	NetworkInitialize();
 
	if (!NetworkListen())
 
		return false;
 

	
 
	// Try to start UDP-server
 
	_network_udp_server = true;
 
	_network_udp_server = NetworkUDPListen(&_udp_server_socket, _network_server_bind_ip, _network_server_port, false);
 

	
 
	_network_server = true;
 
	_networking = true;
 
	_frame_counter = 0;
 
	_frame_counter_server = 0;
 
	_frame_counter_max = 0;
 
	_last_sync_frame = 0;
 
	_network_own_client_index = NETWORK_SERVER_INDEX;
 

	
 
	if (!_network_dedicated)
 
		_network_playas = 1;
 

	
 
	_network_clients_connected = 0;
 

	
 
	NetworkInitGameInfo();
 

	
 
	// execute server initialization script
 
	IConsoleCmdExec("exec scripts/on_server.scr 0");
 
	// if the server is dedicated ... add some other script
 
	if (_network_dedicated) IConsoleCmdExec("exec scripts/on_dedicated.scr 0");
 

	
 
	/* Try to register us to the master server */
 
	_network_last_advertise_date = 0;
 
	NetworkUDPAdvertise();
 
	return true;
 
}
 

	
 
// The server is rebooting...
 
// The only difference with NetworkDisconnect, is the packets that is sent
 
void NetworkReboot(void)
 
{
 
	if (_network_server) {
 
		NetworkClientState *cs;
 
		FOR_ALL_CLIENTS(cs) {
 
			SEND_COMMAND(PACKET_SERVER_NEWGAME)(cs);
 
			NetworkSend_Packets(cs);
 
		}
 
	}
 

	
 
	NetworkClose();
 

	
 
	// Free all queued commands
 
	while (_local_command_queue != NULL) {
 
		CommandPacket *p = _local_command_queue;
 
		_local_command_queue = _local_command_queue->next;
 
		free(p);
 
	}
 

	
 
	_networking = false;
 
	_network_server = false;
 
}
 

	
 
// We want to disconnect from the host/clients
 
void NetworkDisconnect(void)
 
{
 
	if (_network_server) {
 
		NetworkClientState *cs;
 
		FOR_ALL_CLIENTS(cs) {
 
			SEND_COMMAND(PACKET_SERVER_SHUTDOWN)(cs);
 
			NetworkSend_Packets(cs);
 
		}
 
	}
 

	
 
	if (_network_advertise)
 
		NetworkUDPRemoveAdvertise();
 

	
 
	DeleteWindowById(WC_NETWORK_STATUS_WINDOW, 0);
 

	
 
	NetworkClose();
 

	
 
	// Free all queued commands
 
	while (_local_command_queue != NULL) {
 
		CommandPacket *p = _local_command_queue;
 
		_local_command_queue = _local_command_queue->next;
 
		free(p);
 
	}
 

	
 
	if (_networking && !_network_server) {
 
		memcpy(&_patches, &network_tmp_patches, sizeof(_patches));
 
	}
 

	
 
	_networking = false;
 
	_network_server = false;
 
}
 

	
 
// Receives something from the network
 
static bool NetworkReceive(void)
 
{
 
	NetworkClientState *cs;
 
	int n;
 
	fd_set read_fd, write_fd;
 
	struct timeval tv;
 

	
 
	FD_ZERO(&read_fd);
 
	FD_ZERO(&write_fd);
 

	
 
	FOR_ALL_CLIENTS(cs) {
 
		FD_SET(cs->socket, &read_fd);
 
		FD_SET(cs->socket, &write_fd);
 
	}
 

	
 
	// take care of listener port
 
	if (_network_server) {
 
		FD_SET(_listensocket, &read_fd);
 
	}
 

	
 
	tv.tv_sec = tv.tv_usec = 0; // don't block at all.
 
#if !defined(__MORPHOS__) && !defined(__AMIGA__)
 
	n = select(FD_SETSIZE, &read_fd, &write_fd, NULL, &tv);
 
#else
 
	n = WaitSelect(FD_SETSIZE, &read_fd, &write_fd, NULL, &tv, NULL);
 
#endif
 
	if (n == -1 && !_network_server) NetworkError(STR_NETWORK_ERR_LOSTCONNECTION);
 

	
 
	// accept clients..
 
	if (_network_server && FD_ISSET(_listensocket, &read_fd))
 
		NetworkAcceptClients();
 

	
 
	// read stuff from clients
 
	FOR_ALL_CLIENTS(cs) {
 
		cs->writable = !!FD_ISSET(cs->socket, &write_fd);
 
		if (FD_ISSET(cs->socket, &read_fd)) {
 
			if (_network_server)
 
				NetworkServer_ReadPackets(cs);
 
			else {
 
				byte res;
 
				// The client already was quiting!
 
				if (cs->quited) return false;
 
				if ((res = NetworkClient_ReadPackets(cs)) != NETWORK_RECV_STATUS_OKAY) {
 
					// The client made an error of which we can not recover
 
					//   close the client and drop back to main menu
 

	
 
					NetworkClientError(res, cs);
 
					return false;
 
				}
 
			}
 
		}
 
	}
 
	return true;
 
}
 

	
 
// This sends all buffered commands (if possible)
 
static void NetworkSend(void)
 
{
 
	NetworkClientState *cs;
 
	FOR_ALL_CLIENTS(cs) {
 
		if (cs->writable) {
 
			NetworkSend_Packets(cs);
 

	
 
			if (cs->status == STATUS_MAP) {
 
				// This client is in the middle of a map-send, call the function for that
 
				SEND_COMMAND(PACKET_SERVER_MAP)(cs);
 
			}
 
		}
 
	}
 
}
 

	
 
// Handle the local-command-queue
 
static void NetworkHandleLocalQueue(void)
 
{
 
	CommandPacket *cp, **cp_prev;
 

	
 
	cp_prev = &_local_command_queue;
 

	
 
	while ( (cp = *cp_prev) != NULL) {
 

	
 
		// The queue is always in order, which means
 
		// that the first element will be executed first.
 
		if (_frame_counter < cp->frame)
 
			break;
 

	
 
		if (_frame_counter > cp->frame) {
 
			// If we reach here, it means for whatever reason, we've already executed
 
			// past the command we need to execute.
 
			DEBUG(net, 0)("[NET] Trying to execute a packet in the past!");
 
			assert(0);
 
		}
 

	
 
		// We can execute this command
 
		NetworkExecuteCommand(cp);
 

	
 
		*cp_prev = cp->next;
 
		free(cp);
 
	}
 

	
 
	// Just a safety check, to be removed in the future.
 
	// Make sure that no older command appears towards the end of the queue
 
	// In that case we missed executing it. This will never happen.
 
	for(cp = _local_command_queue; cp; cp = cp->next) {
 
		assert(_frame_counter < cp->frame);
 
	}
 

	
 
}
 

	
 
static bool NetworkDoClientLoop(void)
 
{
 
	_frame_counter++;
 

	
 
	NetworkHandleLocalQueue();
 

	
 
	StateGameLoop();
 

	
 
	// Check if we are in sync!
 
	if (_sync_frame != 0) {
 
		if (_sync_frame == _frame_counter) {
 
#ifdef NETWORK_SEND_DOUBLE_SEED
 
			if (_sync_seed_1 != _random_seeds[0][0] || _sync_seed_2 != _random_seeds[0][1]) {
 
#else
 
			if (_sync_seed_1 != _random_seeds[0][0]) {
 
#endif
 
				NetworkError(STR_NETWORK_ERR_DESYNC);
 
				DEBUG(net, 0)("[NET] Sync error detected!");
 
				NetworkClientError(NETWORK_RECV_STATUS_DESYNC, DEREF_CLIENT(0));
 
				return false;
 
			}
 

	
 
			// If this is the first time we have a sync-frame, we
 
			//   need to let the server know that we are ready and at the same
 
			//   frame as he is.. so we can start playing!
 
			if (_network_first_time) {
 
				_network_first_time = false;
 
				SEND_COMMAND(PACKET_CLIENT_ACK)();
 
			}
 

	
 
			_sync_frame = 0;
 
		} else if (_sync_frame < _frame_counter) {
 
			DEBUG(net, 1)("[NET] Missed frame for sync-test (%d / %d)", _sync_frame, _frame_counter);
 
			_sync_frame = 0;
 
		}
 
	}
 

	
 
	return true;
 
}
 

	
 
// We have to do some UDP checking
 
void NetworkUDPGameLoop(void)
 
{
 
	if (_network_udp_server) {
 
		NetworkUDPReceive(_udp_server_socket);
 
		if (_udp_master_socket != INVALID_SOCKET) {
 
			NetworkUDPReceive(_udp_master_socket);
 
		}
 
	}
 
	else if (_udp_client_socket != INVALID_SOCKET) {
 
		NetworkUDPReceive(_udp_client_socket);
 
		if (_network_udp_broadcast > 0)
 
			_network_udp_broadcast--;
 
	}
 
}
 

	
 
// The main loop called from ttd.c
 
//  Here we also have to do StateGameLoop if needed!
 
void NetworkGameLoop(void)
 
{
 
	if (!_networking) return;
 

	
 
	if (!NetworkReceive()) return;
 

	
 
	if (_network_server) {
 
		bool send_frame = false;
 

	
 
		// We first increase the _frame_counter
 
		_frame_counter++;
 
		// Update max-frame-counter
 
		if (_frame_counter > _frame_counter_max) {
 
			_frame_counter_max = _frame_counter + _network_frame_freq;
 
			send_frame = true;
 
		}
 

	
 
		NetworkHandleLocalQueue();
 

	
 
		// Then we make the frame
 
		StateGameLoop();
 

	
 
		_sync_seed_1 = _random_seeds[0][0];
 
#ifdef NETWORK_SEND_DOUBLE_SEED
 
		_sync_seed_2 = _random_seeds[0][1];
 
#endif
 

	
 
		NetworkServer_Tick();
 
		NetworkServer_Tick(send_frame);
 
	} else {
 
		// Client
 

	
 
		// Make sure we are at the frame were the server is (quick-frames)
 
		if (_frame_counter_server > _frame_counter) {
 
			while (_frame_counter_server > _frame_counter) {
 
				if (!NetworkDoClientLoop()) break;
 
			}
 
		} else {
 
			// Else, keep on going till _frame_counter_max
 
			if (_frame_counter_max > _frame_counter) {
 
				NetworkDoClientLoop();
 
			}
 
		}
 
	}
 

	
 
	NetworkSend();
 
}
 

	
 
static void NetworkGenerateUniqueId(void)
 
{
 
	md5_state_t state;
 
	md5_byte_t digest[16];
 
	char hex_output[16*2 + 1];
 
	char coding_string[NETWORK_NAME_LENGTH];
 
	int di;
 

	
 
	snprintf(coding_string, sizeof(coding_string), "%d%s", (uint)Random(), "OpenTTD Unique ID");
 

	
 
	/* Generate the MD5 hash */
 
	md5_init(&state);
 
	md5_append(&state, coding_string, strlen(coding_string));
 
	md5_finish(&state, digest);
 

	
 
	for (di = 0; di < 16; ++di)
 
		sprintf(hex_output + di * 2, "%02x", digest[di]);
 

	
 
	/* _network_unique_id is our id */
 
	snprintf(_network_unique_id, sizeof(_network_unique_id), "%s", hex_output);
 
}
 

	
 
// This tries to launch the network for a given OS
 
void NetworkStartUp(void)
 
{
 
	DEBUG(net, 3) ("[NET][Core] Starting network...");
 

	
 
	#if defined(__MORPHOS__) || defined(__AMIGA__)
 
	/*
 
	 *  IMPORTANT NOTE: SocketBase needs to be initialized before we use _any_
 
	 *  network related function, else: crash.
 
	 */
 
	{
 
		DEBUG(misc,3) ("[NET][Core] Loading bsd socket library");
 
		if (!(SocketBase = OpenLibrary("bsdsocket.library", 4))) {
 
			DEBUG(net, 0) ("[NET][Core] Error: couldn't open bsdsocket.library version 4. Network not available.");
 
			_network_available = false;
 
			return;
 
		}
 

	
 
		#if defined(__AMIGA__)
 
		// for usleep() implementation (only required for legacy AmigaOS builds)
 
		if ( (TimerPort = CreateMsgPort()) ) {
 
			if ( (TimerRequest = (struct timerequest *) CreateIORequest(TimerPort, sizeof(struct timerequest))) ) {
 
				if ( OpenDevice("timer.device", UNIT_MICROHZ, (struct IORequest *) TimerRequest, 0) == 0 ) {
 
					if ( !(TimerBase = TimerRequest->tr_node.io_Device) ) {
 
						// free ressources...
 
						DEBUG(net, 0) ("[NET][Core] Error: couldn't initialize timer. Network not available.");
 
						_network_available = false;
 
						return;
 
					}
 
				}
 
			}
 
		}
 
		#endif // __AMIGA__
 
	}
 
	#endif // __MORPHOS__ / __AMIGA__
 

	
 
    // Network is available
 
	_network_available = true;
 
	_network_dedicated = false;
 
	_network_last_advertise_date = 0;
 
	_network_advertise_retries = 0;
 

	
 
	/* Load the ip from the openttd.cfg */
 
	_network_server_bind_ip = inet_addr(_network_server_bind_ip_host);
 
	/* And put the data back in it in case it was an invalid ip */
 
	snprintf(_network_server_bind_ip_host, sizeof(_network_server_bind_ip_host), "%s", inet_ntoa(*(struct in_addr *)&_network_server_bind_ip));
 

	
 
	/* Generate an unique id when there is none yet */
 
	if (_network_unique_id[0] == '\0')
 
		NetworkGenerateUniqueId();
 

	
 
	memset(&_network_game_info, 0, sizeof(_network_game_info));
 

	
 
	/* XXX - Hard number here, because the strings can currently handle no more
 
	    than 10 clients -- TrueLight */
 
	_network_game_info.clients_max = 10;
 

	
 
	// Let's load the network in windows
 
	#if defined(WIN32)
 
	{
 
		WSADATA wsa;
 
		DEBUG(net, 3) ("[NET][Core] Loading windows socket library");
 
		if (WSAStartup(MAKEWORD(2,0), &wsa) != 0) {
 
			DEBUG(net, 0) ("[NET][Core] Error: WSAStartup failed. Network not available.");
 
			_network_available = false;
 
			return;
 
		}
 
	}
 
	#endif // WIN32
 

	
 
	NetworkInitialize();
 
	DEBUG(net, 3) ("[NET][Core] Network online. Multiplayer available.");
 
	NetworkFindIPs();
 
}
 

	
 
// This shuts the network down
 
void NetworkShutDown(void)
 
{
 
	DEBUG(net, 3) ("[NET][Core] Shutting down the network.");
 

	
 
	_network_available = false;
 

	
 
	#if defined(__MORPHOS__) || defined(__AMIGA__)
 
	{
 
		// free allocated ressources
 
		#if defined(__AMIGA__)
 
			if (TimerBase)    { CloseDevice((struct IORequest *) TimerRequest); }
 
			if (TimerRequest) { DeleteIORequest(TimerRequest); }
 
			if (TimerPort)    { DeleteMsgPort(TimerPort); }
 
		#endif
 

	
 
		if (SocketBase) {
 
			CloseLibrary(SocketBase);
 
		}
 
	}
 
	#endif
 

	
 
	#if defined(WIN32)
 
	{
 
		WSACleanup();
 
	}
 
	#endif
 
}
 
#else
 

	
 
void ParseConnectionString(const char **player, const char **port, char *connection_string) {}
 
void NetworkUpdateClientInfo(uint16 client_index) {}
 

	
 
#endif /* ENABLE_NETWORK */
network_server.c
Show inline comments
 
@@ -734,852 +734,845 @@ DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT
 
		// Mark the client as pre-active, and wait for an ACK
 
		//  so we know he is done loading and in sync with us
 
		cs->status = STATUS_PRE_ACTIVE;
 
		NetworkHandleCommandQueue(cs);
 
		SEND_COMMAND(PACKET_SERVER_FRAME)(cs);
 
		SEND_COMMAND(PACKET_SERVER_SYNC)(cs);
 

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

	
 
		FOR_ALL_CLIENTS(new_cs) {
 
			if (new_cs->status > STATUS_AUTH) {
 
				SEND_COMMAND(PACKET_SERVER_CLIENT_INFO)(new_cs, DEREF_CLIENT_INFO(cs));
 
				SEND_COMMAND(PACKET_SERVER_JOIN)(new_cs, cs->index);
 
			}
 
		}
 

	
 
		if (_network_pause_on_join) {
 
			/* Now pause the game till the client is in sync */
 
			DoCommandP(0, 1, 0, NULL, CMD_PAUSE);
 

	
 
			NetworkServer_HandleChat(NETWORK_ACTION_CHAT, DESTTYPE_BROADCAST, 0, "Game paused (incoming client)", NETWORK_SERVER_INDEX);
 
		}
 
	} else {
 
		// Wrong status for this packet, give a warning to client, and close connection
 
		SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_EXPECTED);
 
	}
 
}
 

	
 
static inline const char* GetPlayerIP(const NetworkClientInfo *ci) {return inet_ntoa(*(struct in_addr *)&ci->client_ip);}
 

	
 
/** Enforce the command flags.
 
 * Eg a server-only command can only be executed by a server, etc.
 
 * @param *cp the commandpacket that is going to be checked
 
 * @param *ci client information for debugging output to console
 
 */
 
static bool CheckCommandFlags(const CommandPacket *cp, const NetworkClientInfo *ci)
 
{
 
	byte flags = GetCommandFlags(cp->cmd);
 

	
 
	if (flags & CMD_SERVER && ci->client_index != NETWORK_SERVER_INDEX) {
 
		IConsolePrintF(_icolour_err, "WARNING: server only command from player %d (IP: %s), kicking...", ci->client_playas, GetPlayerIP(ci));
 
		return false;
 
	}
 

	
 
	if (flags & CMD_OFFLINE) {
 
		IConsolePrintF(_icolour_err, "WARNING: offline only command from player %d (IP: %s), kicking...", ci->client_playas, GetPlayerIP(ci));
 
		return false;
 
	}
 
	return true;
 
}
 

	
 
/** The client has done a command and wants us to handle it
 
 * @param *cs the connected client that has sent the command
 
 * @param *p the packet in which the command was sent
 
 */
 
DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_COMMAND)
 
{
 
	NetworkClientState *new_cs;
 
	const NetworkClientInfo *ci;
 
	byte callback;
 

	
 
	CommandPacket *cp = malloc(sizeof(CommandPacket));
 

	
 
	// The client was never joined.. so this is impossible, right?
 
	//  Ignore the packet, give the client a warning, and close his connection
 
	if (cs->status < STATUS_DONE_MAP || cs->quited) {
 
		SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_EXPECTED);
 
		return;
 
	}
 

	
 
	cp->player = NetworkRecv_uint8(cs, p);
 
	cp->cmd    = NetworkRecv_uint32(cs, p);
 
	cp->p1     = NetworkRecv_uint32(cs, p);
 
	cp->p2     = NetworkRecv_uint32(cs, p);
 
	cp->tile   = NetworkRecv_uint32(cs, p);
 
	NetworkRecv_string(cs, p, cp->text, lengthof(cp->text));
 

	
 
	callback = NetworkRecv_uint8(cs, p);
 

	
 
	if (cs->quited) return;
 

	
 
	ci = DEREF_CLIENT_INFO(cs);
 

	
 
	/* Check if cp->cmd is valid */
 
	if (!IsValidCommand(cp->cmd)) {
 
		IConsolePrintF(_icolour_err, "WARNING: invalid command from player %d (IP: %s).", ci->client_playas, GetPlayerIP(ci));
 
		SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_EXPECTED);
 
		return;
 
	}
 

	
 
	if (!CheckCommandFlags(cp, ci)) {
 
		SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_KICKED);
 
		return;
 
	}
 

	
 
	/** Only CMD_PLAYER_CTRL is always allowed, for the rest, playas needs
 
	 * to match the player 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_PLAYER_CTRL && cp->p1 == 0) && ci->client_playas - 1 != cp->player) {
 
		IConsolePrintF(_icolour_err, "WARNING: player %d (IP: %s) tried to execute a command as player %d, kicking...",
 
									 ci->client_playas - 1, GetPlayerIP(ci), cp->player);
 
		SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_PLAYER_MISMATCH);
 
		return;
 
	}
 

	
 
	/** @todo CMD_PLAYER_CTRL with p1 = 0 announces a new player to the server. To give the
 
	 * player the correct ID, the server injects p2 and executes the command. Any other p1
 
	 * is prohibited. Pretty ugly and should be redone together with its function.
 
	 * @see CmdPlayerCtrl() players.c:655
 
	 */
 
	if (cp->cmd == CMD_PLAYER_CTRL) {
 
		if (cp->p1 != 0) {
 
			SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_CHEATER);
 
			return;
 
		}
 

	
 
		// XXX - UGLY! p2 is mis-used to get the client-id in CmdPlayerCtrl
 
		cp->p2 = cs - _clients;
 
	}
 

	
 
	// The frame can be executed in the same frame as the next frame-packet
 
	//  That frame just before that frame is saved in _frame_counter_max
 
	cp->frame = _frame_counter_max + 1;
 
	cp->next  = NULL;
 

	
 
	// Queue the command for the clients (are send at the end of the frame
 
	//   if they can handle it ;))
 
	FOR_ALL_CLIENTS(new_cs) {
 
		if (new_cs->status > STATUS_AUTH) {
 
			// Callbacks are only send back to the client who sent them in the
 
			//  first place. This filters that out.
 
			cp->callback = (new_cs != cs) ? 0 : callback;
 
			NetworkAddCommandQueue(new_cs, cp);
 
		}
 
	}
 

	
 
	cp->callback = 0;
 
	// Queue the command on the server
 
	if (_local_command_queue == NULL) {
 
		_local_command_queue = cp;
 
	} else {
 
		// Find last packet
 
		CommandPacket *c = _local_command_queue;
 
		while (c->next != NULL) c = c->next;
 
		c->next = cp;
 
	}
 
}
 

	
 
DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_ERROR)
 
{
 
	// This packets means a client noticed an error and is reporting this
 
	//  to us. Display the error and report it to the other clients
 
	NetworkClientState *new_cs;
 
	byte errorno = NetworkRecv_uint8(cs, p);
 
	char str[100];
 
	char client_name[NETWORK_CLIENT_NAME_LENGTH];
 

	
 
	// The client was never joined.. thank the client for the packet, but ignore it
 
	if (cs->status < STATUS_DONE_MAP || cs->quited) {
 
		cs->quited = true;
 
		return;
 
	}
 

	
 
	NetworkGetClientName(client_name, sizeof(client_name), cs);
 

	
 
	GetString(str, STR_NETWORK_ERR_CLIENT_GENERAL + errorno);
 

	
 
	DEBUG(net, 2)("[NET] %s reported an error and is closing his connection (%s)", client_name, str);
 

	
 
	NetworkTextMessage(NETWORK_ACTION_LEAVE, 1, false, client_name, str);
 

	
 
	FOR_ALL_CLIENTS(new_cs) {
 
		if (new_cs->status > STATUS_AUTH) {
 
			SEND_COMMAND(PACKET_SERVER_ERROR_QUIT)(new_cs, cs->index, errorno);
 
		}
 
	}
 

	
 
	cs->quited = true;
 
}
 

	
 
DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_QUIT)
 
{
 
	// The client wants to leave. Display this and report it to the other
 
	//  clients.
 
	NetworkClientState *new_cs;
 
	char str[100];
 
	char client_name[NETWORK_CLIENT_NAME_LENGTH];
 

	
 
	// The client was never joined.. thank the client for the packet, but ignore it
 
	if (cs->status < STATUS_DONE_MAP || cs->quited) {
 
		cs->quited = true;
 
		return;
 
	}
 

	
 
	NetworkRecv_string(cs, p, str, 100);
 

	
 
	NetworkGetClientName(client_name, sizeof(client_name), cs);
 

	
 
	NetworkTextMessage(NETWORK_ACTION_LEAVE, 1, false, client_name, str);
 

	
 
	FOR_ALL_CLIENTS(new_cs) {
 
		if (new_cs->status > STATUS_AUTH) {
 
			SEND_COMMAND(PACKET_SERVER_QUIT)(new_cs, cs->index, str);
 
		}
 
	}
 

	
 
	cs->quited = true;
 
}
 

	
 
DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_ACK)
 
{
 
	uint32 frame = NetworkRecv_uint32(cs, p);
 

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

	
 
		/* Now he is! Unpause the game */
 
		cs->status = STATUS_ACTIVE;
 

	
 
		if (_network_pause_on_join) {
 
			DoCommandP(0, 0, 0, NULL, CMD_PAUSE);
 
			NetworkServer_HandleChat(NETWORK_ACTION_CHAT, DESTTYPE_BROADCAST, 0, "Game unpaused", NETWORK_SERVER_INDEX);
 
		}
 
	}
 

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

	
 

	
 

	
 
void NetworkServer_HandleChat(NetworkAction action, DestType desttype, int dest, const char *msg, uint16 from_index)
 
{
 
	NetworkClientState *cs;
 
	NetworkClientInfo *ci, *ci_own, *ci_to;
 

	
 
	switch (desttype) {
 
	case DESTTYPE_CLIENT:
 
		/* Are we sending to the server? */
 
		if (dest == NETWORK_SERVER_INDEX) {
 
			ci = NetworkFindClientInfoFromIndex(from_index);
 
			/* Display the text locally, and that is it */
 
			if (ci != NULL)
 
				NetworkTextMessage(action, GetDrawStringPlayerColor(ci->client_playas-1), false, ci->client_name, "%s", msg);
 
		} else {
 
			/* Else find the client to send the message to */
 
			FOR_ALL_CLIENTS(cs) {
 
				if (cs->index == dest) {
 
					SEND_COMMAND(PACKET_SERVER_CHAT)(cs, action, from_index, false, msg);
 
					break;
 
				}
 
			}
 
		}
 

	
 
		// Display the message locally (so you know you have sent it)
 
		if (from_index != dest) {
 
			if (from_index == NETWORK_SERVER_INDEX) {
 
				ci = NetworkFindClientInfoFromIndex(from_index);
 
				ci_to = NetworkFindClientInfoFromIndex(dest);
 
				if (ci != NULL && ci_to != NULL)
 
					NetworkTextMessage(action, GetDrawStringPlayerColor(ci->client_playas-1), true, ci_to->client_name, "%s", msg);
 
			} else {
 
				FOR_ALL_CLIENTS(cs) {
 
					if (cs->index == from_index) {
 
						SEND_COMMAND(PACKET_SERVER_CHAT)(cs, action, dest, true, msg);
 
						break;
 
					}
 
				}
 
			}
 
		}
 
		break;
 
	case DESTTYPE_PLAYER: {
 
		bool show_local = true; // If this is false, the message is already displayed
 
														// on the client who did sent it.
 
		/* Find all clients that belong to this player */
 
		ci_to = NULL;
 
		FOR_ALL_CLIENTS(cs) {
 
			ci = DEREF_CLIENT_INFO(cs);
 
			if (ci->client_playas == dest) {
 
				SEND_COMMAND(PACKET_SERVER_CHAT)(cs, action, from_index, false, msg);
 
				if (cs->index == from_index) {
 
					show_local = false;
 
				}
 
				ci_to = ci; // Remember a client that is in the company for company-name
 
			}
 
		}
 

	
 
		ci = NetworkFindClientInfoFromIndex(from_index);
 
		ci_own = NetworkFindClientInfoFromIndex(NETWORK_SERVER_INDEX);
 
		if (ci != NULL && ci_own != NULL && ci_own->client_playas == dest) {
 
			NetworkTextMessage(action, GetDrawStringPlayerColor(ci->client_playas-1), false, ci->client_name, "%s", msg);
 
			if (from_index == NETWORK_SERVER_INDEX)
 
				show_local = false;
 
			ci_to = ci_own;
 
		}
 

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

	
 
		// Display the message locally (so you know you have sent it)
 
		if (ci != NULL && show_local) {
 
			if (from_index == NETWORK_SERVER_INDEX) {
 
				char name[NETWORK_NAME_LENGTH];
 
				GetString(name, GetPlayer(ci_to->client_playas-1)->name_1);
 
				NetworkTextMessage(action, GetDrawStringPlayerColor(ci_own->client_playas-1), true, name, "%s", msg);
 
			} else {
 
				FOR_ALL_CLIENTS(cs) {
 
					if (cs->index == from_index) {
 
						SEND_COMMAND(PACKET_SERVER_CHAT)(cs, action, ci_to->client_index, true, msg);
 
					}
 
				}
 
			}
 
		}
 
		}
 
		break;
 
	default:
 
		DEBUG(net, 0)("[NET][Server] Received unknown destination type %d. Doing broadcast instead.");
 
		/* fall-through to next case */
 
	case DESTTYPE_BROADCAST:
 
		FOR_ALL_CLIENTS(cs) {
 
			SEND_COMMAND(PACKET_SERVER_CHAT)(cs, action, from_index, false, msg);
 
		}
 
		ci = NetworkFindClientInfoFromIndex(from_index);
 
		if (ci != NULL)
 
			NetworkTextMessage(action, GetDrawStringPlayerColor(ci->client_playas-1), false, ci->client_name, "%s", msg);
 
		break;
 
	}
 
}
 

	
 
DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_CHAT)
 
{
 
	NetworkAction action = NetworkRecv_uint8(cs, p);
 
	DestType desttype = NetworkRecv_uint8(cs, p);
 
	int dest = NetworkRecv_uint8(cs, p);
 
	char msg[MAX_TEXT_MSG_LEN];
 

	
 
	NetworkRecv_string(cs, p, msg, MAX_TEXT_MSG_LEN);
 

	
 
	NetworkServer_HandleChat(action, desttype, dest, msg, cs->index);
 
}
 

	
 
DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_SET_PASSWORD)
 
{
 
	char password[NETWORK_PASSWORD_LENGTH];
 
	NetworkClientInfo *ci;
 

	
 
	NetworkRecv_string(cs, p, password, sizeof(password));
 
	ci = DEREF_CLIENT_INFO(cs);
 

	
 
	if (ci->client_playas <= MAX_PLAYERS) {
 
		ttd_strlcpy(_network_player_info[ci->client_playas - 1].password, password, sizeof(_network_player_info[ci->client_playas - 1].password));
 
	}
 
}
 

	
 
DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_SET_NAME)
 
{
 
	char client_name[NETWORK_CLIENT_NAME_LENGTH];
 
	NetworkClientInfo *ci;
 

	
 
	NetworkRecv_string(cs, p, client_name, sizeof(client_name));
 
	ci = DEREF_CLIENT_INFO(cs);
 

	
 
	if (cs->quited)
 
		return;
 

	
 
	if (ci != NULL) {
 
		// Display change
 
		if (NetworkFindName(client_name)) {
 
			NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, 1, false, ci->client_name, client_name);
 
			ttd_strlcpy(ci->client_name, client_name, sizeof(ci->client_name));
 
			NetworkUpdateClientInfo(ci->client_index);
 
		}
 
	}
 
}
 

	
 
DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_RCON)
 
{
 
	char pass[NETWORK_PASSWORD_LENGTH];
 
	char command[NETWORK_RCONCOMMAND_LENGTH];
 

	
 
	if (_network_game_info.rcon_password[0] == '\0')
 
		return;
 

	
 
	NetworkRecv_string(cs, p, pass, sizeof(pass));
 
	NetworkRecv_string(cs, p, command, sizeof(command));
 

	
 
	if (strncmp(pass, _network_game_info.rcon_password, sizeof(pass)) != 0) {
 
		DEBUG(net, 0)("[RCon] Wrong password from client-id %d", cs->index);
 
		return;
 
	}
 

	
 
	DEBUG(net, 0)("[RCon] Client-id %d executed: %s", cs->index, command);
 

	
 
	_redirect_console_to_client = cs->index;
 
	IConsoleCmdExec(command);
 
	_redirect_console_to_client = 0;
 
	return;
 
}
 

	
 
// The layout for the receive-functions by the server
 
typedef void NetworkServerPacket(NetworkClientState *cs, Packet *p);
 

	
 

	
 
// This array matches PacketType. At an incoming
 
//  packet it is matches against this array
 
//  and that way the right function to handle that
 
//  packet is found.
 
static NetworkServerPacket* const _network_server_packet[] = {
 
	NULL, /*PACKET_SERVER_FULL,*/
 
	NULL, /*PACKET_SERVER_BANNED,*/
 
	RECEIVE_COMMAND(PACKET_CLIENT_JOIN),
 
	NULL, /*PACKET_SERVER_ERROR,*/
 
	RECEIVE_COMMAND(PACKET_CLIENT_COMPANY_INFO),
 
	NULL, /*PACKET_SERVER_COMPANY_INFO,*/
 
	NULL, /*PACKET_SERVER_CLIENT_INFO,*/
 
	NULL, /*PACKET_SERVER_NEED_PASSWORD,*/
 
	RECEIVE_COMMAND(PACKET_CLIENT_PASSWORD),
 
	NULL, /*PACKET_SERVER_WELCOME,*/
 
	RECEIVE_COMMAND(PACKET_CLIENT_GETMAP),
 
	NULL, /*PACKET_SERVER_WAIT,*/
 
	NULL, /*PACKET_SERVER_MAP,*/
 
	RECEIVE_COMMAND(PACKET_CLIENT_MAP_OK),
 
	NULL, /*PACKET_SERVER_JOIN,*/
 
	NULL, /*PACKET_SERVER_FRAME,*/
 
	NULL, /*PACKET_SERVER_SYNC,*/
 
	RECEIVE_COMMAND(PACKET_CLIENT_ACK),
 
	RECEIVE_COMMAND(PACKET_CLIENT_COMMAND),
 
	NULL, /*PACKET_SERVER_COMMAND,*/
 
	RECEIVE_COMMAND(PACKET_CLIENT_CHAT),
 
	NULL, /*PACKET_SERVER_CHAT,*/
 
	RECEIVE_COMMAND(PACKET_CLIENT_SET_PASSWORD),
 
	RECEIVE_COMMAND(PACKET_CLIENT_SET_NAME),
 
	RECEIVE_COMMAND(PACKET_CLIENT_QUIT),
 
	RECEIVE_COMMAND(PACKET_CLIENT_ERROR),
 
	NULL, /*PACKET_SERVER_QUIT,*/
 
	NULL, /*PACKET_SERVER_ERROR_QUIT,*/
 
	NULL, /*PACKET_SERVER_SHUTDOWN,*/
 
	NULL, /*PACKET_SERVER_NEWGAME,*/
 
	NULL, /*PACKET_SERVER_RCON,*/
 
	RECEIVE_COMMAND(PACKET_CLIENT_RCON),
 
};
 

	
 
// If this fails, check the array above with network_data.h
 
assert_compile(lengthof(_network_server_packet) == PACKET_END);
 

	
 

	
 
extern const SettingDesc patch_settings[];
 

	
 
// This is a TEMPORARY solution to get the patch-settings
 
//  to the client. When the patch-settings are saved in the savegame
 
//  this should be removed!!
 
void NetworkSendPatchSettings(NetworkClientState *cs)
 
{
 
	const SettingDesc *item;
 
	Packet *p = NetworkSend_Init(PACKET_SERVER_MAP);
 
	NetworkSend_uint8(p, MAP_PACKET_PATCH);
 
	// Now send all the patch-settings in a pretty order..
 

	
 
	item = patch_settings;
 

	
 
	while (item->name != NULL) {
 
		switch (item->flags) {
 
			case SDT_BOOL:
 
			case SDT_INT8:
 
			case SDT_UINT8:
 
				NetworkSend_uint8(p, *(uint8 *)item->ptr);
 
				break;
 
			case SDT_INT16:
 
			case SDT_UINT16:
 
				NetworkSend_uint16(p, *(uint16 *)item->ptr);
 
				break;
 
			case SDT_INT32:
 
			case SDT_UINT32:
 
				NetworkSend_uint32(p, *(uint32 *)item->ptr);
 
				break;
 
		}
 
		item++;
 
	}
 

	
 
	NetworkSend_Packet(p, cs);
 
}
 

	
 
// This update the company_info-stuff
 
void NetworkPopulateCompanyInfo(void)
 
{
 
	char password[NETWORK_PASSWORD_LENGTH];
 
	Player *p;
 
	Vehicle *v;
 
	Station *s;
 
	NetworkClientState *cs;
 
	NetworkClientInfo *ci;
 
	int i;
 
	uint16 months_empty;
 

	
 
	FOR_ALL_PLAYERS(p) {
 
		if (!p->is_active) {
 
			memset(&_network_player_info[p->index], 0, sizeof(NetworkPlayerInfo));
 
			continue;
 
		}
 

	
 
		// Clean the info but not the password
 
		ttd_strlcpy(password, _network_player_info[p->index].password, sizeof(password));
 
		months_empty = _network_player_info[p->index].months_empty;
 
		memset(&_network_player_info[p->index], 0, sizeof(NetworkPlayerInfo));
 
		_network_player_info[p->index].months_empty = months_empty;
 
		ttd_strlcpy(_network_player_info[p->index].password, password, sizeof(_network_player_info[p->index].password));
 

	
 
		// Grap the company name
 
		SetDParam(0, p->name_1);
 
		SetDParam(1, p->name_2);
 
		GetString(_network_player_info[p->index].company_name, STR_JUST_STRING);
 

	
 
		// Check the income
 
		if (_cur_year - 1 == p->inaugurated_year)
 
			// The player is here just 1 year, so display [2], else display[1]
 
			for (i = 0; i < 13; i++)
 
				_network_player_info[p->index].income -= p->yearly_expenses[2][i];
 
		else
 
			for (i = 0; i < 13; i++)
 
				_network_player_info[p->index].income -= p->yearly_expenses[1][i];
 

	
 
		// Set some general stuff
 
		_network_player_info[p->index].inaugurated_year = p->inaugurated_year;
 
		_network_player_info[p->index].company_value = p->old_economy[0].company_value;
 
		_network_player_info[p->index].money = p->money64;
 
		_network_player_info[p->index].performance = p->old_economy[0].performance_history;
 
	}
 

	
 
	// Go through all vehicles and count the type of vehicles
 
	FOR_ALL_VEHICLES(v) {
 
		if (v->owner < MAX_PLAYERS)
 
			switch (v->type) {
 
				case VEH_Train:
 
					if (v->subtype == TS_Front_Engine)
 
						_network_player_info[v->owner].num_vehicle[0]++;
 
					break;
 
				case VEH_Road:
 
					if (v->cargo_type != CT_PASSENGERS)
 
						_network_player_info[v->owner].num_vehicle[1]++;
 
					else
 
						_network_player_info[v->owner].num_vehicle[2]++;
 
					break;
 
				case VEH_Aircraft:
 
					if (v->subtype <= 2)
 
						_network_player_info[v->owner].num_vehicle[3]++;
 
					break;
 
				case VEH_Ship:
 
					_network_player_info[v->owner].num_vehicle[4]++;
 
					break;
 
				case VEH_Special:
 
				case VEH_Disaster:
 
					break;
 
			}
 
	}
 

	
 
	// Go through all stations and count the types of stations
 
	FOR_ALL_STATIONS(s) {
 
		if (s->owner < MAX_PLAYERS) {
 
			if ((s->facilities & FACIL_TRAIN))
 
				_network_player_info[s->owner].num_station[0]++;
 
			if ((s->facilities & FACIL_TRUCK_STOP))
 
				_network_player_info[s->owner].num_station[1]++;
 
			if ((s->facilities & FACIL_BUS_STOP))
 
				_network_player_info[s->owner].num_station[2]++;
 
			if ((s->facilities & FACIL_AIRPORT))
 
				_network_player_info[s->owner].num_station[3]++;
 
			if ((s->facilities & FACIL_DOCK))
 
				_network_player_info[s->owner].num_station[4]++;
 
		}
 
	}
 

	
 
	ci = NetworkFindClientInfoFromIndex(NETWORK_SERVER_INDEX);
 
	// Register local player (if not dedicated)
 
	if (ci != NULL && ci->client_playas > 0  && ci->client_playas <= MAX_PLAYERS)
 
		ttd_strlcpy(_network_player_info[ci->client_playas-1].players, ci->client_name, sizeof(_network_player_info[ci->client_playas-1].players));
 

	
 
	FOR_ALL_CLIENTS(cs) {
 
		char client_name[NETWORK_CLIENT_NAME_LENGTH];
 

	
 
		NetworkGetClientName(client_name, sizeof(client_name), cs);
 

	
 
		ci = DEREF_CLIENT_INFO(cs);
 
		if (ci != NULL && ci->client_playas > 0 && ci->client_playas <= MAX_PLAYERS) {
 
			if (strlen(_network_player_info[ci->client_playas-1].players) != 0)
 
				ttd_strlcat(_network_player_info[ci->client_playas - 1].players, ", ", lengthof(_network_player_info[ci->client_playas - 1].players));
 

	
 
			ttd_strlcat(_network_player_info[ci->client_playas - 1].players, client_name, lengthof(_network_player_info[ci->client_playas - 1].players));
 
		}
 
	}
 
}
 

	
 
// Send a packet to all clients with updated info about this client_index
 
void NetworkUpdateClientInfo(uint16 client_index)
 
{
 
	NetworkClientState *cs;
 
	NetworkClientInfo *ci;
 

	
 
	ci = NetworkFindClientInfoFromIndex(client_index);
 

	
 
	if (ci == NULL)
 
		return;
 

	
 
	FOR_ALL_CLIENTS(cs) {
 
		SEND_COMMAND(PACKET_SERVER_CLIENT_INFO)(cs, ci);
 
	}
 
}
 

	
 
extern void SwitchMode(int new_mode);
 

	
 
/* Check if we want to restart the map */
 
static void NetworkCheckRestartMap(void)
 
{
 
	if (_network_restart_game_date != 0 && _cur_year + MAX_YEAR_BEGIN_REAL >= _network_restart_game_date) {
 
		_docommand_recursive = 0;
 

	
 
		DEBUG(net, 0)("Auto-restarting map. Year %d reached.", _cur_year + MAX_YEAR_BEGIN_REAL);
 

	
 
		_random_seeds[0][0] = Random();
 
		_random_seeds[0][1] = InteractiveRandom();
 

	
 
		SwitchMode(SM_NEWGAME);
 
	}
 
}
 

	
 
/* 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(void)
 
{
 
	NetworkClientState *cs;
 
	NetworkClientInfo *ci;
 
	Player *p;
 
	bool clients_in_company[MAX_PLAYERS];
 

	
 
	if (!_network_autoclean_companies)
 
		return;
 

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

	
 
	/* Detect the active companies */
 
	FOR_ALL_CLIENTS(cs) {
 
		ci = DEREF_CLIENT_INFO(cs);
 
		if (ci->client_playas >= 1 && ci->client_playas <= MAX_PLAYERS) {
 
			clients_in_company[ci->client_playas-1] = true;
 
		}
 
	}
 
	if (!_network_dedicated) {
 
		ci = NetworkFindClientInfoFromIndex(NETWORK_SERVER_INDEX);
 
		if (ci->client_playas >= 1 && ci->client_playas <= MAX_PLAYERS) {
 
			clients_in_company[ci->client_playas-1] = true;
 
		}
 
	}
 

	
 
	/* Go through all the comapnies */
 
	FOR_ALL_PLAYERS(p) {
 
		/* Skip the non-active once */
 
		if (!p->is_active || p->is_ai)
 
			continue;
 

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

	
 
			/* Is the company empty for autoclean_unprotected-months, and is there no protection? */
 
			if (_network_player_info[p->index].months_empty > _network_autoclean_unprotected && _network_player_info[p->index].password[0] == '\0') {
 
				/* Shut the company down */
 
				DoCommandP(0, 2, p->index, NULL, CMD_PLAYER_CTRL);
 
				IConsolePrintF(_icolour_def, "Auto-cleaned company #%d", p->index+1);
 
			}
 
			/* Is the compnay empty for autoclean_protected-months, and there is a protection? */
 
			if (_network_player_info[p->index].months_empty > _network_autoclean_protected && _network_player_info[p->index].password[0] != '\0') {
 
				/* Unprotect the company */
 
				_network_player_info[p->index].password[0] = '\0';
 
				IConsolePrintF(_icolour_def, "Auto-removed protection from company #%d", p->index+1);
 
				_network_player_info[p->index].months_empty = 0;
 
			}
 
		} else {
 
			/* It is not empty, reset the date */
 
			_network_player_info[p->index].months_empty = 0;
 
		}
 
	}
 
}
 

	
 
// This function changes new_name to a name that is unique (by adding #1 ...)
 
//  and it returns true if that succeeded.
 
bool NetworkFindName(char new_name[NETWORK_CLIENT_NAME_LENGTH])
 
{
 
	NetworkClientState *new_cs;
 
	NetworkClientInfo *ci;
 
	bool found_name = false;
 
	byte number = 0;
 
	char original_name[NETWORK_CLIENT_NAME_LENGTH];
 

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

	
 
	while (!found_name) {
 
		found_name = true;
 
		FOR_ALL_CLIENTS(new_cs) {
 
			ci = DEREF_CLIENT_INFO(new_cs);
 
			if (strncmp(ci->client_name, new_name, NETWORK_CLIENT_NAME_LENGTH) == 0) {
 
				// Name already in use
 
				found_name = false;
 
				break;
 
			}
 
		}
 
		// Check if it is the same as the server-name
 
		ci = NetworkFindClientInfoFromIndex(NETWORK_SERVER_INDEX);
 
		if (ci != NULL) {
 
			if (strncmp(ci->client_name, new_name, NETWORK_CLIENT_NAME_LENGTH) == 0) {
 
				// Name already in use
 
				found_name = false;
 
			}
 
		}
 

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

	
 
			// Stop if we tried for more than 50 times..
 
			if (number++ > 50) break;
 
			snprintf(new_name, NETWORK_CLIENT_NAME_LENGTH, "%s #%d", original_name, number);
 
		}
 
	}
 

	
 
	return found_name;
 
}
 

	
 
// Reads a packet from the stream
 
bool NetworkServer_ReadPackets(NetworkClientState *cs)
 
{
 
	Packet *p;
 
	NetworkRecvStatus res;
 
	while((p = NetworkRecv_Packet(cs, &res)) != NULL) {
 
		byte type = NetworkRecv_uint8(cs, p);
 
		if (type < PACKET_END && _network_server_packet[type] != NULL && !cs->quited)
 
			_network_server_packet[type](cs, p);
 
		else
 
			DEBUG(net, 0)("[NET][Server] Received invalid packet type %d", type);
 
		free(p);
 
	}
 

	
 
	return true;
 
}
 

	
 
// Handle the local command-queue
 
void NetworkHandleCommandQueue(NetworkClientState *cs) {
 
	CommandPacket *cp;
 

	
 
	while ( (cp = cs->command_queue) != NULL) {
 
		SEND_COMMAND(PACKET_SERVER_COMMAND)(cs, cp);
 

	
 
		cs->command_queue = cp->next;
 
		free(cp);
 
	}
 
}
 

	
 
// This is called every tick if this is a _network_server
 
void NetworkServer_Tick(void)
 
void NetworkServer_Tick(bool send_frame)
 
{
 
	NetworkClientState *cs;
 
	bool send_frame = false;
 
#ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME
 
	bool send_sync = false;
 
#endif
 

	
 
	// Update max-frame-counter
 
	if (_frame_counter > _frame_counter_max) {
 
		_frame_counter_max = _frame_counter + _network_frame_freq;
 
		send_frame = true;
 
	}
 

	
 
#ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME
 
	if (_frame_counter >= _last_sync_frame + _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_CLIENTS(cs) {
 
		// Check if the speed of the client is what we can expect from a client
 
		if (cs->status == STATUS_ACTIVE) {
 
			// 1 lag-point per day
 
			int lag = NetworkCalculateLag(cs) / DAY_TICKS;
 
			if (lag > 0) {
 
				if (lag > 3) {
 
					// Client did still not report in after 4 game-day, drop him
 
					//  (that is, the 3 of above, + 1 before any lag is counted)
 
					IConsolePrintF(_icolour_err,"Client #%d is dropped because the client did not respond for more than 4 game-days", cs->index);
 
					NetworkCloseClient(cs);
 
					continue;
 
				}
 

	
 
				// Report once per time we detect the lag
 
				if (cs->lag_test == 0) {
 
					IConsolePrintF(_icolour_warn,"[%d] Client #%d is slow, try increasing *net_frame_freq to a higher value!", _frame_counter, cs->index);
 
					cs->lag_test = 1;
 
				}
 
			} else {
 
				cs->lag_test = 0;
 
			}
 
		} else if (cs->status == STATUS_PRE_ACTIVE) {
 
			int lag = NetworkCalculateLag(cs);
 
			if (lag > _network_max_join_time) {
 
				IConsolePrintF(_icolour_err,"Client #%d is dropped because it took longer than %d ticks for him to join", cs->index, _network_max_join_time);
 
				NetworkCloseClient(cs);
 
			}
 
		}
 

	
 
		if (cs->status >= 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)
 
				SEND_COMMAND(PACKET_SERVER_FRAME)(cs);
 

	
 
#ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME
 
			// Send a sync-check packet
 
			if (send_sync)
 
				SEND_COMMAND(PACKET_SERVER_SYNC)(cs);
 
#endif
 
		}
 
	}
 

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

	
 
void NetworkServerYearlyLoop(void)
 
{
 
	NetworkCheckRestartMap();
 
}
 

	
 
void NetworkServerMonthlyLoop(void)
 
{
 
	NetworkAutoCleanCompanies();
 
}
 

	
 
#endif /* ENABLE_NETWORK */
network_server.h
Show inline comments
 
/* $Id$ */
 

	
 
#ifndef NETWORK_SERVER_H
 
#define NETWORK_SERVER_H
 

	
 
#ifdef ENABLE_NETWORK
 

	
 
DEF_SERVER_SEND_COMMAND(PACKET_SERVER_MAP);
 
DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_ERROR_QUIT)(NetworkClientState *cs, uint16 client_index, NetworkErrorCode errorno);
 
DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_ERROR)(NetworkClientState *cs, NetworkErrorCode error);
 
DEF_SERVER_SEND_COMMAND(PACKET_SERVER_SHUTDOWN);
 
DEF_SERVER_SEND_COMMAND(PACKET_SERVER_NEWGAME);
 
DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_RCON)(NetworkClientState *cs, uint16 color, const char *command);
 

	
 
bool NetworkFindName(char new_name[NETWORK_NAME_LENGTH]);
 
void NetworkServer_HandleChat(NetworkAction action, DestType desttype, int dest, const char *msg, uint16 from_index);
 

	
 
bool NetworkServer_ReadPackets(NetworkClientState *cs);
 
void NetworkServer_Tick(void);
 
void NetworkServer_Tick(bool send_frame);
 
void NetworkServerMonthlyLoop(void);
 
void NetworkServerYearlyLoop(void);
 

	
 
#endif /* ENABLE_NETWORK */
 

	
 
#endif // NETWORK_SERVER_H
0 comments (0 inline, 0 general)