Skip to content

Commit 54a1965

Browse files
json config replaced by toml config
- Added server and api addr setting - Added auth_url for session request - Added custom messages
1 parent e2232fd commit 54a1965

File tree

9 files changed

+145
-61
lines changed

9 files changed

+145
-61
lines changed

Cargo.toml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ version = "0.1.0"
44
edition = "2021"
55

66
[dependencies]
7-
tokio = { version = "1.0", features = ["full"] }
7+
tokio = { version = "1.43.0", features = ["full"] }
88
actix-web = "4.9.0"
99
bytes = "1.0"
1010
rsa = "0.9"
@@ -22,3 +22,4 @@ num-bigint = "0.4.6"
2222
tracing = "0.1.41"
2323
tracing-subscriber = "0.3.19"
2424
base64_light = "0.1.5"
25+
toml = "0.8.20"

config.json

Lines changed: 0 additions & 11 deletions
This file was deleted.

config.toml

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
[api]
2+
addr = "0.0.0.0"
3+
port = 8008
4+
code_life_time = 300
5+
6+
[server]
7+
addr = "0.0.0.0"
8+
port = 25566
9+
timeout = 10
10+
11+
[server.config]
12+
protocol = 0
13+
version = "1.21"
14+
auth_url = "https://sessionserver.mojang.com/session/minecraft/hasJoined?username={{NAME}}&serverId={{HASH}}"
15+
16+
[server.status]
17+
description = "§6mc-oauth.andcool.ru"
18+
players_max = 0
19+
players_online = 0
20+
icon_path = "server_icon.png"
21+
22+
[messages]
23+
success = "Hello, §6{{NAME}}§r! Your code is: §a{{CODE}}"
24+
bad_session = "§cFailed to login: Invalid session (Try restarting your game and the launcher)"

