Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions config.example.toml
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,8 @@ concurrency = 16
comments = true
comment_days = 60
comments_per_pass = 2000
# spotters known for spam and fakes, read once a day; "" for none
blacklist_url = "https://spotlist.store/spotnet/blacklist.xml"

[category]
enabled = true
Expand Down
9 changes: 8 additions & 1 deletion src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -553,6 +553,8 @@ pub struct SpotsConfig {
pub comment_days: u32,
/// comments whose text is read in one pass at most; the rest wait for the next
pub comments_per_pass: usize,
/// the Spotnet blacklist of spotters, read once a day (`spotnet::blacklist`); empty for none
pub blacklist_url: String,
}

impl Default for SpotsConfig {
Expand All @@ -566,6 +568,7 @@ impl Default for SpotsConfig {
comments: true,
comment_days: 60,
comments_per_pass: 2_000,
blacklist_url: crate::spotnet::blacklist::DEFAULT_URL.to_string(),
}
}
}
Expand Down Expand Up @@ -599,6 +602,9 @@ impl SpotsConfig {
if let Some(n) = int("comments_per_pass", 1, 100_000) {
c.comments_per_pass = n as usize;
}
if let Some(url) = v.get("blacklist_url").and_then(|u| u.as_str()) {
c.blacklist_url = url.trim().to_string();
}
c
}
}
Expand Down Expand Up @@ -1683,7 +1689,7 @@ mod tests {
assert_eq!(Config::from_value(&json!({})).spots, SpotsConfig::default());
let c = Config::from_value(
&json!({"spots": {"enabled": false, "poll_minutes": 0, "first_articles": 500, "per_pass": 20, "concurrency": 99,
"comments": false, "comment_days": 0, "comments_per_pass": 50}}),
"comments": false, "comment_days": 0, "comments_per_pass": 50, "blacklist_url": " "}}),
)
.spots;
assert_eq!(
Expand All @@ -1697,6 +1703,7 @@ mod tests {
comments: false,
comment_days: 1,
comments_per_pass: 50,
blacklist_url: String::new(),
}
);
assert_eq!(Config::from_value(&json!({"spots": "no"})).spots, SpotsConfig::default());
Expand Down
148 changes: 148 additions & 0 deletions src/spotnet/blacklist.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
//! The Spotnet blacklist: spotters known for spam, fakes and the like, as Spotweb takes them from `blacklist_url`
//! (an XML list of the spotters' public keys, `<Keys><Key Name="...">MODULUS</Key>...</Keys>`). Kept in the main
//! database's `spot_blacklist` by spotter id, read again once a day. A blacklisted spotter's spots aren't fetched,
//! their releases lose the spot tag, and their comments are hidden (`store::disposed_sql`).

use std::time::Duration;

use anyhow::{Result, anyhow, bail};
use rusqlite::{Connection, params};

/// Where Spotweb reads the blacklist.
pub const DEFAULT_URL: &str = "https://spotlist.store/spotnet/blacklist.xml";
/// How often the list is read again.
pub const REFRESH_SECS: i64 = 86_400;
/// The largest list read: the real one is under 100 KB.
const MAX_BYTES: u64 = 4 * 1024 * 1024;
/// When the list was last read, in the main database's `meta`.
const READ_AT: &str = "spot_blacklist_at";

/// The main database's table, if missing.
pub fn create(conn: &Connection) -> rusqlite::Result<()> {
conn.execute_batch("create table if not exists spot_blacklist (spotter TEXT PRIMARY KEY) without rowid")
}

/// The spotter ids a blacklist names, each once. Spotweb takes ids of 3 to 6 characters, and so does this.
pub fn parse(xml: &str) -> Vec<String> {
let mut out = Vec::new();
let mut rest = xml;
while let Some(open) = rest.find("<Key") {
rest = &rest[open + 4..];
// `<Keys>` is the list, not a key
if !rest.starts_with(['>', ' ', '\t', '\r', '\n']) {
continue;
}
let Some(start) = rest.find('>') else { break };
let Some(end) = rest[start..].find("</Key>") else { break };
let key = rest[start + 1..start + end].trim();
if let Some(id) = super::header::spotter_id(key).filter(|id| (3..=6).contains(&id.len()))
&& !out.contains(&id)
{
out.push(id);
}
rest = &rest[start + end..];
}
out
}

/// Reads the list at `url`. Blocking: call it off the runtime's threads.
pub fn fetch(url: &str) -> Result<String> {
let agent: ureq::Agent = ureq::Agent::config_builder()
.timeout_global(Some(Duration::from_secs(60)))
.user_agent(concat!("atlas/", env!("CARGO_PKG_VERSION")))
.build()
.into();
let mut response = agent.get(url).call().map_err(|e| anyhow!("{url}: {e}"))?;
Ok(response.body_mut().with_config().limit(MAX_BYTES).read_to_string()?)
}

