diff --git a/.gitignore b/.gitignore index 89438de..4ed97da 100644 --- a/.gitignore +++ b/.gitignore @@ -20,4 +20,5 @@ tools/target /src/resources/public/* !/src/resources/public/content -*.exe \ No newline at end of file +*.exe +.megamemory/* diff --git a/src/services/game/matchmaking.rs b/src/services/game/matchmaking.rs index fbac46b..fde0e56 100644 --- a/src/services/game/matchmaking.rs +++ b/src/services/game/matchmaking.rs @@ -67,12 +67,23 @@ impl Matchmaking { let mut index = 0; while let Some(entry) = queue.get(index) { - let join_state = { link.read().joinable_state(Some(&entry.rule_set)) }; + let (join_state, tunnel_ready) = { + let game = link.read(); + ( + game.joinable_state(Some(&entry.rule_set)), + game.is_tunnel_ready(config, tunnel_service, &entry.player), + ) + }; // TODO: If player has been in queue long enough create // a game matching their specifics match join_state { + GameJoinableState::Joinable if !tunnel_ready => { + // Player doesn't have a connected tunnel yet so they wouldn't + // be able to communicate with the game, keep them queued + index += 1; + } GameJoinableState::Joinable => { // Index is not advanced, the next entry moves into this position let entry = queue diff --git a/src/services/game/mod.rs b/src/services/game/mod.rs index 65dfdd6..cb335f3 100644 --- a/src/services/game/mod.rs +++ b/src/services/game/mod.rs @@ -1,12 +1,12 @@ use self::rules::RuleSet; use crate::{ - config::Config, + config::{Config, TunnelConfig}, database::entities::Player, session::{ SessionLink, WeakSessionLink, data::NetData, models::{ - NetworkAddress, + NatType, NetworkAddress, game_manager::{ AdminListChange, AdminListOperation, AttributesChange, GameSettings, GameSetupContext, GameSetupResponse, GameState, GetGameDetails, @@ -449,6 +449,45 @@ impl Game { self.games_store.remove_by_id(self.id); } + /// Whether players joining this game must have a connected tunnel + /// (Mirrors the tunnel decision used when sending the game setup) + pub fn requires_tunnel(&self, config: &Config) -> bool { + match config.tunnel { + TunnelConfig::Always => true, + TunnelConfig::Disabled => false, + TunnelConfig::Stricter => { + let host_net = self + .players + .first() + .and_then(|host| host.net()) + .unwrap_or_default(); + !matches!(host_net.qos.natt, NatType::Open) + } + } + } + + /// Whether the player is able to communicate with this game, players + /// without a connected tunnel can't join games that require one + pub fn is_tunnel_ready( + &self, + config: &Config, + tunnel_service: &TunnelService, + player: &GamePlayer, + ) -> bool { + if !self.requires_tunnel(config) { + return true; + } + + let Some(session) = player.link.upgrade() else { + return false; + }; + + session + .data + .get_association() + .is_some_and(|association| tunnel_service.has_tunnel(&association)) + } + pub fn joinable_state(&self, rule_set: Option<&RuleSet>) -> GameJoinableState { if let GameState::Destructing = self.state { return GameJoinableState::Stopping; diff --git a/src/services/tunnel/mod.rs b/src/services/tunnel/mod.rs index 79def3a..0d0465e 100644 --- a/src/services/tunnel/mod.rs +++ b/src/services/tunnel/mod.rs @@ -67,6 +67,15 @@ impl TunnelService { .associate_pool(association, pool_id, pool_index); } + /// Checks whether the client with the provided association + /// currently has a connected tunnel + pub fn has_tunnel(&self, association: &AssociationId) -> bool { + self.mappings + .read() + .get_association_tunnel(association) + .is_some() + } + pub fn dissociate_pool(&self, pool_id: PoolId, pool_index: PoolIndex) { self.mappings.write().dissociate_pool(pool_id, pool_index); } diff --git a/src/session/routes/game_manager.rs b/src/session/routes/game_manager.rs index c425d9f..a80b38b 100644 --- a/src/session/routes/game_manager.rs +++ b/src/session/routes/game_manager.rs @@ -24,7 +24,7 @@ use crate::{ utils::parsing::player_character::PlayerCharacter, }; use chrono::Utc; -use log::{debug, error, info}; +use log::{debug, error, info, warn}; use std::{collections::HashMap, sync::Arc}; pub async fn handle_join_game( @@ -46,13 +46,27 @@ pub async fn handle_join_game( .get_game() .ok_or(GameManagerError::InvalidGameId)?; - // Check the game is joinable - let join_state = { game_ref.read().joinable_state(None) }; + // Check the game is joinable and the player is able to communicate with it + let (join_state, tunnel_ready) = { + let game = game_ref.read(); + ( + game.joinable_state(None), + game.is_tunnel_ready(&config, &tunnel_service, &player), + ) + }; if !matches!(join_state, GameJoinableState::Joinable) { return Err(GameManagerError::GameFull.into()); } + if !tunnel_ready { + warn!( + "Player {} has no connected tunnel, unable to join game (GID: {game_id})", + player.player.display_name + ); + return Err(GameManagerError::JoinPlayerFailed.into()); + } + // Join the game debug!("Joining game from invite (GID: {game_id})"); @@ -721,10 +735,26 @@ pub async fn handle_start_matchmaking( // Find a game thats currently joinable and matches the required rules match games.get_by_rule_set(&rules) { Some((game_id, game_ref)) => { - debug!("Found matching game (GID: {game_id})"); - - // Add the player to the game - matchmaking.add_from_matchmaking(&tunnel_service, &config, game_ref, player); + let tunnel_ready = { + game_ref + .read() + .is_tunnel_ready(&config, &tunnel_service, &player) + }; + + if tunnel_ready { + debug!("Found matching game (GID: {game_id})"); + + // Add the player to the game + matchmaking.add_from_matchmaking(&tunnel_service, &config, game_ref, player); + } else { + warn!( + "Player {} has no connected tunnel, queueing instead of joining game (GID: {game_id})", + player.player.display_name + ); + + // Queue the player until their tunnel is connected + matchmaking.queue(player, rules); + } } None => { matchmaking.queue(player, rules); diff --git a/src/utils/logging.rs b/src/utils/logging.rs index f61040d..80709e3 100644 --- a/src/utils/logging.rs +++ b/src/utils/logging.rs @@ -97,7 +97,12 @@ pub async fn log_connection_urls(http_port: u16) { /// value if its not expired or fetching the new value from the API using /// `fetch_public_addr` pub async fn public_address() -> Option { - // Try fetch from cloudflare first + // Try fetch from ifconfig.me first + if let Some(addr) = public_address_ifconfig().await { + return Some(addr); + } + + // Fallback to cloudflare if let Some(addr) = public_address_cloudflare().await { return Some(addr); } @@ -130,6 +135,17 @@ pub async fn public_address() -> Option { None } +/// Retrieves the public address of the server using the ifconfig.me API +pub async fn public_address_ifconfig() -> Option { + let response = reqwest::get("https://ifconfig.me/ip") + .and_then(reqwest::Response::text) + .await + .ok()?; + + // Trim whitespace and attempt to parse as an IPv4 address + response.trim().parse::().ok() +} + /// Retrieves the public address of the server using the cloudflare API pub async fn public_address_cloudflare() -> Option { let response = match reqwest::get("https://cloudflare.com/cdn-cgi/trace")