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/>.
// SPDX-License-Identifier: AGPL-3.0-or-later
// SPDX-FileCopyrightText: 2025 David Campbell <david@hnefatafl.org>
#![deny(clippy::indexing_slicing)]
#![deny(clippy::expect_used)]
#![deny(clippy::panic)]
#![deny(clippy::unwrap_used)]
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::{IpAddr, 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 clap::Parser;
use hnefatafl_copenhagen::{
Id, SERVER_PORT, VERSION_ID,
accounts::{Account, Accounts, DateTimeUtc},
board::BoardSize,
draw::Draw,
email::Email,
game::TimeUnix,
glicko::Outcome,
rating::Rated,
role::Role,
server_game::{
ArchivedGame, Challenger, Messenger, ServerGame, ServerGameLight, ServerGameSerialized,
ServerGames, ServerGamesLight, ServerGamesLightVec,
status::Status,
time::{Time, TimeEnum, TimeSettings},
tournament::Tournament,
utils::{self, create_data_folder, data_file},
use itertools::Itertools;
use jiff::{Timestamp, ToSpan, Zoned};
use lettre::{
SmtpTransport, Transport,
message::{Mailbox, header::ContentType},
transport::smtp::authentication::Credentials,
use log::{debug, error, info, trace};
use rand::random;
use serde::{Deserialize, Serialize};
use std::fmt::Write as _;
use crate::{
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";
const KEEP_TEXTS: usize = 100;
const HOUR_IN_SECONDS: u64 = 60 * 60;
const DAY_IN_SECONDS: u64 = HOUR_IN_SECONDS * 24;
const DAYS_FOR_INACTIVE_ACCOUNT: i64 = 14;
/// 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";
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 {
return Args::generate_man_page();
}
create_data_folder()?;
let (tx, rx) = mpsc::channel();
let mut server = Server {
tx: Some(tx.clone()),
..Server::default()
if args.skip_the_data_file {
server.skip_the_data_files = true;
} else {
server.load_data_files(tx.clone(), args.systemd)?;
thread::spawn(move || handle_error(server.handle_messages(&rx)));
if !args.skip_advertising_updates {
Server::advertise_updates(tx.clone());
Server::check_once_a_day(tx.clone());
if args.autostart_tournament {
Server::new_tournament(tx.clone());
Server::save(tx.clone());
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;
let peer_address = match stream.peer_addr() {
Ok(peer_address) => peer_address.ip(),
error!("peer_address: {error}");
if args.secure {
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();
thread::spawn(move || {
if let Err(error) = login(index, stream, peer_address, &tx) {
error!("peer_address: {peer_address}, login: {error}");
});
Ok(())
#[allow(clippy::too_many_lines)]
fn login(
id: Id,
mut stream: TcpStream,
peer_address: IpAddr,
tx: &mpsc::Sender<(String, Option<mpsc::Sender<String>>)>,
) -> anyhow::Result<()> {
info!("login attempted from {peer_address}");
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!("{peer_address} {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")?;
info!("{peer_address} {id} {username_proper} logged in");
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} display_games"), None))?;
tx.send((format!("{id} {username_proper} tournament_status_0"), None))?;
tx.send((format!("{id} {username_proper} admin"), None))?;
tx.send((format!("{id} {username_proper} admin_tournament"), None))?;
let mut game_id = None;
'outer: for _ in 0..1_000_000 {
if let Err(err) = reader.read_line(&mut buf) {
error!("peer_address: {peer_address}, 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' {
// Fixme: If a player creates a game less than day main time, then
// leaves the game without declining, then the other players gets a
// game that does not automatically quit.
let words: Vec<_> = buf_str.split_whitespace().collect();
if let Some(first) = words.first() {
if (*first == "join_game" || *first == "resume_game")
&& let Some(second) = words.get(1)
&& let Ok(id) = u128::from_str(second)
game_id = Some(id);
if *first == "leave_game" {
game_id = None;
tx.send((format!("{id} {username_proper} {buf_str}"), None))?;
if let Some(game_id) = game_id {
tx.send((format!("{id} {username_proper} leave_game {game_id}"), None))?;
tx.send((format!("{id} {username_proper} logout"), None))?;
info!("{peer_address} {id} {username_proper} logged out");
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 handle_error<T, E: fmt::Display>(result: Result<T, E>) -> T {
match result {
Ok(value) => value,
error!("{error}");
exit(1)
fn hash_password(password: &str) -> Option<String> {
let ctx = Argon2::default();
Some(ctx.hash_password(password.as_bytes()).ok()?.to_string())
fn timestamp() -> String {
Timestamp::now().strftime("[%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>,
admins_tournament: 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_vec: ServerGamesLightVec,
games_light_old: ServerGamesLight,
skip_the_data_files: bool,
texts: VecDeque<String>,
tx: Option<mpsc::Sender<(String, Option<mpsc::Sender<String>>)>>,
impl Server {
fn advertise_updates(tx: Sender<(String, Option<Sender<String>>)>) {
loop {
handle_error(tx.send(("0 server display_server".to_string(), None)));
thread::sleep(Duration::from_secs(1));
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 archived_games_file = data_file(ARCHIVED_GAMES_FILE);
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;
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 = Timestamp::now().as_second();
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
fn check_once_a_day(tx: Sender<(String, Option<Sender<String>>)>) {
handle_error(tx.send(("0 server delete_unused_accounts".to_string(), None)));
handle_error(tx.send(("0 server check_update_rd".to_string(), None)));
thread::sleep(Duration::from_secs(DAY_IN_SECONDS));
/// <- 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 defender = None;
if switch {
if Some(username.to_string()) == game_old.attacker {
defender = game_old.defender;
} else if Some(username.to_string()) == game_old.defender {
attacker = game_old.attacker;
} 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,
spectators: game_old.spectators,
challenge_accepted: false,
game_over: false,
turn: Role::Roleless,
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();
self.sort_games_light();
let mut names = HashMap::new();
for (name, account) in &self.accounts.0 {
if let Some(id) = account.logged_in {
names.insert(id, name);
for (id, tx) in &mut self.clients {
let Ok(games) = self
.games_light_vec
.display_games(names.get(id).map(|s| s.as_str()))
else {
let _ok = tx.send(format!("= display_games {games}"));
if self.accounts != self.accounts_old {
debug!("0 {username} display_users");
self.accounts_old = self.accounts.clone();
if let Some(id) = account.logged_in
&& let Some(tx) = self.clients.get(&id)
if self.admins.contains(name) {
if let Ok(string) = &self.accounts.display_admin() {
let _ok = tx.send(format!("= display_users_admin {string}"));
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 = Timestamp::now().as_millisecond();
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() {
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_files {
self.append_archived_game(game)
.map_err(|err| {
error!("append_archived_games: {err}");
})
.ok()?;
fn game(
group_size: usize,
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;
game.draw_requested = Role::Roleless;
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;
game_light.turn = Role::Roleless;
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;
Status::Draw => {
// Handled in the draw fn.
Status::Ongoing => {
if attackers_turn_next {
game_light.turn = Role::Attacker;
game.attacker_tx
.send(format!("game {index} generate_move attacker"));
game_light.turn = Role::Defender;
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");
for id in game_light.spectators() {
if let Some(sender) = self.clients.get(&id) {
if game_over {
let Some(game) = self.games.0.remove(&index) else {
unreachable!()
if let Some(game_light) = self.games_light.0.get_mut(&index) {
game_light.game_over = true;
if let Some(tournament) = &mut self.tournament {
if tournament.game_over(&game) {
self.generate_round(group_size);
self.tournament_status_all();
error!("append_archived_game: {err}");
fn generate_round(&mut self, group_size: usize) {
let mut round = None;
let groups = tournament.generate_round(&self.accounts, group_size);
round = Some(groups);
let mut ids = VecDeque::new();
let mut groups_arc_mutex = Vec::new();
if let Some(groups) = round {
for (i, mut group) in groups.into_iter().enumerate() {
for combination in group.records.iter().map(|record| record.0).combinations(2) {
if let (Some(first), Some(second)) = (combination.first(), combination.get(1)) {
ids.push_back((self.new_tournament_game(first, second), i));
ids.push_back((self.new_tournament_game(second, first), i));
group.total_games += 2;
groups_arc_mutex.push(Arc::new(Mutex::new(group)));
if !groups_arc_mutex.is_empty()
&& let Some(tournament) = &mut self.tournament
for (id, i) in ids {
if let Some(group) = groups_arc_mutex.get(i) {
tournament.tournament_games.insert(id, group.clone());
if let Some(rounds) = &mut tournament.groups {
rounds.push(groups_arc_mutex);
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)
.ok()?
.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))
Err(err) => {
let reply = format!("could not send email to {address}");
error!("{reply}: {err}");
Some((self.clients.get(&index_supplied)?.clone(), false, reply))
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),
) {
let username = *username;
if *command != "check_update_rd"
&& *command != "create_account"
&& *command != "display_server"
&& *command != "join_game_pending"
&& *command != "leave_game"
&& *command != "login"
&& *command != "logout"
&& *command != "ping"
&& *command != "resume_game"
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())
"admin_tournament" => {
if self.admins_tournament.contains(username) {
.send("= admin_tournament".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);
"delete_unused_accounts" => {
let now = Timestamp::now();
let mut accounts = Vec::new();
let mut playing = HashSet::new();
for game in self.games_light.0.values() {
if let Some(attacker) = &game.attacker {
playing.insert(attacker);
if let Some(defender) = &game.defender {
playing.insert(defender);
if account.wins == 0
&& account.losses == 0
&& account.draws == 0
&& let Ok(timestamp) = now.checked_sub(DAYS_FOR_INACTIVE_ACCOUNT.day())
&& timestamp > account.last_logged_in.0
&& !playing.contains(name)
accounts.push(name.clone());
for name in &accounts {
info!("deleting {name}...");
self.accounts.0.remove(name);
"display_games" => {
if args.skip_advertising_updates {
self.clients.get(&index_supplied).map(|tx| {
(
tx.clone(),
format!("display_games {:?}", &self.games_light_vec),
)
"display_server" => self.display_server(username),
"draw" => self.draw(index_supplied, command, the_rest.as_slice()),
"game" => self.game(
args.group_size,
"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" => {
&& 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" => {
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),
"new_game" => self.new_game(username, index_supplied, command, the_rest.as_slice()),
"ping" => Some((
)),
"reset_password" => {
if let Some(email) = &account.email {
if email.verified {
let day = 60 * 60 * 24;
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),
"save" => {
debug!("saving users file...");
self.save_server();
"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() >= KEEP_TEXTS {
self.texts.pop_front();
for tx in &mut self.clients.values() {
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_groups_delete" => {
if self.admins_tournament.contains(username)
tournament.groups = None;
tournament.tournament_games = HashMap::new();
"tournament_date" => {
if let Err(error) = self.tournament_date(&the_rest) {
error!("tournament_date: {error}");
"tournament_status_0" => {
trace!("tournament_status: {:#?}", self.tournament);
let tx = self.clients.get(&index_supplied)?;
let tournament = ron::ser::to_string(&self.tournament).ok()?;
format!("tournament_status_0 {tournament}"),
"tournament_start" => {
&& tournament.groups.is_none()
&& Timestamp::now() >= tournament.date
info!("Starting tournament...");
tournament.groups = Some(Vec::new());
tournament.players_left = tournament.players.clone();
self.generate_round(args.group_size);
"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;
game.turn = Role::Attacker;
if let Some(account) = self.accounts.0.get(game.attacker.as_ref()?)
&& let Some(id) = account.logged_in
game.spectators.insert(game.attacker.clone()?, id);
if let Some(account) = self.accounts.0.get(game.defender.as_ref()?)
game.spectators.insert(game.defender.clone()?, id);
let (Some(attacker), Some(defender)) = (&game.attacker, &game.defender) else {
let (Some(attacker_account), Some(defender_account)) =
(self.accounts.0.get(attacker), self.accounts.0.get(defender))
let mut attacker_channel = None;
if let Some(channel_id) = attacker_account.logged_in
&& let Some(channel) = self.clients.get(&channel_id)
attacker_channel = Some(channel);
let mut defender_channel = None;
if let Some(channel_id) = defender_account.logged_in
defender_channel = Some(channel);
for channel in [&attacker_channel, &defender_channel].into_iter().flatten() {
channel
.send(format!(
"= join_game {} {} {} {:?} {}",
game.attacker.clone()?,
game.defender.clone()?,
game.rated,
game.timed,
game.board_size,
let new_game = ServerGame::new(
attacker_channel.cloned(),
defender_channel.cloned(),
game.clone(),
self.games.0.insert(id, new_game);
account.pending_games.remove(&id);
if let Some(channel) = attacker_channel {
.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());
if let Some(defender) = &game.defender
&& let Some(account) = self.accounts.0.get(defender)
&& let Some(channel_id) = account.logged_in
let _ok = channel.send(format!("= challenge_requested {id}"));
} else if game.defender.is_none() {
game.defender = Some(username.clone());
if let Some(attacker) = &game.attacker
&& let Some(account) = self.accounts.0.get(attacker)
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 !game.challenge_accepted {
&& username == attacker
game.attacker = None;
&& 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()));
account.logged_in = Some(index_supplied);
account.last_logged_in = DateTimeUtc(Timestamp::now());
// The username is not in the database.
info!("{index_supplied} {username} is not in the database");
fn load_data_files(
tx: Sender<(String, Option<Sender<String>>)>,
systemd: bool,
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) => {
*self = server_ron;
self.tx = Some(tx.clone());
tournament.remove_duplicate_ids();
self.admins_tournament.insert("server".to_string());
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())),
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);
self.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);
self.games_light.0.insert(id, server_game_light);
self.games.0.insert(id, server_game);
ctrlc::set_handler(move || {
if !systemd {
println!();
handle_error(tx.send(("0 server save".to_string(), None)));
handle_error(tx.send(("0 server exit".to_string(), None)));
})?;
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
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(tx: Sender<(String, Option<Sender<String>>)>) {
handle_error(tx.send(("0 server tournament_start".to_string(), None)));
let now = Zoned::now().with_time_zone(jiff::tz::TimeZone::UTC);
match Zoned::now()
.with_time_zone(jiff::tz::TimeZone::UTC)
.end_of_day()
Ok(midnight) => {
let duration = now.duration_until(&midnight);
debug!("midnight: {midnight}");
debug!("seconds until midnight: {}", duration.as_secs());
match duration.try_into() {
Ok(mut duration) => {
duration += Duration::from_secs(2);
sleep(duration);
error!("new_tournament (1): {error}");
exit(1);
error!("new_tournament (2): {error}");
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(),
spectators: HashMap::new(),
challenge_accepted: true,
board_size: BoardSize::_11,
turn: Role::Attacker,
"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} {command} {id}");
let Some(game_light) = self.games_light.0.get_mut(&id) else {
let mut channel_id = 0;
channel_id = id;
game_light
.spectators
.insert(username.to_string(), channel_id);
let mut request_draw = Role::Roleless;
if let Some(server_game) = self.games.0.get_mut(&id) {
if Some(username) == game_light.attacker.as_deref() {
server_game.attacker_tx =
Messenger::new(self.clients.get(&index_supplied)?.clone());
if server_game.draw_requested == Role::Defender {
request_draw = Role::Attacker;
} else if Some(username) == game_light.defender.as_deref() {
server_game.defender_tx =
if server_game.draw_requested == Role::Attacker {
request_draw = Role::Defender;
let client = self.clients.get(&index_supplied)?;
client
"= resume_game {} {} {} {:?} {} {board} {texts}",
game_light.attacker.clone()?,
game_light.defender.clone()?,
game_light.rated,
game_light.timed,
game_light.board_size,
if request_draw != Role::Roleless {
.send(format!("request_draw {} {request_draw}", game_light.id))
fn request_draw(
let Some(role) = the_rest.get(1) else {
info!("{index_supplied} {username} request_draw {id} {role}");
server_game.draw_requested = role;
let message = format!("request_draw {id} {role}");
if let Some(game) = self.games.0.get(&id) {
match role {
fn save(tx: Sender<(String, Option<Sender<String>>)>) {
thread::sleep(Duration::from_secs(HOUR_IN_SECONDS));
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 sort_games_light(&mut self) {
let mut games: Vec<_> = self
.games_light
.0
.values()
.map(|game| {
let mut rating_1 = 0.0;
let mut rating_2 = 0.0;
rating_1 = account.rating.rating;
rating_2 = account.rating.rating;
if rating_2 > rating_1 {
std::mem::swap(&mut rating_1, &mut rating_2);
(game, rating_1, rating_2)
.collect();
games.sort_by(|a, b| b.2.total_cmp(&a.2));
games.sort_by(|a, b| b.1.total_cmp(&a.1));
self.games_light_vec =
ServerGamesLightVec(games.iter().map(|(game, _, _)| (*game).clone()).collect());
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) {
for index in game.spectators.values() {
if let Some(sender) = self.clients.get(index) {
let _ok = sender.send(text.clone());
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"));
tournament.date = match date.parse() {
Ok(timestamp) => timestamp,
Err(error) => return Err(anyhow::Error::msg(format!("tournament_date: {error}"))),
self.tournament = Some(tournament);
fn tournament_status_all(&self) {
if let Ok(mut tournament) = ron::ser::to_string(&self.tournament) {
tournament = format!("= tournament_status_0 {tournament}");
for tx in self.clients.values() {
let _ok = tx.send(tournament.clone());
fn watch_game(
game.spectators.insert(username.to_string(), index_supplied);
info!("{index_supplied} {username} watch_game {id}");
"= watch_game {} {} {} {:?} {} {board} {texts}",