Skip to content

Commit

Permalink
maintenance + cleanups
Browse files Browse the repository at this point in the history
  • Loading branch information
dankmeme01 committed Dec 12, 2023
1 parent c7dfac3 commit 1812d7c
Show file tree
Hide file tree
Showing 22 changed files with 131 additions and 122 deletions.
39 changes: 12 additions & 27 deletions server/central/src/config.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
use std::{
collections::HashMap,
fs::{File, OpenOptions},
path::Path,
};

use globed_shared::SpecialUser;
use globed_shared::{IntMap, SpecialUser};
use rand::{distributions::Alphanumeric, Rng};
use serde::{Deserialize, Serialize};
use serde_json::{ser::PrettyFormatter, Serializer};
Expand Down Expand Up @@ -39,8 +38,12 @@ fn default_game_servers() -> Vec<GameServerEntry> {
Vec::new()
}

fn default_special_users() -> HashMap<i32, SpecialUser> {
HashMap::new()
fn default_maintenance() -> bool {
false
}

fn default_special_users() -> IntMap<i32, SpecialUser> {
IntMap::default()
}

fn default_userlist_mode() -> UserlistMode {
Expand Down Expand Up @@ -114,10 +117,12 @@ pub struct ServerConfig {
pub web_address: String,
#[serde(default = "default_game_servers")]
pub game_servers: Vec<GameServerEntry>,
#[serde(default = "default_maintenance")]
pub maintenance: bool,

// special users and "special" users
#[serde(default = "default_special_users")]
pub special_users: HashMap<i32, SpecialUser>,
pub special_users: IntMap<i32, SpecialUser>,
#[serde(default = "default_userlist_mode")]
pub userlist_mode: UserlistMode,
#[serde(default = "default_userlist")]
Expand Down Expand Up @@ -177,27 +182,7 @@ impl ServerConfig {
}

pub fn make_default() -> Self {
// i'm okay thanks for asking
Self {
web_mountpoint: default_web_mountpoint(),
web_address: default_web_address(),
use_gd_api: default_use_gd_api(),
gd_api: default_gdapi(),
gd_api_ratelimit: default_gdapi_ratelimit(),
gd_api_period: default_gdapi_period(),
game_servers: default_game_servers(),
special_users: default_special_users(),
userlist_mode: default_userlist_mode(),
userlist: default_userlist(),
no_chat_list: default_userlist(),
tps: default_tps(),
secret_key: default_secret_key(),
game_server_password: default_secret_key(),
challenge_expiry: default_challenge_expiry(),
challenge_level: default_challenge_level(),
challenge_ratelimit: default_challenge_ratelimit(),
cloudflare_protection: default_cloudflare_protection(),
token_expiry: default_token_expiry(),
}
// i'm just so cool like that
serde_json::from_str("{}").unwrap()
}
}
9 changes: 4 additions & 5 deletions server/central/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,13 @@
clippy::missing_panics_doc
)]

use std::{error::Error, path::PathBuf, sync::Arc, time::Duration};
use std::{error::Error, path::PathBuf, time::Duration};

use async_watcher::{notify::RecursiveMode, AsyncDebouncer};
use config::ServerConfig;
use globed_shared::logger::{error, info, log, warn, LogLevelFilter, Logger};
use roa::{tcp::Listener, App};
use state::{ServerState, ServerStateData};
use tokio::sync::RwLock;

