Add support for host names in config address fields, resolve them to IP

This commit is contained in:
timvisee
2021-11-17 16:14:05 +01:00
parent ec24f088b2
commit b1bd9e1837
3 changed files with 38 additions and 1 deletions

View File

@@ -9,6 +9,7 @@ use version_compare::Cmp;
use crate::proto;
use crate::util::error::{quit_error, quit_error_msg, ErrorHintsBuilder};
use crate::util::serde::to_socket_addrs;
/// Default configuration file location.
pub const CONFIG_FILE: &str = "lazymc.toml";
@@ -127,6 +128,7 @@ impl Config {
#[serde(default)]
pub struct Public {
/// Public address.
#[serde(deserialize_with = "to_socket_addrs")]
pub address: SocketAddr,
/// Minecraft protocol version name hint.
@@ -157,7 +159,10 @@ pub struct Server {
pub command: String,
/// Server address.
#[serde(default = "server_address_default")]
#[serde(
deserialize_with = "to_socket_addrs",
default = "server_address_default"
)]
pub address: SocketAddr,
/// Immediately wake server when starting lazymc.
@@ -318,6 +323,7 @@ impl Default for JoinHold {
#[serde(default)]
pub struct JoinForward {
/// IP and port to forward to.
#[serde(deserialize_with = "to_socket_addrs")]
pub address: SocketAddr,
}

View File

@@ -1,5 +1,6 @@
pub mod cli;
pub mod error;
pub mod serde;
pub mod style;
use std::env;

30
src/util/serde.rs Normal file
View File

@@ -0,0 +1,30 @@
use std::net::{SocketAddr, ToSocketAddrs};
use serde::de::{Error, Unexpected};
use serde::{Deserialize, Deserializer};
/// Deserialize a `Vec` into a `HashMap` by key.
pub fn to_socket_addrs<'de, D>(d: D) -> Result<SocketAddr, D::Error>
where
D: Deserializer<'de>,
{
// Deserialize string
let addr = String::deserialize(d)?;
// Try to socket address to resolve
match addr.to_socket_addrs() {
Ok(mut addr) => {
if let Some(addr) = addr.next() {
return Ok(addr);
}
}
Err(err) => {
dbg!(err);
}
}
// Parse raw IP address
addr.parse().map_err(|_| {
Error::invalid_value(Unexpected::Str(&addr), &"IP or resolvable host and port")
})
}