chore: restart the repository with a clean history
CI / Docker image (push) Successful in 12s
CI / Server (push) Successful in 25s
CI / CLI (push) Successful in 13s
Development image / Development image (push) Successful in 21s
CI / CLI (windows) (push) Successful in 57s
CI / CLI (linux-arm64, static) (push) Successful in 1m37s
Release / Prepare release (push) Successful in 2s
Release / Server (linux-x64) (push) Successful in 53s
Release / CLI (linux-arm64, static) (push) Successful in 1m32s
Release / Docker image (push) Successful in 2m48s
Release / Server (windows-x64) (push) Successful in 6m20s
Release / CLI (windows-x64) (push) Successful in 6m48s
Release / CLI (linux-x64) (push) Successful in 7m8s
Release / Publish release (push) Successful in 1s

Squash the tree into one commit, drop docs/architecture.html, reset the version line to 0.3.0, consolidate the changelog, enable Renovate automerge for non-major updates and add AGENTS.md.
This commit is contained in:
fristy committed 2026-11-10 11:31:13 +03:00
commit 650807c1fb
438 files changed
+45070

No files matched your search

+82
View File
@@ -0,0 +1,82 @@
use anyhow::{bail, Result};
use reqwest::Client;
use serde::Deserialize;
pub struct ApiClient {
client: Client,
base_url: String,
token: Option<String>,
}
#[derive(Deserialize)]
pub struct ServerInfo { pub name: String, pub version: String, #[serde(rename = "baseDomain")] pub base_domain: String }
#[derive(Deserialize)]
pub struct DeviceRequest {
pub code: String,
#[serde(rename = "pollToken")] pub poll_token: String,
#[serde(rename = "handoffUrl")] pub handoff_url: String,
}
#[derive(Deserialize)]
pub struct DevicePoll { pub status: String, pub token: Option<String> }
impl ApiClient {
pub fn new(base_url: &str, token: Option<&str>, accept_invalid_certs: bool) -> Result<Self> {
Ok(Self {
client: Client::builder().danger_accept_invalid_certs(accept_invalid_certs).build()?,
base_url: base_url.trim_end_matches('/').to_string(),
token: token.map(|t| t.to_string()),
})
}
fn url(&self, path: &str) -> String { format!("{}/@frislit/api{}", self.base_url, path) }
pub async fn info(&self) -> Result<ServerInfo> {
let resp = self.client.get(self.url("/info")).send().await?;
if !resp.status().is_success() { bail!("Server did not answer like a frislit server ({})", resp.status()); }
Ok(resp.json().await?)
}
pub async fn device_create(&self, client: &str) -> Result<DeviceRequest> {
let response = self.client.post(self.url("/auth/device/create"))
.json(&serde_json::json!({ "client": client })).send().await?;
if !response.status().is_success() { bail!("Could not start the login ({})", response.status()); }
Ok(response.json().await?)
}
pub async fn device_poll(&self, poll_token: &str) -> Result<DevicePoll> {
let response = self.client.post(self.url("/auth/device/poll"))
.json(&serde_json::json!({ "pollToken": poll_token })).send().await?;
if !response.status().is_success() { bail!("Could not check the login ({})", response.status()); }
Ok(response.json().await?)
}
pub async fn get<T: serde::de::DeserializeOwned>(&self, path: &str) -> Result<T> {
let token = self.token.as_deref().ok_or_else(|| anyhow::anyhow!("Not authenticated"))?;
let response = self.client.get(self.url(path)).header("Authorization", format!("Bearer {token}")).send().await?;
match response.status().as_u16() {
200 => Ok(response.json().await?),
401 => bail!("This device is not linked any more. Run `frislit login`"),
other => bail!("Unexpected response from server: {other}"),
}
}
pub async fn whoami(&self) -> Result<Me> {
self.get("/whoami").await
}
}
#[derive(serde::Deserialize)]
pub struct Me { pub username: String, pub guest: Option<String> }
impl Me {
pub fn label(&self) -> String {
match &self.guest { Some(guest) => format!("{guest} (guest of {})", self.username), None => self.username.clone() }
}
}
pub fn ws_url(base_url: &str) -> String {
let base = base_url.trim_end_matches('/').replacen("https://", "wss://", 1).replacen("http://", "ws://", 1);
format!("{base}/@frislit/ws")
}
+93
View File
@@ -0,0 +1,93 @@
use anyhow::{bail, Result};
use std::time::Duration;
use crate::api::{ApiClient, Me, ServerInfo};
use crate::connect::percent_decode;
use crate::config::{normalize_url, Config};
use crate::session::{Events, Stop};
const POLL_INTERVAL: Duration = Duration::from_secs(2);
pub enum LoginEvent {
Code { code: String, handoff_url: String },
Linked { server_url: String, info: ServerInfo },
}
pub struct Invite { pub server_url: String, pub token: String }
pub fn parse_invite(link: &str) -> Option<Invite> {
let link = link.trim();
if let Some(rest) = link.strip_prefix("frislit://invite/") {
let (token, query) = rest.split_once('?').unwrap_or((rest, ""));
let server = query.split('&').find_map(|pair| pair.strip_prefix("server=")).map(percent_decode)?;
return Some(Invite { server_url: normalize_url(&server), token: token.trim_matches('/').to_string() });
}
let (server, token) = link.split_once("/@frislit/invite/")?;
if !server.starts_with("http://") && !server.starts_with("https://") { return None; }
Some(Invite { server_url: normalize_url(server), token: token.trim_matches('/').to_string() })
}
pub async fn accept_invite(invite: Invite, accept_invalid_certs: bool) -> Result<(Me, ServerInfo)> {
if invite.token.is_empty() { bail!("That invite link carries no token"); }
link_token(invite.server_url, invite.token, accept_invalid_certs).await.map_err(|_| anyhow::anyhow!("That invite link is not valid any more"))
}
pub async fn link_token(server_url: String, token: String, accept_invalid_certs: bool) -> Result<(Me, ServerInfo)> {
let server_url = normalize_url(&server_url);
let client = ApiClient::new(&server_url, Some(&token), accept_invalid_certs)?;
let info = client.info().await?;
let me = client.whoami().await.map_err(|_| anyhow::anyhow!("The server did not accept that token"))?;
let mut cfg = Config::load()?;
cfg.server_url = Some(server_url);
cfg.device_token = Some(token);
cfg.save()?;
Ok((me, info))
}
pub async fn link(server_url: &str, accept_invalid_certs: bool, out: Events<LoginEvent>, mut stop: Stop) -> Result<()> {
let server_url = normalize_url(server_url);
let client = ApiClient::new(&server_url, None, accept_invalid_certs)?;
let info = client.info().await?;
let request = client.device_create(&hostname()).await?;
let _ = out.send(LoginEvent::Code { code: request.code.clone(), handoff_url: request.handoff_url.clone() });
let token = loop {
tokio::select! {
_ = tokio::time::sleep(POLL_INTERVAL) => {}
_ = stop.wait() => return Ok(()),
}
let poll = client.device_poll(&request.poll_token).await?;
match poll.status.as_str() {
"pending" => continue,
"authorized" => break poll.token.ok_or_else(|| anyhow::anyhow!("Approved but no token was returned"))?,
_ => bail!("The code expired or was denied. Run `frislit login` again"),
}
};
let linked = ApiClient::new(&server_url, Some(&token), accept_invalid_certs)?;
linked.whoami().await?;
let mut cfg = Config::load()?;
cfg.server_url = Some(server_url.clone());
cfg.device_token = Some(token);
cfg.save()?;
let _ = out.send(LoginEvent::Linked { server_url, info });
Ok(())
}
pub fn logout() -> Result<bool> {
let mut cfg = Config::load()?;
if cfg.device_token.is_none() { return Ok(false); }
cfg.device_token = None;
cfg.save()?;
Ok(true)
}
fn hostname() -> String {
std::env::var("HOSTNAME")
.ok()
.or_else(|| std::env::var("COMPUTERNAME").ok())
.or_else(|| std::fs::read_to_string("/etc/hostname").ok().map(|name| name.trim().to_string()))
.filter(|name| !name.is_empty())
.unwrap_or_else(|| "frislit CLI".to_string())
}
+319
View File
@@ -0,0 +1,319 @@
use anyhow::{Context, Result};
use console::style;
use dialoguer::{Input, Select};
use indicatif::{ProgressBar, ProgressStyle};
use std::future::Future;
use std::io::IsTerminal;
use std::time::Duration;
use tokio::sync::mpsc::UnboundedReceiver;
use crate::auth::{self, LoginEvent};
use crate::config::Config;
use crate::connect;
use crate::qr;
use crate::session::{self, Events, JoinEvent, Online, Request, Stop, TunnelEvent};
use crate::shape::Shape;
use crate::tui;
use crate::tunnel::{self, Options};
use crate::update;
fn ok() -> console::StyledObject<&'static str> { style("✓").green().bold() }
fn warn() -> console::StyledObject<&'static str> { style("!").yellow().bold() }
#[derive(Default)]
struct Printer { spinner: Option<ProgressBar> }
impl Printer {
fn busy(&mut self, message: String) {
match &self.spinner {
Some(spinner) => spinner.set_message(message),
None => {
let spinner = ProgressBar::new_spinner();
spinner.set_style(ProgressStyle::default_spinner().template("{spinner:.green} {msg}").unwrap());
spinner.set_message(message);
spinner.enable_steady_tick(Duration::from_millis(100));
self.spinner = Some(spinner);
}
}
}
fn idle(&mut self) {
if let Some(spinner) = self.spinner.take() { spinner.finish_and_clear(); }
}
fn reconnecting(&mut self, seconds: u64, reason: Option<String>) {
match reason {
None => self.busy("Connection lost, reconnecting...".into()),
Some(text) => self.busy(format!("Reconnecting in {seconds}s... ({text})")),
}
}
}
fn stop_on_ctrl_c() -> Stop {
let (handle, stop) = Stop::new();
tokio::spawn(async move {
let _ = tokio::signal::ctrl_c().await;
handle.stop();
});
stop
}
fn session<E>() -> (Events<E>, UnboundedReceiver<E>, Stop) {
let (events, rx) = session::channel();
(events, rx, stop_on_ctrl_c())
}
async fn printed<E: Send + 'static>(
mut rx: UnboundedReceiver<E>,
mut print: impl FnMut(&mut Printer, E) + Send + 'static,
work: impl Future<Output = Result<()>>,
) -> Result<()> {
let printer = tokio::spawn(async move {
let mut printer = Printer::default();
while let Some(event) = rx.recv().await { print(&mut printer, event); }
printer.idle();
});
let result = work.await;
let _ = printer.await;
result
}
fn print_ready(online: &Online, target_label: &str, server_url: &str, shape: &Shape) {
let kind = if online.persistent { style(" (persistent)").dim().to_string() } else { String::new() };
println!("{} Tunnel {} is online{kind}", ok(), style(&online.id).cyan().bold());
if let Some(url) = &online.url {
println!(" {} {} {}", style(url).cyan().bold().underlined(), style("forwards to").dim(), style(target_label).bold());
for custom in &online.custom_urls {
println!(" {}", style(custom).cyan().underlined());
}
println!();
qr::print(url);
if qr::copy(url) { println!("{} Copied to clipboard", ok()); }
} else if let Some(link) = online.link(server_url) {
println!(" Forwarding {} (tcp+udp)", style(target_label).bold());
println!(" Others run: {}", style(format!("frislit connect {link}")).cyan().bold());
println!();
qr::print(&link);
if qr::copy(&format!("frislit connect {link}")) { println!("{} Copied to clipboard", ok()); }
}
if let Some(summary) = &online.access {
println!(" {} {}", style("Access:").dim(), style(summary).yellow());
}
if let Some(summary) = shape.summary() {
println!(" {} {}", style("Network:").dim(), style(summary).yellow());
}
println!("Press {} to stop.", style("Ctrl+C").bold());
}
fn print_request(request: &Request) {
let status = match request.status {
200..=299 => style(request.status).green(),
300..=399 => style(request.status).cyan(),
400..=499 => style(request.status).yellow(),
_ => style(request.status).red(),
};
let label = if request.kind == "ws" { style("WS ").magenta().to_string() } else { style(format!("{:<4}", request.method)).bold().to_string() };
let intel = request.intel().map(|text| format!(" {text}")).unwrap_or_default();
println!("{} {} {} {}{}", label, status.bold(), style(&request.path).dim(), style(format!("{}ms", request.duration)).dim(), style(intel).dim());
}
pub async fn tunnel(opts: Options, plain: bool) -> Result<()> {
let cfg = Config::load()?;
let (server_url, token) = cfg.require_auth()?;
let (opts, target, label, _local) = tunnel::prepare(opts).await?;
let shape = opts.shape.clone();
let (events, rx) = session::channel();
let hint = events.clone();
let _check = session::Task(tokio::spawn(async move { if let Some(version) = update::check().await { let _ = hint.send(TunnelEvent::Update(version)); } }));
if !plain && std::io::stdout().is_terminal() {
let api = crate::api::ApiClient::new(&server_url, Some(&token), cfg.accept_invalid_certs)?;
let me = api.whoami().await?;
let ctx = tui::Context { server_url, account: me.label(), target: label, network: shape.summary(), tcp: opts.mode == "tcp" };
let (handle, stop) = Stop::new();
let ui = tokio::spawn(tui::run(rx, handle, ctx));
let result = tunnel::run(opts, target, events, stop).await;
match ui.await?? {
Some(reason) => println!("{} Tunnel ended: {}", warn(), style(reason).dim()),
None => println!("{} Tunnel closed", ok()),
}
return result;
}
let stop = stop_on_ctrl_c();
printed(rx, move |printer, event| match event {
TunnelEvent::Connecting => printer.busy("Connecting to server...".into()),
TunnelEvent::Online(online) => { printer.idle(); print_ready(&online, &label, &server_url, &shape); }
TunnelEvent::Resumed(online) => { printer.idle(); println!("{} Reconnected, tunnel {} is back online", ok(), style(&online.id).cyan()); }
TunnelEvent::Replaced(online) => {
printer.idle();
println!("{} The old tunnel expired, a new one was created", warn());
print_ready(&online, &label, &server_url, &shape);
}
TunnelEvent::Request(request) => print_request(&request),
TunnelEvent::Connection(connection) => println!("{}", style(connection.line()).dim()),
TunnelEvent::Access(summary) => println!("{} {}", style("Access:").dim(), style(summary).yellow()),
TunnelEvent::Reconnecting { seconds, reason } => printer.reconnecting(seconds, reason),
TunnelEvent::Update(version) => println!("{} frislit {version} is available, run {}", style("↑").cyan(), style("frislit update").cyan()),
TunnelEvent::Stopped => { printer.idle(); println!("\n{} Tunnel closed", ok()); }
TunnelEvent::Ended(reason) => { printer.idle(); println!("{} Tunnel ended: {}", ok(), style(reason).dim()); }
}, tunnel::run(opts, target, events, stop)).await
}
pub async fn connect(target: String, port: Option<u16>, bind: String, server: Option<String>) -> Result<()> {
let explicit = port.is_some();
let pick_port: connect::PortPicker = Box::new(move |taken| {
println!("{} Port {} is already in use", warn(), style(taken).bold());
if explicit || !console::user_attended() { anyhow::bail!("Choose another port with --port"); }
Ok(Input::new().with_prompt("Local port to use instead").default(taken + 1).interact_text()?)
});
let opts = connect::Options { target, port, bind, server, pick_port: Some(pick_port) };
let (events, rx, stop) = session();
printed(rx, |printer, event| match event {
JoinEvent::Connecting => printer.busy("Connecting to server...".into()),
JoinEvent::Forwarding { bind, port, tunnel_id, owner_online } => {
printer.idle();
println!("{} Forwarding {} (tcp+udp) to {}", ok(), style(format!("{bind}:{port}")).cyan().bold(), style(&tunnel_id).bold().green());
if !owner_online { println!("{} The owner is currently offline, connections will work once it is back", warn()); }
println!("Press {} to stop.", style("Ctrl+C").bold());
}
JoinEvent::Reconnecting { seconds, reason } => printer.reconnecting(seconds, reason),
JoinEvent::Reconnected => { printer.idle(); println!("{} Reconnected", ok()); }
JoinEvent::Stopped => { printer.idle(); println!("\n{} Stopped", ok()); }
JoinEvent::Ended(reason) => { printer.idle(); println!("{} Disconnected: {}", ok(), style(reason).dim()); }
}, connect::run(opts, events, stop)).await
}
#[derive(serde::Deserialize)]
struct Listed {
id: String,
target: String,
url: Option<String>,
online: bool,
#[serde(rename = "graceUntil")] grace_until: Option<u64>,
joiners: u64,
persistent: bool,
#[serde(rename = "customUrls")] custom_urls: Vec<String>,
}
#[derive(serde::Deserialize)]
struct Tunnels { tunnels: Vec<Listed>, now: u64 }
#[derive(serde::Deserialize)]
struct Saved { name: String, url: String, live: bool }
#[derive(serde::Deserialize)]
struct Persistent { tunnels: Vec<Saved> }
fn mark(name: &str, persistent: bool) -> String { if persistent { format!("{name} *") } else { name.to_string() } }
pub async fn list() -> Result<()> {
let cfg = Config::load()?;
let (server_url, token) = cfg.require_auth()?;
let api = crate::api::ApiClient::new(&server_url, Some(&token), cfg.accept_invalid_certs)?;
let (live, saved): (Tunnels, Persistent) = tokio::try_join!(api.get("/tunnels"), api.get("/persistent"))?;
let mut rows: Vec<[String; 4]> = live.tunnels.iter().map(|tunnel| {
let state = if tunnel.online { style("● online").green().to_string() }
else if let Some(until) = tunnel.grace_until { style(format!("○ closes in {}s", until.saturating_sub(live.now) / 1000)).yellow().to_string() }
else { style("○ offline").yellow().to_string() };
let address = match &tunnel.url {
Some(url) => std::iter::once(url.as_str()).chain(tunnel.custom_urls.iter().map(String::as_str)).collect::<Vec<_>>().join(", "),
None => format!("tcp+udp · {} connected", tunnel.joiners),
};
[mark(&tunnel.id, tunnel.persistent), state, address, tunnel.target.clone()]
}).collect();
rows.extend(saved.tunnels.iter().filter(|saved| !saved.live)
.map(|saved| [mark(&saved.name, true), style("○ offline").dim().to_string(), saved.url.clone(), String::new()]));
if rows.is_empty() {
println!("No tunnels. Start one with {}", style("frislit http 3000").cyan());
return Ok(());
}
let widths: Vec<usize> = (0..3).map(|column| rows.iter().map(|row| console::measure_text_width(&row[column])).max().unwrap()).collect();
for [name, state, address, target] in &rows {
println!("{} {} {} {}",
style(console::pad_str(name, widths[0], console::Alignment::Left, None)).bold(),
console::pad_str(state, widths[1], console::Alignment::Left, None),
style(console::pad_str(address, widths[2], console::Alignment::Left, None)).cyan(),
style(target).dim());
}
if rows.iter().any(|row| row[0].ends_with('*')) { println!("{}", style("* persistent").dim()); }
Ok(())
}
pub async fn update() -> Result<()> {
let install = update::detect();
let latest = update::latest().await.context("Could not reach GitHub to look for releases")?;
if !update::newer(&latest) {
println!("{} frislit {} is the latest version", ok(), style(update::CURRENT).cyan());
return Ok(());
}
println!("Updating frislit {} to {}", style(update::CURRENT).dim(), style(&latest).cyan().bold());
if install == update::Install::Managed {
println!(" This frislit was installed by a package manager and is updated through it.");
return Ok(());
}
update::apply(&latest, &install, false).await?;
if install == update::Install::Msi { println!("{} The installer is running, frislit {latest} is ready in a moment", ok()); }
else { println!("{} Updated to frislit {latest}", ok()); }
Ok(())
}
pub async fn login(link: Option<String>, token: Option<String>, server: Option<String>) -> Result<()> {
let cfg = Config::load()?;
if let Some(token) = token {
let server_url = server.or_else(|| cfg.server_url()).context("Pass --server <url> along with the key")?;
let (me, info) = auth::link_token(server_url, token, cfg.accept_invalid_certs).await?;
println!("{} Linked to {} as {}", ok(), style(info.name).cyan().bold(), style(me.label()).cyan());
println!(" Tunnels will be created under {}", style(&info.base_domain).cyan());
return Ok(());
}
if let Some(link) = link {
let invite = auth::parse_invite(&link).ok_or_else(|| anyhow::anyhow!("That is not an invite link. Run `frislit login` without arguments to link with your account"))?;
let (me, info) = auth::accept_invite(invite, cfg.accept_invalid_certs).await?;
println!("{} Linked to {} as {}", ok(), style(info.name).cyan().bold(), style(me.label()).cyan());
println!(" Tunnels will be created under {}", style(&info.base_domain).cyan());
return Ok(());
}
let server_url: String = if let Some(ref url) = cfg.server_url {
println!("Current server: {}", style(url).cyan());
let choice = Select::new().with_prompt("Server URL")
.items(["Keep current server", "Enter a new server URL"]).default(0).interact()?;
if choice == 0 { url.clone() } else { Input::new().with_prompt("Server URL").interact_text()? }
} else {
Input::new().with_prompt("Server URL (e.g. https://frislit.example.com)").interact_text()?
};
let (events, rx, stop) = session();
printed(rx, |printer, event| match event {
LoginEvent::Code { code, handoff_url } => {
println!();
println!(" Approve this device at {}", style(&handoff_url).cyan().bold().underlined());
println!(" Code: {}", style(&code).bold().green());
if open::that_detached(&handoff_url).is_ok() {
println!(" {}", style("Opened in your browser.").dim());
}
println!();
printer.busy("Waiting for approval...".into());
}
LoginEvent::Linked { server_url, info } => {
printer.idle();
println!("{} This device is linked to {} ({} {})", ok(), style(&server_url).cyan().bold(), info.name, info.version);
println!(" Tunnels will be created under {}", style(&info.base_domain).cyan());
}
}, auth::link(&server_url, cfg.accept_invalid_certs, events, stop)).await
}
pub fn logout() -> Result<()> {
if !auth::logout()? {
println!("This device is not linked.");
return Ok(());
}
println!("{} Token removed from this device", ok());
println!(" {}", style("Revoke it on the server too, on the Devices settings page.").dim());
Ok(())
}
+87
View File
@@ -0,0 +1,87 @@
use anyhow::{bail, Context, Result};
use serde::{Deserialize, Serialize};
use std::{fs, path::PathBuf};
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct Config {
#[serde(default)] pub server_url: Option<String>,
#[serde(default)] pub device_token: Option<String>,
#[serde(default)] pub accept_invalid_certs: bool,
#[serde(default)] pub update_checked_at: u64,
#[serde(default)] pub update_latest: Option<String>,
}
impl Config {
fn path() -> Result<PathBuf> {
let dir = dirs::config_dir().context("No config directory")?.join("frislit");
fs::create_dir_all(&dir)?;
Ok(dir.join("config.json"))
}
pub fn load() -> Result<Self> {
let path = Self::path()?;
if !path.exists() { return Ok(Self::default()); }
serde_json::from_str(&fs::read_to_string(&path)?).context("Failed to parse config")
}
pub fn save(&self) -> Result<()> {
Ok(fs::write(Self::path()?, serde_json::to_string_pretty(self)?)?)
}
pub fn server_url(&self) -> Option<String> {
std::env::var("FRISLIT_SERVER").ok().filter(|v| !v.trim().is_empty())
.or_else(|| self.server_url.clone())
.map(|v| normalize_url(&v))
}
pub fn token(&self) -> Option<String> {
std::env::var("FRISLIT_TOKEN").ok().filter(|v| !v.trim().is_empty()).or_else(|| self.device_token.clone())
}
pub fn require_server(&self) -> Result<String> {
self.server_url().ok_or_else(|| anyhow::anyhow!("No server configured. Run `frislit login` or pass --server / FRISLIT_SERVER"))
}
pub fn require_auth(&self) -> Result<(String, String)> {
let url = self.require_server()?;
let token = self.token().ok_or_else(|| anyhow::anyhow!("This device is not linked. Run `frislit login` first"))?;
Ok((url, token))
}
}
pub fn normalize_url(url: &str) -> String {
let trimmed = url.trim().trim_end_matches('/');
if trimmed.starts_with("http://") || trimmed.starts_with("https://") { trimmed.to_string() } else { format!("https://{trimmed}") }
}
pub fn set(key: &str, value: &str) -> Result<()> {
let mut cfg = Config::load()?;
match key {
"server-url" => cfg.server_url = Some(normalize_url(value)),
"device-token" => cfg.device_token = Some(value.to_string()),
"accept-invalid-certs" => cfg.accept_invalid_certs = value.parse().context("Must be 'true' or 'false'")?,
_ => bail!("Unknown key: {key}. Valid: server-url, device-token, accept-invalid-certs"),
}
cfg.save()?;
println!("Set {key} = {}", if key == "device-token" { "(set)" } else { value });
Ok(())
}
pub fn get(key: &str) -> Result<()> {
let cfg = Config::load()?;
println!("{}", match key {
"server-url" => cfg.server_url.unwrap_or_default(),
"accept-invalid-certs" => cfg.accept_invalid_certs.to_string(),
"device-token" => cfg.device_token.map(|_| "(set)".into()).unwrap_or_default(),
_ => bail!("Unknown key: {key}"),
});
Ok(())
}
pub fn show() -> Result<()> {
let cfg = Config::load()?;
println!("server-url: {}", cfg.server_url.as_deref().unwrap_or("(not set)"));
println!("accept-invalid-certs: {}", cfg.accept_invalid_certs);
println!("device-token: {}", if cfg.device_token.is_some() { "(set)" } else { "(not set)" });
Ok(())
}
+294
View File
@@ -0,0 +1,294 @@
use anyhow::{bail, Context, Result};
use serde_json::json;
use std::collections::HashMap;
use std::net::SocketAddr;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use tokio::net::{TcpListener, UdpSocket};
use crate::api::ws_url;
use crate::config::{normalize_url, Config};
use crate::mux::{expect, Incoming, Mux, MuxEvents, MuxWriter, OpenMeta};
use crate::session::{Events, JoinEvent, Stop, Task};
use crate::shape::Shape;
use crate::tcp::{pump_tcp, UDP_IDLE};
use crate::tunnel::server_hello;
pub type PortPicker = Box<dyn Fn(u16) -> Result<u16> + Send + Sync>;
#[derive(Debug)]
pub struct PortInUse { pub port: u16, pub bind: String }
impl std::fmt::Display for PortInUse {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(formatter, "Port {} is already in use on {}", self.port, self.bind)
}
}
impl std::error::Error for PortInUse {}
pub struct Options {
pub target: String,
pub port: Option<u16>,
pub bind: String,
pub server: Option<String>,
pub pick_port: Option<PortPicker>,
}
type Current = Arc<Mutex<Option<Arc<Mux>>>>;
async fn join(url: &str, code: &str, accept_invalid_certs: bool) -> Result<(Arc<Mux>, MuxEvents, u16, bool)> {
let (mux, mut events) = Mux::connect(url, None, accept_invalid_certs).await?;
mux.send_control(server_hello("joiner", None)).await?;
expect(&mut events, "hello").await?;
mux.send_control(json!({ "type": "join", "code": code })).await?;
let msg = expect(&mut events, "joined").await?;
let port = msg.get("port").and_then(|p| p.as_u64()).context("joined without port")? as u16;
let online = msg.get("online").and_then(|o| o.as_bool()).unwrap_or(true);
Ok((mux, events, port, online))
}
async fn bind(bind_addr: &str, port: u16, pick_port: Option<&PortPicker>) -> Result<(TcpListener, UdpSocket, u16)> {
let mut port = port;
loop {
let addr: SocketAddr = format!("{bind_addr}:{port}").parse().with_context(|| format!("Invalid bind address {bind_addr}"))?;
match (TcpListener::bind(addr).await, UdpSocket::bind(addr).await) {
(Ok(tcp), Ok(udp)) => return Ok((tcp, udp, port)),
_ => match pick_port {
Some(pick) => port = pick(port)?,
None => return Err(PortInUse { port, bind: bind_addr.to_string() }.into()),
},
}
}
}
fn parse_scheme(rest: &str) -> Result<(String, Option<String>)> {
let (path, query) = rest.split_once('?').unwrap_or((rest, ""));
let code = path.trim_start_matches("connect").trim_matches('/').to_string();
if code.is_empty() { bail!("That link carries no share code"); }
let mut server = None;
for pair in query.split('&') {
let Some((key, value)) = pair.split_once('=') else { continue };
if key != "server" { continue }
let decoded = percent_decode(value);
if !decoded.starts_with("http://") && !decoded.starts_with("https://") {
bail!("The server in that link is not an http(s) address");
}
server = Some(decoded.trim_end_matches('/').to_string());
}
Ok((code, server))
}
pub fn percent_decode(value: &str) -> String {
let bytes = value.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%' && i + 2 < bytes.len() {
if let Ok(byte) = u8::from_str_radix(&value[i + 1..i + 3], 16) {
out.push(byte);
i += 3;
continue;
}
}
out.push(if bytes[i] == b'+' { b' ' } else { bytes[i] });
i += 1;
}
String::from_utf8_lossy(&out).to_string()
}
fn parse_target(target: &str) -> Result<(String, Option<String>)> {
let target = target.trim();
if let Some(rest) = target.strip_prefix("frislit://") {
return parse_scheme(rest);
}
if let Some(rest) = target.strip_prefix("http://").or_else(|| target.strip_prefix("https://")) {
let scheme = if target.starts_with("https://") { "https" } else { "http" };
let (authority, path) = rest.split_once('/').unwrap_or((rest, ""));
if authority.is_empty() { bail!("\"{target}\" has no server in it"); }
let code = path.rsplit('/').find(|part| !part.is_empty()).unwrap_or("");
if code.is_empty() { bail!("\"{target}\" has no share code in it"); }
return Ok((code.to_string(), Some(format!("{scheme}://{authority}"))));
}
Ok((target.to_string(), None))
}
pub fn resolve(target: &str, server: Option<&str>) -> Result<(String, String, String)> {
if crate::auth::parse_invite(target).is_some() { bail!("That is an invite link. Run `frislit login {target}` instead"); }
let (code, from_link) = parse_target(target)?;
if code.is_empty() || !code.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') { bail!("The share code must be alphanumeric"); }
if code.len() <= 26 { bail!("That share code is too short"); }
let cfg = Config::load()?;
let server_url = server.map(normalize_url).or(from_link).or_else(|| cfg.server_url())
.ok_or_else(|| anyhow::anyhow!("No server in that code. Paste the whole link, or use --server <url>"))?;
let tunnel_id = code[..code.len() - 26].to_string();
Ok((code, tunnel_id, server_url))
}
const INVALID_RETRIES: u32 = 6;
pub async fn run(opts: Options, out: Events<JoinEvent>, mut stop: Stop) -> Result<()> {
let (code, tunnel_id, server_url) = resolve(&opts.target, opts.server.as_deref())?;
let cfg = Config::load()?;
let url = ws_url(&server_url);
let _ = out.send(JoinEvent::Connecting);
let joined = tokio::select! {
result = join(&url, &code, cfg.accept_invalid_certs) => result,
_ = stop.wait() => return Ok(()),
};
let (mux, mut events, remote_port, online) = joined?;
let bound = bind(&opts.bind, opts.port.unwrap_or(remote_port), opts.pick_port.as_ref()).await;
let (tcp, udp, local_port) = match bound {
Ok(bound) => bound,
Err(err) => {
let _ = mux.send_control(json!({ "type": "bye" })).await;
mux.close().await;
return Err(err);
}
};
let _ = out.send(JoinEvent::Forwarding { bind: opts.bind.clone(), port: local_port, tunnel_id, owner_online: online });
let current: Current = Arc::new(Mutex::new(Some(mux.clone())));
let _listeners = (Task(tokio::spawn(accept_tcp(tcp, current.clone()))), Task(tokio::spawn(accept_udp(udp, current.clone()))));
let mut backoff = 1u64;
loop {
let lost = tokio::select! {
ended = drain(&mut events) => {
if let Some(reason) = ended {
*current.lock().unwrap() = None;
let _ = out.send(JoinEvent::Ended(reason));
return Ok(());
}
true
}
_ = stop.wait() => false,
};
if !lost {
let session = current.lock().unwrap().take();
if let Some(session) = session {
let _ = session.send_control(json!({ "type": "bye" })).await;
session.close().await;
}
let _ = out.send(JoinEvent::Stopped);
return Ok(());
}
*current.lock().unwrap() = None;
let mut reason = None;
let mut invalid = 0;
loop {
let _ = out.send(JoinEvent::Reconnecting { seconds: backoff, reason: reason.take() });
tokio::select! {
_ = tokio::time::sleep(Duration::from_secs(backoff)) => {}
_ = stop.wait() => { let _ = out.send(JoinEvent::Stopped); return Ok(()); }
}
let attempt = tokio::select! {
result = join(&url, &code, cfg.accept_invalid_certs) => result,
_ = stop.wait() => { let _ = out.send(JoinEvent::Stopped); return Ok(()); }
};
match attempt {
Ok((new_mux, new_events, _, _)) => {
let _ = out.send(JoinEvent::Reconnected);
*current.lock().unwrap() = Some(new_mux);
events = new_events;
backoff = 1;
break;
}
Err(err) => {
let text = err.to_string();
if text.contains("(invalid_code)") { invalid += 1; }
if text.contains("(not_found)") || invalid > INVALID_RETRIES { bail!("{text}"); }
backoff = (backoff * 2).min(30);
reason = Some(text);
}
}
}
}
}
async fn drain(events: &mut MuxEvents) -> Option<String> {
loop {
tokio::select! {
msg = events.control.recv() => match msg {
None => return None,
Some(msg) => {
if msg.get("type").and_then(|t| t.as_str()) == Some("bye") {
return Some(msg.get("reason").and_then(|r| r.as_str()).unwrap_or("closed by the server").to_string());
}
}
},
stream = events.streams.recv() => { if stream.is_none() { return None; } }
}
}
}
async fn accept_tcp(listener: TcpListener, current: Current) {
loop {
let Ok((socket, peer)) = listener.accept().await else { continue };
let _ = socket.set_nodelay(true);
let mux = current.lock().unwrap().clone();
let Some(mux) = mux else { drop(socket); continue };
tokio::spawn(async move {
match mux.open(&OpenMeta::tcp(peer.to_string())).await {
Ok((writer, reader)) => pump_tcp(socket, writer, reader, &Shape::default()).await,
Err(_) => drop(socket),
}
});
}
}
struct Flow { writer: MuxWriter, last_active: Arc<Mutex<Instant>> }
async fn accept_udp(socket: UdpSocket, current: Current) {
let socket = Arc::new(socket);
let flows: Arc<Mutex<HashMap<SocketAddr, Flow>>> = Arc::new(Mutex::new(HashMap::new()));
let mut sweep = tokio::time::interval(Duration::from_secs(10));
let mut buf = vec![0u8; 65535];
loop {
let (n, src) = tokio::select! {
received = socket.recv_from(&mut buf) => match received { Ok(pair) => pair, Err(_) => continue },
_ = sweep.tick() => {
let expired: Vec<Flow> = {
let mut map = flows.lock().unwrap();
let dead: Vec<SocketAddr> = map.iter().filter(|(_, f)| f.last_active.lock().unwrap().elapsed() > UDP_IDLE).map(|(a, _)| *a).collect();
dead.into_iter().filter_map(|a| map.remove(&a)).collect()
};
for flow in expired { flow.writer.close().await; }
continue;
}
};
let existing = {
let map = flows.lock().unwrap();
map.get(&src).map(|f| { *f.last_active.lock().unwrap() = Instant::now(); f.writer.clone() })
};
let writer = match existing {
Some(w) => w,
None => {
let mux = current.lock().unwrap().clone();
let Some(mux) = mux else { continue };
let Ok((writer, mut reader)) = mux.open(&OpenMeta::udp(src.to_string())).await else { continue };
let last_active = Arc::new(Mutex::new(Instant::now()));
let handle = writer.clone();
flows.lock().unwrap().insert(src, Flow { writer, last_active: last_active.clone() });
let socket = socket.clone();
let flows = flows.clone();
tokio::spawn(async move {
loop {
match reader.recv().await {
Incoming::Datagram(data) => { *last_active.lock().unwrap() = Instant::now(); let _ = socket.send_to(&data, src).await; }
Incoming::Close | Incoming::Reset => break,
Incoming::Data(_) => {}
}
}
flows.lock().unwrap().remove(&src);
});
handle
}
};
let _ = writer.send_datagram(&buf[..n]).await;
}
}
+770
View File
@@ -0,0 +1,770 @@
use eframe::egui::{self, Align, Color32, CursorIcon, Frame, Layout, Margin, RichText, Sense, Stroke, TextureHandle, TextureOptions, Ui, UiBuilder};
use std::collections::{HashMap, VecDeque};
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{self, Receiver, Sender};
use std::sync::Arc;
use tokio::sync::mpsc::UnboundedReceiver;
use std::time::{Duration, Instant};
use tokio::runtime::Handle;
use crate::api::{ApiClient, Me, ServerInfo};
use crate::auth::{self, LoginEvent};
use crate::config::Config;
use crate::connect;
use crate::qr;
use crate::session::{self, Connection, JoinEvent, Online, Request, Stop, StopHandle, Task, TunnelEvent};
use crate::tunnel::{self, connect_target, Options, Target};
use crate::update;
use super::ports::{self, Listener};
use super::{format, hide_by_closing, theme, widgets, Repaint, Wake};
const MAX_REQUESTS: usize = 500;
const TOAST_FOR: Duration = Duration::from_secs(3);
const UNDO_FOR: Duration = Duration::from_secs(8);
const PROBE_TIMEOUT: Duration = Duration::from_secs(1);
const PROBE_INTERVAL: Duration = Duration::from_secs(5);
const SCAN_INTERVAL: Duration = Duration::from_secs(4);
#[derive(Clone, Copy, PartialEq)]
pub enum Page { Tunnels, NewTunnel, Tunnel(u64), Connect, Settings }
pub enum Msg {
TunnelReady(u64, String),
Tunnel(u64, TunnelEvent),
TunnelFailed(u64, String),
Join(u64, JoinEvent),
JoinFailed(u64, String, Option<u16>),
Login(LoginEvent),
LoginFailed(String),
Info(Result<ServerInfo, String>),
Me(Option<Me>),
Linked(Result<String, String>),
Update(Option<String>),
Updated(Result<(), String>),
TunnelProbe(u64, Option<String>),
Listeners(Vec<Listener>),
FolderPicked(Option<PathBuf>),
}
#[derive(Clone, Copy, PartialEq)]
pub enum TunnelKind { Http, Files, Tcp }
impl TunnelKind {
pub fn label(self) -> &'static str { match self { Self::Http => "http", Self::Files => "files", Self::Tcp => "tcp" } }
}
#[derive(PartialEq)]
pub enum TunnelState { Connecting, Online, Reconnecting { seconds: u64, reason: Option<String> } }
pub struct LoggedRequest { pub request: Request, pub at: Instant }
pub struct TunnelCard {
pub id: u64,
pub kind: TunnelKind,
pub opts: Options,
pub target_label: String,
pub access: Option<String>,
pub probe: Option<String>,
pub state: TunnelState,
pub online: Option<Online>,
pub requests: VecDeque<LoggedRequest>,
pub connections: VecDeque<Connection>,
pub request_count: u64,
pub started: Instant,
pub stop: StopHandle,
pub show_qr: bool,
pub copied_at: Option<Instant>,
}
impl TunnelCard {
pub fn link(&self, server_url: &str) -> Option<String> { self.online.as_ref().and_then(|online| online.link(server_url)) }
pub fn title(&self) -> String { self.online.as_ref().map(|online| online.id.clone()).unwrap_or_else(|| self.target_label.clone()) }
}
pub enum JoinState { Connecting, Forwarding, Reconnecting { seconds: u64, reason: Option<String> } }
pub struct Forwarding { pub port: u16, pub tunnel_id: String, pub owner_online: bool }
pub struct JoinCard {
pub id: u64,
pub target: String,
pub code: String,
pub server: String,
pub state: JoinState,
pub forwarding: Option<Forwarding>,
pub started: Instant,
pub stop: StopHandle,
}
pub enum LoginStage { Idle, Starting, Waiting { code: String, url: String }, Failed(String) }
pub struct LoginForm { pub server: String, pub accept_invalid: bool, pub key: String, pub use_key: bool, pub stage: LoginStage, pub stop: Option<StopHandle> }
#[derive(Clone, Copy, PartialEq)]
pub enum AuthChoice { Open, Password, Login }
pub struct NewTunnelForm {
pub kind: TunnelKind,
pub target: String,
pub dir: String,
pub picking_dir: bool,
pub name: String,
pub keep_host: bool,
pub auth: AuthChoice,
pub password: String,
pub allow: Vec<String>,
pub allow_input: String,
pub error: Option<String>,
}
impl Default for NewTunnelForm {
fn default() -> Self {
Self { kind: TunnelKind::Http, target: String::new(), dir: String::new(), picking_dir: false, name: String::new(), keep_host: false,
auth: AuthChoice::Open, password: String::new(), allow: Vec::new(), allow_input: String::new(), error: None }
}
}
#[derive(Default)]
pub struct ConnectForm { pub link: String, pub error: Option<String>, pub retry_port: Option<String> }
pub enum ToastAction { Reopen(TunnelKind, Options) }
pub struct Toast { pub text: String, pub at: Instant, pub error: bool, pub action: Option<ToastAction> }
impl Toast {
pub fn expired(&self) -> bool { self.at.elapsed() > if self.action.is_some() { UNDO_FOR } else { TOAST_FOR } }
}
#[derive(Clone)]
struct Mailbox { tx: Sender<Msg>, repaint: Repaint }
impl Mailbox {
fn send(&self, msg: Msg) {
let _ = self.tx.send(msg);
self.repaint.ping();
}
}
pub struct State {
pub runtime: Handle,
mailbox: Mailbox,
rx: Receiver<Msg>,
pub page: Page,
pub cfg: Config,
pub server_info: Option<Result<ServerInfo, String>>,
pub tunnels: Vec<TunnelCard>,
pub joins: Vec<JoinCard>,
next_id: u64,
pub me: Option<Me>,
pub listeners: Vec<Listener>,
pub scan_ports: Arc<AtomicBool>,
pub update: Option<String>,
pub updating: bool,
pub checked_update: bool,
pub managed: bool,
pub relaunch: bool,
pub start_hidden: bool,
pub hotkey: bool,
pub autostart: bool,
pub login: LoginForm,
pub new_tunnel: NewTunnelForm,
pub connect: ConnectForm,
pub toasts: Vec<Toast>,
pub has_tray: bool,
pub quitting: bool,
monitor: Option<egui::Rect>,
}
impl State {
pub fn new(runtime: Handle, repaint: Repaint, has_tray: bool) -> Self {
let (tx, rx) = mpsc::channel();
let cfg = Config::load().unwrap_or_default();
let login = LoginForm { server: cfg.server_url.clone().unwrap_or_default(), accept_invalid: cfg.accept_invalid_certs, key: String::new(), use_key: false, stage: LoginStage::Idle, stop: None };
let mut state = Self {
runtime, mailbox: Mailbox { tx, repaint }, rx, page: Page::Tunnels, cfg, server_info: None, tunnels: Vec::new(), joins: Vec::new(), next_id: 1,
login, new_tunnel: NewTunnelForm::default(), connect: ConnectForm::default(),
me: None, listeners: Vec::new(), scan_ports: Arc::new(AtomicBool::new(false)), update: None, updating: false, checked_update: false, managed: update::detect() == update::Install::Managed, relaunch: false, start_hidden: false, hotkey: false, autostart: super::autostart::enabled(), toasts: Vec::new(), has_tray, quitting: false, monitor: None,
};
state.fetch_info();
state.fetch_me();
let mailbox = state.mailbox.clone();
state.runtime.spawn(async move { mailbox.send(Msg::Update(update::check().await)); });
let (mailbox, scan) = (state.mailbox.clone(), state.scan_ports.clone());
state.runtime.spawn(async move {
loop {
if scan.load(Ordering::Relaxed) {
if let Ok(found) = tokio::task::spawn_blocking(ports::scan).await { mailbox.send(Msg::Listeners(found)); }
}
tokio::time::sleep(SCAN_INTERVAL).await;
}
});
state
}
pub fn expose(&mut self, listener: &Listener) {
let target = Target { host: "127.0.0.1".into(), port: listener.port, tls: false };
if listener.is_tcp() {
self.start_tunnel(TunnelKind::Tcp, Options::tcp(target, None, tunnel::Access::default()));
} else {
self.start_tunnel(TunnelKind::Http, Options::http(tunnel::TargetSpec::Addr(target), None, false, tunnel::Access::default()));
}
}
pub fn suggestions(&self) -> Vec<Listener> {
self.listeners.iter().filter(|listener| !self.tunnels.iter().any(|card| card.target_label.ends_with(&format!(":{}", listener.port)))).cloned().collect()
}
pub fn start_update(&mut self) {
let Some(version) = self.update.clone() else { return };
self.updating = true;
let mailbox = self.mailbox.clone();
self.runtime.spawn(async move {
let result = update::apply(&version, &update::detect(), true).await.map_err(|err| format!("{err:#}"));
mailbox.send(Msg::Updated(result));
});
}
pub fn linked(&self) -> bool { self.cfg.device_token.is_some() && self.cfg.server_url().is_some() }
pub fn server_url(&self) -> String { self.cfg.server_url().unwrap_or_default() }
pub fn corner_position(&self) -> Option<egui::Pos2> { self.monitor.map(super::corner_for) }
fn next_id(&mut self) -> u64 { let id = self.next_id; self.next_id += 1; id }
fn forward<E: Send + 'static>(&self, mut rx: UnboundedReceiver<E>, wrap: impl Fn(E) -> Msg + Send + 'static) {
let mailbox = self.mailbox.clone();
self.runtime.spawn(async move {
while let Some(event) = rx.recv().await { mailbox.send(wrap(event)); }
});
}
pub fn toast(&mut self, text: impl Into<String>) { self.toasts.push(Toast { text: text.into(), at: Instant::now(), error: false, action: None }); }
pub fn toast_error(&mut self, text: impl Into<String>) { self.toasts.push(Toast { text: text.into(), at: Instant::now(), error: true, action: None }); }
pub fn fetch_me(&mut self) {
let (Some(url), Some(token)) = (self.cfg.server_url(), self.cfg.device_token.clone()) else { self.me = None; return };
let accept = self.cfg.accept_invalid_certs;
let mailbox = self.mailbox.clone();
self.runtime.spawn(async move {
let me = async { ApiClient::new(&url, Some(&token), accept)?.whoami().await }.await.ok();
mailbox.send(Msg::Me(me));
});
}
pub fn reload_config(&mut self) {
self.cfg = Config::load().unwrap_or_default();
self.fetch_me();
}
pub fn stop_all(&self) {
for card in &self.tunnels { card.stop.stop(); }
for join in &self.joins { join.stop.stop(); }
if let Some(stop) = &self.login.stop { stop.stop(); }
}
pub fn open_link(&mut self, link: String) {
if let Some(invite) = auth::parse_invite(&link) {
self.page = Page::Tunnels;
let accept = self.cfg.accept_invalid_certs;
let mailbox = self.mailbox.clone();
self.runtime.spawn(async move {
let result = linked(auth::accept_invite(invite, accept).await);
mailbox.send(Msg::Linked(result));
});
return;
}
self.page = Page::Connect;
self.start_join(link, None, "127.0.0.1".into());
}
pub fn fetch_info(&mut self) {
let Some(url) = self.cfg.server_url() else { self.server_info = None; return };
let accept = self.cfg.accept_invalid_certs;
let mailbox = self.mailbox.clone();
self.runtime.spawn(async move {
let result = async { ApiClient::new(&url, None, accept)?.info().await }.await.map_err(|err| format!("{err:#}"));
mailbox.send(Msg::Info(result));
});
}
pub fn link_with_key(&mut self) {
let server = self.login.server.trim().to_string();
let key = self.login.key.trim().to_string();
if server.is_empty() || key.is_empty() { self.login.stage = LoginStage::Failed("Enter the server URL and the API key".into()); return; }
self.login.stage = LoginStage::Starting;
let accept = self.login.accept_invalid;
let mailbox = self.mailbox.clone();
self.runtime.spawn(async move {
let result = linked(auth::link_token(server, key, accept).await);
mailbox.send(Msg::Linked(result));
});
}
pub fn start_login(&mut self) {
let server = self.login.server.trim().to_string();
if server.is_empty() { self.login.stage = LoginStage::Failed("Enter the URL of your frislit server".into()); return; }
let (events, rx) = session::channel();
let (handle, stop) = Stop::new();
self.login.stop = Some(handle);
self.login.stage = LoginStage::Starting;
let accept = self.login.accept_invalid;
self.forward(rx, Msg::Login);
let mailbox = self.mailbox.clone();
self.runtime.spawn(async move {
if let Err(err) = auth::link(&server, accept, events, stop).await {
mailbox.send(Msg::LoginFailed(format!("{err:#}")));
}
});
}
pub fn cancel_login(&mut self) {
if let Some(stop) = self.login.stop.take() { stop.stop(); }
self.login.stage = LoginStage::Idle;
}
pub fn pick_folder(&mut self) {
if self.new_tunnel.picking_dir { return; }
self.new_tunnel.picking_dir = true;
let start = Some(self.new_tunnel.dir.trim().to_string()).filter(|dir| !dir.is_empty()).map(PathBuf::from);
let mailbox = self.mailbox.clone();
self.runtime.spawn(async move {
let mut dialog = rfd::AsyncFileDialog::new().set_title("Folder to share");
if let Some(start) = start { dialog = dialog.set_directory(start); }
let picked = dialog.pick_folder().await.map(|handle| handle.path().to_path_buf());
mailbox.send(Msg::FolderPicked(picked));
});
}
pub fn start_tunnel(&mut self, kind: TunnelKind, opts: Options) {
let id = self.next_id();
let target_label = opts.target.label();
let (events, rx) = session::channel();
let (handle, stop) = Stop::new();
self.tunnels.push(TunnelCard {
id, kind, opts: opts.clone(), target_label, access: None, probe: None, state: TunnelState::Connecting, online: None,
requests: VecDeque::new(), connections: VecDeque::new(), request_count: 0, started: Instant::now(), stop: handle, show_qr: false, copied_at: None,
});
self.forward(rx, move |event| Msg::Tunnel(id, event));
let mailbox = self.mailbox.clone();
self.runtime.spawn(async move {
let result = async {
let (opts, target, label, _local) = tunnel::prepare(opts).await?;
mailbox.send(Msg::TunnelReady(id, label));
let _probe = (kind != TunnelKind::Files).then(|| Task(tokio::spawn(probe(mailbox.clone(), id, target.clone()))));
tunnel::run(opts, target, events, stop).await
}.await;
if let Err(err) = result { mailbox.send(Msg::TunnelFailed(id, format!("{err:#}"))); }
});
self.page = Page::Tunnel(id);
}
pub fn start_join(&mut self, target: String, port: Option<u16>, bind: String) {
let (code, server) = match connect::resolve(&target, None) {
Ok((code, _, server)) => (code, server),
Err(err) => { self.connect.error = Some(format!("{err:#}")); self.connect.link = target; return; }
};
self.connect = ConnectForm::default();
if self.joins.iter().any(|join| join.code == code) {
self.toast("That share is already connected");
return;
}
let id = self.next_id();
let (events, rx) = session::channel();
let (handle, stop) = Stop::new();
self.joins.insert(0, JoinCard {
id, target: target.clone(), code, server,
state: JoinState::Connecting, forwarding: None, started: Instant::now(), stop: handle,
});
let opts = connect::Options { target, port, bind, server: None, pick_port: None };
self.forward(rx, move |event| Msg::Join(id, event));
let mailbox = self.mailbox.clone();
self.runtime.spawn(async move {
if let Err(err) = connect::run(opts, events, stop).await {
let port_in_use = err.downcast_ref::<connect::PortInUse>().map(|taken| taken.port);
mailbox.send(Msg::JoinFailed(id, format!("{err:#}"), port_in_use));
}
});
}
fn fail_join(&mut self, id: u64, message: String, port_in_use: Option<u16>) {
let Some(index) = self.joins.iter().position(|join| join.id == id) else { return };
let join = self.joins.remove(index);
if let Some(port) = port_in_use {
self.connect.link = join.target;
self.connect.retry_port = Some(port.saturating_add(1).to_string());
self.connect.error = Some(message);
} else {
self.toast_error(message);
}
}
pub fn stop_tunnel(&mut self, id: u64) {
if let Some(index) = self.tunnels.iter().position(|card| card.id == id) {
self.tunnels.remove(index).stop.stop();
}
if self.page == Page::Tunnel(id) { self.page = Page::Tunnels; }
}
pub fn stop_tunnel_by_user(&mut self, id: u64) {
let Some(card) = self.tunnels.iter().find(|card| card.id == id) else { return };
let (kind, opts, name) = (card.kind, card.opts.clone(), card.title());
self.stop_tunnel(id);
self.toasts.push(Toast { text: format!("{name} stopped"), at: Instant::now(), error: false, action: Some(ToastAction::Reopen(kind, opts)) });
}
pub fn stop_join(&mut self, id: u64) {
if let Some(index) = self.joins.iter().position(|join| join.id == id) {
self.joins.remove(index).stop.stop();
}
}
pub fn tunnel_mut(&mut self, id: u64) -> Option<&mut TunnelCard> { self.tunnels.iter_mut().find(|card| card.id == id) }
pub fn drain(&mut self, ctx: &egui::Context) {
while let Ok(msg) = self.rx.try_recv() { self.handle(ctx, msg); }
}
fn handle(&mut self, ctx: &egui::Context, msg: Msg) {
match msg {
Msg::TunnelReady(id, label) => { if let Some(card) = self.tunnel_mut(id) { card.target_label = label; } }
Msg::Tunnel(id, event) => self.handle_tunnel(id, event),
Msg::TunnelFailed(id, message) => {
let fresh = self.tunnel_mut(id).is_some_and(|card| card.online.is_none());
self.stop_tunnel(id);
if fresh { self.new_tunnel.error = Some(message); self.page = Page::NewTunnel; } else { self.toast_error(message); }
}
Msg::Me(me) => self.me = me,
Msg::Linked(Ok(message)) => { self.login.stage = LoginStage::Idle; self.login.key.clear(); self.reload_config(); self.fetch_info(); self.toast(message); }
Msg::Linked(Err(message)) => { self.login.stage = LoginStage::Failed(message); }
Msg::Update(version) => { self.update = version; self.checked_update = true; }
Msg::Updated(Ok(_)) => { self.relaunch = true; self.quitting = true; ctx.send_viewport_cmd(egui::ViewportCommand::Close); }
Msg::Updated(Err(message)) => { self.updating = false; self.toast_error(message); }
Msg::TunnelProbe(id, warning) => { if let Some(card) = self.tunnel_mut(id) { card.probe = warning; } }
Msg::Listeners(found) => self.listeners = found,
Msg::Join(id, event) => self.handle_join(id, event),
Msg::JoinFailed(id, message, port_in_use) => self.fail_join(id, message, port_in_use),
Msg::Login(LoginEvent::Code { code, handoff_url }) => {
ctx.open_url(egui::OpenUrl::new_tab(&handoff_url));
self.login.stage = LoginStage::Waiting { code, url: handoff_url };
}
Msg::Login(LoginEvent::Linked { server_url, info }) => {
self.login.stage = LoginStage::Idle;
self.login.stop = None;
self.reload_config();
self.server_info = Some(Ok(info));
self.toast(format!("This device is linked to {}", format::host_of(&server_url)));
}
Msg::LoginFailed(message) => { self.login.stage = LoginStage::Failed(message); self.login.stop = None; }
Msg::Info(result) => self.server_info = Some(result),
Msg::FolderPicked(path) => {
self.new_tunnel.picking_dir = false;
if let Some(path) = path { self.new_tunnel.dir = path.display().to_string(); }
}
}
}
fn handle_tunnel(&mut self, id: u64, event: TunnelEvent) {
let server_url = self.server_url();
let Some(card) = self.tunnel_mut(id) else { return };
let mut toast = None;
match event {
TunnelEvent::Connecting => card.state = TunnelState::Connecting,
TunnelEvent::Online(online) | TunnelEvent::Resumed(online) | TunnelEvent::Replaced(online) => {
let fresh = card.online.as_ref().is_none_or(|current| current.id != online.id);
card.state = TunnelState::Online;
card.access = online.access.clone();
if fresh {
let copied = online.link(&server_url).is_some_and(|link| qr::copy(&link));
toast = Some(if copied { format!("{} is online, link copied", online.id) } else { format!("{} is online", online.id) });
}
card.online = Some(online);
}
TunnelEvent::Connection(connection) => {
if connection.opened {
card.connections.push_front(connection);
card.connections.truncate(MAX_REQUESTS);
} else if let Some(existing) = card.connections.iter_mut().find(|entry| entry.key == connection.key) {
*existing = connection;
}
}
TunnelEvent::Access(summary) => card.access = Some(summary),
TunnelEvent::Request(request) => {
card.request_count += 1;
if card.requests.len() == MAX_REQUESTS { card.requests.pop_back(); }
card.requests.push_front(LoggedRequest { request, at: Instant::now() });
}
TunnelEvent::Reconnecting { seconds, reason } => card.state = TunnelState::Reconnecting { seconds, reason },
TunnelEvent::Update(version) => self.update = Some(version),
TunnelEvent::Stopped => self.stop_tunnel(id),
TunnelEvent::Ended(reason) => { self.stop_tunnel(id); toast = Some(format!("Tunnel ended: {reason}")); }
}
if let Some(text) = toast { self.toast(text); }
}
fn handle_join(&mut self, id: u64, event: JoinEvent) {
let Some(join) = self.joins.iter_mut().find(|join| join.id == id) else { return };
match event {
JoinEvent::Connecting => join.state = JoinState::Connecting,
JoinEvent::Forwarding { port, tunnel_id, owner_online, .. } => {
join.state = JoinState::Forwarding;
join.forwarding = Some(Forwarding { port, tunnel_id, owner_online });
}
JoinEvent::Reconnecting { seconds, reason } => join.state = JoinState::Reconnecting { seconds, reason },
JoinEvent::Reconnected => join.state = JoinState::Forwarding,
JoinEvent::Stopped => self.stop_join(id),
JoinEvent::Ended(reason) => { self.stop_join(id); self.toast(format!("Disconnected: {reason}")); }
}
}
}
pub struct Window<'a> {
pub state: &'a mut State,
wake: &'a Receiver<Wake>,
pub logo: TextureHandle,
qr: HashMap<u64, (String, TextureHandle)>,
visible: bool,
focused: bool,
was_focused: bool,
needs_show: bool,
place_frames: u8,
}
impl<'a> Window<'a> {
pub fn new(cc: &eframe::CreationContext<'_>, state: &'a mut State, wake: &'a Receiver<Wake>) -> Self {
let logo = cc.egui_ctx.load_texture("logo",
egui::ColorImage::from_rgba_unmultiplied([super::ICON_SIZE as usize; 2], super::ICON_RGBA), TextureOptions::LINEAR);
let start_hidden = std::mem::take(&mut state.start_hidden);
let needs_show = !start_hidden && state.corner_position().is_none() && !hide_by_closing();
Self { state, wake, logo, qr: HashMap::new(), visible: !start_hidden && !needs_show, focused: false, was_focused: false, needs_show, place_frames: 3 }
}
pub fn qr_for(&mut self, ctx: &egui::Context, card_id: u64, link: &str) -> Option<TextureHandle> {
if let Some((known, texture)) = self.qr.get(&card_id) {
if known == link { return Some(texture.clone()); }
}
let texture = qr_texture(ctx, &format!("qr-{card_id}"), link)?;
self.qr.insert(card_id, (link.to_string(), texture.clone()));
Some(texture)
}
fn place(&mut self, ctx: &egui::Context) {
let area = super::work_area(ctx.pixels_per_point())
.or_else(|| ctx.input(|input| input.viewport().monitor_size).map(|monitor| {
egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(monitor.x, monitor.y - 48.0))
}));
let Some(area) = area else { return };
if area.width() <= super::WINDOW_WIDTH || area.height() <= super::WINDOW_HEIGHT { return; }
self.state.monitor = Some(area);
ctx.send_viewport_cmd(egui::ViewportCommand::OuterPosition(super::corner_for(area)));
}
fn show(&mut self, ctx: &egui::Context) {
ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(false));
ctx.send_viewport_cmd(egui::ViewportCommand::Visible(true));
ctx.send_viewport_cmd(egui::ViewportCommand::Focus);
self.visible = true;
self.place_frames = 3;
ctx.request_repaint();
}
pub fn minimize(&mut self, ctx: &egui::Context) {
if !self.state.has_tray {
ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(true));
} else if hide_by_closing() {
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
} else {
ctx.send_viewport_cmd(egui::ViewportCommand::Visible(false));
self.visible = false;
}
}
pub fn quit(&mut self, ctx: &egui::Context) {
self.state.quitting = true;
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
}
fn wake_events(&mut self, ctx: &egui::Context) {
while let Ok(wake) = self.wake.try_recv() {
match wake {
Wake::Toggle => if self.visible && self.focused { self.minimize(ctx) } else { self.show(ctx) },
Wake::Show => self.show(ctx),
Wake::OpenLink(link) => { if let Some(link) = link { self.state.open_link(link); } self.show(ctx); }
Wake::Quit => self.quit(ctx),
}
}
}
fn nav(&mut self, root: &mut Ui) {
let ctx = root.ctx().clone();
let frame = Frame::new().fill(theme::BACKGROUND).inner_margin(Margin::symmetric(theme::GUTTER as i8, 0));
egui::Panel::top("nav").frame(frame).exact_size(52.0).resizable(false).show_separator_line(false).show(root, |ui| {
ui.with_layout(Layout::left_to_right(Align::Center), |ui| {
ui.spacing_mut().item_spacing.x = 6.0;
ui.image((self.logo.id(), egui::vec2(22.0, 22.0)));
widgets::text_family(ui, "frislit", 15.0, theme::TEXT, theme::bold());
ui.add_space(6.0);
for (page, label) in [(Page::Tunnels, "Tunnels"), (Page::Connect, "Connect"), (Page::Settings, "Settings")] {
let active = match (self.state.page, page) {
(Page::Tunnels | Page::NewTunnel | Page::Tunnel(_), Page::Tunnels) => true,
(current, target) => current == target,
};
if nav_link(ui, label, active).clicked() { self.state.page = page; }
}
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
if widgets::minimize_button(ui).clicked() { self.minimize(&ctx); }
});
});
let rect = ui.max_rect();
let y = rect.bottom() + 0.5;
ui.painter().line_segment([egui::pos2(rect.left() - theme::GUTTER, y), egui::pos2(rect.right() + theme::GUTTER, y)], Stroke::new(1.0, theme::BORDER));
});
}
fn toasts(&mut self, ctx: &egui::Context) {
self.state.toasts.retain(|toast| !toast.expired());
if self.state.toasts.is_empty() { return; }
ctx.request_repaint_after(Duration::from_millis(250));
let mut acted = None;
egui::Area::new(egui::Id::new("toasts")).anchor(egui::Align2::CENTER_BOTTOM, egui::vec2(0.0, -16.0)).order(egui::Order::Foreground).show(ctx, |ui| {
ui.set_max_width(super::WINDOW_WIDTH - 32.0);
ui.vertical(|ui| {
for (index, toast) in self.state.toasts.iter().enumerate() {
let (color, dot) = if toast.error { (theme::ERROR, theme::ERROR) } else { (theme::TEXT, theme::SUCCESS) };
Frame::new().fill(theme::SURFACE_RAISED).stroke(Stroke::new(1.0, theme::BORDER_STRONG))
.corner_radius(theme::corner(theme::RADIUS_INPUT)).inner_margin(Margin::symmetric(14, 10))
.shadow(egui::epaint::Shadow { offset: [0, 6], blur: 24, spread: 0, color: Color32::from_black_alpha(140) })
.show(ui, |ui| {
ui.horizontal(|ui| {
widgets::dot(ui, dot);
ui.add(egui::Label::new(RichText::new(&toast.text).size(13.0).color(color)).wrap());
if toast.action.is_some() && widgets::button(ui, "Reopen", widgets::ButtonKind::Ghost).clicked() { acted = Some(index); }
});
});
}
});
});
if let Some(ToastAction::Reopen(kind, opts)) = acted.and_then(|index| self.state.toasts.remove(index).action) { self.state.start_tunnel(kind, opts); }
}
pub fn content(ui: &mut Ui, add: impl FnOnce(&mut Ui)) {
let total = ui.available_width();
let width = total - theme::GUTTER * 2.0;
let outer = ui.available_rect_before_wrap();
let rect = egui::Rect::from_min_size(egui::pos2(outer.left() + theme::GUTTER, outer.top() + 20.0), egui::vec2(width, f32::INFINITY));
let mut child = ui.new_child(UiBuilder::new().max_rect(rect).layout(Layout::top_down(Align::Min)));
child.set_width(width);
add(&mut child);
ui.allocate_space(egui::vec2(total, child.min_rect().height() + 20.0 + 40.0));
}
}
fn nav_link(ui: &mut Ui, label: &str, active: bool) -> egui::Response {
let galley = ui.painter().layout_no_wrap(label.to_string(), theme::font(13.0, theme::medium()), Color32::WHITE);
let size = galley.size() + egui::vec2(18.0, 10.0);
let (rect, response) = ui.allocate_exact_size(size, Sense::click());
let fill = if active { theme::SURFACE_HOVER } else { Color32::TRANSPARENT };
let color = if active || response.hovered() { theme::TEXT } else { theme::MUTED };
ui.painter().rect_filled(rect, theme::corner(theme::RADIUS_SMALL), fill);
ui.painter().galley(rect.center() - galley.size() / 2.0, galley, color);
if response.hovered() { ui.ctx().set_cursor_icon(CursorIcon::PointingHand); }
response
}
pub fn qr_texture(ctx: &egui::Context, name: &str, text: &str) -> Option<TextureHandle> {
let code = qrcode::QrCode::new(text.as_bytes()).ok()?;
let width = code.width();
let quiet = 2;
let size = width + quiet * 2;
let colors = code.to_colors();
let mut rgba = vec![0u8; size * size * 4];
for y in 0..size {
for x in 0..size {
let inside = quiet..width + quiet;
let dark = inside.contains(&x) && inside.contains(&y) && colors[(y - quiet) * width + (x - quiet)] == qrcode::Color::Dark;
let color = if dark { theme::BACKGROUND } else { theme::TEXT };
let offset = (y * size + x) * 4;
rgba[offset..offset + 4].copy_from_slice(&[color.r(), color.g(), color.b(), 255]);
}
}
let image = egui::ColorImage::from_rgba_unmultiplied([size, size], &rgba);
Some(ctx.load_texture(name, image, TextureOptions::NEAREST))
}
impl eframe::App for Window<'_> {
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
self.was_focused = self.focused;
self.focused = ctx.input(|input| input.viewport().focused.unwrap_or(false));
self.wake_events(ctx);
self.state.drain(ctx);
if !self.visible || !self.state.has_tray || self.place_frames > 0 { return; }
let lost_focus = self.was_focused && !self.focused && !self.state.new_tunnel.picking_dir;
let escaped = self.focused && ctx.memory(|memory| memory.focused().is_none()) && ctx.input(|input| input.key_pressed(egui::Key::Escape));
if lost_focus || escaped { self.minimize(ctx); }
}
fn ui(&mut self, root: &mut Ui, _frame: &mut eframe::Frame) {
let ctx = root.ctx().clone();
let closing = ctx.input(|input| input.viewport().close_requested());
if closing && !self.state.quitting && self.state.has_tray && !hide_by_closing() {
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
self.minimize(&ctx);
}
if self.needs_show { self.needs_show = false; self.show(&ctx); }
if self.place_frames > 0 {
self.place_frames -= 1;
self.place(&ctx);
ctx.request_repaint_after(Duration::from_millis(30));
}
self.state.scan_ports.store(self.visible && self.state.page == Page::Tunnels && self.state.linked(), Ordering::Relaxed);
let rect = ctx.content_rect();
ctx.layer_painter(egui::LayerId::background()).rect_stroke(rect, 0.0, Stroke::new(1.0, theme::BORDER_STRONG), egui::StrokeKind::Inside);
self.nav(root);
egui::CentralPanel::default().frame(Frame::new().fill(theme::BACKGROUND)).show(root, |ui| {
let scroll_id = match self.state.page { Page::Tunnels => 0u64, Page::NewTunnel => 1, Page::Tunnel(id) => 100 + id, Page::Connect => 2, Page::Settings => 3 };
egui::ScrollArea::vertical().id_salt(("page", scroll_id)).auto_shrink([false, false]).show(ui, |ui| {
match self.state.page {
Page::Tunnels => self.tunnels_page(ui),
Page::NewTunnel => self.new_tunnel_page(ui),
Page::Tunnel(id) => self.tunnel_page(ui, id),
Page::Connect => self.connect_page(ui),
Page::Settings => self.settings_page(ui),
}
});
});
self.toasts(&ctx);
}
}
fn linked(result: anyhow::Result<(Me, ServerInfo)>) -> Result<String, String> {
result.map(|(me, info)| format!("Linked to {} as {}", info.name, me.label())).map_err(|err| format!("{err:#}"))
}
async fn reachable(target: &Target) -> bool {
let Ok(addrs) = target.resolve().await else { return false };
tokio::time::timeout(PROBE_TIMEOUT, connect_target(&addrs)).await.is_ok_and(|result| result.is_ok())
}
async fn probe(mailbox: Mailbox, id: u64, target: Target) {
while !reachable(&target).await {
mailbox.send(Msg::TunnelProbe(id, Some(format!("Nothing is listening on {} yet", target.authority()))));
tokio::time::sleep(PROBE_INTERVAL).await;
}
mailbox.send(Msg::TunnelProbe(id, None));
}
pub fn state_label(state: &TunnelState) -> &'static str {
match state {
TunnelState::Connecting => "Connecting",
TunnelState::Online => "Online",
TunnelState::Reconnecting { .. } => "Reconnecting",
}
}
pub fn state_dot(state: &TunnelState) -> Color32 {
match state {
TunnelState::Connecting => theme::MUTED,
TunnelState::Online => theme::SUCCESS,
TunnelState::Reconnecting { .. } => theme::WARNING,
}
}
+53
View File
@@ -0,0 +1,53 @@
use anyhow::Result;
#[cfg(unix)]
fn entry() -> Result<std::path::PathBuf> {
use anyhow::Context;
#[cfg(target_os = "linux")]
let path = dirs::config_dir().context("No config directory")?.join("autostart/frislit.desktop");
#[cfg(target_os = "macos")]
let path = dirs::home_dir().context("No home directory")?.join("Library/LaunchAgents/dev.frislit.gui.plist");
Ok(path)
}
#[cfg(unix)]
pub fn enabled() -> bool {
entry().is_ok_and(|path| path.exists())
}
#[cfg(unix)]
pub fn set(on: bool) -> Result<()> {
let path = entry()?;
if !on { let _ = std::fs::remove_file(&path); return Ok(()); }
std::fs::create_dir_all(path.parent().unwrap())?;
let exe = std::env::current_exe()?;
#[cfg(target_os = "linux")]
let body = format!("[Desktop Entry]\nType=Application\nName=frislit\nExec={} gui --hidden\nX-GNOME-Autostart-enabled=true\n", exe.display());
#[cfg(target_os = "macos")]
let body = format!(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\"><dict>\n<key>Label</key><string>dev.frislit.gui</string>\n<key>ProgramArguments</key><array><string>{}</string><string>gui</string><string>--hidden</string></array>\n<key>RunAtLoad</key><true/>\n</dict></plist>\n",
exe.display());
std::fs::write(&path, body)?;
Ok(())
}
#[cfg(windows)]
const RUN_KEY: &str = r"HKCU\Software\Microsoft\Windows\CurrentVersion\Run";
#[cfg(windows)]
fn reg(args: &[&str]) -> Result<bool> {
Ok(std::process::Command::new("reg").args(args).output()?.status.success())
}
#[cfg(windows)]
pub fn enabled() -> bool {
reg(&["query", RUN_KEY, "/v", "frislit"]).unwrap_or(false)
}
#[cfg(windows)]
pub fn set(on: bool) -> Result<()> {
let command = format!("\"{}\" gui --hidden", std::env::current_exe()?.display());
let done = if on { reg(&["add", RUN_KEY, "/v", "frislit", "/t", "REG_SZ", "/d", &command, "/f"])? } else { reg(&["delete", RUN_KEY, "/v", "frislit", "/f"])? };
anyhow::ensure!(done, "Could not update the autostart entry");
Ok(())
}
+15
View File
@@ -0,0 +1,15 @@
use std::time::Instant;
pub fn ago(since: Instant) -> String {
let secs = since.elapsed().as_secs();
if secs < 5 { "just now".into() }
else if secs < 60 { format!("{secs}s ago") }
else if secs < 3600 { format!("{}m ago", secs / 60) }
else if secs < 86_400 { format!("{}h ago", secs / 3600) }
else { format!("{}d ago", secs / 86_400) }
}
pub fn host_of(url: &str) -> String {
let rest = url.split("://").nth(1).unwrap_or(url);
rest.split('/').next().unwrap_or(rest).to_string()
}
+64
View File
@@ -0,0 +1,64 @@
use anyhow::{Context, Result};
use std::io::{BufRead, BufReader, Write};
use std::net::TcpStream;
use std::path::PathBuf;
use std::time::Duration;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader as AsyncBufReader};
use tokio::net::TcpListener;
use tokio::runtime::Handle;
const TIMEOUT: Duration = Duration::from_millis(800);
fn lock_file() -> Result<PathBuf> {
let dir = dirs::config_dir().context("No config directory")?.join("frislit");
std::fs::create_dir_all(&dir)?;
Ok(dir.join("gui.instance"))
}
pub fn hand_over(link: Option<&str>) -> bool {
let Ok(path) = lock_file() else { return false };
let Ok(contents) = std::fs::read_to_string(&path) else { return false };
let mut lines = contents.lines();
let (Some(port), Some(secret)) = (lines.next().and_then(|p| p.parse::<u16>().ok()), lines.next()) else { return false };
let addr = std::net::SocketAddr::from(([127, 0, 0, 1], port));
let Ok(mut stream) = TcpStream::connect_timeout(&addr, TIMEOUT) else { return false };
let _ = stream.set_read_timeout(Some(TIMEOUT));
if writeln!(stream, "{secret} {}", link.unwrap_or("")).is_err() { return false; }
let mut reply = String::new();
BufReader::new(stream).read_line(&mut reply).is_ok() && reply.trim() == "ok"
}
pub fn serve(runtime: &Handle, on_link: impl Fn(Option<String>) + Send + Sync + 'static) -> Result<()> {
let listener = runtime.block_on(TcpListener::bind("127.0.0.1:0"))?;
let port = listener.local_addr()?.port();
let secret: String = (0..32).map(|_| { let n = rand_byte() % 36; (if n < 10 { b'0' + n } else { b'a' + n - 10 }) as char }).collect();
let path = lock_file()?;
std::fs::write(&path, format!("{port}\n{secret}\n"))?;
#[cfg(unix)]
{ use std::os::unix::fs::PermissionsExt; let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)); }
runtime.spawn(async move {
loop {
let Ok((stream, _)) = listener.accept().await else { continue };
let mut reader = AsyncBufReader::new(stream);
let mut line = String::new();
let Ok(Ok(_)) = tokio::time::timeout(TIMEOUT, reader.read_line(&mut line)).await else { continue };
let Some((given, link)) = line.trim_end().split_once(' ') else { continue };
if given != secret { continue; }
let link = link.trim().to_string();
on_link(if link.is_empty() { None } else { Some(link) });
let _ = reader.get_mut().write_all(b"ok\n").await;
}
});
Ok(())
}
pub fn release() {
if let Ok(path) = lock_file() { let _ = std::fs::remove_file(path); }
}
fn rand_byte() -> u8 {
use std::collections::hash_map::RandomState;
use std::hash::{BuildHasher, Hasher};
(RandomState::new().build_hasher().finish() >> 24) as u8
}
+43
View File
@@ -0,0 +1,43 @@
use eframe::egui;
use x11rb::connection::Connection;
use x11rb::protocol::randr;
use x11rb::protocol::xproto::{AtomEnum, ConnectionExt};
#[derive(PartialEq)]
pub enum Backend { X11, Wayland }
pub fn choose_backend() -> Backend {
let has_x11 = std::env::var_os("DISPLAY").is_some_and(|value| !value.is_empty());
let has_wayland = std::env::var_os("WAYLAND_DISPLAY").is_some_and(|value| !value.is_empty());
if has_x11 {
if has_wayland { std::env::remove_var("WAYLAND_DISPLAY"); }
Backend::X11
} else {
Backend::Wayland
}
}
pub fn primary_work_area(pixels_per_point: f32) -> Option<egui::Rect> {
let (connection, screen_number) = x11rb::connect(None).ok()?;
let root = connection.setup().roots.get(screen_number)?.root;
let monitors = randr::get_monitors(&connection, root, true).ok()?.reply().ok()?.monitors;
let monitor = monitors.iter().find(|monitor| monitor.primary).or_else(|| monitors.first())?;
let mut area = egui::Rect::from_min_size(
egui::pos2(monitor.x as f32, monitor.y as f32),
egui::vec2(monitor.width as f32, monitor.height as f32),
);
let atom = connection.intern_atom(false, b"_NET_WORKAREA").ok()?.reply().ok()?.atom;
let reply = connection.get_property(false, root, atom, AtomEnum::CARDINAL, 0, 4).ok()?.reply().ok()?;
if let Some(mut values) = reply.value32() {
if let (Some(x), Some(y), Some(width), Some(height)) = (values.next(), values.next(), values.next(), values.next()) {
let work = egui::Rect::from_min_size(egui::pos2(x as f32, y as f32), egui::vec2(width as f32, height as f32));
area = area.intersect(work);
}
}
if area.width() <= 0.0 || area.height() <= 0.0 { return None; }
let scale = 1.0 / pixels_per_point;
Some(egui::Rect::from_min_max(egui::pos2(area.left() * scale, area.top() * scale), egui::pos2(area.right() * scale, area.bottom() * scale)))
}
+157
View File
@@ -0,0 +1,157 @@
mod app;
mod autostart;
mod format;
mod instance;
#[cfg(target_os = "linux")]
mod linux;
mod pages;
mod ports;
mod theme;
mod tray;
mod widgets;
use anyhow::{Context, Result};
use eframe::egui;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{mpsc, Arc, Mutex};
use tokio::runtime::Handle;
const ICON_SIZE: u32 = 128;
const ICON_RGBA: &[u8] = include_bytes!("../../assets/icon-128.rgba");
pub const WINDOW_WIDTH: f32 = 396.0;
pub const WINDOW_HEIGHT: f32 = 704.0;
const CORNER_MARGIN: f32 = 12.0;
static WAYLAND: AtomicBool = AtomicBool::new(false);
pub fn hide_by_closing() -> bool { WAYLAND.load(Ordering::Relaxed) }
pub const HOTKEY_LABEL: &str = "Super+Shift+T";
pub enum Wake { Toggle, Show, OpenLink(Option<String>), Quit }
#[derive(Clone, Default)]
pub struct Repaint(Arc<Mutex<Option<egui::Context>>>);
impl Repaint {
pub fn attach(&self, ctx: &egui::Context) { *self.0.lock().unwrap() = Some(ctx.clone()); }
pub fn detach(&self) { *self.0.lock().unwrap() = None; }
pub fn ping(&self) { if let Some(ctx) = self.0.lock().unwrap().as_ref() { ctx.request_repaint(); } }
}
pub fn launch(runtime: Handle, link: Option<String>, hidden: bool) -> Result<()> {
detach_console();
if instance::hand_over(link.as_deref()) { return Ok(()); }
#[cfg(target_os = "linux")]
WAYLAND.store(linux::choose_backend() == linux::Backend::Wayland, Ordering::Relaxed);
let (wake_tx, wake_rx) = mpsc::channel::<Wake>();
let repaint = Repaint::default();
let tray = tray::start(wake_tx.clone(), repaint.clone(), &runtime).ok();
{
let (wake_tx, repaint) = (wake_tx.clone(), repaint.clone());
instance::serve(&runtime, move |link| { let _ = wake_tx.send(Wake::OpenLink(link)); repaint.ping(); })
.context("Could not listen for links from the browser")?;
}
let hotkey = hotkey(wake_tx.clone(), repaint.clone());
let mut state = app::State::new(runtime, repaint.clone(), tray.is_some());
state.start_hidden = hidden && tray.is_some();
state.hotkey = hotkey.is_some();
if let Some(link) = link { state.open_link(link); }
let mut open = !(state.start_hidden && hide_by_closing());
let result = loop {
if open {
if let Err(err) = run_window(&mut state, &wake_rx, &repaint) { break Err(err); }
if state.quitting { break Ok(()); }
}
open = true;
match wake_rx.recv() {
Ok(Wake::Toggle | Wake::Show) => {}
Ok(Wake::OpenLink(link)) => { if let Some(link) = link { state.open_link(link); } }
Ok(Wake::Quit) | Err(_) => break Ok(()),
}
};
state.stop_all();
instance::release();
if state.relaunch { let _ = std::process::Command::new(std::env::current_exe()?).arg("gui").spawn(); }
result
}
fn run_window(state: &mut app::State, wake_rx: &mpsc::Receiver<Wake>, repaint: &Repaint) -> Result<()> {
let icon = egui::IconData { rgba: ICON_RGBA.to_vec(), width: ICON_SIZE, height: ICON_SIZE };
let viewport = egui::ViewportBuilder::default()
.with_title("frislit")
.with_app_id("dev.frislit.cli")
.with_inner_size([WINDOW_WIDTH, WINDOW_HEIGHT])
.with_min_inner_size([WINDOW_WIDTH, WINDOW_HEIGHT])
.with_max_inner_size([WINDOW_WIDTH, WINDOW_HEIGHT])
.with_resizable(false)
.with_decorations(false)
.with_taskbar(false)
.with_icon(Arc::new(icon));
let viewport = match state.corner_position() {
Some(position) => viewport.with_position(position),
None => viewport.with_visible(hide_by_closing()),
};
let viewport = if state.start_hidden { viewport.with_visible(false) } else { viewport };
let options = eframe::NativeOptions { viewport, ..Default::default() };
let outcome = eframe::run_native("frislit", options, Box::new(|cc| {
theme::install(&cc.egui_ctx);
repaint.attach(&cc.egui_ctx);
Ok(Box::new(app::Window::new(cc, state, wake_rx)))
}));
repaint.detach();
outcome.map_err(|err| anyhow::anyhow!("{err}")).context("Could not open the frislit window")
}
fn hotkey(wake: mpsc::Sender<Wake>, repaint: Repaint) -> Option<global_hotkey::GlobalHotKeyManager> {
use global_hotkey::{hotkey::{Code, HotKey, Modifiers}, GlobalHotKeyEvent, GlobalHotKeyManager, HotKeyState};
let manager = GlobalHotKeyManager::new().ok()?;
manager.register(HotKey::new(Some(Modifiers::SUPER | Modifiers::SHIFT), Code::KeyT)).ok()?;
GlobalHotKeyEvent::set_event_handler(Some(move |event: GlobalHotKeyEvent| {
if event.state == HotKeyState::Pressed { let _ = wake.send(Wake::Toggle); repaint.ping(); }
}));
Some(manager)
}
pub fn corner_for(area: egui::Rect) -> egui::Pos2 {
egui::pos2(area.right() - WINDOW_WIDTH - CORNER_MARGIN, area.bottom() - WINDOW_HEIGHT - CORNER_MARGIN)
}
#[cfg(windows)]
fn detach_console() {
use windows_sys::Win32::System::Console::{FreeConsole, GetConsoleProcessList};
let mut processes = [0u32; 2];
let count = unsafe { GetConsoleProcessList(processes.as_mut_ptr(), processes.len() as u32) };
if count <= 1 { unsafe { FreeConsole(); } }
}
#[cfg(not(windows))]
fn detach_console() {}
#[cfg(target_os = "linux")]
pub fn work_area(pixels_per_point: f32) -> Option<egui::Rect> {
if hide_by_closing() { return None; }
linux::primary_work_area(pixels_per_point)
}
#[cfg(windows)]
pub fn work_area(pixels_per_point: f32) -> Option<egui::Rect> {
use windows_sys::Win32::Foundation::RECT;
use windows_sys::Win32::UI::WindowsAndMessaging::{SystemParametersInfoW, SPI_GETWORKAREA};
let mut rect = RECT { left: 0, top: 0, right: 0, bottom: 0 };
let ok = unsafe { SystemParametersInfoW(SPI_GETWORKAREA, 0, &mut rect as *mut RECT as *mut _, 0) };
if ok == 0 { return None; }
let scale = 1.0 / pixels_per_point;
Some(egui::Rect::from_min_max(
egui::pos2(rect.left as f32 * scale, rect.top as f32 * scale),
egui::pos2(rect.right as f32 * scale, rect.bottom as f32 * scale),
))
}
#[cfg(not(any(windows, target_os = "linux")))]
pub fn work_area(_pixels_per_point: f32) -> Option<egui::Rect> { None }
+92
View File
@@ -0,0 +1,92 @@
use eframe::egui::{self, Align, Layout, Ui};
use crate::gui::app::{JoinState, Window};
use crate::gui::widgets::{self, ButtonKind, FieldOptions};
use crate::gui::{format, theme};
impl Window<'_> {
pub fn connect_page(&mut self, ui: &mut Ui) {
let logo = self.logo.id();
let state = &mut self.state;
Window::content(ui, |ui| {
let mut start = None;
ui.vertical_centered(|ui| {
ui.add_space(if state.joins.is_empty() { 96.0 } else { 24.0 });
ui.image((logo, egui::vec2(56.0, 56.0)));
ui.add_space(14.0);
widgets::text_family(ui, "Paste a share link.", 24.0, theme::TEXT, theme::semibold());
ui.add_space(20.0);
ui.with_layout(Layout::top_down(Align::Min), |ui| {
let form = &mut state.connect;
let mut submit = widgets::field(ui, "connect-link", &mut form.link, FieldOptions { hint: "https://frislit.example.com/@frislit/connect/…", mono: true, ..Default::default() }).lost_focus()
&& ui.input(|input| input.key_pressed(egui::Key::Enter));
ui.add_space(10.0);
if let Some(error) = &form.error { widgets::error_notice(ui, error); ui.add_space(10.0); }
if let Some(port) = &mut form.retry_port {
widgets::field(ui, "connect-port", port, FieldOptions { label: Some("Local port"), hint: "4000", mono: true, ..Default::default() });
ui.add_space(10.0);
}
if widgets::button_sized(ui, "Connect", ButtonKind::Primary, ui.available_width()).clicked() { submit = true; }
if submit {
let link = form.link.trim().to_string();
let port = form.retry_port.as_ref().map(|port| port.trim().parse::<u16>()).transpose();
if link.is_empty() {
form.error = Some("Paste a share link first".into());
} else if let Ok(port) = port {
start = Some((link, port));
} else {
form.error = Some("The local port must be a number between 1 and 65535".into());
}
}
});
});
if let Some((link, port)) = start { state.start_join(link, port, "127.0.0.1".into()); }
if state.joins.is_empty() { return; }
ui.add_space(36.0);
let mut stop = None;
ui.spacing_mut().item_spacing.y = 8.0;
for join in &state.joins {
widgets::card(ui, |ui| {
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 8.0;
match &join.state {
JoinState::Connecting => widgets::dot(ui, theme::MUTED),
JoinState::Forwarding => widgets::dot(ui, theme::SUCCESS),
JoinState::Reconnecting { .. } => widgets::dot(ui, theme::WARNING),
}
ui.scope(|ui| {
ui.set_max_width(ui.available_width() - 84.0);
if let Some(forwarding) = &join.forwarding {
widgets::mono(ui, format!("Port {}", forwarding.port), 14.0, theme::TEXT);
widgets::arrow_right(ui, theme::MUTED);
ui.add(egui::Label::new(egui::RichText::new(&forwarding.tunnel_id).size(13.0).color(theme::PRIMARY_BRIGHT).family(theme::mono())).truncate());
} else {
ui.add(egui::Label::new(egui::RichText::new(&join.target).size(12.5).color(theme::SUBTEXT).family(theme::mono())).truncate());
}
});
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
if widgets::button(ui, "Stop", ButtonKind::Danger).clicked() { stop = Some(join.id); }
});
});
ui.add_space(2.0);
widgets::text(ui, format!("{} · {}", format::host_of(&join.server), format::ago(join.started)), 12.0, theme::MUTED);
match &join.state {
JoinState::Reconnecting { seconds, reason } => {
ui.add_space(8.0);
let text = match reason { Some(reason) => format!("Connection lost, retrying in {seconds}s ({reason})"), None => "Connection lost, reconnecting...".to_string() };
widgets::warning_notice(ui, &text);
}
JoinState::Forwarding if join.forwarding.as_ref().is_some_and(|f| !f.owner_online) => {
ui.add_space(8.0);
widgets::warning_notice(ui, "The owner is offline right now.");
}
_ => {}
}
});
}
if let Some(id) = stop { state.stop_join(id); }
});
}
}
+155
View File
@@ -0,0 +1,155 @@
use eframe::egui::{self, Align, Layout, Ui};
use crate::gui::app::{state_dot, state_label, Page, TunnelKind, TunnelState, Window};
use crate::gui::widgets::{self, ButtonKind};
use crate::gui::{format, theme};
use crate::session::{bytes, took};
impl Window<'_> {
pub fn tunnel_page(&mut self, ui: &mut Ui, id: u64) {
let server_url = self.state.server_url();
let Some(index) = self.state.tunnels.iter().position(|card| card.id == id) else { self.state.page = Page::Tunnels; return };
let link = self.state.tunnels[index].link(&server_url);
let qr = match (&link, self.state.tunnels[index].show_qr) {
(Some(link), true) => self.qr_for(&ui.ctx().clone(), id, link),
_ => None,
};
let mut go_back = false;
let mut stop = false;
Window::content(ui, |ui| {
let card = &mut self.state.tunnels[index];
if widgets::back_link(ui, "Tunnels").clicked() { go_back = true; }
ui.add_space(12.0);
ui.add(egui::Label::new(egui::RichText::new(card.title()).size(20.0).color(theme::TEXT).family(theme::semibold())).truncate());
ui.add_space(6.0);
ui.horizontal_wrapped(|ui| {
ui.spacing_mut().item_spacing = egui::vec2(6.0, 4.0);
widgets::dot(ui, state_dot(&card.state));
widgets::text(ui, state_label(&card.state), 12.5, theme::SUBTEXT);
widgets::text(ui, "·", 12.5, theme::MUTED);
widgets::text(ui, card.kind.label(), 12.5, theme::SUBTEXT);
widgets::text(ui, "·", 12.5, theme::MUTED);
widgets::mono(ui, &card.target_label, 12.5, theme::SUBTEXT);
widgets::text(ui, "·", 12.5, theme::MUTED);
widgets::text(ui, format!("started {}", format::ago(card.started)), 12.5, theme::MUTED);
});
if let Some(access) = &card.access {
ui.add_space(4.0);
widgets::text(ui, format!("Access: {access}"), 12.5, theme::SUBTEXT);
}
if let Some(warning) = &card.probe {
ui.add_space(4.0);
widgets::text(ui, warning, 12.5, theme::WARNING);
}
ui.add_space(12.0);
ui.horizontal(|ui| {
if let Some(online) = &card.online {
if let Some(url) = &online.url {
if widgets::button(ui, "Open in browser", ButtonKind::Secondary).clicked() { ui.ctx().open_url(egui::OpenUrl::new_tab(url)); }
}
if widgets::button(ui, "Dashboard", ButtonKind::Secondary).clicked() {
ui.ctx().open_url(egui::OpenUrl::new_tab(format!("{server_url}/@frislit/tunnels/{}", online.id)));
}
}
if widgets::button(ui, "Stop", ButtonKind::Danger).clicked() { stop = true; }
});
ui.add_space(12.0);
if let TunnelState::Reconnecting { seconds, reason } = &card.state {
let text = match reason { Some(reason) => format!("Connection lost, retrying in {seconds}s ({reason})"), None => "Connection lost, reconnecting...".to_string() };
widgets::warning_notice(ui, &text);
ui.add_space(12.0);
}
if let Some(link) = &link {
let is_share = card.online.as_ref().is_some_and(|online| online.url.is_none());
let shown = if is_share { format!("frislit connect {link}") } else { link.clone() };
widgets::copy_row(ui, ("copy", card.id), &shown, &mut card.copied_at);
ui.add_space(8.0);
let label = if card.show_qr { "Hide QR code" } else { "Show QR code" };
if widgets::button(ui, label, ButtonKind::Ghost).clicked() { card.show_qr = !card.show_qr; }
if let Some(qr) = &qr {
ui.vertical_centered(|ui| {
egui::Frame::new().fill(theme::TEXT).corner_radius(theme::corner(theme::RADIUS_INPUT)).inner_margin(egui::Margin::same(8)).show(ui, |ui| {
ui.image((qr.id(), egui::vec2(176.0, 176.0)));
});
});
}
} else if card.state == TunnelState::Connecting {
ui.horizontal(|ui| { ui.spinner(); widgets::text(ui, "Connecting to the server...", 14.0, theme::SUBTEXT); });
}
ui.add_space(20.0);
if card.kind == TunnelKind::Tcp {
let open = card.connections.iter().filter(|connection| connection.opened).count();
widgets::section(ui, "Connections", Some(&format!("{open} open")));
widgets::card(ui, |ui| {
if card.connections.is_empty() {
widgets::text(ui, "No connections yet.", 13.0, theme::MUTED);
return;
}
ui.spacing_mut().item_spacing.y = 8.0;
for connection in card.connections.iter().take(100) {
ui.vertical(|ui| {
ui.spacing_mut().item_spacing.y = 2.0;
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 8.0;
widgets::dot(ui, if connection.opened { theme::SUCCESS } else { theme::MUTED });
widgets::mono(ui, &connection.protocol, 12.0, theme::TEXT);
widgets::mono(ui, &connection.ip, 12.0, theme::SUBTEXT);
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
let right = if connection.opened { connection.detail.clone().unwrap_or_default() } else { format!("{} in · {} out · {}", bytes(connection.bytes_in), bytes(connection.bytes_out), took(connection.duration)) };
widgets::mono(ui, right, 11.5, theme::MUTED);
});
});
let note = if connection.opened { connection.intel() } else { connection.reason.clone() };
if let Some(note) = note {
ui.horizontal(|ui| {
ui.add_space(16.0);
ui.add(egui::Label::new(egui::RichText::new(note).size(11.5).color(theme::MUTED)).truncate());
});
}
});
}
});
} else {
widgets::section(ui, "Requests", Some(&format!("{} so far", card.request_count)));
widgets::card(ui, |ui| {
if card.requests.is_empty() {
widgets::text(ui, "No requests yet.", 13.0, theme::MUTED);
return;
}
ui.spacing_mut().item_spacing.y = 8.0;
for logged in card.requests.iter().take(100) {
let request = &logged.request;
ui.vertical(|ui| {
ui.spacing_mut().item_spacing.y = 2.0;
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 8.0;
let method = if request.kind == "ws" { "WS".to_string() } else { request.method.clone() };
ui.allocate_ui_with_layout(egui::vec2(44.0, 18.0), Layout::left_to_right(Align::Center), |ui| { widgets::mono(ui, method, 12.0, theme::TEXT); });
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
ui.allocate_ui_with_layout(egui::vec2(48.0, 18.0), Layout::right_to_left(Align::Center), |ui| { widgets::mono(ui, format!("{}ms", request.duration), 11.5, theme::MUTED); });
widgets::mono(ui, request.status.to_string(), 12.0, widgets::status_color(request.status));
ui.with_layout(Layout::left_to_right(Align::Center), |ui| {
ui.add(egui::Label::new(egui::RichText::new(&request.path).size(12.0).color(theme::SUBTEXT).family(theme::mono())).truncate());
});
});
});
ui.horizontal(|ui| {
ui.add_space(52.0);
let mut note = request.ip.clone();
if let Some(intel) = request.intel() { note = format!("{note} · {intel}"); }
ui.add(egui::Label::new(egui::RichText::new(format!("{note} · {}", format::ago(logged.at))).size(11.5).color(theme::MUTED)).truncate());
});
});
}
});
}
});
if stop { self.state.stop_tunnel_by_user(id); }
if go_back { self.state.page = Page::Tunnels; }
}
}
+5
View File
@@ -0,0 +1,5 @@
mod connect;
mod detail;
mod new_tunnel;
mod settings;
mod tunnels;
+137
View File
@@ -0,0 +1,137 @@
use eframe::egui::{self, Align, Layout, Ui};
use crate::gui::app::{AuthChoice, NewTunnelForm, Page, TunnelKind, Window};
use crate::gui::widgets::{self, ButtonKind, FieldOptions};
use crate::gui::theme;
use crate::tunnel::{Access, Options, Rules, Target, TargetSpec};
impl Window<'_> {
pub fn new_tunnel_page(&mut self, ui: &mut Ui) {
let state = &mut self.state;
Window::content(ui, |ui| {
if widgets::back_link(ui, "Tunnels").clicked() { state.page = Page::Tunnels; }
ui.add_space(12.0);
widgets::text_family(ui, "New tunnel", 22.0, theme::TEXT, theme::semibold());
ui.add_space(16.0);
let mut submit = false;
ui.horizontal(|ui| {
widgets::segmented(ui, &mut state.new_tunnel.kind, &[(TunnelKind::Http, "HTTP"), (TunnelKind::Files, "Folder"), (TunnelKind::Tcp, "TCP + UDP")]);
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
if widgets::button(ui, "Open", ButtonKind::Primary).clicked() { submit = true; }
});
});
if let Some(error) = &state.new_tunnel.error {
ui.add_space(10.0);
widgets::error_notice(ui, error);
}
ui.add_space(14.0);
let mut browse = false;
let form = &mut state.new_tunnel;
widgets::card(ui, |ui| {
ui.spacing_mut().item_spacing.y = 14.0;
match form.kind {
TunnelKind::Http => {
widgets::field(ui, "nt-target", &mut form.target, FieldOptions { label: Some("Local target"), hint: "3000, 192.168.1.5:8080 or https://localhost:8443", mono: true, ..Default::default() });
}
TunnelKind::Files => {
ui.vertical(|ui| {
ui.spacing_mut().item_spacing.y = 6.0;
widgets::field_label(ui, "Folder");
ui.horizontal(|ui| {
let width = ui.available_width() - 96.0;
widgets::field(ui, "nt-dir", &mut form.dir, FieldOptions { hint: "/path/to/dist", mono: true, width: Some(width), ..Default::default() });
ui.add_enabled_ui(!form.picking_dir, |ui| {
if widgets::button(ui, "Browse", ButtonKind::Secondary).clicked() { browse = true; }
});
});
});
}
TunnelKind::Tcp => {
widgets::field(ui, "nt-tcp", &mut form.target, FieldOptions { label: Some("Local port"), hint: "25565 or 192.168.1.5:5432", mono: true, ..Default::default() });
}
}
widgets::field(ui, "nt-name", &mut form.name, FieldOptions { label: Some("Name (optional)"), hint: "myapp", mono: true, ..Default::default() });
if form.kind == TunnelKind::Http {
widgets::toggle_row(ui, "Keep the public host", "Send the public hostname as the Host header", &mut form.keep_host);
}
});
ui.add_space(16.0);
widgets::section(ui, "Access", None);
widgets::card(ui, |ui| {
ui.spacing_mut().item_spacing.y = 14.0;
if form.kind != TunnelKind::Tcp {
ui.vertical(|ui| {
ui.spacing_mut().item_spacing.y = 6.0;
widgets::field_label(ui, "Sign-in");
let label = match form.auth { AuthChoice::Open => "Open to everyone", AuthChoice::Password => "Ask for a password", AuthChoice::Login => "Require a frislit account" };
egui::ComboBox::from_id_salt("nt-auth").selected_text(label).width(ui.available_width()).show_ui(ui, |ui| {
ui.selectable_value(&mut form.auth, AuthChoice::Open, "Open to everyone");
ui.selectable_value(&mut form.auth, AuthChoice::Password, "Ask for a password");
ui.selectable_value(&mut form.auth, AuthChoice::Login, "Require a frislit account");
});
});
if form.auth == AuthChoice::Password {
widgets::field(ui, "nt-password", &mut form.password, FieldOptions { label: Some("Password"), hint: "hunter2", secret: true, ..Default::default() });
}
}
ui.vertical(|ui| {
ui.spacing_mut().item_spacing.y = 6.0;
widgets::field_label(ui, "Allowed addresses");
ui.horizontal(|ui| {
let width = ui.available_width() - 80.0;
let entered = widgets::field(ui, "nt-allow", &mut form.allow_input, FieldOptions { hint: "203.0.113.5 or 10.0.0.0/8", mono: true, width: Some(width), ..Default::default() }).lost_focus()
&& ui.input(|input| input.key_pressed(egui::Key::Enter));
if widgets::button(ui, "Add", ButtonKind::Secondary).clicked() || entered {
let value = form.allow_input.trim().to_string();
if !value.is_empty() && !form.allow.contains(&value) { form.allow.push(value); }
form.allow_input.clear();
}
});
let mut drop = None;
for (index, cidr) in form.allow.iter().enumerate() {
ui.horizontal(|ui| {
widgets::mono(ui, cidr, 13.0, theme::SUBTEXT);
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
if widgets::button(ui, "Remove", ButtonKind::Ghost).clicked() { drop = Some(index); }
});
});
}
if let Some(index) = drop { form.allow.remove(index); }
});
});
if browse { state.pick_folder(); }
if submit {
match build_options(&state.new_tunnel) {
Ok(opts) => {
let kind = state.new_tunnel.kind;
state.new_tunnel.error = None;
state.start_tunnel(kind, opts);
}
Err(err) => state.new_tunnel.error = Some(format!("{err:#}")),
}
}
});
}
}
fn build_options(form: &NewTunnelForm) -> anyhow::Result<Options> {
let name = Some(form.name.trim().to_string()).filter(|name| !name.is_empty());
let auth = if form.kind == TunnelKind::Tcp { AuthChoice::Open } else { form.auth };
let password = (auth == AuthChoice::Password).then(|| form.password.clone());
if password.as_deref() == Some("") { anyhow::bail!("Enter a password, or pick another sign-in option"); }
let access = Access::new(Rules::ips(form.allow.clone()), password, auth == AuthChoice::Login)?;
let target = form.target.trim();
if form.kind != TunnelKind::Files && target.is_empty() { anyhow::bail!("Enter a port or host:port to share"); }
Ok(match form.kind {
TunnelKind::Http => Options::http(TargetSpec::parse(target)?, name, form.keep_host, access),
TunnelKind::Files => {
let dir = form.dir.trim();
if dir.is_empty() { anyhow::bail!("Pick the folder to share"); }
Options::http(TargetSpec::dir(dir)?, name, false, access)
}
TunnelKind::Tcp => Options::tcp(Target::parse(target)?, name, access),
})
}
+115
View File
@@ -0,0 +1,115 @@
use eframe::egui::{self, Align, Layout, Ui};
use crate::auth;
use crate::gui::app::Window;
use crate::gui::widgets::{self, ButtonKind};
use crate::gui::{autostart, theme, HOTKEY_LABEL};
impl Window<'_> {
pub fn settings_page(&mut self, ui: &mut Ui) {
let logo = self.logo.id();
let mut quit = false;
let state = &mut self.state;
let server_url = state.cfg.server_url();
Window::content(ui, |ui| {
widgets::heading(ui, "Settings");
ui.add_space(16.0);
widgets::section(ui, "Server", None);
widgets::card(ui, |ui| {
ui.horizontal(|ui| {
ui.scope(|ui| {
ui.set_max_width(ui.available_width() - 90.0);
match &server_url {
Some(url) => { ui.add(egui::Label::new(egui::RichText::new(url).size(14.0).color(theme::TEXT).family(theme::mono())).truncate()); }
None => { widgets::text(ui, "No server yet", 14.0, theme::SUBTEXT); }
}
});
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
if state.linked() { widgets::text(ui, "Linked", 12.5, theme::SUCCESS); }
else if server_url.is_some() { widgets::text(ui, "Not linked", 12.5, theme::WARNING); }
});
});
ui.add_space(4.0);
match (&server_url, &state.server_info) {
(None, _) => {}
(Some(_), Some(Ok(info))) => { ui.add(egui::Label::new(egui::RichText::new(format!("{} {} · tunnels under {}", info.name, info.version, info.base_domain)).size(12.5).color(theme::SUBTEXT)).wrap()); }
(Some(_), Some(Err(err))) => { ui.add(egui::Label::new(egui::RichText::new(format!("Not reachable: {err}")).size(12.5).color(theme::ERROR)).wrap()); }
(Some(_), None) => { widgets::text(ui, "Checking...", 12.5, theme::MUTED); }
}
if let Some(me) = &state.me {
ui.add_space(2.0);
widgets::text(ui, format!("Signed in as {}", me.label()), 12.5, theme::SUBTEXT);
}
if state.linked() {
ui.add_space(10.0);
if widgets::button(ui, "Unlink this device", ButtonKind::Danger).clicked() {
match auth::logout() {
Ok(_) => { state.reload_config(); state.toast("Device unlinked"); }
Err(err) => state.toast_error(format!("{err:#}")),
}
}
}
ui.add_space(12.0);
widgets::divider(ui);
ui.add_space(12.0);
let mut accept = state.cfg.accept_invalid_certs;
if widgets::toggle_row(ui, "Accept self-signed certificates", "", &mut accept).changed() {
state.cfg.accept_invalid_certs = accept;
state.login.accept_invalid = accept;
match state.cfg.save() { Ok(_) => state.fetch_info(), Err(err) => state.toast_error(format!("{err:#}")) }
}
});
if state.has_tray {
ui.add_space(24.0);
widgets::section(ui, "Window", None);
widgets::card(ui, |ui| {
ui.spacing_mut().item_spacing.y = 14.0;
let mut autostart_on = state.autostart;
if widgets::toggle_row(ui, "Launch at login", "Starts hidden in the tray", &mut autostart_on).changed() {
match autostart::set(autostart_on) {
Ok(_) => state.autostart = autostart_on,
Err(err) => state.toast_error(format!("{err:#}")),
}
}
if state.hotkey { widgets::text(ui, format!("{HOTKEY_LABEL} shows or hides the window"), 12.5, theme::MUTED); }
});
}
ui.add_space(24.0);
widgets::section(ui, "About", None);
widgets::card(ui, |ui| {
ui.horizontal(|ui| {
ui.image((logo, egui::vec2(32.0, 32.0)));
widgets::text_family(ui, format!("frislit {}", env!("CARGO_PKG_VERSION")), 14.0, theme::TEXT, theme::semibold());
if state.has_tray {
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
if widgets::button(ui, "Quit", ButtonKind::Danger).clicked() { quit = true; }
});
}
});
ui.add_space(4.0);
let mut start_update = false;
match (state.update.clone(), state.managed) {
(Some(version), true) => { widgets::text(ui, format!("{version} is available through your package manager"), 12.5, theme::WARNING); }
(Some(version), false) => {
ui.horizontal(|ui| {
widgets::text(ui, format!("{version} is available"), 12.5, theme::WARNING);
ui.add_enabled_ui(!state.updating, |ui| {
if widgets::button(ui, if state.updating { "Updating..." } else { "Update and restart" }, ButtonKind::Primary).clicked() { start_update = true; }
});
});
}
(None, _) => { widgets::text(ui, if state.checked_update { "Up to date" } else { "Checking for updates..." }, 12.5, theme::MUTED); }
}
if start_update { state.start_update(); }
ui.add_space(8.0);
ui.horizontal(|ui| {
if widgets::button(ui, "Documentation", ButtonKind::Ghost).clicked() { ui.ctx().open_url(egui::OpenUrl::new_tab("https://git.fristy.net/fristy/frislit/blob/main/docs/cli.md")); }
if widgets::button(ui, "GitHub", ButtonKind::Ghost).clicked() { ui.ctx().open_url(egui::OpenUrl::new_tab("https://git.fristy.net/fristy/frislit")); }
});
});
});
if quit { self.quit(&ui.ctx().clone()); }
}
}
+151
View File
@@ -0,0 +1,151 @@
use eframe::egui::{self, Align, Layout, Ui};
use crate::gui::app::{state_dot, LoginStage, Page, TunnelState, Window};
use crate::gui::widgets::{self, ButtonKind, FieldOptions};
use crate::gui::{format, theme};
impl Window<'_> {
pub fn tunnels_page(&mut self, ui: &mut Ui) {
Window::content(ui, |ui| {
if !self.state.linked() {
self.login_card(ui);
return;
}
let state = &mut self.state;
let online = state.tunnels.iter().filter(|card| matches!(card.state, TunnelState::Online)).count();
ui.horizontal(|ui| {
ui.vertical(|ui| {
ui.spacing_mut().item_spacing.y = 2.0;
widgets::heading(ui, "Tunnels");
widgets::text(ui, format!("{online} of {} online", state.tunnels.len()), 12.5, theme::MUTED);
});
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
if widgets::button(ui, "New tunnel", ButtonKind::Primary).clicked() {
state.new_tunnel.error = None;
state.page = Page::NewTunnel;
}
});
});
ui.add_space(16.0);
if state.tunnels.is_empty() {
widgets::empty_state(ui, "No tunnels yet", "Share a port, a folder or a TCP service.", |ui| {
if widgets::button(ui, "Open your first tunnel", ButtonKind::Secondary).clicked() { state.page = Page::NewTunnel; }
});
}
let server_url = state.server_url();
let mut open = None;
ui.spacing_mut().item_spacing.y = 8.0;
for card in &state.tunnels {
let response = widgets::clickable_card(ui, ("tunnel-row", card.id), |ui| {
ui.vertical(|ui| {
ui.spacing_mut().item_spacing.y = 4.0;
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 8.0;
widgets::dot(ui, state_dot(&card.state));
widgets::mono(ui, card.title(), 14.0, theme::TEXT);
widgets::text(ui, card.kind.label(), 12.0, theme::MUTED);
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
widgets::chevron_right(ui, theme::MUTED);
widgets::text(ui, format::ago(card.started), 12.0, theme::MUTED);
});
});
let link = card.link(&server_url).unwrap_or_else(|| "connecting...".into());
ui.horizontal(|ui| {
ui.add_space(16.0);
ui.add(egui::Label::new(egui::RichText::new(format!("{link} · {}", card.target_label)).size(12.5).color(theme::SUBTEXT)).truncate());
});
});
});
if response.clicked() { open = Some(card.id); }
}
if let Some(id) = open { state.page = Page::Tunnel(id); }
let suggestions = state.suggestions();
if suggestions.is_empty() { return; }
ui.add_space(24.0);
widgets::section(ui, "Listening on this machine", None);
let mut expose = None;
widgets::card(ui, |ui| {
ui.spacing_mut().item_spacing.y = 10.0;
for listener in &suggestions {
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 10.0;
widgets::mono(ui, format!("localhost:{}", listener.port), 14.0, theme::TEXT);
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
if widgets::button(ui, "Open", ButtonKind::Secondary).clicked() { expose = Some(listener.clone()); }
widgets::text(ui, if listener.is_tcp() { "tcp" } else { "http" }, 12.5, theme::MUTED);
ui.with_layout(Layout::left_to_right(Align::Center), |ui| {
ui.add(egui::Label::new(egui::RichText::new(&listener.process).size(12.5).color(theme::MUTED)).truncate());
});
});
});
}
});
if let Some(listener) = expose { state.expose(&listener); }
});
}
fn login_card(&mut self, ui: &mut Ui) {
let logo = self.logo.id();
let state = &mut self.state;
ui.vertical_centered(|ui| {
ui.add_space(28.0);
ui.image((logo, egui::vec2(56.0, 56.0)));
ui.add_space(12.0);
widgets::text_family(ui, "Link this device.", 24.0, theme::TEXT, theme::semibold());
ui.add_space(24.0);
ui.with_layout(Layout::top_down(Align::Min), |ui| {
match &state.login.stage {
LoginStage::Idle | LoginStage::Failed(_) => {
let mut submit = widgets::field(ui, "login-server", &mut state.login.server,
FieldOptions { label: Some("Server URL"), hint: "https://frislit.example.com", ..Default::default() }).lost_focus()
&& ui.input(|input| input.key_pressed(egui::Key::Enter));
ui.add_space(10.0);
if state.login.use_key {
submit |= widgets::field(ui, "login-key", &mut state.login.key,
FieldOptions { label: Some("API key"), hint: "Created under Devices in the web UI", mono: true, secret: true, ..Default::default() }).lost_focus()
&& ui.input(|input| input.key_pressed(egui::Key::Enter));
ui.add_space(10.0);
}
widgets::toggle_row(ui, "Accept self-signed certificates", "", &mut state.login.accept_invalid);
ui.add_space(8.0);
if let LoginStage::Failed(message) = &state.login.stage {
widgets::error_notice(ui, message);
ui.add_space(8.0);
}
let label = if state.login.use_key { "Link with key" } else { "Continue" };
if widgets::button_sized(ui, label, ButtonKind::Primary, ui.available_width()).clicked() { submit = true; }
if submit { if state.login.use_key { state.link_with_key() } else { state.start_login() } }
ui.add_space(4.0);
let other = if state.login.use_key { "Approve in the browser instead" } else { "Use an API key instead" };
if widgets::button(ui, other, ButtonKind::Ghost).clicked() { state.login.use_key = !state.login.use_key; state.login.stage = LoginStage::Idle; }
}
LoginStage::Starting => {
ui.horizontal(|ui| { ui.spinner(); widgets::text(ui, "Contacting the server...", 14.0, theme::SUBTEXT); });
}
LoginStage::Waiting { code, url } => {
let code = code.clone();
let url = url.clone();
widgets::card(ui, |ui| {
ui.vertical_centered(|ui| {
widgets::text(ui, "Approve this device in your browser", 14.0, theme::SUBTEXT);
ui.add_space(8.0);
widgets::text_family(ui, &code, 30.0, theme::PRIMARY_BRIGHT, theme::bold());
ui.add_space(8.0);
ui.horizontal(|ui| { ui.spinner(); widgets::text(ui, "Waiting for approval...", 13.0, theme::MUTED); });
});
});
ui.add_space(10.0);
ui.horizontal(|ui| {
if widgets::button(ui, "Open approval page", ButtonKind::Secondary).clicked() { ui.ctx().open_url(egui::OpenUrl::new_tab(&url)); }
if widgets::button(ui, "Cancel", ButtonKind::Ghost).clicked() { state.cancel_login(); }
});
}
}
});
});
}
}
+79
View File
@@ -0,0 +1,79 @@
use std::collections::BTreeMap;
#[derive(Clone)]
pub struct Listener { pub port: u16, pub process: String }
const TCP_SERVICES: [&str; 10] = ["postgres", "postmaster", "redis-server", "mysqld", "mariadbd", "mongod", "sshd", "memcached", "valkey-server", "beam.smp"];
impl Listener {
pub fn is_tcp(&self) -> bool { TCP_SERVICES.contains(&self.process.as_str()) }
}
pub fn scan() -> Vec<Listener> {
let own = std::process::id();
let mut found: BTreeMap<u16, String> = BTreeMap::new();
for (port, pid, process) in listeners() {
if !(1024..32768).contains(&port) || pid == own || process == "frislit" { continue; }
found.entry(port).or_insert(process);
}
found.into_iter().map(|(port, process)| Listener { port, process }).collect()
}
#[cfg(target_os = "linux")]
fn listeners() -> Vec<(u16, u32, String)> {
let mut inodes: BTreeMap<u64, u16> = BTreeMap::new();
for table in ["/proc/net/tcp", "/proc/net/tcp6"] {
let Ok(text) = std::fs::read_to_string(table) else { continue };
for line in text.lines().skip(1) {
let fields: Vec<&str> = line.split_whitespace().collect();
if fields.len() < 10 || fields[3] != "0A" { continue; }
let (Some(port), Ok(inode)) = (fields[1].rsplit(':').next().and_then(|hex| u16::from_str_radix(hex, 16).ok()), fields[9].parse::<u64>()) else { continue };
inodes.insert(inode, port);
}
}
let mut out = Vec::new();
let Ok(procs) = std::fs::read_dir("/proc") else { return out };
for entry in procs.flatten() {
let Ok(pid) = entry.file_name().to_string_lossy().parse::<u32>() else { continue };
let Ok(fds) = std::fs::read_dir(entry.path().join("fd")) else { continue };
let cmdline = std::fs::read(entry.path().join("cmdline")).unwrap_or_default();
let argv0 = String::from_utf8_lossy(cmdline.split(|byte| *byte == 0).next().unwrap_or_default()).into_owned();
let name = argv0.rsplit('/').next().unwrap_or_default().to_string();
for fd in fds.flatten() {
let Ok(link) = std::fs::read_link(fd.path()) else { continue };
let text = link.to_string_lossy();
let Some(inode) = text.strip_prefix("socket:[").and_then(|rest| rest.strip_suffix(']')).and_then(|inode| inode.parse::<u64>().ok()) else { continue };
if let Some(port) = inodes.get(&inode) { out.push((*port, pid, name.clone())); }
}
}
out
}
#[cfg(target_os = "macos")]
fn listeners() -> Vec<(u16, u32, String)> {
let Ok(output) = std::process::Command::new("lsof").args(["-nP", "-iTCP", "-sTCP:LISTEN"]).output() else { return Vec::new() };
String::from_utf8_lossy(&output.stdout).lines().skip(1).filter_map(|line| {
let fields: Vec<&str> = line.split_whitespace().collect();
let port = fields.get(8)?.rsplit(':').next()?.parse().ok()?;
Some((port, fields.get(1)?.parse().ok()?, fields[0].to_string()))
}).collect()
}
#[cfg(windows)]
fn listeners() -> Vec<(u16, u32, String)> {
let Ok(netstat) = std::process::Command::new("netstat").args(["-ano", "-p", "TCP"]).output() else { return Vec::new() };
let names: BTreeMap<u32, String> = std::process::Command::new("tasklist").args(["/FO", "CSV", "/NH"]).output().map(|output| {
String::from_utf8_lossy(&output.stdout).lines().filter_map(|line| {
let mut cells = line.split("\",\"");
let name = cells.next()?.trim_start_matches('"').trim_end_matches(".exe").to_string();
Some((cells.next()?.parse().ok()?, name))
}).collect()
}).unwrap_or_default();
String::from_utf8_lossy(&netstat.stdout).lines().filter_map(|line| {
let fields: Vec<&str> = line.split_whitespace().collect();
if fields.get(3) != Some(&"LISTENING") { return None; }
let port = fields.get(1)?.rsplit(':').next()?.parse().ok()?;
let pid: u32 = fields.get(4)?.parse().ok()?;
Some((port, pid, names.get(&pid).cloned().unwrap_or_default()))
}).collect()
}
+102
View File
@@ -0,0 +1,102 @@
use eframe::egui::{self, Color32, CornerRadius, FontData, FontDefinitions, FontFamily, FontId, Stroke, TextStyle, Visuals};
use std::sync::Arc;
pub const BACKGROUND: Color32 = Color32::from_rgb(0x11, 0x10, 0x0E);
pub const SURFACE: Color32 = Color32::from_rgb(0x17, 0x16, 0x13);
pub const SURFACE_RAISED: Color32 = Color32::from_rgb(0x1C, 0x1A, 0x17);
pub const SURFACE_HOVER: Color32 = Color32::from_rgb(0x22, 0x1F, 0x1B);
pub const BORDER: Color32 = Color32::from_rgba_premultiplied(18, 18, 18, 18);
pub const BORDER_STRONG: Color32 = Color32::from_rgba_premultiplied(33, 33, 33, 33);
pub const PRIMARY: Color32 = Color32::from_rgb(0x14, 0xB8, 0xA6);
pub const PRIMARY_BRIGHT: Color32 = Color32::from_rgb(0x2D, 0xD4, 0xBF);
pub const PRIMARY_HOVER: Color32 = Color32::from_rgb(0x5E, 0xEA, 0xD4);
pub const PRIMARY_TINT: Color32 = Color32::from_rgba_premultiplied(3, 26, 23, 36);
pub const ON_PRIMARY: Color32 = Color32::from_rgb(0x05, 0x20, 0x1C);
pub const TEXT: Color32 = Color32::from_rgb(0xFA, 0xFA, 0xF9);
pub const SUBTEXT: Color32 = Color32::from_rgb(0xA8, 0xA2, 0x9E);
pub const MUTED: Color32 = Color32::from_rgb(0x79, 0x71, 0x6B);
pub const ERROR: Color32 = Color32::from_rgb(0xF8, 0x71, 0x71);
pub const ERROR_TINT: Color32 = Color32::from_rgba_premultiplied(32, 15, 15, 33);
pub const SUCCESS: Color32 = Color32::from_rgb(0x34, 0xD3, 0x99);
pub const WARNING: Color32 = Color32::from_rgb(0xFB, 0xBF, 0x24);
pub const WARNING_TINT: Color32 = Color32::from_rgba_premultiplied(32, 25, 5, 33);
pub const RADIUS_INPUT: u8 = 12;
pub const RADIUS_CARD: u8 = 14;
pub const RADIUS_SMALL: u8 = 10;
pub const GUTTER: f32 = 16.0;
pub fn medium() -> FontFamily { FontFamily::Proportional }
pub fn semibold() -> FontFamily { FontFamily::Name("semibold".into()) }
pub fn bold() -> FontFamily { FontFamily::Name("bold".into()) }
pub fn mono() -> FontFamily { FontFamily::Monospace }
pub fn font(size: f32, family: FontFamily) -> FontId { FontId::new(size, family) }
pub fn corner(radius: u8) -> CornerRadius { CornerRadius::same(radius) }
pub fn install(ctx: &egui::Context) {
let mut fonts = FontDefinitions::default();
fonts.font_data.insert("jakarta-medium".into(), Arc::new(FontData::from_static(include_bytes!("../../assets/PlusJakartaSans-Medium.ttf"))));
fonts.font_data.insert("jakarta-semibold".into(), Arc::new(FontData::from_static(include_bytes!("../../assets/PlusJakartaSans-SemiBold.ttf"))));
fonts.font_data.insert("jakarta-bold".into(), Arc::new(FontData::from_static(include_bytes!("../../assets/PlusJakartaSans-Bold.ttf"))));
let fallback = fonts.families.get(&FontFamily::Proportional).cloned().unwrap_or_default();
let with_fallback = |first: &str| std::iter::once(first.to_string()).chain(fallback.iter().cloned()).collect::<Vec<_>>();
fonts.families.insert(FontFamily::Proportional, with_fallback("jakarta-medium"));
fonts.families.insert(semibold(), with_fallback("jakarta-semibold"));
fonts.families.insert(bold(), with_fallback("jakarta-bold"));
ctx.set_fonts(fonts);
let mut visuals = Visuals::dark();
visuals.panel_fill = BACKGROUND;
visuals.window_fill = SURFACE_RAISED;
visuals.window_stroke = Stroke::new(1.0, BORDER_STRONG);
visuals.window_corner_radius = corner(RADIUS_CARD);
visuals.menu_corner_radius = corner(RADIUS_INPUT);
visuals.extreme_bg_color = SURFACE;
visuals.faint_bg_color = SURFACE_RAISED;
visuals.code_bg_color = SURFACE_HOVER;
visuals.override_text_color = Some(TEXT);
visuals.hyperlink_color = PRIMARY_BRIGHT;
visuals.selection.bg_fill = PRIMARY_TINT;
visuals.selection.stroke = Stroke::new(1.0, PRIMARY);
visuals.text_cursor.stroke.color = PRIMARY_BRIGHT;
let widgets = &mut visuals.widgets;
for (widget, fill, border, text) in [
(&mut widgets.noninteractive, SURFACE, BORDER, SUBTEXT),
(&mut widgets.inactive, SURFACE_RAISED, BORDER_STRONG, TEXT),
(&mut widgets.hovered, SURFACE_HOVER, BORDER_STRONG, TEXT),
(&mut widgets.active, SURFACE_HOVER, PRIMARY, TEXT),
(&mut widgets.open, SURFACE_RAISED, PRIMARY, TEXT),
] {
widget.bg_fill = fill;
widget.weak_bg_fill = fill;
widget.bg_stroke = Stroke::new(1.0, border);
widget.fg_stroke = Stroke::new(1.0, text);
widget.corner_radius = corner(RADIUS_SMALL);
widget.expansion = 0.0;
}
ctx.set_visuals(visuals);
ctx.all_styles_mut(|style| {
style.text_styles.insert(TextStyle::Body, font(14.0, medium()));
style.text_styles.insert(TextStyle::Button, font(14.0, medium()));
style.text_styles.insert(TextStyle::Small, font(12.0, medium()));
style.text_styles.insert(TextStyle::Heading, font(22.0, semibold()));
style.text_styles.insert(TextStyle::Monospace, font(13.0, mono()));
style.spacing.item_spacing = egui::vec2(8.0, 8.0);
style.spacing.button_padding = egui::vec2(12.0, 6.0);
style.spacing.interact_size = egui::vec2(40.0, 30.0);
style.spacing.combo_width = 160.0;
style.spacing.scroll.bar_width = 8.0;
style.spacing.scroll.floating = true;
style.visuals.striped = false;
style.interaction.selectable_labels = false;
});
}
+88
View File
@@ -0,0 +1,88 @@
use anyhow::Result;
use std::sync::mpsc::Sender;
use tokio::runtime::Handle;
use super::{Repaint, Wake};
const ICON_SIZE: u32 = 32;
const ICON_RGBA: &[u8] = include_bytes!("../../assets/icon-32.rgba");
pub struct Tray { _keep: Box<dyn std::any::Any> }
#[derive(Clone)]
struct Notifier { wake: Sender<Wake>, repaint: Repaint }
impl Notifier {
fn send(&self, wake: Wake) {
let _ = self.wake.send(wake);
self.repaint.ping();
}
}
#[cfg(target_os = "linux")]
pub fn start(wake: Sender<Wake>, repaint: Repaint, runtime: &Handle) -> Result<Tray> {
use ksni::{menu::{MenuItem, StandardItem}, Icon, ToolTip, TrayMethods};
struct FrislitTray { notify: Notifier }
impl ksni::Tray for FrislitTray {
fn id(&self) -> String { "frislit".into() }
fn title(&self) -> String { "frislit".into() }
fn tool_tip(&self) -> ToolTip { ToolTip { title: "frislit".into(), ..Default::default() } }
fn icon_pixmap(&self) -> Vec<Icon> {
let mut data = Vec::with_capacity(ICON_RGBA.len());
for pixel in ICON_RGBA.chunks(4) { data.extend_from_slice(&[pixel[3], pixel[0], pixel[1], pixel[2]]); }
vec![Icon { width: ICON_SIZE as i32, height: ICON_SIZE as i32, data }]
}
fn activate(&mut self, _x: i32, _y: i32) { self.notify.send(Wake::Toggle); }
fn menu(&self) -> Vec<MenuItem<Self>> {
vec![
StandardItem { label: "Open frislit".into(), activate: Box::new(|tray: &mut Self| tray.notify.send(Wake::Show)), ..Default::default() }.into(),
MenuItem::Separator,
StandardItem { label: "Quit".into(), activate: Box::new(|tray: &mut Self| tray.notify.send(Wake::Quit)), ..Default::default() }.into(),
]
}
}
let tray = FrislitTray { notify: Notifier { wake, repaint } };
let handle = runtime.block_on(tray.spawn()).map_err(|err| anyhow::anyhow!("No tray available: {err}"))?;
Ok(Tray { _keep: Box::new(handle) })
}
#[cfg(any(windows, target_os = "macos"))]
pub fn start(wake: Sender<Wake>, repaint: Repaint, _runtime: &Handle) -> Result<Tray> {
use tray_icon::{menu::{Menu, MenuEvent, MenuItem, PredefinedMenuItem}, Icon, MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent};
let notify = Notifier { wake, repaint };
let menu = Menu::new();
let open = MenuItem::new("Open frislit", true, None);
let quit = MenuItem::new("Quit", true, None);
menu.append_items(&[&open, &PredefinedMenuItem::separator(), &quit])?;
let (open_id, quit_id) = (open.id().clone(), quit.id().clone());
let icon = Icon::from_rgba(ICON_RGBA.to_vec(), ICON_SIZE, ICON_SIZE)?;
let tray = TrayIconBuilder::new()
.with_menu(Box::new(menu))
.with_tooltip("frislit")
.with_icon(icon)
.with_icon_as_template(cfg!(target_os = "macos"))
.with_menu_on_left_click(false)
.build()?;
let clicks = notify.clone();
TrayIconEvent::set_event_handler(Some(move |event: TrayIconEvent| {
if let TrayIconEvent::Click { button: MouseButton::Left, button_state: MouseButtonState::Up, .. } = event {
clicks.send(Wake::Toggle);
}
}));
MenuEvent::set_event_handler(Some(move |event: MenuEvent| {
if *event.id() == open_id { notify.send(Wake::Show); }
else if *event.id() == quit_id { notify.send(Wake::Quit); }
}));
Ok(Tray { _keep: Box::new(tray) })
}
#[cfg(not(any(windows, target_os = "macos", target_os = "linux")))]
pub fn start(_wake: Sender<Wake>, _repaint: Repaint, _runtime: &Handle) -> Result<Tray> {
anyhow::bail!("No tray on this platform")
}
+319
View File
@@ -0,0 +1,319 @@
use eframe::egui::{self, Align, Color32, CursorIcon, Frame, Id, Layout, Margin, Response, RichText, Sense, Stroke, StrokeKind, TextEdit, Ui, Vec2};
use std::time::Instant;
use super::theme::{self, corner};
#[derive(Clone, Copy, PartialEq)]
pub enum ButtonKind { Primary, Secondary, Ghost, Danger }
pub fn button(ui: &mut Ui, text: &str, kind: ButtonKind) -> Response {
button_sized(ui, text, kind, 0.0)
}
pub fn button_sized(ui: &mut Ui, text: &str, kind: ButtonKind, min_width: f32) -> Response {
let family = if kind == ButtonKind::Primary { theme::semibold() } else { theme::medium() };
let galley = ui.painter().layout_no_wrap(text.to_string(), theme::font(14.0, family), Color32::WHITE);
let padding = egui::vec2(16.0, 7.0);
let size = Vec2::new((galley.size().x + padding.x * 2.0).max(min_width), (galley.size().y + padding.y * 2.0).max(34.0));
let (rect, response) = ui.allocate_exact_size(size, Sense::click());
if !ui.is_rect_visible(rect) { return response; }
let enabled = ui.is_enabled();
let hovered = response.hovered() && enabled;
let (fill, stroke, color) = match kind {
ButtonKind::Primary => (if hovered { theme::PRIMARY_HOVER } else { theme::PRIMARY_BRIGHT }, Stroke::NONE, theme::ON_PRIMARY),
ButtonKind::Secondary => (if hovered { theme::SURFACE_HOVER } else { Color32::TRANSPARENT }, Stroke::new(1.0, theme::BORDER_STRONG), theme::TEXT),
ButtonKind::Ghost => (if hovered { theme::SURFACE_HOVER } else { Color32::TRANSPARENT }, Stroke::NONE, if hovered { theme::TEXT } else { theme::SUBTEXT }),
ButtonKind::Danger => if hovered { (theme::ERROR_TINT, Stroke::NONE, theme::ERROR) } else { (Color32::TRANSPARENT, Stroke::new(1.0, theme::BORDER_STRONG), theme::SUBTEXT) },
};
let (fill, color) = if enabled { (fill, color) } else if kind == ButtonKind::Primary { (theme::SURFACE_HOVER, theme::MUTED) } else { (fill, theme::MUTED) };
let painter = ui.painter();
painter.rect(rect, corner(theme::RADIUS_INPUT), fill, stroke, StrokeKind::Inside);
let text_pos = rect.center() - galley.size() / 2.0;
painter.galley(text_pos, galley, color);
if hovered { ui.ctx().set_cursor_icon(CursorIcon::PointingHand); }
response
}
pub fn text(ui: &mut Ui, value: impl Into<String>, size: f32, color: Color32) -> Response {
ui.label(RichText::new(value).size(size).color(color))
}
pub fn text_family(ui: &mut Ui, value: impl Into<String>, size: f32, color: Color32, family: egui::FontFamily) -> Response {
ui.label(RichText::new(value).size(size).color(color).family(family))
}
pub fn mono(ui: &mut Ui, value: impl Into<String>, size: f32, color: Color32) -> Response {
ui.label(RichText::new(value).size(size).color(color).family(theme::mono()))
}
pub fn heading(ui: &mut Ui, value: &str) {
text_family(ui, value, 24.0, theme::TEXT, theme::semibold());
}
pub fn field_label(ui: &mut Ui, label: &str) {
text(ui, label, 13.0, theme::SUBTEXT);
}
#[derive(Default)]
pub struct FieldOptions<'a> {
pub label: Option<&'a str>,
pub hint: &'a str,
pub mono: bool,
pub secret: bool,
pub width: Option<f32>,
}
pub fn field(ui: &mut Ui, id: impl std::hash::Hash + std::fmt::Debug, value: &mut String, options: FieldOptions) -> Response {
let id = Id::new(id);
let edit_id = id.with("edit");
let focused = ui.memory(|memory| memory.has_focus(edit_id));
let width = options.width.unwrap_or_else(|| ui.available_width());
ui.vertical(|ui| {
ui.spacing_mut().item_spacing.y = 6.0;
if let Some(label) = options.label { field_label(ui, label); }
ui.set_width(width);
let frame = Frame::new()
.fill(theme::SURFACE)
.stroke(Stroke::new(1.0, if focused { theme::PRIMARY } else { theme::BORDER }))
.corner_radius(corner(theme::RADIUS_INPUT))
.inner_margin(Margin::symmetric(14, 9));
let inner = frame.show(ui, |ui| {
let family = if options.mono { theme::mono() } else { theme::medium() };
let mut edit = TextEdit::singleline(value)
.id(edit_id)
.frame(Frame::NONE)
.background_color(Color32::TRANSPARENT)
.font(theme::font(15.0, family))
.text_color(theme::TEXT)
.hint_text(RichText::new(options.hint).color(theme::MUTED).size(15.0))
.desired_width(f32::INFINITY)
.margin(Margin::ZERO);
if options.secret { edit = edit.password(true); }
ui.add(edit)
});
let response = inner.inner;
if inner.response.hovered() { ui.ctx().set_cursor_icon(CursorIcon::Text); }
if inner.response.clicked() { ui.memory_mut(|memory| memory.request_focus(edit_id)); }
response
}).inner
}
pub fn dot(ui: &mut Ui, color: Color32) {
let (rect, _) = ui.allocate_exact_size(egui::vec2(8.0, 8.0), Sense::hover());
ui.painter().circle_filled(rect.center(), 3.5, color);
}
pub fn card<R>(ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> egui::InnerResponse<R> {
Frame::new()
.fill(theme::SURFACE)
.stroke(Stroke::new(1.0, theme::BORDER))
.corner_radius(corner(theme::RADIUS_CARD))
.inner_margin(Margin::same(18))
.show(ui, |ui| {
ui.set_width(ui.available_width());
add(ui)
})
}
pub fn clickable_card(ui: &mut Ui, id: impl std::hash::Hash + std::fmt::Debug, add: impl FnOnce(&mut Ui)) -> Response {
let id = Id::new(id);
let hovered = ui.ctx().read_response(id).is_some_and(|response| response.hovered());
let fill = if hovered { theme::SURFACE_HOVER } else { theme::SURFACE };
let frame = Frame::new()
.fill(fill)
.stroke(Stroke::new(1.0, if hovered { theme::BORDER_STRONG } else { theme::BORDER }))
.corner_radius(corner(theme::RADIUS_CARD))
.inner_margin(Margin::symmetric(18, 14));
let inner = frame.show(ui, |ui| {
ui.set_width(ui.available_width());
ui.horizontal(|ui| add(ui));
});
let response = ui.interact(inner.response.rect, id, Sense::click());
if response.hovered() { ui.ctx().set_cursor_icon(CursorIcon::PointingHand); }
response
}
pub fn section(ui: &mut Ui, title: &str, hint: Option<&str>) {
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 10.0;
text_family(ui, title, 16.0, theme::TEXT, theme::semibold());
if let Some(hint) = hint { text(ui, hint, 13.0, theme::MUTED); }
});
ui.add_space(4.0);
}
pub fn toggle(ui: &mut Ui, on: &mut bool) -> Response {
let size = egui::vec2(36.0, 20.0);
let (rect, mut response) = ui.allocate_exact_size(size, Sense::click());
if response.clicked() { *on = !*on; response.mark_changed(); }
let how_on = ui.ctx().animate_bool(response.id, *on);
let fill = if *on { theme::PRIMARY } else { theme::SURFACE_HOVER };
let stroke = if *on { Stroke::NONE } else { Stroke::new(1.0, theme::BORDER_STRONG) };
ui.painter().rect(rect, corner(10), fill, stroke, StrokeKind::Inside);
let radius = 7.0;
let x = egui::lerp((rect.left() + radius + 3.0)..=(rect.right() - radius - 3.0), how_on);
ui.painter().circle_filled(egui::pos2(x, rect.center().y), radius, if *on { theme::ON_PRIMARY } else { theme::SUBTEXT });
if response.hovered() { ui.ctx().set_cursor_icon(CursorIcon::PointingHand); }
response
}
pub fn status_color(status: u16) -> Color32 {
match status {
200..=299 => theme::SUCCESS,
300..=399 => theme::PRIMARY,
400..=499 => theme::WARNING,
_ => theme::ERROR,
}
}
pub fn toggle_row(ui: &mut Ui, label: &str, hint: &str, on: &mut bool) -> Response {
ui.horizontal(|ui| {
let text_width = ui.available_width() - 52.0;
ui.vertical(|ui| {
ui.set_max_width(text_width);
ui.spacing_mut().item_spacing.y = 2.0;
text(ui, label, 14.0, theme::TEXT);
if !hint.is_empty() { ui.add(egui::Label::new(RichText::new(hint).size(12.5).color(theme::MUTED)).wrap()); }
});
ui.with_layout(Layout::right_to_left(Align::Center), |ui| toggle(ui, on)).inner
}).inner
}
pub fn copy_row(ui: &mut Ui, id: impl std::hash::Hash + std::fmt::Debug, value: &str, copied_at: &mut Option<Instant>) -> bool {
let mut copied = false;
let frame = Frame::new()
.fill(theme::SURFACE)
.stroke(Stroke::new(1.0, theme::BORDER))
.corner_radius(corner(theme::RADIUS_SMALL))
.inner_margin(Margin::symmetric(12, 6));
frame.show(ui, |ui| {
ui.set_width(ui.available_width());
ui.horizontal(|ui| {
let recently = copied_at.is_some_and(|at| at.elapsed().as_secs_f32() < 1.6);
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
let label = if recently { "Copied" } else { "Copy" };
let response = ui.push_id(Id::new(&id).with("copy"), |ui| button(ui, label, ButtonKind::Ghost)).inner;
if response.clicked() {
ui.ctx().copy_text(value.to_string());
*copied_at = Some(Instant::now());
copied = true;
}
ui.with_layout(Layout::left_to_right(Align::Center), |ui| {
ui.add(egui::Label::new(RichText::new(value).size(13.0).color(theme::SUBTEXT).family(theme::mono())).truncate());
});
});
});
});
copied
}
pub fn notice(ui: &mut Ui, message: &str, color: Color32, tint: Color32) {
Frame::new()
.fill(tint)
.corner_radius(corner(theme::RADIUS_SMALL))
.inner_margin(Margin::symmetric(14, 10))
.show(ui, |ui| {
ui.set_width(ui.available_width());
ui.add(egui::Label::new(RichText::new(message).size(13.5).color(color)).wrap());
});
}
pub fn error_notice(ui: &mut Ui, message: &str) { notice(ui, message, theme::ERROR, theme::ERROR_TINT); }
pub fn warning_notice(ui: &mut Ui, message: &str) { notice(ui, message, theme::WARNING, theme::WARNING_TINT); }
pub fn empty_state(ui: &mut Ui, title: &str, body: &str, add: impl FnOnce(&mut Ui)) {
Frame::new()
.stroke(Stroke::new(1.0, theme::BORDER_STRONG))
.corner_radius(corner(theme::RADIUS_CARD))
.inner_margin(Margin::symmetric(32, 40))
.show(ui, |ui| {
ui.set_width(ui.available_width());
ui.vertical_centered(|ui| {
ui.spacing_mut().item_spacing.y = 8.0;
text_family(ui, title, 17.0, theme::TEXT, theme::semibold());
ui.add(egui::Label::new(RichText::new(body).size(14.0).color(theme::SUBTEXT)).wrap());
ui.add_space(12.0);
add(ui);
});
});
}
pub fn segmented<T: PartialEq + Copy>(ui: &mut Ui, current: &mut T, options: &[(T, &str)]) {
Frame::new()
.fill(theme::SURFACE)
.stroke(Stroke::new(1.0, theme::BORDER))
.corner_radius(corner(theme::RADIUS_INPUT))
.inner_margin(Margin::same(3))
.show(ui, |ui| {
ui.spacing_mut().item_spacing.x = 3.0;
ui.horizontal(|ui| {
for (value, label) in options {
let selected = *current == *value;
let galley = ui.painter().layout_no_wrap(label.to_string(), theme::font(13.5, theme::medium()), Color32::WHITE);
let size = galley.size() + egui::vec2(24.0, 12.0);
let (rect, response) = ui.allocate_exact_size(size, Sense::click());
let fill = if selected { theme::SURFACE_HOVER } else if response.hovered() { theme::SURFACE_RAISED } else { Color32::TRANSPARENT };
let stroke = if selected { Stroke::new(1.0, theme::BORDER_STRONG) } else { Stroke::NONE };
ui.painter().rect(rect, corner(theme::RADIUS_SMALL), fill, stroke, StrokeKind::Inside);
let color = if selected { theme::TEXT } else { theme::SUBTEXT };
ui.painter().galley(rect.center() - galley.size() / 2.0, galley, color);
if response.hovered() { ui.ctx().set_cursor_icon(CursorIcon::PointingHand); }
if response.clicked() { *current = *value; }
}
});
});
}
fn paint_arrow(painter: &egui::Painter, center: egui::Pos2, size: f32, pointing: f32, stroke: Stroke) {
let half = size / 2.0;
let wing = size * 0.32;
let tip = center + egui::vec2(half * pointing, 0.0);
painter.line_segment([center - egui::vec2(half * pointing, 0.0), tip], stroke);
painter.line_segment([tip, tip + egui::vec2(-wing * pointing, -wing)], stroke);
painter.line_segment([tip, tip + egui::vec2(-wing * pointing, wing)], stroke);
}
pub fn arrow_right(ui: &mut Ui, color: Color32) {
let (rect, _) = ui.allocate_exact_size(egui::vec2(14.0, 14.0), Sense::hover());
paint_arrow(ui.painter(), rect.center(), 10.0, 1.0, Stroke::new(1.4, color));
}
pub fn chevron_right(ui: &mut Ui, color: Color32) {
let (rect, _) = ui.allocate_exact_size(egui::vec2(12.0, 14.0), Sense::hover());
let center = rect.center();
let stroke = Stroke::new(1.5, color);
ui.painter().line_segment([center + egui::vec2(-2.0, -4.0), center + egui::vec2(2.0, 0.0)], stroke);
ui.painter().line_segment([center + egui::vec2(2.0, 0.0), center + egui::vec2(-2.0, 4.0)], stroke);
}
pub fn back_link(ui: &mut Ui, label: &str) -> Response {
let galley = ui.painter().layout_no_wrap(label.to_string(), theme::font(13.0, theme::medium()), Color32::WHITE);
let (rect, response) = ui.allocate_exact_size(egui::vec2(galley.size().x + 20.0, galley.size().y.max(14.0)), Sense::click());
let color = if response.hovered() { theme::TEXT } else { theme::MUTED };
if response.hovered() { ui.ctx().set_cursor_icon(CursorIcon::PointingHand); }
paint_arrow(ui.painter(), egui::pos2(rect.left() + 6.0, rect.center().y), 10.0, -1.0, Stroke::new(1.4, color));
ui.painter().galley(egui::pos2(rect.left() + 20.0, rect.center().y - galley.size().y / 2.0), galley, color);
response
}
pub fn divider(ui: &mut Ui) {
let (rect, _) = ui.allocate_exact_size(egui::vec2(ui.available_width(), 1.0), Sense::hover());
ui.painter().rect_filled(rect, 0.0, theme::BORDER);
}
pub fn minimize_button(ui: &mut Ui) -> Response {
let (rect, response) = ui.allocate_exact_size(egui::vec2(30.0, 30.0), Sense::click());
let hovered = response.hovered();
if hovered {
ui.painter().rect_filled(rect, corner(theme::RADIUS_SMALL), theme::SURFACE_HOVER);
ui.ctx().set_cursor_icon(CursorIcon::PointingHand);
}
let color = if hovered { theme::TEXT } else { theme::SUBTEXT };
let center = rect.center();
let arm = 5.0;
ui.painter().line_segment([center + egui::vec2(-arm, 0.0), center + egui::vec2(arm, 0.0)], Stroke::new(1.6, color));
response
}
+150
View File
@@ -0,0 +1,150 @@
use anyhow::{bail, Context, Result};
use std::fs;
use std::path::PathBuf;
use std::process::Command;
pub const SCHEME: &str = "frislit";
const ICON_SVG: &[u8] = include_bytes!("../../packaging/frislit.svg");
pub fn exe() -> Result<String> {
let path = std::env::current_exe().context("Could not find the frislit binary")?;
Ok(path.to_string_lossy().to_string())
}
fn home() -> Result<PathBuf> {
dirs::home_dir().context("Could not find your home directory")
}
fn data_dir() -> Result<PathBuf> {
dirs::data_dir().context("Could not find your data directory")
}
fn desktop_file() -> Result<PathBuf> {
Ok(data_dir()?.join("applications").join("frislit.desktop"))
}
fn icon_file() -> Result<PathBuf> {
Ok(data_dir()?.join("icons").join("hicolor").join("scalable").join("apps").join("frislit.svg"))
}
fn app_bundle() -> Result<PathBuf> {
Ok(home()?.join("Applications").join("frislit.app"))
}
fn install_linux() -> Result<PathBuf> {
let icon = icon_file()?;
fs::create_dir_all(icon.parent().unwrap())?;
fs::write(&icon, ICON_SVG)?;
let file = desktop_file()?;
fs::create_dir_all(file.parent().unwrap())?;
fs::write(&file, format!(
"[Desktop Entry]\n\
Type=Application\n\
Name=frislit\n\
Comment=Share local ports through your own frislit server\n\
Exec={} gui %u\n\
Icon=frislit\n\
Terminal=false\n\
Categories=Network;Utility;\n\
MimeType=x-scheme-handler/{};\n",
exe()?, SCHEME,
))?;
let dir = file.parent().unwrap().to_string_lossy().to_string();
let _ = Command::new("update-desktop-database").arg(&dir).status();
let _ = Command::new("xdg-mime")
.args(["default", "frislit.desktop", &format!("x-scheme-handler/{SCHEME}")])
.status();
Ok(file)
}
fn install_macos() -> Result<PathBuf> {
let bundle = app_bundle()?;
if bundle.exists() { fs::remove_dir_all(&bundle)?; }
fs::create_dir_all(bundle.parent().unwrap())?;
let exe = exe()?;
let script = std::env::temp_dir().join("frislit-handler.applescript");
fs::write(&script, format!(
"on run\n\
\tdo shell script quoted form of \"{exe}\" & \" gui > /dev/null 2>&1 &\"\n\
end run\n\
on open location this_URL\n\
\tdo shell script quoted form of \"{exe}\" & \" gui \" & quoted form of this_URL & \" > /dev/null 2>&1 &\"\n\
end open location\n",
))?;
let status = Command::new("osacompile")
.args(["-o", &bundle.to_string_lossy(), &script.to_string_lossy()])
.status()
.context("osacompile is not available")?;
let _ = fs::remove_file(&script);
if !status.success() { bail!("osacompile could not build the handler app"); }
let plist = bundle.join("Contents").join("Info.plist");
for args in [
vec!["-insert", "CFBundleURLTypes", "-json", "[]"],
vec!["-insert", "CFBundleURLTypes.0", "-json", "{}"],
vec!["-insert", "CFBundleURLTypes.0.CFBundleURLName", "-string", "frislit"],
vec!["-insert", "CFBundleURLTypes.0.CFBundleURLSchemes", "-json", "[\"frislit\"]"],
vec!["-replace", "CFBundleIdentifier", "-string", "dev.frislit.cli"],
] {
let _ = Command::new("plutil").args(&args).arg(&plist).status();
}
let _ = Command::new("/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister")
.args(["-f", &bundle.to_string_lossy()])
.status();
Ok(bundle)
}
fn install_windows() -> Result<PathBuf> {
let key = format!("HKCU\\Software\\Classes\\{SCHEME}");
let exe = exe()?;
let command = format!("\"{exe}\" gui \"%1\"");
for args in [
vec![key.clone(), "/ve".into(), "/d".into(), format!("URL:{SCHEME}"), "/f".into()],
vec![key.clone(), "/v".into(), "URL Protocol".into(), "/d".into(), String::new(), "/f".into()],
vec![format!("{key}\\DefaultIcon"), "/ve".into(), "/d".into(), format!("{exe},0"), "/f".into()],
vec![format!("{key}\\shell\\open\\command"), "/ve".into(), "/d".into(), command.clone(), "/f".into()],
] {
let status = Command::new("reg").arg("add").args(&args).status()
.context("Could not run reg.exe")?;
if !status.success() { bail!("reg.exe refused to write {key}"); }
}
Ok(PathBuf::from(key))
}
pub fn install() -> Result<PathBuf> {
if cfg!(target_os = "macos") {
install_macos()
} else if cfg!(target_os = "windows") {
install_windows()
} else if cfg!(target_os = "linux") {
install_linux()
} else {
bail!("frislit does not know how to register links on this system")
}
}
pub fn remove() -> Result<()> {
if cfg!(target_os = "macos") {
let bundle = app_bundle()?;
if bundle.exists() { fs::remove_dir_all(&bundle)?; }
} else if cfg!(target_os = "windows") {
let _ = Command::new("reg")
.args(["delete", &format!("HKCU\\Software\\Classes\\{SCHEME}"), "/f"])
.status();
} else {
let file = desktop_file()?;
if file.exists() { fs::remove_file(&file)?; }
let icon = icon_file()?;
if icon.exists() { let _ = fs::remove_file(&icon); }
let _ = Command::new("update-desktop-database")
.arg(file.parent().unwrap().to_string_lossy().to_string())
.status();
}
Ok(())
}
+173
View File
@@ -0,0 +1,173 @@
use anyhow::{bail, Context, Result};
use console::style;
use serde::Deserialize;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use tokio::sync::mpsc::UnboundedReceiver;
use crate::config::Config;
use crate::session::{self, Stop, StopHandle, TunnelEvent};
use crate::shape::Shape;
use crate::router::{Route, RouteTarget};
use crate::tunnel::{self, Access, Options, Rules, Target, TargetSpec};
pub const EXAMPLE: &str = "tunnels:\n myapp:\n http: 3000\n db:\n tcp: 5432\n allow: [10.0.0.0/8]\n";
#[derive(Deserialize)]
struct Manifest {
#[serde(default)]
tunnels: BTreeMap<String, Entry>,
}
#[derive(Deserialize)]
#[serde(untagged)]
enum Scalar { Number(f64), Text(String) }
impl Scalar {
fn text(&self) -> String {
match self { Self::Number(value) => value.to_string(), Self::Text(text) => text.clone() }
}
}
#[derive(Deserialize, Default)]
#[serde(deny_unknown_fields)]
struct ShapeSpec {
latency: Option<Scalar>,
jitter: Option<Scalar>,
bandwidth: Option<Scalar>,
loss: Option<Scalar>,
}
impl ShapeSpec {
fn shape(&self) -> Result<Shape> {
let text = |value: &Option<Scalar>| value.as_ref().map(Scalar::text);
Shape::parse(text(&self.latency).as_deref(), text(&self.jitter).as_deref(), text(&self.bandwidth).as_deref(), text(&self.loss).as_deref())
}
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Entry {
http: Option<Scalar>,
serve: Option<PathBuf>,
tcp: Option<Scalar>,
#[serde(default)] routes: BTreeMap<String, Scalar>,
#[serde(default)] shape: ShapeSpec,
#[serde(default)] keep_host: bool,
#[serde(default)] allow: Vec<String>,
#[serde(default)] allow_countries: Vec<String>,
#[serde(default)] block_ips: Vec<String>,
#[serde(default)] block_countries: Vec<String>,
#[serde(default)] block: Vec<String>,
password: Option<String>,
#[serde(default)] require_login: bool,
}
impl Entry {
fn options(self, name: &str) -> Result<Options> {
let rules = Rules::new(self.allow, self.allow_countries, self.block_ips, self.block_countries, self.block).with_context(|| name.to_string())?;
let access = Access::new(rules, self.password, self.require_login)?;
let shape = self.shape.shape().with_context(|| name.to_string())?;
let id = Some(name.to_string());
let root = match (self.http, self.serve, self.tcp) {
(Some(http), None, None) => RouteTarget::Addr(Target::parse(&http.text())?),
(None, Some(dir), None) => RouteTarget::dir(&dir.to_string_lossy())?,
(None, None, Some(tcp)) => {
if !self.routes.is_empty() { bail!("{name}: routes only work with http or serve"); }
return Ok(Options::tcp(Target::parse(&tcp.text())?, id, access).shaped(shape));
}
_ => bail!("{name}: set exactly one of http, serve or tcp"),
};
let routes = self.routes.into_iter().map(|(prefix, endpoint)| Route::new(&prefix, RouteTarget::parse(&endpoint.text())?)).collect::<Result<_>>()?;
Ok(Options::http(TargetSpec::routed(root, routes)?, id, self.keep_host, access).shaped(shape))
}
}
pub fn default_path() -> Result<PathBuf> {
Ok(dirs::config_dir().context("No config directory")?.join("frislit").join("tunnels.yml"))
}
pub fn load(path: &Path) -> Result<Vec<(String, Options)>> {
let text = std::fs::read_to_string(path).with_context(|| format!("Could not read {}", path.display()))?;
let manifest: Manifest = serde_yaml_ng::from_str(&text).with_context(|| format!("{} is not valid", path.display()))?;
if manifest.tunnels.is_empty() { bail!("{} defines no tunnels", path.display()); }
manifest.tunnels.into_iter().map(|(name, entry)| Ok((name.clone(), entry.options(&name)?))).collect()
}
fn log(name: &str, message: impl std::fmt::Display) {
println!("{} {message}", style(format!("[{name}]")).cyan().bold());
}
async fn print(name: String, mut rx: UnboundedReceiver<TunnelEvent>) {
while let Some(event) = rx.recv().await {
match event {
TunnelEvent::Connecting => {}
TunnelEvent::Online(online) | TunnelEvent::Replaced(online) => {
match &online.url {
Some(url) => log(&name, format!("online {}", style(url).underlined())),
None => log(&name, format!("online, share code {}", online.share_code.as_deref().unwrap_or(""))),
}
for url in &online.custom_urls { log(&name, format!(" {}", style(url).underlined())); }
if let Some(access) = &online.access { log(&name, format!("access: {access}")); }
}
TunnelEvent::Resumed(_) => log(&name, "reconnected"),
TunnelEvent::Request(request) => {
let intel = request.intel().map(|text| format!(" {text}")).unwrap_or_default();
log(&name, format!("{} {} {} {}ms{intel}", request.method, request.status, request.path, request.duration));
}
TunnelEvent::Connection(connection) => log(&name, connection.line()),
TunnelEvent::Access(summary) => log(&name, format!("access: {summary}")),
TunnelEvent::Reconnecting { seconds, reason } => match reason {
Some(reason) => log(&name, format!("reconnecting in {seconds}s ({reason})")),
None => log(&name, "connection lost, reconnecting"),
},
TunnelEvent::Update(version) => log(&name, format!("frislit {version} is available, run frislit update")),
TunnelEvent::Stopped => log(&name, "stopped"),
TunnelEvent::Ended(reason) => log(&name, format!("ended: {reason}")),
}
}
}
async fn wait_for_signal(stop: StopHandle) {
#[cfg(unix)]
{
use tokio::signal::unix::{signal, SignalKind};
let mut term = signal(SignalKind::terminate()).expect("SIGTERM handler");
tokio::select! {
_ = tokio::signal::ctrl_c() => {}
_ = term.recv() => {}
}
}
#[cfg(not(unix))]
{ let _ = tokio::signal::ctrl_c().await; }
stop.stop();
}
pub async fn run(path: Option<PathBuf>) -> Result<()> {
let path = match path { Some(path) => path, None => default_path()? };
Config::load()?.require_auth()?;
let tunnels = load(&path)?;
println!("{} Starting {} tunnel{} from {}", style("✓").green().bold(), tunnels.len(), if tunnels.len() == 1 { "" } else { "s" }, style(path.display()).dim());
let (handle, _) = Stop::new();
tokio::spawn(wait_for_signal(handle.clone()));
let mut tasks = Vec::new();
for (name, opts) in tunnels {
let (events, rx) = session::channel();
let stop = Stop::subscribe(&handle);
let printer = tokio::spawn(print(name.clone(), rx));
tasks.push(tokio::spawn(async move {
let result = async {
let (opts, target, _, _local) = tunnel::prepare(opts).await?;
tunnel::run(opts, target, events, stop).await
}.await;
if let Err(err) = &result { log(&name, format!("{} {err:#}", style("failed:").red())); }
let _ = printer.await;
result.is_ok()
}));
}
let mut ok = true;
for task in tasks { ok &= task.await.unwrap_or(false); }
if ok { Ok(()) } else { bail!("Not every tunnel came up") }
}
+210
View File
@@ -0,0 +1,210 @@
mod api;
mod auth;
mod cli;
mod config;
mod connect;
#[cfg(feature = "gui")]
mod gui;
mod handler;
mod headless;
mod mux;
mod qr;
mod router;
mod serve;
mod service;
mod session;
mod shape;
mod tcp;
mod tls;
mod tui;
mod tunnel;
mod update;
use clap::{Parser, Subcommand};
use console::style;
use std::path::PathBuf;
#[derive(Parser)]
#[command(name = "frislit", about = "frislit CLI - expose local ports through your own frislit server", version)]
struct Cli {
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand)]
enum Commands {
Login {
link: Option<String>,
#[arg(long, value_name = "KEY", help = "Link with an API key instead of the browser")] token: Option<String>,
#[arg(short, long)] server: Option<String>,
},
Logout,
Http {
target: String,
#[arg(short, long)] name: Option<String>,
#[arg(long, value_name = "PATH|SUBDOMAIN", help = "Forwarding style for this tunnel (default: the server setting)")] mode: Option<String>,
#[arg(long, value_name = "PREFIX=TARGET")] route: Vec<String>,
#[arg(long)] keep_host: bool,
#[command(flatten)] rules: RuleArgs,
#[arg(long, value_name = "PASSWORD")] password: Option<String>,
#[arg(long)] require_login: bool,
#[command(flatten)] shape: ShapeArgs,
#[arg(long, help = "Print plain log lines instead of the terminal UI")] plain: bool,
},
Serve {
#[arg(default_value = ".")] dir: String,
#[arg(short, long)] name: Option<String>,
#[arg(long, value_name = "PATH|SUBDOMAIN", help = "Forwarding style for this tunnel (default: the server setting)")] mode: Option<String>,
#[command(flatten)] rules: RuleArgs,
#[arg(long, value_name = "PASSWORD")] password: Option<String>,
#[arg(long)] require_login: bool,
#[command(flatten)] shape: ShapeArgs,
#[arg(long, help = "Print plain log lines instead of the terminal UI")] plain: bool,
},
Tcp {
target: String,
#[arg(short, long)] name: Option<String>,
#[command(flatten)] rules: RuleArgs,
#[command(flatten)] shape: ShapeArgs,
#[arg(long, help = "Print plain log lines instead of the terminal UI")] plain: bool,
},
Connect {
target: String,
#[arg(short, long)] port: Option<u16>,
#[arg(short, long, default_value = "127.0.0.1")] bind: String,
#[arg(short, long)] server: Option<String>,
},
#[command(alias = "status")]
Ls,
Start {
#[arg(short, long, value_name = "FILE")] config: Option<PathBuf>,
},
Service {
#[command(subcommand)]
action: ServiceAction,
},
#[cfg(feature = "gui")]
Gui {
link: Option<String>,
#[arg(long)] hidden: bool,
},
Config {
#[command(subcommand)]
action: ConfigAction,
},
Update,
Links {
#[command(subcommand)]
action: LinkAction,
},
}
#[derive(clap::Args)]
struct RuleArgs {
#[arg(long, value_name = "CIDR")] allow: Vec<String>,
#[arg(long, value_name = "CODE")] allow_country: Vec<String>,
#[arg(long, value_name = "CIDR")] block_ip: Vec<String>,
#[arg(long, value_name = "CODE")] block_country: Vec<String>,
#[arg(long, value_name = "CATEGORY", help = "tor, vpn, datacenter or blocklist")] block: Vec<String>,
}
impl RuleArgs {
fn parse(self) -> anyhow::Result<tunnel::Rules> {
tunnel::Rules::new(self.allow, self.allow_country, self.block_ip, self.block_country, self.block)
}
}
#[derive(clap::Args)]
struct ShapeArgs {
#[arg(long, value_name = "DURATION")] latency: Option<String>,
#[arg(long, value_name = "DURATION")] jitter: Option<String>,
#[arg(long, value_name = "RATE")] bandwidth: Option<String>,
#[arg(long, value_name = "PERCENT")] loss: Option<String>,
}
impl ShapeArgs {
fn parse(&self) -> anyhow::Result<shape::Shape> {
shape::Shape::parse(self.latency.as_deref(), self.jitter.as_deref(), self.bandwidth.as_deref(), self.loss.as_deref())
}
}
#[derive(Subcommand)]
enum ServiceAction {
Install,
Uninstall,
}
#[derive(Subcommand)]
enum LinkAction {
Register,
Forget,
}
#[derive(Subcommand)]
enum ConfigAction {
Set { key: String, value: String },
Get { key: String },
Show,
}
fn main() {
tls::install_provider();
if cfg!(windows) { update::cleanup(); }
let cli = Cli::parse();
let runtime = tokio::runtime::Builder::new_multi_thread().worker_threads(4).enable_all().build().unwrap_or_else(|err| fail(err.into()));
#[cfg(feature = "gui")]
if let Commands::Gui { link, hidden } = cli.command {
gui::launch(runtime.handle().clone(), link, hidden).unwrap_or_else(|err| fail(err));
return;
}
runtime.block_on(run(cli)).unwrap_or_else(|err| fail(err));
}
fn fail(err: anyhow::Error) -> ! {
eprintln!("{} {err:#}", style("✗").red().bold());
std::process::exit(1)
}
async fn run(cli: Cli) -> anyhow::Result<()> {
match cli.command {
Commands::Login { link, token, server } => cli::login(link, token, server).await,
Commands::Logout => cli::logout(),
Commands::Http { target, name, mode, route, keep_host, rules, password, require_login, shape, plain } =>
cli::tunnel(tunnel::Options::http(tunnel::TargetSpec::with_routes(&target, &route)?, name, keep_host, tunnel::Access::new(rules.parse()?, password, require_login)?).http_mode(mode).shaped(shape.parse()?), plain).await,
Commands::Serve { dir, name, mode, rules, password, require_login, shape, plain } =>
cli::tunnel(tunnel::Options::http(tunnel::TargetSpec::dir(&dir)?, name, false, tunnel::Access::new(rules.parse()?, password, require_login)?).http_mode(mode).shaped(shape.parse()?), plain).await,
Commands::Tcp { target, name, rules, shape, plain } =>
cli::tunnel(tunnel::Options::tcp(tunnel::Target::parse(&target)?, name, tunnel::Access::new(rules.parse()?, None, false)?).shaped(shape.parse()?), plain).await,
Commands::Connect { target, port, bind, server } => cli::connect(target, port, bind, server).await,
Commands::Ls => cli::list().await,
Commands::Start { config } => headless::run(config).await,
Commands::Service { action } => match action {
ServiceAction::Install => service::install(),
ServiceAction::Uninstall => service::uninstall(),
},
#[cfg(feature = "gui")]
Commands::Gui { .. } => unreachable!("handled before the runtime starts"),
Commands::Links { action } => match action {
LinkAction::Register => {
let where_ = handler::install()?;
println!("{} {} links now open in this frislit", style("✓").green().bold(), style(format!("{}://", handler::SCHEME)).cyan().bold());
println!(" {}", style(where_.to_string_lossy()).dim());
println!(" Your browser will ask before it opens one.");
Ok(())
}
LinkAction::Forget => {
handler::remove()?;
println!("{} {} links are no longer handled by frislit", style("✓").green().bold(), style(format!("{}://", handler::SCHEME)).bold());
Ok(())
}
},
Commands::Update => cli::update().await,
Commands::Config { action } => match action {
ConfigAction::Set { key, value } => config::set(&key, &value),
ConfigAction::Get { key } => config::get(&key),
ConfigAction::Show => config::show(),
},
}
}
+332
View File
@@ -0,0 +1,332 @@
use anyhow::{anyhow, bail, Context, Result};
use futures_util::{SinkExt, StreamExt};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::sync::{mpsc, Notify};
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
use tokio_tungstenite::tungstenite::Message;
use tokio_tungstenite::{connect_async_tls_with_config, Connector};
pub const WINDOW: u32 = 1024 * 1024;
pub const CHUNK: usize = 64 * 1024;
const ACK_THRESHOLD: u32 = 256 * 1024;
const PING_INTERVAL: Duration = Duration::from_secs(20);
const DEAD_AFTER: Duration = Duration::from_secs(60);
const OPEN: u8 = 0x01;
const DATA: u8 = 0x02;
const CLOSE: u8 = 0x03;
const WINDOW_UPDATE: u8 = 0x04;
const DATAGRAM: u8 = 0x05;
const RESET: u8 = 0x06;
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct OpenMeta {
#[serde(default)] pub protocol: String,
#[serde(default)] pub remote: String,
}
impl OpenMeta {
pub fn tcp(remote: impl Into<String>) -> Self { Self { protocol: "tcp".into(), remote: remote.into() } }
pub fn udp(remote: impl Into<String>) -> Self { Self { protocol: "udp".into(), remote: remote.into() } }
pub fn is_udp(&self) -> bool { self.protocol == "udp" }
}
#[derive(Debug)]
pub enum Incoming {
Data(Vec<u8>),
Datagram(Vec<u8>),
Close,
Reset,
}
fn encode(kind: u8, id: u32, payload: &[u8]) -> Vec<u8> {
let mut frame = Vec::with_capacity(5 + payload.len());
frame.push(kind);
frame.extend_from_slice(&id.to_be_bytes());
frame.extend_from_slice(payload);
frame
}
struct Credit {
available: Mutex<i64>,
notify: Notify,
}
impl Credit {
fn new() -> Self { Self { available: Mutex::new(WINDOW as i64), notify: Notify::new() } }
fn add(&self, n: u32) {
*self.available.lock().unwrap() += n as i64;
self.notify.notify_waiters();
}
async fn take(&self, n: usize, dead: &AtomicBool) -> bool {
loop {
if dead.load(Ordering::Relaxed) { return false; }
{
let mut avail = self.available.lock().unwrap();
if *avail >= n as i64 { *avail -= n as i64; return true; }
}
let notified = self.notify.notified();
if dead.load(Ordering::Relaxed) { return false; }
let _ = tokio::time::timeout(Duration::from_millis(500), notified).await;
}
}
}
struct Shared {
id: u32,
mux: Arc<Mux>,
credit: Credit,
dead: AtomicBool,
close_sent: AtomicBool,
close_received: AtomicBool,
}
impl Drop for Shared {
fn drop(&mut self) {
self.mux.forget(self.id);
let clean = self.close_sent.load(Ordering::Relaxed) && self.close_received.load(Ordering::Relaxed);
if !self.dead.load(Ordering::Relaxed) && !clean {
self.mux.try_send(Message::Binary(encode(RESET, self.id, &[]).into()));
}
}
}
#[derive(Clone)]
pub struct MuxWriter { shared: Arc<Shared> }
pub struct MuxReader { shared: Arc<Shared>, rx: mpsc::UnboundedReceiver<Incoming>, unacked: u32 }
impl MuxWriter {
pub async fn send(&self, data: &[u8]) -> Result<()> {
for chunk in data.chunks(CHUNK) {
if !self.shared.credit.take(chunk.len(), &self.shared.dead).await { bail!("stream closed"); }
self.shared.mux.send(Message::Binary(encode(DATA, self.shared.id, chunk).into())).await?;
}
Ok(())
}
pub async fn send_datagram(&self, data: &[u8]) -> Result<()> {
if data.len() > 65507 { return Ok(()); }
if self.shared.dead.load(Ordering::Relaxed) { bail!("stream closed"); }
self.shared.mux.send(Message::Binary(encode(DATAGRAM, self.shared.id, data).into())).await
}
pub async fn close(&self) {
if self.shared.dead.load(Ordering::Relaxed) || self.shared.close_sent.swap(true, Ordering::Relaxed) { return; }
let _ = self.shared.mux.send(Message::Binary(encode(CLOSE, self.shared.id, &[]).into())).await;
}
pub fn reset(&self) {
if self.shared.dead.swap(true, Ordering::Relaxed) { return; }
self.shared.mux.try_send(Message::Binary(encode(RESET, self.shared.id, &[]).into()));
}
}
impl MuxReader {
fn ack(&mut self) {
if self.unacked == 0 || self.shared.dead.load(Ordering::Relaxed) { return; }
let n = self.unacked;
self.unacked = 0;
self.shared.mux.try_send(Message::Binary(encode(WINDOW_UPDATE, self.shared.id, &n.to_be_bytes()).into()));
}
pub async fn recv(&mut self) -> Incoming {
if self.unacked >= ACK_THRESHOLD { self.ack(); }
match self.rx.recv().await {
Some(Incoming::Data(d)) => {
self.unacked += d.len() as u32;
Incoming::Data(d)
}
Some(Incoming::Close) => {
self.shared.close_received.store(true, Ordering::Relaxed);
Incoming::Close
}
Some(Incoming::Reset) | None => {
self.shared.dead.store(true, Ordering::Relaxed);
Incoming::Reset
}
Some(other) => other,
}
}
}
struct Entry {
tx: mpsc::UnboundedSender<Incoming>,
shared: std::sync::Weak<Shared>,
}
pub struct Mux {
out: mpsc::Sender<Message>,
streams: Mutex<HashMap<u32, Entry>>,
next_id: AtomicU32,
closed: AtomicBool,
}
pub struct MuxEvents {
pub control: mpsc::Receiver<Value>,
pub streams: mpsc::Receiver<(MuxWriter, MuxReader, OpenMeta)>,
}
impl Mux {
pub async fn connect(url: &str, token: Option<&str>, accept_invalid_certs: bool) -> Result<(Arc<Mux>, MuxEvents)> {
let mut request = url.into_client_request().context("Invalid server URL")?;
if let Some(token) = token {
request.headers_mut().insert("Authorization", format!("Bearer {token}").parse()?);
}
let connector = Some(Connector::Rustls(crate::tls::client_config(accept_invalid_certs)?));
let (ws, _) = connect_async_tls_with_config(request, None, true, connector).await
.map_err(|e| anyhow!("Could not connect to {url}: {e}"))?;
let (mut sink, mut source) = ws.split();
let (out_tx, mut out_rx) = mpsc::channel::<Message>(256);
let (control_tx, control_rx) = mpsc::channel::<Value>(64);
let (stream_tx, stream_rx) = mpsc::channel(64);
let mux = Arc::new(Mux { out: out_tx, streams: Mutex::new(HashMap::new()), next_id: AtomicU32::new(1), closed: AtomicBool::new(false) });
tokio::spawn(async move {
while let Some(msg) = out_rx.recv().await {
if sink.send(msg).await.is_err() { break; }
}
let _ = sink.close().await;
});
let ping_out = mux.out.clone();
tokio::spawn(async move {
loop {
tokio::time::sleep(PING_INTERVAL).await;
if ping_out.send(Message::Text(r#"{"type":"ping"}"#.into())).await.is_err() { break; }
}
});
let reader_mux = mux.clone();
tokio::spawn(async move {
loop {
let msg = match tokio::time::timeout(DEAD_AFTER, source.next()).await {
Ok(Some(Ok(msg))) => msg,
_ => break,
};
match msg {
Message::Text(text) => {
let Ok(value) = serde_json::from_str::<Value>(&text) else { continue };
match value.get("type").and_then(|t| t.as_str()) {
Some("ping") => { let _ = reader_mux.out.send(Message::Text(r#"{"type":"pong"}"#.into())).await; }
Some("pong") => {}
Some(_) => { if control_tx.send(value).await.is_err() { break; } }
None => {}
}
}
Message::Binary(data) => {
if data.len() < 5 { continue; }
let kind = data[0];
let id = u32::from_be_bytes([data[1], data[2], data[3], data[4]]);
let payload = &data[5..];
if kind == OPEN {
let meta: OpenMeta = serde_json::from_slice(payload).unwrap_or_default();
let (writer, reader) = reader_mux.register(id);
if stream_tx.send((writer, reader, meta)).await.is_err() { break; }
continue;
}
let (tx, shared) = {
let streams = reader_mux.streams.lock().unwrap();
match streams.get(&id) { Some(e) => (e.tx.clone(), e.shared.upgrade()), None => continue }
};
match kind {
DATA => { let _ = tx.send(Incoming::Data(payload.to_vec())); }
DATAGRAM => { let _ = tx.send(Incoming::Datagram(payload.to_vec())); }
CLOSE => { let _ = tx.send(Incoming::Close); }
RESET => {
if let Some(s) = shared { s.dead.store(true, Ordering::Relaxed); }
let _ = tx.send(Incoming::Reset);
reader_mux.forget(id);
}
WINDOW_UPDATE => {
if payload.len() >= 4 {
if let Some(s) = shared { s.credit.add(u32::from_be_bytes([payload[0], payload[1], payload[2], payload[3]])); }
}
}
_ => {}
}
}
Message::Close(_) => break,
_ => {}
}
}
reader_mux.shutdown();
});
Ok((mux, MuxEvents { control: control_rx, streams: stream_rx }))
}
fn register(self: &Arc<Self>, id: u32) -> (MuxWriter, MuxReader) {
let (tx, rx) = mpsc::unbounded_channel();
let shared = Arc::new(Shared {
id, mux: self.clone(), credit: Credit::new(),
dead: AtomicBool::new(false), close_sent: AtomicBool::new(false), close_received: AtomicBool::new(false),
});
self.streams.lock().unwrap().insert(id, Entry { tx, shared: Arc::downgrade(&shared) });
(MuxWriter { shared: shared.clone() }, MuxReader { shared, rx, unacked: 0 })
}
pub async fn open(self: &Arc<Self>, meta: &OpenMeta) -> Result<(MuxWriter, MuxReader)> {
if self.closed.load(Ordering::Relaxed) { bail!("not connected"); }
let id = self.next_id.fetch_add(2, Ordering::Relaxed);
let (writer, reader) = self.register(id);
self.send(Message::Binary(encode(OPEN, id, serde_json::to_vec(meta)?.as_slice()).into())).await?;
Ok((writer, reader))
}
pub async fn send_control(&self, message: Value) -> Result<()> {
self.send(Message::Text(message.to_string().into())).await
}
pub async fn close(&self) {
let _ = self.out.send(Message::Close(None)).await;
self.shutdown();
}
async fn send(&self, msg: Message) -> Result<()> {
if self.closed.load(Ordering::Relaxed) { bail!("connection closed"); }
self.out.send(msg).await.map_err(|_| anyhow!("connection closed"))
}
fn try_send(&self, msg: Message) {
if self.closed.load(Ordering::Relaxed) { return; }
let out = self.out.clone();
tokio::spawn(async move { let _ = out.send(msg).await; });
}
fn forget(&self, id: u32) {
self.streams.lock().unwrap().remove(&id);
}
fn shutdown(&self) {
self.closed.store(true, Ordering::Relaxed);
let entries: Vec<Entry> = self.streams.lock().unwrap().drain().map(|(_, e)| e).collect();
for entry in entries {
if let Some(shared) = entry.shared.upgrade() { shared.dead.store(true, Ordering::Relaxed); }
let _ = entry.tx.send(Incoming::Reset);
}
}
}
pub async fn expect(events: &mut MuxEvents, expected: &str) -> Result<Value> {
match events.control.recv().await {
Some(msg) => {
let kind = msg.get("type").and_then(|t| t.as_str()).unwrap_or("");
if kind == "error" {
let message = msg.get("message").and_then(|m| m.as_str()).unwrap_or("unknown error");
let code = msg.get("code").and_then(|m| m.as_str()).unwrap_or("error");
bail!("{message} ({code})");
}
if kind != expected { bail!("Unexpected message from server: {kind}"); }
Ok(msg)
}
None => bail!("Connection closed by server"),
}
}
+21
View File
@@ -0,0 +1,21 @@
use qrcode::render::unicode;
use qrcode::QrCode;
pub fn print(text: &str) {
let Ok(code) = QrCode::new(text.as_bytes()) else { return };
let rendered = code.render::<unicode::Dense1x2>().dark_color(unicode::Dense1x2::Light).light_color(unicode::Dense1x2::Dark).quiet_zone(true).build();
for line in rendered.lines() { println!(" {line}"); }
}
pub fn copy(text: &str) -> bool {
let Ok(mut clip) = arboard::Clipboard::new() else { return false };
let text = text.to_string();
#[cfg(target_os = "linux")]
{
use arboard::SetExtLinux;
std::thread::spawn(move || { let _ = clip.set().wait().text(text); });
true
}
#[cfg(not(target_os = "linux"))]
clip.set_text(text).is_ok()
}
+168
View File
@@ -0,0 +1,168 @@
use crate::session::Task;
use anyhow::{bail, Result};
use bytes::Bytes;
use http_body_util::{combinators::BoxBody, BodyExt, Empty};
use hyper::body::Incoming;
use hyper::header::{HeaderValue, CONNECTION, UPGRADE};
use hyper::server::conn::http1;
use hyper::service::service_fn;
use hyper::{Request, Response, StatusCode};
use hyper_util::rt::TokioIo;
use std::path::PathBuf;
use std::sync::Arc;
use tokio::io::{AsyncRead, AsyncWrite};
use tokio::net::TcpListener;
use crate::serve;
use crate::tunnel::{connect_target, Target};
#[derive(Clone)]
pub enum RouteTarget { Addr(Target), Dir(PathBuf) }
#[derive(Clone)]
pub struct Route { pub prefix: String, pub target: RouteTarget }
impl Route {
pub fn parse(raw: &str) -> Result<Self> {
let Some((prefix, target)) = raw.split_once('=') else { bail!("Invalid route \"{raw}\": use <prefix>=<target>") };
Ok(Self { prefix: normalize(prefix)?, target: RouteTarget::parse(target)? })
}
pub fn new(prefix: &str, target: RouteTarget) -> Result<Self> {
Ok(Self { prefix: normalize(prefix)?, target })
}
}
impl RouteTarget {
pub fn parse(raw: &str) -> Result<Self> {
let path = std::path::Path::new(raw);
if path.is_dir() { return Ok(Self::Dir(path.to_path_buf())); }
Ok(Self::Addr(Target::parse(raw)?))
}
pub fn dir(raw: &str) -> Result<Self> {
let path = std::path::Path::new(raw);
if !path.exists() { bail!("\"{raw}\" does not exist"); }
if !path.is_dir() { bail!("\"{raw}\" is not a directory - use `frislit http {raw}` for a port or host:port"); }
Ok(Self::Dir(path.to_path_buf()))
}
pub fn label(&self) -> String {
match self { Self::Addr(target) => target.label(), Self::Dir(dir) => dir.display().to_string() }
}
}
fn normalize(prefix: &str) -> Result<String> {
let trimmed = prefix.trim().trim_end_matches('/');
if trimmed.is_empty() { return Ok("/".into()); }
if !trimmed.starts_with('/') { bail!("Route prefix \"{prefix}\" must start with /"); }
Ok(trimmed.to_string())
}
struct Mounted { prefix: String, target: Target, strip: bool }
impl Mounted {
fn matches(&self, path: &str) -> bool {
self.prefix == "/" || (path.starts_with(&self.prefix) && matches!(path.as_bytes().get(self.prefix.len()), None | Some(b'/')))
}
fn rest<'a>(&self, path: &'a str) -> &'a str {
if !self.strip || self.prefix == "/" { return path; }
match &path[self.prefix.len()..] { "" => "/", rest => rest }
}
}
struct Table { routes: Vec<Mounted> }
impl Table {
fn pick(&self, path: &str) -> &Mounted {
self.routes.iter().filter(|route| route.matches(path)).max_by_key(|route| route.prefix.len()).expect("the root route always matches")
}
}
pub async fn start(routes: Vec<Route>) -> Result<(u16, Task)> {
let mut mounted = Vec::new();
let mut servers = Vec::new();
for route in routes {
let (target, strip) = match route.target {
RouteTarget::Addr(target) => (target, false),
RouteTarget::Dir(dir) => {
let (port, server) = serve::start(dir).await?;
servers.push(server);
(Target { host: "127.0.0.1".into(), port, tls: false }, true)
}
};
mounted.push(Mounted { prefix: route.prefix, target, strip });
}
let table = Arc::new(Table { routes: mounted });
let listener = TcpListener::bind("127.0.0.1:0").await?;
let port = listener.local_addr()?.port();
let task = tokio::spawn(async move {
let _servers = servers;
loop {
let Ok((socket, _)) = listener.accept().await else { continue };
let table = table.clone();
tokio::spawn(async move {
let service = service_fn(move |req| handle(req, table.clone()));
let _ = http1::Builder::new().preserve_header_case(true).serve_connection(TokioIo::new(socket), service).with_upgrades().await;
});
}
});
Ok((port, Task(task)))
}
type Body = BoxBody<Bytes, hyper::Error>;
fn status(code: StatusCode) -> Response<Body> {
Response::builder().status(code).body(Empty::new().map_err(|never| match never {}).boxed()).unwrap()
}
async fn connect(target: &Target) -> Result<Box<dyn Stream>> {
let socket = connect_target(&target.resolve().await?).await?;
if !target.tls { return Ok(Box::new(socket)); }
Ok(Box::new(crate::tls::connect_trusting(&target.host, socket).await?))
}
trait Stream: AsyncRead + AsyncWrite + Unpin + Send {}
impl<T: AsyncRead + AsyncWrite + Unpin + Send> Stream for T {}
async fn handle(mut req: Request<Incoming>, table: Arc<Table>) -> Result<Response<Body>, hyper::Error> {
let path = req.uri().path().to_string();
let route = table.pick(&path);
if route.strip {
let rest = route.rest(&path);
let uri = match req.uri().query() { Some(query) => format!("{rest}?{query}"), None => rest.to_string() };
let Ok(parsed) = uri.parse() else { return Ok(status(StatusCode::BAD_REQUEST)) };
*req.uri_mut() = parsed;
}
let Ok(stream) = connect(&route.target).await else { return Ok(status(StatusCode::BAD_GATEWAY)) };
let Ok((mut sender, conn)) = hyper::client::conn::http1::Builder::new().preserve_header_case(true).handshake(TokioIo::new(stream)).await
else { return Ok(status(StatusCode::BAD_GATEWAY)) };
tokio::spawn(async move { let _ = conn.with_upgrades().await; });
let upgrading = req.headers().get(UPGRADE).cloned();
let client_upgrade = upgrading.as_ref().map(|_| hyper::upgrade::on(&mut req));
let mut response = match sender.send_request(req).await {
Ok(response) => response,
Err(_) => return Ok(status(StatusCode::BAD_GATEWAY)),
};
if response.status() == StatusCode::SWITCHING_PROTOCOLS {
if let (Some(client), Some(upgrade)) = (client_upgrade, upgrading) {
let upstream = hyper::upgrade::on(&mut response);
tokio::spawn(async move {
if let (Ok(a), Ok(b)) = (client.await, upstream.await) {
let mut a = TokioIo::new(a);
let mut b = TokioIo::new(b);
let _ = tokio::io::copy_bidirectional(&mut a, &mut b).await;
}
});
response.headers_mut().insert(UPGRADE, upgrade);
response.headers_mut().insert(CONNECTION, HeaderValue::from_static("upgrade"));
}
}
Ok(response.map(|body| body.boxed()))
}
+190
View File
@@ -0,0 +1,190 @@
use anyhow::{Context, Result};
use std::path::{Path, PathBuf};
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::net::{TcpListener, TcpStream};
use crate::session::Task;
const MAX_HEADER_BYTES: usize = 16 * 1024;
pub async fn start(dir: PathBuf) -> Result<(u16, Task)> {
let dir = dir.canonicalize().with_context(|| format!("Cannot read directory {}", dir.display()))?;
let listener = TcpListener::bind("127.0.0.1:0").await?;
let port = listener.local_addr()?.port();
let task = tokio::spawn(async move {
loop {
let Ok((socket, _)) = listener.accept().await else { continue };
let dir = dir.clone();
tokio::spawn(async move { let _ = handle(socket, &dir).await; });
}
});
Ok((port, Task(task)))
}
async fn handle(socket: TcpStream, root: &Path) -> Result<()> {
let (rd, mut wr) = socket.into_split();
let mut reader = BufReader::new(rd);
let mut request_line = String::new();
reader.read_line(&mut request_line).await?;
let mut parts = request_line.split_whitespace();
let method = parts.next().unwrap_or("").to_string();
let raw_path = parts.next().unwrap_or("/").to_string();
let mut total = request_line.len();
loop {
let mut line = String::new();
let n = reader.read_line(&mut line).await?;
total += n;
if n == 0 || line == "\r\n" || line == "\n" || total > MAX_HEADER_BYTES { break; }
}
if method != "GET" && method != "HEAD" {
return respond(&mut wr, 405, "text/plain; charset=utf-8", b"Method Not Allowed", false).await;
}
let path_only = raw_path.split('?').next().unwrap_or("/");
let decoded = percent_decode(path_only);
let Some(target) = resolve(root, &decoded) else {
return respond(&mut wr, 404, "text/plain; charset=utf-8", b"Not Found", method == "HEAD").await;
};
if target.is_dir() {
if !path_only.ends_with('/') {
let location = format!("{}/", path_only);
let head = format!("HTTP/1.1 301 Moved Permanently\r\nLocation: {location}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
wr.write_all(head.as_bytes()).await?;
return Ok(());
}
let index = target.join("index.html");
if index.is_file() { return send_file(&mut wr, &index, method == "HEAD").await; }
let body = listing(&target, &decoded).await;
return respond(&mut wr, 200, "text/html; charset=utf-8", body.as_bytes(), method == "HEAD").await;
}
if target.is_file() { return send_file(&mut wr, &target, method == "HEAD").await; }
respond(&mut wr, 404, "text/plain; charset=utf-8", b"Not Found", method == "HEAD").await
}
fn resolve(root: &Path, request_path: &str) -> Option<PathBuf> {
let mut path = root.to_path_buf();
for segment in request_path.split('/') {
match segment {
"" | "." => {}
".." => return None,
s if s.contains('\\') || s.contains('\0') => return None,
s => path.push(s),
}
}
let resolved = path.canonicalize().ok()?;
if resolved.starts_with(root) { Some(resolved) } else { None }
}
async fn send_file(wr: &mut tokio::net::tcp::OwnedWriteHalf, path: &Path, head_only: bool) -> Result<()> {
let mut file = tokio::fs::File::open(path).await?;
let len = file.metadata().await?.len();
let mime = mime_for(path);
let head = format!("HTTP/1.1 200 OK\r\nContent-Type: {mime}\r\nContent-Length: {len}\r\nCache-Control: no-cache\r\nConnection: close\r\n\r\n");
wr.write_all(head.as_bytes()).await?;
if !head_only { tokio::io::copy(&mut file, wr).await?; }
wr.shutdown().await?;
Ok(())
}
async fn respond(wr: &mut tokio::net::tcp::OwnedWriteHalf, status: u16, mime: &str, body: &[u8], head_only: bool) -> Result<()> {
let reason = match status { 200 => "OK", 404 => "Not Found", 405 => "Method Not Allowed", _ => "Error" };
let head = format!("HTTP/1.1 {status} {reason}\r\nContent-Type: {mime}\r\nContent-Length: {}\r\nCache-Control: no-cache\r\nConnection: close\r\n\r\n", body.len());
wr.write_all(head.as_bytes()).await?;
if !head_only { wr.write_all(body).await?; }
wr.shutdown().await?;
Ok(())
}
async fn listing(dir: &Path, request_path: &str) -> String {
let mut entries = Vec::new();
if let Ok(mut read) = tokio::fs::read_dir(dir).await {
while let Ok(Some(entry)) = read.next_entry().await {
let name = entry.file_name().to_string_lossy().to_string();
let is_dir = entry.file_type().await.map(|t| t.is_dir()).unwrap_or(false);
let size = entry.metadata().await.map(|m| m.len()).unwrap_or(0);
entries.push((is_dir, name, size));
}
}
entries.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.to_lowercase().cmp(&b.1.to_lowercase())));
let title = escape(if request_path.is_empty() { "/" } else { request_path });
let mut html = format!("<!doctype html><html><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><title>Index of {title}</title><style>body{{font-family:system-ui,sans-serif;margin:2rem auto;max-width:48rem;padding:0 1rem;color:#222}}h1{{font-size:1.25rem}}table{{border-collapse:collapse;width:100%}}td{{padding:.35rem .5rem;border-bottom:1px solid #eee}}td.s{{text-align:right;color:#888;white-space:nowrap}}a{{color:#0d9488;text-decoration:none}}a:hover{{text-decoration:underline}}</style></head><body><h1>Index of {title}</h1><table>");
if request_path != "/" && !request_path.is_empty() {
html.push_str("<tr><td><a href=\"../\">../</a></td><td class=\"s\"></td></tr>");
}
for (is_dir, name, size) in entries {
let href = percent_encode(&name);
let (label, suffix) = if is_dir { (format!("{}/", escape(&name)), "/") } else { (escape(&name), "") };
let size_text = if is_dir { String::new() } else { human_size(size) };
html.push_str(&format!("<tr><td><a href=\"{href}{suffix}\">{label}</a></td><td class=\"s\">{size_text}</td></tr>"));
}
html.push_str("</table></body></html>");
html
}
fn human_size(bytes: u64) -> String {
const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"];
let mut value = bytes as f64;
let mut unit = 0;
while value >= 1024.0 && unit < UNITS.len() - 1 { value /= 1024.0; unit += 1; }
if unit == 0 { format!("{bytes} B") } else { format!("{value:.1} {}", UNITS[unit]) }
}
fn escape(text: &str) -> String {
text.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;")
}
fn percent_encode(text: &str) -> String {
let mut out = String::new();
for byte in text.bytes() {
match byte {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => out.push(byte as char),
_ => out.push_str(&format!("%{byte:02X}")),
}
}
out
}
fn percent_decode(text: &str) -> String {
let bytes = text.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%' && i + 2 < bytes.len() {
if let Ok(value) = u8::from_str_radix(&text[i + 1..i + 3], 16) { out.push(value); i += 3; continue; }
}
out.push(bytes[i]);
i += 1;
}
String::from_utf8_lossy(&out).to_string()
}
fn mime_for(path: &Path) -> &'static str {
match path.extension().and_then(|e| e.to_str()).map(|e| e.to_ascii_lowercase()).as_deref() {
Some("html") | Some("htm") => "text/html; charset=utf-8",
Some("css") => "text/css; charset=utf-8",
Some("js") | Some("mjs") => "text/javascript; charset=utf-8",
Some("json") => "application/json; charset=utf-8",
Some("md") | Some("txt") | Some("log") => "text/plain; charset=utf-8",
Some("xml") => "application/xml",
Some("svg") => "image/svg+xml",
Some("png") => "image/png",
Some("jpg") | Some("jpeg") => "image/jpeg",
Some("gif") => "image/gif",
Some("webp") => "image/webp",
Some("ico") => "image/x-icon",
Some("woff") => "font/woff",
Some("woff2") => "font/woff2",
Some("ttf") => "font/ttf",
Some("pdf") => "application/pdf",
Some("zip") => "application/zip",
Some("wasm") => "application/wasm",
Some("mp4") => "video/mp4",
Some("webm") => "video/webm",
Some("mp3") => "audio/mpeg",
_ => "application/octet-stream",
}
}
+207
View File
@@ -0,0 +1,207 @@
use crate::config::Config;
use crate::handler::exe;
use crate::headless;
use anyhow::{bail, Context, Result};
use console::style;
use std::fs;
use std::path::PathBuf;
use std::process::Command;
const NAME: &str = "frislit";
#[cfg(not(target_os = "windows"))]
fn run(program: &str, args: &[&str]) -> Result<()> {
let status = Command::new(program)
.args(args)
.status()
.with_context(|| format!("Could not run {program}"))?;
if !status.success() {
bail!("{program} {} failed", args.join(" "));
}
Ok(())
}
fn ensure_manifest() -> Result<PathBuf> {
let path = headless::default_path()?;
if path.exists() {
headless::load(&path)?;
return Ok(path);
}
fs::create_dir_all(path.parent().unwrap())?;
fs::write(&path, headless::EXAMPLE)?;
bail!(
"Wrote an example to {}. Edit it, then run `frislit service install` again",
path.display()
);
}
#[cfg(target_os = "linux")]
fn unit_path() -> Result<PathBuf> {
Ok(dirs::config_dir()
.context("No config directory")?
.join("systemd")
.join("user")
.join(format!("{NAME}.service")))
}
#[cfg(target_os = "linux")]
fn install_platform() -> Result<String> {
let path = unit_path()?;
fs::create_dir_all(path.parent().unwrap())?;
fs::write(&path, format!(
"[Unit]\nDescription=frislit tunnels\nAfter=network-online.target\nWants=network-online.target\n\n\
[Service]\nExecStart={} start\nRestart=on-failure\nRestartSec=5\n\n\
[Install]\nWantedBy=default.target\n",
exe()?,
))?;
run("systemctl", &["--user", "daemon-reload"])?;
run("systemctl", &["--user", "enable", "--now", NAME])?;
if let Ok(user) = std::env::var("USER") {
let _ = Command::new("loginctl")
.args(["enable-linger", &user])
.status();
}
Ok(format!(
"systemd user unit {}\n Logs: journalctl --user -u {NAME} -f",
path.display()
))
}
#[cfg(target_os = "linux")]
fn uninstall_platform() -> Result<()> {
let _ = Command::new("systemctl")
.args(["--user", "disable", "--now", NAME])
.status();
let path = unit_path()?;
if path.exists() {
fs::remove_file(path)?;
}
let _ = Command::new("systemctl")
.args(["--user", "daemon-reload"])
.status();
Ok(())
}
#[cfg(target_os = "macos")]
fn plist_path() -> Result<PathBuf> {
Ok(dirs::home_dir()
.context("No home directory")?
.join("Library")
.join("LaunchAgents")
.join("dev.frislit.start.plist"))
}
#[cfg(target_os = "macos")]
fn domain() -> Result<String> {
let output = Command::new("id")
.arg("-u")
.output()
.context("Could not run id")?;
Ok(format!(
"gui/{}",
String::from_utf8_lossy(&output.stdout).trim()
))
}
#[cfg(target_os = "macos")]
fn install_platform() -> Result<String> {
let path = plist_path()?;
let log = dirs::home_dir()
.context("No home directory")?
.join("Library")
.join("Logs")
.join("frislit.log");
fs::create_dir_all(path.parent().unwrap())?;
fs::write(&path, format!(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n\
<plist version=\"1.0\"><dict>\n\
<key>Label</key><string>dev.frislit.start</string>\n\
<key>ProgramArguments</key><array><string>{}</string><string>start</string></array>\n\
<key>RunAtLoad</key><true/>\n<key>KeepAlive</key><true/>\n\
<key>StandardOutPath</key><string>{log}</string>\n<key>StandardErrorPath</key><string>{log}</string>\n\
</dict></plist>\n",
exe()?, log = log.display(),
))?;
let _ = Command::new("launchctl")
.args(["bootout", &domain()?, &path.to_string_lossy()])
.status();
run(
"launchctl",
&["bootstrap", &domain()?, &path.to_string_lossy()],
)?;
Ok(format!(
"launch agent {}\n Logs: {}",
path.display(),
log.display()
))
}
#[cfg(target_os = "macos")]
fn uninstall_platform() -> Result<()> {
let path = plist_path()?;
let _ = Command::new("launchctl")
.args(["bootout", &domain()?, &path.to_string_lossy()])
.status();
if path.exists() {
fs::remove_file(path)?;
}
Ok(())
}
#[cfg(target_os = "windows")]
fn install_platform() -> Result<String> {
// schtasks /TR keeps the quotes around the exe path inside <Command>, which Windows
// cannot launch, so the task is registered through the ScheduledTasks module instead.
let exe = exe()?.replace('\'', "''");
let script = format!(
"$ErrorActionPreference = 'Stop'\n\
$user = \"$env:USERDOMAIN\\$env:USERNAME\"\n\
$action = New-ScheduledTaskAction -Execute '{exe}' -Argument 'start'\n\
$trigger = New-ScheduledTaskTrigger -AtLogOn -User $user\n\
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries `\n\
-StartWhenAvailable -ExecutionTimeLimit ([TimeSpan]::Zero)\n\
Register-ScheduledTask -TaskName '{NAME}' -Action $action -Trigger $trigger -Settings $settings -Force | Out-Null\n"
);
let path = std::env::temp_dir().join(format!("{NAME}-service.ps1"));
fs::write(&path, script)?;
let status = Command::new("powershell")
.args(["-NoProfile", "-ExecutionPolicy", "Bypass", "-File"])
.arg(&path)
.status()
.context("Could not run powershell")?;
let _ = fs::remove_file(&path);
if !status.success() {
bail!("Registering the scheduled task \"{NAME}\" failed");
}
Ok(format!("scheduled task \"{NAME}\", runs at logon"))
}
#[cfg(target_os = "windows")]
fn uninstall_platform() -> Result<()> {
let _ = Command::new("schtasks")
.args(["/End", "/TN", NAME])
.status();
let _ = Command::new("schtasks")
.args(["/Delete", "/F", "/TN", NAME])
.status();
Ok(())
}
pub fn install() -> Result<()> {
Config::load()?.require_auth()?;
let manifest = ensure_manifest()?;
let installed = install_platform()?;
println!(
"{} frislit starts with your session: {installed}",
style("✓").green().bold()
);
println!(" Tunnels: {}", style(manifest.display()).dim());
Ok(())
}
pub fn uninstall() -> Result<()> {
uninstall_platform()?;
println!("{} Service removed", style("✓").green().bold());
Ok(())
}
+183
View File
@@ -0,0 +1,183 @@
use tokio::sync::{mpsc, watch};
pub struct Request {
pub kind: String,
pub method: String,
pub path: String,
pub status: u16,
pub duration: u64,
pub ip: String,
pub country: Option<String>,
pub org: Option<String>,
pub flags: Vec<String>,
}
impl Request {
pub fn from_control(message: &serde_json::Value) -> Self {
let field = |key: &str| message.get(key).and_then(|value| value.as_str()).unwrap_or("").to_string();
let optional = |key: &str| message.get(key).and_then(|value| value.as_str()).map(String::from);
Self {
kind: field("kind"),
method: field("method"),
path: field("path"),
status: message.get("status").and_then(|value| value.as_u64()).unwrap_or(0) as u16,
duration: message.get("duration").and_then(|value| value.as_u64()).unwrap_or(0),
ip: field("ip"),
country: optional("country"),
org: optional("org"),
flags: message.get("flags").and_then(|value| value.as_array()).map(|list| list.iter().filter_map(|v| v.as_str().map(String::from)).collect()).unwrap_or_default(),
}
}
pub fn intel(&self) -> Option<String> {
let parts: Vec<&str> = self.country.iter().chain(self.org.iter()).chain(self.flags.iter()).map(String::as_str).collect();
if parts.is_empty() { None } else { Some(parts.join(" · ")) }
}
}
pub struct Connection {
pub key: String,
pub opened: bool,
pub protocol: String,
pub ip: String,
pub country: Option<String>,
pub org: Option<String>,
pub bytes_in: u64,
pub bytes_out: u64,
pub duration: u64,
pub reason: Option<String>,
pub detail: Option<String>,
}
impl Connection {
pub fn from_control(message: &serde_json::Value) -> Self {
let text = |key: &str| message.get(key).and_then(|value| value.as_str()).map(String::from);
let number = |key: &str| message.get(key).and_then(|value| value.as_u64()).unwrap_or(0);
let detail = message.get("detail").filter(|value| !value.is_null()).map(|value| {
let name = value.get("name").and_then(|v| v.as_str()).unwrap_or("");
match value.get("info").and_then(|v| v.as_str()) { Some(info) => format!("{name} {info}"), None => name.to_string() }
});
Self {
key: text("key").unwrap_or_default(),
opened: message.get("event").and_then(|value| value.as_str()) == Some("open"),
protocol: text("protocol").unwrap_or_default().to_uppercase(),
ip: text("ip").unwrap_or_default(),
country: text("country"),
org: text("org"),
bytes_in: number("bytesIn"),
bytes_out: number("bytesOut"),
duration: number("duration"),
reason: text("reason"),
detail,
}
}
pub fn intel(&self) -> Option<String> {
let parts: Vec<&str> = self.country.iter().chain(self.org.iter()).map(String::as_str).collect();
if parts.is_empty() { None } else { Some(parts.join(" · ")) }
}
pub fn line(&self) -> String {
let mut parts = vec![format!("{:<4}", self.protocol), if self.opened { "open ".to_string() } else { "closed".to_string() }, self.ip.clone()];
if self.opened {
if let Some(detail) = &self.detail { parts.push(detail.clone()); }
if let Some(intel) = self.intel() { parts.push(intel); }
} else {
parts.push(format!("{} in, {} out, {}", bytes(self.bytes_in), bytes(self.bytes_out), took(self.duration)));
if let Some(reason) = &self.reason { parts.push(reason.clone()); }
}
parts.join(" ")
}
}
pub fn bytes(value: u64) -> String {
const UNITS: [&str; 4] = ["B", "kB", "MB", "GB"];
let mut size = value as f64;
let mut unit = 0;
while size >= 1000.0 && unit < UNITS.len() - 1 { size /= 1000.0; unit += 1; }
if unit == 0 { format!("{value} B") } else { format!("{size:.1} {}", UNITS[unit]) }
}
pub fn took(millis: u64) -> String {
if millis < 1000 { format!("{millis}ms") } else if millis < 60_000 { format!("{:.1}s", millis as f64 / 1000.0) } else { format!("{}m {}s", millis / 60_000, (millis % 60_000) / 1000) }
}
#[derive(Clone)]
pub struct Online {
pub id: String,
pub url: Option<String>,
pub share_code: Option<String>,
pub connect_url: Option<String>,
pub custom_urls: Vec<String>,
pub persistent: bool,
pub access: Option<String>,
}
impl Online {
pub fn link(&self, server_url: &str) -> Option<String> {
if let Some(url) = &self.url { return Some(url.clone()); }
let code = self.share_code.as_ref()?;
Some(self.connect_url.clone().unwrap_or_else(|| format!("{server_url}/@frislit/connect/{code}")))
}
}
pub enum TunnelEvent {
Connecting,
Online(Online),
Resumed(Online),
Replaced(Online),
Request(Request),
Connection(Connection),
Access(String),
Reconnecting { seconds: u64, reason: Option<String> },
Update(String),
Stopped,
Ended(String),
}
pub enum JoinEvent {
Connecting,
Forwarding { bind: String, port: u16, tunnel_id: String, owner_online: bool },
Reconnecting { seconds: u64, reason: Option<String> },
Reconnected,
Stopped,
Ended(String),
}
pub type Events<T> = mpsc::UnboundedSender<T>;
pub fn channel<T>() -> (Events<T>, mpsc::UnboundedReceiver<T>) { mpsc::unbounded_channel() }
pub struct Task(pub tokio::task::JoinHandle<()>);
impl Drop for Task {
fn drop(&mut self) { self.0.abort(); }
}
#[derive(Clone)]
pub struct StopHandle(watch::Sender<bool>);
impl StopHandle {
pub fn stop(&self) { let _ = self.0.send(true); }
}
pub struct Stop(watch::Receiver<bool>);
impl Stop {
pub fn new() -> (StopHandle, Self) {
let (tx, rx) = watch::channel(false);
(StopHandle(tx), Self(rx))
}
pub fn subscribe(handle: &StopHandle) -> Self {
Self(handle.0.subscribe())
}
pub async fn wait(&mut self) {
if *self.0.borrow() { return; }
while self.0.changed().await.is_ok() {
if *self.0.borrow() { return; }
}
std::future::pending::<()>().await;
}
}
+105
View File
@@ -0,0 +1,105 @@
use anyhow::{bail, Context, Result};
use std::time::Duration;
use tokio::sync::mpsc::Receiver;
use tokio::time::Instant;
const MIN_STALL: Duration = Duration::from_millis(200);
#[derive(Clone, Default)]
pub struct Shape {
pub latency: Duration,
pub jitter: Duration,
pub bandwidth: Option<u64>,
pub loss: f64,
}
fn number(text: &str, unit: &str) -> Result<f64> {
text.parse::<f64>().ok().filter(|value| *value >= 0.0).with_context(|| format!("Invalid {unit} \"{text}\""))
}
pub fn duration(raw: &str) -> Result<Duration> {
let text = raw.trim().to_ascii_lowercase();
let (value, factor) = match text.strip_suffix("ms") {
Some(value) => (value, 0.001),
None => match text.strip_suffix('s') { Some(value) => (value, 1.0), None => (text.as_str(), 0.001) },
};
Ok(Duration::from_secs_f64(number(value.trim(), "duration")? * factor))
}
pub fn rate(raw: &str) -> Result<u64> {
let text = raw.trim().to_ascii_lowercase().replace(' ', "");
let units = [("gbps", 125_000_000.0), ("mbps", 125_000.0), ("kbps", 125.0), ("bps", 0.125), ("gb/s", 1e9), ("mb/s", 1e6), ("kb/s", 1e3), ("b/s", 1.0)];
for (suffix, factor) in units {
if let Some(value) = text.strip_suffix(suffix) {
let bytes = number(value, "bandwidth")? * factor;
if bytes < 1.0 { bail!("Bandwidth \"{raw}\" is too low"); }
return Ok(bytes as u64);
}
}
bail!("Invalid bandwidth \"{raw}\": use e.g. 512kbps, 2mbps or 100kB/s")
}
pub fn percent(raw: &str) -> Result<f64> {
let value = number(raw.trim().trim_end_matches('%').trim(), "loss")?;
if value > 100.0 { bail!("Loss must be between 0 and 100 percent"); }
Ok(value / 100.0)
}
impl Shape {
pub fn parse(latency: Option<&str>, jitter: Option<&str>, bandwidth: Option<&str>, loss: Option<&str>) -> Result<Self> {
Ok(Self {
latency: latency.map(duration).transpose()?.unwrap_or_default(),
jitter: jitter.map(duration).transpose()?.unwrap_or_default(),
bandwidth: bandwidth.map(rate).transpose()?,
loss: loss.map(percent).transpose()?.unwrap_or_default(),
})
}
pub fn active(&self) -> bool {
!self.latency.is_zero() || !self.jitter.is_zero() || self.bandwidth.is_some() || self.loss > 0.0
}
pub fn summary(&self) -> Option<String> {
if !self.active() { return None; }
let mut parts = Vec::new();
if !self.latency.is_zero() || !self.jitter.is_zero() {
let mut text = format!("{} ms latency", self.latency.as_millis());
if !self.jitter.is_zero() { text.push_str(&format!(" ±{} ms", self.jitter.as_millis())); }
parts.push(text);
}
if let Some(bytes) = self.bandwidth {
let bits = bytes * 8;
parts.push(if bits >= 1_000_000 { format!("{:.1} mbps", bits as f64 / 1e6) } else { format!("{} kbps", bits / 1000) });
}
if self.loss > 0.0 { parts.push(format!("{}% loss", (self.loss * 100.0 * 10.0).round() / 10.0)); }
Some(parts.join(" · "))
}
pub fn lose(&self) -> bool {
self.loss > 0.0 && fastrand::f64() < self.loss
}
fn release(&self, arrived: Instant, len: usize, stall: bool, last: &mut Instant) -> Instant {
let jitter = Duration::from_secs_f64(fastrand::f64() * self.jitter.as_secs_f64());
let mut at = arrived + self.latency + jitter;
if stall && self.lose() { at += (self.latency * 3).max(MIN_STALL); }
at = at.max(*last);
if let Some(bytes) = self.bandwidth { at += Duration::from_secs_f64(len as f64 / bytes as f64); }
*last = at;
at
}
pub async fn next(&self, queue: &mut Queue, stall: bool) -> Option<Vec<u8>> {
let (arrived, chunk) = queue.rx.recv().await?;
tokio::time::sleep_until(self.release(arrived, chunk.len(), stall, &mut queue.last)).await;
Some(chunk)
}
}
pub struct Queue { rx: Receiver<(Instant, Vec<u8>)>, last: Instant }
impl Queue {
pub fn new(rx: Receiver<(Instant, Vec<u8>)>) -> Self {
Self { rx, last: Instant::now() }
}
}
+120
View File
@@ -0,0 +1,120 @@
use anyhow::Result;
use std::net::SocketAddr;
use std::time::Duration;
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use tokio::net::UdpSocket;
use tokio::sync::mpsc;
use tokio::time::Instant;
use crate::mux::{Incoming, MuxReader, MuxWriter, CHUNK};
use crate::shape::{Queue, Shape};
pub const UDP_IDLE: Duration = Duration::from_secs(60);
const QUEUE: usize = 256;
pub async fn pump_tcp<S: AsyncRead + AsyncWrite + Unpin>(socket: S, writer: MuxWriter, mut reader: MuxReader, shape: &Shape) {
let (mut rd, mut wr) = tokio::io::split(socket);
if !shape.active() {
let to_mux = async {
let mut buf = vec![0u8; CHUNK];
loop {
match rd.read(&mut buf).await {
Ok(0) => { writer.close().await; break; }
Ok(n) => { if writer.send(&buf[..n]).await.is_err() { break; } }
Err(_) => { writer.reset(); break; }
}
}
};
let from_mux = async {
loop {
match reader.recv().await {
Incoming::Data(data) => { if wr.write_all(&data).await.is_err() { break; } }
Incoming::Close => { let _ = wr.shutdown().await; break; }
Incoming::Reset => break,
Incoming::Datagram(_) => {}
}
}
};
tokio::join!(to_mux, from_mux);
return;
}
let (to_mux_tx, to_mux_rx) = mpsc::channel::<(Instant, Vec<u8>)>(QUEUE);
let (to_socket_tx, to_socket_rx) = mpsc::channel::<(Instant, Vec<u8>)>(QUEUE);
let read_socket = async {
let mut buf = vec![0u8; CHUNK];
loop {
match rd.read(&mut buf).await {
Ok(0) | Err(_) => break,
Ok(n) => { if to_mux_tx.send((Instant::now(), buf[..n].to_vec())).await.is_err() { break; } }
}
}
drop(to_mux_tx);
};
let read_mux = async {
loop {
match reader.recv().await {
Incoming::Data(data) => { if to_socket_tx.send((Instant::now(), data)).await.is_err() { break; } }
Incoming::Close | Incoming::Reset => break,
Incoming::Datagram(_) => {}
}
}
drop(to_socket_tx);
};
let write_mux = async {
let mut queue = Queue::new(to_mux_rx);
while let Some(chunk) = shape.next(&mut queue, true).await {
if writer.send(&chunk).await.is_err() { break; }
}
writer.close().await;
};
let write_socket = async {
let mut queue = Queue::new(to_socket_rx);
while let Some(chunk) = shape.next(&mut queue, true).await {
if wr.write_all(&chunk).await.is_err() { break; }
}
let _ = wr.shutdown().await;
};
tokio::join!(read_socket, read_mux, write_mux, write_socket);
}
pub async fn pump_udp_owner(target: SocketAddr, writer: MuxWriter, mut reader: MuxReader, shape: &Shape) -> Result<()> {
let bind: SocketAddr = if target.is_ipv4() { "0.0.0.0:0".parse()? } else { "[::]:0".parse()? };
let socket = UdpSocket::bind(bind).await?;
socket.connect(target).await?;
let (to_mux_tx, to_mux_rx) = mpsc::channel::<(Instant, Vec<u8>)>(QUEUE);
let (to_socket_tx, to_socket_rx) = mpsc::channel::<(Instant, Vec<u8>)>(QUEUE);
let relay = async {
let mut buf = vec![0u8; 65535];
loop {
tokio::select! {
incoming = tokio::time::timeout(UDP_IDLE, reader.recv()) => match incoming {
Ok(Incoming::Datagram(data)) => { if !shape.lose() { let _ = to_socket_tx.try_send((Instant::now(), data)); } }
Ok(Incoming::Close) | Ok(Incoming::Reset) | Err(_) => break,
Ok(_) => {}
},
received = socket.recv(&mut buf) => match received {
Ok(n) => { if !shape.lose() { let _ = to_mux_tx.try_send((Instant::now(), buf[..n].to_vec())); } }
Err(_) => {}
},
}
}
drop(to_socket_tx);
drop(to_mux_tx);
};
let write_socket = async {
let mut queue = Queue::new(to_socket_rx);
while let Some(datagram) = shape.next(&mut queue, false).await { let _ = socket.send(&datagram).await; }
};
let write_mux = async {
let mut queue = Queue::new(to_mux_rx);
while let Some(datagram) = shape.next(&mut queue, false).await {
if writer.send_datagram(&datagram).await.is_err() { break; }
}
};
tokio::join!(relay, write_socket, write_mux);
writer.close().await;
Ok(())
}
+51
View File
@@ -0,0 +1,51 @@
use anyhow::Result;
use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
use rustls::crypto::{ring, CryptoProvider};
use rustls::{ClientConfig, DigitallySignedStruct, SignatureScheme};
use rustls_pki_types::{CertificateDer, ServerName, UnixTime};
use rustls_platform_verifier::Verifier;
use std::sync::Arc;
use tokio::net::TcpStream;
use tokio_rustls::client::TlsStream;
use tokio_rustls::TlsConnector;
#[derive(Debug)]
struct Trusting;
impl ServerCertVerifier for Trusting {
fn verify_server_cert(&self, _: &CertificateDer<'_>, _: &[CertificateDer<'_>], _: &ServerName<'_>, _: &[u8], _: UnixTime) -> Result<ServerCertVerified, rustls::Error> {
Ok(ServerCertVerified::assertion())
}
fn verify_tls12_signature(&self, _: &[u8], _: &CertificateDer<'_>, _: &DigitallySignedStruct) -> Result<HandshakeSignatureValid, rustls::Error> {
Ok(HandshakeSignatureValid::assertion())
}
fn verify_tls13_signature(&self, _: &[u8], _: &CertificateDer<'_>, _: &DigitallySignedStruct) -> Result<HandshakeSignatureValid, rustls::Error> {
Ok(HandshakeSignatureValid::assertion())
}
fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
provider().signature_verification_algorithms.supported_schemes()
}
}
pub fn install_provider() {
let _ = ring::default_provider().install_default();
}
fn provider() -> Arc<CryptoProvider> {
CryptoProvider::get_default().unwrap().clone()
}
pub fn client_config(accept_invalid_certs: bool) -> Result<Arc<ClientConfig>> {
let verifier: Arc<dyn ServerCertVerifier> = if accept_invalid_certs { Arc::new(Trusting) } else { Arc::new(Verifier::new(provider())?) };
let config = ClientConfig::builder_with_provider(provider()).with_safe_default_protocol_versions()?
.dangerous().with_custom_certificate_verifier(verifier).with_no_client_auth();
Ok(Arc::new(config))
}
pub async fn connect_trusting(host: &str, socket: TcpStream) -> Result<TlsStream<TcpStream>> {
let name = ServerName::try_from(host.to_string())?;
Ok(TlsConnector::from(client_config(true)?).connect(name, socket).await?)
}
+409
View File
@@ -0,0 +1,409 @@
use anyhow::Result;
use chrono::{DateTime, Local};
use crossterm::event::{Event, EventStream, KeyCode, KeyEvent, KeyModifiers};
use futures_util::StreamExt;
use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, BorderType, Borders, Cell, Padding, Paragraph, Row, Sparkline, Table, TableState};
use ratatui::Frame;
use std::collections::VecDeque;
use std::time::{Duration, Instant};
use tokio::sync::mpsc::UnboundedReceiver;
use crate::qr;
use crate::session::{bytes, took, Connection, Online, Request, StopHandle, TunnelEvent};
const KEEP: usize = 500;
const TICK: Duration = Duration::from_millis(200);
const SPINNER: [&str; 10] = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
const TEAL: Color = Color::Rgb(20, 184, 166);
const TEAL_BRIGHT: Color = Color::Rgb(45, 212, 191);
const AMBER: Color = Color::Rgb(251, 191, 36);
const RED: Color = Color::Rgb(248, 113, 113);
const GREEN: Color = Color::Rgb(52, 211, 153);
const MUTED: Color = Color::Rgb(121, 113, 107);
const SUBTEXT: Color = Color::Rgb(168, 162, 158);
const BORDER: Color = Color::Rgb(60, 56, 52);
pub struct Context {
pub server_url: String,
pub account: String,
pub target: String,
pub network: Option<String>,
pub tcp: bool,
}
enum Status { Connecting, Online, Reconnecting(u64, Option<String>) }
struct Seen<T> { at: DateTime<Local>, item: T }
struct State {
ctx: Context,
status: Status,
online: Option<Online>,
access: Option<String>,
requests: VecDeque<Seen<Request>>,
connections: VecDeque<Seen<Connection>>,
samples: VecDeque<(Instant, u64)>,
total: u64,
errors: u64,
open: i64,
bytes_in: u64,
bytes_out: u64,
table: TableState,
copied: bool,
notice: Option<(String, Instant)>,
update: Option<String>,
frame: usize,
ended: Option<String>,
}
impl State {
fn apply(&mut self, event: TunnelEvent) {
match event {
TunnelEvent::Connecting => self.status = Status::Connecting,
TunnelEvent::Online(online) | TunnelEvent::Resumed(online) | TunnelEvent::Replaced(online) => {
self.status = Status::Online;
self.access = online.access.clone();
self.online = Some(online);
if !self.copied && self.copy() { self.notice("Link copied to clipboard"); }
}
TunnelEvent::Request(request) => {
self.total += 1;
if request.status >= 400 { self.errors += 1; }
self.samples.push_back((Instant::now(), request.duration));
while self.samples.len() > KEEP { self.samples.pop_front(); }
self.requests.push_front(Seen { at: Local::now(), item: request });
self.requests.truncate(KEEP);
self.bump();
}
TunnelEvent::Connection(connection) => {
if connection.opened {
self.open += 1;
self.total += 1;
self.connections.push_front(Seen { at: Local::now(), item: connection });
self.connections.truncate(KEEP);
self.bump();
} else {
self.open -= 1;
self.bytes_in += connection.bytes_in;
self.bytes_out += connection.bytes_out;
self.samples.push_back((Instant::now(), connection.duration));
match self.connections.iter_mut().find(|seen| seen.item.key == connection.key) {
Some(seen) => seen.item = connection,
None => { self.connections.push_front(Seen { at: Local::now(), item: connection }); self.connections.truncate(KEEP); }
}
}
}
TunnelEvent::Access(summary) => { self.access = Some(summary); self.notice("Access rules updated"); }
TunnelEvent::Reconnecting { seconds, reason } => self.status = Status::Reconnecting(seconds, reason),
TunnelEvent::Update(version) => self.update = Some(version),
TunnelEvent::Stopped => {}
TunnelEvent::Ended(reason) => self.ended = Some(reason),
}
}
fn bump(&mut self) {
if let Some(selected) = self.table.selected() { self.table.select(Some((selected + 1).min(self.entries() - 1))); }
}
fn entries(&self) -> usize {
if self.ctx.tcp { self.connections.len() } else { self.requests.len() }
}
fn link(&self) -> Option<String> {
let online = self.online.as_ref()?;
online.url.clone().or_else(|| online.link(&self.ctx.server_url).map(|link| format!("frislit connect {link}")))
}
fn copy(&mut self) -> bool {
let Some(link) = self.link() else { return false };
self.copied = qr::copy(&link);
self.copied
}
fn notice(&mut self, text: &str) {
self.notice = Some((text.to_string(), Instant::now()));
}
fn rate(&self, window: Duration) -> f64 {
let since = Instant::now() - window;
self.samples.iter().filter(|(at, _)| *at >= since).count() as f64 / window.as_secs_f64()
}
fn percentile(&self, fraction: f64) -> u64 {
if self.samples.is_empty() { return 0; }
let mut values: Vec<u64> = self.samples.iter().map(|(_, value)| *value).collect();
values.sort_unstable();
values[((values.len() - 1) as f64 * fraction).round() as usize]
}
fn histogram(&self, buckets: usize) -> Vec<u64> {
let now = Instant::now();
let mut counts = vec![0u64; buckets];
for (at, _) in &self.samples {
let age = now.duration_since(*at).as_secs() as usize;
if age < buckets { counts[buckets - 1 - age] += 1; }
}
counts
}
}
fn status_color(status: u16) -> Color {
match status { 200..=299 => GREEN, 300..=399 => TEAL_BRIGHT, 400..=499 => AMBER, _ => RED }
}
fn panel(title: &str) -> Block<'static> {
Block::default()
.borders(Borders::ALL)
.border_type(BorderType::Rounded)
.border_style(Style::default().fg(BORDER))
.title(Span::styled(format!(" {title} "), Style::default().fg(SUBTEXT).add_modifier(Modifier::BOLD)))
.padding(Padding::horizontal(1))
}
fn field(name: &str, value: Span<'static>) -> Line<'static> {
Line::from(vec![Span::styled(format!("{:<11}", name), Style::default().fg(MUTED)), value])
}
fn plain(text: impl Into<String>) -> Span<'static> { Span::raw(text.into()) }
fn header(state: &State, area: Rect, frame: &mut Frame) {
let spinner = SPINNER[state.frame % SPINNER.len()];
let status = match &state.status {
Status::Connecting => Span::styled(format!("{spinner} connecting"), Style::default().fg(AMBER)),
Status::Online => Span::raw(""),
Status::Reconnecting(seconds, reason) => Span::styled(
match reason { Some(reason) => format!("{spinner} reconnecting in {seconds}s · {reason}"), None => format!("{spinner} reconnecting") },
Style::default().fg(AMBER),
),
};
let notice = state.notice.as_ref().filter(|(_, at)| at.elapsed() < Duration::from_secs(3)).map(|(text, _)| text.clone());
let right = notice.map(|text| Span::styled(text, Style::default().fg(TEAL_BRIGHT))).unwrap_or(status);
let mut left = vec![
Span::styled("fris", Style::default().fg(Color::White).add_modifier(Modifier::BOLD)),
Span::styled("lit", Style::default().fg(TEAL).add_modifier(Modifier::BOLD)),
Span::styled(format!(" v{}", env!("CARGO_PKG_VERSION")), Style::default().fg(MUTED)),
];
if let Some(version) = &state.update {
left.push(Span::styled(format!(" ↑ v{version} available · frislit update"), Style::default().fg(AMBER)));
}
let used: usize = left.iter().map(|span| span.width()).sum::<usize>() + right.width();
let mut spans = left;
spans.push(Span::raw(" ".repeat((area.width as usize).saturating_sub(used))));
spans.push(right);
frame.render_widget(Paragraph::new(Line::from(spans)), area);
}
fn tunnel_lines(state: &State) -> Vec<Line<'static>> {
let mut lines = Vec::new();
match &state.online {
Some(online) => {
let name = if online.persistent { format!("{} persistent", online.id) } else { online.id.clone() };
match &online.url {
Some(url) => {
lines.push(field("Public", Span::styled(url.clone(), Style::default().fg(TEAL_BRIGHT).add_modifier(Modifier::BOLD))));
for custom in &online.custom_urls { lines.push(field("", Span::styled(custom.clone(), Style::default().fg(TEAL_BRIGHT)))); }
}
None => {
if let Some(link) = online.link(&state.ctx.server_url) {
lines.push(field("Share", Span::styled(format!("frislit connect {link}"), Style::default().fg(TEAL_BRIGHT).add_modifier(Modifier::BOLD))));
}
}
}
lines.push(field("Local", plain(state.ctx.target.clone())));
lines.push(field("Name", plain(name)));
}
None => lines.push(field("Local", plain(state.ctx.target.clone()))),
}
lines.push(field("Account", plain(format!("{} · {}", state.ctx.account, state.ctx.server_url))));
if let Some(access) = &state.access { lines.push(field("Access", Span::styled(access.clone(), Style::default().fg(AMBER)))); }
if let Some(network) = &state.ctx.network { lines.push(field("Network", Span::styled(network.clone(), Style::default().fg(AMBER)))); }
lines
}
fn tunnel_panel(lines: Vec<Line<'static>>, area: Rect, frame: &mut Frame) {
frame.render_widget(Paragraph::new(lines).block(panel("Tunnel")), area);
}
fn stat(label: &str, value: String) -> Line<'static> {
Line::from(vec![Span::styled(format!("{:<8}", label), Style::default().fg(MUTED)), Span::styled(value, Style::default().add_modifier(Modifier::BOLD))])
}
fn stats_panel(state: &State, area: Rect, frame: &mut Frame) {
let block = panel("Activity");
let inner = block.inner(area);
frame.render_widget(block, area);
let rows = Layout::default().direction(Direction::Vertical).constraints([Constraint::Length(2), Constraint::Min(1), Constraint::Length(1)]).split(inner);
let columns = Layout::default().direction(Direction::Horizontal)
.constraints([Constraint::Ratio(1, 3), Constraint::Ratio(1, 3), Constraint::Ratio(1, 3)]).split(rows[0]);
let (left, middle, right) = if state.ctx.tcp {
(
vec![stat("open", state.open.max(0).to_string()), stat("total", state.total.to_string())],
vec![stat("in", bytes(state.bytes_in)), stat("out", bytes(state.bytes_out))],
vec![stat("per min", format!("{:.1}", state.rate(Duration::from_secs(60)) * 60.0)), stat("p50", format!("{}ms", state.percentile(0.5)))],
)
} else {
(
vec![stat("total", state.total.to_string()), stat("errors", state.errors.to_string())],
vec![stat("per min", format!("{:.1}", state.rate(Duration::from_secs(60)) * 60.0)), stat("per 5m", format!("{:.1}", state.rate(Duration::from_secs(300)) * 300.0))],
vec![stat("p50", format!("{}ms", state.percentile(0.5))), stat("p90", format!("{}ms", state.percentile(0.9)))],
)
};
frame.render_widget(Paragraph::new(left), columns[0]);
frame.render_widget(Paragraph::new(middle), columns[1]);
frame.render_widget(Paragraph::new(right), columns[2]);
let width = rows[1].width as usize;
if width > 0 && rows[1].height > 0 {
let data = state.histogram(width);
frame.render_widget(Sparkline::default().data(&data).style(Style::default().fg(TEAL)), rows[1]);
let caption = format!("{} per second · last {width}s", if state.ctx.tcp { "connections" } else { "requests" });
frame.render_widget(Paragraph::new(Span::styled(caption, Style::default().fg(MUTED))).right_aligned(), rows[2]);
}
}
fn request_row(seen: &Seen<Request>) -> Row<'static> {
let request = &seen.item;
let method = if request.kind == "ws" { "WS".to_string() } else { request.method.clone() };
Row::new(vec![
Cell::from(Span::styled(seen.at.format("%H:%M:%S").to_string(), Style::default().fg(MUTED))),
Cell::from(Span::styled(method, Style::default().add_modifier(Modifier::BOLD))),
Cell::from(Span::styled(request.status.to_string(), Style::default().fg(status_color(request.status)).add_modifier(Modifier::BOLD))),
Cell::from(request.path.clone()),
Cell::from(Span::styled(format!("{}ms", request.duration), Style::default().fg(SUBTEXT))),
Cell::from(Span::styled(request.ip.clone(), Style::default().fg(SUBTEXT))),
Cell::from(Span::styled(request.intel().unwrap_or_default(), Style::default().fg(MUTED))),
])
}
fn connection_row(seen: &Seen<Connection>) -> Row<'static> {
let connection = &seen.item;
let state = if connection.opened { Span::styled("open", Style::default().fg(GREEN)) } else { Span::styled(connection.reason.clone().unwrap_or_default(), Style::default().fg(MUTED)) };
Row::new(vec![
Cell::from(Span::styled(seen.at.format("%H:%M:%S").to_string(), Style::default().fg(MUTED))),
Cell::from(Span::styled(connection.protocol.clone(), Style::default().add_modifier(Modifier::BOLD))),
Cell::from(Span::styled(connection.ip.clone(), Style::default().fg(SUBTEXT))),
Cell::from(connection.detail.clone().unwrap_or_default()),
Cell::from(Span::styled(if connection.opened { String::new() } else { format!("{} / {}", bytes(connection.bytes_in), bytes(connection.bytes_out)) }, Style::default().fg(SUBTEXT))),
Cell::from(Span::styled(if connection.opened { String::new() } else { took(connection.duration) }, Style::default().fg(SUBTEXT))),
Cell::from(state),
Cell::from(Span::styled(connection.intel().unwrap_or_default(), Style::default().fg(MUTED))),
])
}
fn table(state: &mut State, area: Rect, frame: &mut Frame) {
let head = Style::default().fg(MUTED).add_modifier(Modifier::BOLD);
let (title, header, widths, rows): (&str, Vec<&str>, Vec<Constraint>, Vec<Row>) = if state.ctx.tcp {
(
"Connections",
vec!["time", "proto", "client", "protocol", "in / out", "took", "state", "where"],
vec![Constraint::Length(8), Constraint::Length(5), Constraint::Length(16), Constraint::Min(16), Constraint::Length(18), Constraint::Length(7), Constraint::Length(18), Constraint::Length(24)],
state.connections.iter().map(connection_row).collect(),
)
} else {
(
"Requests",
vec!["time", "method", "status", "path", "took", "client", "where"],
vec![Constraint::Length(8), Constraint::Length(6), Constraint::Length(6), Constraint::Min(16), Constraint::Length(7), Constraint::Length(16), Constraint::Length(28)],
state.requests.iter().map(request_row).collect(),
)
};
let empty = rows.is_empty();
let table = Table::new(rows, widths)
.header(Row::new(header.into_iter().map(|name| Cell::from(Span::styled(name, head))).collect::<Vec<_>>()).bottom_margin(0))
.block(panel(title))
.column_spacing(2)
.row_highlight_style(Style::default().bg(Color::Rgb(34, 31, 27)).add_modifier(Modifier::BOLD));
frame.render_stateful_widget(table, area, &mut state.table);
if empty {
let hint = if state.ctx.tcp { "Waiting for the first connection" } else { "Waiting for the first request" };
let inner = Rect::new(area.x + 2, area.y + 2, area.width.saturating_sub(4), 1);
frame.render_widget(Paragraph::new(Span::styled(hint, Style::default().fg(MUTED))), inner);
}
}
fn footer(state: &State, area: Rect, frame: &mut Frame) {
let keys: Vec<(&str, &str)> = if state.ctx.tcp {
vec![("q", "quit"), ("↑↓", "select"), ("c", "copy share command"), ("d", "dashboard")]
} else {
vec![("q", "quit"), ("↑↓", "select"), ("c", "copy url"), ("o", "open in browser"), ("d", "dashboard")]
};
let mut spans = Vec::new();
for (index, (key, action)) in keys.iter().enumerate() {
if index > 0 { spans.push(Span::styled(" · ", Style::default().fg(BORDER))); }
spans.push(Span::styled(*key, Style::default().fg(TEAL_BRIGHT).add_modifier(Modifier::BOLD)));
spans.push(Span::styled(format!(" {action}"), Style::default().fg(MUTED)));
}
frame.render_widget(Paragraph::new(Line::from(spans)), area);
}
fn draw(frame: &mut Frame, state: &mut State) {
let area = frame.area();
let lines = tunnel_lines(state);
let widest = lines.iter().map(|line| line.width()).fold(0, usize::max) as u16 + 4;
let column = area.width.saturating_sub(2) * 58 / 100;
let side_by_side = area.width >= 100 && widest <= column;
let tunnel_height = if side_by_side { (lines.len() as u16 + 2).max(8) } else { lines.len() as u16 + 2 };
let constraints = if side_by_side {
vec![Constraint::Length(1), Constraint::Length(1), Constraint::Length(tunnel_height), Constraint::Min(5), Constraint::Length(1)]
} else {
vec![Constraint::Length(1), Constraint::Length(1), Constraint::Length(tunnel_height), Constraint::Length(8), Constraint::Min(5), Constraint::Length(1)]
};
let outer = Layout::default().direction(Direction::Vertical).constraints(constraints).horizontal_margin(1).split(area);
header(state, outer[0], frame);
if side_by_side {
let top = Layout::default().direction(Direction::Horizontal)
.constraints([Constraint::Percentage(58), Constraint::Percentage(42)]).split(outer[2]);
tunnel_panel(lines, top[0], frame);
stats_panel(state, top[1], frame);
table(state, outer[3], frame);
footer(state, outer[4], frame);
} else {
tunnel_panel(lines, outer[2], frame);
stats_panel(state, outer[3], frame);
table(state, outer[4], frame);
footer(state, outer[5], frame);
}
}
fn quit(key: &KeyEvent) -> bool {
key.code == KeyCode::Char('q') || (key.code == KeyCode::Char('c') && key.modifiers.contains(KeyModifiers::CONTROL))
}
pub async fn run(mut rx: UnboundedReceiver<TunnelEvent>, stop: StopHandle, ctx: Context) -> Result<Option<String>> {
let mut state = State {
ctx, status: Status::Connecting, online: None, access: None, requests: VecDeque::new(), connections: VecDeque::new(),
samples: VecDeque::new(), total: 0, errors: 0, open: 0, bytes_in: 0, bytes_out: 0, table: TableState::default(),
copied: false, notice: None, update: None, frame: 0, ended: None,
};
let mut terminal = ratatui::init();
let mut keys = EventStream::new();
let mut ticker = tokio::time::interval(TICK);
loop {
tokio::select! {
event = rx.recv() => match event {
Some(event) => state.apply(event),
None => break,
},
Some(Ok(Event::Key(key))) = keys.next() => {
if quit(&key) { stop.stop(); }
let last = state.entries().saturating_sub(1);
match key.code {
KeyCode::Up => state.table.select(Some(state.table.selected().map_or(0, |at| at.saturating_sub(1)))),
KeyCode::Down => state.table.select(Some(state.table.selected().map_or(0, |at| (at + 1).min(last)))),
KeyCode::PageUp => state.table.select(Some(state.table.selected().map_or(0, |at| at.saturating_sub(10)))),
KeyCode::PageDown => state.table.select(Some(state.table.selected().map_or(0, |at| (at + 10).min(last)))),
KeyCode::Esc | KeyCode::Home => state.table.select(None),
KeyCode::Char('c') => { if state.copy() { state.notice("Link copied to clipboard"); } }
KeyCode::Char('o') => { if let Some(url) = state.online.as_ref().and_then(|online| online.url.clone()) { let _ = open::that(url); } }
KeyCode::Char('d') => { if let Some(online) = &state.online { let _ = open::that(format!("{}/@frislit/tunnels/{}", state.ctx.server_url, online.id)); } }
_ => {}
}
},
_ = ticker.tick() => state.frame += 1,
}
terminal.draw(|frame| draw(frame, &mut state))?;
}
ratatui::restore();
Ok(state.ended)
}
+376
View File
@@ -0,0 +1,376 @@
use anyhow::{bail, Context, Result};
use serde_json::json;
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use tokio::net::TcpStream;
use crate::api::ws_url;
use crate::config::Config;
use crate::mux::{expect, Mux, MuxEvents, OpenMeta};
use crate::router::{self, Route, RouteTarget};
use crate::serve;
use crate::session::{Connection, Events, Online, Request, Stop, Task, TunnelEvent};
use crate::shape::Shape;
use crate::tcp::{pump_tcp, pump_udp_owner};
pub const PROTOCOL_VERSION: u64 = 1;
const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
#[derive(Clone)]
pub struct Target { pub host: String, pub port: u16, pub tls: bool }
impl Target {
pub fn parse(raw: &str) -> Result<Self> {
let raw = raw.trim();
if let Ok(port) = raw.parse::<u16>() { return Ok(Self { host: "127.0.0.1".into(), port, tls: false }); }
let (scheme, rest) = match raw.split_once("://") {
Some((scheme, rest)) => (Some(scheme.to_ascii_lowercase()), rest.split(['/', '?', '#']).next().unwrap_or("")),
None => (None, raw),
};
let default_port = match scheme.as_deref() {
Some("https") => Some(443),
Some("http") => Some(80),
Some(other) => bail!("Invalid target \"{raw}\": {other}:// is not supported, use http:// or https://"),
None => None,
};
let (host, port) = match rest.rsplit_once(':') {
Some((host, port)) if !port.contains(']') => {
(host, port.parse::<u16>().with_context(|| format!("Invalid port in \"{raw}\""))?)
}
_ => (rest, default_port.with_context(|| format!("Invalid target \"{raw}\": use <port>, <host>:<port> or https://<host>[:<port>]"))?),
};
let host = host.trim_matches(|c| c == '[' || c == ']');
if host.is_empty() { bail!("Invalid target \"{raw}\""); }
let tls = match scheme.as_deref() {
Some("https") => true,
Some(_) => false,
None => port == 443,
};
Ok(Self { host: host.to_string(), port, tls })
}
pub fn authority(&self) -> String {
if self.host.contains(':') { format!("[{}]:{}", self.host, self.port) } else { format!("{}:{}", self.host, self.port) }
}
pub fn label(&self) -> String {
if self.tls { format!("https://{}", self.authority()) } else { self.authority() }
}
pub async fn resolve(&self) -> Result<Vec<SocketAddr>> {
let addrs: Vec<SocketAddr> = tokio::net::lookup_host((self.host.as_str(), self.port)).await?.collect();
if addrs.is_empty() { bail!("Could not resolve {}", self.host); }
Ok(addrs)
}
}
#[derive(Clone)]
pub enum TargetSpec { Addr(Target), Dir(PathBuf), Routes(Vec<Route>) }
impl TargetSpec {
pub fn with_routes(target: &str, routes: &[String]) -> Result<Self> {
Self::routed(RouteTarget::parse(target)?, routes.iter().map(|raw| Route::parse(raw)).collect::<Result<_>>()?)
}
pub fn label(&self) -> String {
match self {
Self::Addr(target) => target.label(),
Self::Dir(dir) => format!("{} (static files)", dir.display()),
Self::Routes(routes) => format!("{} +{} routes", routes[0].target.label(), routes.len() - 1),
}
}
pub fn dir(raw: &str) -> Result<Self> {
Self::routed(RouteTarget::dir(raw)?, Vec::new())
}
pub fn routed(root: RouteTarget, mut routes: Vec<Route>) -> Result<Self> {
if routes.is_empty() {
return Ok(match root { RouteTarget::Addr(target) => Self::Addr(target), RouteTarget::Dir(dir) => Self::Dir(dir) });
}
routes.insert(0, Route::new("/", root)?);
Ok(Self::Routes(routes))
}
pub fn parse(raw: &str) -> Result<Self> {
let path = Path::new(raw);
if path.is_dir() { return Ok(Self::Dir(path.to_path_buf())); }
Ok(Self::Addr(Target::parse(raw)?))
}
}
const CATEGORIES: [&str; 4] = ["tor", "vpn", "datacenter", "blocklist"];
#[derive(Clone, Default)]
pub struct Rules {
pub allow_ips: Vec<String>,
pub allow_countries: Vec<String>,
pub block_ips: Vec<String>,
pub block_countries: Vec<String>,
pub block: Vec<String>,
}
fn split(values: Vec<String>) -> Vec<String> {
values.iter().flat_map(|value| value.split(',')).map(str::trim).filter(|value| !value.is_empty()).map(String::from).collect()
}
fn countries(values: Vec<String>) -> Result<Vec<String>> {
split(values).into_iter().map(|code| {
let code = code.to_uppercase();
if code.len() != 2 || !code.chars().all(|c| c.is_ascii_uppercase()) { bail!("\"{code}\" is not a country code"); }
Ok(code)
}).collect()
}
impl Rules {
pub fn ips(allow_ips: Vec<String>) -> Self {
Self { allow_ips, ..Self::default() }
}
pub fn new(allow_ips: Vec<String>, allow_countries: Vec<String>, block_ips: Vec<String>, block_countries: Vec<String>, block: Vec<String>) -> Result<Self> {
let block = split(block).into_iter().map(|entry| {
let entry = entry.to_lowercase();
if !CATEGORIES.contains(&entry.as_str()) { bail!("\"{entry}\" is not one of {}", CATEGORIES.join(", ")); }
Ok(entry)
}).collect::<Result<_>>()?;
Ok(Self { allow_ips: split(allow_ips), allow_countries: countries(allow_countries)?, block_ips: split(block_ips), block_countries: countries(block_countries)?, block })
}
fn is_empty(&self) -> bool {
self.allow_ips.is_empty() && self.allow_countries.is_empty() && self.block_ips.is_empty() && self.block_countries.is_empty() && self.block.is_empty()
}
}
#[derive(Clone, Default)]
pub struct Access {
pub rules: Rules,
pub password: Option<String>,
pub require_login: bool,
}
impl Access {
pub fn new(rules: Rules, password: Option<String>, require_login: bool) -> Result<Self> {
if password.is_some() && require_login {
bail!("Use either --password or --require-login, not both");
}
Ok(Self { rules, password, require_login })
}
fn as_json(&self) -> Option<serde_json::Value> {
if self.rules.is_empty() && self.password.is_none() && !self.require_login { return None; }
let auth = if self.require_login { "frislit" } else if self.password.is_some() { "password" } else { "none" };
let rules = &self.rules;
Some(json!({
"auth": auth,
"password": self.password,
"allow": { "ips": rules.allow_ips, "countries": rules.allow_countries },
"block": { "ips": rules.block_ips, "countries": rules.block_countries, "categories": rules.block },
}))
}
}
#[derive(Clone)]
pub struct Options { pub mode: &'static str, pub http_mode: Option<String>, pub target: TargetSpec, pub name: Option<String>, pub keep_host: bool, pub access: Access, pub shape: Shape }
impl Options {
pub fn http(target: TargetSpec, name: Option<String>, keep_host: bool, access: Access) -> Self {
Self { mode: "http", http_mode: None, target, name, keep_host, access, shape: Shape::default() }
}
pub fn tcp(target: Target, name: Option<String>, access: Access) -> Self {
Self { mode: "tcp", http_mode: None, target: TargetSpec::Addr(target), name, keep_host: false, access, shape: Shape::default() }
}
pub fn http_mode(mut self, http_mode: Option<String>) -> Self {
self.http_mode = http_mode;
self
}
pub fn shaped(self, shape: Shape) -> Self {
Self { shape, ..self }
}
}
pub fn server_hello(role: &str, token: Option<&str>) -> serde_json::Value {
let mut hello = json!({ "type": "hello", "version": PROTOCOL_VERSION, "role": role, "client": format!("frislit-cli/{}", env!("CARGO_PKG_VERSION")) });
if let Some(token) = token { hello["token"] = json!(token); }
hello
}
struct Registration { online: Online, resume_token: String }
async fn register(url: &str, token: &str, accept_invalid_certs: bool, opts: &Options, target: &Target, resume: Option<&str>, share: Option<&str>) -> Result<(Arc<Mux>, MuxEvents, Registration)> {
let (mux, mut events) = Mux::connect(url, Some(token), accept_invalid_certs).await?;
mux.send_control(server_hello("owner", Some(token))).await?;
expect(&mut events, "hello").await?;
let mut message = json!({
"type": "register", "mode": opts.mode, "target": target.authority(),
"name": opts.name, "keepHost": opts.keep_host, "resume": resume, "share": share,
});
if let Some(http_mode) = &opts.http_mode {
message["httpMode"] = json!(http_mode);
}
if let Some(policy) = opts.access.as_json() {
message["policy"] = policy;
}
mux.send_control(message).await?;
let msg = expect(&mut events, "registered").await?;
let get = |key: &str| msg.get(key).and_then(|v| v.as_str()).map(|s| s.to_string());
let registration = Registration {
online: Online {
id: get("id").context("registered without id")?,
url: get("url"),
share_code: get("shareCode"),
connect_url: get("connectUrl"),
custom_urls: msg.get("customUrls").and_then(|v| v.as_array()).map(|list| list.iter().filter_map(|v| v.as_str().map(String::from)).collect()).unwrap_or_default(),
persistent: msg.get("persistent").and_then(|v| v.as_bool()).unwrap_or(false),
access: get("access"),
},
resume_token: get("resumeToken").context("registered without resume token")?,
};
Ok((mux, events, registration))
}
enum Ended {
Dropped,
Error(String),
ByServer(String),
}
async fn serve_streams(events: &mut MuxEvents, target: &Target, shape: &Shape, out: &Events<TunnelEvent>) -> Ended {
loop {
tokio::select! {
stream = events.streams.recv() => {
let Some((writer, reader, meta)) = stream else { return Ended::Dropped };
let target = target.clone();
let shape = shape.clone();
tokio::spawn(async move { handle_stream(writer, reader, meta, target, shape).await; });
}
control = events.control.recv() => match control {
None => return Ended::Dropped,
Some(msg) => match msg.get("type").and_then(|t| t.as_str()) {
Some("error") => return Ended::Error(msg.get("message").and_then(|m| m.as_str()).unwrap_or("unknown error").to_string()),
Some("bye") => return Ended::ByServer(msg.get("reason").and_then(|r| r.as_str()).unwrap_or("closed by the server").to_string()),
Some("request") => { let _ = out.send(TunnelEvent::Request(Request::from_control(&msg))); }
Some("connection") => { let _ = out.send(TunnelEvent::Connection(Connection::from_control(&msg))); }
Some("access") => { let _ = out.send(TunnelEvent::Access(msg.get("access").and_then(|v| v.as_str()).unwrap_or("open to anyone").to_string())); }
_ => {}
},
}
}
}
}
pub async fn connect_target(addrs: &[SocketAddr]) -> Result<TcpStream> {
let mut last = anyhow::anyhow!("no address to connect to");
for addr in addrs {
match tokio::time::timeout(CONNECT_TIMEOUT, TcpStream::connect(addr)).await {
Ok(Ok(socket)) => { let _ = socket.set_nodelay(true); return Ok(socket); }
Ok(Err(err)) => last = err.into(),
Err(_) => last = anyhow::anyhow!("connect timed out"),
}
}
Err(last)
}
async fn handle_stream(writer: crate::mux::MuxWriter, reader: crate::mux::MuxReader, meta: OpenMeta, target: Target, shape: Shape) {
let Ok(addrs) = target.resolve().await else { writer.reset(); return };
if meta.is_udp() {
let _ = pump_udp_owner(addrs[0], writer, reader, &shape).await;
return;
}
let Ok(socket) = connect_target(&addrs).await else { writer.reset(); return };
if !target.tls { return pump_tcp(socket, writer, reader, &shape).await; }
match tokio::time::timeout(CONNECT_TIMEOUT, crate::tls::connect_trusting(&target.host, socket)).await {
Ok(Ok(stream)) => pump_tcp(stream, writer, reader, &shape).await,
_ => writer.reset(),
}
}
pub async fn prepare(opts: Options) -> Result<(Options, Target, String, Option<Task>)> {
let label = opts.target.label();
let (target, local) = match opts.target {
TargetSpec::Addr(target) => (target, None),
TargetSpec::Dir(dir) => {
if opts.mode == "tcp" { bail!("`frislit tcp` needs a port or host:port, not a directory"); }
local(serve::start(dir).await?)
}
TargetSpec::Routes(routes) => local(router::start(routes).await?),
};
Ok((Options { target: TargetSpec::Addr(target.clone()), ..opts }, target, label, local))
}
fn local((port, task): (u16, Task)) -> (Target, Option<Task>) {
(Target { host: "127.0.0.1".into(), port, tls: false }, Some(task))
}
fn is_fatal(text: &str) -> bool {
text.contains("(unauthorized)") || text.contains("(invalid_name)") || text.contains("(name_taken)") || text.contains("(name_reserved)") || text.contains("(quota_exceeded)")
}
pub async fn run(opts: Options, target: Target, out: Events<TunnelEvent>, mut stop: Stop) -> Result<()> {
let cfg = Config::load()?;
let (server_url, token) = cfg.require_auth()?;
let url = ws_url(&server_url);
let _ = out.send(TunnelEvent::Connecting);
let first = tokio::select! {
result = register(&url, &token, cfg.accept_invalid_certs, &opts, &target, None, None) => result,
_ = stop.wait() => return Ok(()),
};
let (mut mux, mut events, mut reg) = first?;
let _ = out.send(TunnelEvent::Online(reg.online.clone()));
let mut backoff = 1u64;
loop {
let outcome = tokio::select! {
result = serve_streams(&mut events, &target, &opts.shape, &out) => result,
_ = stop.wait() => {
let _ = mux.send_control(json!({ "type": "bye" })).await;
mux.close().await;
let _ = out.send(TunnelEvent::Stopped);
return Ok(());
}
};
match outcome {
Ended::Error(message) => bail!("Server error: {message}"),
Ended::ByServer(reason) => {
let _ = out.send(TunnelEvent::Ended(reason));
return Ok(());
}
Ended::Dropped => {}
}
let mut reason = None;
loop {
let _ = out.send(TunnelEvent::Reconnecting { seconds: backoff, reason: reason.take() });
tokio::select! {
_ = tokio::time::sleep(Duration::from_secs(backoff)) => {}
_ = stop.wait() => { let _ = out.send(TunnelEvent::Stopped); return Ok(()); }
}
let attempt = tokio::select! {
result = register(&url, &token, cfg.accept_invalid_certs, &opts, &target, Some(&reg.resume_token), reg.online.share_code.as_deref()) => result,
_ = stop.wait() => { let _ = out.send(TunnelEvent::Stopped); return Ok(()); }
};
match attempt {
Ok((new_mux, new_events, new_reg)) => {
let same = new_reg.online.id == reg.online.id;
mux = new_mux; events = new_events; reg = new_reg;
let _ = out.send(if same { TunnelEvent::Resumed(reg.online.clone()) } else { TunnelEvent::Replaced(reg.online.clone()) });
backoff = 1;
break;
}
Err(err) => {
let text = err.to_string();
if is_fatal(&text) { bail!("{text}"); }
backoff = (backoff * 2).min(30);
reason = Some(text);
}
}
}
}
}
+132
View File
@@ -0,0 +1,132 @@
use anyhow::{bail, Context, Result};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use crate::config::Config;
const REPOSITORY: &str = "https://git.fristy.net/fristy/frislit";
const CHECK_EVERY: u64 = 24 * 60 * 60;
pub const CURRENT: &str = env!("CARGO_PKG_VERSION");
#[derive(PartialEq)]
pub enum Install { Binary, Msi, Managed }
fn exe() -> Result<PathBuf> {
std::env::current_exe().context("Could not find the frislit binary")
}
fn owned_by(command: &str, args: &[&str], path: &Path) -> bool {
Command::new(command).args(args).arg(path).output().is_ok_and(|out| out.status.success())
}
pub fn detect() -> Install {
let Ok(path) = exe() else { return Install::Binary };
let text = path.to_string_lossy();
if cfg!(windows) {
let program_files = std::env::var("ProgramFiles").unwrap_or_default();
return if !program_files.is_empty() && text.starts_with(&program_files) { Install::Msi } else { Install::Binary };
}
let managed = text.contains("/Cellar/") || text.contains("/homebrew/")
|| (cfg!(target_os = "linux") && (owned_by("dpkg", &["-S"], &path) || owned_by("rpm", &["-qf"], &path)));
if managed { Install::Managed } else { Install::Binary }
}
fn parse(version: &str) -> Option<[u64; 3]> {
let mut parts = version.trim_start_matches('v').split('.').map(|part| part.parse::<u64>().ok());
Some([parts.next()??, parts.next()??, parts.next()??])
}
pub fn newer(candidate: &str) -> bool {
matches!((parse(candidate), parse(CURRENT)), (Some(a), Some(b)) if a > b)
}
fn client() -> Result<reqwest::Client> {
Ok(reqwest::Client::builder().user_agent(format!("frislit/{CURRENT}")).timeout(Duration::from_secs(60)).build()?)
}
pub async fn latest() -> Result<String> {
#[derive(serde::Deserialize)]
struct Release { tag_name: String }
let release: Release = client()?.get("https://git.fristy.net/api/v1/repos/fristy/frislit/releases/latest").send().await?.error_for_status()?.json().await?;
Ok(release.tag_name.trim_start_matches('v').to_string())
}
fn now() -> u64 {
SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
}
pub async fn check() -> Option<String> {
let mut cfg = Config::load().ok()?;
if now().saturating_sub(cfg.update_checked_at) < CHECK_EVERY {
return cfg.update_latest.clone().filter(|version| newer(version));
}
let version = latest().await.ok()?;
cfg.update_checked_at = now();
cfg.update_latest = Some(version.clone());
cfg.save().ok()?;
newer(&version).then_some(version)
}
fn asset(install: &Install) -> Result<&'static str> {
let gui = cfg!(feature = "gui");
Ok(match (install, std::env::consts::OS, std::env::consts::ARCH) {
(Install::Msi, _, "x86_64") => "frislit-x64.msi",
(Install::Msi, _, "aarch64") => "frislit-arm64.msi",
(_, "windows", "x86_64") => "frislit-windows-x64.exe",
(_, "windows", "aarch64") => "frislit-windows-arm64.exe",
(_, "linux", "x86_64") => if gui { "frislit-linux-x64" } else { "frislit-linux-x64-static" },
(_, "linux", "aarch64") => if gui { "frislit-linux-arm64" } else { "frislit-linux-arm64-static" },
(_, "linux", "arm") => "frislit-linux-armv7-static",
(_, "linux", "riscv64") => "frislit-linux-riscv64-static",
(_, "macos", "x86_64") => "frislit-macos-x64",
(_, "macos", "aarch64") => "frislit-macos-arm64",
(_, os, arch) => bail!("No prebuilt frislit for {os} {arch}"),
})
}
async fn download(version: &str, name: &str, to: &Path) -> Result<()> {
let url = format!("{REPOSITORY}/releases/download/v{version}/{name}");
let bytes = client()?.get(&url).send().await?.error_for_status().with_context(|| format!("Could not download {url}"))?.bytes().await?;
let magic: &[u8] = if name.ends_with(".msi") { b"\xD0\xCF\x11\xE0" } else if cfg!(windows) { b"MZ" } else if cfg!(target_os = "macos") { &[0xCF, 0xFA, 0xED, 0xFE] } else { b"\x7FELF" };
if !bytes.starts_with(magic) { bail!("The download does not look like a frislit build"); }
std::fs::write(to, &bytes)?;
Ok(())
}
pub async fn apply(version: &str, install: &Install, relaunch_gui: bool) -> Result<()> {
let name = asset(install)?;
#[cfg(windows)]
if *install == Install::Msi {
use std::os::windows::process::CommandExt;
let path = std::env::temp_dir().join(name);
download(version, name, &path).await?;
let mut script = format!("msiexec /i \"{}\" /passive /norestart", path.display());
if relaunch_gui { script.push_str(&format!(" && start \"\" \"{}\" gui", exe()?.display())); }
Command::new("cmd").args(["/c", &script]).creation_flags(0x0000_0008 | 0x0800_0000).spawn()?;
return Ok(());
}
#[cfg(not(windows))]
let _ = relaunch_gui;
let target = exe()?;
let staged = target.with_extension("update");
download(version, name, &staged).await?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&staged, std::fs::Permissions::from_mode(0o755))?;
}
if cfg!(windows) {
let old = target.with_extension("old");
let _ = std::fs::remove_file(&old);
std::fs::rename(&target, &old)?;
}
std::fs::rename(&staged, &target).map_err(|err| {
let _ = std::fs::remove_file(&staged);
if err.kind() == std::io::ErrorKind::PermissionDenied { anyhow::anyhow!("No permission to replace {}. Run `sudo frislit update`", target.display()) } else { err.into() }
})?;
Ok(())
}
pub fn cleanup() {
if let Ok(target) = exe() { let _ = std::fs::remove_file(target.with_extension("old")); }
}