refactor(monorepo): reorganización lógica + renames + SDDs + split CHANGELOG

Reorganización física de crates/:
- core/ (mezclaba 6 propósitos) se divide en protocol/, init/, runtime/, compat/
- shared/ (3 crates) se redistribuye en protocol/ e init/
- lapaloma (sub-módulo de ui_engine) se promueve a modules/pineal/

Renames de proyectos:
- shipote → shuma (runtime de sandboxes)
- nouser → akasha (explorador de Mónadas)
- yahweh → nahual (motor GPUI, antes ui_engine/)
- lapaloma → pineal (data-viz agnóstica)

Fraccionamiento UI → core agnóstico:
- vista-core (DeckState + snap, 175 LOC, 5 tests verdes)
- barra-core (Task + render_html + sanitize, 90 LOC, 5 tests verdes)
- vista-web y barra-web ahora son thin DOM bindings

Documentación nueva:
- 16 SDDs por subdirectorio (≤80 LOC c/u): protocol/init/runtime/compat
  + 10 módulos + apps/
- docs/STATUS.md con cifras reales por proyecto
- docs/ROADMAP.md con plan a finalización (6 hitos, ~6-8 semanas)
- CHANGELOG.md particionado en docs/changelog/<proyecto>.md (7 buckets)

Automatización:
- scripts/reorg.py — script idempotente que: git mv directorios, renombra
  package names, recomputa path = refs, reescribe imports rust, actualiza
  workspace Cargo.toml. Soporta --dry-run.
- scripts/split-changelog.py — particiona CHANGELOG por componente.

