# Écriture JSON en shell POSIX, commune aux collecteurs Linux et macOS. # Inclus à la construction (construire.sh). Compatible sh de Mac OS X 10.4 (bash 2.05b), dash, busybox. _D=0 _F0=1 _SAUTES='' # Remplace le nom d'utilisateur et le nom de machine dans chaque texte. _anon_prepare() { _ANON_U=''; _ANON_H=''; _ANON_HS='' _u=$(id -un 2>/dev/null) [ -n "$_u" ] || _u=${USER:-} [ ${#_u} -ge 3 ] && _ANON_U=$_u _h=$(hostname 2>/dev/null) [ ${#_h} -ge 3 ] && _ANON_H=$_h _hs=${_h%%.*} [ ${#_hs} -ge 3 ] && [ "$_hs" != "$_h" ] && _ANON_HS=$_hs # Noms génériques (images de systèmes, comptes par défaut) : les remplacer effacerait des données utiles. _gen=' root admin administrator user nobody guest test ubuntu debian fedora centos rhel alpine arch archlinux manjaro opensuse suse linux localhost raspberrypi pi mac macbook imac apple windows ' case "$_gen" in *" $(printf '%s' "$_ANON_U" | tr 'A-Z' 'a-z') "*) _ANON_U='' ;; esac case "$_gen" in *" $(printf '%s' "$_ANON_H" | tr 'A-Z' 'a-z') "*) _ANON_H='' ;; esac case "$_gen" in *" $(printf '%s' "$_ANON_HS" | tr 'A-Z' 'a-z') "*) _ANON_HS='' ;; esac } _esc() { printf '%s' "$1" | tr -d '\000-\010\013-\037' | awk -v u="$_ANON_U" -v h="$_ANON_H" -v hs="$_ANON_HS" ' function rep(s, a, b, i, o) { if (a == "") return s o = "" while ((i = index(s, a)) > 0) { o = o substr(s, 1, i - 1) b; s = substr(s, i + length(a)) } return o s } function repi(s, a, b, i, o, la) { if (a == "") return s o = ""; la = tolower(a) while ((i = index(tolower(s), la)) > 0) { o = o substr(s, 1, i - 1) b; s = substr(s, i + length(a)) } return o s } { l = rep($0, "\\", "\\\\"); l = rep(l, "\"", "\\\""); gsub(/\t/, "\\t", l) l = repi(l, h, ""); l = repi(l, hs, ""); l = repi(l, u, "") if (NR > 1) printf "\\n" printf "%s", l }' } _jsep() { eval "_f=\$_F$_D" if [ "$_f" = 1 ]; then eval "_F$_D=0"; else printf ',' >&3; fi } _jkey() { _jsep; [ -n "$1" ] && printf '"%s":' "$1" >&3; return 0; } jo() { _jkey "$1"; printf '{' >&3; _D=$((_D + 1)); eval "_F$_D=1"; } jc() { printf '}' >&3; _D=$((_D - 1)); } ja() { _jkey "$1"; printf '[' >&3; _D=$((_D + 1)); eval "_F$_D=1"; } jac() { printf ']' >&3; _D=$((_D - 1)); } # Texte ; vide = null. js() { _jkey "$1" if [ -z "$2" ]; then printf 'null' >&3; else printf '"%s"' "$(_esc "$2")" >&3; fi } # Texte obligatoire (jamais null). jsr() { _jkey "$1"; printf '"%s"' "$(_esc "$2")" >&3; } # Nombre ; sinon null. jn() { _jkey "$1" printf '%s' "$(printf '%s\n' "$2" | awk 'NR==1 { if ($0 ~ /^-?[0-9]+(\.[0-9]+)?$/) print $0 + 0; else print "null"; exit } END { if (NR == 0) print "null" }')" >&3 } # Booléen : 1/oui/true/yes/on -> true ; 0/non/false/no/off -> false ; sinon null. jb() { _jkey "$1" case "$2" in 1|oui|true|yes|on|TRUE|Yes|YES) printf 'true' >&3 ;; 0|non|false|no|off|FALSE|No|NO) printf 'false' >&3 ;; *) printf 'null' >&3 ;; esac } # Valeur brute déjà en JSON (constante écrite par le collecteur). jraw() { _jkey "$1"; printf '%s' "$2" >&3; } # Élément texte d'un tableau. jsv() { js '' "$1"; } # Section : ouverture, éléments sautés, fermeture avec statut. sec() { jo "$1"; _SAUTES=''; } saute() { _SAUTES="$_SAUTES$1|$2 "; } fin() { if [ -n "$_SAUTES" ]; then ja sautes printf '%s' "$_SAUTES" | while IFS='|' read -r _e _r; do [ -n "$_e" ] || continue _jsep; printf '{"element":"%s","raison":"%s"}' "$(_esc "$_e")" "$_r" >&3 done # Le sous-shell de la boucle ne remonte pas le drapeau : on le pose ici. eval "_F$_D=0" jac fi _s=$1 jsr statut "$_s" if [ -n "$2" ]; then jsr note "$2" elif [ "$_s" = non_disponible ]; then jsr note "non disponible sur ce système"; fi jc _SAUTES='' } # Outils. _a() { type "$1" >/dev/null 2>&1; } # Délai maximal : timeout (Linux), perl alarm (macOS), sinon sans délai. _t() { if _a timeout; then timeout "$@" elif _a perl; then perl -e 'alarm shift; exec @ARGV or exit 127' "$@" else shift; "$@"; fi } _rf() { [ -r "$1" ] && head -n 1 "$1" 2>/dev/null; return 0; } _div() { awk -v a="$1" -v b="$2" -v p="${3:-1}" 'BEGIN { if (a == "" || b == "" || b + 0 == 0) exit; printf "%." p "f\n", a / b }'; } _trim() { printf '%s' "$1" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//'; } # Préfixe constructeur d'une adresse MAC (3 premiers octets). _mac() { case "$1" in ??:??:??:??:??:??) printf '%s:xx:xx:xx' "$(printf '%s' "$1" | cut -c1-8 | tr 'ABCDEF' 'abcdef')" ;; *) printf '' ;; esac } # Date ISO depuis un temps Unix : GNU et busybox (-d @N), BSD et macOS (-r N). _iso() { [ -n "$1" ] || return 0 date -u -d "@$1" '+%Y-%m-%dT%H:%M:%SZ' 2>/dev/null || date -u -r "$1" '+%Y-%m-%dT%H:%M:%SZ' 2>/dev/null return 0 } # Signatures de défauts connus dans un journal (une ligne par message) : sortie clé=nombre. _J_SIG=' BEGIN { split("disque_es systeme_fichiers memoire_saturee erreur_materielle graphique_blocage thermique plantage_appli arret_inattendu usb reseau pilote", K, " ") } { l = tolower($0) if (l ~ /i\/o error|blk_update_request|medium error|critical medium|ata[0-9.]+: (failed|error)|nvme.*(timeout|controller is down|reset)|uncorrectable error/) c["disque_es"]++ if (l ~ /ext4-fs error|btrfs.*(error|corrupt)|xfs.*(corrupt|error)|fat-fs.*error|remounting filesystem read-only|fsck needed/) c["systeme_fichiers"]++ if (l ~ /out of memory|oom-kill|oom_reaper|invoked oom-killer/) c["memoire_saturee"]++ if (l ~ /mce:|machine check|hardware error|edac .*(ce|ue) |pcie bus error|aer:.*error/) c["erreur_materielle"]++ if (l ~ /gpu hang|ring [a-z0-9_.]+ timeout|nvrm: xid|gpu reset|gpu fault|amdgpu.*page fault|i915.*(hang|reset)/) c["graphique_blocage"]++ if (l ~ /temperature above threshold|clock throttled|critical temperature|thermal shutdown|overheat/) c["thermique"]++ if (l ~ /segfault at|general protection fault|dumped core|traps: /) c["plantage_appli"]++ if (l ~ /device descriptor read|unable to enumerate usb|over-current|cannot enable\. maybe the usb cable/) c["usb"]++ if (l ~ /transmit queue [0-9]+ timed out|tx timeout|firmware crash|deauthenticated|link is not ready/) c["reseau"]++ if (l ~ /direct firmware load .* failed|failed to load firmware|probe .* failed with error|module verification failed/) c["pilote"]++ } END { for (i = 1; i <= 11; i++) printf "%s=%d\n", K[i], c[K[i]] + 0 }' _sig_emit() { jo signatures; printf '%s\n' "$1" | while IFS='=' read -r k v; do [ -n "$k" ] && jn "$k" "$v"; done; eval "_F$_D=0"; jc; } _now_utc() { date -u '+%Y-%m-%dT%H:%M:%SZ'; }