src/config/mod.rs

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,17 @@ pub async fn load(path: &str) -> Result<()> {
1414
.await
1515
.expect("Couldn't load config file");
1616

17-
let mut config: types::Config =
18-
serde_json::from_str(&file).expect("Couldn't parse config json");
19-
match server_icon::load(&config.icon_path).await {
17+
let mut config: types::Config = match toml::from_str(&file) {
18+
Ok(config) => config,
19+
Err(err) => {
20+
panic!("Couldn't parse config: {}", err.message())
21+
}
22+
};
23+
24+
//let mut config: types::Config = toml::from_str(&file);
25+
match server_icon::load(&config.server.status.icon_path).await {
2026
Ok(base64) => config.image = Some(format!("data:image/png;base64,{}", base64)),
21-
Err(e) => warn!("Error loading server icon: {}", e)
27+
Err(e) => warn!("Error loading server icon: {}", e),
2228
}
2329

2430
CONFIG.set(config).expect("Couldn't load config");

src/config/types.rs

Lines changed: 73 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,88 @@
1-
use serde::{Deserialize, Serialize};
1+
use serde::Deserialize;
22

3-
#[derive(Serialize, Deserialize, Debug)]
3+
#[derive(Deserialize, Debug)]
44
pub struct Config {
5-
/// Minecraft server port (Minecraft's default port is `25565`)
6-
pub server_port: u16,
5+
/// API config
6+
pub api: API,
7+
8+
/// Minecraft server config
9+
pub server: Server,
10+
11+
/// Messages config
12+
pub messages: Messages,
13+
14+
#[serde(skip)]
15+
/// Base 64 encoded server icon
16+
pub image: Option<String>,
17+
}
18+
19+
#[derive(Deserialize, Debug)]
20+
pub struct API {
21+
/// API address
22+
pub addr: String,
723

824
/// API port
9-
pub api_port: u16,
25+
pub port: u16,
1026

11-
/// Display count of max server players
12-
pub players_max: usize,
27+
/// Life time of assigned code
28+
pub code_life_time: u64,
29+
}
1330

14-
/// Display count of max server players
15-
pub players_online: usize,
31+
#[derive(Deserialize, Debug)]
32+
pub struct Server {
33+
/// Server address
34+
pub addr: String,
1635

17-
/// Server protocol version (0 for auto)
18-
pub proto_ver: usize,
36+
/// Server port
37+
pub port: u16,
1938

20-
/// Server version string (e.g. 1.20.5)
21-
pub server_ver: String,
39+
/// Server connection timeout
40+
pub timeout: u64,
2241

23-
/// Server description (you can use a `§` codes)
24-
pub motd: String,
42+
/// Minecraft server config
43+
pub config: ServerConfig,
2544

26-
/// Assigned 6-digit code life time in seconds
27-
pub code_life_time: u64,
45+
/// Server list ping config
46+
pub status: ServerStatus,
47+
}
48+
49+
#[derive(Deserialize, Debug)]
50+
pub struct ServerConfig {
51+
/// Protocol version (`0` for auto)
52+
pub protocol: usize,
53+
54+
/// Minecraft version string (e.g. `1.20.1`)
55+
pub version: String,
56+
57+
/// Session Auth URL
58+
/// `{{NAME}}` in string will be replaced to client nickname
59+
/// `{{HASH}}` will be replaced to generated client hash
60+
pub auth_url: String,
61+
}
62+
63+
#[derive(Deserialize, Debug)]
64+
pub struct ServerStatus {
65+
/// Server description (you can use MOTD)
66+
pub description: String,
67+
68+
/// Max players count, displayed in server list
69+
pub players_max: usize,
70+
71+
/// Online players count, displayed in server list
72+
pub players_online: usize,
2873

2974
/// Path to the server icon
3075
pub icon_path: String,
76+
}
3177

32-
#[serde(skip)]
33-
/// Base 64 encoded server icon
34-
pub image: Option<String>,
78+
#[derive(Deserialize, Debug)]
79+
pub struct Messages {
80+
/// Message for success auth
81+
/// `{{NAME}}` will be replaced to client nickname
82+
/// `{{UUID}}` will be replaced to client UUID
83+
/// `{{CODE}}` will be replaced to generated code
84+
pub success: String,
85+
86+
/// Message for Mojang API error
87+
pub bad_session: String,
3588
}

src/handlers/client_handler.rs

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -58,8 +58,9 @@ pub async fn handle(mut stream: TcpStream, keys: Arc<rsa::RsaPrivateKey>) -> Res
5858
disconnect::send(
5959
&mut stream,
6060
session,
61-
"§cFailed to login: Invalid session (Try restarting your game and the launcher)".to_string()
62-
).await?;
61+
config.messages.bad_session.clone(),
62+
)
63+
.await?;
6364
break;
6465
}
6566
let player_data = player_data.unwrap();
@@ -70,15 +71,20 @@ pub async fn handle(mut stream: TcpStream, keys: Arc<rsa::RsaPrivateKey>) -> Res
7071
map.insert(
7172
code.clone(),
7273
player_data.clone(),
73-
Duration::from_secs(config.code_life_time),
74+
Duration::from_secs(config.api.code_life_time),
7475
)
7576
.await;
7677

7778
// Disconnect client with code
7879
disconnect::send(
7980
&mut stream,
8081
session,
81-
format!("Hello, §6{}§r! Your code is: §a{}", player_data.name, code),
82+
config
83+
.messages
84+
.success
85+
.replace("{{NAME}}", &player_data.name)
86+
.replace("{{UUID}}", &player_data.id)
87+
.replace("{{CODE}}", &code),
8288
)
8389
.await?;
8490

src/main.rs

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ mod responses;
1313

