Skip to content

Commit e7f05db

Browse files
authored
Add CLI option for a custom host suffix (tonarino#373)
* client, server: option for custom host suffixes * shared: Better wording in the doc * client, shared: nits and formatting * shared: underscore to dash in option name --------- Co-authored-by: Štěpán Mikéska <stepan@nesp.im>
1 parent 95a8c7e commit e7f05db

5 files changed

Lines changed: 50 additions & 37 deletions

File tree

client/src/main.rs

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ use innernet_shared::{
99
prompts, update_hosts_file,
1010
wg::{DeviceExt, PeerInfoExt},
1111
AddCidrOpts, AddDeleteAssociationOpts, AddPeerOpts, Association, AssociationContents, Cidr,
12-
CidrTree, DeleteCidrOpts, EnableDisablePeerOpts, Endpoint, EndpointContents, HostsOpt,
12+
CidrTree, DeleteCidrOpts, EnableDisablePeerOpts, Endpoint, EndpointContents, HostsOpts,
1313
InstallOpts, Interface, IoErrorContext, ListenPortOpts, NatOpts, NetworkOpts,
1414
OverrideEndpointOpts, Peer, RedeemContents, RenameCidrOpts, RenamePeerOpts, ServerCapabilities,
1515
State, WrappedIoError, REDEEM_TRANSITION_WAIT,
@@ -82,7 +82,7 @@ enum Command {
8282
invite: PathBuf,
8383

8484
#[clap(flatten)]
85-
hosts: HostsOpt,
85+
hosts: HostsOpts,
8686

8787
#[clap(flatten)]
8888
install_opts: InstallOpts,
@@ -118,7 +118,7 @@ enum Command {
118118
interval: u64,
119119

120120
#[clap(flatten)]
121-
hosts: HostsOpt,
121+
hosts: HostsOpts,
122122

123123
#[clap(flatten)]
124124
nat: NatOpts,
@@ -131,7 +131,7 @@ enum Command {
131131
interface: Interface,
132132

133133
#[clap(flatten)]
134-
hosts: HostsOpt,
134+
hosts: HostsOpts,
135135

136136
#[clap(flatten)]
137137
nat: NatOpts,
@@ -274,7 +274,7 @@ enum Command {
274274
fn install(
275275
opts: &Opts,
276276
invite: &Path,
277-
hosts_file: Option<PathBuf>,
277+
hosts_opts: HostsOpts,
278278
install_opts: InstallOpts,
279279
nat: &NatOpts,
280280
) -> Result<(), Error> {
@@ -323,7 +323,7 @@ fn install(
323323

324324
let mut fetch_success = false;
325325
for _ in 0..3 {
326-
if fetch(&iface, opts, true, hosts_file.clone(), nat).is_ok() {
326+
if fetch(&iface, opts, true, &hosts_opts, nat).is_ok() {
327327
fetch_success = true;
328328
break;
329329
}
@@ -466,7 +466,7 @@ fn up(
466466
interface: Option<Interface>,
467467
opts: &Opts,
468468
loop_interval: Option<Duration>,
469-
hosts_path: Option<PathBuf>,
469+
hosts_opts: HostsOpts,
470470
nat: &NatOpts,
471471
) -> Result<(), Error> {
472472
loop {
@@ -476,7 +476,7 @@ fn up(
476476
};
477477

478478
for iface in interfaces {
479-
fetch(&iface, opts, true, hosts_path.clone(), nat)?;
479+
fetch(&iface, opts, true, &hosts_opts, nat)?;
480480
}
481481

482482
match loop_interval {
@@ -492,7 +492,7 @@ fn fetch(
492492
interface: &InterfaceName,
493493
opts: &Opts,
494494
bring_up_interface: bool,
495-
hosts_path: Option<PathBuf>,
495+
hosts_opts: &HostsOpts,
496496
nat: &NatOpts,
497497
) -> Result<(), Error> {
498498
let config = InterfaceConfig::from_interface(&opts.config_dir, interface)?;
@@ -577,8 +577,8 @@ fn fetch(
577577
.apply(interface, opts.network.backend)
578578
.with_str(interface.to_string())?;
579579

580-
if let Some(path) = hosts_path {
581-
update_hosts_file(interface, &path, &peers)?;
580+
if !hosts_opts.no_write_hosts {
581+
update_hosts_file(interface, hosts_opts, &peers)?;
582582
}
583583

584584
println!();
@@ -1290,7 +1290,7 @@ fn run(opts: &Opts) -> Result<(), Error> {
12901290
hosts,
12911291
install_opts,
12921292
nat,
1293-
} => install(opts, &invite, hosts.into(), install_opts, &nat)?,
1293+
} => install(opts, &invite, hosts, install_opts, &nat)?,
12941294
Command::Show {
12951295
short,
12961296
tree,
@@ -1300,7 +1300,7 @@ fn run(opts: &Opts) -> Result<(), Error> {
13001300
interface,
13011301
hosts,
13021302
nat,
1303-
} => fetch(&interface, opts, false, hosts.into(), &nat)?,
1303+
} => fetch(&interface, opts, false, &hosts, &nat)?,
13041304
Command::Up {
13051305
interface,
13061306
daemon,
@@ -1311,7 +1311,7 @@ fn run(opts: &Opts) -> Result<(), Error> {
13111311
interface,
13121312
opts,
13131313
daemon.then(|| Duration::from_secs(interval)),
1314-
hosts.into(),
1314+
hosts,
13151315
&nat,
13161316
)?,
13171317
Command::Down { interface } => wg::down(&interface, opts.network.backend)?,

server/src/lib.rs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@ use hyper::{http, server::conn::AddrStream, Body, Request, Response};
55
use indoc::printdoc;
66
use innernet_shared::{
77
get_local_addrs, update_hosts_file, AddCidrOpts, AddPeerOpts, DeleteCidrOpts,
8-
EnableDisablePeerOpts, Endpoint, IoErrorContext, NetworkOpts, PeerContents, RenameCidrOpts,
9-
RenamePeerOpts, INNERNET_PUBKEY_HEADER,
8+
EnableDisablePeerOpts, Endpoint, HostsOpts, IoErrorContext, NetworkOpts, PeerContents,
9+
RenameCidrOpts, RenamePeerOpts, INNERNET_PUBKEY_HEADER,
1010
};
1111
use ipnet::IpNet;
1212
use parking_lot::{Mutex, RwLock};
@@ -429,7 +429,7 @@ fn spawn_expired_invite_sweeper(db: Db) {
429429
});
430430
}
431431

432-
fn spawn_hostfile_writer(db: Db, interface: InterfaceName, hosts_path: PathBuf) {
432+
fn spawn_hostfile_writer(db: Db, interface: InterfaceName, hosts_opts: HostsOpts) {
433433
tokio::task::spawn({
434434
async move {
435435
let mut interval = tokio::time::interval(Duration::from_secs(10));
@@ -440,7 +440,7 @@ fn spawn_hostfile_writer(db: Db, interface: InterfaceName, hosts_path: PathBuf)
440440
Ok(peers) => {
441441
if let Err(e) = update_hosts_file(
442442
&interface,
443-
&hosts_path,
443+
&hosts_opts,
444444
peers.into_iter().map(|peer| peer.inner),
445445
) {
446446
log::error!("Failed to write hostfile: {}", e);
@@ -459,7 +459,7 @@ pub async fn serve(
459459
interface: InterfaceName,
460460
conf: &ServerConfig,
461461
network: NetworkOpts,
462-
hosts_path: Option<PathBuf>,
462+
hosts_opts: HostsOpts,
463463
) -> Result<(), Error> {
464464
let config = ConfigFile::from_file(conf.config_path(&interface))?;
465465
log::debug!("opening database connection...");
@@ -514,8 +514,8 @@ pub async fn serve(
514514
let endpoints = spawn_endpoint_refresher(interface, network);
515515
spawn_expired_invite_sweeper(db.clone());
516516

517-
if let Some(path) = hosts_path {
518-
spawn_hostfile_writer(db.clone(), interface, path);
517+
if !hosts_opts.no_write_hosts {
518+
spawn_hostfile_writer(db.clone(), interface, hosts_opts);
519519
}
520520

521521
let context = Context {

server/src/main.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use clap::{Parser, Subcommand};
22
use colored::*;
33
use innernet_shared::{
4-
AddCidrOpts, AddPeerOpts, DeleteCidrOpts, EnableDisablePeerOpts, HostsOpt, NetworkOpts,
4+
AddCidrOpts, AddPeerOpts, DeleteCidrOpts, EnableDisablePeerOpts, HostsOpts, NetworkOpts,
55
RenameCidrOpts, RenamePeerOpts,
66
};
77
use std::{env, path::PathBuf};
@@ -62,7 +62,7 @@ enum Command {
6262
network: NetworkOpts,
6363

6464
#[clap(flatten)]
65-
hosts: HostsOpt,
65+
hosts: HostsOpts,
6666
},
6767

6868
/// Add a peer to an existing network.
@@ -156,7 +156,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
156156
interface,
157157
network: routing,
158158
hosts,
159-
} => serve(*interface, &conf, routing, hosts.into()).await?,
159+
} => serve(*interface, &conf, routing, hosts).await?,
160160
Command::AddPeer { interface, args } => add_peer(&interface, &conf, args, opts.network)?,
161161
Command::RenamePeer { interface, args } => rename_peer(&interface, &conf, args)?,
162162
Command::DisablePeer { interface, args } => {

shared/src/lib.rs

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -147,22 +147,35 @@ impl IpNetExt for IpNet {
147147

148148
pub fn update_hosts_file(
149149
interface: &InterfaceName,
150-
hosts_path: &Path,
150+
opts: &HostsOpts,
151151
peers: impl IntoIterator<Item = impl AsRef<Peer>>,
152152
) -> Result<(), WrappedIoError> {
153+
if opts.no_write_hosts {
154+
return Ok(());
155+
}
156+
153157
let mut hosts_builder = HostsBuilder::new(format!("innernet {interface}"));
154158
for peer in peers {
155159
let peer = peer.as_ref();
156-
hosts_builder.add_hostname(
157-
peer.contents.ip,
158-
format!("{}.{}.wg", peer.contents.name, interface),
159-
);
160+
let peer_hostname = if let Some(suffix) = &opts.host_suffix {
161+
if suffix.is_empty() {
162+
peer.contents.name.to_string()
163+
} else {
164+
format!("{}.{}", peer.contents.name, suffix)
165+
}
166+
} else {
167+
format!("{}.{}.wg", peer.contents.name, interface)
168+
};
169+
hosts_builder.add_hostname(peer.contents.ip, peer_hostname);
160170
}
161-
match hosts_builder.write_to(hosts_path).with_path(hosts_path) {
171+
match hosts_builder
172+
.write_to(opts.hosts_path.as_path())
173+
.with_path(opts.hosts_path.as_path())
174+
{
162175
Ok(has_written) if has_written => {
163176
log::info!(
164177
"updated {} with the latest peers.",
165-
hosts_path.to_string_lossy().yellow()
178+
opts.hosts_path.to_string_lossy().yellow()
166179
)
167180
},
168181
Ok(_) => {},

shared/src/types.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -521,20 +521,20 @@ pub struct NetworkOpts {
521521
}
522522

523523
#[derive(Clone, Debug, Args)]
524-
pub struct HostsOpt {
524+
pub struct HostsOpts {
525525
/// The path to write hosts to
526526
#[clap(long = "hosts-path", default_value = "/etc/hosts")]
527527
pub hosts_path: PathBuf,
528528

529529
/// Don't write to any hosts files
530530
#[clap(long = "no-write-hosts", conflicts_with = "hosts_path")]
531531
pub no_write_hosts: bool,
532-
}
533532

534-
impl From<HostsOpt> for Option<PathBuf> {
535-
fn from(opt: HostsOpt) -> Self {
536-
(!opt.no_write_hosts).then_some(opt.hosts_path)
537-
}
533+
/// Use a different suffix for hosts, than '<interface>.wg' , ex.
534+
/// --host-suffix 'evilnet' names peers: <peer>.evilnet, and
535+
/// --host-suffix '' gives peers no suffix, just: <peer>
536+
#[clap(long = "host-suffix")]
537+
pub host_suffix: Option<String>,
538538
}
539539

540540
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]

0 commit comments

Comments
 (0)