Skip to content

Commit

Permalink
some changes
Browse files Browse the repository at this point in the history
  • Loading branch information
dankmeme01 committed Nov 22, 2023
1 parent d544f64 commit 2390205
Show file tree
Hide file tree
Showing 23 changed files with 374 additions and 220 deletions.
9 changes: 5 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,14 @@ Known issues:

## Hosting a server

todo!
See the [server readme](./server/readme.md) for more information about the server and how you can host it.

## Building

Building should be the same as any other mod!

todo macaroni os
```sh
cmake -DCMAKE_BUILD_TYPE=Release -B build
cmake --build build --config Release
```

## Credit

Expand Down
2 changes: 1 addition & 1 deletion server/central/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ fn default_secret_key() -> String {
.map(char::from)
.collect();

format!("Insecure-{}", rand_string)
format!("Insecure-{rand_string}")
}

fn default_challenge_expiry() -> u32 {
Expand Down
6 changes: 3 additions & 3 deletions server/central/src/ip_blocker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ pub struct IpBlocker {
}

impl IpBlocker {
pub fn new(v4: Vec<String>, v6: Vec<String>) -> Self {
pub fn new(v4: &[String], v6: &[String]) -> Self {
let range_v4 = v4.iter().map(|s| s.parse().unwrap()).collect();
let range_v6 = v6.iter().map(|s| s.parse().unwrap()).collect();

Expand Down Expand Up @@ -44,10 +44,10 @@ lazy_static! {
} else if proto == "v6" {
v6.push(range.to_string());
} else {
eprintln!("ignoring invalid IP address entry: {}", line);
eprintln!("ignoring invalid IP address entry: {line}");
}
}

IpBlocker::new(v4, v6)
IpBlocker::new(&v4, &v6)
};
}
8 changes: 4 additions & 4 deletions server/central/src/logger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ const TIME_FORMAT: &str = "[year]-[month]-[day] [hour]:[minute]:[second].[subsec

impl log::Log for Logger {
fn enabled(&self, metadata: &log::Metadata) -> bool {
if !metadata.target().starts_with("globed_central_server") {
metadata.level() <= Level::Warn
} else {
if metadata.target().starts_with("globed_central_server") {
true
} else {
metadata.level() <= Level::Warn
}
}

Expand All @@ -37,7 +37,7 @@ impl log::Log for Logger {
Level::Trace => (record.level().to_string().black(), record.args().to_string().black()),
};

println!("[{}] [{}] - {}", formatted_time, level, args,)
println!("[{formatted_time}] [{level}] - {args}");
}
}

Expand Down
11 changes: 5 additions & 6 deletions server/central/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,8 @@ async fn main() -> Result<(), Box<dyn Error>> {

// config file

let mut config_path = std::env::var("GLOBED_CONFIG_PATH")
.map(PathBuf::from)
.unwrap_or_else(|_| std::env::current_dir().unwrap());
let mut config_path =
std::env::var("GLOBED_CONFIG_PATH").map_or_else(|_| std::env::current_dir().unwrap(), PathBuf::from);

if config_path.is_dir() {
config_path = config_path.join("central-conf.json");
Expand Down Expand Up @@ -80,7 +79,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
let mut state = watcher_state.state_write().await;
let cpath = state.config_path.clone();
match state.config.reload_in_place(&cpath) {
Ok(_) => {
Ok(()) => {
info!("Successfully reloaded the configuration");
}
Err(err) => {
Expand All @@ -93,8 +92,8 @@ async fn main() -> Result<(), Box<dyn Error>> {
// roa your favorite web app

let router = web::routes::build_router();
let routes = router.routes(Box::leak(Box::new(mnt_point)))?;
let app = App::state(state).end(routes);
let route_list = router.routes(Box::leak(Box::new(mnt_point)))?;
let app = App::state(state).end(route_list);

app.listen(mnt_addr, |addr| {
info!("Globed central server launched on {addr}");
Expand Down
4 changes: 2 additions & 2 deletions server/central/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ impl ServerStateData {

// uses hmac-sha256 to derive an auth key from user's account ID and name
pub fn generate_authkey(&self, account_id: i32, account_name: &str) -> Vec<u8> {
let val = format!("{}:{}", account_id, account_name);
let val = format!("{account_id}:{account_name}");

let mut hmac: Hmac<Sha256> = self.hmac.clone();
hmac.update(val.as_bytes());
Expand Down Expand Up @@ -92,7 +92,7 @@ impl ServerStateData {
.expect("whoops our clock went backwards")
.as_secs();

let data = format!("{}.{}.{}", account_id, account_name, timestamp);
let data = format!("{account_id}.{account_name}.{timestamp}");
let mut hmac = self.hmac.clone();
hmac.update(data.as_bytes());
let res = hmac.finalize();
Expand Down
15 changes: 7 additions & 8 deletions server/central/src/web/routes/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,18 +59,19 @@ macro_rules! get_user_ip {
pub async fn totp_login(context: &mut Context<ServerState>) -> roa::Result {
check_user_agent!(context, _ua);

let state = context.state_read().await;
get_user_ip!(state, context, _ip);

let account_id = context.must_query("aid")?.parse::<i32>()?;
let account_name = &*context.must_query("aname")?;
let code = &*context.must_query("code")?;

// if account_name.to_lowercase().contains("sevenworks")
// && rand::thread_rng().gen_ratio(1, 25) {

// || account_name.to_lowercase() == "7works" && rand::thread_rng().gen_ratio(1, 25)
// {
// throw!(StatusCode::IM_A_TEAPOT);
// }

let state = context.state_read().await;

if state.should_block(account_id) {
throw!(
StatusCode::FORBIDDEN,
Expand Down Expand Up @@ -138,7 +139,7 @@ pub async fn challenge_start(context: &mut Context<ServerState>) -> roa::Result
} else {
let passed_time = current_time - challenge.started;
// if it hasn't expired yet, throw an error
if passed_time.as_secs() < (state.config.challenge_expiry as u64) {
if passed_time.as_secs() < u64::from(state.config.challenge_expiry) {
throw!(
StatusCode::FORBIDDEN,
"challenge already requested for this account ID, please wait a minute and try again"
Expand Down Expand Up @@ -264,7 +265,7 @@ pub async fn challenge_finish(context: &mut Context<ServerState>) -> roa::Result
// no ratelimiting in debug mode
if !cfg!(debug_assertions) {
match state.record_login_attempt(&user_ip) {
Ok(_) => {}
Ok(()) => {}
Err(err) => {
warn!("peer is sending too many verification requests: {}", user_ip);
throw!(StatusCode::TOO_MANY_REQUESTS, err.to_string())
Expand Down Expand Up @@ -370,8 +371,6 @@ pub async fn challenge_finish(context: &mut Context<ServerState>) -> roa::Result

context.write(format!("{}:{}", comment_id, b64e::STANDARD.encode(authkey)));
return Ok(());
} else {
break;
}
}

Expand Down
2 changes: 1 addition & 1 deletion server/central/src/web/routes/game_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ macro_rules! check_user_agent {

let $ua = useragent.unwrap().to_str()?;
if !cfg!(debug_assertions) && !$ua.starts_with("globed-game-server") {
throw!(StatusCode::UNAUTHORIZED, "mismatched user agent");
throw!(StatusCode::UNAUTHORIZED, "bad request");
}
};
}
Expand Down
12 changes: 6 additions & 6 deletions server/game/src/bytebufferext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ impl ByteBufferExt for ByteBuffer {

impl ByteBufferExtWrite for ByteBuffer {
fn write_bool(&mut self, val: bool) {
self.write_u8(if val { 1u8 } else { 0u8 });
self.write_u8(u8::from(val));
}

fn write_byte_array(&mut self, val: &[u8]) {
Expand All @@ -152,25 +152,25 @@ impl ByteBufferExtWrite for ByteBuffer {

fn write_value_vec<T: Encodable>(&mut self, val: &[T]) {
self.write_u32(val.len() as u32);
for elem in val.iter() {
for elem in val {
elem.encode(self);
}
}

fn write_enum<E: Into<B>, B: Encodable>(&mut self, val: E) {
self.write_value(&val.into())
self.write_value(&val.into());
}

fn write_color3(&mut self, val: cocos::Color3B) {
self.write_value(&val)
self.write_value(&val);
}

fn write_color4(&mut self, val: cocos::Color4B) {
self.write_value(&val)
self.write_value(&val);
}

fn write_point(&mut self, val: cocos::Point) {
self.write_value(&val)
self.write_value(&val);
}
}

Expand Down
14 changes: 7 additions & 7 deletions server/game/src/data/packets/client/game.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,9 @@ packet!(RequestProfilesPacket, 11001, false, {
encode_unimpl!(RequestProfilesPacket);

decode_impl!(RequestProfilesPacket, buf, {
let len = buf.read_u32()?;
let mut ids = Vec::new();
for _ in 0..len {
ids.push(buf.read_i32()?);
}

Ok(Self { ids })
Ok(Self {
ids: buf.read_value_vec()?,
})
});

/* LevelJoinPacket - 11002 */
Expand Down Expand Up @@ -66,6 +62,10 @@ encode_unimpl!(PlayerDataPacket);

decode_impl!(PlayerDataPacket, buf, Ok(Self { data: buf.read_value()? }));

/* RequestPlayerListPacket - 11005 */

empty_client_packet!(RequestPlayerListPacket, 11005);

/* VoicePacket - 11010 */

packet!(VoicePacket, 11010, true, {
Expand Down
12 changes: 12 additions & 0 deletions server/game/src/data/packets/server/game.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,18 @@ decode_unimpl!(PlayerProfilesPacket);

empty_server_packet!(LevelDataPacket, 21001);

/* PlayerListPacket - 21002 */

packet!(PlayerListPacket, 21002, false, {
profiles: Vec<PlayerAccountData>,
});

encode_impl!(PlayerListPacket, buf, self, {
buf.write_value_vec(&self.profiles);
});

decode_unimpl!(PlayerListPacket);

/* VoiceBroadcastPacket - 21010 */

packet!(VoiceBroadcastPacket, 21010, true, {
Expand Down
72 changes: 36 additions & 36 deletions server/game/src/data/types/gd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,18 @@ use super::Color3B;

#[derive(Clone)]
pub struct PlayerIconData {
pub cube: i32,
pub ship: i32,
pub ball: i32,
pub ufo: i32,
pub wave: i32,
pub robot: i32,
pub spider: i32,
pub swing: i32,
pub jetpack: i32,
pub death_effect: i32,
pub color1: i32,
pub color2: i32,
pub cube: i16,
pub ship: i16,
pub ball: i16,
pub ufo: i16,
pub wave: i16,
pub robot: i16,
pub spider: i16,
pub swing: i16,
pub jetpack: i16,
pub death_effect: i16,
pub color1: i16,
pub color2: i16,
}

impl Default for PlayerIconData {
Expand All @@ -40,33 +40,33 @@ impl Default for PlayerIconData {
}

encode_impl!(PlayerIconData, buf, self, {
buf.write_i32(self.cube);
buf.write_i32(self.ship);
buf.write_i32(self.ball);
buf.write_i32(self.ufo);
buf.write_i32(self.wave);
buf.write_i32(self.robot);
buf.write_i32(self.spider);
buf.write_i32(self.swing);
buf.write_i32(self.jetpack);
buf.write_i32(self.death_effect);
buf.write_i32(self.color1);
buf.write_i32(self.color2);
buf.write_i16(self.cube);
buf.write_i16(self.ship);
buf.write_i16(self.ball);
buf.write_i16(self.ufo);
buf.write_i16(self.wave);
buf.write_i16(self.robot);
buf.write_i16(self.spider);
buf.write_i16(self.swing);
buf.write_i16(self.jetpack);
buf.write_i16(self.death_effect);
buf.write_i16(self.color1);
buf.write_i16(self.color2);
});

decode_impl!(PlayerIconData, buf, {
let cube = buf.read_i32()?;
let ship = buf.read_i32()?;
let ball = buf.read_i32()?;
let ufo = buf.read_i32()?;
let wave = buf.read_i32()?;
let robot = buf.read_i32()?;
let spider = buf.read_i32()?;
let swing = buf.read_i32()?;
let jetpack = buf.read_i32()?;
let death_effect = buf.read_i32()?;
let color1 = buf.read_i32()?;
let color2 = buf.read_i32()?;
let cube = buf.read_i16()?;
let ship = buf.read_i16()?;
let ball = buf.read_i16()?;
let ufo = buf.read_i16()?;
let wave = buf.read_i16()?;
let robot = buf.read_i16()?;
let spider = buf.read_i16()?;
let swing = buf.read_i16()?;
let jetpack = buf.read_i16()?;
let death_effect = buf.read_i16()?;
let color1 = buf.read_i16()?;
let color2 = buf.read_i16()?;
Ok(Self {
cube,
ship,
Expand Down
8 changes: 4 additions & 4 deletions server/game/src/logger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ const TIME_FORMAT: &str = "[year]-[month]-[day] [hour]:[minute]:[second].[subsec

impl log::Log for Logger {
fn enabled(&self, metadata: &log::Metadata) -> bool {
if !metadata.target().starts_with("globed_game_server") {
metadata.level() <= Level::Warn
} else {
if metadata.target().starts_with("globed_game_server") {
true
} else {
metadata.level() <= Level::Warn
}
}

Expand All @@ -37,7 +37,7 @@ impl log::Log for Logger {
Level::Trace => (record.level().to_string().black(), record.args().to_string().black()),
};

println!("[{}] [{}] - {}", formatted_time, level, args,)
println!("[{formatted_time}] [{level}] - {args}");
}
}

Expand Down
Loading

0 comments on commit 2390205

Please sign in to comment.