toe_beans/v4/server/config/
mod.rs

1mod lease_time;
2
3use super::RESOLVED_SERVER_PORT;
4use crate::v4::MessageOptions;
5use ip_network::Ipv4Network;
6pub use lease_time::LeaseTime;
7use log::{info, warn};
8use serde::{Deserialize, Serialize};
9use std::collections::HashMap;
10use std::fs::{read_to_string, OpenOptions};
11use std::io::Write;
12use std::net::{Ipv4Addr, SocketAddrV4};
13use std::os::unix::fs::OpenOptionsExt;
14use std::path::PathBuf;
15use toml;
16
17/// Representation of a `toe-beans.toml` file. Used by the [Server](crate::v4::Server).
18///
19/// This is exported for you to use in your application to generate a `toe-beans.toml`.
20#[derive(Serialize, Deserialize, Debug)]
21pub struct Config {
22    /// The path to a directory where this config will exist on disk.
23    #[serde(skip)]
24    pub path: PathBuf,
25    /// See: [LeaseTime](lease_time::LeaseTime)
26    pub lease_time: LeaseTime,
27    /// Controls whether the server agrees to use [Rapid Commit](crate::v4::MessageOptions::RapidCommit).
28    pub rapid_commit: bool,
29    /// A range of IP addresses for the server to lease. Specified in CIDR notation. For example: `10.1.9.32/16`
30    pub network_cidr: Ipv4Network,
31    /// The server will bind to this address and port.
32    pub listen_address: SocketAddrV4,
33    /// The name of the network interface to broadcast server responses to.
34    /// Currently only takes one interface.
35    pub interface: Option<String>,
36    /// May or may not match the IP address in `listen_address`.
37    /// For example, you might be listening to `0.0.0.0`, but your server has another address it can be reached from.
38    /// This is used in both the `siaddr` field and `ServerIdentifier` option.
39    ///
40    /// If `None`, then `listen_address` is used.
41    pub server_address: Option<Ipv4Addr>,
42    /// DHCP option numbers (as a String) mapped to values that are used to respond to parameter request list options
43    /// Please note that this field, in particular, is subject to change.
44    pub parameters: HashMap<String, MessageOptions>,
45}
46
47impl Default for Config {
48    fn default() -> Self {
49        Self {
50            path: PathBuf::new(),                        // empty, the current directory
51            lease_time: LeaseTime::new(86_400).unwrap(), // seconds in a day
52            rapid_commit: true,
53            network_cidr: Ipv4Network::new(Ipv4Addr::new(10, 0, 0, 0), 16).unwrap(), // 2^(32-16) addresses
54            listen_address: SocketAddrV4::new(Ipv4Addr::new(0, 0, 0, 0), RESOLVED_SERVER_PORT),
55            interface: None,
56            server_address: None,
57            parameters: HashMap::with_capacity(u8::MAX as usize),
58        }
59    }
60}
61
62impl Config {
63    /// The file name that the Config is read from and written to.
64    pub const FILE_NAME: &'static str = "toe-beans.toml";
65
66    /// Reads the `toe-beans.toml` file and deserializes it into a Config.
67    /// Returns default options if there are any issues.
68    pub fn read(from_where: PathBuf) -> Self {
69        let read_result = read_to_string(from_where.join(Self::FILE_NAME));
70        if let Ok(config_string) = read_result {
71            let toml_result = toml::from_str(&config_string);
72            match toml_result {
73                Ok(config) => {
74                    return Self {
75                        path: from_where, // from_where might be different if passed through cli args
76                        ..config
77                    };
78                }
79                Err(error) => {
80                    warn!("{error}");
81                    warn!(
82                        "Warning: invalid {}. Using default values.",
83                        Self::FILE_NAME
84                    );
85                }
86            }
87        } else {
88            warn!(
89                "Warning: can't read {}. Using default values.",
90                Self::FILE_NAME
91            );
92        }
93
94        Self {
95            path: from_where,
96            ..Config::default()
97        }
98    }
99
100    /// Serializes a Config and writes it to a `toe-beans.toml` file.
101    pub fn write(&self) {
102        info!("Writing {}", Self::FILE_NAME);
103
104        let config_content = toml::to_string_pretty(self).expect("Failed to generate toml data");
105        let mode = 0o600;
106
107        let mut file = OpenOptions::new()
108            .read(false)
109            .write(true)
110            .create(true)
111            .truncate(true)
112            .mode(mode) // ensure that file permissions are set before creating file
113            .open(self.path.join(Self::FILE_NAME))
114            .unwrap_or_else(|_| panic!("Failed to open config {} for writing", Self::FILE_NAME));
115
116        file.write_all(config_content.as_bytes())
117            .unwrap_or_else(|_| panic!("Failed to write config to {}", Self::FILE_NAME));
118    }
119}