Cactus/net/slp/
ip_logger.rs

1//! Manages the logging of IPs passed down from the SLP handler.
2
3use log::error;
4use std::path::Path;
5
6/// Holds Notchian client information that will be logged into the logged_ips file.
7pub struct ClientIpLoggerInfo {
8    pub ip: String,
9}
10
11/// Makes the line that will be appended to the logged_ips file.
12fn make_line(info: &ClientIpLoggerInfo) -> String {
13    let time: String = crate::time::get_time_iso().unwrap();
14    format!("{},{}\n", time, info.ip)
15}
16
17/// Logs an IP to the logged_ips file. This function should be called in the SLP after
18/// receiving positive confirmation the client is a Notchian Minecraft server.
19/// This function is low-friction, does not propagate errors.
20pub fn log_ip(info: ClientIpLoggerInfo) {
21    let path: &Path = Path::new(crate::consts::file_paths::LOGGED_IPS);
22    if !path.is_file() {
23        if let Err(e) = crate::fs_manager::utils::create_file(path, None) {
24            error!("Failed to log IP: failed to create {path:#?}: {e}");
25            return;
26        }
27    }
28
29    // Check a second time to make sure the function really created the file.
30    if !path.is_file() {
31        error!("Failed to log IP: {path:#?} does not exist");
32        return;
33    }
34
35    // append file with IP, date,
36    if let Err(e) = crate::fs_manager::utils::append_file(path, &make_line(&info)) {
37        error!("Failed to log IP: {e}");
38    }
39}