Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,5 @@ tools/target
/src/resources/public/*
!/src/resources/public/content

*.exe
*.exe
.megamemory/*
13 changes: 12 additions & 1 deletion src/services/game/matchmaking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
43 changes: 41 additions & 2 deletions src/services/game/mod.rs
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -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;
Expand Down
9 changes: 9 additions & 0 deletions src/services/tunnel/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down
44 changes: 37 additions & 7 deletions src/session/routes/game_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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})");

Expand Down Expand Up @@ -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);
Expand Down
18 changes: 17 additions & 1 deletion src/utils/logging.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Ipv4Addr> {
// 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);
}
Expand Down Expand Up @@ -130,6 +135,17 @@ pub async fn public_address() -> Option<Ipv4Addr> {
None
}

/// Retrieves the public address of the server using the ifconfig.me API
pub async fn public_address_ifconfig() -> Option<Ipv4Addr> {
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::<Ipv4Addr>().ok()
}

/// Retrieves the public address of the server using the cloudflare API
pub async fn public_address_cloudflare() -> Option<Ipv4Addr> {
let response = match reqwest::get("https://cloudflare.com/cdn-cgi/trace")
Expand Down
Loading