Skip to content

Commit

Permalink
fix service management on windows (#15)
Browse files Browse the repository at this point in the history
* 🐛 fix service management on windows

* 🔖 Bump version to 0.1.4
  • Loading branch information
mokeyish authored Dec 11, 2022
1 parent 1bc1af1 commit 6961422
Show file tree
Hide file tree
Showing 10 changed files with 273 additions and 152 deletions.
10 changes: 7 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "smartdns"
version = "0.1.1"
version = "0.1.4"
authors = ["YISH <[email protected]>"]
edition = "2021"

Expand Down Expand Up @@ -32,7 +32,7 @@ async-trait = "0.1.43"
time = "0.3"
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["std", "fmt", "env-filter"] }
tokio = { version = "1.21", features = ["time", "rt"] }
tokio = { version = "1.21", features = ["time", "rt", "signal"] }
url = "2.3.1"
trust-dns-proto = { version = "0.22.0", features = ["dns-over-https-rustls"]}
trust-dns-client = { version = "0.22.0", features = ["dns-over-https-rustls"]}
Expand All @@ -48,11 +48,15 @@ surge-ping = { version = "0.7.4", git = "https://github.com/mokeyish/surge-ping.
rand = "0.8.5"
smallvec = "1.10.0"
csv = "1.1"
service-manager = "0.2.0"
service-manager = { version = "0.2.0", git = "https://github.com/chipsenkbeil/service-manager-rs.git", branch = "main"}
byte-unit = "4.0.17"
# rnp = "0.1"
# boomphf = "0.5.9"

[target.'cfg(windows)'.dependencies]
windows = { version = "0.43.0", features = ["Win32_System_Console", "Win32_Foundation"] }
windows-service = "0.5.0"


[build-dependencies]
reqwest = { version = "0.11", default-features = false, features = ["blocking", "rustls-tls"] }
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ sudo ./target/release/smartdns run -c ./etc/smartdns/smartdns.conf

程序会安装到 `/usr/local/bin/smartdns`

服务会安装到 `/Library/LaunchDaemons/sys.dns.smartdns-rs.plist`
服务会安装到 `/Library/LaunchDaemons/smartdns-rs.plist`

2. 启动服务

Expand Down Expand Up @@ -86,7 +86,7 @@ sudo ./target/release/smartdns run -c ./etc/smartdns/smartdns.conf

程序会安装到 `/sbin/smartdns`

服务会安装到 `/etc/systemd/system/dns-smartdns-rs.service`
服务会安装到 `/etc/systemd/system/smartdns-rs.service`

2. 启动服务

Expand Down
13 changes: 6 additions & 7 deletions src/cli.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use clap::{Parser, Subcommand};
use clap::Subcommand;

pub use clap::Parser;

/// Smart-DNS.
///
Expand Down Expand Up @@ -35,8 +37,7 @@ pub enum ServiceCommands {
Install,

/// Uninstall the Smart-DNS service.
Uninstall{

Uninstall {
/// Purge both the binary and config files.
#[arg(short = 'p', long)]
purge: bool,
Expand All @@ -52,7 +53,7 @@ pub enum ServiceCommands {
Restart,

/// Print the service status of Smart-DNS
Status
Status,
}

#[cfg(test)]
Expand Down Expand Up @@ -119,9 +120,7 @@ mod tests {
assert_eq!(
cli.command,
Commands::Service {
command: ServiceCommands::Uninstall {
purge: false
}
command: ServiceCommands::Uninstall { purge: false }
}
);
}
Expand Down
6 changes: 2 additions & 4 deletions src/dns.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,15 +68,13 @@ impl SmartDnsConfig {
}

pub fn audit_size(&self) -> u64 {
use byte_unit::n_kb_bytes;
use byte_unit::n_kb_bytes;
self.audit_size.unwrap_or(n_kb_bytes(128) as u64)
}

pub fn audit_num(&self) -> usize {
self.audit_num.unwrap_or(2)
}


}

pub trait DefaultSOA {
Expand Down
57 changes: 52 additions & 5 deletions src/dns_conf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,13 @@ use trust_dns_resolver::Name;
use crate::dns_url::DnsUrl;
use crate::log::{error, info, warn};

const DEFAULT_SERVER:&'static str = "https://cloudflare-dns.com/dns-query";
const DEFAULT_SERVER: &'static str = "https://cloudflare-dns.com/dns-query";

#[derive(Debug, Default, Clone)]
pub struct SmartDnsConfig {
pub server_name: Name,
pub user: Option<String>,

pub audit_enable: bool,
pub audit_file: Option<PathBuf>,
pub audit_size: Option<u64>,
Expand Down Expand Up @@ -53,6 +53,45 @@ impl SmartDnsConfig {
}
}

pub fn load<P: AsRef<Path>>(path: Option<P>) -> Self {
if let Some(ref conf) = path {
let path = conf.as_ref();

info!("loading configuration from: {:?}", path);
SmartDnsConfig::load_from_file(path)
} else {
cfg_if! {
if #[cfg(target_os = "android")] {
let candidate_path = [
"/data/data/com.termux/files/usr/etc/smartdns.conf",
"/data/data/com.termux/files/usr/etc/smartdns/smartdns.conf"
];

} else if #[cfg(target_os = "windows")] {
let candidate_path = [""];
} else {
let candidate_path = [
"/etc/smartdns.conf",
"/etc/smartdns/smartdns.conf",
"/usr/local/etc/smartdns.conf",
"/usr/local/etc/smartdns/smartdns.conf"
];
}
};

candidate_path
.iter()
.map(Path::new)
.filter(|p| p.exists())
.map(|p| {
info!("loading configuration from: {:?}", p);
SmartDnsConfig::load_from_file(p)
})
.next()
.expect("No configuation file found.")
}
}

pub fn load_from_file<P: AsRef<Path>>(path: P) -> Self {
let path = path.as_ref();

Expand All @@ -73,10 +112,12 @@ impl SmartDnsConfig {
let server_count: usize = cfg.servers.iter().map(|(_, o)| o.len()).sum();

if server_count == 0 {
cfg.servers.get_mut("default").unwrap().push(DnsServer::from_str(DEFAULT_SERVER).unwrap());
cfg.servers
.get_mut("default")
.unwrap()
.push(DnsServer::from_str(DEFAULT_SERVER).unwrap());
}


if let Some(ss) = cfg.servers.get("default") {
for s in ss {
info!("default server: {}", s.url.to_string());
Expand Down Expand Up @@ -467,7 +508,13 @@ mod parse {
"cache-size" => self.cache_size = usize::from_str(options).ok(),
"audit-enable" => self.audit_enable = parse_bool(options),
"audit-file" => self.audit_file = Some(Path::new(options).to_owned()),
"audit-size" => self.audit_size = Some(Byte::from_str(options).expect("parse byte size failed. support KB,MB,GB").get_bytes() as u64),
"audit-size" => {
self.audit_size = Some(
Byte::from_str(options)
.expect("parse byte size failed. support KB,MB,GB")
.get_bytes() as u64,
)
}
"audit-num" => self.audit_num = usize::from_str(options).ok(),
"log-level" => self.log_level = Some(options.to_string()),
"dnsmasq-lease-file" => self.dnsmasq_lease_file = Some(options.to_string()),
Expand Down
32 changes: 15 additions & 17 deletions src/dns_mw_audit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,6 @@ impl DnsAuditMiddleware {
const BUF_SIZE: usize = 10;
let mut buf: SmallVec<[DnsAuditRecord; BUF_SIZE]> = SmallVec::new();


while let Some(audit) = audit_rx.recv().await {
buf.push(audit);

Expand Down Expand Up @@ -177,27 +176,27 @@ impl ToString for DnsAuditRecord {
}

fn record_audit_to_file(audit_file: &mut MappedFile, audit_records: &[DnsAuditRecord]) {

if matches!(audit_file.extension(), Some(ext) if ext == "csv") {
// write as csv

if audit_file.peamble().is_none() {
let mut writer = csv::Writer::from_writer(vec![]);
writer.write_record(&[
"id",
"timestamp",
"client",
"name",
"type",
"elapsed",
"speed",
"state",
"result",
"lookup_source",
]).unwrap();

audit_file.set_peamble(Some(writer.into_inner().unwrap().into_boxed_slice()))
writer
.write_record(&[
"id",
"timestamp",
"client",
"name",
"type",
"elapsed",
"speed",
"state",
"result",
"lookup_source",
])
.unwrap();

audit_file.set_peamble(Some(writer.into_inner().unwrap().into_boxed_slice()))
}

let mut writer = csv::Writer::from_writer(audit_file);
Expand All @@ -222,7 +221,6 @@ fn record_audit_to_file(audit_file: &mut MappedFile, audit_records: &[DnsAuditRe
])
.unwrap();
}

} else {
// write as nornmal log format.
for audit in audit_records {
Expand Down
Loading

0 comments on commit 6961422

Please sign in to comment.