ente-policy-provider, ente-tmpfiles-compat, journald export format

- ente-policy-provider (nuevo): BusServer que se anuncia como
  POLKIT_DECISION_IFACE provider. Decode blob (pid_be|uid_be|action_id),
  consulta /etc/ente/policy.json (o defaults), responde [allow|deny].
  Reglas con glob simple (foo.* / *.bar / *), require_uid/require_pid,
  audit flag para logging estructurado. Defaults conservadores: hostname/
  timezone/locale set requieren uid 0.

- ente-tmpfiles-compat (nuevo): aplica directivas de
  /usr/lib/tmpfiles.d, /etc/tmpfiles.d, /run/tmpfiles.d (last-wins).
  Soporta d/D/f/L/r/R/e. Orden: removes → creates → adjusts. lookup_uid
  resuelve usuarios via getpwnam. EPERM en chown silenciado en dev
  (esperado sin root). OneShot.

- journald export format: ente-journalctl gana --output=export
  produce systemd journal export format compatible con
  `journalctl --input-format=export -m`. Fields:
  __CURSOR/__REALTIME_TIMESTAMP/_HOSTNAME/_TRANSPORT, native KEY=value
  preservados, syslog text → MESSAGE=. Filter de bytes seguros
  (ASCII printable + tab) para evitar export multipart binario.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Sergio
2026-05-04 10:35:13 +00:00
parent 48e41331a1
commit 883c14dade
8 changed files with 667 additions and 8 deletions
+100 -8
View File
@@ -20,13 +20,24 @@ struct Args {
grep: Option<String>,
tail: Option<usize>,
source: Option<String>,
json: bool,
output: OutputFormat,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum OutputFormat {
Pretty,
Json,
/// systemd journal export format: `KEY=value\n` por field, blank line
/// entre entries. Documented at https://systemd.io/JOURNAL_EXPORT_FORMATS/
/// Compatible con `journalctl --input-format=export`.
Export,
}
fn parse_args() -> Args {
let mut args = std::env::args().skip(1);
let mut a = Args {
unit: None, since_secs: None, grep: None, tail: None, source: None, json: false,
unit: None, since_secs: None, grep: None, tail: None,
source: None, output: OutputFormat::Pretty,
};
while let Some(arg) = args.next() {
match arg.as_str() {
@@ -35,7 +46,19 @@ fn parse_args() -> Args {
"--grep" | "-g" => a.grep = args.next(),
"--tail" | "-n" => a.tail = args.next().and_then(|s| s.parse().ok()),
"--source" => a.source = args.next(),
"--json" => a.json = true,
"--json" => a.output = OutputFormat::Json,
"--output" | "-o" => {
a.output = match args.next().as_deref() {
Some("pretty") | None => OutputFormat::Pretty,
Some("json") | Some("json-lines") => OutputFormat::Json,
Some("export") => OutputFormat::Export,
Some(other) => {
eprintln!("output desconocido: {other}");
eprintln!("válidos: pretty | json | export");
std::process::exit(2);
}
};
}
"-h" | "--help" => { print_help(); std::process::exit(0); }
other => {
eprintln!("argumento desconocido: {other}");
@@ -57,7 +80,8 @@ fn print_help() {
eprintln!(" --grep, -g <text> Contiene <text> en el body decoded");
eprintln!(" --tail, -n <N> Últimas N entries");
eprintln!("Output:");
eprintln!(" --json JSON-lines en lugar de pretty");
eprintln!(" --output, -o <fmt> pretty | json | export (systemd journal export)");
eprintln!(" --json alias de --output json");
}
fn index_path() -> PathBuf {
@@ -146,10 +170,10 @@ fn main() -> anyhow::Result<()> {
}
for (e, body) in out {
if args.json {
print_json(&e, &body);
} else {
print_pretty(&e, &body);
match args.output {
OutputFormat::Pretty => print_pretty(&e, &body),
OutputFormat::Json => print_json(&e, &body),
OutputFormat::Export => print_export(&e, &body),
}
}
Ok(())
@@ -180,6 +204,74 @@ fn print_pretty(e: &IndexEntry, body: &str) {
}
}
/// systemd journal export format. Cada entry es un bloque de líneas
/// `KEY=value\n` separado por blank line. Para values con newlines o
/// bytes binarios, el formato usa una variante con length-prefix
/// (8 bytes LE u64) — por simplicidad sólo emitimos values con texto
/// que no contienen newlines o caracteres no-printables. Extraemos
/// MESSAGE/PRIORITY/_SYSTEMD_UNIT del body si es journald native.
///
/// Compatible con `journalctl --input-format=export -m`.
fn print_export(e: &IndexEntry, body: &str) {
// Timestamps: __REALTIME_TIMESTAMP en µs, __MONOTONIC_TIMESTAMP también.
let realtime_us = e.timestamp_ms.saturating_mul(1000);
println!("__CURSOR=s={};t={};x={}",
&e.sha_hex[..16], // pseudo-cursor: prefix del SHA
realtime_us,
&e.sha_hex[..8]);
println!("__REALTIME_TIMESTAMP={}", realtime_us);
println!("__MONOTONIC_TIMESTAMP={}", realtime_us);
let host = gethostname_safe();
if !host.is_empty() {
println!("_HOSTNAME={host}");
}
if e.unit != "-" {
println!("_SYSTEMD_UNIT={}", e.unit);
}
println!("_TRANSPORT={}", match e.source.as_str() {
"syslog" => "syslog",
"journal" => "journal",
_ => "stdout",
});
// Si el body es journald native (KEY=value lines), emitir cada uno
// verbatim — son los fields originales del producer. Filtrar líneas
// que no son seguras para export (con newlines en value, etc).
if body.contains('=') && body.lines().any(|l| l.contains('=')) {
for line in body.lines() {
if line.contains('=') && line.bytes().all(safe_export_byte) {
println!("{line}");
}
}
} else {
// Syslog text — empaquetar como MESSAGE.
let msg = body.trim_end()
.replace('\n', " "); // collapsa newlines
if msg.bytes().all(safe_export_byte) {
println!("MESSAGE={msg}");
}
}
// Blank line separa entries.
println!();
}
fn safe_export_byte(b: u8) -> bool {
// ASCII printable, espacio, tab. No newlines (manejados aparte).
(0x20..=0x7E).contains(&b) || b == b'\t'
}
fn gethostname_safe() -> String {
let mut buf = [0u8; 256];
let r = unsafe {
libc::gethostname(buf.as_mut_ptr() as *mut _, buf.len())
};
if r != 0 { return String::new(); }
let len = buf.iter().position(|&b| b == 0).unwrap_or(buf.len());
std::str::from_utf8(&buf[..len]).unwrap_or("").to_string()
}
fn print_json(e: &IndexEntry, body: &str) {
// JSON-lines básico, sin dependencia de serde — formato simple y estable.
let escaped_body = body