/// Whether the list is due to be read again at `now`.
pub fn due(conn: &Connection, now: i64) -> rusqlite::Result<bool> {
let at = super::store::read_cursor(conn, READ_AT)?.and_then(|at| i64::try_from(at).ok());
Ok(at.is_none_or(|at| now - at >= REFRESH_SECS))
}

/// Puts `spotters` in place of the list kept, and notes when. An empty list is no list (a page that changed or an
/// error page): the one kept stays, and it's read again at the next refresh. Returns how many are listed.
pub fn replace(conn: &mut Connection, spotters: &[String], now: i64) -> Result<usize> {
if spotters.is_empty() {
bail!("the blacklist names no spotters");
}
let tx = conn.transaction()?;
tx.execute("delete from spot_blacklist", [])?;
{
let mut insert = tx.prepare_cached("insert or ignore into spot_blacklist (spotter) values (?)")?;
for s in spotters {
insert.execute(params![s])?;
}
}
super::store::write_cursor(&tx, READ_AT, now.max(0) as u64)?;
tx.commit()?;
Ok(spotters.len())
}

/// Empties the list kept, for a blacklist turned off; the next one turned on is read at once. Returns how many
/// spotters it named.
pub fn clear(conn: &Connection) -> rusqlite::Result<usize> {
let n = conn.execute("delete from spot_blacklist", [])?;
conn.execute("delete from meta where key = ?", [READ_AT])?;
Ok(n)
}

/// Notes a failed read, so it's tried again at the next refresh, not every pass.
pub fn tried(conn: &Connection, now: i64) -> rusqlite::Result<()> {
super::store::write_cursor(conn, READ_AT, now.max(0) as u64)
}

#[cfg(test)]
mod tests {
use super::*;

// two entries of the real list (spotlist.store, November 2026), one key twice, a blank and a non-key
const LIST: &str = r#"<Keys>
<Key Name="12garfield56">rKflaUf7aBQ6pFGm34N/sf1klvSsk9RmCLQClebgdFfo8lXr1l7NKuty77wo4qsn</Key>
<Key Name="aaaaaa">1COQWpNScg8ugJwHAvRVD9V2+HlaMTv2yKhdrKRJgZ2DirCXT/EmripwUvXMqMlz</Key>
<Key Name="again">rKflaUf7aBQ6pFGm34N/sf1klvSsk9RmCLQClebgdFfo8lXr1l7NKuty77wo4qsn</Key>
<Key Name="blank"></Key>
<KeyNote>not a key</KeyNote>
</Keys>"#;

#[test]
fn reads_the_spotter_ids() {
let ids = parse(LIST);
assert_eq!(ids.len(), 2, "{ids:?}");
assert_eq!(
ids[0],
crate::spotnet::header::spotter_id("rKflaUf7aBQ6pFGm34N/sf1klvSsk9RmCLQClebgdFfo8lXr1l7NKuty77wo4qsn")
.unwrap()
);
assert!(parse("<html>not found</html>").is_empty());
}

#[test]
fn replaces_the_list_and_keeps_it_on_an_empty_one() {
let mut conn = Connection::open_in_memory().unwrap();
conn.execute_batch("create table meta (key TEXT PRIMARY KEY, value INTEGER)").unwrap();
create(&conn).unwrap();
assert!(due(&conn, 100).unwrap());
assert_eq!(replace(&mut conn, &["abc".into(), "def".into()], 100).unwrap(), 2);
assert!(!due(&conn, 100 + REFRESH_SECS - 1).unwrap());
assert!(due(&conn, 100 + REFRESH_SECS).unwrap());
assert!(replace(&mut conn, &[], 200).is_err());
assert_eq!(replace(&mut conn, &["xyz".into()], 300).unwrap(), 1);
let left: Vec<String> = conn
.prepare("select spotter from spot_blacklist")
.unwrap()
.query_map([], |r| r.get(0))
.unwrap()
.map(|r| r.unwrap())
.collect();
assert_eq!(left, ["xyz"]);
tried(&conn, 400).unwrap();
assert!(!due(&conn, 401).unwrap());
// turned off: nothing left, and turned on again it's read at once
assert_eq!(clear(&conn).unwrap(), 1);
assert_eq!(clear(&conn).unwrap(), 0);
assert!(due(&conn, 402).unwrap());
}
}
40 changes: 39 additions & 1 deletion src/spotnet/ingest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ use crate::indexer::{Db, on_db};
use crate::nntp::{Pool, says_absent};

