Implementa xexeu scanner (loop contínuo) e xexeu serve (API Axum + dashboard + ingestão automática de lotes)
This commit is contained in:
1 parent
a814e100fb
commit
b4d2c29d24
4 files changed
+1060
-26
No files matched your search
+599
-25
@@ -1,19 +1,29 @@
|
||||
use std::collections::{BTreeSet, HashSet};
|
||||
use std::collections::{BTreeMap, BTreeSet, HashSet};
|
||||
use std::fs;
|
||||
use std::net::IpAddr;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::ExitCode;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use chrono::Utc;
|
||||
use axum::extract::{Query, State};
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::Html;
|
||||
use axum::{Json, Router};
|
||||
use chrono::{DateTime, Utc};
|
||||
use clap::{Parser, Subcommand};
|
||||
use serde::Serialize;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tokio::sync::Mutex;
|
||||
use xexeu_core::batch::{EngineMode, SweepBatch, SweepManifest, SweepStatus};
|
||||
use xexeu_core::config::{ValidationReport, XexeuConfig};
|
||||
use xexeu_core::diff::{diff_batch, DiffOptions};
|
||||
use xexeu_core::scan::{
|
||||
discover_hosts_tcp, scan_hosts_tcp_connect, DiscoveryConfig, HostState, PortScanConfig,
|
||||
PortState, PortTarget, DEFAULT_DISCOVERY_PORTS,
|
||||
};
|
||||
use xexeu_core::schedule::{next_runs, should_run_now, RunDecision, RunHistory};
|
||||
use xexeu_core::storage::{SqliteStorage, Storage};
|
||||
use xexeu_core::targets::{
|
||||
effective_cadence, expand_group, filter_in_scope, resolve_name, scope_ranges, IpRange,
|
||||
};
|
||||
@@ -130,14 +140,25 @@ async fn main() -> ExitCode {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(message) => fail(&message),
|
||||
},
|
||||
Command::Scanner { config, out } => match run_scanner(&config, &out).await {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(message) => fail(&message),
|
||||
},
|
||||
Command::Serve {
|
||||
bind,
|
||||
config,
|
||||
sweeps,
|
||||
data_dir,
|
||||
} => match run_serve(&bind, &config, &sweeps, &data_dir).await {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(message) => fail(&message),
|
||||
},
|
||||
Command::Changes { since, data_dir } => run_changes(&since, &data_dir),
|
||||
Command::Config { action } => match action {
|
||||
ConfigAction::Check { config } => run_config_check(&config),
|
||||
},
|
||||
Command::Doctor { json } => run_doctor(json),
|
||||
Command::Serve { .. } => not_implemented("serve"),
|
||||
Command::Scanner { .. } => not_implemented("scanner"),
|
||||
Command::Feeds { .. } => not_implemented("feeds"),
|
||||
Command::Changes { .. } => not_implemented("changes"),
|
||||
Command::Export { .. } => not_implemented("export"),
|
||||
}
|
||||
}
|
||||
@@ -250,21 +271,23 @@ fn ip_value(address: IpAddr) -> u128 {
|
||||
}
|
||||
}
|
||||
|
||||
async fn scan_once(
|
||||
group: Option<String>,
|
||||
once: bool,
|
||||
config_path: &Path,
|
||||
struct ScanSummary {
|
||||
batch: SweepBatch,
|
||||
directory: PathBuf,
|
||||
targets_count: usize,
|
||||
alive_count: usize,
|
||||
}
|
||||
|
||||
async fn execute_scan_for_group(
|
||||
config: &XexeuConfig,
|
||||
group_name: &str,
|
||||
out: &Path,
|
||||
) -> Result<(), String> {
|
||||
if !once {
|
||||
return Err("varredura contínua pertence ao comando scanner; use --once".to_string());
|
||||
}
|
||||
let name = group.ok_or_else(|| "informe o grupo com --group".to_string())?;
|
||||
let (config, _report) = validated_config(config_path)?;
|
||||
) -> Result<ScanSummary, String> {
|
||||
let group = config
|
||||
.group(&name)
|
||||
.ok_or_else(|| format!("grupo '{name}' não existe na configuração"))?;
|
||||
let expansion = expand_group(group).map_err(|error| format!("grupo '{name}': {error}"))?;
|
||||
.group(group_name)
|
||||
.ok_or_else(|| format!("grupo '{group_name}' não existe na configuração"))?;
|
||||
let expansion =
|
||||
expand_group(group).map_err(|error| format!("grupo '{group_name}': {error}"))?;
|
||||
let scope =
|
||||
scope_ranges(&config.scope.authorized).map_err(|error| format!("escopo: {error}"))?;
|
||||
|
||||
@@ -293,11 +316,12 @@ async fn scan_once(
|
||||
return Err("nenhum alvo dentro do escopo autorizado".to_string());
|
||||
}
|
||||
|
||||
let profile_name = group.effective_profile(&config);
|
||||
let profile_name = group.effective_profile(config);
|
||||
let profile = config
|
||||
.profiles
|
||||
.get(profile_name)
|
||||
.ok_or_else(|| format!("perfil '{profile_name}' não definido"))?;
|
||||
|
||||
if profile.engine != "nativo" && profile.engine != "nativo-sem-raw" {
|
||||
return Err(format!(
|
||||
"motor '{}' do perfil '{profile_name}' não implementado; use nativo",
|
||||
@@ -359,15 +383,40 @@ async fn scan_once(
|
||||
.write(out)
|
||||
.map_err(|error| format!("falha ao gravar o lote: {error}"))?;
|
||||
|
||||
Ok(ScanSummary {
|
||||
targets_count: targets.len(),
|
||||
alive_count: alive.len(),
|
||||
batch,
|
||||
directory,
|
||||
})
|
||||
}
|
||||
|
||||
async fn scan_once(
|
||||
group: Option<String>,
|
||||
once: bool,
|
||||
config_path: &Path,
|
||||
out: &Path,
|
||||
) -> Result<(), String> {
|
||||
if !once {
|
||||
return Err("varredura contínua pertence ao comando scanner; use --once".to_string());
|
||||
}
|
||||
let name = group.ok_or_else(|| "informe o grupo com --group".to_string())?;
|
||||
let (config, _report) = validated_config(config_path)?;
|
||||
let summary = execute_scan_for_group(&config, &name, out).await?;
|
||||
|
||||
let profile_name = summary.batch.manifest.profile.as_str();
|
||||
println!(
|
||||
"lote {} (grupo {}, perfil {}) gravado em {}",
|
||||
batch.manifest.sweep_id,
|
||||
group.name,
|
||||
summary.batch.manifest.sweep_id,
|
||||
name,
|
||||
profile_name,
|
||||
directory.display()
|
||||
summary.directory.display()
|
||||
);
|
||||
println!("alvos: {}; vivos: {}", targets.len(), alive.len());
|
||||
for result in &batch.ports {
|
||||
println!(
|
||||
"alvos: {}; vivos: {}",
|
||||
summary.targets_count, summary.alive_count
|
||||
);
|
||||
for result in &summary.batch.ports {
|
||||
let open: Vec<String> = result
|
||||
.ports
|
||||
.iter()
|
||||
@@ -382,6 +431,531 @@ async fn scan_once(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn run_scanner(config_path: &Path, out_dir: &Path) -> Result<(), String> {
|
||||
let (config, _report) = validated_config(config_path)?;
|
||||
fs::create_dir_all(out_dir)
|
||||
.map_err(|error| format!("falha ao criar {}: {error}", out_dir.display()))?;
|
||||
|
||||
let mut histories: BTreeMap<String, RunHistory> = BTreeMap::new();
|
||||
for group in &config.groups {
|
||||
histories.insert(group.name.clone(), RunHistory::default());
|
||||
}
|
||||
|
||||
println!(
|
||||
"scanner contínuo iniciado com {} grupo(s) configurado(s)",
|
||||
config.groups.len()
|
||||
);
|
||||
|
||||
let tick_interval = std::env::var("XEXEU_SCANNER_TICK_SECS")
|
||||
.ok()
|
||||
.and_then(|val| val.parse().ok())
|
||||
.map(Duration::from_secs)
|
||||
.unwrap_or(Duration::from_secs(10));
|
||||
|
||||
loop {
|
||||
let now = Utc::now();
|
||||
for group in &config.groups {
|
||||
let history = histories.entry(group.name.clone()).or_default();
|
||||
|
||||
match should_run_now(group, &config, now, history) {
|
||||
Ok(RunDecision::Run) => {
|
||||
history.running = true;
|
||||
history.last_started = Some(now);
|
||||
|
||||
match execute_scan_for_group(&config, &group.name, out_dir).await {
|
||||
Ok(summary) => {
|
||||
history.running = false;
|
||||
history.last_finished = Some(Utc::now());
|
||||
let open_count = summary
|
||||
.batch
|
||||
.ports
|
||||
.iter()
|
||||
.flat_map(|r| &r.ports)
|
||||
.filter(|p| p.state == PortState::Open)
|
||||
.count();
|
||||
println!(
|
||||
"[{}] grupo {}: {} alvo(s), {} vivo(s), {} porta(s) aberta(s) (lote {})",
|
||||
Utc::now().to_rfc3339(),
|
||||
group.name,
|
||||
summary.targets_count,
|
||||
summary.alive_count,
|
||||
open_count,
|
||||
summary.batch.manifest.sweep_id
|
||||
);
|
||||
}
|
||||
Err(error) => {
|
||||
history.running = false;
|
||||
eprintln!("erro na varredura do grupo {}: {error}", group.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(RunDecision::Deferred { .. }) => {
|
||||
eprintln!(
|
||||
"aviso: execução do grupo {} adiada (anterior ainda em andamento)",
|
||||
group.name
|
||||
);
|
||||
}
|
||||
Ok(RunDecision::Wait { .. }) => {}
|
||||
Err(error) => {
|
||||
eprintln!("erro no agendador para o grupo {}: {error}", group.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tokio::select! {
|
||||
_ = shutdown_signal() => {
|
||||
println!("scanner encerrado graciosamente");
|
||||
break;
|
||||
}
|
||||
_ = tokio::time::sleep(tick_interval) => {}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn find_sweep_manifests(sweeps_dir: &Path) -> Vec<PathBuf> {
|
||||
let mut manifests = Vec::new();
|
||||
let group_entries = match fs::read_dir(sweeps_dir) {
|
||||
Ok(entries) => entries,
|
||||
Err(_) => return manifests,
|
||||
};
|
||||
for group_entry in group_entries.flatten() {
|
||||
if !group_entry.path().is_dir() {
|
||||
continue;
|
||||
}
|
||||
let sweep_entries = match fs::read_dir(group_entry.path()) {
|
||||
Ok(entries) => entries,
|
||||
Err(_) => continue,
|
||||
};
|
||||
for sweep_entry in sweep_entries.flatten() {
|
||||
let sweep_path = sweep_entry.path();
|
||||
if sweep_path.is_dir() && sweep_path.join("manifest.json").exists() {
|
||||
manifests.push(sweep_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Lexicographical sorting by ULID directory name orders sweeps chronologically.
|
||||
manifests.sort();
|
||||
manifests
|
||||
}
|
||||
|
||||
async fn poll_sweeps(
|
||||
sweeps_dir: PathBuf,
|
||||
storage: Arc<Mutex<SqliteStorage>>,
|
||||
sweeps_ingested: Arc<AtomicUsize>,
|
||||
) {
|
||||
loop {
|
||||
let manifests = find_sweep_manifests(&sweeps_dir);
|
||||
for sweep_path in manifests {
|
||||
match SweepBatch::read(&sweep_path) {
|
||||
Ok(batch) => {
|
||||
let mut storage_guard = storage.lock().await;
|
||||
match storage_guard.load_state(&[]) {
|
||||
Ok(current_state) => {
|
||||
match diff_batch(¤t_state, &batch, &DiffOptions::default()) {
|
||||
Ok(diff) => match storage_guard.ingest(&batch, &diff) {
|
||||
Ok(true) => {
|
||||
sweeps_ingested.fetch_add(1, Ordering::SeqCst);
|
||||
println!(
|
||||
"lote {} (grupo {}) ingerido com sucesso ({} eventos)",
|
||||
batch.manifest.sweep_id,
|
||||
batch.manifest.group,
|
||||
diff.events.len()
|
||||
);
|
||||
}
|
||||
Ok(false) => {
|
||||
// Sweep already recorded.
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!(
|
||||
"aviso: falha ao ingerir lote {}: {err}",
|
||||
sweep_path.display()
|
||||
);
|
||||
}
|
||||
},
|
||||
Err(err) => {
|
||||
eprintln!(
|
||||
"aviso: falha ao calcular diff de {}: {err}",
|
||||
sweep_path.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("aviso: falha ao carregar estado do banco: {err}");
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!(
|
||||
"aviso: falha ao ler lote em {}: {err}",
|
||||
sweep_path.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(1500)).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct ServerState {
|
||||
config: Arc<XexeuConfig>,
|
||||
config_path: PathBuf,
|
||||
storage: Arc<Mutex<SqliteStorage>>,
|
||||
sweeps_ingested: Arc<AtomicUsize>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct HealthResponse {
|
||||
status: &'static str,
|
||||
version: &'static str,
|
||||
}
|
||||
|
||||
async fn health_handler() -> Json<HealthResponse> {
|
||||
Json(HealthResponse {
|
||||
status: "ok",
|
||||
version: env!("CARGO_PKG_VERSION"),
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct StatusResponse {
|
||||
status: &'static str,
|
||||
version: &'static str,
|
||||
config_path: String,
|
||||
sweeps_ingested: usize,
|
||||
groups: Vec<GroupScheduleDto>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct GroupScheduleDto {
|
||||
group: String,
|
||||
profile: String,
|
||||
cron: String,
|
||||
next_run: String,
|
||||
}
|
||||
|
||||
async fn status_handler(State(state): State<ServerState>) -> Json<StatusResponse> {
|
||||
let now = Utc::now();
|
||||
let schedules = next_runs(&state.config, now).unwrap_or_default();
|
||||
let groups = state
|
||||
.config
|
||||
.groups
|
||||
.iter()
|
||||
.map(|group| {
|
||||
let next_run = schedules
|
||||
.iter()
|
||||
.find(|s| s.group == group.name)
|
||||
.map(|s| s.next_run.to_rfc3339())
|
||||
.unwrap_or_default();
|
||||
GroupScheduleDto {
|
||||
group: group.name.clone(),
|
||||
profile: group.effective_profile(&state.config).to_string(),
|
||||
cron: group.effective_cron(&state.config).to_string(),
|
||||
next_run,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
Json(StatusResponse {
|
||||
status: "ok",
|
||||
version: env!("CARGO_PKG_VERSION"),
|
||||
config_path: state.config_path.display().to_string(),
|
||||
sweeps_ingested: state.sweeps_ingested.load(Ordering::SeqCst),
|
||||
groups,
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct HostDto {
|
||||
asset_key: String,
|
||||
network: String,
|
||||
ip: String,
|
||||
status: &'static str,
|
||||
absences: u32,
|
||||
first_seen: String,
|
||||
last_seen: String,
|
||||
ports: Vec<PortDto>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct PortDto {
|
||||
protocol: String,
|
||||
port: u16,
|
||||
status: &'static str,
|
||||
absences: u32,
|
||||
first_seen: String,
|
||||
last_seen: String,
|
||||
product: Option<String>,
|
||||
version: Option<String>,
|
||||
cpe: Option<String>,
|
||||
}
|
||||
|
||||
async fn hosts_handler(
|
||||
State(state): State<ServerState>,
|
||||
) -> Result<Json<Vec<HostDto>>, (StatusCode, String)> {
|
||||
let storage = state.storage.lock().await;
|
||||
let current_state = storage.load_state(&[]).map_err(|error| {
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("erro ao consultar estado: {error}"),
|
||||
)
|
||||
})?;
|
||||
|
||||
let dtos = current_state
|
||||
.assets
|
||||
.into_iter()
|
||||
.map(|asset| HostDto {
|
||||
asset_key: asset.asset_key,
|
||||
network: asset.network,
|
||||
ip: asset.ip.to_string(),
|
||||
status: asset.status.as_str(),
|
||||
absences: asset.absences,
|
||||
first_seen: asset.first_seen.to_rfc3339(),
|
||||
last_seen: asset.last_seen.to_rfc3339(),
|
||||
ports: asset
|
||||
.ports
|
||||
.into_iter()
|
||||
.map(|port| PortDto {
|
||||
protocol: port.protocol,
|
||||
port: port.port,
|
||||
status: port.status.as_str(),
|
||||
absences: port.absences,
|
||||
first_seen: port.first_seen.to_rfc3339(),
|
||||
last_seen: port.last_seen.to_rfc3339(),
|
||||
product: port.product,
|
||||
version: port.version,
|
||||
cpe: port.cpe,
|
||||
})
|
||||
.collect(),
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ok(Json(dtos))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct ChangesQuery {
|
||||
since: Option<String>,
|
||||
}
|
||||
|
||||
fn parse_since(raw: &str) -> Option<DateTime<Utc>> {
|
||||
let raw = raw.trim();
|
||||
if raw.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if raw.len() > 1 {
|
||||
let (num_str, unit) = raw.split_at(raw.len() - 1);
|
||||
if let Ok(number) = num_str.parse::<i64>() {
|
||||
let duration = match unit {
|
||||
"s" => Some(chrono::Duration::seconds(number)),
|
||||
"m" => Some(chrono::Duration::minutes(number)),
|
||||
"h" => Some(chrono::Duration::hours(number)),
|
||||
"d" => Some(chrono::Duration::days(number)),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(dur) = duration {
|
||||
return Some(Utc::now() - dur);
|
||||
}
|
||||
}
|
||||
}
|
||||
DateTime::parse_from_rfc3339(raw)
|
||||
.ok()
|
||||
.map(|date_time| date_time.with_timezone(&Utc))
|
||||
}
|
||||
|
||||
async fn changes_handler(
|
||||
State(state): State<ServerState>,
|
||||
Query(query): Query<ChangesQuery>,
|
||||
) -> Result<Json<Vec<xexeu_core::diff::Event>>, (StatusCode, String)> {
|
||||
let since = query.since.as_deref().and_then(parse_since);
|
||||
let storage = state.storage.lock().await;
|
||||
let events = storage.events(since).map_err(|error| {
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("erro ao consultar eventos: {error}"),
|
||||
)
|
||||
})?;
|
||||
Ok(Json(events))
|
||||
}
|
||||
|
||||
async fn dashboard_handler() -> Html<&'static str> {
|
||||
const HTML: &str = r#"<!DOCTYPE html>
|
||||
<html lang="pt-BR">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Xexéu — Painel de Auditoria Contínua</title>
|
||||
<style>
|
||||
body { font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; background: #0f172a; color: #f8fafc; margin: 0; padding: 28px; }
|
||||
h1 { font-size: 1.6rem; margin-bottom: 6px; color: #38bdf8; }
|
||||
.subtitle { color: #94a3b8; font-size: 0.95rem; margin-bottom: 24px; }
|
||||
.card { background: #1e293b; border: 1px solid #334155; border-radius: 8px; padding: 18px; margin-bottom: 20px; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1); }
|
||||
.badge { display: inline-block; padding: 3px 8px; border-radius: 4px; font-size: 0.8rem; font-weight: 600; }
|
||||
.badge-active { background: #065f46; color: #34d399; }
|
||||
.badge-open { background: #0284c7; color: #bae6fd; margin-right: 4px; font-family: monospace; }
|
||||
table { width: 100%; border-collapse: collapse; margin-top: 14px; }
|
||||
th, td { text-align: left; padding: 12px; border-bottom: 1px solid #334155; font-size: 0.9rem; }
|
||||
th { color: #94a3b8; font-weight: 600; text-transform: uppercase; font-size: 0.75rem; letter-spacing: 0.05em; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Xexéu</h1>
|
||||
<div class="subtitle">Auditoria contínua de superfície de ataque e identificação de vulnerabilidades</div>
|
||||
<div id="status-card" class="card"><strong>Carregando status...</strong></div>
|
||||
<div class="card">
|
||||
<h2 style="font-size: 1.15rem; margin-top: 0; margin-bottom: 12px;">Ativos e Superfície Descoberta</h2>
|
||||
<div id="hosts-container">Carregando ativos...</div>
|
||||
</div>
|
||||
<script>
|
||||
async function loadData() {
|
||||
try {
|
||||
const sRes = await fetch('/api/status');
|
||||
const status = await sRes.json();
|
||||
document.getElementById('status-card').innerHTML = `
|
||||
<div><strong>Versão:</strong> ${status.version} | <strong>Lotes Ingeridos:</strong> ${status.sweeps_ingested}</div>
|
||||
<div style="margin-top: 6px; font-size: 0.85rem; color: #94a3b8;">Configuração: <code>${status.config_path}</code></div>
|
||||
`;
|
||||
const hRes = await fetch('/api/hosts');
|
||||
const hosts = await hRes.json();
|
||||
if (hosts.length === 0) {
|
||||
document.getElementById('hosts-container').innerHTML = '<p style="color: #94a3b8; margin: 0;">Nenhum ativo ingerido ainda.</p>';
|
||||
return;
|
||||
}
|
||||
let html = '<table><thead><tr><th>IP</th><th>Grupo</th><th>Status</th><th>Portas Abertas</th><th>Visto em</th></tr></thead><tbody>';
|
||||
for (const h of hosts) {
|
||||
const ports = h.ports.filter(p => p.status === 'aberta').map(p => `<span class="badge badge-open">${p.protocol}/${p.port}</span>`).join(' ') || '—';
|
||||
html += `<tr><td><strong>${h.ip}</strong></td><td>${h.network}</td><td><span class="badge badge-active">${h.status}</span></td><td>${ports}</td><td>${h.last_seen}</td></tr>`;
|
||||
}
|
||||
html += '</tbody></table>';
|
||||
document.getElementById('hosts-container').innerHTML = html;
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
loadData();
|
||||
setInterval(loadData, 5000);
|
||||
</script>
|
||||
</body>
|
||||
</html>"#;
|
||||
Html(HTML)
|
||||
}
|
||||
|
||||
async fn run_serve(
|
||||
bind: &str,
|
||||
config_path: &Path,
|
||||
sweeps_dir: &Path,
|
||||
data_dir: &Path,
|
||||
) -> Result<(), String> {
|
||||
let (config, _report) = validated_config(config_path)?;
|
||||
fs::create_dir_all(sweeps_dir)
|
||||
.map_err(|error| format!("falha ao criar {}: {error}", sweeps_dir.display()))?;
|
||||
fs::create_dir_all(data_dir)
|
||||
.map_err(|error| format!("falha ao criar {}: {error}", data_dir.display()))?;
|
||||
|
||||
let db_path = data_dir.join("xexeu.db");
|
||||
let storage = SqliteStorage::open(&db_path).map_err(|error| {
|
||||
format!(
|
||||
"falha ao abrir banco de dados em {}: {error}",
|
||||
db_path.display()
|
||||
)
|
||||
})?;
|
||||
|
||||
let shared_storage = Arc::new(Mutex::new(storage));
|
||||
let sweeps_ingested = Arc::new(AtomicUsize::new(0));
|
||||
|
||||
// Spawn background poller for incoming sweeps.
|
||||
let poller_storage = Arc::clone(&shared_storage);
|
||||
let poller_ingested = Arc::clone(&sweeps_ingested);
|
||||
let poller_sweeps = sweeps_dir.to_path_buf();
|
||||
tokio::spawn(async move {
|
||||
poll_sweeps(poller_sweeps, poller_storage, poller_ingested).await;
|
||||
});
|
||||
|
||||
let state = ServerState {
|
||||
config: Arc::new(config),
|
||||
config_path: config_path.to_path_buf(),
|
||||
storage: shared_storage,
|
||||
sweeps_ingested,
|
||||
};
|
||||
|
||||
let app = Router::new()
|
||||
.route("/api/health", axum::routing::get(health_handler))
|
||||
.route("/api/status", axum::routing::get(status_handler))
|
||||
.route("/api/hosts", axum::routing::get(hosts_handler))
|
||||
.route("/api/changes", axum::routing::get(changes_handler))
|
||||
.route("/", axum::routing::get(dashboard_handler))
|
||||
.route("/dashboard", axum::routing::get(dashboard_handler))
|
||||
.with_state(state);
|
||||
|
||||
let listener = tokio::net::TcpListener::bind(bind)
|
||||
.await
|
||||
.map_err(|error| format!("falha ao vincular endereço {bind}: {error}"))?;
|
||||
|
||||
let local_addr = listener
|
||||
.local_addr()
|
||||
.map_err(|error| format!("falha ao obter endereço local: {error}"))?;
|
||||
|
||||
println!("Xexéu listening on http://{local_addr}");
|
||||
|
||||
axum::serve(listener, app)
|
||||
.with_graceful_shutdown(shutdown_signal())
|
||||
.await
|
||||
.map_err(|error| format!("erro no servidor HTTP: {error}"))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn run_changes(since: &str, data_dir: &Path) -> ExitCode {
|
||||
let db_path = data_dir.join("xexeu.db");
|
||||
if !db_path.exists() {
|
||||
return fail(&format!(
|
||||
"banco de dados não encontrado em {}",
|
||||
db_path.display()
|
||||
));
|
||||
}
|
||||
let storage = match SqliteStorage::open(&db_path) {
|
||||
Ok(s) => s,
|
||||
Err(e) => return fail(&format!("falha ao abrir banco: {e}")),
|
||||
};
|
||||
let since_dt = parse_since(since);
|
||||
match storage.events(since_dt) {
|
||||
Ok(events) => match serde_json::to_string_pretty(&events) {
|
||||
Ok(json) => {
|
||||
println!("{json}");
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(e) => fail(&format!("falha ao serializar eventos: {e}")),
|
||||
},
|
||||
Err(e) => fail(&format!("falha ao consultar eventos: {e}")),
|
||||
}
|
||||
}
|
||||
|
||||
async fn shutdown_signal() {
|
||||
let ctrl_c = async {
|
||||
tokio::signal::ctrl_c()
|
||||
.await
|
||||
.expect("falha ao registrar listener de Ctrl+C");
|
||||
};
|
||||
|
||||
#[cfg(unix)]
|
||||
let terminate = async {
|
||||
match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
|
||||
Ok(mut signal) => signal.recv().await,
|
||||
Err(_) => std::future::pending::<Option<()>>().await,
|
||||
};
|
||||
};
|
||||
|
||||
#[cfg(not(unix))]
|
||||
let terminate = std::future::pending::<()>();
|
||||
|
||||
tokio::select! {
|
||||
_ = ctrl_c => {},
|
||||
_ = terminate => {},
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct DoctorReport {
|
||||
version: &'static str,
|
||||
|
||||
Reference in new issue
Block a user