Make banned IP format less strict to support possible future changes

This commit is contained in:
timvisee 2021-11-17 18:46:45 +01:00
parent b168dcefde
commit 785bd2f33e
No known key found for this signature in database
GPG Key ID: B8DB720BC383E172
2 changed files with 23 additions and 9 deletions

View File

@ -45,31 +45,37 @@ pub struct BannedIp {
pub ip: IpAddr,
/// Ban creation time.
pub created: String,
pub created: Option<String>,
/// Ban source.
pub source: String,
pub source: Option<String>,
/// Ban expiry time.
pub expires: String,
pub expires: Option<String>,
/// Ban reason.
pub reason: String,
pub reason: Option<String>,
}
impl BannedIp {
/// Check if this entry is currently banned.
pub fn is_banned(&self) -> bool {
// Get expiry time
let expires = match &self.expires {
Some(expires) => expires,
None => return true,
};
// If expiry is forever, the user is banned
if self.expires.trim().to_lowercase() == EXPIRY_FOREVER {
if expires.trim().to_lowercase() == EXPIRY_FOREVER {
return true;
}
// Parse expiry time, check if it has passed
let expiry = match DateTime::parse_from_str(&self.expires, "%Y-%m-%d %H:%M:%S %z") {
let expiry = match DateTime::parse_from_str(&expires, "%Y-%m-%d %H:%M:%S %z") {
Ok(expiry) => expiry,
Err(err) => {
error!(target: "lazymc", "Failed to parse ban expiry '{}', assuming still banned: {}", self.expires, err);
error!(target: "lazymc", "Failed to parse ban expiry '{}', assuming still banned: {}", expires, err);
return true;
}
};

View File

@ -19,6 +19,9 @@ use crate::proto::packet::{self, RawPacket};
use crate::proto::packets;
use crate::server::{self, Server};
/// Default ban reason if unknown.
const DEFAULT_BAN_REASON: &str = "Banned by an operator.";
/// Proxy the given inbound stream to a target address.
// TODO: do not drop error here, return Box<dyn Error>
pub async fn serve(
@ -130,8 +133,13 @@ pub async fn serve(
// Kick if client is banned
if let Some(ban) = server.ban_entry(&client.peer.ip()).await {
if ban.is_banned() {
info!(target: "lazymc", "Login from banned IP {} ({}), disconnecting", client.peer.ip(), &ban.reason);
action::kick(&client, &ban.reason, &mut writer).await?;
if let Some(reason) = ban.reason {
info!(target: "lazymc", "Login from banned IP {} ({}), disconnecting", client.peer.ip(), &reason);
action::kick(&client, &reason, &mut writer).await?;
} else {
info!(target: "lazymc", "Login from banned IP {}, disconnecting", client.peer.ip());
action::kick(&client, DEFAULT_BAN_REASON, &mut writer).await?;
}
break;
}
}