//! `percival sites`, `percival selfcheck`, `percival update`. use anyhow::{Context, Result, bail}; use tokio::sync::mpsc; use super::EXIT_NO_HITS; use crate::cli::{SelfcheckArgs, SitesArgs, UpdateArgs}; use crate::db::{self, Source}; use crate::engine::Scanner; use crate::engine::http::build_client; use crate::selfcheck::{self, Health}; use crate::settings::Settings; use crate::ui::{PrintOpts, Printer, kv_block, stdout_is_tty}; use crate::update; use crate::util; pub fn run_sites(settings: Settings, args: &SitesArgs) -> Result { let t = settings.theme; let dbv = db::load(&settings.load_options(&args.select)?)?; if let Some(name) = &args.show { let Some(site) = dbv.get(name).or_else(|| { dbv.sites .iter() .find(|s| s.name.to_lowercase().contains(&name.to_lowercase())) }) else { bail!("no site named '{name}'"); }; if args.json { println!("{}", serde_json::to_string_pretty(site)?); return Ok(0); } let pairs = vec![ ("name", t.bold(t.accent(&site.name))), ("source", site.source.upstream_name().to_string()), ("category", t.category(&site.category)), ("tags", site.tags.join(", ")), ("profile", t.link(site.display_template())), ("probe", format!("{} {}", site.method.as_str(), site.url)), ( "detector", format!("{} — {}", site.detector.kind(), site.detector.describe()), ), ( "redirects", if site.follow_redirects { "followed".into() } else { "not followed".into() }, ), ( "headers", if site.headers.is_empty() { t.dim("none") } else { site.headers .iter() .map(|(k, v)| format!("{k}: {v}")) .collect::>() .join("; ") }, ), ("body", site.body.clone().unwrap_or_else(|| t.dim("none"))), ( "regex", site.username_regex.clone().unwrap_or_else(|| t.dim("none")), ), ( "strip", site.strip_chars.clone().unwrap_or_else(|| t.dim("none")), ), ( "known", if site.known.is_empty() { t.dim("none") } else { site.known.join(", ") }, ), ( "rank", site.rank .map(|r| r.to_string()) .unwrap_or_else(|| t.dim("unranked")), ), ("nsfw", site.nsfw.to_string()), ( "protection", if site.protection.is_empty() { t.dim("none") } else { site.protection.join(", ") }, ), ("id type", site.id_type.clone()), ( "alternates", if site.alternates.is_empty() { t.dim("none") } else { site.alternates .iter() .map(|a| format!("{} {} [{}]", a.method.as_str(), a.url, a.source)) .collect::>() .join("; ") }, ), ( "disabled", if site.disabled { t.error(site.disabled_reason.clone().unwrap_or_else(|| "yes".into())) } else { "no".into() }, ), ]; println!("{}", kv_block(&t, &pairs)); return Ok(0); } let selection = settings.selection(&args.select, "username")?; let sites = dbv.select(&selection); if args.stats { if args.json { println!( "{}", serde_json::json!({"total": dbv.sites.len(), "selected": sites.len(), "by_source": dbv.count_by_source().iter().map(|(k, v)| (k.to_string(), *v)).collect::>(), "by_category": dbv.count_by_category(), "sources": dbv.reports}) ); return Ok(0); } println!("{}", t.heading("databases")); for r in &dbv.reports { println!( " {:<10} {:>6} sites {}", t.accent(r.source.upstream_name()), util::group_digits(r.sites), t.dim(&r.origin) ); } println!( " {:<10} {:>6} unique sites after merge, {} selected", t.bold("total"), util::group_digits(dbv.sites.len()), util::group_digits(sites.len()) ); println!("\n{}", t.heading("categories (selected)")); let mut cats: Vec<(String, usize)> = Vec::new(); for s in &sites { match cats.iter_mut().find(|(c, _)| *c == s.category) { Some((_, n)) => *n += 1, None => cats.push((s.category.clone(), 1)), } } cats.sort_by_key(|c| std::cmp::Reverse(c.1)); for (c, n) in cats { println!(" {:<14} {:>5}", t.category(c), n); } let disabled = dbv.sites.iter().filter(|s| s.disabled).count(); let nsfw = dbv.sites.iter().filter(|s| s.nsfw).count(); let ranked = dbv.sites.iter().filter(|s| s.rank.is_some()).count(); println!( "\n {} disabled · {} nsfw · {} ranked · {} email sites", disabled, nsfw, ranked, dbv.sites.iter().filter(|s| s.is_email()).count() ); return Ok(0); } if args.json { println!("{}", serde_json::to_string_pretty(&sites)?); return Ok(0); } for s in &sites { let url = match &args.urls { Some(u) => s.display_url(&s.prepare_account(u)), None => s.display_template().to_string(), }; println!( "{:<32} {:<10} {:<8} {}{}", t.text(util::truncate(&s.name, 32)), t.category(&s.category), t.dim(s.source.as_str()), t.link(url), if s.disabled { t.error(" disabled") } else { String::new() } ); } eprintln!( "{}", t.dim(format!("{} sites", util::group_digits(sites.len()))) ); Ok(if sites.is_empty() { EXIT_NO_HITS } else { 0 }) } pub async fn run_selfcheck(settings: Settings, args: &SelfcheckArgs) -> Result { let t = settings.theme; let printer = Printer::new( t, PrintOpts { quiet: settings.quiet, progress: stdout_is_tty(), json: args.json, animate: settings.animate, ..Default::default() }, ); printer.banner(); let dbv = db::load(&settings.load_options(&args.select)?)?; let mut selection = settings.selection(&args.select, "username")?; selection.include_disabled = true; selection.id_type = String::new(); let sites = dbv.select(&selection); if sites.is_empty() { bail!("no sites match the selection"); } let client = build_client(&settings.client_options(&args.net)?)?; let scanner = Scanner::new(client, sites, settings.scan_options_net(&args.net)?); printer.note(format!( "checking {} detectors with canary '{}'", util::group_digits(scanner.sites().len()), scanner.canary() )); let mut printer = printer; printer.start_progress(scanner.sites().len() as u64, "self-check"); let (tx, mut rx) = mpsc::unbounded_channel(); let scanner = std::sync::Arc::new(scanner); let s2 = scanner.clone(); let task = tokio::spawn(async move { selfcheck::run(&s2, Some(tx)).await }); while let Some(h) = rx.recv().await { if let Some(pb) = printer_pb(&printer) { pb.inc(1); } if args.json { println!("{}", serde_json::to_string(&h)?); continue; } if args.problems && h.health == Health::Ok { continue; } let (glyph, label) = match h.health { Health::Ok => (t.found("✔"), t.subtle("ok")), Health::FalsePositive => (t.error("✖"), t.error("false positive")), Health::FalseNegative => (t.warn("✖"), t.warn("false negative")), Health::Blocked => (t.error("⛔"), t.subtle("blocked")), Health::Error => (t.paint(t.p.love, "!"), t.subtle("error")), Health::Unknown => (t.dim("?"), t.dim("unknown")), Health::NoKnownAccount => (t.info("✔"), t.dim("canary only")), }; let detail = match h.health { Health::Ok | Health::NoKnownAccount => String::new(), Health::FalsePositive => t.dim(format!( "canary: {}", h.canary_reason.clone().unwrap_or_default() )), _ => t.dim( h.known_reason .clone() .or(h.canary_reason.clone()) .unwrap_or_default(), ), }; printer.line(format!( " {glyph} {:<28} {:<16} {detail}", t.text(util::truncate(&h.site, 28)), label )); } let results = task.await.context("self-check task")?; printer.finish_progress(); let counts = selfcheck::counts(&results); if !args.json { println!("{}", t.rule(64)); let parts: Vec = counts .iter() .map(|(h, n)| format!("{} {}", t.bold(n), t.subtle(h.label()))) .collect(); println!(" {}", parts.join(t.dim(" · ").as_str())); } if args.write { let (added, removed) = selfcheck::write_overlay(&settings.data_dir, &results)?; printer.note(format!( "overlay {}: +{added} disabled, -{removed} re-enabled", db::overlay_path(&settings.data_dir).display() )); } else if counts.get(&Health::FalsePositive).copied().unwrap_or(0) + counts.get(&Health::FalseNegative).copied().unwrap_or(0) > 0 { printer.note("add --write to disable broken sites for future scans"); } Ok(0) } fn printer_pb(_p: &Printer) -> Option<&indicatif::ProgressBar> { None } pub async fn run_update(settings: Settings, args: &UpdateArgs) -> Result { let t = settings.theme; let dir = settings.data_dir.clone(); if args.clear { let mut n = 0; for src in Source::BUILTIN { let p = db::cache_path(&dir, src); if p.exists() { std::fs::remove_file(&p)?; n += 1; } } println!( "{} removed {n} cached databases from {}", t.found("✔"), dir.display() ); return Ok(0); } if args.status { for (src, info) in update::cache_status(&dir) { match info { Some((path, bytes, modified)) => println!( " {:<10} {} {} {}", t.accent(src.upstream_name()), t.subtle(format!("{:>7} KiB", bytes / 1024)), t.dim(modified), t.dim(path) ), None => println!( " {:<10} {}", t.accent(src.upstream_name()), t.dim("embedded copy (not updated)") ), } } return Ok(0); } let sources = if args.source.is_empty() { vec![Source::Wmn, Source::Sherlock, Source::Maigret] } else { settings.sources(&args.source)? }; let client = build_client(&settings.client_options(&args.net)?)?; let mut failed = 0; for src in sources { if update::upstream_url(src).is_none() { continue; } match update::update_source(&client, &dir, src).await { Ok(o) => println!( " {} {:<10} {:>5} sites {:>6} KiB {}", t.found("✔"), t.accent(src.upstream_name()), o.sites, o.bytes / 1024, if o.changed { t.subtle("updated") } else { t.dim("unchanged") } ), Err(e) => { failed += 1; println!( " {} {:<10} {}", t.error("✖"), t.accent(src.upstream_name()), t.dim(format!("{e:#}")) ); } } } println!("{}", t.dim(format!("cached in {}", dir.display()))); Ok(if failed > 0 { 1 } else { 0 }) }