use super::store::{self, SAVED, SKIPPED, Settled, SpotRow};
use super::{MAX_XML_BYTES, SPOT_GROUP, binary, comments, full, header, release, sign};
use super::{MAX_XML_BYTES, SPOT_GROUP, binary, blacklist, comments, full, header, release, sign};

/// Overview lines asked for in one XOVER.
const XOVER_STEP: u64 = 5_000;
Expand Down Expand Up @@ -117,6 +117,16 @@ pub async fn pass(pool: &Arc<Pool>, db: &Db, config: &SpotsConfig, stopping: &im
let comments_off = !config.comments;
on_db(db, move |conn| Ok(store::prune(conn, now)? + if comments_off { comments::prune(conn, now)? } else { 0 }))
.await?;
if config.blacklist_url.is_empty() {
// turned off: the list kept goes too, so it no longer removes anything
match on_db(db, |conn| Ok(blacklist::clear(conn)?)).await {
Ok(0) => {}
Ok(n) => println!("spots: the blacklist is off, {n} spotters taken off it"),
Err(e) => eprintln!("spots: blacklist: {e:#}"),
}
} else {
refresh_blacklist(db, &config.blacklist_url, now).await;
}
match backfill_xml(pool, db, stopping).await {
Ok(0) => {}
Ok(n) => println!("spots: read the XML of {n} spots saved before it was kept"),
Expand Down Expand Up @@ -177,6 +187,34 @@ pub async fn pass(pool: &Arc<Pool>, db: &Db, config: &SpotsConfig, stopping: &im
Ok(done)
}

/// Reads the blacklist again when it's a day old. A failed read is logged, the list kept stays, and it's tried
/// again a day later.
async fn refresh_blacklist(db: &Db, url: &str, now: i64) {
match on_db(db, move |conn| Ok(blacklist::due(conn, now)?)).await {
Ok(true) => {}
Ok(false) => return,
Err(e) => return eprintln!("spots: blacklist: {e:#}"),
}
let u = url.to_string();
let read = tokio::task::spawn_blocking(move || blacklist::fetch(&u).map(|xml| blacklist::parse(&xml)))
.await
.map_err(|e| anyhow!("{e}"))
.and_then(|r| r);
let done = match read {
Ok(spotters) => on_db(db, move |conn| blacklist::replace(conn, &spotters, now)).await,
Err(e) => Err(e),
};
match done {
Ok(n) => println!("spots: the blacklist names {n} spotters"),
Err(e) => {
eprintln!("spots: blacklist {url}: {e:#}");
if let Err(e) = on_db(db, move |conn| Ok(blacklist::tried(conn, now)?)).await {
eprintln!("spots: blacklist: {e:#}");
}
}
}
}

/// What a spot task came to: settled (`SAVED`, `SKIPPED`, or None for one more try), or left for a later pass.
enum Waited {
Done(Option<i64>),
Expand Down
1 change: 1 addition & 0 deletions src/spotnet/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
//! spot's signatures.

pub mod binary;
pub mod blacklist;
pub mod category;
pub mod comments;
pub mod full;
Expand Down
66 changes: 48 additions & 18 deletions src/spotnet/store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ pub fn create_main(conn: &Connection) -> Result<()> {
PRIMARY KEY (message_id, spotter)
) without rowid;",
)?;
super::blacklist::create(conn)?;
super::comments::create(conn)
}

Expand Down Expand Up @@ -148,15 +149,17 @@ pub struct Disposal {
/// How long after a spot its spotter's own removal of it holds, as in Spotweb: five days.
pub const OWN_DISPOSAL_SECS: i64 = 5 * 86_400;

/// SQL for whether a disposal removes the row `s` (with its spot's `message_id`, and its spotter id in column
/// `spotter`), aliasing the disposal `d`. `created` is the column with when the spot was made, when the row has
/// one: a spotter's own removal holds only `OWN_DISPOSAL_SECS` after it.
/// SQL for whether the row `s` (with its spot's `message_id`, and its spotter id in column `spotter`) was removed:
/// by a disposal, aliased `d`, or because its spotter is on the blacklist (`blacklist`). `created` is the column
/// with when the spot was made, when the row has one: a spotter's own removal holds only `OWN_DISPOSAL_SECS` after
/// it.
pub(crate) fn disposed_sql(d: &str, s: &str, spotter: &str, created: Option<&str>) -> String {
// 0: the spot's XML had no date, so not known, as NULL
let made = created.map_or(format!("{d}.at"), |c| format!("coalesce(nullif({s}.{c}, 0), {d}.at)"));
format!(
"exists (select 1 from main.spot_disposals {d} where {d}.message_id = {s}.message_id
and ({d}.spotter = '' or ({d}.spotter = {s}.{spotter} and {d}.at - {made} <= {OWN_DISPOSAL_SECS})))"
"(exists (select 1 from main.spot_disposals {d} where {d}.message_id = {s}.message_id
and ({d}.spotter = '' or ({d}.spotter = {s}.{spotter} and {d}.at - {made} <= {OWN_DISPOSAL_SECS})))
or exists (select 1 from main.spot_blacklist {d}_b where {d}_b.spotter = {s}.{spotter}))"
)
}

