feat: custom hostname

This commit is contained in:
m1m1sha
2024-05-08 14:47:22 +08:00
parent c3df9ea7fa
commit 0498b55d39
10 changed files with 91 additions and 8 deletions
+22 -7
View File
@@ -54,7 +54,7 @@ pub struct GlobalCtx {
ip_collector: Arc<IPCollector>,
hotname: AtomicCell<Option<String>>,
hostname: AtomicCell<Option<String>>,
stun_info_collection: Box<dyn StunInfoCollectorTrait>,
@@ -80,6 +80,7 @@ impl GlobalCtx {
let id = config_fs.get_id();
let network = config_fs.get_network_identity();
let net_ns = NetNS::new(config_fs.get_netns());
let hostname = config_fs.get_hostname();
let (event_bus, _) = tokio::sync::broadcast::channel(100);
@@ -96,7 +97,7 @@ impl GlobalCtx {
ip_collector: Arc::new(IPCollector::new(net_ns)),
hotname: AtomicCell::new(None),
hostname: AtomicCell::new(Some(hostname)),
stun_info_collection: Box::new(StunInfoCollector::new_with_default_servers()),
@@ -166,13 +167,27 @@ impl GlobalCtx {
}
pub fn get_hostname(&self) -> Option<String> {
if let Some(hostname) = self.hotname.take() {
self.hotname.store(Some(hostname.clone()));
return Some(hostname);
let hostname = gethostname::gethostname().to_string_lossy().to_string();
let hostname = match self.hostname.take() {
Some(name) => {
// when allowing custom hostname, there may be empty
if name.is_empty() {
hostname
} else {
name
}
},
None => hostname,
};
let re = regex::Regex::new(r"[^\u4E00-\u9FA5a-zA-Z0-9\-]*").unwrap();
let mut hostname = re.replace_all(&hostname, "").to_string();
if hostname.len() > 32 {
hostname = hostname.chars().take(32).collect::<String>();
}
let hostname = gethostname::gethostname().to_string_lossy().to_string();
self.hotname.store(Some(hostname.clone()));
self.hostname.store(Some(hostname.clone()));
return Some(hostname);
}