Lines
0 %
Functions
Branches
100 %
// This file is part of hnefatafl-copenhagen.
//
// hnefatafl-copenhagen is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// hnefatafl-copenhagen is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
#![deny(clippy::expect_used)]
#![deny(clippy::indexing_slicing)]
#![deny(clippy::panic)]
#![deny(clippy::unwrap_used)]
mod accounts;
mod command_line;
mod remove_connection;
mod smtp;
mod tests;
mod unix_timestamp;
use std::{
collections::{HashMap, HashSet, VecDeque},
fmt,
fs::{self, File, OpenOptions},
io::{BufRead, BufReader, ErrorKind, Read, Write},
net::{TcpListener, TcpStream},
process::exit,
str::FromStr,
sync::{
Arc, Mutex,
mpsc::{self, Receiver, Sender},
},
thread::{self, sleep},
time::Duration,
};
use argon2::{Argon2, PasswordHash, PasswordHasher, PasswordVerifier};
use chrono::{DateTime, Days, Local, Utc};
use clap::{CommandFactory, Parser};
use hnefatafl_copenhagen::{
COPYRIGHT, Id, SERVER_PORT, VERSION_ID,
board::BoardSize,
draw::Draw,
email::Email,
game::TimeUnix,
glicko::Outcome,
rating::Rated,
role::Role,
server_game::{
ArchivedGame, Challenger, Messenger, ServerGame, ServerGameLight, ServerGameSerialized,
ServerGames, ServerGamesLight,
status::Status,
time::{Time, TimeEnum, TimeSettings},
tournament::{self, Player, Players, Tournament, TournamentTree, Wins},
utils::{self, create_data_folder, data_file},
use lettre::{
SmtpTransport, Transport,
message::{Mailbox, header::ContentType},
transport::smtp::authentication::Credentials,
use log::{debug, error, info, trace};
use old_rand::{rngs::OsRng, seq::SliceRandom, thread_rng};
use password_hash::SaltString;
use rand::random;
use serde::{Deserialize, Serialize};
use std::fmt::Write as _;
use crate::{
accounts::{Account, Accounts},
command_line::Args,
remove_connection::RemoveConnection,
smtp::Smtp,
unix_timestamp::UnixTimestamp,
const ACTIVE_GAMES_FILE: &str = "active-games.postcard";
const ARCHIVED_GAMES_FILE: &str = "archived-games.ron";
/// Seconds in two months: `60.0 * 60.0 * 24.0 * 30.417 * 2.0 = 5_256_057.6`
const TWO_MONTHS: i64 = 5_256_058;
const SEVEN_DAYS: i64 = 1_000 * 60 * 60 * 24 * 7;
const USERS_FILE: &str = "users.ron";
const MESSAGE_FILE: &str = "message.txt";
#[allow(clippy::too_many_lines)]
fn main() -> anyhow::Result<()> {
// println!("{:x}", rand::random::<u32>());
// return Ok(());
let args = Args::parse();
utils::init_logger("hnefatafl_server_full", args.debug, args.systemd);
if args.man {
let mut buffer: Vec<u8> = Vec::default();
let cmd = Args::command()
.name("hnefatafl-server-full")
.long_version(None);
let man = clap_mangen::Man::new(cmd).date("2025-06-23");
man.render(&mut buffer)?;
write!(buffer, "{COPYRIGHT}")?;
std::fs::write("hnefatafl-server-full.1", buffer)?;
return Ok(());
}
create_data_folder()?;
let (tx, rx) = mpsc::channel();
let mut server = Server {
tx: Some(tx.clone()),
..Server::default()
if !args.skip_the_data_file {
let users_file = data_file(USERS_FILE);
match &fs::read_to_string(&users_file) {
Ok(string) => match ron::from_str(string.as_str()) {
Ok(server_ron) => {
server = server_ron;
server.tx = Some(tx.clone());
Err(err) => {
return Err(anyhow::Error::msg(format!(
"RON: {}: {err}",
users_file.display(),
)));
Err(err) => match err.kind() {
ErrorKind::NotFound => {}
_ => return Err(anyhow::Error::msg(err.to_string())),
let archived_games_file = data_file(ARCHIVED_GAMES_FILE);
match fs::read_to_string(&archived_games_file) {
Ok(archived_games_string) => {
let mut archived_games = Vec::new();
for line in archived_games_string.lines() {
let archived_game: ArchivedGame = match ron::from_str(line) {
Ok(archived_game) => archived_game,
archived_games_file.display(),
archived_games.push(archived_game);
server.archived_games = archived_games;
error!("archived games file not found: {err}");
let active_games_file = data_file(ACTIVE_GAMES_FILE);
if fs::exists(&active_games_file)? {
let mut file = File::open(active_games_file)?;
let mut data = Vec::new();
file.read_to_end(&mut data)?;
let games: Vec<ServerGameSerialized> = postcard::from_bytes(data.as_slice())?;
for game in games {
let id = game.id;
let server_game_light = ServerGameLight::from(&game);
let server_game = ServerGame::from(game);
server.games_light.0.insert(id, server_game_light);
server.games.0.insert(id, server_game);
let tx_signals = tx.clone();
ctrlc::set_handler(move || {
if !args.systemd {
println!();
handle_error(tx_signals.send(("0 server exit".to_string(), None)));
})?;
if args.skip_the_data_file {
server.skip_the_data_file = true;
thread::spawn(move || handle_error(server.handle_messages(&rx)));
if !args.skip_advertising_updates {
let tx_messages_1 = tx.clone();
thread::spawn(move || {
loop {
handle_error(tx_messages_1.send(("0 server display_server".to_string(), None)));
thread::sleep(Duration::from_secs(1));
});
let tx_messages_2 = tx.clone();
handle_error(tx_messages_2.send(("0 server check_update_rd".to_string(), None)));
thread::sleep(Duration::from_secs(60 * 60 * 24));
let tx_messages_3 = tx.clone();
handle_error(tx_messages_3.send(("0 server tournament_start".to_string(), None)));
let now_utc = Utc::now();
let tomorrow_midnight_utc = (now_utc + Days::new(1))
.date_naive()
.and_hms_opt(0, 0, 0)
.unwrap_or_else(|| {
error!("and_hms_opt failed");
exit(1)
})
.and_local_timezone(Utc)
.single()
error!("single failed");
let duration_until_midnight = tomorrow_midnight_utc.signed_duration_since(now_utc);
debug!(
"seconds until midnight UTC: {}",
duration_until_midnight.num_seconds()
);
let std_duration = duration_until_midnight.to_std().unwrap_or_else(|error| {
error!("to_std failed: {error}");
sleep(std_duration);
sleep(Duration::from_secs(1));
let mut address = "[::]".to_string();
address.push_str(SERVER_PORT);
let listener = match TcpListener::bind(&address) {
Ok(listener) => listener,
Err(error) => {
error!("TcpLister::bind: {error}");
address = "0.0.0.0".to_string();
TcpListener::bind(&address)?
info!("listening on {address} ...");
for (index, stream) in (1..).zip(listener.incoming()) {
let stream = match stream {
Ok(stream) => stream,
error!("stream: {error}");
continue;
if args.secure {
let peer_address = match stream.peer_addr() {
Ok(peer_address) => peer_address.ip(),
error!("peer_address: {error}");
let (tx_close, rx_close) = mpsc::channel();
tx.send((
format!("0 server connection_add {peer_address}"),
Some(tx_close),
))?;
match rx_close.recv() {
Ok(close) => match close.parse() {
Ok(close) => {
if close {
error!("close 2: {error}");
error!("close 1: {error}");
let tx = tx.clone();
if let Err(error) = login(index, stream, &tx) {
error!("login: {error}");
Ok(())
fn login(
id: Id,
mut stream: TcpStream,
tx: &mpsc::Sender<(String, Option<mpsc::Sender<String>>)>,
) -> anyhow::Result<()> {
let _remove_connection;
_remove_connection = RemoveConnection {
address: stream.peer_addr()?.ip(),
tx: tx.clone(),
let mut reader = BufReader::new(stream.try_clone()?);
let mut buf = String::new();
let (client_tx, client_rx) = mpsc::channel();
let mut username_proper = "_".to_string();
let mut login_successful = false;
for _ in 0..100 {
reader.read_line(&mut buf)?;
for ch in buf.trim().chars() {
if ch.is_control() || ch == '\0' {
return Err(anyhow::Error::msg(
"there are control characters in the username or password",
));
if buf.trim().is_empty() {
"The user sent a command without logging in, then quit.",
let buf_clone = buf.clone();
let mut username_password_etc = buf_clone.split_ascii_whitespace();
let version_id = username_password_etc.next();
let create_account_login = username_password_etc.next();
let username_option = username_password_etc.next();
if let (Some(version_id), Some(create_account_login), Some(username)) =
(version_id, create_account_login, username_option)
{
username_proper = username.to_string();
if version_id != VERSION_ID {
stream.write_all(b"? login wrong_version\n")?;
buf.clear();
let password: Vec<&str> = username_password_etc.collect();
let password = password.join(" ");
if username.len() > 16 {
stream.write_all(b"? login _ username is more than 16 characters\n")?;
if password.len() > 32 {
stream.write_all(b"? login _ password is more than 32 characters\n")?;
debug!("{id} {username} {create_account_login} {password}");
if create_account_login == "reset_password" {
format!("0 {username} reset_password"),
Some(client_tx.clone()),
stream.write_all(b"? login reset_password\n")?;
format!("{id} {username} {create_account_login} {password}"),
let message = client_rx.recv()?;
if create_account_login == "login" {
if "= login" == message.as_str() {
login_successful = true;
break;
stream.write_all(b"? login multiple_possible_errors\n")?;
} else if create_account_login == "create_account" {
if "= create_account" == message.as_str() {
stream.write_all(b"? create_account\n")?;
stream.write_all(b"? login _\n")?;
if !login_successful {
return Err(anyhow::Error::msg("the user failed to login"));
stream.write_all(b"= login\n")?;
if let Err(error) = receiving_and_writing(stream, &client_rx) {
error!("receiving_and_writing: {error}");
tx.send((format!("{id} {username_proper} email_get"), None))?;
tx.send((format!("{id} {username_proper} texts"), None))?;
tx.send((format!("{id} {username_proper} message"), None))?;
tx.send((format!("{id} {username_proper} display_games"), None))?;
tx.send((format!("{id} {username_proper} tournament_status"), None))?;
tx.send((format!("{id} {username_proper} admin"), None))?;
'outer: for _ in 0..1_000_000 {
if let Err(err) = reader.read_line(&mut buf) {
error!("reader.read_line(): {err}");
break 'outer;
let buf_str = buf.trim();
if buf_str.is_empty() {
for char in buf_str.chars() {
if char.is_control() || char == '\0' {
tx.send((format!("{id} {username_proper} {buf_str}"), None))?;
tx.send((format!("{id} {username_proper} logout"), None))?;
fn receiving_and_writing<T: Send + Write>(
mut stream: T,
client_rx: &Receiver<String>,
for mut message in client_rx {
match message.as_str() {
"= archived_games" => {
let ron_archived_games = client_rx.recv()?;
let archived_games: Vec<ArchivedGame> = ron::from_str(&ron_archived_games)?;
let postcard_archived_games = &postcard::to_allocvec(&archived_games)?;
writeln!(message, " {}", postcard_archived_games.len())?;
stream.write_all(message.as_bytes())?;
stream.write_all(postcard_archived_games)?;
"= logout" => return Ok(()),
_ => {
message.push('\n');
if let Err(error) = stream.write_all(message.as_bytes()) {
return Err(anyhow::Error::msg(format!("{message}: {error}")));
fn generate_round_one(players: Vec<Player>) -> Vec<tournament::Status> {
let players_len = players.len();
if players_len == 1
&& let Some(player) = players.first()
return vec![tournament::Status::Won(player.clone())];
let mut power = 1;
while power < players_len {
power *= 2;
let mut tournament_players = VecDeque::new();
for player in players {
tournament_players.push_front(tournament::Status::Ready(player));
for _ in 0..(power - players_len) {
tournament_players.push_back(tournament::Status::None);
let mut round = Vec::new();
for i in 0..tournament_players.len() {
if i % 2 == 0 {
let Some(player) = tournament_players.pop_back() else {
unreachable!()
round.push(player);
} else {
let Some(player) = tournament_players.pop_front() else {
let mut round_new = Vec::new();
for statuses in round.chunks(2) {
let (Some(status_1), Some(status_2)) = (statuses.first(), statuses.get(1)) else {
return round_new;
let status_1 = status_1.clone();
let status_2 = status_2.clone();
let (status_1, status_2) = match (status_1, status_2) {
(tournament::Status::Ready(player), tournament::Status::None) => (
tournament::Status::Won(player.clone()),
tournament::Status::None,
),
(tournament::Status::None, tournament::Status::Ready(player)) => (
(status_1, status_2) => (status_1, status_2),
round_new.push(status_1);
round_new.push(status_2);
round = round_new;
round
fn handle_error<T, E: fmt::Display>(result: Result<T, E>) -> T {
match result {
Ok(value) => value,
error!("{error}");
fn hash_password(password: &str) -> Option<String> {
let ctx = Argon2::default();
let salt = SaltString::generate(&mut OsRng);
Some(
ctx.hash_password(password.as_bytes(), &salt)
.ok()?
.to_string(),
)
fn timestamp() -> String {
Utc::now().format("[%F %T UTC]").to_string()
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
struct Server {
#[serde(default)]
game_id: Id,
ran_update_rd: UnixTimestamp,
admins: HashSet<String>,
smtp: Smtp,
tournament: Option<Tournament>,
accounts: Accounts,
#[serde(skip)]
accounts_old: Accounts,
archived_games: Vec<ArchivedGame>,
clients: HashMap<usize, mpsc::Sender<String>>,
connections: HashMap<String, u128>,
games: ServerGames,
games_light: ServerGamesLight,
games_light_old: ServerGamesLight,
skip_the_data_file: bool,
texts: VecDeque<String>,
tx: Option<mpsc::Sender<(String, Option<mpsc::Sender<String>>)>>,
impl Server {
fn append_archived_game(&mut self, game: ServerGame) -> anyhow::Result<()> {
let Some(attacker) = self.accounts.0.get(&game.attacker) else {
return Err(anyhow::Error::msg("failed to get rating!"));
let Some(defender) = self.accounts.0.get(&game.defender) else {
let game = ArchivedGame::new(game, attacker.rating.clone(), defender.rating.clone());
let mut game_string = ron::ser::to_string(&game)?;
game_string.push('\n');
let mut file = OpenOptions::new()
.create(true)
.append(true)
.open(archived_games_file)?;
file.write_all(game_string.as_bytes())?;
self.archived_games.push(game);
fn bcc_mailboxes(&self, username: &str) -> Vec<Mailbox> {
let mut emails = Vec::new();
if let Some(account) = self.accounts.0.get(username)
&& account.send_emails
for account in self.accounts.0.values() {
if let Some(email) = &account.email
&& email.verified
&& let Some(email) = email.to_mailbox()
emails.push(email);
emails
fn bcc_send(&self, username: &str) -> String {
emails.push(email.tx());
emails.sort();
emails.join(" ")
/// ```sh
/// # PASSWORD can be the empty string.
/// <- change_password PASSWORD
/// -> = change_password
/// ```
fn change_password(
&mut self,
username: &str,
index_supplied: usize,
command: &str,
the_rest: &[&str],
) -> Option<(mpsc::Sender<String>, bool, String)> {
info!("{index_supplied} {username} change_password");
let account = self.accounts.0.get_mut(username)?;
let password = the_rest.join(" ");
return Some((
self.clients.get(&index_supplied)?.clone(),
false,
format!("{command} password is greater than 32 characters"),
let hash = hash_password(&password)?;
account.password = hash;
self.save_server();
Some((
true,
(*command).to_string(),
))
/// # server internal
///
/// c = 63.2
/// This assumes 30 2 month periods must pass before one's rating
/// deviation is the same as a new player and that a typical RD is 50.
#[must_use]
fn check_update_rd(&mut self) -> bool {
let now = Local::now().to_utc().timestamp();
if now - self.ran_update_rd.0 >= TWO_MONTHS {
for account in self.accounts.0.values_mut() {
account.rating.update_rd();
self.ran_update_rd = UnixTimestamp(now);
true
false
/// <- VERSION_ID create_account player-1 PASSWORD
/// -> = login
fn create_account(
option_tx: Option<Sender<String>>,
let tx = option_tx?;
if self.accounts.0.contains_key(username) || username == "server" {
info!("{index_supplied} {username} is already in the database");
Some((tx, false, (*command).to_string()))
info!("{index_supplied} {username} created user account");
self.clients.insert(index_supplied, tx);
self.accounts.0.insert(
(*username).to_string(),
Account {
password: hash,
logged_in: Some(index_supplied),
..Default::default()
fn decline_game(
mut command: String,
let channel = self.clients.get(&index_supplied)?;
let Some(id) = the_rest.first() else {
return Some((channel.clone(), false, command));
let Ok(id) = id.parse::<Id>() else {
let mut switch = false;
if let Some(&"switch") = the_rest.get(1) {
switch = true;
info!("{index_supplied} {username} decline_game {id} switch={switch}");
if let Some(game_old) = self.games_light.0.remove(&id) {
let mut attacker = None;
let mut attacker_channel = None;
let mut defender = None;
let mut defender_channel = None;
if switch {
if Some(username.to_string()) == game_old.attacker {
defender = game_old.defender;
defender_channel = game_old.defender_channel;
} else if Some(username.to_string()) == game_old.defender {
attacker = game_old.attacker;
attacker_channel = game_old.attacker_channel;
} else if Some(username.to_string()) == game_old.attacker {
let game = ServerGameLight {
id,
attacker,
defender,
challenger: Challenger::default(),
rated: game_old.rated,
timed: game_old.timed,
board_size: game_old.board_size,
attacker_channel,
defender_channel,
spectators: game_old.spectators,
challenge_accepted: false,
game_over: false,
command = format!("{command} {game:?}");
self.games_light.0.insert(id, game);
Some((channel.clone(), true, command))
fn delete_account(&mut self, username: &str, index_supplied: usize) {
info!("{index_supplied} {username} delete_account");
self.accounts.0.remove(username);
fn display_server(&mut self, username: &str) -> Option<(mpsc::Sender<String>, bool, String)> {
if self.games_light != self.games_light_old {
debug!("0 {username} display_games");
self.games_light_old = self.games_light.clone();
for tx in &mut self.clients.values() {
let _ok = tx.send(format!("= display_games {:?}", &self.games_light));
if self.accounts != self.accounts_old {
debug!("0 {username} display_users");
self.accounts_old = self.accounts.clone();
let _ok = tx.send(format!("= display_users {}", &self.accounts));
for game in self.games.0.values_mut() {
match game.game.turn {
Role::Attacker => {
if game.game.status == Status::Ongoing
&& let TimeUnix::Time(game_time) = &mut game.game.time
let now = Local::now().to_utc().timestamp_millis();
let elapsed_time = now - *game_time;
game.elapsed_time += elapsed_time;
*game_time = now;
if game.elapsed_time > SEVEN_DAYS
&& let Some(tx) = &mut self.tx
let _ok = tx.send((
format!(
"0 {} game {} play attacker resigns _",
game.attacker, game.id
None,
return None;
if let TimeSettings::Timed(attacker_time) = &mut game.game.attacker_time {
if attacker_time.milliseconds_left > 0 {
attacker_time.milliseconds_left -= elapsed_time;
} else if let Some(tx) = &mut self.tx {
Role::Roleless => {}
Role::Defender => {
"0 {} game {} play defender resigns _",
game.defender, game.id
if let TimeSettings::Timed(defender_time) = &mut game.game.defender_time {
if defender_time.milliseconds_left > 0 {
defender_time.milliseconds_left -= elapsed_time;
None
fn draw(
let Some(draw) = the_rest.get(1) else {
let Ok(draw) = Draw::from_str(draw) else {
let Some(mut game) = self.games.0.remove(&id) else {
let message = format!("= draw {draw}");
game.attacker_tx.send(message.clone());
game.defender_tx.send(message.clone());
if draw == Draw::Accept {
let Some(game_light) = self.games_light.0.get(&id) else {
for spectator in game_light.spectators.values() {
if let Some(sender) = self.clients.get(spectator) {
let _ok = sender.send(message.clone());
game.game.status = Status::Draw;
let accounts = &mut self.accounts.0;
let (attacker_rating, defender_rating) = if let (Some(attacker), Some(defender)) =
(accounts.get(&game.attacker), accounts.get(&game.defender))
(attacker.rating.rating, defender.rating.rating)
unreachable!();
if let Some(attacker) = accounts.get_mut(&game.attacker) {
attacker.draws += 1;
if game.rated.into() {
attacker
.rating
.update_rating(defender_rating, &Outcome::Draw);
if let Some(defender) = accounts.get_mut(&game.defender) {
defender.draws += 1;
defender
.update_rating(attacker_rating, &Outcome::Draw);
if let Some(game) = self.games_light.0.get_mut(&id) {
game.game_over = true;
if !self.skip_the_data_file {
self.append_archived_game(game)
.map_err(|err| {
error!("append_archived_games: {err}");
.ok()?;
fn game(
if the_rest.len() < 5 {
let index = the_rest.first()?;
let Ok(index) = index.parse() else {
let role = the_rest.get(2)?;
let Ok(role) = Role::from_str(role) else {
let from = the_rest.get(3)?;
let to = the_rest.get(4)?;
let mut to = (*to).to_string();
if to == "_" {
to = String::new();
let Some(game) = self.games.0.get_mut(&index) else {
let Some(game_light) = self.games_light.0.get_mut(&index) else {
game.elapsed_time = 0;
let mut attackers_turn_next = true;
if role == Role::Attacker {
if *username == game.attacker {
game.game
.read_line(&format!("play attacker {from} {to}"))
.map_err(|error| {
error!("play attacker {from} {to}: {error}");
error
attackers_turn_next = false;
let message = format!("game {index} play attacker {from} {to}");
if let Some(client) = self.clients.get(spectator) {
let _ok = client.send(message.clone());
game.defender_tx.send(message);
} else if *username == game.defender {
.read_line(&format!("play defender {from} {to}"))
error!("play defender {from} {to}: {error}");
let message = format!("game {index} play defender {from} {to}");
game.attacker_tx.send(message);
let mut game_over = false;
let mut winner_role = Role::Roleless;
let mut winner_wins = None;
match game.game.status {
Status::AttackerWins => {
attacker.wins += 1;
.update_rating(defender_rating, &Outcome::Win);
defender.losses += 1;
.update_rating(attacker_rating, &Outcome::Loss);
let message = format!("= game_over {index} attacker_wins");
game_over = true;
winner_role = Role::Attacker;
Status::Draw => {
// Handled in the draw fn.
Status::Ongoing => {
if attackers_turn_next {
game.attacker_tx
.send(format!("game {index} generate_move attacker"));
game.defender_tx
.send(format!("game {index} generate_move defender"));
Status::DefenderWins => {
attacker.losses += 1;
.update_rating(defender_rating, &Outcome::Loss);
defender.wins += 1;
.update_rating(attacker_rating, &Outcome::Win);
let message = format!("= game_over {index} defender_wins");
winner_role = Role::Defender;
if game_over {
let mut attacker_defender = None;
let Some(game) = self.games.0.remove(&index) else {
if let Some(game_light) = self.games_light.0.get_mut(&index) {
game_light.game_over = true;
let mut active_game_arc = None;
let mut tournament_status_update = false;
if let Some(tournament) = &mut self.tournament
&& let Some(tree) = &mut tournament.tree
&& let Some(active_game) = tree.active_games.get_mut(&game.id)
tournament_status_update = true;
active_game_arc = Some(active_game.clone());
let mut active_game = active_game.lock().ok()?;
match winner_role {
if game.attacker == active_game.player_1.name {
active_game.player_1.attacker += 1;
active_game.player_2.attacker += 1;
if game.defender == active_game.player_1.name {
active_game.player_1.defender += 1;
active_game.player_2.defender += 1;
let player_1_wins = active_game.player_1.attacker + active_game.player_1.defender;
let player_2_wins = active_game.player_2.attacker + active_game.player_2.defender;
let total_wins = player_1_wins + player_2_wins;
let rating_1 = if let Some(account_1) =
self.accounts.0.get(active_game.player_1.name.as_str())
account_1.rating.rating.round()
1500.0
let rating_2 = if let Some(account_2) =
self.accounts.0.get(active_game.player_2.name.as_str())
account_2.rating.rating.round()
trace!("total_wins: {total_wins}");
if total_wins < 2 {
// Do nothing.
} else if total_wins % 2 == 0 || total_wins > 4 {
if player_1_wins > player_2_wins {
winner_wins = Some(active_game.player_1.clone());
} else if player_2_wins > player_1_wins {
winner_wins = Some(active_game.player_2.clone());
} else if active_game.player_1.attacker > active_game.player_2.attacker {
} else if active_game.player_2.attacker > active_game.player_1.attacker {
trace!(
"winner: {winner_wins:#?}, active_game_round: {}",
active_game.round
if let Some(ref mut winner) = winner_wins
&& let winner_name = winner.name.as_str()
&& let Some(round) = tree.rounds.get_mut(active_game.round)
for (i, statuses) in round.chunks_mut(2).enumerate() {
if i == active_game.chunk {
let (status_1, status_2) = statuses.split_at_mut(1);
let (Some(status_1), Some(status_2)) =
(status_1.first_mut(), status_2.first_mut())
else {
if winner_name == active_game.player_1.name.as_str() {
*status_1 = tournament::Status::Won(Player {
name: active_game.player_1.name.clone(),
rating: rating_1,
*status_2 = tournament::Status::Lost(Player {
name: active_game.player_2.name.clone(),
rating: rating_2,
*status_1 = tournament::Status::Lost(Player {
*status_2 = tournament::Status::Won(Player {
} else if total_wins > 1 {
if total_wins % 2 == 0 {
// Add a game with the higher rated player as the attacker.
let player_1_attacking = if rating_1 > rating_2 {
} else if rating_1 < rating_2 {
random()
if player_1_attacking {
attacker_defender =
Some((active_game.player_1.clone(), active_game.player_2.clone()));
Some((active_game.player_2.clone(), active_game.player_1.clone()));
// Add the player as the attacker with more total wins.
tree.active_games.remove(&game.id);
if tournament_status_update {
self.tournament_update_wins();
self.tournament_ready_to_playing();
self.tournament_status_all();
error!("append_archived_game: {err}");
"attacker_defender: {attacker_defender:#?}, active_game_arc: {active_game_arc:#?}"
if let (Some((attacker, defender)), Some(active_game)) =
(attacker_defender, active_game_arc)
let id = self.new_tournament_game(&attacker.name, &defender.name);
tree.active_games.insert(id, active_game);
fn set_email(
email: Option<&str>,
let Some(address) = email else {
let Some(account) = self.accounts.0.get_mut(username) else {
let random_u32 = random();
let email = Email {
address: address.to_string(),
code: Some(random_u32),
username: username.to_string(),
verified: false,
info!("{index_supplied} {username} email {}", email.tx());
let email_send = lettre::Message::builder()
.from("Hnefatafl Org <no-reply@hnefatafl.org>".parse().ok()?)
.to(email.to_mailbox()?)
.subject("Account Verification")
.header(ContentType::TEXT_PLAIN)
.body(format!(
"Dear {username},\nyour email verification code is as follows: {random_u32:x}",
let credentials = Credentials::new(self.smtp.username.clone(), self.smtp.password.clone());
let mailer = SmtpTransport::relay(&self.smtp.service)
.credentials(credentials)
.build();
match mailer.send(&email_send) {
Ok(_) => {
info!("email sent to {address} successfully!");
account.email = Some(email);
let reply = format!("email {address} false");
Some((self.clients.get(&index_supplied)?.clone(), true, reply))
let reply = format!("could not send email to {address}");
error!("{reply}: {err}");
Some((self.clients.get(&index_supplied)?.clone(), false, reply))
pub(crate) fn handle_messages(
rx: &mpsc::Receiver<(String, Option<mpsc::Sender<String>>)>,
if let Some((tx, ok, command)) = self.handle_messages_internal(rx) {
if ok {
tx.send(format!("= {command}"))?;
tx.send(format!("? {command}"))?;
fn handle_messages_internal(
let (message, option_tx) = rx.recv().ok()?;
let index_username_command: Vec<_> = message.split_ascii_whitespace().collect();
if let (Some(index_supplied), Some(username), Some(command)) = (
index_username_command.first(),
index_username_command.get(1),
index_username_command.get(2),
) {
if *command != "check_update_rd"
&& *command != "create_account"
&& *command != "display_server"
&& *command != "login"
&& *command != "ping"
debug!("{index_supplied} {username} {command}");
let index_supplied = index_supplied.parse::<usize>().ok()?;
let the_rest: Vec<_> = index_username_command.clone().into_iter().skip(3).collect();
match *command {
"admin" => {
if self.admins.contains(*username) {
self.clients
.get(&index_supplied)?
.send("= admin".to_string())
"archived_games" => {
.send("= archived_games".to_string())
.send(ron::ser::to_string(&self.archived_games).ok()?)
"change_password" => {
self.change_password(username, index_supplied, command, the_rest.as_slice())
"check_update_rd" => {
let bool = self.check_update_rd();
info!("0 {username} check_update_rd {bool}");
"connection_add" => {
if let Some(address) = the_rest.first()
&& let Some(tx) = option_tx
if let Some(connections) = self.connections.get(*address)
&& *connections > 2_000
tx.send("true".to_string()).ok()?;
tx.send("false".to_string()).ok()?;
let entry = self.connections.entry(address.to_string());
entry.and_modify(|value| *value += 1).or_insert(1);
debug!("connections: {:?}", self.connections);
"connection_remove" => {
if let Some(connection) = the_rest.first() {
let entry = self.connections.entry(connection.to_string());
entry.and_modify(|value| *value = value.saturating_sub(1));
if let Some(value) = self.connections.get(*connection)
&& *value == 0
self.connections.remove(*connection);
"create_account" => self.create_account(
username,
index_supplied,
command,
the_rest.as_slice(),
option_tx,
"decline_game" => self.decline_game(
"delete_account" => {
self.delete_account(username, index_supplied);
"display_games" => {
if args.skip_advertising_updates {
self.clients.get(&index_supplied).map(|tx| {
(
tx.clone(),
format!("display_games {:?}", &self.games_light),
"display_server" => self.display_server(username),
"draw" => self.draw(index_supplied, command, the_rest.as_slice()),
"game" => self.game(index_supplied, username, command, the_rest.as_slice()),
"email" => {
self.set_email(index_supplied, username, command, the_rest.first().copied())
"email_everyone" => {
info!("{index_supplied} {username} email_everyone");
error!("{index_supplied} {username} email_everyone");
let emails_bcc = self.bcc_mailboxes(username);
let subject = the_rest.first()?;
let email_string = the_rest.get(1..)?.join(" ").replace("\\n", "\n");
let mut email = lettre::Message::builder();
for email_bcc in emails_bcc {
email = email.bcc(email_bcc);
let email = email
.subject(*subject)
.body(email_string)
let credentials =
Credentials::new(self.smtp.username.clone(), self.smtp.password.clone());
match mailer.send(&email) {
info!("emails sent successfully!");
let reply = "could not send emails";
reply.to_string(),
"emails_bcc" => {
let emails_bcc = self.bcc_send(username);
if !emails_bcc.is_empty() {
.send(format!("= emails_bcc {emails_bcc}"))
"email_code" => {
if let Some(account) = self.accounts.0.get_mut(*username)
&& let Some(email) = &mut account.email
&& let (Some(code_1), Some(code_2)) = (email.code, the_rest.first())
if format!("{code_1:x}") == *code_2 {
email.verified = true;
.send("= email_code".to_string())
email.verified = false;
.send("? email_code".to_string())
"email_get" => {
if let Some(account) = self.accounts.0.get(*username)
&& let Some(email) = &account.email
.send(format!("= email {} {}", email.address, email.verified))
"email_reset" => {
if let Some(account) = self.accounts.0.get_mut(*username) {
account.email = None;
"exit" => {
info!("saving active games...");
let mut active_games = Vec::new();
for game in self.games.0.values() {
let mut serialized_game = ServerGameSerialized::from(game);
if let Some(game_light) = self.games_light.0.get(&game.id) {
serialized_game.timed = game_light.timed.clone();
active_games.push(serialized_game);
let mut file = handle_error(File::create(data_file(ACTIVE_GAMES_FILE)));
handle_error(
file.write_all(
handle_error(postcard::to_allocvec(&active_games)).as_slice(),
exit(0);
"join_game" => self.join_game(
"join_game_pending" => self.join_game_pending(
"join_tournament" => {
if let Some(tournament) = &mut self.tournament {
tournament.players.insert(username.to_string());
"leave_game" => self.leave_game(
"leave_tournament" => {
tournament.players.remove(*username);
"login" => self.login(
"logout" => self.logout(username, index_supplied, command),
"message" => {
if Args::parse().skip_message {
let message_file = data_file(MESSAGE_FILE);
let mut message = String::new();
match fs::read_to_string(&message_file) {
Ok(new_message) => message = new_message.trim().replace('\n', "\\n"),
_ => error!("Error loading message: {err}"),
if message.trim().is_empty() {
.send(format!("= message {message}"))
"new_game" => self.new_game(username, index_supplied, command, the_rest.as_slice()),
"ping" => Some((
)),
"reset_password" => {
let account = self.accounts.0.get_mut(*username)?;
if let Some(email) = &account.email {
if email.verified {
let day = 60 * 60 * 24;
let now = Utc::now().timestamp();
if now - account.email_sent > day {
let password = format!("{:x}", random::<u32>());
account.password = hash_password(&password)?;
let message = lettre::Message::builder()
.subject("Password Reset")
"Dear {username},\nyour new password is as follows: {password}",
let credentials = Credentials::new(
self.smtp.username.clone(),
self.smtp.password.clone(),
match mailer.send(&message) {
info!("email sent to {} successfully!", email.address);
account.email_sent = now;
error!("could not send email to {}: {err}", email.address);
error!(
"a password reset email was sent less than a day ago for {username}"
error!("the email address for account {username} is unverified");
error!("no email exists for account {username}");
"resume_game" => self.resume_game(username, index_supplied, command, &the_rest),
"request_draw" => self.request_draw(username, index_supplied, command, &the_rest),
"text" => {
let timestamp = timestamp();
let the_rest = the_rest.join(" ");
info!("{index_supplied} {timestamp} {username} text {the_rest}");
let text = format!("= text {timestamp} {username}: {the_rest}");
if self.texts.len() >= 32 {
self.texts.pop_front();
let _ok = tx.send(text.clone());
self.texts.push_back(text);
"texts" => {
if !self.texts.is_empty() {
let string = Vec::from(self.texts.clone()).join("\n");
self.clients.get(&index_supplied)?.send(string).ok()?;
"text_game" => self.text_game(username, index_supplied, command, the_rest),
"tournament_delete" => {
self.tournament = None;
"tournament_tree_delete" => {
if self.admins.contains(*username)
&& let Some(tournament) = &mut self.tournament
tournament.tree = None;
"tournament_date" => {
if let Err(error) = self.tournament_date(&the_rest) {
error!("tournament_date: {error}");
"tournament_status" => {
trace!("tournament_status: {:#?}", self.tournament);
let tx = self.clients.get(&index_supplied)?;
let tournament = ron::ser::to_string(&self.tournament).ok()?;
Some((tx.clone(), true, format!("tournament_status {tournament}")))
"tournament_start" => {
let mut start_tournament = false;
if let Some(tournament) = &self.tournament
&& tournament.tree.is_none()
&& Utc::now() >= tournament.date
start_tournament = true;
if start_tournament {
info!("Starting tournament...");
self.tournament_tree();
"watch_game" => self.watch_game(
"=" => None,
_ => self.clients.get(&index_supplied).map(|channel| {
error!("{index_supplied} {username} {command}");
(channel.clone(), false, (*command).to_string())
}),
error!("{index_username_command:?}");
fn join_game(
command: String,
return Some((self.clients.get(&index_supplied)?.clone(), false, command));
info!("{index_supplied} {username} join_game {id}");
let Some(game) = self.games_light.0.get_mut(&id) else {
game.challenge_accepted = true;
let (Some(attacker_tx), Some(defender_tx)) = (game.attacker_channel, game.defender_channel)
for tx in [&attacker_tx, &defender_tx] {
.get(tx)?
.send(format!(
"= join_game {} {} {} {:?} {}",
game.attacker.clone()?,
game.defender.clone()?,
game.rated,
game.timed,
game.board_size,
let new_game = ServerGame::new(
Some(self.clients.get(&attacker_tx)?.clone()),
Some(self.clients.get(&defender_tx)?.clone()),
game.clone(),
self.games.0.insert(id, new_game);
if let Some(account) = self.accounts.0.get_mut(username) {
account.pending_games.remove(&id);
.get(&attacker_tx)?
.send(format!("game {id} generate_move attacker"))
fn join_game_pending(
username: String,
info!("{index_supplied} {username} join_game_pending {id}");
command.push_str(" the id doesn't refer to a pending game");
if game.attacker.is_none() {
game.attacker = Some(username.clone());
game.attacker_channel = Some(index_supplied);
if let Some(channel) = game.defender_channel
&& let Some(channel) = self.clients.get(&channel)
let _ok = channel.send(format!("= challenge_requested {id}"));
} else if game.defender.is_none() {
game.defender = Some(username.clone());
game.defender_channel = Some(index_supplied);
if let Some(channel) = game.attacker_channel
game.challenger.0 = Some(username);
command.push(' ');
command.push_str(the_rest.first()?);
fn leave_game(
info!("{index_supplied} {username} leave_game {id}");
let mut remove = false;
match self.games_light.0.get_mut(&id) {
Some(game) => {
if let Some(attacker) = &game.attacker
&& username == attacker
game.attacker = None;
if let Some(defender) = &game.defender
&& username == defender
game.defender = None;
if let Some(challenger) = &game.challenger.0
&& username == challenger
game.challenger.0 = None;
game.spectators.remove(username);
if game.attacker.is_none() && game.defender.is_none() {
remove = true;
None => return Some((self.clients.get(&index_supplied)?.clone(), false, command)),
if remove {
self.games_light.0.remove(&id);
Some((self.clients.get(&index_supplied)?.clone(), true, command))
let password_1 = the_rest.join(" ");
// The username is in the database and already logged in.
if let Some(index_database) = account.logged_in {
info!("{index_supplied} {username} login failed, {index_database} is logged in");
Some(((tx), false, (*command).to_string()))
// The username is in the database, but not logged in yet.
let hash_2 = PasswordHash::try_from(account.password.as_str()).ok()?;
if let Err(_error) =
Argon2::default().verify_password(password_1.as_bytes(), &hash_2)
info!("{index_supplied} {username} provided the wrong password");
return Some((tx, false, (*command).to_string()));
info!("{index_supplied} {username} logged in");
account.logged_in = Some(index_supplied);
// The username is not in the database.
info!("{index_supplied} {username} is not in the database");
fn logout(
for id in &account.pending_games {
if let Some(tx) = &self.tx
&& let Some(game) = self.games_light.0.get(id)
&& let TimeSettings::Timed(Time {
milliseconds_left, ..
}) = game.timed
&& milliseconds_left < 1_000 * 60 * 60 * 24
let _ok =
tx.send((format!("{index_supplied} {username} leave_game {id}"), None));
if let Some(index_database) = account.logged_in
&& index_database == index_supplied
info!("{index_supplied} {username} logged out");
account.logged_in = None;
.send("= logout".to_string())
self.clients.remove(&index_database);
.get(&index_supplied)
.map(|sender| (sender.clone(), false, (*command).to_string()))
/// <- new_game attacker rated fischer 900000 10 13
/// -> = new_game game 6 player-1 _ rated fischer 900000 10 _ false {}
fn new_game(
if the_rest.len() < 6 {
let role = the_rest.first()?;
let rated = the_rest.get(1)?;
let Ok(rated) = Rated::from_str(rated) else {
let timed = the_rest.get(2)?;
let minutes = the_rest.get(3)?;
let add_seconds = the_rest.get(4)?;
let Ok(timed) = TimeSettings::try_from(vec!["time-settings", timed, minutes, add_seconds])
let board_size = the_rest.get(5)?;
let board_size = BoardSize::from_str(board_size).ok()?;
info!(
"{index_supplied} {username} new_game {} {role} {rated} {timed:?} {board_size}",
self.game_id
let game = ServerGameLight::new(
self.game_id,
rated,
timed,
board_size,
role,
let command = format!("{command} {game:?}");
self.games_light.0.insert(self.game_id, game);
account.pending_games.insert(self.game_id);
self.game_id += 1;
fn new_tournament_game(&mut self, attacker: &str, defender: &str) -> Id {
let id = self.game_id;
let game_light = ServerGameLight {
attacker: Some(attacker.to_string()),
defender: Some(defender.to_string()),
challenger: Challenger(None),
rated: Rated::Yes,
timed: TimeEnum::Long.into(),
attacker_channel: None,
defender_channel: None,
spectators: HashMap::new(),
challenge_accepted: true,
board_size: BoardSize::_11,
"0 server new_tournament_game {id} {} {:?} {}",
game_light.rated, game_light.timed, game_light.board_size
let game = ServerGame::new(None, None, game_light.clone());
self.games_light.0.insert(id, game_light);
self.games.0.insert(id, game);
id
fn resume_game(
let Some(server_game) = self.games.0.get(&id) else {
let game = &server_game.game;
let Ok(board) = ron::ser::to_string(game) else {
let texts = &server_game.texts;
let Ok(texts) = ron::ser::to_string(&texts) else {
info!("{index_supplied} {username} watch_game {id}");
let Some(game_light) = self.games_light.0.get_mut(&id) else {
if Some((*username).to_string()) == game_light.attacker {
if let Some(server_game) = self.games.0.get_mut(&id) {
server_game.attacker_tx =
Messenger::new(self.clients.get(&index_supplied)?.clone());
game_light.attacker_channel = Some(index_supplied);
} else if Some((*username).to_string()) == game_light.defender {
server_game.defender_tx =
game_light.defender_channel = Some(index_supplied);
"= resume_game {} {} {} {:?} {} {board} {texts}",
game_light.attacker.clone()?,
game_light.defender.clone()?,
game_light.rated,
game_light.timed,
game_light.board_size,
fn request_draw(
let Some(role) = the_rest.get(1) else {
info!("{index_supplied} {username} request_draw {id} {role}");
let message = format!("request_draw {id} {role}");
if let Some(game) = self.games.0.get(&id) {
match role {
fn save_server(&self) {
let mut server = self.clone();
for account in server.accounts.0.values_mut() {
match ron::ser::to_string_pretty(&server, ron::ser::PrettyConfig::default()) {
Ok(string) => {
if !string.trim().is_empty() {
match File::create(&users_file) {
Ok(mut file) => {
if let Err(error) = file.write_all(string.as_bytes()) {
error!("save file (3): {error}");
Err(error) => error!("save file (2): {error}"),
Err(error) => error!("save file (1): {error}"),
fn text_game(
mut the_rest: Vec<&str>,
let text = the_rest.split_off(1);
let mut text = text.join(" ");
text = format!("{timestamp} {username}: {text}");
info!("{index_supplied} {username} text_game {id} {text}");
if let Some(game) = self.games.0.get_mut(&id) {
game.texts.push_front(text.clone());
text = format!("= text_game {text}");
if let Some(game) = self.games_light.0.get(&id) {
let mut watching = false;
for (spectator, index) in &game.spectators {
if spectator == username {
watching = true;
if let Some(sender) = self.clients.get(index) {
let _ok = sender.send(text.clone());
if watching {
if let Some(attacker_channel) = game.attacker_channel
&& let Some(sender) = self.clients.get(&attacker_channel)
if let Some(defender_channel) = game.defender_channel
&& let Some(sender) = self.clients.get(&defender_channel)
fn tournament_date(&mut self, the_rest: &[&str]) -> anyhow::Result<()> {
let mut tournament = Tournament::default();
let Some(date) = the_rest.first() else {
return Err(anyhow::Error::msg("tournament_date: date is empty"));
let datetime = match DateTime::parse_from_str(
&format!("{date} 00:00:00 +0000"),
"%Y-%m-%d %H:%M:%S %z",
Ok(datetime) => datetime,
Err(error) => return Err(anyhow::Error::msg(format!("tournament_date: {error}"))),
tournament.date = datetime.to_utc();
self.tournament = Some(tournament);
fn tournament_ready_to_playing(&mut self) {
let mut new_games = Vec::new();
for (i, round) in tree.rounds.iter_mut().enumerate() {
for (j, statuses) in round.chunks_mut(2).enumerate() {
if let tournament::Status::Ready(player_1) = status_1.clone()
&& let tournament::Status::Ready(player_2) = status_2.clone()
*status_1 = tournament::Status::Playing(player_1.clone());
*status_2 = tournament::Status::Playing(player_2.clone());
new_games.push((player_1.name, player_2.name, i, j));
trace!("new_games: {new_games:#?}");
for (player_1, player_2, round, chunk) in new_games {
let id_1 = self.new_tournament_game(&player_1, &player_2);
let id_2 = self.new_tournament_game(&player_2, &player_1);
let game_players = Players {
round,
chunk,
player_1: Wins {
name: player_1,
attacker: 0,
defender: 0,
player_2: Wins {
name: player_2,
let game_players = Arc::new(Mutex::new(game_players));
tree.active_games.insert(id_1, game_players.clone());
tree.active_games.insert(id_2, game_players.clone());
fn tournament_status_all(&self) {
if let Ok(mut tournament) = ron::ser::to_string(&self.tournament) {
tournament = format!("= tournament_status {tournament}");
for tx in self.clients.values() {
let _ok = tx.send(tournament.clone());
fn tournament_tree(&mut self) {
let Some(tournament) = &mut self.tournament else {
return;
let mut players = Vec::new();
for player in &tournament.players {
if let Some(account) = self.accounts.0.get(player) {
players.push(Player {
name: player.clone(),
rating: account.rating.rating.round_ties_even(),
let mut rng = thread_rng();
players.shuffle(&mut rng);
players.sort_unstable_by(|a, b| a.rating.total_cmp(&b.rating));
tournament.tree = Some(TournamentTree {
active_games: HashMap::new(),
rounds: vec![generate_round_one(players)],
fn tournament_update_wins(&mut self) {
let mut updates = Vec::new();
let mut player = None;
let mut move_forward = false;
let new_round_length = round.len() / 2;
for (mut j, status) in round.iter_mut().enumerate() {
if j % 2 == 0 {
move_forward = false;
player = None;
j /= 2;
if j % 2 != 0 {
j = new_round_length - j;
match &status {
tournament::Status::Lost(_)
| tournament::Status::Playing(_)
| tournament::Status::Waiting => continue,
tournament::Status::None => {
move_forward = true;
tournament::Status::Ready(p) => player = Some(p.clone()),
tournament::Status::Won(player) => {
updates.push((i + 1, j, player.clone()));
if move_forward && let Some(player) = &player {
for (i, j, player) in updates {
let len;
if let Some(round) = tree.rounds.get(i - 1) {
len = round.len() / 2;
error!("tree.rounds.get({i} - 1) is None");
if tree.rounds.get(i).is_none() {
for _ in 0..len {
round.push(tournament::Status::Waiting);
tree.rounds.push(round);
if let Some(round) = tree.rounds.get_mut(i)
&& let Some(status) = round.get_mut(j)
match status {
| tournament::Status::None
| tournament::Status::Ready(_)
| tournament::Status::Won(_) => {}
tournament::Status::Waiting => *status = tournament::Status::Ready(player),
error!("tree.rounds[{i}][{j}] is None");
fn watch_game(
game.spectators.insert(username.to_string(), index_supplied);
"= watch_game {} {} {} {:?} {} {board} {texts}",