use std::fs::{File, OpenOptions};
use std::io::{self, BufRead, BufReader, BufWriter, Write};
use std::path::PathBuf;
use std::process::ExitCode;
use std::time::Duration;
use legit_hasher::{DEFAULT_MAX_LINE_BYTES, Finished, Info, RunConfig, Settings, Summary};
#[cfg(feature = "serve")]
mod serve_command;
const HELP: &str = "\
legit-hasher: every legit-hashes definition, images and text, over JSON lines
Usage:
legit-hasher run [options] hash requests, one JSON line each, into results
legit-hasher distance [options] compare pairs of stored hashes or signatures
legit-hasher info [limits] print the definitions, limits and CPU as JSON
legit-hasher serve [options] take hashing tasks from Redis Streams and reply
(in a build with the `serve` feature)
legit-hasher help print this help
legit-hasher --version print the version
Input and output (run, distance):
--input FILE read from FILE rather than standard input
--output FILE write to FILE rather than standard output
Run:
--jobs N hash N requests at once (default: the available cores)
--unordered write each result as it finishes, not in request order
--timings add the time each step took, in microseconds
--resume skip requests whose ids already have a result in --output,
and append to it; a torn last line is cut and redone
--retry-failed with --resume, run the failed requests again too
--progress SECONDS report progress on standard error at this interval
Limits (run, info):
--max-line-bytes N the longest request line read (default: 8388608)
--max-pixels N refuse images of more pixels as too_large, and images whose
size can't be read before decoding (default: none)
--max-text-bytes N refuse longer texts as too_large (default: none; the line
limit bounds them)
Serve:
--redis URL the Redis server, such as redis://127.0.0.1:6379; without
it, LEGIT_HASHER_REDIS_URL, which keeps a password off the
command line
--key-prefix PREFIX a prefix every key on the server carries (default: none)
--kind KIND the task kind, which names the streams (default: hash)
--consumer NAME this worker's name in the group (default: legit-hasher-HOST);
the process id is added
--jobs N bulk tasks run at once (default: the available cores)
--fast-jobs N fast-lane tasks run at once (default: 2)
--no-fast serve the bulk lane only
--allow-host HOST[:PORT] fetch image_url sources from HOST, a name, *.example.com for
every name under one, or an address ([v6]:PORT with a port),
on PORT or else the scheme's default port; repeatable. With
none, every image_url is refused
--allow-hosts-file FILE the same, one host a line
--allow-range CIDR also connect to addresses in CIDR, such as 10.0.0.0/8, or to
one address; every
address that isn't public unicast is refused without one;
repeatable
--allow-http fetch plain http URLs too, for a private network
--max-fetch-bytes N the longest body fetched (default and most: 67108864)
--connect-timeout S seconds allowed to connect (default: 10)
--fetch-timeout S seconds allowed for a whole fetch (default: 60)
--max-redirects N redirects followed, each checked as the URL is (default: 0)
--connect-retries N times a request is tried again when it couldn't connect, or
lost its connection before any byte of a reply (default: 1)
--idle-timeout S seconds a connection may stay idle and still be reused
(default: 60)
--user-agent TEXT the User-Agent fetches send (default: legit-hasher/VERSION)
--max-pixels N as for run (default: 50000000)
--max-text-bytes N as for run (default: 1048576)
--shutdown-grace S seconds a stop waits for tasks already fetching or hashing;
a task not yet fetching is released at once (default: 30)
--heartbeat S seconds between heartbeat lines (default: 30)
--stats-file PATH rewrite PATH whole with a JSON document of what the worker
has done, at the start, every heartbeat and the stop; its
directory must exist
--events-file PATH replace PATH every interval with the tasks answered in it,
four numbers each, when there was one; its directory must
exist, and it isn't the stats file
--events-interval S seconds between events documents, from 0.2 to 60 (default: 1)
--events-max N the most tasks one events document holds; the rest are
counted in its dropped, from 1 to 100000 (default: 10000)
--events-socket PATH send a datagram to the Unix socket a collector has bound at
PATH when each task starts and when it is answered; dropped
when nobody can take it at once. Unix only
--timings as for run
Log lines and heartbeats are JSON on standard error. SIGTERM or SIGINT stops it
cleanly; a second one stops it at once.
Memory: on 64-bit Linux with glibc, run and serve keep freed memory for reuse; set
LEGIT_HASHER_MALLOC=default, or GLIBC_TUNABLES, to keep glibc's own settings.
Exit status: 0 when every request succeeded, 1 when any request or definition
failed (each failure is a result line), 2 when the run itself couldn't go on.
`serve` exits 0 after a clean stop on a signal, and 2 when it couldn't run.
The request and result formats are in the README: https://docs.rs/legit-hasher
";
struct Usage(String);
const HELP_ASKED: &str = "--help";
#[derive(Default)]
struct Arguments {
input: Option<PathBuf>,
output: Option<PathBuf>,
jobs: Option<usize>,
unordered: bool,
timings: bool,
resume: bool,
retry_failed: bool,
progress: Option<Duration>,
max_line_bytes: Option<usize>,
max_pixels: Option<u64>,
max_text_bytes: Option<u64>,
user_agent: Option<String>,
}
#[cfg(all(target_os = "linux", target_env = "gnu", target_pointer_width = "64"))]
fn keep_freed_memory() {
use std::ffi::c_int;
const M_TRIM_THRESHOLD: c_int = -1;
const M_MMAP_THRESHOLD: c_int = -3;
unsafe extern "C" {
fn mallopt(param: c_int, value: c_int) -> c_int;
}
unsafe {
mallopt(M_MMAP_THRESHOLD, 32 << 20);
mallopt(M_TRIM_THRESHOLD, 128 << 20);
}
}
#[cfg(not(all(target_os = "linux", target_env = "gnu", target_pointer_width = "64")))]
const fn keep_freed_memory() {}
fn main() -> ExitCode {
let mut arguments = std::env::args().skip(1);
let command = arguments.next();
if matches!(command.as_deref(), Some("run" | "serve"))
&& legit_hasher::Malloc::detect() == legit_hasher::Malloc::Tuned
{
keep_freed_memory();
}
let rest: Vec<String> = arguments.collect();
let result = match command.as_deref() {
Some("run") => parse(&rest, &RUN_FLAGS).and_then(|arguments| run(&arguments)),
Some("distance") => parse(&rest, &["--input", "--output"]).and_then(|arguments| distance(&arguments)),
Some("info") => parse(&rest, INFO_FLAGS).and_then(|arguments| info(&arguments)),
#[cfg(feature = "serve")]
Some("serve") => serve_command::serve(&rest),
#[cfg(not(feature = "serve"))]
Some("serve") => Err(Usage(
"this build has no `serve`; build it with `--features serve`".to_owned(),
)),
Some("help" | "--help" | "-h") | None => {
print!("{HELP}");
Ok(ExitCode::SUCCESS)
}
Some("--version" | "-V") => {
println!("legit-hasher {}", env!("CARGO_PKG_VERSION"));
Ok(ExitCode::SUCCESS)
}
Some(other) => Err(Usage(format!("there's no command `{other}`"))),
};
result.unwrap_or_else(|Usage(message)| {
if message == HELP_ASKED {
print!("{HELP}");
return ExitCode::SUCCESS;
}
eprintln!("legit-hasher: {message}; see `legit-hasher help`");
ExitCode::from(2)
})
}
const RUN_FLAGS: [&str; 11] = [
"--input",
"--output",
"--jobs",
"--unordered",
"--timings",
"--resume",
"--retry-failed",
"--progress",
"--max-line-bytes",
"--max-pixels",
"--max-text-bytes",
];
const INFO_FLAGS: &[&str] = &[
"--max-line-bytes",
"--max-pixels",
"--max-text-bytes",
#[cfg(feature = "serve")]
"--user-agent",
];
fn parse(rest: &[String], allowed: &[&str]) -> Result<Arguments, Usage> {
let mut arguments = Arguments::default();
let mut iter = rest.iter();
while let Some(flag) = iter.next() {
let (flag, inline) = match flag.split_once('=') {
Some((flag, value)) if flag.starts_with("--") => (flag, Some(value.to_owned())),
_ => (flag.as_str(), None),
};
if matches!(flag, "--help" | "-h") {
return Err(Usage(HELP_ASKED.to_owned()));
}
if !allowed.contains(&flag) {
return Err(Usage(format!("`{flag}` isn't an option here")));
}
let mut value = || {
inline
.clone()
.or_else(|| iter.next().cloned())
.ok_or_else(|| Usage(format!("`{flag}` needs a value")))
};
match flag {
"--input" => arguments.input = Some(PathBuf::from(value()?)),
"--output" => arguments.output = Some(PathBuf::from(value()?)),
"--jobs" => arguments.jobs = Some(number(flag, &value()?, 1)?),
"--progress" => arguments.progress = Some(Duration::from_secs(number(flag, &value()?, 1)?)),
"--max-line-bytes" => arguments.max_line_bytes = Some(number(flag, &value()?, 1)?),
"--max-pixels" => arguments.max_pixels = Some(number(flag, &value()?, 1)?),
"--max-text-bytes" => arguments.max_text_bytes = Some(number(flag, &value()?, 0)?),
"--user-agent" => arguments.user_agent = Some(value()?),
"--unordered" => arguments.unordered = true,
"--timings" => arguments.timings = true,
"--resume" => arguments.resume = true,
_ => arguments.retry_failed = true,
}
}
Ok(arguments)
}
fn number<T: std::str::FromStr + PartialOrd + From<u8>>(flag: &str, text: &str, least: u8) -> Result<T, Usage> {
match text.parse::<T>() {
Ok(value) if value >= T::from(least) => Ok(value),
_ => Err(Usage(format!(
"`{flag}` takes a whole number of at least {least}, not `{text}`"
))),
}
}
fn input(arguments: &Arguments) -> Result<Box<dyn BufRead + Send>, Usage> {
match &arguments.input {
Some(path) if path.as_os_str() != "-" => File::open(path)
.map(|file| Box::new(BufReader::with_capacity(1 << 16, file)) as Box<dyn BufRead + Send>)
.map_err(|error| Usage(format!("couldn't open `{}`: {error}", path.display()))),
_ => Ok(Box::new(BufReader::with_capacity(1 << 16, io::stdin()))),
}
}
fn exit(summary: Summary) -> ExitCode {
if summary.failed > 0 {
ExitCode::from(1)
} else {
ExitCode::SUCCESS
}
}
fn fatal(error: &legit_hasher::Error) -> ExitCode {
eprintln!("legit-hasher: {error}");
ExitCode::from(2)
}
fn run(arguments: &Arguments) -> Result<ExitCode, Usage> {
if arguments.resume && arguments.output.is_none() {
return Err(Usage(
"`--resume` needs `--output FILE`, the results to resume".to_owned(),
));
}
if arguments.retry_failed && !arguments.resume {
return Err(Usage("`--retry-failed` goes with `--resume`".to_owned()));
}
let config = RunConfig {
jobs: arguments.jobs.unwrap_or_else(|| RunConfig::new().jobs),
ordered: !arguments.unordered,
settings: Settings {
timings: arguments.timings,
max_pixels: arguments.max_pixels,
max_text_bytes: arguments.max_text_bytes,
},
max_line_bytes: arguments.max_line_bytes.unwrap_or(DEFAULT_MAX_LINE_BYTES),
progress: arguments.progress,
};
let reader = input(arguments)?;
let finished = match (&arguments.output, arguments.resume) {
(Some(path), true) => match Finished::load(path, arguments.retry_failed) {
Ok(finished) => finished,
Err(error) => return Ok(fatal(&error)),
},
_ => Finished::default(),
};
let summary = match &arguments.output {
Some(path) => {
let file = if arguments.resume {
OpenOptions::new().create(true).append(true).open(path)
} else {
OpenOptions::new().create_new(true).write(true).open(path)
};
let file = match file {
Ok(file) => file,
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {
return Err(Usage(format!(
"`{}` exists; pass `--resume` to continue it, or remove it",
path.display()
)));
}
Err(error) => return Err(Usage(format!("couldn't open `{}`: {error}", path.display()))),
};
legit_hasher::run(reader, BufWriter::with_capacity(1 << 16, file), &config, &finished)
}
None => legit_hasher::run(reader, BufWriter::new(io::stdout().lock()), &config, &finished),
};
Ok(summary.map_or_else(|error| fatal(&error), exit))
}
fn distance(arguments: &Arguments) -> Result<ExitCode, Usage> {
let reader = input(arguments)?;
let summary = match &arguments.output {
Some(path) => match OpenOptions::new().create_new(true).write(true).open(path) {
Ok(file) => legit_hasher::distances(reader, BufWriter::new(file)),
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {
return Err(Usage(format!("`{}` exists; remove it", path.display())));
}
Err(error) => return Err(Usage(format!("couldn't open `{}`: {error}", path.display()))),
},
None => legit_hasher::distances(reader, BufWriter::new(io::stdout().lock())),
};
Ok(summary.map_or_else(|error| fatal(&error), exit))
}
fn info(arguments: &Arguments) -> Result<ExitCode, Usage> {
#[cfg_attr(not(feature = "serve"), allow(unused_mut))]
let mut info = Info::detect(
Settings {
timings: false,
max_pixels: arguments.max_pixels,
max_text_bytes: arguments.max_text_bytes,
},
arguments.max_line_bytes.unwrap_or(DEFAULT_MAX_LINE_BYTES),
);
#[cfg(feature = "serve")]
if let (Some(serve), Some(user_agent)) = (info.serve.as_mut(), &arguments.user_agent) {
legit_hasher::serve::FetchPolicy::new()
.with_user_agent(user_agent)
.map_err(|message| Usage(format!("`--user-agent`: {message}")))?;
serve.user_agent = Some(user_agent.clone());
}
let json = serde_json::to_string_pretty(&info).map_err(|error| Usage(error.to_string()))?;
let mut stdout = io::stdout().lock();
if writeln!(stdout, "{json}").is_err() {
return Ok(ExitCode::from(2));
}
Ok(ExitCode::SUCCESS)
}