Validación:
- cargo check --workspace pasa (124 crates + 2 nuevos cores).
- 10 tests adicionales (5 en vista-core + 5 en barra-core) verdes.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
sergio
2026-05-19 14:48:34 +00:00
parent 86fb6ae20b
commit 550c98f275
375 changed files with 8512 additions and 7155 deletions
+44
View File
@@ -0,0 +1,44 @@
# compat/ — Shims D-Bus systemd
**Propósito.** Permitir que software systemd-aware (GNOME, KDE,
PolicyKit, NetworkManager, etc.) corra sobre `ente-zero` sin systemd.
Cada shim es un binario standalone que se anuncia con un nombre
well-known D-Bus y traduce las llamadas al bus interno.
## Crates
| binario | reemplaza | D-Bus name |
| --------------------------- | --------------------- | ----------------------------------- |
| `ente-logind-compat` | systemd-logind | `org.freedesktop.login1` |
| `ente-hostnamed-compat` | systemd-hostnamed | `org.freedesktop.hostname1` |
| `ente-timedated-compat` | systemd-timedated | `org.freedesktop.timedate1` |
| `ente-localed-compat` | systemd-localed | `org.freedesktop.locale1` |
| `ente-journald-compat` | systemd-journald | `org.freedesktop.LogControl1` |
| `ente-resolved-compat` | systemd-resolved | `org.freedesktop.resolve1` |
| `ente-polkit-compat` | polkitd | `org.freedesktop.PolicyKit1` |
| `ente-machined-compat` | systemd-machined | `org.freedesktop.machine1` |
| `ente-systemd1-compat` | systemd Manager | `org.freedesktop.systemd1` |
| `ente-notify-compat` | sd_notify socket | `/run/systemd/notify` (datagram) |
| `ente-timer-compat` | systemd timers | (cron-like, sin D-Bus) |
| `ente-tmpfiles-compat` | systemd-tmpfiles | (aplica tmpfiles.d al boot) |
| `ente-binfmt-compat` | systemd-binfmt | (registra handlers binfmt_misc) |
| `ente-policy-provider` | (interno) | provider de decisiones polkit |
## Dependencias
- Todos ← `zbus`, `ente-bus`, `protocol/brahman-card`. Sin tests
(esperado: stubs D-Bus que delegan al bus interno).
## Patrón común
Cada shim:
1. Se conecta a `/run/brahman/bus`.
2. Reclama un well-known name vía zbus.
3. Implementa los métodos de la interfaz mínima usada por el ecosistema.
4. Loggea eventos al audit log de `ente-brain`.
## Estado
LOC ~5K total (~300 LOC c/u). Suficiente para que `desktop-file-utils`,
`xdg-open`, login managers, y CLIs systemd-aware no rompan. Pendiente:
cobertura de métodos avanzados (Inhibit en logind, SetVariable en localed).
@@ -0,0 +1,15 @@
[package]
name = "ente-binfmt-compat"
version = "0.0.1"
edition.workspace = true
license.workspace = true
publish.workspace = true
[[bin]]
name = "ente-binfmt-compat"
path = "src/main.rs"
[dependencies]
anyhow = { workspace = true }
tracing = { workspace = true }
tracing-subscriber = { workspace = true }
@@ -0,0 +1,109 @@
//! ente-binfmt-compat: registra handlers de binfmt_misc al boot.
//!
//! systemd-binfmt lee `/usr/lib/binfmt.d/*.conf` y `/etc/binfmt.d/*.conf` y
//! escribe cada línea al kernel via `/proc/sys/fs/binfmt_misc/register`.
//! Esto habilita ejecución transparente de binarios no-ELF (qemu-user,
//! wine, etc).
//!
//! Formato de cada línea:
//! :<name>:<type>:<offset>:<magic>:<mask>:<interpreter>:<flags>
//!
//! Líneas que empiezan con `#` o vacías se ignoran.
use std::fs;
use std::io::Write;
use std::path::Path;
use tracing::{info, warn};
use tracing_subscriber::EnvFilter;
const REGISTER_PATH: &str = "/proc/sys/fs/binfmt_misc/register";
const SEARCH_DIRS: &[&str] = &[
"/usr/lib/binfmt.d",
"/etc/binfmt.d",
"/run/binfmt.d",
];
fn main() {
init_tracing();
info!("ente-binfmt-compat: registrando handlers binfmt_misc");
if !Path::new(REGISTER_PATH).exists() {
warn!(path = REGISTER_PATH, "binfmt_misc no montado — skip");
std::process::exit(0);
}
let mut registered = 0;
let mut errors = 0;
let mut skipped = 0;
for dir in SEARCH_DIRS {
if !Path::new(dir).exists() { continue; }
let mut entries: Vec<_> = match fs::read_dir(dir) {
Ok(rd) => rd.filter_map(|e| e.ok()).collect(),
Err(_) => continue,
};
entries.sort_by_key(|e| e.file_name());
for entry in entries {
let path = entry.path();
if path.extension().map(|e| e != "conf").unwrap_or(true) { continue; }
let content = match fs::read_to_string(&path) {
Ok(c) => c,
Err(e) => { warn!(?e, path = %path.display(), "read"); continue; }
};
for line in content.lines() {
let line = line.trim();
if line.is_empty() || line.starts_with('#') { continue; }
match register(line) {
Ok(name) => {
info!(file = %path.display(), %name, "binfmt registrado");
registered += 1;
}
Err(e) => {
if e.is_already_exists() {
skipped += 1;
} else {
warn!(?e, file = %path.display(), "registro falló");
errors += 1;
}
}
}
}
}
}
info!(registered, skipped, errors, "binfmt aplicado");
if errors > 0 { std::process::exit(1); }
}
#[derive(Debug)]
struct RegError(std::io::Error);
impl std::fmt::Display for RegError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.0) }
}
impl RegError {
fn is_already_exists(&self) -> bool {
// EEXIST = 17 en Linux.
self.0.raw_os_error() == Some(17)
}
}
/// Escribe la línea al register file. Devuelve el `name` extraído del
/// primer campo (entre `:` separators) si tuvo éxito.
fn register(line: &str) -> Result<String, RegError> {
// Sintaxis: :<name>:<type>:<offset>:<magic>:<mask>:<interpreter>:<flags>
// Field 0 (después del ':' inicial) es el name.
let name = line.split(':').nth(1)
.map(|s| s.to_string())
.unwrap_or_else(|| "?".into());
let mut f = fs::OpenOptions::new()
.write(true)
.open(REGISTER_PATH)
.map_err(RegError)?;
f.write_all(line.as_bytes()).map_err(RegError)?;
Ok(name)
}
fn init_tracing() {
let filter = EnvFilter::try_from_default_env()
.unwrap_or_else(|_| EnvFilter::new("ente_binfmt_compat=info"));
tracing_subscriber::fmt().with_env_filter(filter).with_target(true).init();
}
@@ -0,0 +1,21 @@
[package]
name = "ente-hostnamed-compat"
version = "0.0.1"
edition.workspace = true
license.workspace = true
publish.workspace = true
[[bin]]
name = "ente-hostnamed-compat"
path = "src/main.rs"
[dependencies]
ente-card = { path = "../../protocol/ente-card" }
ente-bus = { path = "../../runtime/ente-bus" }
nix = { workspace = true }
libc = { workspace = true }
anyhow = { workspace = true }
tokio = { workspace = true }
tracing = { workspace = true }
tracing-subscriber = { workspace = true }
zbus = { version = "4", default-features = false, features = ["tokio"] }
@@ -0,0 +1,340 @@
//! ente-hostnamed-compat: shim de `org.freedesktop.hostname1`.
//!
//! GNOME control-center y otros componentes consultan este servicio al boot
//! para mostrar nombre de host, OS, kernel. Sin esto los settings panels
//! se rompen aunque el sistema funcione.
//!
//! Read-only properties: leemos /etc/hostname, /etc/os-release, uname().
//! Set* methods: log + forward al bus interno (no aplicamos cambios reales
//! en el stub — un siguiente paso es persistir a /etc/* y rehash).
use ente_bus::{BusClient, BusRequest, BusResponse};
use ente_card::Capability;
use std::sync::Mutex;
use tokio::signal::unix::{signal, SignalKind};
use tracing::{info, warn};
use tracing_subscriber::EnvFilter;
use zbus::{fdo, interface};
const BUS_NAME: &str = "org.freedesktop.hostname1";
const OBJ_PATH: &str = "/org/freedesktop/hostname1";
#[tokio::main(flavor = "current_thread")]
async fn main() -> anyhow::Result<()> {
init_tracing();
info!("ente-hostnamed-compat: arrancando");
announce_to_fractal().await;
let manager = HostnameManager::default();
let conn_result = zbus::connection::Builder::system()
.and_then(|b| b.name(BUS_NAME))
.and_then(|b| b.serve_at(OBJ_PATH, manager));
match conn_result {
Ok(builder) => match builder.build().await {
Ok(_conn) => {
info!(name = BUS_NAME, "name acquired, sirviendo");
wait_for_term().await
}
Err(e) => {
warn!(?e, "build conn falló — modo idle");
wait_for_term().await
}
},
Err(e) => {
warn!(?e, "builder D-Bus falló — modo idle");
wait_for_term().await
}
}
}
#[derive(Default)]
struct HostnameManager {
/// Cache para SetHostname. En el stub no persistimos a /etc.
transient_hostname: Mutex<Option<String>>,
}
#[interface(name = "org.freedesktop.hostname1")]
impl HostnameManager {
// ----- Properties read-only -----
#[zbus(property)]
async fn hostname(&self) -> String {
if let Some(h) = self.transient_hostname.lock().unwrap().clone() {
return h;
}
gethostname_libc().unwrap_or_else(|| "localhost".into())
}
#[zbus(property)]
async fn static_hostname(&self) -> String {
std::fs::read_to_string("/etc/hostname")
.map(|s| s.trim().to_string())
.unwrap_or_default()
}
#[zbus(property)]
async fn pretty_hostname(&self) -> String {
read_machine_info_field("PRETTY_HOSTNAME").unwrap_or_default()
}
#[zbus(property)]
async fn icon_name(&self) -> String {
read_machine_info_field("ICON_NAME").unwrap_or_default()
}
#[zbus(property)]
async fn chassis(&self) -> String {
read_machine_info_field("CHASSIS").unwrap_or_else(|| "desktop".into())
}
#[zbus(property)]
async fn deployment(&self) -> String {
read_machine_info_field("DEPLOYMENT").unwrap_or_default()
}
#[zbus(property)]
async fn location(&self) -> String {
read_machine_info_field("LOCATION").unwrap_or_default()
}
#[zbus(property)]
async fn kernel_name(&self) -> String {
nix::sys::utsname::uname()
.ok()
.and_then(|u| u.sysname().to_str().map(String::from))
.unwrap_or_else(|| "Linux".into())
}
#[zbus(property)]
async fn kernel_release(&self) -> String {
nix::sys::utsname::uname()
.ok()
.and_then(|u| u.release().to_str().map(String::from))
.unwrap_or_default()
}
#[zbus(property)]
async fn kernel_version(&self) -> String {
nix::sys::utsname::uname()
.ok()
.and_then(|u| u.version().to_str().map(String::from))
.unwrap_or_default()
}
#[zbus(property)]
async fn operating_system_pretty_name(&self) -> String {
read_os_release_field("PRETTY_NAME").unwrap_or_else(|| "Linux".into())
}
#[zbus(property)]
async fn operating_system_cpename(&self) -> String {
read_os_release_field("CPE_NAME").unwrap_or_default()
}
#[zbus(property)]
async fn home_url(&self) -> String {
read_os_release_field("HOME_URL").unwrap_or_default()
}
#[zbus(property)]
async fn hardware_vendor(&self) -> String {
read_dmi("/sys/class/dmi/id/sys_vendor")
}
#[zbus(property)]
async fn hardware_model(&self) -> String {
read_dmi("/sys/class/dmi/id/product_name")
}
#[zbus(property)]
async fn firmware_version(&self) -> String {
read_dmi("/sys/class/dmi/id/bios_version")
}
// ----- Setters: forward al bus interno y guardan en cache -----
async fn set_hostname(&self, name: String, _interactive: bool) -> fdo::Result<()> {
if !is_valid_hostname(&name) {
return Err(fdo::Error::InvalidArgs(format!("hostname inválido: {name:?}")));
}
// sethostname(2) cambia sólo el running kernel value.
let cstr = std::ffi::CString::new(name.clone())
.map_err(|e| fdo::Error::Failed(format!("CString: {e}")))?;
let r = unsafe { libc::sethostname(cstr.as_ptr(), name.len()) };
if r != 0 {
warn!(error = %std::io::Error::last_os_error(), %name, "sethostname syscall falló (¿CAP_SYS_ADMIN?)");
// No es fatal — guardamos transient para que el property lea el valor nuevo.
}
*self.transient_hostname.lock().unwrap() = Some(name.clone());
info!(%name, "SetHostname aplicado");
Ok(())
}
async fn set_static_hostname(&self, name: String, _interactive: bool) -> fdo::Result<()> {
if !is_valid_hostname(&name) {
return Err(fdo::Error::InvalidArgs(format!("hostname inválido: {name:?}")));
}
atomic_write("/etc/hostname", format!("{name}\n").as_bytes())
.map_err(|e| fdo::Error::Failed(format!("write /etc/hostname: {e}")))?;
info!(%name, "SetStaticHostname → /etc/hostname");
Ok(())
}
async fn set_pretty_hostname(&self, name: String, _interactive: bool) -> fdo::Result<()> {
update_machine_info("PRETTY_HOSTNAME", &name)
.map_err(|e| fdo::Error::Failed(format!("machine-info: {e}")))?;
info!(%name, "SetPrettyHostname → /etc/machine-info");
Ok(())
}
async fn set_icon_name(&self, name: String, _interactive: bool) -> fdo::Result<()> {
update_machine_info("ICON_NAME", &name)
.map_err(|e| fdo::Error::Failed(format!("machine-info: {e}")))?;
info!(%name, "SetIconName → /etc/machine-info");
Ok(())
}
async fn set_chassis(&self, chassis: String, _interactive: bool) -> fdo::Result<()> {
if !matches!(chassis.as_str(), "desktop"|"laptop"|"server"|"tablet"|"handset"|"watch"|"embedded"|"vm"|"container") {
return Err(fdo::Error::InvalidArgs(format!("chassis inválido: {chassis}")));
}
update_machine_info("CHASSIS", &chassis)
.map_err(|e| fdo::Error::Failed(format!("machine-info: {e}")))?;
info!(%chassis, "SetChassis → /etc/machine-info");
Ok(())
}
async fn set_deployment(&self, deployment: String, _interactive: bool) -> fdo::Result<()> {
update_machine_info("DEPLOYMENT", &deployment)
.map_err(|e| fdo::Error::Failed(format!("machine-info: {e}")))?;
info!(%deployment, "SetDeployment → /etc/machine-info");
Ok(())
}
async fn set_location(&self, location: String, _interactive: bool) -> fdo::Result<()> {
update_machine_info("LOCATION", &location)
.map_err(|e| fdo::Error::Failed(format!("machine-info: {e}")))?;
info!(%location, "SetLocation → /etc/machine-info");
Ok(())
}
}
// ---------------- helpers ----------------
fn gethostname_libc() -> Option<String> {
let mut buf = [0u8; 256];
let r = unsafe { libc::gethostname(buf.as_mut_ptr() as *mut _, buf.len()) };
if r != 0 { return None; }
let len = buf.iter().position(|&b| b == 0).unwrap_or(buf.len());
std::str::from_utf8(&buf[..len]).ok().map(String::from)
}
fn read_os_release_field(field: &str) -> Option<String> {
parse_kv_file("/etc/os-release", field)
}
fn read_machine_info_field(field: &str) -> Option<String> {
parse_kv_file("/etc/machine-info", field)
}
fn parse_kv_file(path: &str, field: &str) -> Option<String> {
let content = std::fs::read_to_string(path).ok()?;
for line in content.lines() {
if let Some((k, v)) = line.split_once('=') {
if k.trim() == field {
return Some(v.trim().trim_matches('"').to_string());
}
}
}
None
}
fn read_dmi(path: &str) -> String {
std::fs::read_to_string(path)
.map(|s| s.trim().to_string())
.unwrap_or_default()
}
/// RFC 1123 + extra: ASCII alfanumérico, dash, dot. Longitud 1..253.
/// Rechaza vacíos, espacios, control chars.
fn is_valid_hostname(s: &str) -> bool {
if s.is_empty() || s.len() > 253 { return false; }
s.chars().all(|c|
c.is_ascii_alphanumeric() || c == '-' || c == '.' || c == '_'
)
}
/// Escritura atómica via tmp + rename. fsync del directorio para
/// garantizar durabilidad post-crash. Permisos 0644.
fn atomic_write(path: &str, content: &[u8]) -> std::io::Result<()> {
use std::io::Write;
use std::os::unix::fs::OpenOptionsExt;
let p = std::path::Path::new(path);
if let Some(parent) = p.parent() { let _ = std::fs::create_dir_all(parent); }
let tmp = p.with_extension("tmp");
{
let mut f = std::fs::OpenOptions::new()
.create(true).write(true).truncate(true)
.mode(0o644)
.open(&tmp)?;
f.write_all(content)?;
f.sync_all()?;
}
std::fs::rename(&tmp, p)?;
Ok(())
}
/// Lee /etc/machine-info, actualiza/inserta una clave, escribe atómico.
fn update_machine_info(key: &str, value: &str) -> std::io::Result<()> {
let path = "/etc/machine-info";
let existing = std::fs::read_to_string(path).unwrap_or_default();
let mut found = false;
let mut out = String::new();
for line in existing.lines() {
if let Some((k, _)) = line.split_once('=') {
if k.trim() == key {
out.push_str(&format!("{key}={value}\n"));
found = true;
continue;
}
}
out.push_str(line);
out.push('\n');
}
if !found {
out.push_str(&format!("{key}={value}\n"));
}
atomic_write(path, out.as_bytes())
}
async fn announce_to_fractal() {
if let Ok(mut client) = BusClient::from_env().await {
let req = BusRequest::Announce {
capabilities: vec![Capability::Endpoint {
interface: ente_card::InterfaceId([0xa0; 16]),
version: 1,
}],
};
match client.call(req).await {
Ok(BusResponse::Ok) => info!("Announce → bus interno OK"),
Ok(other) => warn!(?other, "Announce respuesta inesperada"),
Err(e) => warn!(?e, "Announce falló"),
}
}
}
async fn wait_for_term() -> anyhow::Result<()> {
let mut term = signal(SignalKind::terminate())?;
let mut int_ = signal(SignalKind::interrupt())?;
tokio::select! {
_ = term.recv() => info!("SIGTERM"),
_ = int_.recv() => info!("SIGINT"),
}
Ok(())
}
fn init_tracing() {
let filter = EnvFilter::try_from_default_env()
.unwrap_or_else(|_| EnvFilter::new("ente_hostnamed_compat=info"));
tracing_subscriber::fmt().with_env_filter(filter).with_target(true).init();
}
@@ -0,0 +1,25 @@
[package]
name = "ente-journald-compat"
version = "0.0.1"
edition.workspace = true
license.workspace = true
publish.workspace = true
[[bin]]
name = "ente-journald-compat"
path = "src/main.rs"
[[bin]]
name = "ente-journalctl"
path = "src/journalctl.rs"
[dependencies]
ente-card = { path = "../../protocol/ente-card" }
ente-bus = { path = "../../runtime/ente-bus" }
ente-cas = { path = "../../runtime/ente-cas" }
nix = { workspace = true }
libc = { workspace = true }
anyhow = { workspace = true }
tokio = { workspace = true }
tracing = { workspace = true }
tracing-subscriber = { workspace = true }
@@ -0,0 +1,289 @@
//! ente-journalctl: query CLI sobre el journal persistido en CAS.
//!
//! Lee el index `~/.local/share/ente/journal/index.log` (líneas
//! `timestamp_ms:source:unit:sha_hex`), filtra, y para cada match
//! restituye el blob desde CAS y lo imprime.
//!
//! Uso:
//! ente-journalctl # todo el journal
//! ente-journalctl --unit foo.service # filtra por unit
//! ente-journalctl --since 60 # últimos 60 segundos
//! ente-journalctl --grep "panic" # contiene "panic"
//! ente-journalctl --tail 20 # últimas 20 entries
//! ente-journalctl --json # output JSON-lines
use std::path::PathBuf;
struct Args {
unit: Option<String>,
since_secs: Option<u64>,
grep: Option<String>,
tail: Option<usize>,
source: Option<String>,
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, output: OutputFormat::Pretty,
};
while let Some(arg) = args.next() {
match arg.as_str() {
"--unit" | "-u" => a.unit = args.next(),
"--since" | "-S" => a.since_secs = args.next().and_then(|s| s.parse().ok()),
"--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.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}");
print_help();
std::process::exit(2);
}
}
}
a
}
fn print_help() {
eprintln!("ente-journalctl — query CLI del journal persistido en CAS");
eprintln!();
eprintln!("Filtros:");
eprintln!(" --unit, -u <name> Filtra por unidad (e.g. foo.service)");
eprintln!(" --source <s> journal | syslog");
eprintln!(" --since, -S <secs> Sólo últimos N segundos");
eprintln!(" --grep, -g <text> Contiene <text> en el body decoded");
eprintln!(" --tail, -n <N> Últimas N entries");
eprintln!("Output:");
eprintln!(" --output, -o <fmt> pretty | json | export (systemd journal export)");
eprintln!(" --json alias de --output json");
}
fn index_path() -> PathBuf {
let base = if let Ok(d) = std::env::var("XDG_DATA_HOME") { d }
else if let Ok(h) = std::env::var("HOME") { format!("{h}/.local/share") }
else { "/var/lib".into() };
PathBuf::from(base).join("ente").join("journal").join("index.log")
}
fn now_ms() -> u128 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis())
.unwrap_or(0)
}
#[derive(Debug)]
struct IndexEntry {
timestamp_ms: u128,
source: String,
unit: String,
sha_hex: String,
}
fn parse_line(line: &str) -> Option<IndexEntry> {
let mut parts = line.splitn(4, ':');
let ts: u128 = parts.next()?.parse().ok()?;
let source = parts.next()?.to_string();
let unit = parts.next()?.to_string();
let sha = parts.next()?.to_string();
if sha.len() != 64 { return None; }
Some(IndexEntry { timestamp_ms: ts, source, unit, sha_hex: sha })
}
fn parse_sha(hex: &str) -> Option<[u8; 32]> {
if hex.len() != 64 { return None; }
let mut sha = [0u8; 32];
for i in 0..32 {
sha[i] = u8::from_str_radix(&hex[i*2..i*2+2], 16).ok()?;
}
Some(sha)
}
fn main() -> anyhow::Result<()> {
let args = parse_args();
let path = index_path();
if !path.exists() {
eprintln!("index no existe: {} — ¿journald-compat ha corrido?", path.display());
std::process::exit(1);
}
let raw = std::fs::read_to_string(&path)?;
let mut entries: Vec<IndexEntry> = raw.lines()
.filter_map(parse_line)
.collect();
// Filtros
let now = now_ms();
if let Some(secs) = args.since_secs {
let cutoff = now.saturating_sub(secs as u128 * 1000);
entries.retain(|e| e.timestamp_ms >= cutoff);
}
if let Some(unit) = &args.unit {
entries.retain(|e| &e.unit == unit);
}
if let Some(src) = &args.source {
entries.retain(|e| &e.source == src);
}
// tail después de filtros temporales/identidad pero antes de grep —
// grep es post porque requiere cargar bytes del CAS.
let mut out: Vec<(IndexEntry, String)> = entries.into_iter()
.filter_map(|e| {
let sha = parse_sha(&e.sha_hex)?;
let bytes = ente_cas::resolve(&sha).ok()?;
let body = String::from_utf8_lossy(&bytes).into_owned();
Some((e, body))
})
.collect();
if let Some(g) = &args.grep {
out.retain(|(_, body)| body.contains(g.as_str()));
}
if let Some(n) = args.tail {
let len = out.len();
if len > n { out.drain(..len - n); }
}
for (e, body) in out {
match args.output {
OutputFormat::Pretty => print_pretty(&e, &body),
OutputFormat::Json => print_json(&e, &body),
OutputFormat::Export => print_export(&e, &body),
}
}
Ok(())
}
fn print_pretty(e: &IndexEntry, body: &str) {
let secs = e.timestamp_ms / 1000;
let ms = e.timestamp_ms % 1000;
let header = if e.unit == "-" {
format!("{}.{:03} [{}]", secs, ms, e.source)
} else {
format!("{}.{:03} [{}] {{{}}}", secs, ms, e.source, e.unit)
};
println!("{header}");
// Si es journald native (KEY=value lines), extraer MESSAGE.
if body.contains('=') && body.lines().any(|l| l.contains('=')) {
for line in body.lines() {
if let Some((k, v)) = line.split_once('=') {
if k.trim() == "MESSAGE" {
println!(" {v}");
return;
}
}
}
}
for line in body.trim_end().lines() {
println!(" {line}");
}
}
/// 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
.replace('\\', "\\\\")
.replace('"', "\\\"")
.replace('\n', "\\n")
.replace('\r', "\\r")
.replace('\t', "\\t");
let unit_field = if e.unit == "-" { "null".to_string() }
else { format!("\"{}\"", e.unit) };
println!(
r#"{{"timestamp_ms":{},"source":"{}","unit":{},"sha":"{}","body":"{}"}}"#,
e.timestamp_ms, e.source, unit_field, e.sha_hex, escaped_body
);
}
@@ -0,0 +1,218 @@
//! ente-journald-compat: stub que absorbe escrituras al journal socket.
//!
//! Listen en `/run/systemd/journal/socket` (datagram) — todo lo que llega
//! se decodifica best-effort y se emite como tracing event.
//!
//! Sin esto, apps que usan `sd_journal_send` o syslog fallan al escribir.
//! Para una implementación real: persistir a CAS por timestamp+sha,
//! exponer query API, indexar por unidad/usuario.
use ente_bus::{BusClient, BusRequest, BusResponse};
use ente_card::Capability;
use std::os::fd::{AsRawFd, OwnedFd};
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use tokio::io::unix::AsyncFd;
use tokio::signal::unix::{signal, SignalKind};
use tracing::{debug, info, warn};
use tracing_subscriber::EnvFilter;
const JOURNAL_SOCKET: &str = "/run/systemd/journal/socket";
const DEV_LOG: &str = "/dev/log";
#[tokio::main(flavor = "current_thread")]
async fn main() -> anyhow::Result<()> {
init_tracing();
info!("ente-journald-compat: arrancando");
announce_to_fractal().await;
// Intentamos vincular ambos sockets. Cada uno puede fallar
// independientemente; si alguno funciona, seguimos.
let mut bound = 0usize;
if let Some(stream) = bind_dgram(JOURNAL_SOCKET) {
bound += 1;
spawn_listener(stream, "journal");
} else {
warn!(path = JOURNAL_SOCKET, "no se pudo bind — necesita CAP_NET_BIND_SERVICE o /run writable");
}
if let Some(stream) = bind_dgram(DEV_LOG) {
bound += 1;
spawn_listener(stream, "syslog");
} else {
warn!(path = DEV_LOG, "no se pudo bind /dev/log");
}
if bound == 0 {
warn!("ningún socket bound — modo idle");
} else {
info!(sockets_bound = bound, "journald-compat listening");
}
wait_for_term().await
}
fn bind_dgram(path: &str) -> Option<AsyncFd<OwnedFdWrap>> {
use nix::sys::socket::{bind, socket, AddressFamily, SockFlag, SockType, UnixAddr};
let _ = std::fs::remove_file(path);
if let Some(parent) = Path::new(path).parent() {
let _ = std::fs::create_dir_all(parent);
}
let fd = match socket(
AddressFamily::Unix,
SockType::Datagram,
SockFlag::SOCK_NONBLOCK | SockFlag::SOCK_CLOEXEC,
None,
) {
Ok(f) => f,
Err(e) => { warn!(?e, "socket() falló"); return None; }
};
let addr = match UnixAddr::new(path) {
Ok(a) => a,
Err(e) => { warn!(?e, "UnixAddr falló"); return None; }
};
if let Err(e) = bind(fd.as_raw_fd(), &addr) {
warn!(?e, %path, "bind falló");
return None;
}
AsyncFd::new(OwnedFdWrap(fd)).ok()
}
struct OwnedFdWrap(OwnedFd);
impl AsRawFd for OwnedFdWrap {
fn as_raw_fd(&self) -> std::os::fd::RawFd { self.0.as_raw_fd() }
}
fn spawn_listener(async_fd: AsyncFd<OwnedFdWrap>, source: &'static str) {
tokio::spawn(async move {
let mut buf = vec![0u8; 64 * 1024];
loop {
let mut guard = match async_fd.readable().await {
Ok(g) => g,
Err(e) => { warn!(?e, source, "readable failed"); return; }
};
let raw_fd = guard.get_inner().as_raw_fd();
loop {
let n = unsafe {
libc::recv(raw_fd, buf.as_mut_ptr() as *mut _, buf.len(), 0)
};
if n <= 0 { break; }
handle_message(&buf[..n as usize], source);
}
guard.clear_ready();
}
});
}
/// Mutex sobre el archivo index para escrituras concurrentes desde
/// múltiples listeners (journal + syslog).
static INDEX_FILE: Mutex<()> = Mutex::new(());
/// Path del index file: `$XDG_DATA_HOME/ente/journal/index.log` (default
/// `~/.local/share/ente/journal/index.log`).
fn index_path() -> PathBuf {
let base = if let Ok(d) = std::env::var("XDG_DATA_HOME") { d }
else if let Ok(h) = std::env::var("HOME") { format!("{h}/.local/share") }
else { "/var/lib".into() };
PathBuf::from(base).join("ente").join("journal").join("index.log")
}
fn now_ms() -> u128 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis())
.unwrap_or(0)
}
/// Persiste el blob crudo al CAS y appendea una línea al index:
/// `<timestamp_ms>:<source>:<unit>:<sha_hex>`. Errores se logean pero
/// no abortan — perder un mensaje no debe romper journald.
fn persist_to_cas(buf: &[u8], source: &'static str, unit: Option<&str>) {
let sha = match ente_cas::store(buf) {
Ok(s) => s,
Err(e) => { warn!(?e, "CAS store falló"); return; }
};
let line = format!(
"{}:{}:{}:{}\n",
now_ms(), source, unit.unwrap_or("-"), ente_cas::hex(&sha)
);
let path = index_path();
let _guard = INDEX_FILE.lock().unwrap();
if let Some(parent) = path.parent() {
let _ = std::fs::create_dir_all(parent);
}
use std::io::Write;
let mut f = match std::fs::OpenOptions::new()
.create(true).append(true)
.open(&path)
{
Ok(f) => f,
Err(e) => { warn!(?e, path = %path.display(), "abrir index"); return; }
};
if let Err(e) = f.write_all(line.as_bytes()) {
warn!(?e, "write index");
}
}
/// Decodifica best-effort. Formato journald nativo: lines de "KEY=value"
/// (binario para values con newlines, pero raro). Formato syslog: texto
/// con prefijo "<priority>tag: message".
fn handle_message(buf: &[u8], source: &'static str) {
if let Ok(s) = std::str::from_utf8(buf) {
if s.contains('=') && s.lines().any(|l| l.contains('=')) {
let mut message = None;
let mut priority = None;
let mut unit: Option<String> = None;
for line in s.lines() {
if let Some((k, v)) = line.split_once('=') {
match k {
"MESSAGE" => message = Some(v.to_string()),
"PRIORITY" => priority = Some(v.to_string()),
"_SYSTEMD_UNIT" | "UNIT" => unit = Some(v.to_string()),
_ => {}
}
}
}
persist_to_cas(buf, source, unit.as_deref());
if let Some(msg) = message {
info!(target: "journal", source, ?priority, ?unit, "{msg}");
} else {
debug!(source, len = buf.len(), "journal native sin MESSAGE");
}
} else {
persist_to_cas(buf, source, None);
info!(target: "syslog", source, "{}", s.trim_end());
}
} else {
persist_to_cas(buf, source, None);
debug!(source, len = buf.len(), "journal binario (no UTF-8)");
}
}
async fn announce_to_fractal() {
if let Ok(mut client) = BusClient::from_env().await {
let req = BusRequest::Announce {
capabilities: vec![Capability::Journal],
};
match client.call(req).await {
Ok(BusResponse::Ok) => info!("Announce → bus interno OK"),
Ok(other) => warn!(?other, "Announce respuesta inesperada"),
Err(e) => warn!(?e, "Announce falló"),
}
}
}
async fn wait_for_term() -> anyhow::Result<()> {
let mut term = signal(SignalKind::terminate())?;
let mut int_ = signal(SignalKind::interrupt())?;
tokio::select! {
_ = term.recv() => info!("SIGTERM"),
_ = int_.recv() => info!("SIGINT"),
}
Ok(())
}
fn init_tracing() {
let filter = EnvFilter::try_from_default_env()
.unwrap_or_else(|_| EnvFilter::new("ente_journald_compat=info,journal=info,syslog=info"));
tracing_subscriber::fmt().with_env_filter(filter).with_target(true).init();
}
@@ -0,0 +1,19 @@
[package]
name = "ente-localed-compat"
version = "0.0.1"
edition.workspace = true
license.workspace = true
publish.workspace = true
[[bin]]
name = "ente-localed-compat"
path = "src/main.rs"
[dependencies]
ente-card = { path = "../../protocol/ente-card" }
ente-bus = { path = "../../runtime/ente-bus" }
anyhow = { workspace = true }
tokio = { workspace = true }
tracing = { workspace = true }
tracing-subscriber = { workspace = true }
zbus = { version = "4", default-features = false, features = ["tokio"] }
@@ -0,0 +1,219 @@
//! ente-localed-compat: shim de `org.freedesktop.locale1`.
//!
//! GNOME settings panel "Region & Language" llama aquí. Properties leen
//! /etc/locale.conf y /etc/vconsole.conf; setters log + forward.
use ente_bus::{BusClient, BusRequest, BusResponse};
use ente_card::Capability;
use std::sync::Mutex;
use tokio::signal::unix::{signal, SignalKind};
use tracing::{info, warn};
use tracing_subscriber::EnvFilter;
use zbus::{fdo, interface};
const BUS_NAME: &str = "org.freedesktop.locale1";
const OBJ_PATH: &str = "/org/freedesktop/locale1";
#[tokio::main(flavor = "current_thread")]
async fn main() -> anyhow::Result<()> {
init_tracing();
info!("ente-localed-compat: arrancando");
announce_to_fractal().await;
let manager = LocaleManager::default();
let conn_result = zbus::connection::Builder::system()
.and_then(|b| b.name(BUS_NAME))
.and_then(|b| b.serve_at(OBJ_PATH, manager));
match conn_result {
Ok(builder) => match builder.build().await {
Ok(_conn) => {
info!(name = BUS_NAME, "name acquired, sirviendo");
wait_for_term().await
}
Err(e) => {
warn!(?e, "build conn falló — modo idle");
wait_for_term().await
}
},
Err(e) => {
warn!(?e, "builder D-Bus falló — modo idle");
wait_for_term().await
}
}
}
#[derive(Default)]
struct LocaleManager {
transient_locale: Mutex<Option<Vec<String>>>,
}
#[interface(name = "org.freedesktop.locale1")]
impl LocaleManager {
/// Locale actual como array de "KEY=value" (LANG=en_US.UTF-8, LC_TIME=...).
/// Default: leer /etc/locale.conf.
#[zbus(property)]
async fn locale(&self) -> Vec<String> {
if let Some(v) = self.transient_locale.lock().unwrap().clone() {
return v;
}
match std::fs::read_to_string("/etc/locale.conf") {
Ok(c) => c.lines()
.filter(|l| !l.trim().is_empty() && !l.starts_with('#'))
.map(|s| s.trim().to_string())
.collect(),
Err(_) => vec!["LANG=C.UTF-8".into()],
}
}
#[zbus(property)]
async fn x11layout(&self) -> String {
read_kv("/etc/X11/xorg.conf.d/00-keyboard.conf", "XkbLayout").unwrap_or_default()
}
#[zbus(property)]
async fn x11model(&self) -> String {
read_kv("/etc/X11/xorg.conf.d/00-keyboard.conf", "XkbModel").unwrap_or_default()
}
#[zbus(property)]
async fn x11variant(&self) -> String {
read_kv("/etc/X11/xorg.conf.d/00-keyboard.conf", "XkbVariant").unwrap_or_default()
}
#[zbus(property)]
async fn x11options(&self) -> String {
read_kv("/etc/X11/xorg.conf.d/00-keyboard.conf", "XkbOptions").unwrap_or_default()
}
#[zbus(property)]
async fn vconsole_keymap(&self) -> String {
read_vconsole("KEYMAP").unwrap_or_default()
}
#[zbus(property)]
async fn vconsole_keymap_toggle(&self) -> String {
read_vconsole("KEYMAP_TOGGLE").unwrap_or_default()
}
async fn set_locale(&self, locale: Vec<String>, _interactive: bool) -> fdo::Result<()> {
// Validar formato KEY=value en cada entry.
for entry in &locale {
if !entry.contains('=') {
return Err(fdo::Error::InvalidArgs(
format!("locale entry inválido (sin '='): {entry}")
));
}
}
let content: String = locale.iter()
.map(|s| format!("{s}\n"))
.collect();
atomic_write("/etc/locale.conf", content.as_bytes())
.map_err(|e| fdo::Error::Failed(format!("write /etc/locale.conf: {e}")))?;
*self.transient_locale.lock().unwrap() = Some(locale.clone());
info!(?locale, "SetLocale → /etc/locale.conf");
Ok(())
}
async fn set_vconsole_keymap(
&self,
keymap: String,
keymap_toggle: String,
_convert: bool,
_interactive: bool,
) -> fdo::Result<()> {
info!(%keymap, %keymap_toggle, "SetVConsoleKeymap (stub)");
Ok(())
}
async fn set_x11_keyboard(
&self,
layout: String,
model: String,
variant: String,
options: String,
_convert: bool,
_interactive: bool,
) -> fdo::Result<()> {
info!(%layout, %model, %variant, %options, "SetX11Keyboard (stub)");
Ok(())
}
}
fn atomic_write(path: &str, content: &[u8]) -> std::io::Result<()> {
use std::io::Write;
use std::os::unix::fs::OpenOptionsExt;
let p = std::path::Path::new(path);
if let Some(parent) = p.parent() { let _ = std::fs::create_dir_all(parent); }
let tmp = p.with_extension("tmp");
{
let mut f = std::fs::OpenOptions::new()
.create(true).write(true).truncate(true)
.mode(0o644)
.open(&tmp)?;
f.write_all(content)?;
f.sync_all()?;
}
std::fs::rename(&tmp, p)?;
Ok(())
}
fn read_kv(path: &str, key: &str) -> Option<String> {
let content = std::fs::read_to_string(path).ok()?;
for line in content.lines() {
let trimmed = line.trim();
if trimmed.starts_with(&format!("Option \"{key}\"")) || trimmed.starts_with(key) {
// Best-effort parse: tomar lo que está entre comillas.
if let Some(start) = trimmed.find('"') {
let rest = &trimmed[start + 1..];
if let Some(end) = rest.find('"') {
return Some(rest[..end].to_string());
}
}
}
}
None
}
fn read_vconsole(key: &str) -> Option<String> {
let content = std::fs::read_to_string("/etc/vconsole.conf").ok()?;
for line in content.lines() {
if let Some((k, v)) = line.split_once('=') {
if k.trim() == key {
return Some(v.trim().trim_matches('"').to_string());
}
}
}
None
}
async fn announce_to_fractal() {
if let Ok(mut client) = BusClient::from_env().await {
let req = BusRequest::Announce {
capabilities: vec![Capability::Endpoint {
interface: ente_card::InterfaceId([0xa2; 16]),
version: 1,
}],
};
match client.call(req).await {
Ok(BusResponse::Ok) => info!("Announce → bus interno OK"),
Ok(other) => warn!(?other, "Announce respuesta inesperada"),
Err(e) => warn!(?e, "Announce falló"),
}
}
}
async fn wait_for_term() -> anyhow::Result<()> {
let mut term = signal(SignalKind::terminate())?;
let mut int_ = signal(SignalKind::interrupt())?;
tokio::select! {
_ = term.recv() => info!("SIGTERM"),
_ = int_.recv() => info!("SIGINT"),
}
Ok(())
}
fn init_tracing() {
let filter = EnvFilter::try_from_default_env()
.unwrap_or_else(|_| EnvFilter::new("ente_localed_compat=info"));
tracing_subscriber::fmt().with_env_filter(filter).with_target(true).init();
}
@@ -0,0 +1,19 @@
[package]
name = "ente-logind-compat"
version = "0.0.1"
edition.workspace = true
license.workspace = true
publish.workspace = true
[[bin]]
name = "ente-logind-compat"
path = "src/main.rs"
[dependencies]
ente-card = { path = "../../protocol/ente-card" }
ente-bus = { path = "../../runtime/ente-bus" }
anyhow = { workspace = true }
tokio = { workspace = true }
tracing = { workspace = true }
tracing-subscriber = { workspace = true }
zbus = { version = "4", default-features = false, features = ["tokio"] }
@@ -0,0 +1,249 @@
//! ente-logind-compat: el Ente que se hace pasar por systemd-logind.
//!
//! Vive FUERA de PID 1 — un parser D-Bus en el Init es una bomba con CVEs
//! históricos. Ejecutado como hijo del Ente #0 con `Restart` supervision.
//!
//! Implementa el subset del interface `org.freedesktop.login1.Manager` que
//! GNOME/KDE consultan en arranque. Cada método se traduce internamente en
//! una request al bus interno del fractal — capacidades tipadas, no nombres
//! D-Bus opacos hacia abajo.
//!
//! ## Lo que GNOME/KDE realmente llaman al boot
//! - ListSessions, ListUsers, GetSession*
//! - Inhibit (mantiene un fd vivo mientras la app está activa)
//! - CanPowerOff/CanReboot/CanSuspend
//! - PowerOff/Reboot/Suspend
//! - Properties: IdleHint, Docked, etc.
//!
//! El stub responde "no hay sesiones" y "sí puedo apagar" — suficiente para
//! que GNOME complete arranque sin marcar fallo.
use ente_bus::{BusClient, BusRequest, BusResponse};
use ente_card::Capability;
use std::sync::atomic::{AtomicU32, Ordering};
use std::time::Duration;
use tokio::signal::unix::{signal, SignalKind};
use tracing::{info, warn};
use tracing_subscriber::EnvFilter;
use zbus::{fdo, interface, zvariant::OwnedObjectPath, Connection};
const BUS_NAME: &str = "org.freedesktop.login1";
const MANAGER_PATH: &str = "/org/freedesktop/login1";
#[tokio::main(flavor = "current_thread")]
async fn main() -> anyhow::Result<()> {
init_tracing();
info!("ente-logind-compat: arrancando");
let bus_addr = std::env::var("DBUS_SYSTEM_BUS_ADDRESS")
.unwrap_or_else(|_| "unix:path=/var/run/dbus/system_bus_socket".into());
let bus_path = bus_addr.strip_prefix("unix:path=").unwrap_or(&bus_addr);
let bus_present = std::path::Path::new(bus_path).exists();
info!(bus_addr, bus_present, "configuración D-Bus");
// Anunciamos nuestra presencia al bus interno del fractal antes de
// intentar registrar el nombre D-Bus. Esto sirve como handshake "estoy
// vivo" independiente del estado del system bus.
announce_to_fractal().await;
if !bus_present {
warn!("system bus no disponible — modo idle (esperando SIGTERM)");
return wait_for_term().await;
}
let conn = match build_connection().await {
Ok(c) => c,
Err(e) => {
warn!(?e, "fallo al registrar org.freedesktop.login1 — modo idle");
// No retornamos error: la supervisión Restart entraría en bucle
// si systemd-logind real ya posee el nombre. Esperar señal y salir.
return wait_for_term().await;
}
};
info!("logind compat corriendo — esperando señales");
let _ = conn; // mantener viva la conexión hasta SIGTERM
wait_for_term().await
}
async fn build_connection() -> anyhow::Result<Connection> {
let manager = LogindManager::default();
let conn = zbus::connection::Builder::system()?
.name(BUS_NAME)?
.serve_at(MANAGER_PATH, manager)?
.build()
.await?;
info!(name = BUS_NAME, path = MANAGER_PATH, "name acquired + manager served");
Ok(conn)
}
async fn announce_to_fractal() {
match BusClient::from_env().await {
Ok(mut client) => {
let req = BusRequest::Announce {
capabilities: vec![Capability::LegacyLogind],
};
match client.call(req).await {
Ok(BusResponse::Ok) => info!("Announce → bus interno OK"),
Ok(other) => warn!(?other, "Announce respuesta inesperada"),
Err(e) => warn!(?e, "Announce falló"),
}
}
Err(e) => warn!(?e, "no se pudo conectar al bus interno"),
}
}
async fn forward_to_fractal(req: BusRequest) -> fdo::Result<()> {
let mut client = BusClient::from_env().await
.map_err(|e| fdo::Error::Failed(format!("bus client: {e}")))?;
match client.call(req).await {
Ok(BusResponse::Ok) => Ok(()),
Ok(BusResponse::Error(s)) => Err(fdo::Error::Failed(s)),
Ok(other) => Err(fdo::Error::Failed(format!("respuesta inesperada: {other:?}"))),
Err(e) => Err(fdo::Error::Failed(format!("bus call: {e}"))),
}
}
async fn wait_for_term() -> anyhow::Result<()> {
let mut term = signal(SignalKind::terminate())?;
let mut int_ = signal(SignalKind::interrupt())?;
let mut tick = tokio::time::interval(Duration::from_secs(60));
tick.tick().await; // descartar el primer tick inmediato
loop {
tokio::select! {
_ = term.recv() => { info!("SIGTERM — cierre ordenado"); return Ok(()); }
_ = int_.recv() => { info!("SIGINT — cierre"); return Ok(()); }
_ = tick.tick() => { info!("heartbeat"); }
}
}
}
fn init_tracing() {
let filter = EnvFilter::try_from_default_env()
.unwrap_or_else(|_| EnvFilter::new("ente_logind_compat=info"));
tracing_subscriber::fmt().with_env_filter(filter).with_target(true).init();
}
#[derive(Default)]
struct LogindManager {
/// Contador monótono de inhibits. Real impl mantendría una tabla con
/// el fd vivo de cada uno y los enrutaría al bus interno del fractal.
inhibit_counter: AtomicU32,
}
/// Tipos del wire format de `org.freedesktop.login1.Manager`.
type SessionTuple = (String, u32, String, String, OwnedObjectPath);
type UserTuple = (u32, String, OwnedObjectPath);
#[interface(name = "org.freedesktop.login1.Manager")]
impl LogindManager {
// ---- Listado / lookup ----
async fn list_sessions(&self) -> fdo::Result<Vec<SessionTuple>> {
Ok(vec![])
}
async fn list_users(&self) -> fdo::Result<Vec<UserTuple>> {
Ok(vec![])
}
async fn get_session(&self, _session_id: String) -> fdo::Result<OwnedObjectPath> {
Err(fdo::Error::Failed("no sessions in fractal".into()))
}
async fn get_session_by_pid(&self, _pid: u32) -> fdo::Result<OwnedObjectPath> {
Err(fdo::Error::Failed("no sessions in fractal".into()))
}
async fn get_user(&self, _uid: u32) -> fdo::Result<OwnedObjectPath> {
Err(fdo::Error::Failed("no users in fractal".into()))
}
async fn get_user_by_pid(&self, _pid: u32) -> fdo::Result<OwnedObjectPath> {
Err(fdo::Error::Failed("no users in fractal".into()))
}
// ---- Inhibit ----
//
// Real: devuelve un fd que el cliente mantiene abierto mientras quiere
// inhibir. Cuando lo cierra, sabemos que terminó. Aquí: stub que falla
// con NotSupported — GNOME registra warning pero continúa el arranque.
async fn inhibit(
&self,
what: String,
who: String,
why: String,
mode: String,
) -> fdo::Result<zbus::zvariant::OwnedFd> {
let n = self.inhibit_counter.fetch_add(1, Ordering::Relaxed);
info!(n, %what, %who, %why, %mode, "Inhibit (stub)");
Err(fdo::Error::NotSupported("Inhibit todavía no enruta al bus interno".into()))
}
// ---- Power management ----
async fn power_off(&self, interactive: bool) -> fdo::Result<()> {
info!(interactive, "PowerOff D-Bus → bus interno");
forward_to_fractal(BusRequest::PowerOff { interactive }).await
}
async fn reboot(&self, interactive: bool) -> fdo::Result<()> {
info!(interactive, "Reboot D-Bus → bus interno");
forward_to_fractal(BusRequest::Reboot { interactive }).await
}
async fn suspend(&self, interactive: bool) -> fdo::Result<()> {
info!(interactive, "Suspend D-Bus → bus interno");
forward_to_fractal(BusRequest::Suspend { interactive }).await
}
async fn hibernate(&self, interactive: bool) -> fdo::Result<()> {
info!(interactive, "Hibernate D-Bus → bus interno");
forward_to_fractal(BusRequest::Hibernate { interactive }).await
}
async fn can_power_off(&self) -> fdo::Result<String> {
Ok("yes".into())
}
async fn can_reboot(&self) -> fdo::Result<String> {
Ok("yes".into())
}
async fn can_suspend(&self) -> fdo::Result<String> {
// "challenge" = válido, requiere autenticación. GNOME muestra el
// botón pero pide PIN/contraseña antes de invocar Suspend.
Ok("challenge".into())
}
async fn can_hibernate(&self) -> fdo::Result<String> {
Ok("challenge".into())
}
// ---- Properties mínimas ----
#[zbus(property)]
async fn idle_hint(&self) -> bool { false }
#[zbus(property)]
async fn idle_since_hint(&self) -> u64 { 0 }
#[zbus(property)]
async fn idle_since_hint_monotonic(&self) -> u64 { 0 }
#[zbus(property)]
async fn block_inhibited(&self) -> String { String::new() }
#[zbus(property)]
async fn delay_inhibited(&self) -> String { String::new() }
#[zbus(property)]
async fn docked(&self) -> bool { false }
#[zbus(property)]
async fn lid_closed(&self) -> bool { false }
#[zbus(property)]
async fn on_external_power(&self) -> bool { true }
}
@@ -0,0 +1,19 @@
[package]
name = "ente-machined-compat"
version = "0.0.1"
edition.workspace = true
license.workspace = true
publish.workspace = true
[[bin]]
name = "ente-machined-compat"
path = "src/main.rs"
[dependencies]
ente-card = { path = "../../protocol/ente-card" }
ente-bus = { path = "../../runtime/ente-bus" }
anyhow = { workspace = true }
tokio = { workspace = true }
tracing = { workspace = true }
tracing-subscriber = { workspace = true }
zbus = { version = "4", default-features = false, features = ["tokio"] }
@@ -0,0 +1,186 @@
//! ente-machined-compat: shim de `org.freedesktop.machine1`.
//!
//! systemd-machined trackea VMs y containers (typically managed por systemd-nspawn).
//! En el fractal cada Ente con namespaces es candidato a "machine", pero la
//! correspondencia no es 1:1 — un Ente puede tener menos aislamiento que una
//! container completa.
//!
//! Este shim devuelve listas vacías para no romper clientes (gnome-boxes,
//! virt-manager, etc) que llaman a `ListMachines` durante boot. Métodos de
//! mutación (RegisterMachine, KillMachine) se aceptan como no-op con audit
//! log via tracing.
//!
//! Producción real: integrar con el graph del fractal — ListMachines query
//! BusRequest::ListEntes filtrado por `card.soma.namespaces.pid`.
use ente_bus::{BusClient, BusRequest, BusResponse};
use ente_card::Capability;
use std::collections::HashMap;
use tokio::signal::unix::{signal, SignalKind};
use tracing::{info, warn};
use tracing_subscriber::EnvFilter;
use zbus::{fdo, interface, zvariant::OwnedValue};
const BUS_NAME: &str = "org.freedesktop.machine1";
const OBJ_PATH: &str = "/org/freedesktop/machine1";
#[tokio::main(flavor = "current_thread")]
async fn main() -> anyhow::Result<()> {
init_tracing();
info!("ente-machined-compat: arrancando");
announce_to_fractal().await;
let manager = MachineManager;
let conn_result = zbus::connection::Builder::system()
.and_then(|b| b.name(BUS_NAME))
.and_then(|b| b.serve_at(OBJ_PATH, manager));
match conn_result {
Ok(builder) => match builder.build().await {
Ok(_conn) => {
info!(name = BUS_NAME, "name acquired, sirviendo");
wait_for_term().await
}
Err(e) => { warn!(?e, "build conn falló — modo idle"); wait_for_term().await }
},
Err(e) => { warn!(?e, "builder D-Bus falló — modo idle"); wait_for_term().await }
}
}
struct MachineManager;
/// Tipo del wire format de ListMachines: `(s, s, s, u, ay, ay, t, ay)` —
/// name, class, service, leader_pid, root_directory_path, id_unix, time_obtained,
/// machine_id_bytes. systemd usa este struct simplificado.
type Machine = (String, String, String, u32, String);
#[interface(name = "org.freedesktop.machine1.Manager")]
impl MachineManager {
/// Lista vacía — no trackeamos containers todavía.
async fn list_machines(&self) -> fdo::Result<Vec<Machine>> {
Ok(vec![])
}
/// Devuelve siempre NotFound — sin machines registradas.
async fn get_machine(&self, name: String) -> fdo::Result<zbus::zvariant::OwnedObjectPath> {
Err(fdo::Error::Failed(format!("machine '{name}' no encontrada")))
}
async fn get_machine_by_pid(&self, pid: u32) -> fdo::Result<zbus::zvariant::OwnedObjectPath> {
Err(fdo::Error::Failed(format!("PID {pid} no asociado a ninguna machine")))
}
async fn register_machine(
&self,
name: String,
_id: Vec<u8>,
_service: String,
class: String,
_leader_pid: u32,
_root_directory: String,
) -> fdo::Result<zbus::zvariant::OwnedObjectPath> {
info!(%name, %class, "RegisterMachine (no-op)");
Err(fdo::Error::NotSupported(
"RegisterMachine no implementado — usar Cards del fractal".into()
))
}
async fn register_machine_with_network(
&self,
name: String,
id: Vec<u8>,
service: String,
class: String,
leader_pid: u32,
root_directory: String,
_network_interfaces: Vec<i32>,
) -> fdo::Result<zbus::zvariant::OwnedObjectPath> {
self.register_machine(name, id, service, class, leader_pid, root_directory).await
}
async fn create_machine(
&self,
name: String,
_id: Vec<u8>,
_service: String,
class: String,
_leader_pid: u32,
_root_directory: String,
_scope_properties: Vec<(String, OwnedValue)>,
) -> fdo::Result<zbus::zvariant::OwnedObjectPath> {
info!(%name, %class, "CreateMachine (no-op)");
Err(fdo::Error::NotSupported(
"CreateMachine no implementado".into()
))
}
async fn terminate_machine(&self, name: String) -> fdo::Result<()> {
info!(%name, "TerminateMachine (no-op)");
Ok(())
}
async fn kill_machine(&self, name: String, _who: String, _signal: i32) -> fdo::Result<()> {
info!(%name, "KillMachine (no-op)");
Ok(())
}
async fn get_machine_address(&self, name: String) -> fdo::Result<Vec<(i32, Vec<u8>)>> {
warn!(%name, "GetMachineAddress (sin tracking, devuelvo vacío)");
Ok(vec![])
}
async fn get_machine_osrelease(&self, name: String) -> fdo::Result<HashMap<String, String>> {
warn!(%name, "GetMachineOSRelease (sin tracking)");
Ok(HashMap::new())
}
/// Operaciones sobre la "host machine" (PID 1 namespace) — siempre
/// disponibles. Usamos el path canónico `/org/freedesktop/machine1/machine/_host`.
async fn open_machine_login(&self, _name: String) -> fdo::Result<(zbus::zvariant::OwnedObjectPath, zbus::zvariant::OwnedFd)> {
Err(fdo::Error::NotSupported(
"OpenMachineLogin no implementado".into()
))
}
async fn open_machine_shell(
&self,
_name: String,
_user: String,
_path: String,
_args: Vec<String>,
_environment: Vec<String>,
) -> fdo::Result<(zbus::zvariant::OwnedObjectPath, zbus::zvariant::OwnedFd)> {
Err(fdo::Error::NotSupported("OpenMachineShell no implementado".into()))
}
}
async fn announce_to_fractal() {
if let Ok(mut client) = BusClient::from_env().await {
let req = BusRequest::Announce {
capabilities: vec![Capability::Endpoint {
interface: ente_card::InterfaceId([0xa5; 16]),
version: 1,
}],
};
match client.call(req).await {
Ok(BusResponse::Ok) => info!("Announce → bus interno OK"),
Ok(other) => warn!(?other, "Announce respuesta inesperada"),
Err(e) => warn!(?e, "Announce falló"),
}
}
}
async fn wait_for_term() -> anyhow::Result<()> {
let mut term = signal(SignalKind::terminate())?;
let mut int_ = signal(SignalKind::interrupt())?;
tokio::select! {
_ = term.recv() => info!("SIGTERM"),
_ = int_.recv() => info!("SIGINT"),
}
Ok(())
}
fn init_tracing() {
let filter = EnvFilter::try_from_default_env()
.unwrap_or_else(|_| EnvFilter::new("ente_machined_compat=info"));
tracing_subscriber::fmt().with_env_filter(filter).with_target(true).init();
}
@@ -0,0 +1,20 @@
[package]
name = "ente-notify-compat"
version = "0.0.1"
edition.workspace = true
license.workspace = true
publish.workspace = true
[[bin]]
name = "ente-notify-compat"
path = "src/main.rs"
[dependencies]
ente-card = { path = "../../protocol/ente-card" }
ente-bus = { path = "../../runtime/ente-bus" }
nix = { workspace = true }
libc = { workspace = true }
anyhow = { workspace = true }
tokio = { workspace = true }
tracing = { workspace = true }
tracing-subscriber = { workspace = true }
@@ -0,0 +1,160 @@
//! ente-notify-compat: NOTIFY_SOCKET listener para apps `Type=notify`.
//!
//! systemd convention: el servicio escribe `KEY=value\n` lines a un socket
//! datagram cuya path está en `$NOTIFY_SOCKET`. Keys típicos:
//! - READY=1 (servicio listo para recibir requests)
//! - STATUS=text (descripción del estado)
//! - WATCHDOG=1 (heartbeat)
//! - STOPPING=1 (cierre ordenado)
//! - MAINPID=<pid> (cambio de PID principal)
//!
//! Path canonical: /run/systemd/notify. Bindeable sólo con CAP_NET_BIND_SERVICE
//! o si /run es writable.
//!
//! Para que las apps lo usen, ente-soma debe inyectar `NOTIFY_SOCKET=<path>`
//! en el envp de cada Ente encarnado. Eso ya lo hace via build_env() —
//! aquí sólo necesitamos que el path sea coherente.
use ente_bus::{BusClient, BusRequest, BusResponse};
use ente_card::Capability;
use std::os::fd::{AsRawFd, OwnedFd};
use std::path::Path;
use tokio::io::unix::AsyncFd;
use tokio::signal::unix::{signal, SignalKind};
use tracing::{debug, info, warn};
use tracing_subscriber::EnvFilter;
const NOTIFY_SOCKET_PATH: &str = "/run/systemd/notify";
#[tokio::main(flavor = "current_thread")]
async fn main() -> anyhow::Result<()> {
init_tracing();
info!(path = NOTIFY_SOCKET_PATH, "ente-notify-compat: arrancando");
announce_to_fractal().await;
let stream = match bind_dgram(NOTIFY_SOCKET_PATH) {
Some(s) => s,
None => {
warn!("no se pudo bind — modo idle (apps Type=notify caerán a no-op)");
return wait_for_term().await;
}
};
info!("NOTIFY_SOCKET listening");
spawn_listener(stream);
wait_for_term().await
}
fn bind_dgram(path: &str) -> Option<AsyncFd<OwnedFdWrap>> {
use nix::sys::socket::{bind, socket, AddressFamily, SockFlag, SockType, UnixAddr};
let _ = std::fs::remove_file(path);
if let Some(parent) = Path::new(path).parent() {
let _ = std::fs::create_dir_all(parent);
}
let fd = socket(
AddressFamily::Unix,
SockType::Datagram,
SockFlag::SOCK_NONBLOCK | SockFlag::SOCK_CLOEXEC,
None,
).ok()?;
let addr = UnixAddr::new(path).ok()?;
if let Err(e) = bind(fd.as_raw_fd(), &addr) {
warn!(?e, %path, "bind");
return None;
}
// Permisos abiertos: cualquier proceso debería poder escribir notificaciones.
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o666));
AsyncFd::new(OwnedFdWrap(fd)).ok()
}
struct OwnedFdWrap(OwnedFd);
impl AsRawFd for OwnedFdWrap {
fn as_raw_fd(&self) -> std::os::fd::RawFd { self.0.as_raw_fd() }
}
fn spawn_listener(async_fd: AsyncFd<OwnedFdWrap>) {
tokio::spawn(async move {
let mut buf = vec![0u8; 16 * 1024];
loop {
let mut guard = match async_fd.readable().await {
Ok(g) => g,
Err(e) => { warn!(?e, "readable"); return; }
};
let raw_fd = guard.get_inner().as_raw_fd();
loop {
let n = unsafe { libc::recv(raw_fd, buf.as_mut_ptr() as *mut _, buf.len(), 0) };
if n <= 0 { break; }
handle_notification(&buf[..n as usize]);
}
guard.clear_ready();
}
});
}
fn handle_notification(buf: &[u8]) {
let s = match std::str::from_utf8(buf) {
Ok(s) => s,
Err(_) => { debug!(len = buf.len(), "notify binario, skip"); return; }
};
let mut ready = false;
let mut status = None;
let mut mainpid = None;
let mut watchdog = false;
let mut stopping = false;
let mut other_keys = Vec::new();
for line in s.lines() {
if let Some((k, v)) = line.split_once('=') {
match k {
"READY" if v == "1" => ready = true,
"STATUS" => status = Some(v.to_string()),
"MAINPID" => mainpid = v.parse::<u32>().ok(),
"WATCHDOG" if v == "1" => watchdog = true,
"STOPPING" if v == "1" => stopping = true,
_ => other_keys.push(format!("{k}={v}")),
}
}
}
if ready {
info!(?status, ?mainpid, "sd_notify READY");
} else if stopping {
info!(?status, "sd_notify STOPPING");
} else if watchdog {
debug!("sd_notify WATCHDOG");
} else if let Some(s) = status {
info!(%s, "sd_notify STATUS");
} else if !other_keys.is_empty() {
debug!(keys = ?other_keys, "sd_notify (other)");
}
}
async fn announce_to_fractal() {
if let Ok(mut client) = BusClient::from_env().await {
let req = BusRequest::Announce {
capabilities: vec![Capability::Endpoint {
interface: ente_card::InterfaceId([0xa7; 16]),
version: 1,
}],
};
match client.call(req).await {
Ok(BusResponse::Ok) => info!("Announce → bus interno OK"),
Ok(other) => warn!(?other, "Announce respuesta inesperada"),
Err(e) => warn!(?e, "Announce falló"),
}
}
}
async fn wait_for_term() -> anyhow::Result<()> {
let mut term = signal(SignalKind::terminate())?;
let mut int_ = signal(SignalKind::interrupt())?;
tokio::select! {
_ = term.recv() => info!("SIGTERM"),
_ = int_.recv() => info!("SIGINT"),
}
Ok(())
}
fn init_tracing() {
let filter = EnvFilter::try_from_default_env()
.unwrap_or_else(|_| EnvFilter::new("ente_notify_compat=info"));
tracing_subscriber::fmt().with_env_filter(filter).with_target(true).init();
}
@@ -0,0 +1,20 @@
[package]
name = "ente-policy-provider"
version = "0.0.1"
edition.workspace = true
license.workspace = true
publish.workspace = true
[[bin]]
name = "ente-policy-provider"
path = "src/main.rs"
[dependencies]
ente-card = { path = "../../protocol/ente-card" }
ente-bus = { path = "../../runtime/ente-bus" }
serde = { workspace = true }
serde_json = { workspace = true }
anyhow = { workspace = true }
tokio = { workspace = true }
tracing = { workspace = true }
tracing-subscriber = { workspace = true }
@@ -0,0 +1,221 @@
//! ente-policy-provider: Ente que arbitra autorizaciones de Polkit.
//!
//! Se anuncia como proveedor de `POLKIT_DECISION_IFACE` en el bus interno.
//! Cuando `ente-polkit-compat` recibe `CheckAuthorization` D-Bus, forwarda
//! a este Ente vía Invoke. Aquí decidimos sí/no según política configurada.
//!
//! Wire format del blob de entrada: `pid_be_u32 | uid_be_u32 | action_id_utf8`.
//! Respuesta: `[decision_byte]` — 1 = allow, 0 = deny.
//!
//! Política se carga de `/etc/ente/policy.json` (o ruta override por env
//! `ENTE_POLICY_FILE`). Formato:
//! ```json
//! {
//! "default": "allow",
//! "rules": [
//! { "match": "org.freedesktop.hostname1.*", "decision": "allow" },
//! { "match": "org.freedesktop.login1.power-off", "require_uid": 0 },
//! { "match": "*.set-*", "decision": "deny", "audit": true }
//! ]
//! }
//! ```
use ente_bus::{BusResponse, BusServer, InvokeHandler, POLKIT_DECISION_IFACE};
use ente_card::Capability;
use serde::Deserialize;
use std::sync::Arc;
use tokio::signal::unix::{signal, SignalKind};
use tracing::{info, warn};
use tracing_subscriber::EnvFilter;
#[derive(Debug, Clone, Deserialize)]
struct PolicyConfig {
#[serde(default = "default_decision")]
default: Decision,
#[serde(default)]
rules: Vec<Rule>,
}
fn default_decision() -> Decision { Decision::Allow }
#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
enum Decision { Allow, Deny }
#[derive(Debug, Clone, Deserialize)]
struct Rule {
/// Glob simple: `*` = wildcard. `org.freedesktop.hostname1.*` matchea
/// cualquier action_id con ese prefijo.
r#match: String,
#[serde(default)]
decision: Option<Decision>,
/// Si presente, sólo este uid pasa. Otros se denegen.
#[serde(default)]
require_uid: Option<u32>,
/// Si presente, sólo este pid pasa.
#[serde(default)]
require_pid: Option<u32>,
#[serde(default)]
audit: bool,
}
impl Default for PolicyConfig {
fn default() -> Self {
// Default sensato: caps escaladas requieren uid 0; el resto allow.
Self {
default: Decision::Allow,
rules: vec![
// Power management: cualquiera puede pedir el reboot,
// pero la decisión final está en el holder de Capability::Spawn.
Rule {
r#match: "org.freedesktop.login1.set-wall-message".into(),
decision: Some(Decision::Allow), require_uid: None, require_pid: None, audit: true,
},
// hostname/timezone/locale: requieren root.
Rule {
r#match: "org.freedesktop.hostname1.*".into(),
decision: None, require_uid: Some(0), require_pid: None, audit: true,
},
Rule {
r#match: "org.freedesktop.timedate1.*".into(),
decision: None, require_uid: Some(0), require_pid: None, audit: true,
},
Rule {
r#match: "org.freedesktop.locale1.*".into(),
decision: None, require_uid: Some(0), require_pid: None, audit: true,
},
],
}
}
}
#[tokio::main(flavor = "current_thread")]
async fn main() -> anyhow::Result<()> {
init_tracing();
info!("ente-policy-provider: arrancando");
let policy = load_policy();
info!(rules = policy.rules.len(), default = ?policy.default, "policy cargada");
let handler = PolicyHandler { policy: Arc::new(policy) };
tokio::spawn(async {
let mut term = signal(SignalKind::terminate()).unwrap();
let mut int_ = signal(SignalKind::interrupt()).unwrap();
tokio::select! {
_ = term.recv() => info!("SIGTERM"),
_ = int_.recv() => info!("SIGINT"),
}
std::process::exit(0);
});
// Una única conexión: announce + serve. Bidirectional bajo el hood.
let mut server = BusServer::from_env().await?;
server.announce(vec![Capability::Endpoint {
interface: POLKIT_DECISION_IFACE,
version: 1,
}]).await?;
info!("Announce OK; sirviendo invokes de policy decision");
server.serve(handler).await?;
Ok(())
}
struct PolicyHandler {
policy: Arc<PolicyConfig>,
}
impl InvokeHandler for PolicyHandler {
fn handle(&mut self, cap: Capability, blob: Vec<u8>) -> BusResponse {
// Validar cap (defensa contra forwarding a interface incorrecto).
if !matches!(&cap, Capability::Endpoint { interface, .. } if *interface == POLKIT_DECISION_IFACE) {
return BusResponse::Error(format!("policy-provider: cap inesperado {cap:?}"));
}
// Decodificar blob: [pid:4][uid:4][action_id...]
if blob.len() < 8 {
return BusResponse::Error("blob demasiado corto (esperado pid|uid|action_id)".into());
}
let pid = u32::from_be_bytes(blob[0..4].try_into().unwrap());
let uid = u32::from_be_bytes(blob[4..8].try_into().unwrap());
let action_id = match std::str::from_utf8(&blob[8..]) {
Ok(s) => s,
Err(_) => return BusResponse::Error("action_id no es UTF-8".into()),
};
let decision = decide(&self.policy, action_id, pid, uid);
let byte = if decision == Decision::Allow { 1u8 } else { 0u8 };
info!(action_id, pid, uid, ?decision, "policy decision");
BusResponse::Invoked { result: vec![byte] }
}
}
fn decide(policy: &PolicyConfig, action_id: &str, pid: u32, uid: u32) -> Decision {
for rule in &policy.rules {
if !glob_match(&rule.r#match, action_id) { continue; }
if let Some(req_uid) = rule.require_uid {
if uid != req_uid {
if rule.audit {
info!(action_id, uid, req_uid, "AUDIT: deny por uid mismatch");
}
return Decision::Deny;
}
}
if let Some(req_pid) = rule.require_pid {
if pid != req_pid {
if rule.audit {
info!(action_id, pid, req_pid, "AUDIT: deny por pid mismatch");
}
return Decision::Deny;
}
}
if let Some(d) = rule.decision {
if rule.audit {
info!(action_id, ?d, "AUDIT: rule match con decisión explícita");
}
return d;
}
// Rule matched pero sin decisión explícita (sólo require_*) y todos
// los requires pasaron — caemos al default.
if rule.audit {
info!(action_id, ?policy.default, "AUDIT: rule match → default");
}
return policy.default;
}
policy.default
}
/// Glob simple: `*` matchea cualquier cosa. Soporta prefix (`foo.*`),
/// suffix (`*.bar`) y wildcard exacto (`*`). No es PCRE — intencional.
fn glob_match(pattern: &str, target: &str) -> bool {
if pattern == "*" { return true; }
if let Some(prefix) = pattern.strip_suffix(".*") {
return target == prefix || target.starts_with(&format!("{prefix}."));
}
if let Some(suffix) = pattern.strip_prefix("*.") {
return target == suffix || target.ends_with(&format!(".{suffix}"));
}
pattern == target
}
fn load_policy() -> PolicyConfig {
let path = std::env::var("ENTE_POLICY_FILE")
.unwrap_or_else(|_| "/etc/ente/policy.json".into());
match std::fs::read_to_string(&path) {
Ok(content) => match serde_json::from_str(&content) {
Ok(p) => { info!(path, "policy file cargado"); p }
Err(e) => {
warn!(?e, path, "policy file inválido, usando defaults");
PolicyConfig::default()
}
},
Err(_) => {
info!(path, "policy file ausente — usando defaults conservadores");
PolicyConfig::default()
}
}
}
fn init_tracing() {
let filter = EnvFilter::try_from_default_env()
.unwrap_or_else(|_| EnvFilter::new("ente_policy_provider=info"));
tracing_subscriber::fmt().with_env_filter(filter).with_target(true).init();
}
@@ -0,0 +1,19 @@
[package]
name = "ente-polkit-compat"
version = "0.0.1"
edition.workspace = true
license.workspace = true
publish.workspace = true
[[bin]]
name = "ente-polkit-compat"
path = "src/main.rs"
[dependencies]
ente-card = { path = "../../protocol/ente-card" }
ente-bus = { path = "../../runtime/ente-bus" }
anyhow = { workspace = true }
tokio = { workspace = true }
tracing = { workspace = true }
tracing-subscriber = { workspace = true }
zbus = { version = "4", default-features = false, features = ["tokio"] }
@@ -0,0 +1,264 @@
//! ente-polkit-compat: shim de `org.freedesktop.PolicyKit1.Authority`.
//!
//! Polkit autoriza llamadas privilegiadas (e.g. SetHostname, PowerOff).
//! En el fractal no usamos polkit como gatekeeper — la auth se hace en
//! el bus interno via SO_PEERCRED y capability grants. Pero apps que
//! usan polkit (gnome-control-center, etc) bloquean en `CheckAuthorization`
//! si no responde nadie.
//!
//! Este shim responde "is_authorized=true" siempre — el fractal queda
//! como sistema confiado. El logging deja audit trail de qué acciones se
//! han pedido para futuro análisis.
//!
//! Producción real: integrar con el grant system del bus interno —
//! CheckAuthorization solicita un token al graph y devuelve true/false
//! según el resultado.
use ente_bus::{BusClient, BusRequest, BusResponse, POLKIT_DECISION_IFACE, POLKIT_SERVICE_IFACE};
use ente_card::Capability;
use std::collections::HashMap;
use tokio::signal::unix::{signal, SignalKind};
use tracing::{debug, info, warn};
use tracing_subscriber::EnvFilter;
use zbus::{fdo, interface, zvariant::OwnedValue};
const BUS_NAME: &str = "org.freedesktop.PolicyKit1";
const OBJ_PATH: &str = "/org/freedesktop/PolicyKit1/Authority";
#[tokio::main(flavor = "current_thread")]
async fn main() -> anyhow::Result<()> {
init_tracing();
info!("ente-polkit-compat: arrancando");
announce_to_fractal().await;
let manager = PolkitAuthority;
let conn_result = zbus::connection::Builder::system()
.and_then(|b| b.name(BUS_NAME))
.and_then(|b| b.serve_at(OBJ_PATH, manager));
match conn_result {
Ok(builder) => match builder.build().await {
Ok(_conn) => {
info!(name = BUS_NAME, "name acquired, sirviendo");
wait_for_term().await
}
Err(e) => { warn!(?e, "build conn falló — modo idle"); wait_for_term().await }
},
Err(e) => { warn!(?e, "builder D-Bus falló — modo idle"); wait_for_term().await }
}
}
struct PolkitAuthority;
/// Wire format de Polkit: `Subject = (s, a{sv})` — kind ("unix-session",
/// "unix-process", "system-bus-name") + detalles. El detail típico:
/// {"pid": u32, "start-time": u64, "uid": u32}
type Subject = (String, HashMap<String, OwnedValue>);
/// Resultado de `CheckAuthorization`: `(b, b, a{ss})` —
/// is_authorized, is_challenge, details.
type AuthResult = (bool, bool, HashMap<String, String>);
#[interface(name = "org.freedesktop.PolicyKit1.Authority")]
impl PolkitAuthority {
async fn check_authorization(
&self,
subject: Subject,
action_id: String,
_details: HashMap<String, String>,
_flags: u32,
_cancellation_id: String,
) -> fdo::Result<AuthResult> {
let (subj_kind, subj_details) = subject;
let pid = subj_details.get("pid")
.and_then(|v| u32::try_from(v).ok());
let uid = subj_details.get("uid")
.and_then(|v| u32::try_from(v).ok());
// Pregunta al bus interno del fractal si hay un policy provider.
// Si lo hay, su decisión gobierna. Si no (NoProvider), default = allow.
let decision = query_policy(&action_id, pid, uid).await;
info!(%action_id, %subj_kind, ?pid, ?uid, ?decision, "CheckAuthorization");
Ok((decision.allow, false, HashMap::new()))
}
async fn check_authorization_by_async(
&self,
subject: Subject,
action_id: String,
details: HashMap<String, String>,
flags: u32,
cancellation_id: String,
) -> fdo::Result<AuthResult> {
// Mismo comportamiento; algunos clientes llaman la versión async.
self.check_authorization(subject, action_id, details, flags, cancellation_id).await
}
async fn cancel_check_authorization(&self, _cancellation_id: String) -> fdo::Result<()> {
Ok(())
}
async fn enumerate_actions(&self, _locale: String) -> fdo::Result<Vec<EnumeratedAction>> {
// Devolvemos lista vacía — no enumeramos acciones registradas.
// El llamador (típicamente gnome-control-center settings panel)
// debería degradar grácilmente.
Ok(vec![])
}
async fn register_authentication_agent(
&self,
_subject: Subject,
_locale: String,
_object_path: String,
) -> fdo::Result<()> {
info!("RegisterAuthenticationAgent (no-op)");
Ok(())
}
async fn register_authentication_agent_with_options(
&self,
_subject: Subject,
_locale: String,
_object_path: String,
_options: HashMap<String, OwnedValue>,
) -> fdo::Result<()> {
Ok(())
}
async fn unregister_authentication_agent(
&self,
_subject: Subject,
_object_path: String,
) -> fdo::Result<()> {
Ok(())
}
async fn authentication_agent_response(
&self,
_cookie: String,
_identity: (String, HashMap<String, OwnedValue>),
) -> fdo::Result<()> {
Ok(())
}
async fn enumerate_temporary_authorizations(
&self,
_subject: Subject,
) -> fdo::Result<Vec<TemporaryAuth>> {
Ok(vec![])
}
async fn revoke_temporary_authorizations(&self, _subject: Subject) -> fdo::Result<()> {
Ok(())
}
async fn revoke_temporary_authorization_by_id(&self, _id: String) -> fdo::Result<()> {
Ok(())
}
#[zbus(property)]
async fn backend_name(&self) -> String { "ente-polkit-compat".into() }
#[zbus(property)]
async fn backend_version(&self) -> String { env!("CARGO_PKG_VERSION").into() }
#[zbus(property)]
async fn backend_features(&self) -> u32 { 0 }
}
/// Wire signature de EnumerateActions item:
/// `(ssssssuusa{ss})` — action_id, descripción, message, vendor, vendor_url,
/// icon_name, implicit_any, implicit_inactive, implicit_active, annotations.
type EnumeratedAction = (
String, String, String, String, String, String,
u32, u32, String, HashMap<String, String>,
);
/// Wire signature de TemporaryAuthorization:
/// `(sssss)` — id, action_id, subject_kind, subject_detail, time_obtained, time_expires.
/// Aquí `(string)` * 5 + 2 timestamps. Simplificamos al subset relevante.
type TemporaryAuth = (String, String, (String, HashMap<String, OwnedValue>), u64, u64);
/// Resultado de una consulta de policy al fractal.
#[derive(Debug)]
struct PolicyDecision {
allow: bool,
/// Origen: "fractal" si vino del bus, "default-allow" si no había proveedor.
/// Sólo aparece en `Debug` (logging); ningún consumer lo lee programmático.
#[allow(dead_code)]
source: &'static str,
}
/// Pregunta al bus interno: ¿hay alguien que decida sobre `action_id`?
/// Wire format del blob: `pid_u32_be | uid_u32_be | action_id_utf8`.
/// El proveedor responde con `Invoked { result: [0|1] }` — 1 = allow.
async fn query_policy(action_id: &str, pid: Option<u32>, uid: Option<u32>) -> PolicyDecision {
let mut blob = Vec::with_capacity(8 + action_id.len());
blob.extend_from_slice(&pid.unwrap_or(0).to_be_bytes());
blob.extend_from_slice(&uid.unwrap_or(0).to_be_bytes());
blob.extend_from_slice(action_id.as_bytes());
let mut client = match BusClient::from_env().await {
Ok(c) => c,
Err(e) => {
debug!(?e, "no bus client — default allow");
return PolicyDecision { allow: true, source: "no-bus" };
}
};
let req = BusRequest::Invoke {
cap: Capability::Endpoint {
interface: POLKIT_DECISION_IFACE,
version: 1,
},
blob,
};
match client.call(req).await {
Ok(BusResponse::Invoked { result }) => {
let allow = result.first().copied().unwrap_or(1) != 0;
PolicyDecision { allow, source: "fractal" }
}
Ok(BusResponse::Error(msg)) if msg.contains("sin proveedor") => {
// No hay policy provider — default allow.
PolicyDecision { allow: true, source: "default-allow" }
}
Ok(other) => {
warn!(?other, "policy: respuesta inesperada — default allow");
PolicyDecision { allow: true, source: "default-allow" }
}
Err(e) => {
warn!(?e, "policy: bus call falló — default allow");
PolicyDecision { allow: true, source: "default-allow" }
}
}
}
async fn announce_to_fractal() {
if let Ok(mut client) = BusClient::from_env().await {
let req = BusRequest::Announce {
capabilities: vec![Capability::Endpoint {
interface: POLKIT_SERVICE_IFACE,
version: 1,
}],
};
match client.call(req).await {
Ok(BusResponse::Ok) => info!("Announce → bus interno OK"),
Ok(other) => warn!(?other, "Announce respuesta inesperada"),
Err(e) => warn!(?e, "Announce falló"),
}
}
}
async fn wait_for_term() -> anyhow::Result<()> {
let mut term = signal(SignalKind::terminate())?;
let mut int_ = signal(SignalKind::interrupt())?;
tokio::select! {
_ = term.recv() => info!("SIGTERM"),
_ = int_.recv() => info!("SIGINT"),
}
Ok(())
}
fn init_tracing() {
let filter = EnvFilter::try_from_default_env()
.unwrap_or_else(|_| EnvFilter::new("ente_polkit_compat=info"));
tracing_subscriber::fmt().with_env_filter(filter).with_target(true).init();
}
@@ -0,0 +1,20 @@
[package]
name = "ente-resolved-compat"
version = "0.0.1"
edition.workspace = true
license.workspace = true
publish.workspace = true
[[bin]]
name = "ente-resolved-compat"
path = "src/main.rs"
[dependencies]
ente-card = { path = "../../protocol/ente-card" }
ente-bus = { path = "../../runtime/ente-bus" }
libc = { workspace = true }
anyhow = { workspace = true }
tokio = { workspace = true }
tracing = { workspace = true }
tracing-subscriber = { workspace = true }
zbus = { version = "4", default-features = false, features = ["tokio"] }
@@ -0,0 +1,210 @@
//! ente-resolved-compat: shim de `org.freedesktop.resolve1`.
//!
//! Bajo el capó usa `tokio::net::lookup_host` (que termina en getaddrinfo
//! del libc del sistema). No reimplementamos un resolver DNS — delegamos
//! al stack de resolución del kernel/glibc.
//!
//! Métodos cubiertos:
//! - ResolveHostname (name → addresses)
//! - ResolveAddress (address → name reverse)
//! - ResolveRecord (TXT/SRV/etc) — NotSupported (requiere DNS query directa)
use ente_bus::{BusClient, BusRequest, BusResponse};
use ente_card::Capability;
use std::net::IpAddr;
use tokio::signal::unix::{signal, SignalKind};
use tracing::{info, warn};
use tracing_subscriber::EnvFilter;
use zbus::{fdo, interface};
const BUS_NAME: &str = "org.freedesktop.resolve1";
const OBJ_PATH: &str = "/org/freedesktop/resolve1";
const AF_INET: i32 = 2;
const AF_INET6: i32 = 10;
#[tokio::main(flavor = "current_thread")]
async fn main() -> anyhow::Result<()> {
init_tracing();
info!("ente-resolved-compat: arrancando");
announce_to_fractal().await;
let manager = ResolveManager;
let conn_result = zbus::connection::Builder::system()
.and_then(|b| b.name(BUS_NAME))
.and_then(|b| b.serve_at(OBJ_PATH, manager));
match conn_result {
Ok(builder) => match builder.build().await {
Ok(_conn) => {
info!(name = BUS_NAME, "name acquired, sirviendo");
wait_for_term().await
}
Err(e) => { warn!(?e, "build conn falló — modo idle"); wait_for_term().await }
},
Err(e) => { warn!(?e, "builder D-Bus falló — modo idle"); wait_for_term().await }
}
}
struct ResolveManager;
/// Tipo del wire format de `ResolveHostname`. Por entry: (ifindex, family,
/// address-as-bytes). systemd-resolved devuelve hasta 4 bytes para AF_INET
/// y 16 para AF_INET6.
type HostnameAddress = (i32, i32, Vec<u8>);
#[interface(name = "org.freedesktop.resolve1.Manager")]
impl ResolveManager {
/// Wire signature: `ResolveHostname(in iiusst, out a(iiay)st)` — recibe
/// (ifindex, name, family, flags), devuelve (addresses, canonical, flags).
async fn resolve_hostname(
&self,
_ifindex: i32,
name: String,
family: i32,
_flags: u64,
) -> fdo::Result<(Vec<HostnameAddress>, String, u64)> {
// tokio::net::lookup_host requiere "host:port"; usamos puerto sentinel.
let target = format!("{name}:0");
let addrs = match tokio::net::lookup_host(&target).await {
Ok(it) => it,
Err(e) => return Err(fdo::Error::Failed(format!("lookup_host {name}: {e}"))),
};
let mut out = Vec::new();
for sa in addrs {
let ip = sa.ip();
let (af, bytes) = match ip {
IpAddr::V4(v4) => (AF_INET, v4.octets().to_vec()),
IpAddr::V6(v6) => (AF_INET6, v6.octets().to_vec()),
};
// Filtrado por family si el llamador lo pidió específico.
if family != 0 && family != af { continue; }
out.push((0i32, af, bytes));
}
if out.is_empty() {
return Err(fdo::Error::Failed(format!("sin resoluciones para {name} (family={family})")));
}
info!(%name, family, count = out.len(), "ResolveHostname");
Ok((out, name, 0))
}
/// Wire signature: `ResolveAddress(in iiayt, out a(is)t)` — (ifindex,
/// family, address, flags) → (names, flags).
async fn resolve_address(
&self,
_ifindex: i32,
family: i32,
address: Vec<u8>,
_flags: u64,
) -> fdo::Result<(Vec<(i32, String)>, u64)> {
let ip = parse_address(family, &address)
.ok_or_else(|| fdo::Error::InvalidArgs(format!("address malformado family={family} bytes={}", address.len())))?;
// Reverse lookup vía getnameinfo. Usamos std::net::lookup_addr no existe,
// así que invocamos via libc directamente.
let name = reverse_lookup(ip)
.ok_or_else(|| fdo::Error::Failed(format!("sin reverse para {ip}")))?;
info!(%ip, %name, "ResolveAddress");
Ok((vec![(0, name)], 0))
}
async fn resolve_record(
&self,
_ifindex: i32,
_name: String,
_class: u16,
_type_: u16,
_flags: u64,
) -> fdo::Result<(Vec<(i32, u16, u16, Vec<u8>)>, u64)> {
Err(fdo::Error::NotSupported(
"ResolveRecord requiere acceso DNS directo — stub no implementado".into()
))
}
}
fn parse_address(family: i32, bytes: &[u8]) -> Option<IpAddr> {
match family {
AF_INET if bytes.len() == 4 => {
let mut a = [0u8; 4];
a.copy_from_slice(bytes);
Some(IpAddr::V4(std::net::Ipv4Addr::from(a)))
}
AF_INET6 if bytes.len() == 16 => {
let mut a = [0u8; 16];
a.copy_from_slice(bytes);
Some(IpAddr::V6(std::net::Ipv6Addr::from(a)))
}
_ => None,
}
}
/// getnameinfo(3) wrapper. Devuelve None si no resuelve.
fn reverse_lookup(ip: IpAddr) -> Option<String> {
use std::os::raw::c_char;
let mut buf = [0i8; 256];
let r = match ip {
IpAddr::V4(v4) => unsafe {
let octets = v4.octets();
let mut sin = std::mem::zeroed::<libc::sockaddr_in>();
sin.sin_family = libc::AF_INET as u16;
sin.sin_addr = libc::in_addr {
s_addr: u32::from_ne_bytes(octets),
};
libc::getnameinfo(
&sin as *const _ as *const libc::sockaddr,
std::mem::size_of::<libc::sockaddr_in>() as u32,
buf.as_mut_ptr() as *mut c_char, buf.len() as u32,
std::ptr::null_mut(), 0,
libc::NI_NAMEREQD,
)
},
IpAddr::V6(v6) => unsafe {
let octets = v6.octets();
let mut sin6 = std::mem::zeroed::<libc::sockaddr_in6>();
sin6.sin6_family = libc::AF_INET6 as u16;
sin6.sin6_addr.s6_addr.copy_from_slice(&octets);
libc::getnameinfo(
&sin6 as *const _ as *const libc::sockaddr,
std::mem::size_of::<libc::sockaddr_in6>() as u32,
buf.as_mut_ptr() as *mut c_char, buf.len() as u32,
std::ptr::null_mut(), 0,
libc::NI_NAMEREQD,
)
},
};
if r != 0 { return None; }
let cs = unsafe { std::ffi::CStr::from_ptr(buf.as_ptr()) };
cs.to_str().ok().map(String::from)
}
extern crate libc;
async fn announce_to_fractal() {
if let Ok(mut client) = BusClient::from_env().await {
let req = BusRequest::Announce {
capabilities: vec![Capability::Endpoint {
interface: ente_card::InterfaceId([0xa3; 16]),
version: 1,
}],
};
match client.call(req).await {
Ok(BusResponse::Ok) => info!("Announce → bus interno OK"),
Ok(other) => warn!(?other, "Announce respuesta inesperada"),
Err(e) => warn!(?e, "Announce falló"),
}
}
}
async fn wait_for_term() -> anyhow::Result<()> {
let mut term = signal(SignalKind::terminate())?;
let mut int_ = signal(SignalKind::interrupt())?;
tokio::select! {
_ = term.recv() => info!("SIGTERM"),
_ = int_.recv() => info!("SIGINT"),
}
Ok(())
}
fn init_tracing() {
let filter = EnvFilter::try_from_default_env()
.unwrap_or_else(|_| EnvFilter::new("ente_resolved_compat=info"));
tracing_subscriber::fmt().with_env_filter(filter).with_target(true).init();
}
@@ -0,0 +1,19 @@
[package]
name = "ente-systemd1-compat"
version = "0.0.1"
edition.workspace = true
license.workspace = true
publish.workspace = true
[[bin]]
name = "ente-systemd1-compat"
path = "src/main.rs"
[dependencies]
ente-card = { path = "../../protocol/ente-card" }
ente-bus = { path = "../../runtime/ente-bus" }
anyhow = { workspace = true }
tokio = { workspace = true }
tracing = { workspace = true }
tracing-subscriber = { workspace = true }
zbus = { version = "4", default-features = false, features = ["tokio"] }
@@ -0,0 +1,280 @@
//! ente-systemd1-compat: shim de `org.freedesktop.systemd1.Manager`.
//!
//! Centro de control que `systemctl` consulta. Sin esto, `systemctl list-units`
//! falla con `Failed to connect to bus` aunque el sistema funcione.
//!
//! Mapeo: cada Ente vivo del fractal aparece como una "unit" cuyo nombre es
//! `<label>.service`. Estados:
//! - `loaded` siempre (porque está en el grafo)
//! - `active` si tiene PID o es Wasm corriendo, `inactive` si está virtual
//! - sub_state: `running`/`exited`/`virtual`
//!
//! Métodos cubiertos del subset que `systemctl` típicamente llama al boot:
//! - ListUnits (basis de `systemctl list-units`)
//! - GetUnit / GetUnitByPID (object-path lookup; no servimos métodos del unit)
//! - StartUnit / StopUnit / RestartUnit (forwardea al bus interno)
//! - Subscribe / Unsubscribe (no-op)
//! - Reload (no-op — Cards inmutables)
//! - ListUnitFiles (vacío)
//! - GetVersion / Environment / Architecture (properties)
use ente_bus::{BusClient, BusRequest, BusResponse};
use ente_card::Capability;
use std::collections::HashMap;
use tokio::signal::unix::{signal, SignalKind};
use tracing::{info, warn};
use tracing_subscriber::EnvFilter;
use zbus::{fdo, interface, zvariant::{ObjectPath, OwnedObjectPath, OwnedValue}};
const BUS_NAME: &str = "org.freedesktop.systemd1";
const OBJ_PATH: &str = "/org/freedesktop/systemd1";
#[tokio::main(flavor = "current_thread")]
async fn main() -> anyhow::Result<()> {
init_tracing();
info!("ente-systemd1-compat: arrancando");
announce_to_fractal().await;
let manager = SystemdManager;
let conn_result = zbus::connection::Builder::system()
.and_then(|b| b.name(BUS_NAME))
.and_then(|b| b.serve_at(OBJ_PATH, manager));
match conn_result {
Ok(builder) => match builder.build().await {
Ok(_conn) => {
info!(name = BUS_NAME, "name acquired, sirviendo systemctl");
wait_for_term().await
}
Err(e) => { warn!(?e, "build conn falló — modo idle"); wait_for_term().await }
},
Err(e) => { warn!(?e, "builder D-Bus falló — modo idle"); wait_for_term().await }
}
}
struct SystemdManager;
/// Wire format de un unit en `ListUnits`:
/// (name, description, load_state, active_state, sub_state, followed,
/// unit_path, job_id, job_type, job_path)
type UnitInfo = (
String, String, String, String, String, String,
OwnedObjectPath, u32, String, OwnedObjectPath,
);
#[interface(name = "org.freedesktop.systemd1.Manager")]
impl SystemdManager {
async fn list_units(&self) -> fdo::Result<Vec<UnitInfo>> {
let entes = match query_list_entes().await {
Some(es) => es,
None => return Ok(vec![]),
};
let unit_path = ObjectPath::try_from("/org/freedesktop/systemd1/unit/_invalid")
.map_err(|e| fdo::Error::Failed(format!("path: {e}")))?;
let job_path = ObjectPath::try_from("/")
.map_err(|e| fdo::Error::Failed(format!("path: {e}")))?;
let mut out = Vec::with_capacity(entes.len());
for e in entes {
let name = format!("{}.service", e.label);
let description = format!("Ente: {} ({})", e.label, e.id);
let active_state = if e.pid.is_some() { "active" } else { "active" };
let sub_state = match e.pid {
Some(_) => "running",
None => "virtual",
};
out.push((
name,
description,
"loaded".to_string(),
active_state.to_string(),
sub_state.to_string(),
String::new(), // followed_unit
unit_path.clone().into(),
0u32, // job_id
String::new(), // job_type
job_path.clone().into(),
));
}
info!(count = out.len(), "ListUnits");
Ok(out)
}
async fn list_units_filtered(&self, _states: Vec<String>) -> fdo::Result<Vec<UnitInfo>> {
// Subset simple: ignoramos el filtro y devolvemos todas.
self.list_units().await
}
async fn list_units_by_names(&self, names: Vec<String>) -> fdo::Result<Vec<UnitInfo>> {
let all = self.list_units().await?;
let want: std::collections::HashSet<&String> = names.iter().collect();
Ok(all.into_iter().filter(|u| want.contains(&u.0)).collect())
}
async fn get_unit(&self, name: String) -> fdo::Result<OwnedObjectPath> {
if let Some(entes) = query_list_entes().await {
if entes.iter().any(|e| format!("{}.service", e.label) == name) {
let path = format!("/org/freedesktop/systemd1/unit/{}", escape_unit_name(&name));
return ObjectPath::try_from(path)
.map(OwnedObjectPath::from)
.map_err(|e| fdo::Error::Failed(format!("path: {e}")));
}
}
Err(fdo::Error::Failed(format!("Unit {name} not found")))
}
async fn get_unit_by_pid(&self, pid: u32) -> fdo::Result<OwnedObjectPath> {
if let Some(entes) = query_list_entes().await {
if let Some(e) = entes.iter().find(|e| e.pid == Some(pid as i32)) {
let path = format!("/org/freedesktop/systemd1/unit/{}",
escape_unit_name(&format!("{}.service", e.label)));
return ObjectPath::try_from(path)
.map(OwnedObjectPath::from)
.map_err(|e| fdo::Error::Failed(format!("path: {e}")));
}
}
Err(fdo::Error::Failed(format!("PID {pid} not in any unit")))
}
async fn start_unit(&self, name: String, _mode: String) -> fdo::Result<OwnedObjectPath> {
warn!(%name, "StartUnit no implementado — Cards no se 'start' tras boot");
Err(fdo::Error::NotSupported(
"StartUnit: el fractal usa Cards cargadas al boot, no unit files dinámicos".into()
))
}
async fn stop_unit(&self, name: String, _mode: String) -> fdo::Result<OwnedObjectPath> {
warn!(%name, "StopUnit (stub: TODO via bus capability)");
// TODO: bus → graph → kill PID por label. Por ahora no-op.
let path = ObjectPath::try_from("/").unwrap();
Ok(path.into())
}
async fn restart_unit(&self, name: String, mode: String) -> fdo::Result<OwnedObjectPath> {
info!(%name, "RestartUnit (delega a StopUnit)");
self.stop_unit(name, mode).await
}
async fn reload_unit(&self, name: String, _mode: String) -> fdo::Result<OwnedObjectPath> {
info!(%name, "ReloadUnit (no-op — Cards inmutables)");
let path = ObjectPath::try_from("/").unwrap();
Ok(path.into())
}
async fn kill_unit(&self, name: String, _who: String, _signal: i32) -> fdo::Result<()> {
warn!(%name, "KillUnit (stub)");
Ok(())
}
async fn subscribe(&self) -> fdo::Result<()> { Ok(()) }
async fn unsubscribe(&self) -> fdo::Result<()> { Ok(()) }
async fn reload(&self) -> fdo::Result<()> {
info!("Reload: trigger re-read (no-op — Cards no se recargan tras boot)");
Ok(())
}
async fn list_unit_files(&self) -> fdo::Result<Vec<(String, String)>> {
// Empty: no usamos unit files. Cards en su lugar.
Ok(vec![])
}
async fn list_jobs(&self) -> fdo::Result<Vec<(u32, String, String, String, OwnedObjectPath, OwnedObjectPath)>> {
Ok(vec![])
}
async fn get_default_target(&self) -> fdo::Result<String> {
Ok("multi-user.target".into())
}
async fn set_default_target(&self, _name: String, _force: bool) -> fdo::Result<(Vec<String>, Vec<String>, Vec<String>)> {
Err(fdo::Error::NotSupported("default target gestionado por Card de Semilla".into()))
}
// ----- Properties -----
#[zbus(property)]
async fn version(&self) -> String { format!("ente-systemd1-compat {}", env!("CARGO_PKG_VERSION")) }
#[zbus(property)]
async fn architecture(&self) -> String { std::env::consts::ARCH.into() }
#[zbus(property)]
async fn features(&self) -> String { "+ENTE-FRACTAL".into() }
#[zbus(property)]
async fn virtualization(&self) -> String { String::new() }
#[zbus(property)]
async fn confined(&self) -> bool { false }
#[zbus(property)]
async fn environment(&self) -> Vec<String> {
std::env::vars().map(|(k, v)| format!("{k}={v}")).collect()
}
#[zbus(property)]
async fn n_names(&self) -> u32 { 0 }
#[zbus(property)]
async fn n_jobs(&self) -> u32 { 0 }
#[zbus(property)]
async fn progress(&self) -> f64 { 1.0 }
}
/// Pregunta al bus interno por la lista de Entes vivos.
async fn query_list_entes() -> Option<Vec<ente_bus::EnteInfo>> {
let mut client = match BusClient::from_env().await {
Ok(c) => c,
Err(e) => { warn!(?e, "no bus client — devuelvo vacío"); return None; }
};
match client.call(BusRequest::ListEntes).await {
Ok(BusResponse::Entes(entes)) => Some(entes),
Ok(other) => { warn!(?other, "ListEntes respuesta inesperada"); None }
Err(e) => { warn!(?e, "ListEntes call falló"); None }
}
}
/// Escape de nombres de units para object paths según convención systemd:
/// `.` → `_2e`, `-` → `_2d`, etc. Para el demo usamos un escape simple.
fn escape_unit_name(name: &str) -> String {
name.chars().map(|c| match c {
c if c.is_ascii_alphanumeric() => c.to_string(),
c => format!("_{:02x}", c as u32),
}).collect()
}
async fn announce_to_fractal() {
if let Ok(mut client) = BusClient::from_env().await {
let req = BusRequest::Announce {
capabilities: vec![Capability::Endpoint {
interface: ente_card::InterfaceId([0xa6; 16]),
version: 1,
}],
};
match client.call(req).await {
Ok(BusResponse::Ok) => info!("Announce → bus interno OK"),
Ok(other) => warn!(?other, "Announce respuesta inesperada"),
Err(e) => warn!(?e, "Announce falló"),
}
}
}
async fn wait_for_term() -> anyhow::Result<()> {
let mut term = signal(SignalKind::terminate())?;
let mut int_ = signal(SignalKind::interrupt())?;
tokio::select! {
_ = term.recv() => info!("SIGTERM"),
_ = int_.recv() => info!("SIGINT"),
}
Ok(())
}
fn init_tracing() {
let filter = EnvFilter::try_from_default_env()
.unwrap_or_else(|_| EnvFilter::new("ente_systemd1_compat=info"));
tracing_subscriber::fmt().with_env_filter(filter).with_target(true).init();
}
#[allow(dead_code)]
fn _suppress(_: HashMap<String, OwnedValue>) {} // mantener import si se reduce
@@ -0,0 +1,19 @@
[package]
name = "ente-timedated-compat"
version = "0.0.1"
edition.workspace = true
license.workspace = true
publish.workspace = true
[[bin]]
name = "ente-timedated-compat"
path = "src/main.rs"
[dependencies]
ente-card = { path = "../../protocol/ente-card" }
ente-bus = { path = "../../runtime/ente-bus" }
anyhow = { workspace = true }
tokio = { workspace = true }
tracing = { workspace = true }
tracing-subscriber = { workspace = true }
zbus = { version = "4", default-features = false, features = ["tokio"] }
@@ -0,0 +1,182 @@
//! ente-timedated-compat: shim de `org.freedesktop.timedate1`.
//!
//! GNOME settings panel "Date & Time" llama aquí. Properties read-only se
//! mapean a syscalls/lecturas del sistema; setters log + forward.
use ente_bus::{BusClient, BusRequest, BusResponse};
use ente_card::Capability;
use std::time::{SystemTime, UNIX_EPOCH};
use tokio::signal::unix::{signal, SignalKind};
use tracing::{info, warn};
use tracing_subscriber::EnvFilter;
use zbus::{fdo, interface};
const BUS_NAME: &str = "org.freedesktop.timedate1";
const OBJ_PATH: &str = "/org/freedesktop/timedate1";
#[tokio::main(flavor = "current_thread")]
async fn main() -> anyhow::Result<()> {
init_tracing();
info!("ente-timedated-compat: arrancando");
announce_to_fractal().await;
let manager = TimedateManager::default();
let conn_result = zbus::connection::Builder::system()
.and_then(|b| b.name(BUS_NAME))
.and_then(|b| b.serve_at(OBJ_PATH, manager));
match conn_result {
Ok(builder) => match builder.build().await {
Ok(_conn) => {
info!(name = BUS_NAME, "name acquired, sirviendo");
wait_for_term().await
}
Err(e) => {
warn!(?e, "build conn falló — modo idle");
wait_for_term().await
}
},
Err(e) => {
warn!(?e, "builder D-Bus falló — modo idle");
wait_for_term().await
}
}
}
#[derive(Default)]
struct TimedateManager;
#[interface(name = "org.freedesktop.timedate1")]
impl TimedateManager {
// ----- Properties -----
/// Timezone configurada. Por defecto leemos el target de /etc/localtime
/// (un symlink a /usr/share/zoneinfo/<TZ>).
#[zbus(property)]
async fn timezone(&self) -> String {
std::fs::read_link("/etc/localtime")
.ok()
.and_then(|p| {
let s = p.to_string_lossy().into_owned();
s.strip_prefix("/usr/share/zoneinfo/").map(String::from)
.or_else(|| s.split("/zoneinfo/").nth(1).map(String::from))
})
.unwrap_or_else(|| "UTC".into())
}
/// True si el RTC del hardware está en local time. Convención moderna
/// es UTC (false). Reportamos false como default.
#[zbus(property)]
async fn local_rtc(&self) -> bool { false }
/// Si NTP es soportado. Reportamos true (asumimos systemd-timesyncd
/// o chrony están disponibles en el host).
#[zbus(property)]
async fn can_ntp(&self) -> bool { true }
/// Si NTP está activo. Sin daemon real bajo nuestro control no podemos
/// consultarlo con precisión — false como default seguro.
#[zbus(property)]
async fn ntp(&self) -> bool { false }
#[zbus(property)]
async fn ntpsynchronized(&self) -> bool { false }
/// Timestamp actual en microsegundos desde epoch.
#[zbus(property)]
async fn time_usec(&self) -> u64 {
SystemTime::now().duration_since(UNIX_EPOCH)
.map(|d| d.as_micros() as u64)
.unwrap_or(0)
}
#[zbus(property)]
async fn rtctime_usec(&self) -> u64 {
// El RTC real requiere ioctl a /dev/rtc — usamos system clock como aprox.
SystemTime::now().duration_since(UNIX_EPOCH)
.map(|d| d.as_micros() as u64)
.unwrap_or(0)
}
// ----- Setters -----
async fn set_time(&self, usec_utc: i64, _relative: bool, _interactive: bool) -> fdo::Result<()> {
info!(usec_utc, "SetTime (stub: requiere CAP_SYS_TIME para aplicar)");
Ok(())
}
async fn set_timezone(&self, timezone: String, _interactive: bool) -> fdo::Result<()> {
// Validar contra zoneinfo: el archivo destino debe existir.
let zoneinfo = format!("/usr/share/zoneinfo/{timezone}");
if !std::path::Path::new(&zoneinfo).exists() {
return Err(fdo::Error::InvalidArgs(format!("timezone desconocida: {timezone}")));
}
// Atomic relink: crear localtime.tmp como symlink, rename.
let tmp = "/etc/localtime.tmp";
let _ = std::fs::remove_file(tmp);
if let Err(e) = std::os::unix::fs::symlink(&zoneinfo, tmp) {
return Err(fdo::Error::Failed(format!("symlink: {e}")));
}
if let Err(e) = std::fs::rename(tmp, "/etc/localtime") {
return Err(fdo::Error::Failed(format!("rename: {e}")));
}
info!(%timezone, "SetTimezone → /etc/localtime");
Ok(())
}
async fn set_local_rtc(&self, local_rtc: bool, _fix_system: bool, _interactive: bool) -> fdo::Result<()> {
info!(local_rtc, "SetLocalRTC (stub)");
Ok(())
}
async fn set_ntp(&self, ntp: bool, _interactive: bool) -> fdo::Result<()> {
info!(ntp, "SetNTP (stub: no controlamos timesyncd)");
Ok(())
}
async fn list_timezones(&self) -> fdo::Result<Vec<String>> {
// Listar /usr/share/zoneinfo recursivamente. Hacemos un best-effort.
let mut out = Vec::new();
if let Ok(rd) = std::fs::read_dir("/usr/share/zoneinfo") {
for entry in rd.flatten() {
if let Ok(name) = entry.file_name().into_string() {
if !name.starts_with(|c: char| c.is_lowercase()) && name != "posix" && name != "right" {
out.push(name);
}
}
}
}
Ok(out)
}
}
async fn announce_to_fractal() {
if let Ok(mut client) = BusClient::from_env().await {
let req = BusRequest::Announce {
capabilities: vec![Capability::Endpoint {
interface: ente_card::InterfaceId([0xa1; 16]),
version: 1,
}],
};
match client.call(req).await {
Ok(BusResponse::Ok) => info!("Announce → bus interno OK"),
Ok(other) => warn!(?other, "Announce respuesta inesperada"),
Err(e) => warn!(?e, "Announce falló"),
}
}
}
async fn wait_for_term() -> anyhow::Result<()> {
let mut term = signal(SignalKind::terminate())?;
let mut int_ = signal(SignalKind::interrupt())?;
tokio::select! {
_ = term.recv() => info!("SIGTERM"),
_ = int_.recv() => info!("SIGINT"),
}
Ok(())
}
fn init_tracing() {
let filter = EnvFilter::try_from_default_env()
.unwrap_or_else(|_| EnvFilter::new("ente_timedated_compat=info"));
tracing_subscriber::fmt().with_env_filter(filter).with_target(true).init();
}
@@ -0,0 +1,21 @@
[package]
name = "ente-timer-compat"
version = "0.0.1"
edition.workspace = true
license.workspace = true
publish.workspace = true
[[bin]]
name = "ente-timer-compat"
path = "src/main.rs"
[dependencies]
ente-card = { path = "../../protocol/ente-card" }
ente-bus = { path = "../../runtime/ente-bus" }
serde = { workspace = true }
serde_json = { workspace = true }
ulid = { workspace = true }
anyhow = { workspace = true }
tokio = { workspace = true }
tracing = { workspace = true }
tracing-subscriber = { workspace = true }
+228
View File
@@ -0,0 +1,228 @@
//! ente-timer-compat: scheduler estilo cron + systemd .timer.
//!
//! Lee config en JSON desde `/etc/ente/timers.json` (override env
//! `ENTE_TIMERS_FILE`):
//!
//! ```json
//! [
//! {
//! "name": "daily-cleanup",
//! "schedule": "0 4 * * *",
//! "card": {
//! "id": "01KQ_TIMER_CLEANUP_0000000",
//! "label": "daily-cleanup-job",
//! "schema_version": 1,
//! "soma": {"namespaces": {}, "rlimits": {}, "cgroup": {"path": ""}},
//! "payload": {"Native": {"exec": "/usr/local/bin/cleanup", "argv": [], "envp": []}},
//! "supervision": "OneShot",
//! "provides": [], "requires": []
//! }
//! }
//! ]
//! ```
//!
//! Schedule: cron 5-fields `min hour dom mon dow` (DOM/DOW como en cron
//! tradicional). `*` y `*/N` soportados, listas no.
//!
//! Cuando un timer dispara, se envía un `BusRequest::Invoke` al bus interno
//! con la cap "TimerFire" + payload = serialized Card. Un Ente que provea
//! esa cap (futuro: ente-zero internamente) hace el spawn.
//!
//! Para el demo: log "FIRE" cada vez que el schedule matchea, sin spawn real
//! (requiere mover SpawnRequest al protocolo del bus, fuera de scope).
use ente_bus::{BusClient, BusRequest, BusResponse};
use ente_card::Capability;
use serde::Deserialize;
use std::time::{SystemTime, UNIX_EPOCH};
use tokio::signal::unix::{signal, SignalKind};
use tracing::{info, warn};
use tracing_subscriber::EnvFilter;
#[derive(Debug, Clone, Deserialize)]
struct TimerConfig {
name: String,
/// Cron 5-field: `min hour dom mon dow`. `*`, `N`, `*/N` soportados.
schedule: String,
/// Card a disparar. Por ahora se loguea — futuro: SpawnRequest via bus.
#[serde(default)]
card: Option<serde_json::Value>,
}
#[derive(Debug)]
struct Cron {
min: CronField,
hour: CronField,
dom: CronField,
mon: CronField,
dow: CronField,
}
#[derive(Debug)]
enum CronField {
Any,
Exact(u32),
Step(u32), // */N
}
impl CronField {
fn parse(s: &str) -> Option<Self> {
if s == "*" { return Some(CronField::Any); }
if let Some(n) = s.strip_prefix("*/") {
return n.parse().ok().map(CronField::Step);
}
s.parse().ok().map(CronField::Exact)
}
fn matches(&self, v: u32) -> bool {
match self {
CronField::Any => true,
CronField::Exact(n) => *n == v,
CronField::Step(n) if *n > 0 => v % n == 0,
_ => false,
}
}
}
impl Cron {
fn parse(s: &str) -> Option<Self> {
let parts: Vec<&str> = s.split_whitespace().collect();
if parts.len() != 5 { return None; }
Some(Self {
min: CronField::parse(parts[0])?,
hour: CronField::parse(parts[1])?,
dom: CronField::parse(parts[2])?,
mon: CronField::parse(parts[3])?,
dow: CronField::parse(parts[4])?,
})
}
fn matches(&self, t: &TimeBits) -> bool {
self.min.matches(t.min)
&& self.hour.matches(t.hour)
&& self.dom.matches(t.dom)
&& self.mon.matches(t.mon)
&& self.dow.matches(t.dow)
}
}
#[derive(Debug)]
struct TimeBits {
min: u32, hour: u32, dom: u32, mon: u32, dow: u32,
}
/// Decompose epoch_secs en componentes UTC. Algoritmo simple (Howard Hinnant).
fn time_bits_utc(epoch_secs: i64) -> TimeBits {
let secs_per_day = 86400i64;
let days_since_epoch = epoch_secs.div_euclid(secs_per_day);
let secs_in_day = epoch_secs.rem_euclid(secs_per_day);
let hour = (secs_in_day / 3600) as u32;
let min = ((secs_in_day % 3600) / 60) as u32;
// dow: 1970-01-01 fue jueves (4); cron usa 0-6 con 0=domingo.
let dow = ((days_since_epoch + 4).rem_euclid(7)) as u32;
// Conversión a y/m/d (Howard Hinnant Civil from days).
let z = days_since_epoch + 719_468;
let era = z.div_euclid(146_097);
let doe = (z - era * 146_097) as u64;
let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
let y = yoe as i64 + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
let m = (if mp < 10 { mp + 3 } else { mp - 9 }) as u32;
let _y = y + if m <= 2 { 1 } else { 0 };
TimeBits { min, hour, dom: d, mon: m, dow }
}
#[tokio::main(flavor = "current_thread")]
async fn main() -> anyhow::Result<()> {
init_tracing();
info!("ente-timer-compat: arrancando");
announce_to_fractal().await;
let timers = load_timers();
info!(count = timers.len(), "timers cargados");
for t in &timers {
info!(name = %t.name, schedule = %t.schedule, "timer activo");
}
let parsed: Vec<(TimerConfig, Cron)> = timers.into_iter()
.filter_map(|t| {
let cron = Cron::parse(&t.schedule)?;
Some((t, cron))
})
.collect();
let mut term = signal(SignalKind::terminate())?;
let mut int_ = signal(SignalKind::interrupt())?;
let mut tick = tokio::time::interval(std::time::Duration::from_secs(60));
// Alinear al próximo minuto entero.
let now_ms = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_millis() as u64;
let to_next_min = 60_000 - (now_ms % 60_000);
tokio::time::sleep(std::time::Duration::from_millis(to_next_min)).await;
tick.tick().await; // descartar primer tick post-alignment
info!("scheduler activo (cron 5-field UTC)");
loop {
tokio::select! {
_ = tick.tick() => {
let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs() as i64;
let bits = time_bits_utc(now);
for (cfg, cron) in &parsed {
if cron.matches(&bits) {
fire(cfg).await;
}
}
}
_ = term.recv() => { info!("SIGTERM"); return Ok(()); }
_ = int_.recv() => { info!("SIGINT"); return Ok(()); }
}
}
}
async fn fire(cfg: &TimerConfig) {
info!(name = %cfg.name, "TIMER FIRE");
if cfg.card.is_none() {
return;
}
// En el futuro: forwardear via bus a un proveedor que haga SpawnRequest.
// Por ahora log estructurado.
info!(name = %cfg.name, "card spawn requested (no-op por ahora)");
}
fn load_timers() -> Vec<TimerConfig> {
let path = std::env::var("ENTE_TIMERS_FILE")
.unwrap_or_else(|_| "/etc/ente/timers.json".into());
match std::fs::read_to_string(&path) {
Ok(content) => serde_json::from_str(&content).unwrap_or_else(|e| {
warn!(?e, path, "timers.json inválido — sin timers");
vec![]
}),
Err(_) => {
info!(path, "timers.json ausente — scheduler inactivo");
vec![]
}
}
}
async fn announce_to_fractal() {
if let Ok(mut client) = BusClient::from_env().await {
let req = BusRequest::Announce {
capabilities: vec![Capability::Endpoint {
interface: ente_card::InterfaceId([0xa8; 16]),
version: 1,
}],
};
match client.call(req).await {
Ok(BusResponse::Ok) => info!("Announce → bus interno OK"),
Ok(other) => warn!(?other, "Announce respuesta inesperada"),
Err(e) => warn!(?e, "Announce falló"),
}
}
}
fn init_tracing() {
let filter = EnvFilter::try_from_default_env()
.unwrap_or_else(|_| EnvFilter::new("ente_timer_compat=info"));
tracing_subscriber::fmt().with_env_filter(filter).with_target(true).init();
}
@@ -0,0 +1,17 @@
[package]
name = "ente-tmpfiles-compat"
version = "0.0.1"
edition.workspace = true
license.workspace = true
publish.workspace = true
[[bin]]
name = "ente-tmpfiles-compat"
path = "src/main.rs"
[dependencies]
nix = { workspace = true }
libc = { workspace = true }
anyhow = { workspace = true }
tracing = { workspace = true }
tracing-subscriber = { workspace = true }
@@ -0,0 +1,281 @@
//! ente-tmpfiles-compat: aplica directivas tmpfiles.d al boot.
//!
//! Lee, en orden, los conf files de:
//! /usr/lib/tmpfiles.d/*.conf
//! /etc/tmpfiles.d/*.conf (override del usuario, gana)
//! /run/tmpfiles.d/*.conf (efímero)
//!
//! Aplica un subset de directivas — las suficientes para el boot:
//! d — crear directorio (idempotente: no falla si existe)
//! D — crear directorio + limpiar contenido si existe
//! f — crear archivo (vacío, perms aplicados)
//! L — crear symlink (overrideable con `+L` si existe)
//! r — remove file (no falla si ausente)
//! R — remove recursivamente
//! e — adjust perms si existe
//!
//! Edad/cleanup (`age` field) y modos exotic (b, c, p, P) se ignoran.
//! El proceso es OneShot: corre, aplica, sale con código 0 / 1.
use std::collections::BTreeMap;
use std::fs;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use tracing::{debug, info, warn};
use tracing_subscriber::EnvFilter;
const SEARCH_DIRS: &[&str] = &[
"/usr/lib/tmpfiles.d",
"/etc/tmpfiles.d",
"/run/tmpfiles.d",
];
#[derive(Debug, Clone)]
struct Directive {
typ: char, // d, D, f, L, r, R, e
path: PathBuf,
mode: Option<u32>,
user: Option<String>,
group: Option<String>,
arg: Option<String>, // symlink target o content
}
fn main() {
init_tracing();
info!("ente-tmpfiles-compat: aplicando directivas tmpfiles.d");
let directives = collect_directives();
info!(count = directives.len(), "directivas a aplicar");
let mut applied = 0;
let mut skipped = 0;
let mut errors = 0;
for d in directives {
match apply(&d) {
Ok(true) => applied += 1,
Ok(false) => skipped += 1,
Err(e) => {
warn!(?e, ?d.typ, path = %d.path.display(), "directiva falló");
errors += 1;
}
}
}
info!(applied, skipped, errors, "tmpfiles aplicado");
if errors > 0 { std::process::exit(1); }
}
fn collect_directives() -> Vec<Directive> {
// Last-wins por path: /etc supera /usr/lib, /run supera /etc.
let mut by_path: BTreeMap<(PathBuf, char), Directive> = BTreeMap::new();
for dir in SEARCH_DIRS {
if !Path::new(dir).exists() { continue; }
let mut entries: Vec<_> = match fs::read_dir(dir) {
Ok(rd) => rd.filter_map(|e| e.ok()).collect(),
Err(_) => continue,
};
entries.sort_by_key(|e| e.file_name());
for entry in entries {
let path = entry.path();
if path.extension().map(|e| e != "conf").unwrap_or(true) { continue; }
match fs::read_to_string(&path) {
Ok(content) => {
for (line_no, line) in content.lines().enumerate() {
if let Some(d) = parse_line(line) {
by_path.insert((d.path.clone(), d.typ), d);
} else if !line.trim().is_empty() && !line.trim().starts_with('#') {
debug!(file = %path.display(), line_no, line, "no parseable, skip");
}
}
}
Err(e) => warn!(?e, path = %path.display(), "read"),
}
}
}
// Orden de aplicación: removes (r/R) primero, luego creates (d/D/f/L),
// adjusts (e) al final.
let mut all: Vec<Directive> = by_path.into_values().collect();
all.sort_by_key(|d| match d.typ {
'r' | 'R' => 0,
'd' | 'D' | 'f' | 'L' => 1,
'e' => 2,
_ => 3,
});
all
}
fn parse_line(line: &str) -> Option<Directive> {
let line = line.trim();
if line.is_empty() || line.starts_with('#') { return None; }
// Formato: TYPE PATH MODE USER GROUP AGE ARGUMENT
// Strip leading '+' (override marker) y '!' (boot-only) — los soportamos
// implícitamente.
let typ_str = line.chars().next()?;
let typ = match typ_str {
'+' | '!' => line.chars().nth(1)?,
c => c,
};
if !"dDfLrRe".contains(typ) { return None; }
// tokenize tomando en cuenta '-' como "default"
let mut parts = line.splitn(7, char::is_whitespace).filter(|s| !s.is_empty());
let _t = parts.next()?;
let path = parts.next()?.to_string();
let mode = parts.next().and_then(parse_mode);
let user = parts.next().and_then(parse_default);
let group = parts.next().and_then(parse_default);
let _age = parts.next();
let arg = parts.next().and_then(parse_default);
Some(Directive {
typ,
path: PathBuf::from(path),
mode, user, group, arg,
})
}
fn parse_default(s: &str) -> Option<String> {
if s == "-" { None } else { Some(s.to_string()) }
}
fn parse_mode(s: &str) -> Option<u32> {
if s == "-" { return None; }
u32::from_str_radix(s.trim_start_matches('~'), 8).ok()
}
fn apply(d: &Directive) -> anyhow::Result<bool> {
match d.typ {
'd' | 'D' => apply_d(d),
'f' => apply_f(d),
'L' => apply_l(d),
'r' => apply_r(d, false),
'R' => apply_r(d, true),
'e' => apply_e(d),
_ => Ok(false),
}
}
fn apply_d(d: &Directive) -> anyhow::Result<bool> {
fs::create_dir_all(&d.path)
.map_err(|e| anyhow::anyhow!("mkdir {}: {e}", d.path.display()))?;
if let Some(mode) = d.mode {
fs::set_permissions(&d.path, fs::Permissions::from_mode(mode))?;
}
chown(&d.path, d.user.as_deref(), d.group.as_deref())?;
if d.typ == 'D' {
// Limpiar contenido (no recursivo).
if let Ok(rd) = fs::read_dir(&d.path) {
for entry in rd.flatten() {
let p = entry.path();
if p.is_dir() { let _ = fs::remove_dir_all(&p); }
else { let _ = fs::remove_file(&p); }
}
}
}
info!(path = %d.path.display(), mode = ?d.mode, "d/D aplicado");
Ok(true)
}
fn apply_f(d: &Directive) -> anyhow::Result<bool> {
if !d.path.exists() {
if let Some(parent) = d.path.parent() {
let _ = fs::create_dir_all(parent);
}
let content = d.arg.clone().unwrap_or_default();
fs::write(&d.path, content.as_bytes())?;
}
if let Some(mode) = d.mode {
fs::set_permissions(&d.path, fs::Permissions::from_mode(mode))?;
}
chown(&d.path, d.user.as_deref(), d.group.as_deref())?;
info!(path = %d.path.display(), mode = ?d.mode, "f aplicado");
Ok(true)
}
fn apply_l(d: &Directive) -> anyhow::Result<bool> {
let target = match &d.arg {
Some(t) => t,
None => anyhow::bail!("L sin target en {}", d.path.display()),
};
if d.path.exists() {
// No sobreescribimos symlinks/files existentes (modo no-`+`).
debug!(path = %d.path.display(), "L: existe, skip");
return Ok(false);
}
if let Some(parent) = d.path.parent() {
let _ = fs::create_dir_all(parent);
}
std::os::unix::fs::symlink(target, &d.path)?;
info!(path = %d.path.display(), %target, "L aplicado");
Ok(true)
}
fn apply_r(d: &Directive, recursive: bool) -> anyhow::Result<bool> {
if !d.path.exists() {
return Ok(false);
}
if recursive {
fs::remove_dir_all(&d.path)?;
} else if d.path.is_dir() {
fs::remove_dir(&d.path)?;
} else {
fs::remove_file(&d.path)?;
}
info!(path = %d.path.display(), recursive, "remove aplicado");
Ok(true)
}
fn apply_e(d: &Directive) -> anyhow::Result<bool> {
if !d.path.exists() {
return Ok(false);
}
if let Some(mode) = d.mode {
fs::set_permissions(&d.path, fs::Permissions::from_mode(mode))?;
}
chown(&d.path, d.user.as_deref(), d.group.as_deref())?;
info!(path = %d.path.display(), "e aplicado");
Ok(true)
}
fn chown(path: &Path, user: Option<&str>, group: Option<&str>) -> anyhow::Result<()> {
use std::ffi::CString;
let uid = match user {
Some(u) => Some(lookup_uid(u)?),
None => None,
};
let gid = match group {
Some(g) => Some(lookup_gid(g)?),
None => None,
};
let (uid, gid) = (uid.unwrap_or(u32::MAX), gid.unwrap_or(u32::MAX));
let cstr = CString::new(path.as_os_str().as_encoded_bytes())?;
let r = unsafe { libc::chown(cstr.as_ptr(), uid, gid) };
if r != 0 {
let e = std::io::Error::last_os_error();
// No-op si ya somos non-root y el chown falla con EPERM.
if e.raw_os_error() == Some(libc::EPERM) {
debug!(path = %path.display(), "chown EPERM (esperado sin root)");
return Ok(());
}
return Err(anyhow::anyhow!("chown: {e}"));
}
Ok(())
}
fn lookup_uid(name: &str) -> anyhow::Result<u32> {
if let Ok(n) = name.parse::<u32>() { return Ok(n); }
let cstr = std::ffi::CString::new(name)?;
let pw = unsafe { libc::getpwnam(cstr.as_ptr()) };
if pw.is_null() { anyhow::bail!("user '{name}' no encontrado"); }
Ok(unsafe { (*pw).pw_uid })
}
fn lookup_gid(name: &str) -> anyhow::Result<u32> {
if let Ok(n) = name.parse::<u32>() { return Ok(n); }
let cstr = std::ffi::CString::new(name)?;
let gr = unsafe { libc::getgrnam(cstr.as_ptr()) };
if gr.is_null() { anyhow::bail!("group '{name}' no encontrado"); }
Ok(unsafe { (*gr).gr_gid })
}
fn init_tracing() {
let filter = EnvFilter::try_from_default_env()
.unwrap_or_else(|_| EnvFilter::new("ente_tmpfiles_compat=info"));
tracing_subscriber::fmt().with_env_filter(filter).with_target(true).init();
}