windows: whitelist-bypass

Creators and joiners, built from upstream's tag with upstream's patches
(links and passwords from the environment, never argv), run by the
service as whitelist-bypass.nix runs them: joiners while the proxy runs,
as its outbounds, creators while the suite is on, their logins kept in
a working copy they refresh. proxy-ctl wl list|link|auth|join|new|restart
over new API requests (whitelistBypass scope).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Opus 5.5 committed 2026-10-27 13:01:10 +03:00
1 parent 1f4fcf540d
commit 610e36a28b
15 files changed
+585 -7

No files matched your search

@@ -116,7 +116,6 @@ fn not_ported(cfg: &Config, v: &mut Issues) {
(cfg.amnezia_wg.enable && cfg.amnezia_wg.profiles.values().any(|p| p.as_outbound.is_none()), "amneziaWg.profiles", "AmneziaWG as a system-wide VPN (its driver; as outbounds it is here)"),
(cfg.warp.enable && cfg.warp.as_amnezia_wg, "warp.asAmneziaWg", "WARP as an AmneziaWG profile"),
(cfg.tor.enable && cfg.tor.onion_service.enable, "tor.onionService.enable", "Tor's onion service (it serves the inbounds)"),
(cfg.whitelist_bypass.enable, "whitelistBypass.enable", "whitelist-bypass"),
(cfg.inbounds.enable, "inbounds.enable", "Serving inbounds"),
(cfg.proxy.auto_proxy.enable, "proxy.autoProxy.enable", "autoProxy"),
] {
+1
View File
@@ -17,6 +17,7 @@ anyhow.workspace = true
serde_json.workspace = true
tokio.workspace = true
clap.workspace = true
rpassword.workspace = true
[dev-dependencies]
serde_json.workspace = true
+129 -2
View File
@@ -54,6 +54,11 @@ enum Cmd {
#[command(subcommand)]
verb: TgVerb,
},
/// whitelist-bypass creators and joiners.
Wl {
#[command(subcommand)]
verb: Option<WlVerb>,
},
/// The backend programs: what is installed, and installing them (administrator).
Components {
#[command(subcommand)]
@@ -67,6 +72,23 @@ enum TgVerb {
Link,
}
#[derive(Subcommand)]
enum WlVerb {
/// Creators and joiners, and their state.
List,
/// The call a creator made, for its joiner.
Link { creator: String },
/// A creator's login: a cookies export (a file, or - for stdin); DION and Bitrix ask for
/// an email and password without one.
Auth { creator: String, file: Option<String> },
/// The call link a joiner joins (or - for stdin).
Join { joiner: String, link: String },
/// Start a new call, if the platform closed the old one.
New { creator: String },
/// Restart all of them, or the one named.
Restart { name: Option<String> },
}
#[derive(Subcommand)]
enum ZapretVerb {
Status,
@@ -245,9 +267,13 @@ fn read_arg(value: &str) -> Result<String> {
}
}
/// A file's text, or stdin's for -.
fn read_arg_file(file: &str) -> Result<String> {
if file == "-" { read_arg("-") } else { std::fs::read_to_string(file).with_context(|| format!("reading {file}")) }
}
fn read_file_arg(file: &str) -> Result<Value> {
let text = if file == "-" { read_arg("-")? } else { std::fs::read_to_string(file).with_context(|| format!("reading {file}"))? };
serde_json::from_str(&text).with_context(|| format!("{file} is not JSON"))
serde_json::from_str(&read_arg_file(file)?).with_context(|| format!("{file} is not JSON"))
}
async fn status(ctl: &Ctl) -> Result<()> {
@@ -549,6 +575,106 @@ async fn zapret(ctl: &Ctl, verb: Option<ZapretVerb>) -> Result<()> {
Ok(())
}
/// A login for the DION and Bitrix creators, which log in on their own from it.
fn password_login(platform: &str, name: &str) -> Result<String> {
let fields: &[&str] = match platform {
"dion" => &["email", "password"],
"bitrix" => &["email", "password", "portal"],
_ => bail!("{platform} logs in only in a browser: export its cookies from the desktop Creator, then: proxy-ctl wl auth {name} <file>"),
};
let mut login = serde_json::Map::new();
for field in fields {
let value = if *field == "password" {
rpassword::prompt_password("Password: ")?
} else {
eprint!("{}{}: ", field[..1].to_uppercase(), &field[1..]);
let mut line = String::new();
std::io::stdin().read_line(&mut line)?;
line.trim().to_owned()
};
let value = match *field {
"portal" => {
let portal = value.trim_end_matches('/');
if portal.contains("://") { portal.to_owned() } else { format!("https://{portal}") }
}
_ => value,
};
login.insert((*field).to_owned(), Value::String(value));
}
Ok(Value::Object(login).to_string())
}
async fn wl(ctl: &Ctl, verb: Option<WlVerb>) -> Result<()> {
let say = |r: &Value| println!("{}: {}", r["unit"].as_str().unwrap_or("?"), r["state"].as_str().unwrap_or("?"));
match verb.unwrap_or(WlVerb::List) {
WlVerb::List => {
let r = ctl.call(Request::WlList).await?;
if ctl.json {
ctl.print(&r);
return Ok(());
}
let list = r.as_array().cloned().unwrap_or_default();
if list.is_empty() {
println!("No whitelist-bypass creators or joiners configured.");
return Ok(());
}
println!(" {:<16} {:<8} {:<10} STATUS", "NAME", "ROLE", "PLATFORM");
for w in list {
let f = |k: &str| w[k].as_str().unwrap_or("").to_owned();
println!(" {:<16} {:<8} {:<10} {}", f("name"), f("role"), f("platform"), f("state"));
}
}
WlVerb::Link { creator } => {
let r = ctl.call(Request::WlLink { name: creator }).await?;
println!("{}", r["link"].as_str().unwrap_or(""));
}
WlVerb::Auth { creator, file } => {
let login = match file {
Some(f) => {
let text = read_arg_file(&f)?;
serde_json::from_str::<Value>(&text).context("not a cookies export, not valid JSON")?;
text
}
None => {
let list = ctl.call(Request::WlList).await?;
let platform = list
.as_array()
.into_iter()
.flatten()
.find(|w| w["name"] == creator.as_str() && w["role"] == "creator")
.and_then(|w| w["platform"].as_str().map(str::to_owned))
.with_context(|| format!("no whitelist-bypass creator '{creator}'"))?;
password_login(&platform, &creator)?
}
};
say(&ctl.call(Request::WlAuth { name: creator, login }).await?);
}
WlVerb::Join { joiner, link } => {
let link = read_arg(&link)?;
say(&ctl.call(Request::WlJoin { name: joiner, link: link.trim().to_owned() }).await?);
}
WlVerb::New { creator } => {
say(&ctl.call(Request::WlNew { name: creator.clone() }).await?);
println!("Its joiner needs the new call: proxy-ctl wl link {creator}");
}
WlVerb::Restart { name } => {
let list = ctl.call(Request::WlList).await?;
let units: Vec<String> = list
.as_array()
.into_iter()
.flatten()
.filter(|w| name.as_deref().is_none_or(|n| w["name"] == n))
.map(|w| format!("proxy-suite-wb-{}-{}", w["role"].as_str().unwrap_or(""), w["name"].as_str().unwrap_or("")))
.collect();
if units.is_empty() {
bail!("no such whitelist-bypass creator or joiner");
}
ctl.call(Request::Restart { units }).await?;
}
}
Ok(())
}
async fn components(ctl: &Ctl, verb: Option<ComponentsVerb>) -> Result<()> {
match verb.unwrap_or(ComponentsVerb::List) {
ComponentsVerb::List => {
@@ -601,6 +727,7 @@ async fn real_main() -> Result<()> {
Cmd::Proxy(p) => proxy(&ctl, p.verb).await?,
Cmd::Zapret { verb } => zapret(&ctl, verb).await?,
Cmd::Components { verb } => components(&ctl, verb).await?,
Cmd::Wl { verb } => wl(&ctl, verb).await?,
Cmd::Tg { verb: TgVerb::Link } => {
let r = ctl.call(Request::TgLinks).await?;
for l in r["links"].as_array().into_iter().flatten().filter_map(Value::as_str) {
+11
View File
@@ -65,6 +65,17 @@ pub enum Request {
TgLinks,
/// Fetch and install components (all wanted, or the named ones).
ComponentsInstall { names: Vec<String> },
/// whitelist-bypass's creators and joiners, and their state.
WlList,
/// The call a creator made and keeps rejoining.
WlLink { name: String },
/// A creator's login: a cookies export, or (DION, Bitrix) the JSON of its email, password
/// and portal.
WlAuth { name: String, login: String },
/// The call link a joiner joins.
WlJoin { name: String, link: String },
/// Drops the call a creator rejoins: it makes a new one.
WlNew { name: String },
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+92
View File
@@ -135,10 +135,27 @@ fn scope_of(req: &Request) -> Option<Scope> {
// Backend logs name the sites visited (at info), and errors may quote what was dialled.
Request::RenderedConfig | Request::Logs { .. } | Request::TgLinks => Some(Scope::Secrets),
Request::Restart { .. } | Request::Start { .. } | Request::Stop { .. } => Some(Scope::Services),
Request::WlList | Request::WlLink { .. } | Request::WlAuth { .. } | Request::WlJoin { .. } | Request::WlNew { .. } => Some(Scope::WhitelistBypass),
_ => None,
}
}
/// Re-applies whitelist-bypass, so a unit that waited starts, and restarts `unit` on what
/// was just left for it.
async fn wl_restart(s: &mut service::Service, unit: &str) -> Response {
let started = |s: &service::Service| s.sup.status().into_iter().find(|u| u.name == unit).map(|u| u.since);
let before = started(s);
if let Err(e) = s.apply_wl().await {
return Response::err(format!("{e:#}"));
}
// Unless the apply (re)started it on a new spec, or it does not run (off, or its proxy is).
let after = started(s);
if after.is_some() && after == before {
s.sup.restart(unit);
}
Response::ok(json!({ "unit": unit, "state": s.sup.state_of(unit).as_str() }))
}
fn has_secrets(cfg: &Config, peer: &Peer) -> bool {
allowed(cfg, peer, Some(Scope::Secrets)).is_ok()
}
@@ -476,6 +493,81 @@ pub async fn handle(req: Request, peer: &Peer, shared: &Shared) -> Response {
}
}
Request::WlList => {
let s = shared.lock().await;
let wl = &s.cfg().whitelist_bypass;
let state = |unit: String| if wl.enable { s.sup.state_of(&unit).as_str() } else { "off" };
let mut list: Vec<Value> = wl
.creators
.iter()
.map(|(name, c)| json!({ "name": name, "role": "creator", "platform": c.platform.as_str(), "state": state(format!("{}{name}", crate::wl::CREATOR_PREFIX)) }))
.collect();
list.extend(wl.joiners.iter().map(|(name, j)| {
json!({ "name": name, "role": "joiner", "platform": j.platform.as_str(), "state": state(format!("{}{name}", crate::wl::JOINER_PREFIX)) })
}));
Response::ok(json!(list))
}
Request::WlLink { name } => {
let s = shared.lock().await;
if !s.cfg().whitelist_bypass.creators.contains_key(&name) {
return Response::err(format!("no whitelist-bypass creator '{name}'"));
}
match crate::wl::last_link(s.paths(), &name) {
Some(link) => Response::ok(json!({ "link": link })),
None => Response::err(format!("{name} has no call yet: see proxy-ctl logs {}{name}", crate::wl::CREATOR_PREFIX)),
}
}
Request::WlAuth { name, login } => {
let mut s = shared.lock().await;
if !s.cfg().whitelist_bypass.creators.contains_key(&name) {
return Response::err(format!("no whitelist-bypass creator '{name}'"));
}
if login.len() > 1 << 20 || serde_json::from_str::<Value>(&login).is_err() {
return Response::err("not a cookies export (or a login): not valid JSON");
}
let file = crate::wl::state_dir(s.paths()).join(format!("{name}.cookies.json"));
if let Err(e) = crate::wl::write_private(&file, login.as_bytes()) {
return Response::err(format!("{e:#}"));
}
wl_restart(&mut s, &format!("{}{name}", crate::wl::CREATOR_PREFIX)).await
}
Request::WlJoin { name, link } => {
let mut s = shared.lock().await;
if !s.cfg().whitelist_bypass.joiners.contains_key(&name) {
return Response::err(format!("no whitelist-bypass joiner '{name}'"));
}
let link = link.trim();
let link = match crate::wl::clean_link(link) {
Ok(l) if l == link => l,
_ => return Response::err("a call link is one word: a room id, a slug or a URL"),
};
let file = crate::wl::state_dir(s.paths()).join(format!("{name}.join"));
if let Err(e) = crate::wl::write_private(&file, format!("{link}\n").as_bytes()) {
return Response::err(format!("{e:#}"));
}
wl_restart(&mut s, &format!("{}{name}", crate::wl::JOINER_PREFIX)).await
}
Request::WlNew { name } => {
let mut s = shared.lock().await;
let Some(c) = s.cfg().whitelist_bypass.creators.get(&name) else {
return Response::err(format!("no whitelist-bypass creator '{name}'"));
};
if c.link_file.is_some() {
return Response::err(format!("{name} rejoins the call its linkFile sets: change that instead"));
}
let file = crate::wl::state_dir(s.paths()).join(format!("{name}.link"));
if let Err(e) = std::fs::remove_file(&file)
&& e.kind() != std::io::ErrorKind::NotFound
{
return Response::err(format!("removing {}: {e}", file.display()));
}
wl_restart(&mut s, &format!("{}{name}", crate::wl::CREATOR_PREFIX)).await
}
Request::ComponentsInstall { names } => {
// Programs the service runs as SYSTEM: an administrator's call, whatever the scopes.
if !peer.admin {
+1
View File
@@ -21,6 +21,7 @@ mod units;
mod warp;
#[cfg(windows)]
mod winsvc;
mod wl;
mod zapret;
use std::path::PathBuf;
+60 -2
View File
@@ -1,6 +1,6 @@
//! The service's state and what it does with it: render, write, check, (re)start, fetch.
use std::collections::BTreeMap;
use std::collections::{BTreeMap, BTreeSet};
use std::path::PathBuf;
use std::sync::Arc;
use std::time::{Duration, SystemTime};
@@ -37,6 +37,8 @@ pub struct Service {
pub last_error: Option<String>,
pub last_fetch: BTreeMap<String, SystemTime>,
tcp_timestamps_on: bool,
/// What whitelist-bypass's units waited for at the last apply, said when it first did.
wl_waiting: BTreeSet<String>,
}
fn digest(data: &[u8]) -> String {
@@ -59,6 +61,7 @@ impl Service {
last_error: None,
last_fetch: BTreeMap::new(),
tcp_timestamps_on: false,
wl_waiting: BTreeSet::new(),
store,
})
}
@@ -99,6 +102,17 @@ impl Service {
{
direct.push(p.to_string_lossy().into_owned());
}
// The joiners' calls, and the creators' unless they go through the proxy.
if cfg.whitelist_bypass.enable {
let wl = &cfg.whitelist_bypass;
let joiners = wl.joiners.values().map(|j| format!("headless-{}-joiner", j.platform.as_str()));
let creators = wl.creators.values().filter(|c| c.upstream == ps_core::config::Upstream::Direct).map(|c| format!("headless-{}-creator", c.platform.as_str()));
for name in joiners.chain(creators).collect::<BTreeSet<_>>() {
if let Some(p) = self.comps.find("whitelist-bypass", &name) {
direct.push(p.to_string_lossy().into_owned());
}
}
}
// Tor's own connections, unless it is to go through the proxy (upstream = "proxy").
if cfg.tor.enable
&& cfg.tor.upstream == ps_core::config::Upstream::Direct
@@ -163,8 +177,52 @@ impl Service {
if let Err(e) = &awg {
self.sup.note(SOCKS_UNIT, format!("proxy-suite: AmneziaWG: {e:#}"));
}
let wl = self.apply_wl().await;
if let Err(e) = &wl {
self.sup.note(SOCKS_UNIT, format!("proxy-suite: whitelist-bypass: {e:#}"));
}
let proxy = self.apply_proxy().await;
zapret.and(tg).and(ssh).and(tor).and(awg).and(proxy)
zapret.and(tg).and(ssh).and(tor).and(awg).and(wl).and(proxy)
}
/// whitelist-bypass: the joiners while the proxy they serve runs, the creators while it
/// is on; the ones no longer wanted stopped, and what the rest wait for said once.
pub async fn apply_wl(&mut self) -> Result<()> {
let cfg = self.cfg().clone();
let mut wanted_cfg = cfg.clone();
let on = cfg.enable && cfg.whitelist_bypass.enable;
if !self.proxy_wanted() {
wanted_cfg.whitelist_bypass.joiners.clear();
}
let (units, waiting) = if on {
let auth = &cfg.proxy.listener.auth;
let password = match (&auth.password, &auth.password_file) {
(Some(p), _) => Some(p.clone()),
(None, Some(f)) => Some(std::fs::read_to_string(f).with_context(|| format!("reading {f}"))?.lines().next().unwrap_or("").to_owned()),
(None, None) => None,
};
let login = auth.username.clone().zip(password);
let hop = (self.store.secrets.hop_user.clone(), self.store.secrets.hop_password.clone());
let program = |name: &str| self.comps.program("whitelist-bypass", name);
crate::wl::units(&wanted_cfg, self.paths(), &program, (&hop.0, &hop.1), login)
} else {
(Vec::new(), Vec::new())
};
let waiting: BTreeSet<String> = waiting.into_iter().collect();
for w in waiting.difference(&self.wl_waiting) {
self.sup.note(SOCKS_UNIT, format!("proxy-suite: {w}"));
}
self.wl_waiting = waiting;
let wanted: Vec<String> = units.iter().map(|u| u.name.clone()).collect();
for name in self.sup.names() {
if (name.starts_with(crate::wl::JOINER_PREFIX) || name.starts_with(crate::wl::CREATOR_PREFIX)) && !wanted.contains(&name) {
self.sup.stop(&name).await;
}
}
for unit in units {
self.sup.ensure(unit);
}
Ok(())
}
/// The wireproxy tunnels behind "userspace" AmneziaWG outbounds and WARP devices, while
+199
View File
@@ -0,0 +1,199 @@
//! whitelist-bypass, as upstream's whitelist-bypass.nix runs it: joiners, each a SOCKS listener
//! on loopback (with the hop login) behind its outbound, tunnelled through a video call; and
//! creators, the free ends of those calls. Links, logins and passwords reach them through the
//! environment (the build makes those the flags' defaults), never their command lines.
//!
//! A joiner waits for its call's link (`proxy-ctl wl join`, or `linkFile`); a creator for a login
//! (`proxy-ctl wl auth`, or `cookiesFile`), which it keeps refreshing in its own working copy.
use std::path::{Path, PathBuf};
use anyhow::{Context, Result, bail};
use ps_core::config::{Config, Upstream, WlCreator, WlResources};
use ps_core::derived::ports;
use crate::paths::{Paths, write_atomic};
use crate::units::UnitSpec;
pub const JOINER_PREFIX: &str = "proxy-suite-wb-joiner-";
pub const CREATOR_PREFIX: &str = "proxy-suite-wb-creator-";
/// What `proxy-ctl wl` leaves for the units: links (`<name>.join`), logins
/// (`<name>.cookies.json`), and the creators' calls (`<name>.link`, last line the current).
pub fn state_dir(paths: &Paths) -> PathBuf {
paths.root.join("whitelist-bypass")
}
/// The creators' working logins, which they rewrite as they refresh them.
fn sessions_dir(paths: &Paths) -> PathBuf {
paths.root.join("whitelist-bypass-sessions")
}
fn resources(r: WlResources) -> &'static str {
match r {
WlResources::Moderate => "moderate",
WlResources::Default => "default",
WlResources::Unlimited => "unlimited",
}
}
/// A link as the units take it: whitespace gone, one line.
pub fn clean_link(text: &str) -> Result<String> {
let link: String = text.chars().filter(|c| !c.is_whitespace()).collect();
if link.is_empty() {
bail!("an empty link");
}
if link.len() > 4096 || link.chars().any(char::is_control) {
bail!("that is not a call link");
}
Ok(link)
}
/// The units, and what each that cannot run yet waits for. `program` finds one of the
/// component's programs by name.
pub fn units(
cfg: &Config,
paths: &Paths,
program: &dyn Fn(&str) -> Result<PathBuf>,
hop: (&str, &str),
proxy_login: Option<(String, String)>,
) -> (Vec<UnitSpec>, Vec<String>) {
let w = &cfg.whitelist_bypass;
let state = state_dir(paths);
let mut units = Vec::new();
let mut waiting = Vec::new();
for (i, (tag, j)) in w.joiners.iter().enumerate() {
let port = ports::WL_JOINER_BASE + i as u16;
// The link `wl join` gave wins over linkFile.
let link = std::fs::read_to_string(state.join(format!("{tag}.join")))
.ok()
.or_else(|| j.link_file.as_ref().and_then(|f| std::fs::read_to_string(f).ok()))
.and_then(|t| clean_link(&t).ok());
let Some(link) = link else {
waiting.push(format!("whitelist-bypass joiner '{tag}' waits for its call's link: proxy-ctl wl join {tag} <link>"));
continue;
};
let program = match program(&format!("headless-{}-joiner", j.platform.as_str())) {
Ok(p) => p,
Err(e) => {
waiting.push(format!("whitelist-bypass joiner '{tag}': {e:#}"));
continue;
}
};
let args = vec!["--socks-port".into(), port.to_string(), "--socks-user".into(), hop.0.to_owned()];
units.push(UnitSpec {
name: format!("{JOINER_PREFIX}{tag}"),
program,
generation: format!("{args:?}{link}"),
args,
env: vec![("WB_LINK".into(), link), ("WB_SOCKS_PASS".into(), hop.1.to_owned())],
cwd: None,
});
}
for (name, c) in &w.creators {
match creator(cfg, paths, program, name, c, proxy_login.clone()) {
Ok(Some(unit)) => units.push(unit),
Ok(None) => waiting.push(format!("whitelist-bypass creator '{name}' waits for a login: proxy-ctl wl auth {name} <cookies.json>")),
Err(e) => waiting.push(format!("whitelist-bypass creator '{name}': {e:#}")),
}
}
(units, waiting)
}
/// The call a creator made and keeps rejoining: the last line it wrote.
pub fn last_link(paths: &Paths, name: &str) -> Option<String> {
let text = std::fs::read_to_string(state_dir(paths).join(format!("{name}.link"))).ok()?;
text.lines().map(str::trim).rfind(|l| !l.is_empty()).map(str::to_owned)
}
/// Writes a file only the service reads: a link, a login.
pub fn write_private(file: &Path, data: &[u8]) -> Result<()> {
if let Some(dir) = file.parent() {
std::fs::create_dir_all(dir)?;
}
write_atomic(file, data).with_context(|| format!("writing {}", file.display()))?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(file, std::fs::Permissions::from_mode(0o600))?;
}
Ok(())
}
fn creator(
cfg: &Config,
paths: &Paths,
program: &dyn Fn(&str) -> Result<PathBuf>,
name: &str,
c: &WlCreator,
proxy_login: Option<(String, String)>,
) -> Result<Option<UnitSpec>> {
let program = program(&format!("headless-{}-creator", c.platform.as_str()))?;
let state = state_dir(paths);
let sessions = sessions_dir(paths);
std::fs::create_dir_all(&state)?;
std::fs::create_dir_all(&sessions)?;
let given = state.join(format!("{name}.cookies.json"));
let cookies = sessions.join(format!("{name}.cookies.json"));
// A login `wl auth` left replaces the working copy, then goes.
if given.is_file() {
write_private(&cookies, &std::fs::read(&given)?)?;
std::fs::remove_file(&given)?;
} else if !cookies.is_file()
&& let Some(f) = &c.cookies_file
{
write_private(&cookies, &std::fs::read(f).with_context(|| format!("reading {f}"))?)?;
}
if !cookies.is_file() {
return Ok(None);
}
let links = state.join(format!("{name}.link"));
// linkFile's call, or the last one it made (empty: it makes one).
let link = match &c.link_file {
Some(f) => clean_link(&std::fs::read_to_string(f).with_context(|| format!("reading {f}"))?)?,
None => last_link(paths, name).unwrap_or_default(),
};
let mut args: Vec<String> = vec![
"--cookies".into(),
cookies.display().to_string(),
"--write-file".into(),
links.display().to_string(),
"--resources".into(),
resources(c.resources).into(),
];
let mut env = vec![("WB_LINK".to_owned(), link)];
if c.upstream == Upstream::Proxy {
// From the parsed address, as Tor's: the listener's own, or loopback for a wildcard.
let l = &cfg.proxy.listener;
let host = match l.address.parse::<std::net::IpAddr>().context("proxy.listener.address is not an IP address")? {
ip if ip.is_unspecified() => "127.0.0.1".to_owned(),
std::net::IpAddr::V6(v6) => format!("[{v6}]"),
v4 => v4.to_string(),
};
args.extend(["--upstream-socks".into(), format!("{host}:{}", l.port)]);
if let Some((user, password)) = proxy_login {
args.extend(["--upstream-user".into(), user]);
env.push(("WB_UPSTREAM_PASS".into(), password));
}
}
Ok(Some(UnitSpec {
name: format!("{CREATOR_PREFIX}{name}"),
program,
generation: format!("{args:?}{}", env[0].1),
args,
env,
cwd: None,
}))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn links_are_one_clean_line() {
assert_eq!(clean_link(" https://stream.wb.ru/room/abc \n").unwrap(), "https://stream.wb.ru/room/abc");
assert!(clean_link(" \n").is_err());
assert!(clean_link("a\u{7}b").is_err());
}
}