chessbaseLinux/website/server/src/main.rs

630 lines
23 KiB
Rust
Raw Normal View History

//! The ChessPenguin website: serves the static page, answers "which release is the
//! latest" from the GitHub API (cached), counts downloads and redirects them to the
//! release files on GitHub (the visitor stays on the site), and shows the download
//! statistics behind a password.
//!
//! Nothing personal is stored: a download keeps its time, platform, version, the
//! country/region/city looked up from the IP (DB-IP Lite) and the browser language; the
//! IP itself is not written anywhere.
mod site;
use std::collections::HashMap;
use std::net::{IpAddr, SocketAddr};
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use axum::extract::{ConnectInfo, Path, Query, State};
use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
use axum::response::{Html, IntoResponse, Redirect, Response};
use axum::routing::get;
use axum::{Json, Router};
use base64::Engine as _;
use serde::Serialize;
use tower_http::services::ServeDir;
/// Downloadable files, by the platform names used in `/download/<platform>`.
pub const PLATFORMS: &[(&str, &str)] = &[
("windows", "-windows-x86_64.zip"),
("macos", "-macos-arm64.dmg"),
("deb", "_amd64.deb"),
("rpm", ".x86_64.rpm"),
("arch", ".pkg.tar.zst"),
("appimage", ".AppImage"),
("flatpak", ".flatpak"),
("tarball", "-linux-x86_64.tar.gz"),
("checksums", "SHA256SUMS.txt"),
];
/// The latest release is asked from GitHub at most this often.
const RELEASE_TTL: Duration = Duration::from_secs(600);
struct Config {
port: u16,
static_dir: PathBuf,
site_dir: PathBuf,
/// Public address of the site (canonical links, sitemap, Open Graph).
site_url: String,
db_path: PathBuf,
/// Geolocation databases (MaxMind DB format): DB-IP Lite City, either the official
/// file or the IPv4/IPv6 pair of ip-location-db; comma-separated.
geoip_paths: Vec<PathBuf>,
repo: String,
stats_user: String,
stats_password: String,
/// Take the client address from `X-Forwarded-For` / `X-Real-IP` (behind nginx).
trust_proxy: bool,
}
impl Config {
fn from_env() -> Config {
let var = |k: &str, d: &str| std::env::var(k).unwrap_or_else(|_| d.to_string());
Config {
port: var("PORT", "8080").parse().unwrap_or(8080),
static_dir: var("STATIC_DIR", "static").into(),
site_dir: var("SITE_DIR", "site").into(),
site_url: var("SITE_URL", "http://localhost:8080"),
db_path: var("DB_PATH", "data/downloads.sqlite").into(),
geoip_paths: var("GEOIP_DB", "data/dbip-city-ipv4.mmdb,data/dbip-city-ipv6.mmdb")
.split(',')
.map(|s| PathBuf::from(s.trim()))
.filter(|p| !p.as_os_str().is_empty())
.collect(),
repo: var("GITHUB_REPO", "vrubelroman/chessPenguin"),
stats_user: var("STATS_USER", "admin"),
stats_password: var("STATS_PASSWORD", ""),
trust_proxy: var("TRUST_PROXY", "1") != "0",
}
}
}
#[derive(Clone, Serialize)]
pub struct Asset {
pub platform: &'static str,
pub name: String,
pub size: u64,
#[serde(skip)]
url: String,
}
#[derive(Clone, Serialize)]
pub struct Release {
pub version: String,
pub published: String,
pub assets: Vec<Asset>,
}
struct AppState {
config: Config,
site: site::Site,
db: Mutex<rusqlite::Connection>,
geoip: Vec<maxminddb::Reader<Vec<u8>>>,
http: reqwest::Client,
release: tokio::sync::Mutex<Option<(Instant, Release)>>,
}
type Shared = Arc<AppState>;
#[tokio::main]
async fn main() {
let config = Config::from_env();
if let Some(dir) = config.db_path.parent() {
let _ = std::fs::create_dir_all(dir);
}
let db = rusqlite::Connection::open(&config.db_path).expect("open the database");
db.execute_batch(
"PRAGMA journal_mode = WAL;
CREATE TABLE IF NOT EXISTS downloads (
id INTEGER PRIMARY KEY,
ts TEXT NOT NULL, -- UTC, RFC 3339
platform TEXT NOT NULL,
version TEXT NOT NULL,
asset TEXT NOT NULL,
country TEXT, -- ISO 3166-1 alpha-2
region TEXT,
city TEXT,
lang TEXT, -- first browser language
referrer TEXT -- host of the referring page
);
CREATE INDEX IF NOT EXISTS downloads_ts ON downloads (ts);",
)
.expect("create the table");
let geoip: Vec<_> = config
.geoip_paths
.iter()
.filter_map(|p| match maxminddb::Reader::open_readfile(p) {
Ok(r) => Some(r),
Err(e) => {
eprintln!("geolocation database {} not used: {e}", p.display());
None
}
})
.collect();
if geoip.is_empty() {
eprintln!("geolocation off: downloads are stored without a country");
}
if config.stats_password.is_empty() {
eprintln!("STATS_PASSWORD is empty: /stats is disabled");
}
let port = config.port;
let static_dir = config.static_dir.clone();
let site = site::Site::load(&config.site_dir, config.site_url.clone());
let state: Shared = Arc::new(AppState {
site,
config,
db: Mutex::new(db),
geoip,
http: reqwest::Client::builder()
.user_agent("chesspenguin-site")
.timeout(Duration::from_secs(15))
.build()
.expect("http client"),
release: tokio::sync::Mutex::new(None),
});
let mut app = Router::new()
.route("/", get(home))
.route("/robots.txt", get(robots))
.route("/sitemap.xml", get(sitemap));
for (code, _, _) in site::LANGS.iter().skip(1) {
let code: &'static str = code;
app = app
.route(
&format!("/{code}/"),
get(move |s: State<Shared>| async move { page(s, code).await }),
)
.route(
&format!("/{code}"),
get(move || async move { Redirect::permanent(&format!("/{code}/")) }),
);
}
let not_found = {
let state = state.clone();
move || async move { (StatusCode::NOT_FOUND, Html(state.site.not_found("en"))) }
};
let app = app
.route("/api/release", get(api_release))
.route("/download/{platform}", get(download))
.route("/stats", get(stats))
.route("/stats.csv", get(stats_csv))
.route("/healthz", get(|| async { "ok" }))
.fallback_service(ServeDir::new(static_dir).fallback(get(not_found)))
.with_state(state);
let listener = tokio::net::TcpListener::bind(("0.0.0.0", port))
.await
.expect("bind");
println!("listening on :{port}");
axum::serve(
listener,
app.into_make_service_with_connect_info::<SocketAddr>(),
)
.with_graceful_shutdown(async {
let _ = tokio::signal::ctrl_c().await;
})
.await
.expect("serve");
}
/// `/`: English, or `?lang=xx` → `/xx/`.
async fn home(state: State<Shared>, Query(q): Query<HashMap<String, String>>) -> Response {
if let Some(lang) = q.get("lang")
&& lang != "en"
&& state.site.has_lang(lang)
{
return Redirect::permanent(&format!("/{lang}/")).into_response();
}
page(state, "en").await
}
async fn page(State(state): State<Shared>, lang: &'static str) -> Response {
let release = latest(&state).await;
let mut resp = Html(state.site.page(lang, release.as_ref())).into_response();
resp.headers_mut().insert(
header::CACHE_CONTROL,
HeaderValue::from_static("public, max-age=300"),
);
resp
}
async fn robots(State(state): State<Shared>) -> String {
format!(
"User-agent: *\nDisallow: /stats\nDisallow: /download/\nSitemap: {}/sitemap.xml\n",
state.site.url
)
}
async fn sitemap(State(state): State<Shared>) -> Response {
(
[(header::CONTENT_TYPE, "application/xml; charset=utf-8")],
state.site.sitemap(),
)
.into_response()
}
/// The latest release, from the cache or GitHub; the last good answer is kept when
/// GitHub fails.
async fn latest(state: &Shared) -> Option<Release> {
let mut cache = state.release.lock().await;
if let Some((at, r)) = cache.as_ref()
&& at.elapsed() < RELEASE_TTL
{
return Some(r.clone());
}
let url = format!(
"https://api.github.com/repos/{}/releases/latest",
state.config.repo
);
let fetched = async {
let v: serde_json::Value = state
.http
.get(&url)
.header("Accept", "application/vnd.github+json")
.send()
.await
.ok()?
.error_for_status()
.ok()?
.json()
.await
.ok()?;
let version = v["tag_name"].as_str()?.trim_start_matches('v').to_string();
let published = v["published_at"].as_str().unwrap_or("").to_string();
let mut assets = Vec::new();
for a in v["assets"].as_array()? {
let name = a["name"].as_str().unwrap_or("");
if let Some((platform, _)) = PLATFORMS.iter().find(|(_, end)| name.ends_with(end)) {
assets.push(Asset {
platform,
name: name.to_string(),
size: a["size"].as_u64().unwrap_or(0),
url: a["browser_download_url"].as_str()?.to_string(),
});
}
}
Some(Release {
version,
published,
assets,
})
}
.await;
match fetched {
Some(r) => {
*cache = Some((Instant::now(), r.clone()));
Some(r)
}
None => cache.as_ref().map(|(_, r)| r.clone()),
}
}
async fn api_release(State(state): State<Shared>) -> Response {
match latest(&state).await {
Some(r) => {
let mut resp = Json(r).into_response();
resp.headers_mut().insert(
header::CACHE_CONTROL,
HeaderValue::from_static("public, max-age=300"),
);
resp
}
None => (StatusCode::SERVICE_UNAVAILABLE, "release information unavailable").into_response(),
}
}
/// Counts the download and sends the browser to the file on GitHub.
async fn download(
State(state): State<Shared>,
Path(platform): Path<String>,
ConnectInfo(peer): ConnectInfo<SocketAddr>,
headers: HeaderMap,
) -> Response {
if !PLATFORMS.iter().any(|(p, _)| *p == platform) {
return (StatusCode::NOT_FOUND, Html(state.site.not_found("en"))).into_response();
}
// Without the release data the visitor still gets the files, from GitHub's page.
let fallback = format!("https://github.com/{}/releases/latest", state.config.repo);
let Some(release) = latest(&state).await else {
return Redirect::to(&fallback).into_response();
};
let Some(asset) = release.assets.iter().find(|a| a.platform == platform) else {
return Redirect::to(&fallback).into_response();
};
let ip = client_ip(&state.config, peer, &headers);
let (country, region, city) = locate(&state, ip);
let lang = headers
.get(header::ACCEPT_LANGUAGE)
.and_then(|v| v.to_str().ok())
.and_then(|v| v.split([',', ';']).next())
.map(|s| s.trim().chars().take(16).collect::<String>());
let referrer = headers
.get(header::REFERER)
.and_then(|v| v.to_str().ok())
.and_then(|v| v.split('/').nth(2))
.map(|s| s.chars().take(64).collect::<String>());
if let Ok(db) = state.db.lock() {
let _ = db.execute(
"INSERT INTO downloads (ts, platform, version, asset, country, region, city, lang, referrer)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
rusqlite::params![
chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
asset.platform,
release.version,
asset.name,
country,
region,
city,
lang,
referrer
],
);
}
Redirect::to(&asset.url).into_response()
}
fn client_ip(config: &Config, peer: SocketAddr, headers: &HeaderMap) -> IpAddr {
if config.trust_proxy {
let forwarded = headers
.get("x-forwarded-for")
.and_then(|v| v.to_str().ok())
.and_then(|v| v.split(',').next())
.or_else(|| headers.get("x-real-ip").and_then(|v| v.to_str().ok()))
.and_then(|s| s.trim().parse().ok());
if let Some(ip) = forwarded {
return ip;
}
}
peer.ip()
}
/// Country code, region and city of an address (all `None` without a database). Reads
/// both the GeoIP2-style records of the official DB-IP file (`country.iso_code`,
/// `subdivisions[0].names.en`, `city.names.en`) and the flat ones of ip-location-db
/// (`country_code`, `state1`, `city`).
fn locate(state: &AppState, ip: IpAddr) -> (Option<String>, Option<String>, Option<String>) {
let record = state.geoip.iter().find_map(|reader| {
reader
.lookup(ip)
.ok()?
.decode::<serde_json::Value>()
.ok()
.flatten()
});
let Some(r) = record else {
return (None, None, None);
};
let text = |v: &serde_json::Value| v.as_str().filter(|s| !s.is_empty()).map(str::to_string);
let country = text(&r["country_code"]).or_else(|| text(&r["country"]["iso_code"]));
let region = text(&r["state1"]).or_else(|| text(&r["subdivisions"][0]["names"]["en"]));
let city = text(&r["city"]).or_else(|| text(&r["city"]["names"]["en"]));
(country, region, city)
}
/// Basic authentication against STATS_USER / STATS_PASSWORD.
fn authorized(config: &Config, headers: &HeaderMap) -> bool {
if config.stats_password.is_empty() {
return false;
}
let Some(value) = headers
.get(header::AUTHORIZATION)
.and_then(|v| v.to_str().ok())
.and_then(|v| v.strip_prefix("Basic "))
else {
return false;
};
let expected = format!("{}:{}", config.stats_user, config.stats_password);
base64::engine::general_purpose::STANDARD
.decode(value.trim())
.is_ok_and(|d| d == expected.as_bytes())
}
fn ask_password() -> Response {
(
StatusCode::UNAUTHORIZED,
[(header::WWW_AUTHENTICATE, "Basic realm=\"ChessPenguin stats\"")],
"Password required",
)
.into_response()
}
/// Rows of `SELECT label, count` as pairs.
fn pairs(db: &rusqlite::Connection, sql: &str) -> Vec<(String, i64)> {
let Ok(mut stmt) = db.prepare(sql) else {
return Vec::new();
};
stmt.query_map([], |r| {
Ok((
r.get::<_, Option<String>>(0)?.unwrap_or_else(|| "—".into()),
r.get::<_, i64>(1)?,
))
})
.map(|rows| rows.flatten().collect())
.unwrap_or_default()
}
fn count(db: &rusqlite::Connection, filter: &str) -> i64 {
db.query_row(
&format!("SELECT COUNT(*) FROM downloads WHERE platform <> 'checksums' {filter}"),
[],
|r| r.get(0),
)
.unwrap_or(0)
}
fn esc(s: &str) -> String {
s.replace('&', "&amp;")
.replace('<', "&lt;")
.replace('>', "&gt;")
.replace('"', "&quot;")
}
/// A ranked list with bars.
fn table(title: &str, rows: &[(String, i64)]) -> String {
let max = rows.iter().map(|r| r.1).max().unwrap_or(1).max(1);
let mut out = format!("<section><h2>{}</h2><table>", esc(title));
if rows.is_empty() {
out.push_str("<tr><td class=muted>No downloads yet</td></tr>");
}
for (label, n) in rows {
let w = (*n as f64 / max as f64 * 100.0).round();
out.push_str(&format!(
"<tr><td>{}</td><td class=num>{n}</td><td class=bar><span style=\"width:{w}%\"></span></td></tr>",
esc(label)
));
}
out.push_str("</table></section>");
out
}
async fn stats(State(state): State<Shared>, headers: HeaderMap) -> Response {
if !authorized(&state.config, &headers) {
return ask_password();
}
let Ok(db) = state.db.lock() else {
return StatusCode::INTERNAL_SERVER_ERROR.into_response();
};
// "Today" and the days follow the server's time zone (TZ in the environment).
let total = count(&db, "");
let today = count(&db, "AND date(ts, 'localtime') = date('now', 'localtime')");
let week = count(&db, "AND ts >= datetime('now', '-7 days')");
let month = count(&db, "AND ts >= datetime('now', '-30 days')");
let base = "FROM downloads WHERE platform <> 'checksums'";
let by_platform = pairs(&db, &format!("SELECT platform, COUNT(*) {base} GROUP BY 1 ORDER BY 2 DESC"));
let by_version = pairs(&db, &format!("SELECT version, COUNT(*) {base} GROUP BY 1 ORDER BY 2 DESC LIMIT 15"));
let by_country = pairs(&db, &format!("SELECT country, COUNT(*) {base} GROUP BY 1 ORDER BY 2 DESC LIMIT 30"));
let by_region = pairs(
&db,
&format!(
"SELECT country || ' · ' || COALESCE(region, '—') || COALESCE(' · ' || city, ''), COUNT(*) {base} GROUP BY 1 ORDER BY 2 DESC LIMIT 30"
),
);
let by_lang = pairs(&db, &format!("SELECT lang, COUNT(*) {base} GROUP BY 1 ORDER BY 2 DESC LIMIT 15"));
let days: HashMap<String, i64> = pairs(
&db,
&format!(
"SELECT date(ts, 'localtime'), COUNT(*) {base} AND ts >= datetime('now', '-31 days') GROUP BY 1"
),
)
.into_iter()
.collect();
let mut daily = Vec::new();
for back in (0..30).rev() {
let day = (chrono::Local::now() - chrono::Duration::days(back))
.format("%Y-%m-%d")
.to_string();
let n = days.get(&day).copied().unwrap_or(0);
daily.push((day, n));
}
let max_day = daily.iter().map(|d| d.1).max().unwrap_or(1).max(1);
let mut chart = String::from("<section class=wide><h2>Last 30 days</h2><div class=chart>");
for (day, n) in &daily {
let h = (*n as f64 / max_day as f64 * 100.0).round();
chart.push_str(&format!(
"<div title=\"{day}: {n}\"><span style=\"height:{h}%\"></span><small>{}</small></div>",
&day[8..]
));
}
chart.push_str("</div></section>");
let mut recent = String::from(
"<section class=wide><h2>Latest downloads</h2><table><tr><th>Time (UTC)</th><th>Platform</th><th>Version</th><th>Where</th><th>Language</th><th>From</th></tr>",
);
if let Ok(mut stmt) = db.prepare(
"SELECT ts, platform, version, country, region, city, lang, referrer FROM downloads ORDER BY id DESC LIMIT 50",
) {
let rows = stmt.query_map([], |r| {
let s = |i| r.get::<_, Option<String>>(i).map(|v| v.unwrap_or_default());
Ok([s(0)?, s(1)?, s(2)?, s(3)?, s(4)?, s(5)?, s(6)?, s(7)?])
});
for row in rows.into_iter().flatten().flatten() {
let place = [&row[3], &row[4], &row[5]]
.iter()
.filter(|s| !s.is_empty())
.map(|s| esc(s))
.collect::<Vec<_>>()
.join(" · ");
recent.push_str(&format!(
"<tr><td>{}</td><td>{}</td><td>{}</td><td>{place}</td><td>{}</td><td>{}</td></tr>",
esc(&row[0].replace('T', " ").replace('Z', "")),
esc(&row[1]),
esc(&row[2]),
esc(&row[6]),
esc(&row[7])
));
}
}
recent.push_str("</table></section>");
let tile = |label: &str, n: i64| format!("<div class=tile><b>{n}</b><span>{label}</span></div>");
let page = format!(
r#"<!doctype html><html lang=en><head><meta charset=utf-8><meta name=viewport content="width=device-width,initial-scale=1">
<meta name=robots content=noindex><title>ChessPenguin · downloads</title><style>
:root{{color-scheme:light dark;--bg:#f6f7f9;--fg:#1b1f24;--muted:#6b7280;--card:#fff;--line:#e5e7eb;--accent:#1f6fa8}}
@media(prefers-color-scheme:dark){{:root{{--bg:#16181b;--fg:#e6e8eb;--muted:#9aa1ab;--card:#1f2226;--line:#2c3036;--accent:#4a9be0}}}}
body{{margin:0;font:15px/1.45 system-ui,sans-serif;background:var(--bg);color:var(--fg)}}
main{{max-width:1100px;margin:0 auto;padding:24px 16px}} h1{{font-size:22px;margin:0 0 16px}}
.tiles{{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:12px;margin-bottom:20px}}
.tile{{background:var(--card);border:1px solid var(--line);border-radius:10px;padding:14px}}
.tile b{{display:block;font-size:28px}} .tile span{{color:var(--muted)}}
.grid{{display:grid;grid-template-columns:repeat(auto-fit,minmax(320px,1fr));gap:16px}}
section{{background:var(--card);border:1px solid var(--line);border-radius:10px;padding:14px;overflow-x:auto}}
section.wide{{margin-top:16px}} h2{{font-size:15px;margin:0 0 10px}}
table{{border-collapse:collapse;width:100%}} td,th{{padding:4px 6px;border-bottom:1px solid var(--line);text-align:left;white-space:nowrap}}
.num{{text-align:right;width:60px}} .bar{{width:40%}} .bar span{{display:block;height:8px;border-radius:4px;background:var(--accent)}}
.muted{{color:var(--muted)}} .chart{{display:flex;align-items:flex-end;gap:3px;height:140px}}
.chart div{{flex:1;display:flex;flex-direction:column;justify-content:flex-end;height:100%;text-align:center}}
.chart span{{background:var(--accent);border-radius:3px 3px 0 0;min-height:1px}} .chart small{{color:var(--muted);font-size:10px}}
a{{color:var(--accent)}}</style></head><body><main>
<h1>ChessPenguin downloads</h1>
<div class=tiles>{}{}{}{}</div>
<div class=grid>{}{}{}{}{}</div>{chart}{recent}
<p class=muted>Checksum downloads are not counted. <a href="/stats.csv">Download all as CSV</a> · IP geolocation by <a href="https://db-ip.com">DB-IP</a></p>
</main></body></html>"#,
tile("today", today),
tile("last 7 days", week),
tile("last 30 days", month),
tile("all time", total),
table("By platform", &by_platform),
table("By version", &by_version),
table("By country", &by_country),
table("By region and city", &by_region),
table("By browser language", &by_lang),
);
Html(page).into_response()
}
async fn stats_csv(State(state): State<Shared>, headers: HeaderMap) -> Response {
if !authorized(&state.config, &headers) {
return ask_password();
}
let Ok(db) = state.db.lock() else {
return StatusCode::INTERNAL_SERVER_ERROR.into_response();
};
let mut out = String::from("time_utc,platform,version,asset,country,region,city,language,referrer\n");
if let Ok(mut stmt) = db.prepare(
"SELECT ts, platform, version, asset, country, region, city, lang, referrer FROM downloads ORDER BY id",
) {
let rows = stmt.query_map([], |r| {
(0..9)
.map(|i| r.get::<_, Option<String>>(i).map(|v| v.unwrap_or_default()))
.collect::<Result<Vec<_>, _>>()
});
for row in rows.into_iter().flatten().flatten() {
let cells: Vec<String> = row
.iter()
.map(|c| format!("\"{}\"", c.replace('"', "\"\"")))
.collect();
out.push_str(&cells.join(","));
out.push('\n');
}
}
(
[
(header::CONTENT_TYPE, "text/csv; charset=utf-8"),
(
header::CONTENT_DISPOSITION,
"attachment; filename=\"chesspenguin-downloads.csv\"",
),
],
out,
)
.into_response()
}