Expand Down Expand Up @@ -597,15 +600,25 @@ pub struct Detail {
/// categories, size, when it was made)
pub spot: FullSpot,
pub xml: Xml,
/// when the spot was removed, and whether by a Spotnet moderator (else by its spotter)
/// when the spot was removed, and by whom
pub removed: Option<Removed>,
}

/// A spot's removal, for its release page.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Removed {
/// when the removal was posted; 0 for the blacklist, which says no when
pub at: i64,
pub by_moderator: bool,
pub by: RemovedBy,
}

/// Who took a spot back.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RemovedBy {
Moderator,
Spotter,
/// its spotter is on the Spotnet blacklist
Blacklist,
}

/// Release `id`'s spot, from its shard, when it has one.
Expand Down Expand Up @@ -652,19 +665,29 @@ pub fn detail_of_with(conn: &Connection, id: i64) -> Result<Option<Detail>> {
}

/// The removal of spot `message_id`, posted by `spotter_id` and made at `created` (0: not known), when there is
/// one that holds (`disposed_sql`): a moderator's first.
/// one that holds (`disposed_sql`): a moderator's first, then the spotter's own, then the blacklist.
fn removal(conn: &Connection, message_id: &str, spotter_id: Option<&str>, created: i64) -> Result<Option<Removed>> {
conn.query_row(
&format!(
"select at, spotter = '' from main.spot_disposals
let posted = conn
.query_row(
&format!(
"select at, spotter = '' from main.spot_disposals
where message_id = ?1
and (spotter = '' or (spotter = ?2 and at - coalesce(nullif(?3, 0), at) <= {OWN_DISPOSAL_SECS}))
order by spotter = '' desc, at limit 1"
),
params![message_id, spotter_id, created],
|r| Ok(Removed { at: r.get(0)?, by_moderator: r.get(1)? }),
)
.optional()
),
params![message_id, spotter_id, created],
|r| {
let by = if r.get(1)? { RemovedBy::Moderator } else { RemovedBy::Spotter };
Ok(Removed { at: r.get(0)?, by })
},
)
.optional()?;
if posted.is_some() {
return Ok(posted);
}
let listed =
conn.query_row("select 1 from main.spot_blacklist where spotter = ?", [spotter_id], |_| Ok(())).optional()?;
Ok(listed.map(|()| Removed { at: 0, by: RemovedBy::Blacklist }))
}

/// Spots of this shard saved before their XML was kept: (release id, spot message-id), at most `limit`, in no
Expand Down Expand Up @@ -1067,11 +1090,18 @@ mod tests {
left.sort();
assert_eq!(left, ["forged@spot.net", "kept@spot.net", "late@spot.net"], "removed past five days of the spot");
let removed = |n: usize| detail_of_with(&conn, ids[n]).unwrap().unwrap().removed;
assert_eq!(removed(0), Some(Removed { at: 10, by_moderator: true }));
assert_eq!(removed(1), Some(Removed { at: 10, by_moderator: false }));
assert_eq!(removed(0), Some(Removed { at: 10, by: RemovedBy::Moderator }));
assert_eq!(removed(1), Some(Removed { at: 10, by: RemovedBy::Spotter }));
assert_eq!(removed(2), None);
assert_eq!(removed(4), None);

// a blacklisted spotter: their saved spot loses its tag, and their waiting one isn't fetched
conn.execute("insert into spot_blacklist (spotter) values ('ddd')", []).unwrap();
assert_eq!(removed(3), Some(Removed { at: 0, by: RemovedBy::Blacklist }));
assert!(!spots_of_with(&conn, &ids).unwrap().contains_key(&ids[3]));
assert_eq!(todo(&conn, 10).unwrap(), ["forged@spot.net"]);
conn.execute("delete from spot_blacklist", []).unwrap();

// removals of nothing kept go after `KEEP_DAYS`; one of a saved spot or a spot still waiting stays
let saved = Settled { state: SAVED, release_id: Some(ids[0]), ..Default::default() };
settle(&conn, "mod@spot.net", Some(&saved), 0).unwrap();
Expand Down
Loading