1414
use std::{
1515
net::{Ipv4Addr, SocketAddrV4},
16+
str::FromStr,
1617
sync::Arc,
1718
time::Duration,
1819
};
@@ -43,7 +44,7 @@ async fn main() -> anyhow::Result<()> {
4344
init_logger(tracing::Level::INFO);
4445

4546
// Load config from file
46-
config::load("config.json").await?;
47+
config::load("config.toml").await?;
4748
let config = config::get_config().await;
4849

4950
// Generate key pair
@@ -52,19 +53,19 @@ async fn main() -> anyhow::Result<()> {
5253

5354
// Start HTTP API
5455
let http = build_http_server(SocketAddrV4::new(
55-
Ipv4Addr::new(0, 0, 0, 0),
56-
config.api_port,
56+
Ipv4Addr::from_str(&config.api.addr)?,
57+
config.api.port,
5758
));
5859
tokio::spawn(async move { http.await });
59-
info!("API started on port {}", config.api_port);
60+
info!("API started on port {}", config.api.port);
6061

6162
// Bind TCP server
6263
let listener = TcpListener::bind(SocketAddrV4::new(
63-
Ipv4Addr::new(0, 0, 0, 0),
64-
config.server_port,
64+
Ipv4Addr::from_str(&config.server.addr)?,
65+
config.server.port,
6566
))
6667
.await?;
67-
info!("Server started on port {}", config.server_port);
68+
info!("Server started on port {}", config.server.port);
6869

6970
// Some graceful shutdown things
7071
let shutdown_signal = signal::ctrl_c();
@@ -97,7 +98,7 @@ async fn main() -> anyhow::Result<()> {
9798

9899
tokio::spawn(async move {
99100
// Setting client timeout
100-
match timeout(Duration::from_secs(10), client_handler::handle(stream, keys)).await {
101+
match timeout(Duration::from_secs(config.server.timeout), client_handler::handle(stream, keys)).await {
101102
Ok(_) => info!("Connection from {} closed", addr),
102103
Err(e) => error!("Client exceptionally closed connection: {}", e)
103104
}

src/mojang/mod.rs

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use std::sync::Arc;
55
use anyhow::Result;
66
use sha1::{Digest, Sha1};
77

8-
use crate::client_sessions::Session;
8+
use crate::{client_sessions::Session, config};
99
use rsa::pkcs8::EncodePublicKey;
1010

1111
use num_bigint::BigInt;
@@ -20,12 +20,16 @@ pub async fn join(
2020
digest.update(keys.to_public_key().to_public_key_der()?.as_bytes());
2121
let hash = BigInt::from_signed_bytes_be(&digest.finalize()).to_str_radix(16);
2222

23-
let url = format!(
24-
"https://sessionserver.mojang.com/session/minecraft/hasJoined?username={}&serverId={}",
25-
session.nickname.clone().unwrap(),
26-
hash
27-
);
28-
let response = reqwest::get(url).await?;
23+
let config = config::get_config().await;
24+
let response = reqwest::get(
25+
config
26+
.server
27+
.config
28+
.auth_url
29+
.replace("{{NAME}}", &session.nickname.clone().unwrap())
30+
.replace("{{HASH}}", &hash),
31+
)
32+
.await?;
2933

3034
if response.status().as_u16() != 200 {
3135
return Ok(None);

src/responses/status.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,23 +7,23 @@ use crate::{client_sessions::Session, config::get_config, packets::status};
77

88
pub async fn send(stream: &mut TcpStream, session: &mut Session) -> Result<()> {
99
let config = get_config().await;
10-
let proto_ver = if config.proto_ver == 0 {
10+
let proto_ver = if config.server.config.protocol == 0 {
1111
session.proto_ver.unwrap()
1212
} else {
13-
config.proto_ver
13+
config.server.config.protocol
1414
};
1515

1616
let data = status::StatusData {
1717
version: status::Version {
18-
name: config.server_ver.clone(),
18+
name: config.server.config.version.clone(),
1919
protocol: proto_ver,
2020
},
2121
players: status::Players {
22-
max: config.players_max,
23-
online: config.players_online,
22+
max: config.server.status.players_max,
23+
online: config.server.status.players_online,
2424
sample: vec![],
2525
},
26-
description: json!({"text": config.motd.clone()}),
26+
description: json!({"text": config.server.status.description.clone()}),
2727
favicon: config.image.clone(),
2828
enforces_secure_chat: false,
2929
};

0 commit comments

Comments
 (0)