pub mod config;
pub mod ip_blocker;
Expand Down Expand Up @@ -71,9 +70,7 @@ async fn main() -> Result<(), Box<dyn Error>> {

let state_skey = config.secret_key.clone();

let state = ServerState {
inner: Arc::new(RwLock::new(ServerStateData::new(config_path.clone(), config, &state_skey))),
};
let state = ServerState::new(ServerStateData::new(config_path.clone(), config, &state_skey));

// config file watcher

Expand All @@ -90,6 +87,8 @@ async fn main() -> Result<(), Box<dyn Error>> {
match state.config.reload_in_place(&cpath) {
Ok(()) => {
info!("Successfully reloaded the configuration");
// set the maintenance flag appropriately
watcher_state.set_maintenance(state.config.maintenance);
}
Err(err) => {
warn!("Failed to reload configuration: {}", err.to_string());
Expand Down
26 changes: 22 additions & 4 deletions server/central/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ use std::{
collections::HashMap,
net::IpAddr,
path::PathBuf,
sync::Arc,
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
};

Expand Down Expand Up @@ -171,15 +174,30 @@ impl ServerStateData {

#[derive(Clone)]
pub struct ServerState {
pub inner: Arc<RwLock<ServerStateData>>,
pub inner: Arc<(RwLock<ServerStateData>, AtomicBool)>,
}

impl ServerState {
pub fn new(ssd: ServerStateData) -> Self {
let maintenance = ssd.config.maintenance;
ServerState {
inner: Arc::new((RwLock::new(ssd), AtomicBool::new(maintenance))),
}
}

pub async fn state_read(&self) -> RwLockReadGuard<'_, ServerStateData> {
self.inner.read().await
self.inner.0.read().await
}

pub async fn state_write(&self) -> RwLockWriteGuard<'_, ServerStateData> {
self.inner.write().await
self.inner.0.write().await
}

pub fn maintenance(&self) -> bool {
self.inner.1.load(Ordering::Relaxed)
}

pub fn set_maintenance(&self, state: bool) {
self.inner.1.store(state, Ordering::Relaxed);
}
}
14 changes: 13 additions & 1 deletion server/central/src/web/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ pub mod routes {
.on("/", get(meta::index))
.on("/version", get(meta::version))
.on("/servers", get(meta::servers))
.on("/amoung_pequeno", get(meta::pagina_grande))
/* auth */
.on("/totplogin", post(auth::totp_login))
.on("/challenge/new", post(auth::challenge_start))
Expand All @@ -22,4 +21,17 @@ pub mod routes {
.on("/gs/boot", post(game_server::boot))
.on("/gs/verify", post(game_server::verify_token))
}

macro_rules! check_maintenance {
($ctx:expr) => {
if $ctx.maintenance() {
throw!(
roa::http::StatusCode::SERVICE_UNAVAILABLE,
"The server is currently under maintenance, please try connecting again later"
);
}
};
}

pub(crate) use check_maintenance;
}
1 change: 1 addition & 0 deletions server/central/src/web/routes/._p
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>pagina grande</title><style>.amoung{width:100%;height:100%}.pagina{max-width:500px;max-height:100px;scale:130%;width:auto;height:auto;padding-bottom:15px;padding-top:15px}.pequeno{display:flex;flex-direction:column;align-items:center;height:calc(100vh - 20px)}</style></head><body><main><div class="pequeno"><img class="pagina" src="https://user-images.githubusercontent.com/42031238/283487282-eb98a543-643b-4bab-bd6e-b3318d53a5e9.png"> <img class="amoung" src="https://user-images.githubusercontent.com/42031238/283811999-c68a4b52-cbad-49e5-81f4-0720a0e7af77.png"></div></main></body></html>
8 changes: 7 additions & 1 deletion server/central/src/web/routes/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,11 @@ use globed_shared::logger::{debug, info, log, warn};
use rand::{distributions::Alphanumeric, Rng};
use roa::{http::StatusCode, preload::PowerBody, query::Query, throw, Context};

use crate::state::{ActiveChallenge, ServerState};
use crate::{config::UserlistMode, ip_blocker::IpBlocker};
use crate::{
state::{ActiveChallenge, ServerState},
web::routes::check_maintenance,
};

macro_rules! check_user_agent {
($ctx:expr, $ua:ident) => {
Expand Down Expand Up @@ -57,6 +60,7 @@ macro_rules! get_user_ip {
};
}
pub async fn totp_login(context: &mut Context<ServerState>) -> roa::Result {
check_maintenance!(context);
check_user_agent!(context, _ua);

let state = context.state_read().await;
Expand Down Expand Up @@ -102,6 +106,7 @@ pub async fn totp_login(context: &mut Context<ServerState>) -> roa::Result {
}

pub async fn challenge_start(context: &mut Context<ServerState>) -> roa::Result {
check_maintenance!(context);
check_user_agent!(context, _ua);

let account_id = context.must_query("aid")?.parse::<i32>()?;
Expand Down Expand Up @@ -192,6 +197,7 @@ pub async fn challenge_start(context: &mut Context<ServerState>) -> roa::Result
// rollercoaster of a function i'd say
#[allow(clippy::too_many_lines)]
pub async fn challenge_finish(context: &mut Context<ServerState>) -> roa::Result {
check_maintenance!(context);
check_user_agent!(context, _ua);

let account_id = &*context.must_query("aid")?;
Expand Down
1 change: 1 addition & 0 deletions server/central/src/web/routes/game_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ pub async fn boot(context: &mut Context<ServerState>) -> roa::Result {
no_chat: config.no_chat_list.clone(),
special_users: config.special_users.clone(),
tps: config.tps,
maintenance: config.maintenance,
};

debug!(
Expand Down
14 changes: 9 additions & 5 deletions server/central/src/web/routes/meta.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,32 +4,36 @@ use roa::{preload::PowerBody, throw, Context};

use crate::state::ServerState;

use super::check_maintenance;

pub async fn version(context: &mut Context<ServerState>) -> roa::Result {
check_maintenance!(context);
context.write(PROTOCOL_VERSION.to_string());
Ok(())
}

pub async fn index(context: &mut Context<ServerState>) -> roa::Result {
if rand::thread_rng().gen_ratio(1, 100) {
context.resp.headers.append("Location", "/amoung_pequeno".parse()?);
throw!(roa::http::StatusCode::TEMPORARY_REDIRECT);
return _check(context);
}

context.write("hi there cutie :3");
Ok(())
}

pub async fn servers(context: &mut Context<ServerState>) -> roa::Result {
check_maintenance!(context);
let serialized = serde_json::to_string(&context.state_read().await.config.game_servers)?;
context.write(serialized);
Ok(())
}

pub async fn pagina_grande(context: &mut Context<ServerState>) -> roa::Result {
let html = include_str!("page.html");
fn _check(context: &mut Context<ServerState>) -> roa::Result {
let html = include_str!("._p");
context
.resp
.headers
.append(roa::http::header::CACHE_CONTROL, "public, max-age=86400".parse()?);
.append(roa::http::header::CACHE_CONTROL, "public, max-age=1".parse()?);

context.resp.headers.append("pagina", "grande".parse()?);

Expand Down
45 changes: 0 additions & 45 deletions server/central/src/web/routes/page.html

This file was deleted.

1 change: 0 additions & 1 deletion server/game/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ anyhow = "1.0.75"
array-init = "2.1.0"
bytebuffer = "2.2.0"
crypto_box = { version = "0.9.1", features = ["std", "chacha20"] }
nohash-hasher = "0.2.0"
parking_lot = "0.12.1"
reqwest = "0.11.22"
rustc-hash = "1.1.0"
Expand Down
8 changes: 1 addition & 7 deletions server/game/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
)]

use std::{
collections::HashMap,
error::Error,
net::{IpAddr, Ipv4Addr, SocketAddr},
};
Expand Down Expand Up @@ -159,12 +158,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
let state = ServerState::new();
let gsbd = if standalone {
warn!("Starting in standalone mode, authentication is disabled");
GameServerBootData {
protocol: PROTOCOL_VERSION,
no_chat: Vec::new(),
special_users: HashMap::new(),
tps: 30,
}
GameServerBootData::default()
} else {
let (central_url, central_pw) = startup_config.central_data.unwrap();
config.central_url = central_url;
Expand Down
2 changes: 1 addition & 1 deletion server/game/src/managers/player.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use nohash_hasher::IntMap;
use globed_shared::IntMap;

use crate::data::types::{AssociatedPlayerData, PlayerData};

Expand Down
2 changes: 1 addition & 1 deletion server/game/src/managers/room.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use nohash_hasher::IntMap;
use globed_shared::IntMap;
use parking_lot::{Mutex as SyncMutex, MutexGuard as SyncMutexGuard};
use rand::Rng;

Expand Down
15 changes: 14 additions & 1 deletion server/game/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -409,8 +409,21 @@ impl GameServer {

let configuration = response.text().await?;
let boot_data: GameServerBootData = serde_json::from_str(&configuration)?;
let mut conf = self.central_conf.lock();

*self.central_conf.lock() = boot_data;
let is_now_under_maintenance = !conf.maintenance && boot_data.maintenance;

*conf = boot_data;

// if we are now under maintenance, disconnect everyone who's still connected
if is_now_under_maintenance {
let threads: Vec<_> = self.threads.lock().values().cloned().collect();
for thread in threads {
thread.push_new_message(ServerThreadMessage::TerminationNotice(FastString::from_str(
"The server is now under maintenance, please try connecting again later",
)))?;
}
}

Ok(())
}
Expand Down
8 changes: 8 additions & 0 deletions server/game/src/server_thread/handlers/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,14 @@ impl GameServerThread {
return Ok(());
}

// disconnect if server is under maintenance
if self.game_server.central_conf.lock().maintenance {
gs_disconnect!(
self,
FastString::from_str("The server is currently under maintenance, please try connecting again later.")
);
}

// lets verify the given token

let url = format!("{}gs/verify", self.game_server.config.central_url);
Expand Down
Loading

0 comments on commit 1812d7c

Please sign in to comment.