network_udp.c
branchcustombridgeheads
changeset 5642 bfa6074e2833
parent 5641 d4d00a16ef26
child 5643 3778051e8095
equal deleted inserted replaced
5641:d4d00a16ef26 5642:bfa6074e2833
     1 /* $Id$ */
       
     2 
       
     3 #ifdef ENABLE_NETWORK
       
     4 
       
     5 #include "stdafx.h"
       
     6 #include "debug.h"
       
     7 #include "string.h"
       
     8 #include "network_data.h"
       
     9 #include "date.h"
       
    10 #include "map.h"
       
    11 #include "network_gamelist.h"
       
    12 #include "network_udp.h"
       
    13 #include "variables.h"
       
    14 #include "newgrf_config.h"
       
    15 
       
    16 //
       
    17 // This file handles all the LAN-stuff
       
    18 // Stuff like:
       
    19 //   - UDP search over the network
       
    20 //
       
    21 
       
    22 typedef enum {
       
    23 	PACKET_UDP_CLIENT_FIND_SERVER,
       
    24 	PACKET_UDP_SERVER_RESPONSE,
       
    25 	PACKET_UDP_CLIENT_DETAIL_INFO,
       
    26 	PACKET_UDP_SERVER_DETAIL_INFO,   // Is not used in OpenTTD itself, only for external querying
       
    27 	PACKET_UDP_SERVER_REGISTER,      // Packet to register itself to the master server
       
    28 	PACKET_UDP_MASTER_ACK_REGISTER,  // Packet indicating registration has succedeed
       
    29 	PACKET_UDP_CLIENT_GET_LIST,      // Request for serverlist from master server
       
    30 	PACKET_UDP_MASTER_RESPONSE_LIST, // Response from master server with server ip's + port's
       
    31 	PACKET_UDP_SERVER_UNREGISTER,    // Request to be removed from the server-list
       
    32 	PACKET_UDP_CLIENT_GET_NEWGRFS,   // Requests the name for a list of GRFs (GRF_ID and MD5)
       
    33 	PACKET_UDP_SERVER_NEWGRFS,       // Sends the list of NewGRF's requested.
       
    34 	PACKET_UDP_END
       
    35 } PacketUDPType;
       
    36 
       
    37 enum {
       
    38 	ADVERTISE_NORMAL_INTERVAL = 30000, // interval between advertising in ticks (15 minutes)
       
    39 	ADVERTISE_RETRY_INTERVAL  =   300, // readvertise when no response after this many ticks (9 seconds)
       
    40 	ADVERTISE_RETRY_TIMES     =     3  // give up readvertising after this much failed retries
       
    41 };
       
    42 
       
    43 #define DEF_UDP_RECEIVE_COMMAND(type) void NetworkPacketReceive_ ## type ## _command(Packet *p, struct sockaddr_in *client_addr)
       
    44 static void NetworkSendUDP_Packet(SOCKET udp, Packet* p, struct sockaddr_in* recv);
       
    45 
       
    46 static NetworkClientState _udp_cs;
       
    47 
       
    48 /**
       
    49  * Serializes the GRFIdentifier (GRF ID and MD5 checksum) to the packet
       
    50  * @param p the packet to write the data to
       
    51  * @param c the configuration to write the GRF ID and MD5 checksum from
       
    52  */
       
    53 static void NetworkSend_GRFIdentifier(Packet *p, const GRFConfig *c)
       
    54 {
       
    55 	uint j;
       
    56 	NetworkSend_uint32(p, c->grfid);
       
    57 	for (j = 0; j < sizeof(c->md5sum); j++) {
       
    58 		NetworkSend_uint8 (p, c->md5sum[j]);
       
    59 	}
       
    60 }
       
    61 
       
    62 /**
       
    63  * Deserializes the GRFIdentifier (GRF ID and MD5 checksum) from the packet
       
    64  * @param p the packet to read the data from
       
    65  * @param c the configuration to write the GRF ID and MD5 checksum to
       
    66  */
       
    67 static void NetworkRecv_GRFIdentifier(Packet *p, GRFConfig *c)
       
    68 {
       
    69 	uint j;
       
    70 	c->grfid = NetworkRecv_uint32(&_udp_cs, p);
       
    71 	for (j = 0; j < sizeof(c->md5sum); j++) {
       
    72 		c->md5sum[j] = NetworkRecv_uint8(&_udp_cs, p);
       
    73 	}
       
    74 }
       
    75 
       
    76 DEF_UDP_RECEIVE_COMMAND(PACKET_UDP_CLIENT_FIND_SERVER)
       
    77 {
       
    78 	Packet *packet;
       
    79 	// Just a fail-safe.. should never happen
       
    80 	if (!_network_udp_server)
       
    81 		return;
       
    82 
       
    83 	packet = NetworkSend_Init(PACKET_UDP_SERVER_RESPONSE);
       
    84 
       
    85 	// Update some game_info
       
    86 	_network_game_info.game_date = _date;
       
    87 	_network_game_info.map_width = MapSizeX();
       
    88 	_network_game_info.map_height = MapSizeY();
       
    89 	_network_game_info.map_set = _opt.landscape;
       
    90 
       
    91 	NetworkSend_uint8 (packet, NETWORK_GAME_INFO_VERSION);
       
    92 
       
    93 	/* NETWORK_GAME_INFO_VERSION = 4 */
       
    94 	{
       
    95 		/* Only send the GRF Identification (GRF_ID and MD5 checksum) of
       
    96 		 * the GRFs that are needed, i.e. the ones that the server has
       
    97 		 * selected in the NewGRF GUI and not the ones that are used due
       
    98 		 * to the fact that they are in [newgrf-static] in openttd.cfg */
       
    99 		const GRFConfig *c;
       
   100 		uint i = 0;
       
   101 
       
   102 		/* Count number of GRFs to send information about */
       
   103 		for (c = _grfconfig; c != NULL; c = c->next) {
       
   104 			if (!HASBIT(c->flags, GCF_STATIC)) i++;
       
   105 		}
       
   106 		NetworkSend_uint8 (packet, i); // Send number of GRFs
       
   107 
       
   108 		/* Send actual GRF Identifications */
       
   109 		for (c = _grfconfig; c != NULL; c = c->next) {
       
   110 			if (!HASBIT(c->flags, GCF_STATIC)) NetworkSend_GRFIdentifier(packet, c);
       
   111 		}
       
   112 	}
       
   113 
       
   114 	/* NETWORK_GAME_INFO_VERSION = 3 */
       
   115 	NetworkSend_uint32(packet, _network_game_info.game_date);
       
   116 	NetworkSend_uint32(packet, _network_game_info.start_date);
       
   117 
       
   118 	/* NETWORK_GAME_INFO_VERSION = 2 */
       
   119 	NetworkSend_uint8 (packet, _network_game_info.companies_max);
       
   120 	NetworkSend_uint8 (packet, ActivePlayerCount());
       
   121 	NetworkSend_uint8 (packet, _network_game_info.spectators_max);
       
   122 
       
   123 	/* NETWORK_GAME_INFO_VERSION = 1 */
       
   124 	NetworkSend_string(packet, _network_game_info.server_name);
       
   125 	NetworkSend_string(packet, _network_game_info.server_revision);
       
   126 	NetworkSend_uint8 (packet, _network_game_info.server_lang);
       
   127 	NetworkSend_uint8 (packet, _network_game_info.use_password);
       
   128 	NetworkSend_uint8 (packet, _network_game_info.clients_max);
       
   129 	NetworkSend_uint8 (packet, _network_game_info.clients_on);
       
   130 	NetworkSend_uint8 (packet, NetworkSpectatorCount());
       
   131 	NetworkSend_string(packet, _network_game_info.map_name);
       
   132 	NetworkSend_uint16(packet, _network_game_info.map_width);
       
   133 	NetworkSend_uint16(packet, _network_game_info.map_height);
       
   134 	NetworkSend_uint8 (packet, _network_game_info.map_set);
       
   135 	NetworkSend_uint8 (packet, _network_game_info.dedicated);
       
   136 
       
   137 	// Let the client know that we are here
       
   138 	NetworkSendUDP_Packet(_udp_server_socket, packet, client_addr);
       
   139 
       
   140 	free(packet);
       
   141 
       
   142 	DEBUG(net, 2, "[udp] queried from '%s'", inet_ntoa(client_addr->sin_addr));
       
   143 }
       
   144 
       
   145 DEF_UDP_RECEIVE_COMMAND(PACKET_UDP_SERVER_RESPONSE)
       
   146 {
       
   147 	extern const char _openttd_revision[];
       
   148 	NetworkGameList *item;
       
   149 	byte game_info_version;
       
   150 
       
   151 	// Just a fail-safe.. should never happen
       
   152 	if (_network_udp_server)
       
   153 		return;
       
   154 
       
   155 	game_info_version = NetworkRecv_uint8(&_udp_cs, p);
       
   156 
       
   157 	if (_udp_cs.has_quit) return;
       
   158 
       
   159 	DEBUG(net, 4, "[udp] server response from %s:%d", inet_ntoa(client_addr->sin_addr),ntohs(client_addr->sin_port));
       
   160 
       
   161 	// Find next item
       
   162 	item = NetworkGameListAddItem(inet_addr(inet_ntoa(client_addr->sin_addr)), ntohs(client_addr->sin_port));
       
   163 
       
   164 	item->info.compatible = true;
       
   165 	/* Please observer the order. In the order in which packets are sent
       
   166 	 * they are to be received */
       
   167 	switch (game_info_version) {
       
   168 		case 4: {
       
   169 			GRFConfig *c, **dst = &item->info.grfconfig;
       
   170 			const GRFConfig *f;
       
   171 			uint i;
       
   172 			uint num_grfs = NetworkRecv_uint8(&_udp_cs, p);
       
   173 
       
   174 			for (i = 0; i < num_grfs; i++) {
       
   175 				c = calloc(1, sizeof(*c));
       
   176 				NetworkRecv_GRFIdentifier(p, c);
       
   177 
       
   178 				/* Find the matching GRF file */
       
   179 				f = FindGRFConfig(c->grfid, c->md5sum);
       
   180 				if (f == NULL) {
       
   181 					/* Don't know the GRF, so mark game incompatible and the (possibly)
       
   182 					 * already resolved name for this GRF (another server has sent the
       
   183 					 * name of the GRF already */
       
   184 					item->info.compatible = false;
       
   185 					c->name     = FindUnknownGRFName(c->grfid, c->md5sum, true);
       
   186 					SETBIT(c->flags, GCF_NOT_FOUND);
       
   187 				} else {
       
   188 					c->filename = f->filename;
       
   189 					c->name     = f->name;
       
   190 					c->info     = f->info;
       
   191 				}
       
   192 				SETBIT(c->flags, GCF_COPY);
       
   193 
       
   194 				/* Append GRFConfig to the list */
       
   195 				*dst = c;
       
   196 				dst = &c->next;
       
   197 			}
       
   198 		} /* Fallthrough */
       
   199 		case 3:
       
   200 			item->info.game_date     = NetworkRecv_uint32(&_udp_cs, p);
       
   201 			item->info.start_date    = NetworkRecv_uint32(&_udp_cs, p);
       
   202 			/* Fallthrough */
       
   203 		case 2:
       
   204 			item->info.companies_max = NetworkRecv_uint8(&_udp_cs, p);
       
   205 			item->info.companies_on = NetworkRecv_uint8(&_udp_cs, p);
       
   206 			item->info.spectators_max = NetworkRecv_uint8(&_udp_cs, p);
       
   207 			/* Fallthrough */
       
   208 		case 1:
       
   209 			NetworkRecv_string(&_udp_cs, p, item->info.server_name, sizeof(item->info.server_name));
       
   210 			NetworkRecv_string(&_udp_cs, p, item->info.server_revision, sizeof(item->info.server_revision));
       
   211 			item->info.server_lang   = NetworkRecv_uint8(&_udp_cs, p);
       
   212 			item->info.use_password  = NetworkRecv_uint8(&_udp_cs, p);
       
   213 			item->info.clients_max   = NetworkRecv_uint8(&_udp_cs, p);
       
   214 			item->info.clients_on    = NetworkRecv_uint8(&_udp_cs, p);
       
   215 			item->info.spectators_on = NetworkRecv_uint8(&_udp_cs, p);
       
   216 			if (game_info_version < 3) { // 16 bits dates got scrapped and are read earlier
       
   217 				item->info.game_date     = NetworkRecv_uint16(&_udp_cs, p) + DAYS_TILL_ORIGINAL_BASE_YEAR;
       
   218 				item->info.start_date    = NetworkRecv_uint16(&_udp_cs, p) + DAYS_TILL_ORIGINAL_BASE_YEAR;
       
   219 			}
       
   220 			NetworkRecv_string(&_udp_cs, p, item->info.map_name, sizeof(item->info.map_name));
       
   221 			item->info.map_width     = NetworkRecv_uint16(&_udp_cs, p);
       
   222 			item->info.map_height    = NetworkRecv_uint16(&_udp_cs, p);
       
   223 			item->info.map_set       = NetworkRecv_uint8(&_udp_cs, p);
       
   224 			item->info.dedicated     = NetworkRecv_uint8(&_udp_cs, p);
       
   225 
       
   226 			if (item->info.server_lang >= NETWORK_NUM_LANGUAGES) item->info.server_lang = 0;
       
   227 			if (item->info.map_set >= NUM_LANDSCAPE ) item->info.map_set = 0;
       
   228 
       
   229 			if (item->info.hostname[0] == '\0')
       
   230 				snprintf(item->info.hostname, sizeof(item->info.hostname), "%s", inet_ntoa(client_addr->sin_addr));
       
   231 
       
   232 			/* Check if we are allowed on this server based on the revision-match */
       
   233 			item->info.version_compatible =
       
   234 				strcmp(item->info.server_revision, _openttd_revision) == 0 ||
       
   235 				strcmp(item->info.server_revision, NOREV_STRING) == 0;
       
   236 			item->info.compatible &= item->info.version_compatible; // Already contains match for GRFs
       
   237 			break;
       
   238 	}
       
   239 
       
   240 	{
       
   241 		/* Checks whether there needs to be a request for names of GRFs and makes
       
   242 		 * the request if necessary. GRFs that need to be requested are the GRFs
       
   243 		 * that do not exist on the clients system and we do not have the name
       
   244 		 * resolved of, i.e. the name is still UNKNOWN_GRF_NAME_PLACEHOLDER.
       
   245 		 * The in_request array and in_request_count are used so there is no need
       
   246 		 * to do a second loop over the GRF list, which can be relatively expensive
       
   247 		 * due to the string comparisons. */
       
   248 		const GRFConfig *in_request[NETWORK_MAX_GRF_COUNT];
       
   249 		const GRFConfig *c;
       
   250 		uint in_request_count = 0;
       
   251 		struct sockaddr_in out_addr;
       
   252 
       
   253 		for (c = item->info.grfconfig; c != NULL; c = c->next) {
       
   254 			if (!HASBIT(c->flags, GCF_NOT_FOUND) || strcmp(c->name, UNKNOWN_GRF_NAME_PLACEHOLDER) != 0) continue;
       
   255 			in_request[in_request_count] = c;
       
   256 			in_request_count++;
       
   257 		}
       
   258 
       
   259 		if (in_request_count > 0) {
       
   260 			/* There are 'unknown' GRFs, now send a request for them */
       
   261 			uint i;
       
   262 			Packet *packet = NetworkSend_Init(PACKET_UDP_CLIENT_GET_NEWGRFS);
       
   263 
       
   264 			NetworkSend_uint8 (packet, in_request_count);
       
   265 			for (i = 0; i < in_request_count; i++) {
       
   266 				NetworkSend_GRFIdentifier(packet, in_request[i]);
       
   267 			}
       
   268 
       
   269 			out_addr.sin_family      = AF_INET;
       
   270 			out_addr.sin_port        = htons(item->port);
       
   271 			out_addr.sin_addr.s_addr = item->ip;
       
   272 			NetworkSendUDP_Packet(_udp_client_socket, packet, &out_addr);
       
   273 			free(packet);
       
   274 		}
       
   275 	}
       
   276 
       
   277 	item->online = true;
       
   278 
       
   279 	UpdateNetworkGameWindow(false);
       
   280 }
       
   281 
       
   282 DEF_UDP_RECEIVE_COMMAND(PACKET_UDP_CLIENT_DETAIL_INFO)
       
   283 {
       
   284 	NetworkClientState *cs;
       
   285 	NetworkClientInfo *ci;
       
   286 	Packet *packet;
       
   287 	Player *player;
       
   288 	byte current = 0;
       
   289 	int i;
       
   290 
       
   291 	// Just a fail-safe.. should never happen
       
   292 	if (!_network_udp_server) return;
       
   293 
       
   294 	packet = NetworkSend_Init(PACKET_UDP_SERVER_DETAIL_INFO);
       
   295 
       
   296 	/* Send the amount of active companies */
       
   297 	NetworkSend_uint8 (packet, NETWORK_COMPANY_INFO_VERSION);
       
   298 	NetworkSend_uint8 (packet, ActivePlayerCount());
       
   299 
       
   300 	/* Fetch the latest version of everything */
       
   301 	NetworkPopulateCompanyInfo();
       
   302 
       
   303 	/* Go through all the players */
       
   304 	FOR_ALL_PLAYERS(player) {
       
   305 		/* Skip non-active players */
       
   306 		if (!player->is_active) continue;
       
   307 
       
   308 		current++;
       
   309 
       
   310 		/* Send the information */
       
   311 		NetworkSend_uint8(packet, current);
       
   312 
       
   313 		NetworkSend_string(packet, _network_player_info[player->index].company_name);
       
   314 		NetworkSend_uint32(packet, _network_player_info[player->index].inaugurated_year);
       
   315 		NetworkSend_uint64(packet, _network_player_info[player->index].company_value);
       
   316 		NetworkSend_uint64(packet, _network_player_info[player->index].money);
       
   317 		NetworkSend_uint64(packet, _network_player_info[player->index].income);
       
   318 		NetworkSend_uint16(packet, _network_player_info[player->index].performance);
       
   319 
       
   320 		/* Send 1 if there is a passord for the company else send 0 */
       
   321 		if (_network_player_info[player->index].password[0] != '\0') {
       
   322 			NetworkSend_uint8(packet, 1);
       
   323 		} else {
       
   324 			NetworkSend_uint8(packet, 0);
       
   325 		}
       
   326 
       
   327 		for (i = 0; i < NETWORK_VEHICLE_TYPES; i++)
       
   328 			NetworkSend_uint16(packet, _network_player_info[player->index].num_vehicle[i]);
       
   329 
       
   330 		for (i = 0; i < NETWORK_STATION_TYPES; i++)
       
   331 			NetworkSend_uint16(packet, _network_player_info[player->index].num_station[i]);
       
   332 
       
   333 		/* Find the clients that are connected to this player */
       
   334 		FOR_ALL_CLIENTS(cs) {
       
   335 			ci = DEREF_CLIENT_INFO(cs);
       
   336 			if (ci->client_playas == player->index) {
       
   337 				/* The uint8 == 1 indicates that a client is following */
       
   338 				NetworkSend_uint8(packet, 1);
       
   339 				NetworkSend_string(packet, ci->client_name);
       
   340 				NetworkSend_string(packet, ci->unique_id);
       
   341 				NetworkSend_uint32(packet, ci->join_date);
       
   342 			}
       
   343 		}
       
   344 		/* Also check for the server itself */
       
   345 		ci = NetworkFindClientInfoFromIndex(NETWORK_SERVER_INDEX);
       
   346 		if (ci->client_playas == player->index) {
       
   347 			/* The uint8 == 1 indicates that a client is following */
       
   348 			NetworkSend_uint8(packet, 1);
       
   349 			NetworkSend_string(packet, ci->client_name);
       
   350 			NetworkSend_string(packet, ci->unique_id);
       
   351 			NetworkSend_uint32(packet, ci->join_date);
       
   352 		}
       
   353 
       
   354 		/* Indicates end of client list */
       
   355 		NetworkSend_uint8(packet, 0);
       
   356 	}
       
   357 
       
   358 	/* And check if we have any spectators */
       
   359 	FOR_ALL_CLIENTS(cs) {
       
   360 		ci = DEREF_CLIENT_INFO(cs);
       
   361 		if (!IsValidPlayer(ci->client_playas)) {
       
   362 			/* The uint8 == 1 indicates that a client is following */
       
   363 			NetworkSend_uint8(packet, 1);
       
   364 			NetworkSend_string(packet, ci->client_name);
       
   365 			NetworkSend_string(packet, ci->unique_id);
       
   366 			NetworkSend_uint32(packet, ci->join_date);
       
   367 		}
       
   368 	}
       
   369 
       
   370 	/* Also check for the server itself */
       
   371 	ci = NetworkFindClientInfoFromIndex(NETWORK_SERVER_INDEX);
       
   372 	if (!IsValidPlayer(ci->client_playas)) {
       
   373 		/* The uint8 == 1 indicates that a client is following */
       
   374 		NetworkSend_uint8(packet, 1);
       
   375 		NetworkSend_string(packet, ci->client_name);
       
   376 		NetworkSend_string(packet, ci->unique_id);
       
   377 		NetworkSend_uint32(packet, ci->join_date);
       
   378 	}
       
   379 
       
   380 	/* Indicates end of client list */
       
   381 	NetworkSend_uint8(packet, 0);
       
   382 
       
   383 	NetworkSendUDP_Packet(_udp_server_socket, packet, client_addr);
       
   384 
       
   385 	free(packet);
       
   386 }
       
   387 
       
   388 DEF_UDP_RECEIVE_COMMAND(PACKET_UDP_MASTER_RESPONSE_LIST)
       
   389 {
       
   390 	int i;
       
   391 	struct in_addr ip;
       
   392 	uint16 port;
       
   393 	uint8 ver;
       
   394 
       
   395 	/* packet begins with the protocol version (uint8)
       
   396 	 * then an uint16 which indicates how many
       
   397 	 * ip:port pairs are in this packet, after that
       
   398 	 * an uint32 (ip) and an uint16 (port) for each pair
       
   399 	 */
       
   400 
       
   401 	ver = NetworkRecv_uint8(&_udp_cs, p);
       
   402 
       
   403 	if (_udp_cs.has_quit) return;
       
   404 
       
   405 	if (ver == 1) {
       
   406 		for (i = NetworkRecv_uint16(&_udp_cs, p); i != 0 ; i--) {
       
   407 			ip.s_addr = TO_LE32(NetworkRecv_uint32(&_udp_cs, p));
       
   408 			port = NetworkRecv_uint16(&_udp_cs, p);
       
   409 			NetworkUDPQueryServer(inet_ntoa(ip), port);
       
   410 		}
       
   411 	}
       
   412 }
       
   413 
       
   414 DEF_UDP_RECEIVE_COMMAND(PACKET_UDP_MASTER_ACK_REGISTER)
       
   415 {
       
   416 	_network_advertise_retries = 0;
       
   417 	DEBUG(net, 2, "[udp] advertising on master server successfull");
       
   418 
       
   419 	/* We are advertised, but we don't want to! */
       
   420 	if (!_network_advertise) NetworkUDPRemoveAdvertise();
       
   421 }
       
   422 
       
   423 /**
       
   424  * A client has requested the names of some NewGRFs.
       
   425  *
       
   426  * Replying this can be tricky as we have a limit of SEND_MTU bytes
       
   427  * in the reply packet and we can send up to 100 bytes per NewGRF
       
   428  * (GRF ID, MD5sum and NETWORK_GRF_NAME_LENGTH bytes for the name).
       
   429  * As SEND_MTU is _much_ less than 100 * NETWORK_MAX_GRF_COUNT, it
       
   430  * could be that a packet overflows. To stop this we only reply
       
   431  * with the first N NewGRFs so that if the first N + 1 NewGRFs
       
   432  * would be sent, the packet overflows.
       
   433  * in_reply and in_reply_count are used to keep a list of GRFs to
       
   434  * send in the reply.
       
   435  */
       
   436 DEF_UDP_RECEIVE_COMMAND(PACKET_UDP_CLIENT_GET_NEWGRFS)
       
   437 {
       
   438 	uint8 num_grfs;
       
   439 	uint i;
       
   440 
       
   441 	const GRFConfig *in_reply[NETWORK_MAX_GRF_COUNT];
       
   442 	Packet *packet;
       
   443 	uint8 in_reply_count = 0;
       
   444 	uint packet_len = 0;
       
   445 
       
   446 	/* Just a fail-safe.. should never happen */
       
   447 	if (_udp_cs.has_quit) return;
       
   448 
       
   449 	DEBUG(net, 6, "[udp] newgrf data request from %s:%d", inet_ntoa(client_addr->sin_addr), ntohs(client_addr->sin_port));
       
   450 
       
   451 	num_grfs = NetworkRecv_uint8 (&_udp_cs, p);
       
   452 	if (num_grfs > NETWORK_MAX_GRF_COUNT) return;
       
   453 
       
   454 	for (i = 0; i < num_grfs; i++) {
       
   455 		GRFConfig c;
       
   456 		const GRFConfig *f;
       
   457 
       
   458 		NetworkRecv_GRFIdentifier(p, &c);
       
   459 
       
   460 		/* Find the matching GRF file */
       
   461 		f = FindGRFConfig(c.grfid, c.md5sum);
       
   462 		if (f == NULL) continue; // The GRF is unknown to this server
       
   463 
       
   464 		/* If the reply might exceed the size of the packet, only reply
       
   465 		 * the current list and do not send the other data.
       
   466 		 * The name could be an empty string, if so take the filename. */
       
   467 		packet_len += sizeof(c.grfid) + sizeof(c.md5sum) +
       
   468 				min(strlen((f->name != NULL && strlen(f->name) > 0) ? f->name : f->filename) + 1, NETWORK_GRF_NAME_LENGTH);
       
   469 		if (packet_len > SEND_MTU - 4) { // 4 is 3 byte header + grf count in reply
       
   470 			break;
       
   471 		}
       
   472 		in_reply[in_reply_count] = f;
       
   473 		in_reply_count++;
       
   474 	}
       
   475 
       
   476 	if (in_reply_count == 0) return;
       
   477 
       
   478 	packet = NetworkSend_Init(PACKET_UDP_SERVER_NEWGRFS);
       
   479 	NetworkSend_uint8 (packet, in_reply_count);
       
   480 	for (i = 0; i < in_reply_count; i++) {
       
   481 		char name[NETWORK_GRF_NAME_LENGTH];
       
   482 
       
   483 		/* The name could be an empty string, if so take the filename */
       
   484 		ttd_strlcpy(name, (in_reply[i]->name != NULL && strlen(in_reply[i]->name) > 0) ?
       
   485 				in_reply[i]->name : in_reply[i]->filename, sizeof(name));
       
   486 	 	NetworkSend_GRFIdentifier(packet, in_reply[i]);
       
   487 		NetworkSend_string(packet, name);
       
   488 	}
       
   489 
       
   490 	NetworkSendUDP_Packet(_udp_server_socket, packet, client_addr);
       
   491 	free(packet);
       
   492 }
       
   493 
       
   494 /** The return of the client's request of the names of some NewGRFs */
       
   495 DEF_UDP_RECEIVE_COMMAND(PACKET_UDP_SERVER_NEWGRFS)
       
   496 {
       
   497 	uint8 num_grfs;
       
   498 	uint i;
       
   499 
       
   500 	/* Just a fail-safe.. should never happen */
       
   501 	if (_udp_cs.has_quit) return;
       
   502 
       
   503 	DEBUG(net, 6, "[udp] newgrf data reply from %s:%d", inet_ntoa(client_addr->sin_addr),ntohs(client_addr->sin_port));
       
   504 
       
   505 	num_grfs = NetworkRecv_uint8 (&_udp_cs, p);
       
   506 	if (num_grfs > NETWORK_MAX_GRF_COUNT) return;
       
   507 
       
   508 	for (i = 0; i < num_grfs; i++) {
       
   509 		char *unknown_name;
       
   510 		char name[NETWORK_GRF_NAME_LENGTH];
       
   511 		GRFConfig c;
       
   512 
       
   513 		NetworkRecv_GRFIdentifier(p, &c);
       
   514 		NetworkRecv_string(&_udp_cs, p, name, sizeof(name));
       
   515 
       
   516 		/* An empty name is not possible under normal circumstances
       
   517 		 * and causes problems when showing the NewGRF list. */
       
   518 		if (strlen(name) == 0) continue;
       
   519 
       
   520 		/* Finds the fake GRFConfig for the just read GRF ID and MD5sum tuple.
       
   521 		 * If it exists and not resolved yet, then name of the fake GRF is
       
   522 		 * overwritten with the name from the reply. */
       
   523 		unknown_name = FindUnknownGRFName(c.grfid, c.md5sum, false);
       
   524 		if (unknown_name != NULL && strcmp(unknown_name, UNKNOWN_GRF_NAME_PLACEHOLDER) == 0) {
       
   525 			ttd_strlcpy(unknown_name, name, NETWORK_GRF_NAME_LENGTH);
       
   526 		}
       
   527 	}
       
   528 }
       
   529 
       
   530 
       
   531 // The layout for the receive-functions by UDP
       
   532 typedef void NetworkUDPPacket(Packet *p, struct sockaddr_in *client_addr);
       
   533 
       
   534 static NetworkUDPPacket* const _network_udp_packet[] = {
       
   535 	RECEIVE_COMMAND(PACKET_UDP_CLIENT_FIND_SERVER),
       
   536 	RECEIVE_COMMAND(PACKET_UDP_SERVER_RESPONSE),
       
   537 	RECEIVE_COMMAND(PACKET_UDP_CLIENT_DETAIL_INFO),
       
   538 	NULL,
       
   539 	NULL,
       
   540 	RECEIVE_COMMAND(PACKET_UDP_MASTER_ACK_REGISTER),
       
   541 	NULL,
       
   542 	RECEIVE_COMMAND(PACKET_UDP_MASTER_RESPONSE_LIST),
       
   543 	NULL,
       
   544 	RECEIVE_COMMAND(PACKET_UDP_CLIENT_GET_NEWGRFS),
       
   545 	RECEIVE_COMMAND(PACKET_UDP_SERVER_NEWGRFS),
       
   546 };
       
   547 
       
   548 
       
   549 // If this fails, check the array above with network_data.h
       
   550 assert_compile(lengthof(_network_udp_packet) == PACKET_UDP_END);
       
   551 
       
   552 
       
   553 static void NetworkHandleUDPPacket(Packet* p, struct sockaddr_in* client_addr)
       
   554 {
       
   555 	byte type;
       
   556 
       
   557 	/* Fake a client, so we can see when there is an illegal packet */
       
   558 	_udp_cs.socket = INVALID_SOCKET;
       
   559 	_udp_cs.has_quit = false;
       
   560 
       
   561 	type = NetworkRecv_uint8(&_udp_cs, p);
       
   562 
       
   563 	if (type < PACKET_UDP_END && _network_udp_packet[type] != NULL && !_udp_cs.has_quit) {
       
   564 		_network_udp_packet[type](p, client_addr);
       
   565 	} else {
       
   566 		if (!_udp_cs.has_quit) {
       
   567 			DEBUG(net, 0, "[udp] received invalid packet type %d", type);
       
   568 		} else {
       
   569 			DEBUG(net, 0, "[udp] received illegal packet");
       
   570 		}
       
   571 	}
       
   572 }
       
   573 
       
   574 
       
   575 // Send a packet over UDP
       
   576 static void NetworkSendUDP_Packet(SOCKET udp, Packet* p, struct sockaddr_in* recv)
       
   577 {
       
   578 	int res;
       
   579 
       
   580 	// Put the length in the buffer
       
   581 	p->buffer[0] = p->size & 0xFF;
       
   582 	p->buffer[1] = p->size >> 8;
       
   583 
       
   584 	// Send the buffer
       
   585 	res = sendto(udp, p->buffer, p->size, 0, (struct sockaddr *)recv, sizeof(*recv));
       
   586 
       
   587 	// Check for any errors, but ignore it otherwise
       
   588 	if (res == -1) DEBUG(net, 1, "[udp] sendto failed with: %i", GET_LAST_ERROR());
       
   589 }
       
   590 
       
   591 // Start UDP listener
       
   592 bool NetworkUDPListen(SOCKET *udp, uint32 host, uint16 port, bool broadcast)
       
   593 {
       
   594 	struct sockaddr_in sin;
       
   595 
       
   596 	// Make sure socket is closed
       
   597 	closesocket(*udp);
       
   598 
       
   599 	*udp = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
       
   600 	if (*udp == INVALID_SOCKET) {
       
   601 		DEBUG(net, 0, "[udp] failed to start UDP listener");
       
   602 		return false;
       
   603 	}
       
   604 
       
   605 	// set nonblocking mode for socket
       
   606 	{
       
   607 		unsigned long blocking = 1;
       
   608 #ifndef BEOS_NET_SERVER
       
   609 		ioctlsocket(*udp, FIONBIO, &blocking);
       
   610 #else
       
   611 		setsockopt(*udp, SOL_SOCKET, SO_NONBLOCK, &blocking, NULL);
       
   612 #endif
       
   613 	}
       
   614 
       
   615 	sin.sin_family = AF_INET;
       
   616 	// Listen on all IPs
       
   617 	sin.sin_addr.s_addr = host;
       
   618 	sin.sin_port = htons(port);
       
   619 
       
   620 	if (bind(*udp, (struct sockaddr*)&sin, sizeof(sin)) != 0) {
       
   621 		DEBUG(net, 0, "[udp] bind failed on %s:%i", inet_ntoa(*(struct in_addr *)&host), port);
       
   622 		return false;
       
   623 	}
       
   624 
       
   625 	if (broadcast) {
       
   626 		/* Enable broadcast */
       
   627 		unsigned long val = 1;
       
   628 #ifndef BEOS_NET_SERVER // will work around this, some day; maybe.
       
   629 		setsockopt(*udp, SOL_SOCKET, SO_BROADCAST, (char *) &val , sizeof(val));
       
   630 #endif
       
   631 	}
       
   632 
       
   633 	DEBUG(net, 1, "[udp] listening on port %s:%d", inet_ntoa(*(struct in_addr *)&host), port);
       
   634 
       
   635 	return true;
       
   636 }
       
   637 
       
   638 // Close UDP connection
       
   639 void NetworkUDPClose(void)
       
   640 {
       
   641 	DEBUG(net, 1, "[udp] closed listeners");
       
   642 
       
   643 	if (_network_udp_server) {
       
   644 		if (_udp_server_socket != INVALID_SOCKET) {
       
   645 			closesocket(_udp_server_socket);
       
   646 			_udp_server_socket = INVALID_SOCKET;
       
   647 		}
       
   648 
       
   649 		if (_udp_master_socket != INVALID_SOCKET) {
       
   650 			closesocket(_udp_master_socket);
       
   651 			_udp_master_socket = INVALID_SOCKET;
       
   652 		}
       
   653 
       
   654 		_network_udp_server = false;
       
   655 		_network_udp_broadcast = 0;
       
   656 	} else {
       
   657 		if (_udp_client_socket != INVALID_SOCKET) {
       
   658 			closesocket(_udp_client_socket);
       
   659 			_udp_client_socket = INVALID_SOCKET;
       
   660 		}
       
   661 		_network_udp_broadcast = 0;
       
   662 	}
       
   663 }
       
   664 
       
   665 // Receive something on UDP level
       
   666 void NetworkUDPReceive(SOCKET udp)
       
   667 {
       
   668 	struct sockaddr_in client_addr;
       
   669 	socklen_t client_len;
       
   670 	int nbytes;
       
   671 	static Packet *p = NULL;
       
   672 	int packet_len;
       
   673 
       
   674 	// If p is NULL, malloc him.. this prevents unneeded mallocs
       
   675 	if (p == NULL) p = malloc(sizeof(*p));
       
   676 
       
   677 	packet_len = sizeof(p->buffer);
       
   678 	client_len = sizeof(client_addr);
       
   679 
       
   680 	// Try to receive anything
       
   681 	nbytes = recvfrom(udp, p->buffer, packet_len, 0, (struct sockaddr *)&client_addr, &client_len);
       
   682 
       
   683 	// We got some bytes.. just asume we receive the whole packet
       
   684 	if (nbytes > 0) {
       
   685 		// Get the size of the buffer
       
   686 		p->size = (uint16)p->buffer[0];
       
   687 		p->size += (uint16)p->buffer[1] << 8;
       
   688 		// Put the position on the right place
       
   689 		p->pos = 2;
       
   690 		p->next = NULL;
       
   691 
       
   692 		// Handle the packet
       
   693 		NetworkHandleUDPPacket(p, &client_addr);
       
   694 
       
   695 		// Free the packet
       
   696 		free(p);
       
   697 		p = NULL;
       
   698 	}
       
   699 }
       
   700 
       
   701 // Broadcast to all ips
       
   702 static void NetworkUDPBroadCast(SOCKET udp)
       
   703 {
       
   704 	Packet* p = NetworkSend_Init(PACKET_UDP_CLIENT_FIND_SERVER);
       
   705 	uint i;
       
   706 
       
   707 	for (i = 0; _broadcast_list[i] != 0; i++) {
       
   708 		struct sockaddr_in out_addr;
       
   709 
       
   710 		out_addr.sin_family = AF_INET;
       
   711 		out_addr.sin_port = htons(_network_server_port);
       
   712 		out_addr.sin_addr.s_addr = _broadcast_list[i];
       
   713 
       
   714 		DEBUG(net, 4, "[udp] broadcasting to %s", inet_ntoa(out_addr.sin_addr));
       
   715 
       
   716 		NetworkSendUDP_Packet(udp, p, &out_addr);
       
   717 	}
       
   718 
       
   719 	free(p);
       
   720 }
       
   721 
       
   722 
       
   723 // Request the the server-list from the master server
       
   724 void NetworkUDPQueryMasterServer(void)
       
   725 {
       
   726 	struct sockaddr_in out_addr;
       
   727 	Packet *p;
       
   728 
       
   729 	if (_udp_client_socket == INVALID_SOCKET)
       
   730 		if (!NetworkUDPListen(&_udp_client_socket, 0, 0, true))
       
   731 			return;
       
   732 
       
   733 	p = NetworkSend_Init(PACKET_UDP_CLIENT_GET_LIST);
       
   734 
       
   735 	out_addr.sin_family = AF_INET;
       
   736 	out_addr.sin_port = htons(NETWORK_MASTER_SERVER_PORT);
       
   737 	out_addr.sin_addr.s_addr = NetworkResolveHost(NETWORK_MASTER_SERVER_HOST);
       
   738 
       
   739 	// packet only contains protocol version
       
   740 	NetworkSend_uint8(p, NETWORK_MASTER_SERVER_VERSION);
       
   741 
       
   742 	NetworkSendUDP_Packet(_udp_client_socket, p, &out_addr);
       
   743 
       
   744 	DEBUG(net, 2, "[udp] master server queried at %s:%d", inet_ntoa(out_addr.sin_addr),ntohs(out_addr.sin_port));
       
   745 
       
   746 	free(p);
       
   747 }
       
   748 
       
   749 // Find all servers
       
   750 void NetworkUDPSearchGame(void)
       
   751 {
       
   752 	// We are still searching..
       
   753 	if (_network_udp_broadcast > 0) return;
       
   754 
       
   755 	// No UDP-socket yet..
       
   756 	if (_udp_client_socket == INVALID_SOCKET)
       
   757 		if (!NetworkUDPListen(&_udp_client_socket, 0, 0, true))
       
   758 			return;
       
   759 
       
   760 	DEBUG(net, 0, "[udp] searching server");
       
   761 
       
   762 	NetworkUDPBroadCast(_udp_client_socket);
       
   763 	_network_udp_broadcast = 300; // Stay searching for 300 ticks
       
   764 }
       
   765 
       
   766 NetworkGameList *NetworkUDPQueryServer(const char* host, unsigned short port)
       
   767 {
       
   768 	struct sockaddr_in out_addr;
       
   769 	Packet *p;
       
   770 	NetworkGameList *item;
       
   771 
       
   772 	// No UDP-socket yet..
       
   773 	if (_udp_client_socket == INVALID_SOCKET)
       
   774 		if (!NetworkUDPListen(&_udp_client_socket, 0, 0, true))
       
   775 			return NULL;
       
   776 
       
   777 	out_addr.sin_family = AF_INET;
       
   778 	out_addr.sin_port = htons(port);
       
   779 	out_addr.sin_addr.s_addr = NetworkResolveHost(host);
       
   780 
       
   781 	// Clear item in gamelist
       
   782 	item = NetworkGameListAddItem(inet_addr(inet_ntoa(out_addr.sin_addr)), ntohs(out_addr.sin_port));
       
   783 	memset(&item->info, 0, sizeof(item->info));
       
   784 	ttd_strlcpy(item->info.server_name, host, lengthof(item->info.server_name));
       
   785 	ttd_strlcpy(item->info.hostname, host, lengthof(item->info.hostname));
       
   786 	item->online = false;
       
   787 
       
   788 	// Init the packet
       
   789 	p = NetworkSend_Init(PACKET_UDP_CLIENT_FIND_SERVER);
       
   790 
       
   791 	NetworkSendUDP_Packet(_udp_client_socket, p, &out_addr);
       
   792 
       
   793 	free(p);
       
   794 
       
   795 	UpdateNetworkGameWindow(false);
       
   796 	return item;
       
   797 }
       
   798 
       
   799 /* Remove our advertise from the master-server */
       
   800 void NetworkUDPRemoveAdvertise(void)
       
   801 {
       
   802 	struct sockaddr_in out_addr;
       
   803 	Packet *p;
       
   804 
       
   805 	/* Check if we are advertising */
       
   806 	if (!_networking || !_network_server || !_network_udp_server) return;
       
   807 
       
   808 	/* check for socket */
       
   809 	if (_udp_master_socket == INVALID_SOCKET)
       
   810 		if (!NetworkUDPListen(&_udp_master_socket, _network_server_bind_ip, 0, false))
       
   811 			return;
       
   812 
       
   813 	DEBUG(net, 1, "[udp] removing advertise from master server");
       
   814 
       
   815 	/* Find somewhere to send */
       
   816 	out_addr.sin_family = AF_INET;
       
   817 	out_addr.sin_port = htons(NETWORK_MASTER_SERVER_PORT);
       
   818 	out_addr.sin_addr.s_addr = NetworkResolveHost(NETWORK_MASTER_SERVER_HOST);
       
   819 
       
   820 	/* Send the packet */
       
   821 	p = NetworkSend_Init(PACKET_UDP_SERVER_UNREGISTER);
       
   822 	/* Packet is: Version, server_port */
       
   823 	NetworkSend_uint8(p, NETWORK_MASTER_SERVER_VERSION);
       
   824 	NetworkSend_uint16(p, _network_server_port);
       
   825 	NetworkSendUDP_Packet(_udp_master_socket, p, &out_addr);
       
   826 
       
   827 	free(p);
       
   828 }
       
   829 
       
   830 /* Register us to the master server
       
   831      This function checks if it needs to send an advertise */
       
   832 void NetworkUDPAdvertise(void)
       
   833 {
       
   834 	struct sockaddr_in out_addr;
       
   835 	Packet *p;
       
   836 
       
   837 	/* Check if we should send an advertise */
       
   838 	if (!_networking || !_network_server || !_network_udp_server || !_network_advertise)
       
   839 		return;
       
   840 
       
   841 	/* check for socket */
       
   842 	if (_udp_master_socket == INVALID_SOCKET)
       
   843 		if (!NetworkUDPListen(&_udp_master_socket, _network_server_bind_ip, 0, false))
       
   844 			return;
       
   845 
       
   846 	if (_network_need_advertise) {
       
   847 		_network_need_advertise = false;
       
   848 		_network_advertise_retries = ADVERTISE_RETRY_TIMES;
       
   849 	} else {
       
   850 		/* Only send once every ADVERTISE_NORMAL_INTERVAL ticks */
       
   851 		if (_network_advertise_retries == 0) {
       
   852 			if ((_network_last_advertise_frame + ADVERTISE_NORMAL_INTERVAL) > _frame_counter)
       
   853 				return;
       
   854 			_network_advertise_retries = ADVERTISE_RETRY_TIMES;
       
   855 		}
       
   856 
       
   857 		if ((_network_last_advertise_frame + ADVERTISE_RETRY_INTERVAL) > _frame_counter)
       
   858 			return;
       
   859 	}
       
   860 
       
   861 	_network_advertise_retries--;
       
   862 	_network_last_advertise_frame = _frame_counter;
       
   863 
       
   864 	/* Find somewhere to send */
       
   865 	out_addr.sin_family = AF_INET;
       
   866 	out_addr.sin_port = htons(NETWORK_MASTER_SERVER_PORT);
       
   867 	out_addr.sin_addr.s_addr = NetworkResolveHost(NETWORK_MASTER_SERVER_HOST);
       
   868 
       
   869 	DEBUG(net, 1, "[udp] advertising to master server");
       
   870 
       
   871 	/* Send the packet */
       
   872 	p = NetworkSend_Init(PACKET_UDP_SERVER_REGISTER);
       
   873 	/* Packet is: WELCOME_MESSAGE, Version, server_port */
       
   874 	NetworkSend_string(p, NETWORK_MASTER_SERVER_WELCOME_MESSAGE);
       
   875 	NetworkSend_uint8(p, NETWORK_MASTER_SERVER_VERSION);
       
   876 	NetworkSend_uint16(p, _network_server_port);
       
   877 	NetworkSendUDP_Packet(_udp_master_socket, p, &out_addr);
       
   878 
       
   879 	free(p);
       
   880 }
       
   881 
       
   882 void NetworkUDPInitialize(void)
       
   883 {
       
   884 	_udp_client_socket = INVALID_SOCKET;
       
   885 	_udp_server_socket = INVALID_SOCKET;
       
   886 	_udp_master_socket = INVALID_SOCKET;
       
   887 
       
   888 	_network_udp_server = false;
       
   889 	_network_udp_broadcast = 0;
       
   890 }
       
   891 
       
   892 #endif /* ENABLE_NETWORK */