1use std::{
39 collections::{BTreeMap, BTreeSet},
40 ffi::{OsStr, OsString},
41 path::{Path, PathBuf},
42};
43
44use kizz_trace::{
45 AbsolutePath, AccessKind, Connection, IncompleteReason, Observations, Outcome, ProcessTree,
46 Program, Termination, TraceError,
47};
48
49pub const FORMAT: &str = "kizz-execute";
51
52pub const VERSION: u32 = 1;
57
58#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
60pub enum ReportFormat {
61 Text,
63 Json,
65}
66
67#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
69pub enum ReportMode {
70 Hierarchical,
73 Compact,
76}
77
78impl ReportMode {
79 #[must_use]
81 pub const fn name(self) -> &'static str {
82 match self {
83 Self::Hierarchical => "hierarchical",
84 Self::Compact => "compact",
85 }
86 }
87
88 pub fn json_fields(self) -> impl Iterator<Item = &'static str> {
91 JSON_FIELDS
92 .iter()
93 .filter(move |field| field.is_in(self))
94 .map(|field| field.path)
95 }
96}
97
98#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
104pub struct JsonField {
105 pub path: &'static str,
107 pub hierarchical: bool,
109 pub compact: bool,
111}
112
113impl JsonField {
114 const fn both(path: &'static str) -> Self {
116 Self {
117 path,
118 hierarchical: true,
119 compact: true,
120 }
121 }
122
123 const fn hierarchical(path: &'static str) -> Self {
125 Self {
126 path,
127 hierarchical: true,
128 compact: false,
129 }
130 }
131
132 const fn compact(path: &'static str) -> Self {
134 Self {
135 path,
136 hierarchical: false,
137 compact: true,
138 }
139 }
140
141 #[must_use]
143 pub const fn is_in(
144 self,
145 mode: ReportMode,
146 ) -> bool {
147 match mode {
148 ReportMode::Hierarchical => self.hierarchical,
149 ReportMode::Compact => self.compact,
150 }
151 }
152}
153
154pub const JSON_FIELDS: &[JsonField] = &[
162 JsonField::both("format"),
163 JsonField::both("version"),
164 JsonField::both("mode"),
165 JsonField::both("complete"),
166 JsonField::both("totals"),
167 JsonField::both("totals.commands"),
168 JsonField::both("totals.cached"),
169 JsonField::both("totals.processes"),
170 JsonField::both("totals.programs"),
171 JsonField::both("totals.paths"),
172 JsonField::both("totals.connections"),
173 JsonField::both("totals.kinds"),
174 JsonField::both("totals.kinds.read"),
175 JsonField::both("totals.kinds.probe"),
176 JsonField::both("totals.kinds.list"),
177 JsonField::both("totals.kinds.write"),
178 JsonField::both("totals.kinds.exec"),
179 JsonField::both("totals.kinds.xattr"),
180 JsonField::both("commands"),
181 JsonField::both("commands[].argv"),
182 JsonField::both("commands[].program"),
183 JsonField::both("commands[].cwd"),
184 JsonField::both("commands[].cached"),
185 JsonField::both("commands[].outcome"),
186 JsonField::both("commands[].outcome.kind"),
187 JsonField::both("commands[].outcome.code"),
188 JsonField::both("commands[].outcome.signal"),
189 JsonField::both("commands[].outcome.error"),
190 JsonField::both("commands[].complete"),
191 JsonField::both("commands[].incomplete"),
192 JsonField::both("commands[].incomplete[].kind"),
193 JsonField::both("commands[].incomplete[].detail"),
194 JsonField::both("commands[].incomplete[].number"),
195 JsonField::hierarchical("commands[].incomplete[].process"),
196 JsonField::hierarchical("commands[].processes"),
197 JsonField::hierarchical("commands[].processes[].id"),
198 JsonField::hierarchical("commands[].processes[].pid"),
199 JsonField::hierarchical("commands[].processes[].parent"),
200 JsonField::hierarchical("commands[].processes[].exit"),
201 JsonField::hierarchical("commands[].processes[].exit.kind"),
202 JsonField::hierarchical("commands[].processes[].exit.code"),
203 JsonField::hierarchical("commands[].processes[].exit.signal"),
204 JsonField::hierarchical("commands[].processes[].programs"),
205 JsonField::hierarchical("commands[].processes[].programs[].path"),
206 JsonField::hierarchical("commands[].processes[].programs[].args"),
207 JsonField::hierarchical("commands[].processes[].programs[].inherited"),
208 JsonField::hierarchical("commands[].processes[].programs[].observations"),
209 JsonField::hierarchical("commands[].processes[].programs[].observations[].path"),
210 JsonField::hierarchical("commands[].processes[].programs[].observations[].access"),
211 JsonField::hierarchical("commands[].processes[].programs[].observations[].access.read"),
212 JsonField::hierarchical("commands[].processes[].programs[].observations[].access.probe"),
213 JsonField::hierarchical("commands[].processes[].programs[].observations[].access.list"),
214 JsonField::hierarchical("commands[].processes[].programs[].observations[].access.write"),
215 JsonField::hierarchical("commands[].processes[].programs[].observations[].access.exec"),
216 JsonField::hierarchical("commands[].processes[].programs[].observations[].access.xattr"),
217 JsonField::hierarchical("commands[].processes[].programs[].connections"),
218 JsonField::hierarchical("commands[].processes[].programs[].connections[].kind"),
219 JsonField::hierarchical("commands[].processes[].programs[].connections[].address"),
220 JsonField::hierarchical("commands[].processes[].programs[].connections[].path"),
221 JsonField::hierarchical("commands[].processes[].programs[].connections[].name"),
222 JsonField::both("task_program"),
223 JsonField::both("task_program.task"),
224 JsonField::hierarchical("task_program.observations"),
225 JsonField::hierarchical("task_program.observations[].path"),
226 JsonField::hierarchical("task_program.observations[].access"),
227 JsonField::hierarchical("task_program.observations[].access.read"),
228 JsonField::hierarchical("task_program.observations[].access.probe"),
229 JsonField::hierarchical("task_program.observations[].access.list"),
230 JsonField::hierarchical("task_program.observations[].access.write"),
231 JsonField::hierarchical("task_program.observations[].access.exec"),
232 JsonField::hierarchical("task_program.observations[].access.xattr"),
233 JsonField::compact("observations"),
234 JsonField::compact("observations[].path"),
235 JsonField::compact("observations[].access"),
236 JsonField::compact("observations[].access.read"),
237 JsonField::compact("observations[].access.probe"),
238 JsonField::compact("observations[].access.list"),
239 JsonField::compact("observations[].access.write"),
240 JsonField::compact("observations[].access.exec"),
241 JsonField::compact("observations[].access.xattr"),
242 JsonField::compact("connections"),
243 JsonField::compact("connections[].kind"),
244 JsonField::compact("connections[].address"),
245 JsonField::compact("connections[].path"),
246 JsonField::compact("connections[].name"),
247];
248
249#[derive(Debug, Clone, PartialEq, Eq, Hash)]
251pub enum CommandOutcome {
252 Exited(i32),
254 Signaled(i32),
256 NotFound(String),
258 NotExecutable(String),
260 StartFailed(String),
263 Failed(String),
266}
267
268impl CommandOutcome {
269 #[must_use]
271 pub const fn from_termination(termination: Termination) -> Self {
272 match termination {
273 Termination::Exited(code) => Self::Exited(code),
274 Termination::Signaled(signal) => Self::Signaled(signal),
275 }
276 }
277
278 #[must_use]
280 pub fn from_error(error: &TraceError) -> Self {
281 let message = error.to_string();
282 match error {
283 TraceError::ProgramNotFound { .. } => Self::NotFound(message),
284 TraceError::ProgramNotExecutable { .. } => Self::NotExecutable(message),
285 TraceError::StartFailed { .. } => Self::StartFailed(message),
286 TraceError::Tracer { .. } => Self::Failed(message),
287 }
288 }
289
290 #[must_use]
292 pub const fn kind(&self) -> &'static str {
293 match self {
294 Self::Exited(_) => "exited",
295 Self::Signaled(_) => "signaled",
296 Self::NotFound(_) => "not_found",
297 Self::NotExecutable(_) => "not_executable",
298 Self::StartFailed(_) => "start_failed",
299 Self::Failed(_) => "failed",
300 }
301 }
302
303 #[must_use]
307 pub fn text(&self) -> String {
308 match self {
309 Self::Exited(code) => format!("exited with {code}"),
310 Self::Signaled(signal) => format!("signaled with {signal}"),
311 Self::NotFound(error) => format!("not found: {}", escape_text(error)),
312 Self::NotExecutable(error) => format!("not executable: {}", escape_text(error)),
313 Self::StartFailed(error) => format!("start failed: {}", escape_text(error)),
314 Self::Failed(error) => format!("failed: {}", escape_text(error)),
315 }
316 }
317}
318
319#[derive(Debug, Clone, PartialEq, Eq)]
321pub enum Execution {
322 Cached {
324 outcome: CommandOutcome,
326 },
327 Ran {
329 outcome: CommandOutcome,
331 tree: Option<ProcessTree>,
334 lookup: Observations,
336 },
337}
338
339#[derive(Debug, Clone, PartialEq, Eq)]
341pub struct CommandInput {
342 pub argv: Vec<OsString>,
344 pub program: Option<AbsolutePath>,
346 pub cwd: AbsolutePath,
348 pub execution: Execution,
350}
351
352#[derive(Debug, Clone, PartialEq, Eq)]
354pub struct TaskProgramInput {
355 pub task: String,
357 pub observations: Observations,
359}
360
361#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
364pub enum ReasonKind {
365 NonNativeSystemCall,
367 UntraceableSystemCall,
369 UnknownSystemCall,
371 TracerFailed,
373 Other,
375}
376
377impl ReasonKind {
378 #[must_use]
380 pub const fn name(self) -> &'static str {
381 match self {
382 Self::NonNativeSystemCall => "non_native_system_call",
383 Self::UntraceableSystemCall => "untraceable_system_call",
384 Self::UnknownSystemCall => "unknown_system_call",
385 Self::TracerFailed => "tracer_failed",
386 Self::Other => "other",
387 }
388 }
389
390 #[must_use]
392 pub const fn text(self) -> &'static str {
393 match self {
394 Self::NonNativeSystemCall => "non-native system call",
395 Self::UntraceableSystemCall => "untraceable system call",
396 Self::UnknownSystemCall => "unknown system call",
397 Self::TracerFailed => "tracer failed",
398 Self::Other => "other",
399 }
400 }
401}
402
403#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
407pub struct Reason {
408 pub process: Option<u32>,
410 pub kind: ReasonKind,
412 pub number: Option<u32>,
414 pub detail: String,
416}
417
418impl Reason {
419 fn of_tracer(
421 reason: IncompleteReason,
422 process: u32,
423 ) -> Self {
424 let (kind, detail) = match reason {
425 IncompleteReason::NonNativeSystemCall { detail } => {
426 (ReasonKind::NonNativeSystemCall, detail)
427 },
428 IncompleteReason::UntraceableSystemCall { detail } => {
429 (ReasonKind::UntraceableSystemCall, detail)
430 },
431 IncompleteReason::Other { detail } => (ReasonKind::Other, detail),
432 };
433 Self {
434 process: Some(process),
435 kind,
436 number: None,
437 detail,
438 }
439 }
440
441 fn unknown(
443 number: u32,
444 process: u32,
445 ) -> Self {
446 Self {
447 process: Some(process),
448 kind: ReasonKind::UnknownSystemCall,
449 number: Some(number),
450 detail: format!("the tracer does not know system call {number}"),
451 }
452 }
453}
454
455#[derive(Debug, Clone, PartialEq, Eq)]
457pub struct ReportProgram {
458 pub path: PathBuf,
461 pub args: Vec<OsString>,
463 pub inherited: bool,
465 pub observations: Observations,
467 pub connections: BTreeSet<Connection>,
469}
470
471impl ReportProgram {
472 fn named(
474 path: PathBuf,
475 args: Vec<OsString>,
476 ) -> Self {
477 Self {
478 path,
479 args,
480 inherited: false,
481 observations: Observations::new(),
482 connections: BTreeSet::new(),
483 }
484 }
485
486 fn looked_up(argv: &[OsString]) -> Self {
489 let name = argv.first().map_or_default(PathBuf::from);
490 Self::named(name, argv.to_vec())
491 }
492}
493
494#[derive(Debug, Clone, PartialEq, Eq)]
496pub struct ReportProcess {
497 pub id: u32,
499 pub pid: Option<u32>,
501 pub parent: Option<u32>,
503 pub exit: Option<Termination>,
505 pub programs: Vec<ReportProgram>,
507}
508
509#[derive(Debug, Clone, PartialEq, Eq)]
511pub struct ReportCommand {
512 pub argv: Vec<OsString>,
514 pub program: Option<AbsolutePath>,
516 pub cwd: AbsolutePath,
518 pub cached: bool,
520 pub outcome: CommandOutcome,
522 pub incomplete: Vec<Reason>,
524 pub processes: Vec<ReportProcess>,
526}
527
528impl ReportCommand {
529 #[must_use]
532 pub const fn complete(&self) -> Option<bool> {
533 if self.cached {
534 None
535 } else {
536 Some(self.incomplete.is_empty())
537 }
538 }
539
540 fn build(
543 input: CommandInput,
544 next_id: &mut u32,
545 ) -> Self {
546 let CommandInput {
547 argv,
548 program,
549 cwd,
550 execution,
551 } = input;
552 let (outcome, tree, lookup) = match execution {
553 Execution::Cached { outcome } => {
554 return Self {
555 argv,
556 program,
557 cwd,
558 cached: true,
559 outcome,
560 incomplete: Vec::new(),
561 processes: Vec::new(),
562 };
563 },
564 Execution::Ran {
565 outcome,
566 tree,
567 lookup,
568 } => (outcome, tree, lookup),
569 };
570 let (mut processes, mut incomplete) = renumber(tree.unwrap_or_default(), next_id);
571 if processes.is_empty() {
572 processes.push(ReportProcess {
573 id: take_id(next_id),
574 pid: None,
575 parent: None,
576 exit: None,
577 programs: Vec::new(),
578 });
579 }
580 let first_id = processes.first().map(|process| process.id);
581 if let Some(first) = processes.first_mut() {
582 if first.programs.is_empty() {
583 first.programs.push(ReportProgram::looked_up(&argv));
584 }
585 if let Some(program) = first.programs.first_mut() {
586 program.observations.merge(&lookup);
587 }
588 }
589 if let CommandOutcome::Failed(message) = &outcome {
590 incomplete.push(Reason {
591 process: first_id,
592 kind: ReasonKind::TracerFailed,
593 number: None,
594 detail: message.clone(),
595 });
596 }
597 incomplete.sort();
598 incomplete.dedup();
599 Self {
600 argv,
601 program,
602 cwd,
603 cached: false,
604 outcome,
605 incomplete,
606 processes,
607 }
608 }
609}
610
611fn take_id(next_id: &mut u32) -> u32 {
613 let id = *next_id;
614 *next_id = next_id.saturating_add(1);
615 id
616}
617
618fn renumber(
622 tree: ProcessTree,
623 next_id: &mut u32,
624) -> (Vec<ReportProcess>, Vec<Reason>) {
625 let mut processes = tree.processes;
626 processes.sort_by_key(|process| process.number);
627 let mut ids = BTreeMap::new();
628 let numbered: Vec<_> = processes
629 .into_iter()
630 .map(|process| {
631 let id = take_id(next_id);
632 ids.entry(process.number).or_insert(id);
633 (id, process)
634 })
635 .collect();
636 let mut reasons = Vec::new();
637 let renumbered = numbered
638 .into_iter()
639 .map(|(id, process)| {
640 let programs = process
641 .programs
642 .into_iter()
643 .map(|program| report_program(program, id, &mut reasons))
644 .collect();
645 ReportProcess {
646 id,
647 pid: process.pid,
648 parent: process.parent.and_then(|parent| ids.get(&parent).copied()),
649 exit: process.status,
650 programs,
651 }
652 })
653 .collect();
654 (renumbered, reasons)
655}
656
657fn report_program(
660 program: Program,
661 process: u32,
662 reasons: &mut Vec<Reason>,
663) -> ReportProgram {
664 let Program {
665 path,
666 args,
667 inherited,
668 observations,
669 connections,
670 unknown_system_calls,
671 incomplete,
672 } = program;
673 reasons.extend(
674 incomplete
675 .into_iter()
676 .map(|reason| Reason::of_tracer(reason, process)),
677 );
678 reasons.extend(
679 unknown_system_calls
680 .into_iter()
681 .map(|number| Reason::unknown(number, process)),
682 );
683 ReportProgram {
684 path: path.into_path_buf(),
685 args,
686 inherited,
687 observations,
688 connections,
689 }
690}
691
692#[derive(Debug, Clone, PartialEq, Eq)]
694pub struct ReportTaskProgram {
695 pub task: String,
697 pub observations: Observations,
699}
700
701#[derive(Debug, Clone, PartialEq, Eq)]
703pub struct Totals {
704 pub commands: usize,
706 pub cached: usize,
708 pub processes: usize,
710 pub programs: usize,
712 pub paths: usize,
714 pub connections: usize,
716 pub kinds: BTreeMap<AccessKind, usize>,
718}
719
720impl Totals {
721 fn count(
724 commands: &[ReportCommand],
725 observations: &Observations,
726 connections: &BTreeSet<Connection>,
727 ) -> Self {
728 let mut totals = Self {
729 commands: commands.len(),
730 cached: 0,
731 processes: 0,
732 programs: 0,
733 paths: observations.len(),
734 connections: connections.len(),
735 kinds: AccessKind::ALL.iter().map(|kind| (*kind, 0)).collect(),
736 };
737 for command in commands {
738 if command.cached {
739 totals.cached = totals.cached.saturating_add(1);
740 }
741 for process in &command.processes {
742 totals.processes = totals.processes.saturating_add(1);
743 for program in &process.programs {
744 if !program.inherited {
745 totals.programs = totals.programs.saturating_add(1);
746 }
747 }
748 }
749 }
750 for (_, kinds) in observations {
751 for kind in kinds.keys() {
752 let count = totals.kinds.entry(*kind).or_default();
753 *count = count.saturating_add(1);
754 }
755 }
756 totals
757 }
758
759 #[must_use]
761 pub fn kind(
762 &self,
763 kind: AccessKind,
764 ) -> usize {
765 self.kinds.get(&kind).copied().unwrap_or_default()
766 }
767}
768
769#[derive(Debug, Clone, PartialEq, Eq)]
772pub struct Report {
773 pub commands: Vec<ReportCommand>,
775 pub task_program: Option<ReportTaskProgram>,
777 pub observations: Observations,
780 pub connections: BTreeSet<Connection>,
782 pub totals: Totals,
784}
785
786impl Report {
787 #[must_use]
790 pub fn new(
791 commands: Vec<CommandInput>,
792 task_program: Option<TaskProgramInput>,
793 ) -> Self {
794 let mut next_id = 1;
795 let commands: Vec<ReportCommand> = commands
796 .into_iter()
797 .map(|command| ReportCommand::build(command, &mut next_id))
798 .collect();
799 let task_program = task_program.map(|input| {
800 ReportTaskProgram {
801 task: input.task,
802 observations: input.observations,
803 }
804 });
805 let mut observations = Observations::new();
806 let mut connections = BTreeSet::new();
807 for command in &commands {
808 for process in &command.processes {
809 for program in &process.programs {
810 observations.merge(&program.observations);
811 connections.extend(program.connections.iter().cloned());
812 }
813 }
814 }
815 if let Some(task_program) = &task_program {
816 observations.merge(&task_program.observations);
817 }
818 let totals = Totals::count(&commands, &observations, &connections);
819 Self {
820 commands,
821 task_program,
822 observations,
823 connections,
824 totals,
825 }
826 }
827
828 #[must_use]
831 pub fn complete(&self) -> bool {
832 self.commands
833 .iter()
834 .all(|command| command.complete() != Some(false))
835 }
836
837 #[must_use]
839 pub fn render(
840 &self,
841 format: ReportFormat,
842 mode: ReportMode,
843 ) -> String {
844 match format {
845 ReportFormat::Text => self.text(mode),
846 ReportFormat::Json => self.json(mode),
847 }
848 }
849
850 #[must_use]
854 pub fn text(
855 &self,
856 mode: ReportMode,
857 ) -> String {
858 let mut blocks = vec![self.text_header(mode)];
859 for (index, command) in self.commands.iter().enumerate() {
860 blocks.push(text_command(index.saturating_add(1), command, mode));
861 }
862 if let Some(task_program) = &self.task_program {
863 let mut block = format!("task program: {}\n", escape_text(&task_program.task));
864 if mode == ReportMode::Hierarchical {
865 text_groups(&mut block, &task_program.observations, None, 1);
866 }
867 blocks.push(block);
868 }
869 if mode == ReportMode::Compact {
870 let mut block = String::new();
871 text_groups(&mut block, &self.observations, Some(&self.connections), 0);
872 if !block.is_empty() {
873 blocks.push(block);
874 }
875 }
876 blocks.join("\n")
877 }
878
879 fn text_header(
881 &self,
882 mode: ReportMode,
883 ) -> String {
884 let totals = &self.totals;
885 let kinds: Vec<String> = AccessKind::ALL
886 .iter()
887 .map(|kind| format!("{} {}", kind.name(), totals.kind(*kind)))
888 .collect();
889 format!(
890 "kizz observation report, version {VERSION}, {}\ntrace: {}\ntotals: commands {}, cached \
891 {}, processes {}, programs {}, paths {}, connections {}\npaths by access: {}\n",
892 mode.name(),
893 if self.complete() {
894 "complete"
895 } else {
896 "incomplete"
897 },
898 totals.commands,
899 totals.cached,
900 totals.processes,
901 totals.programs,
902 totals.paths,
903 totals.connections,
904 kinds.join(", ")
905 )
906 }
907
908 #[must_use]
911 pub fn json(
912 &self,
913 mode: ReportMode,
914 ) -> String {
915 let totals = &self.totals;
916 let kinds = AccessKind::ALL
917 .iter()
918 .map(|kind| (kind.name(), Json::count(totals.kind(*kind))))
919 .collect();
920 let mut members = vec![
921 ("format", Json::text(FORMAT)),
922 ("version", Json::Number(VERSION.to_string())),
923 ("mode", Json::text(mode.name())),
924 ("complete", Json::Bool(self.complete())),
925 (
926 "totals",
927 Json::Object(vec![
928 ("commands", Json::count(totals.commands)),
929 ("cached", Json::count(totals.cached)),
930 ("processes", Json::count(totals.processes)),
931 ("programs", Json::count(totals.programs)),
932 ("paths", Json::count(totals.paths)),
933 ("connections", Json::count(totals.connections)),
934 ("kinds", Json::Object(kinds)),
935 ]),
936 ),
937 (
938 "commands",
939 Json::Array(
940 self.commands
941 .iter()
942 .map(|command| json_command(command, mode))
943 .collect(),
944 ),
945 ),
946 (
947 "task_program",
948 self.task_program
949 .as_ref()
950 .map_or(Json::Null, |task_program| {
951 let mut members = vec![("task", Json::text(&task_program.task))];
952 if mode == ReportMode::Hierarchical {
953 members.push((
954 "observations",
955 json_observations(&task_program.observations),
956 ));
957 }
958 Json::Object(members)
959 }),
960 ),
961 ];
962 if mode == ReportMode::Compact {
963 members.push(("observations", json_observations(&self.observations)));
964 members.push(("connections", json_connections(&self.connections)));
965 }
966 let mut text = String::new();
967 Json::Object(members).write(&mut text, 0);
968 text.push('\n');
969 text
970 }
971}
972
973fn lossy(text: &OsStr) -> String {
976 text.to_string_lossy().into_owned()
977}
978
979fn lossy_path(path: &Path) -> String {
981 lossy(path.as_os_str())
982}
983
984#[must_use]
993pub fn escape_text(text: &str) -> String {
994 let mut escaped = String::with_capacity(text.len());
995 for character in text.chars() {
996 match character {
997 '\\' => escaped.push_str("\\\\"),
998 '\n' => escaped.push_str("\\n"),
999 '\t' => escaped.push_str("\\t"),
1000 '\r' => escaped.push_str("\\r"),
1001 other if other.is_control() || matches!(other, '\u{2028}' | '\u{2029}') => {
1002 escaped.extend(other.escape_unicode());
1003 },
1004 other => escaped.push(other),
1005 }
1006 }
1007 escaped
1008}
1009
1010fn text_path(path: &Path) -> String {
1013 escape_text(&lossy_path(path))
1014}
1015
1016fn is_plain_word(word: &str) -> bool {
1019 !word.is_empty()
1020 && word
1021 .chars()
1022 .all(|character| character.is_ascii_alphanumeric() || "-_./=:,+@%^".contains(character))
1023}
1024
1025fn shell_words(args: &[OsString]) -> String {
1030 let words: Vec<String> = args
1031 .iter()
1032 .map(|arg| {
1033 let word = escape_text(&lossy(arg));
1034 if is_plain_word(&word) {
1035 word
1036 } else {
1037 format!("'{}'", word.replace('\'', "'\\''"))
1038 }
1039 })
1040 .collect();
1041 words.join(" ")
1042}
1043
1044fn with_args(
1046 head: String,
1047 args: &[OsString],
1048) -> String {
1049 if args.is_empty() {
1050 head
1051 } else {
1052 format!("{head}: {}", shell_words(args))
1053 }
1054}
1055
1056fn indent(
1058 text: &mut String,
1059 depth: usize,
1060) {
1061 for _ in 0..depth {
1062 text.push_str(" ");
1063 }
1064}
1065
1066fn line(
1068 text: &mut String,
1069 depth: usize,
1070 content: &str,
1071) {
1072 indent(text, depth);
1073 text.push_str(content);
1074 text.push('\n');
1075}
1076
1077fn outcome_list<'a>(outcomes: impl Iterator<Item = &'a Outcome>) -> String {
1080 let outcomes: Vec<String> = outcomes
1081 .map(|outcome| escape_text(&outcome.to_string()))
1082 .collect();
1083 outcomes.join(", ")
1084}
1085
1086fn connection_text(connection: &Connection) -> String {
1090 match connection {
1091 Connection::Ip(address) => format!("ip {address}"),
1092 Connection::UnixPath(path) => format!("unix {}", text_path(path.as_path())),
1093 Connection::UnixAbstract(name) => {
1094 format!("abstract {}", escape_text(&String::from_utf8_lossy(name)))
1095 },
1096 }
1097}
1098
1099fn text_groups(
1103 text: &mut String,
1104 observations: &Observations,
1105 connections: Option<&BTreeSet<Connection>>,
1106 depth: usize,
1107) {
1108 let inner = depth.saturating_add(1);
1109 for kind in AccessKind::ALL {
1110 let paths: Vec<_> = observations
1111 .iter()
1112 .filter_map(|(path, kinds)| kinds.get(&kind).map(|outcomes| (path, outcomes)))
1113 .collect();
1114 if paths.is_empty() {
1115 continue;
1116 }
1117 line(text, depth, &format!("{}:", kind.name()));
1118 for (path, outcomes) in paths {
1119 line(
1120 text,
1121 inner,
1122 &format!(
1123 "{}: {}",
1124 text_path(path.as_path()),
1125 outcome_list(outcomes.iter())
1126 ),
1127 );
1128 }
1129 }
1130 if let Some(connections) = connections.filter(|connections| !connections.is_empty()) {
1131 line(text, depth, "connections:");
1132 for connection in connections {
1133 line(text, inner, &connection_text(connection));
1134 }
1135 }
1136}
1137
1138fn exit_text(exit: Termination) -> String {
1140 match exit {
1141 Termination::Exited(code) => format!("exited with {code}"),
1142 Termination::Signaled(signal) => format!("signaled with {signal}"),
1143 }
1144}
1145
1146fn process_line(process: &ReportProcess) -> String {
1150 if process.pid.is_none() && process.exit.is_none() {
1151 return format!("process {}, not started", process.id);
1152 }
1153 let mut parts = vec![format!("process {}", process.id)];
1154 parts.push(
1155 process
1156 .pid
1157 .map_or_else(|| "no pid".to_owned(), |pid| format!("pid {pid}")),
1158 );
1159 if let Some(parent) = process.parent {
1160 parts.push(format!("child of process {parent}"));
1161 }
1162 parts.push(
1163 process
1164 .exit
1165 .map_or_else(|| "end not seen".to_owned(), exit_text),
1166 );
1167 parts.join(", ")
1168}
1169
1170fn reason_line(
1172 reason: &Reason,
1173 mode: ReportMode,
1174) -> String {
1175 match (mode, reason.process) {
1176 (ReportMode::Hierarchical, Some(process)) => {
1177 format!(
1178 "{}, process {process}: {}",
1179 reason.kind.text(),
1180 escape_text(&reason.detail)
1181 )
1182 },
1183 _ => format!("{}: {}", reason.kind.text(), escape_text(&reason.detail)),
1184 }
1185}
1186
1187fn text_command(
1189 number: usize,
1190 command: &ReportCommand,
1191 mode: ReportMode,
1192) -> String {
1193 let mut text = String::new();
1194 line(
1195 &mut text,
1196 0,
1197 &with_args(format!("command {number}"), &command.argv),
1198 );
1199 let program = command.program.as_ref().map_or_else(
1200 || "not found".to_owned(),
1201 |program| text_path(program.as_path()),
1202 );
1203 line(&mut text, 1, &format!("program: {program}"));
1204 line(
1205 &mut text,
1206 1,
1207 &format!("directory: {}", text_path(command.cwd.as_path())),
1208 );
1209 line(
1210 &mut text,
1211 1,
1212 &format!("outcome: {}", command.outcome.text()),
1213 );
1214 let trace = match command.complete() {
1215 None => "cached, not traced",
1216 Some(true) => "complete",
1217 Some(false) => "incomplete",
1218 };
1219 line(&mut text, 1, &format!("trace: {trace}"));
1220 for reason in &command.incomplete {
1221 line(&mut text, 2, &reason_line(reason, mode));
1222 }
1223 if mode == ReportMode::Hierarchical {
1224 text_processes(&mut text, &command.processes);
1225 }
1226 text
1227}
1228
1229fn text_processes(
1235 text: &mut String,
1236 processes: &[ReportProcess],
1237) {
1238 let positions: BTreeMap<u32, usize> = processes
1239 .iter()
1240 .enumerate()
1241 .rev()
1242 .map(|(position, process)| (process.id, position))
1243 .collect();
1244 let mut children: Vec<Vec<&ReportProcess>> = processes.iter().map(|_| Vec::new()).collect();
1245 let mut roots = Vec::new();
1246 for (position, process) in processes.iter().enumerate() {
1247 let parent = process
1248 .parent
1249 .and_then(|parent| positions.get(&parent).copied())
1250 .filter(|parent| *parent < position);
1251 match parent.and_then(|parent| children.get_mut(parent)) {
1252 Some(siblings) => siblings.push(process),
1253 None => roots.push(process),
1254 }
1255 }
1256 let mut stack: Vec<(&ReportProcess, usize)> = roots
1257 .into_iter()
1258 .rev()
1259 .map(|process| (process, 1))
1260 .collect();
1261 while let Some((process, depth)) = stack.pop() {
1262 line(text, depth, &process_line(process));
1263 let inner = depth.saturating_add(1);
1264 for program in &process.programs {
1265 let head = if program.inherited {
1266 format!("program {}, inherited", text_path(&program.path))
1267 } else {
1268 format!("program {}", text_path(&program.path))
1269 };
1270 line(text, inner, &with_args(head, &program.args));
1271 text_groups(
1272 text,
1273 &program.observations,
1274 Some(&program.connections),
1275 inner.saturating_add(1),
1276 );
1277 }
1278 let own = positions
1279 .get(&process.id)
1280 .and_then(|position| children.get(*position));
1281 for child in own.into_iter().flatten().rev() {
1282 stack.push((*child, inner));
1283 }
1284 }
1285}
1286
1287#[derive(Debug, Clone, PartialEq, Eq)]
1289enum Json {
1290 Null,
1292 Bool(bool),
1294 Number(String),
1296 String(String),
1298 Array(Vec<Self>),
1300 Object(Vec<(&'static str, Self)>),
1302}
1303
1304impl Json {
1305 fn text(text: &str) -> Self {
1307 Self::String(text.to_owned())
1308 }
1309
1310 fn count(count: usize) -> Self {
1312 Self::Number(count.to_string())
1313 }
1314
1315 fn optional<T: ToString>(value: Option<T>) -> Self {
1317 value.map_or(Self::Null, |value| Self::Number(value.to_string()))
1318 }
1319
1320 fn write(
1324 &self,
1325 text: &mut String,
1326 level: usize,
1327 ) {
1328 let inner = level.saturating_add(1);
1329 match self {
1330 Self::Null => text.push_str("null"),
1331 Self::Bool(value) => text.push_str(if *value { "true" } else { "false" }),
1332 Self::Number(number) => text.push_str(number),
1333 Self::String(value) => write_json_string(text, value),
1334 Self::Array(items) if items.is_empty() => text.push_str("[]"),
1335 Self::Object(members) if members.is_empty() => text.push_str("{}"),
1336 Self::Array(items) => {
1337 text.push('[');
1338 for (index, item) in items.iter().enumerate() {
1339 text.push_str(if index == 0 { "\n" } else { ",\n" });
1340 indent(text, inner);
1341 item.write(text, inner);
1342 }
1343 text.push('\n');
1344 indent(text, level);
1345 text.push(']');
1346 },
1347 Self::Object(members) => {
1348 text.push('{');
1349 for (index, (key, member)) in members.iter().enumerate() {
1350 text.push_str(if index == 0 { "\n" } else { ",\n" });
1351 indent(text, inner);
1352 write_json_string(text, key);
1353 text.push_str(": ");
1354 member.write(text, inner);
1355 }
1356 text.push('\n');
1357 indent(text, level);
1358 text.push('}');
1359 },
1360 }
1361 }
1362}
1363
1364fn write_json_string(
1368 text: &mut String,
1369 value: &str,
1370) {
1371 text.push('"');
1372 for character in value.chars() {
1373 match character {
1374 '"' => text.push_str("\\\""),
1375 '\\' => text.push_str("\\\\"),
1376 '\n' => text.push_str("\\n"),
1377 '\r' => text.push_str("\\r"),
1378 '\t' => text.push_str("\\t"),
1379 '\u{08}' => text.push_str("\\b"),
1380 '\u{0c}' => text.push_str("\\f"),
1381 control if control < ' ' => {
1382 let code = u32::from(control);
1385 text.push_str(if code & 0x10 == 0 { "\\u000" } else { "\\u001" });
1386 let low = usize::try_from(code & 0x0F).unwrap_or_default();
1387 text.push(char::from(
1388 b"0123456789abcdef".get(low).copied().unwrap_or(b'0'),
1389 ));
1390 },
1391 other => text.push(other),
1392 }
1393 }
1394 text.push('"');
1395}
1396
1397fn json_args(args: &[OsString]) -> Json {
1399 Json::Array(args.iter().map(|arg| Json::String(lossy(arg))).collect())
1400}
1401
1402fn json_outcome(outcome: &CommandOutcome) -> Json {
1404 let detail = match outcome {
1405 CommandOutcome::Exited(code) => ("code", Json::Number(code.to_string())),
1406 CommandOutcome::Signaled(signal) => ("signal", Json::Number(signal.to_string())),
1407 CommandOutcome::NotFound(error)
1408 | CommandOutcome::NotExecutable(error)
1409 | CommandOutcome::StartFailed(error)
1410 | CommandOutcome::Failed(error) => ("error", Json::text(error)),
1411 };
1412 Json::Object(vec![("kind", Json::text(outcome.kind())), detail])
1413}
1414
1415fn json_exit(exit: Termination) -> Json {
1418 match exit {
1419 Termination::Exited(code) => {
1420 Json::Object(vec![
1421 ("kind", Json::text("exited")),
1422 ("code", Json::Number(code.to_string())),
1423 ])
1424 },
1425 Termination::Signaled(signal) => {
1426 Json::Object(vec![
1427 ("kind", Json::text("signaled")),
1428 ("signal", Json::Number(signal.to_string())),
1429 ])
1430 },
1431 }
1432}
1433
1434fn json_reason(
1436 reason: &Reason,
1437 mode: ReportMode,
1438) -> Json {
1439 let mut members = vec![
1440 ("kind", Json::text(reason.kind.name())),
1441 ("detail", Json::text(&reason.detail)),
1442 ("number", Json::optional(reason.number)),
1443 ];
1444 if mode == ReportMode::Hierarchical {
1445 members.push(("process", Json::optional(reason.process)));
1446 }
1447 Json::Object(members)
1448}
1449
1450fn json_observations(observations: &Observations) -> Json {
1453 Json::Array(
1454 observations
1455 .iter()
1456 .map(|(path, kinds)| {
1457 let access = kinds
1458 .iter()
1459 .map(|(kind, outcomes)| {
1460 (
1461 kind.name(),
1462 Json::Array(
1463 outcomes
1464 .iter()
1465 .map(|outcome| Json::String(outcome.to_string()))
1466 .collect(),
1467 ),
1468 )
1469 })
1470 .collect();
1471 Json::Object(vec![
1472 ("path", Json::String(lossy_path(path.as_path()))),
1473 ("access", Json::Object(access)),
1474 ])
1475 })
1476 .collect(),
1477 )
1478}
1479
1480fn json_connections(connections: &BTreeSet<Connection>) -> Json {
1483 Json::Array(
1484 connections
1485 .iter()
1486 .map(|connection| {
1487 let (kind, member) = match connection {
1488 Connection::Ip(address) => {
1489 ("ip", ("address", Json::String(address.to_string())))
1490 },
1491 Connection::UnixPath(path) => {
1492 ("unix", ("path", Json::String(lossy_path(path.as_path()))))
1493 },
1494 Connection::UnixAbstract(name) => {
1495 (
1496 "abstract",
1497 (
1498 "name",
1499 Json::String(String::from_utf8_lossy(name).into_owned()),
1500 ),
1501 )
1502 },
1503 };
1504 Json::Object(vec![("kind", Json::text(kind)), member])
1505 })
1506 .collect(),
1507 )
1508}
1509
1510fn json_program(program: &ReportProgram) -> Json {
1512 Json::Object(vec![
1513 ("path", Json::String(lossy_path(&program.path))),
1514 ("args", json_args(&program.args)),
1515 ("inherited", Json::Bool(program.inherited)),
1516 ("observations", json_observations(&program.observations)),
1517 ("connections", json_connections(&program.connections)),
1518 ])
1519}
1520
1521fn json_process(process: &ReportProcess) -> Json {
1523 Json::Object(vec![
1524 ("id", Json::Number(process.id.to_string())),
1525 ("pid", Json::optional(process.pid)),
1526 ("parent", Json::optional(process.parent)),
1527 ("exit", process.exit.map_or(Json::Null, json_exit)),
1528 (
1529 "programs",
1530 Json::Array(process.programs.iter().map(json_program).collect()),
1531 ),
1532 ])
1533}
1534
1535fn json_command(
1537 command: &ReportCommand,
1538 mode: ReportMode,
1539) -> Json {
1540 let mut members = vec![
1541 ("argv", json_args(&command.argv)),
1542 (
1543 "program",
1544 command.program.as_ref().map_or(Json::Null, |program| {
1545 Json::String(lossy_path(program.as_path()))
1546 }),
1547 ),
1548 ("cwd", Json::String(lossy_path(command.cwd.as_path()))),
1549 ("cached", Json::Bool(command.cached)),
1550 ("outcome", json_outcome(&command.outcome)),
1551 (
1552 "complete",
1553 command.complete().map_or(Json::Null, Json::Bool),
1554 ),
1555 (
1556 "incomplete",
1557 Json::Array(
1558 command
1559 .incomplete
1560 .iter()
1561 .map(|reason| json_reason(reason, mode))
1562 .collect(),
1563 ),
1564 ),
1565 ];
1566 if mode == ReportMode::Hierarchical {
1567 members.push((
1568 "processes",
1569 Json::Array(command.processes.iter().map(json_process).collect()),
1570 ));
1571 }
1572 Json::Object(members)
1573}
1574
1575#[cfg(test)]
1577#[allow(clippy::disallowed_macros, reason = "test code: the tests assert")]
1578mod tests {
1579 use std::ffi::OsString;
1580
1581 use super::{Json, escape_text, is_plain_word, shell_words, write_json_string};
1582
1583 #[test]
1585 fn strings_escape_as_serde_json_does() -> Result<(), serde_json::Error> {
1586 let value = format!(
1587 "quote \" backslash \\ newline \n tab \t bell \u{07} back \u{08} feed \u{0c} return \
1588 \r unit \u{1f} delete \u{7f} replacement {}",
1589 char::REPLACEMENT_CHARACTER
1590 );
1591 let mut text = String::new();
1592 write_json_string(&mut text, &value);
1593 assert_eq!(text, serde_json::to_string(&value)?);
1594 assert_eq!(serde_json::from_str::<String>(&text)?, value);
1595 Ok(())
1596 }
1597
1598 #[test]
1601 fn values_write_in_order() {
1602 let mut text = String::new();
1603 Json::Object(vec![
1604 ("b", Json::Array(Vec::new())),
1605 ("a", Json::Object(Vec::new())),
1606 ("c", Json::Array(vec![Json::Null, Json::Bool(false)])),
1607 ])
1608 .write(&mut text, 0);
1609 assert_eq!(
1610 text,
1611 "{\n \"b\": [],\n \"a\": {},\n \"c\": [\n null,\n false\n ]\n}"
1612 );
1613 }
1614
1615 #[test]
1618 fn words_are_quoted_for_a_shell() {
1619 assert!(is_plain_word("a-Z_0./=:,+@%^"));
1620 assert!(!is_plain_word(""));
1621 assert!(!is_plain_word("a b"));
1622 assert!(!is_plain_word("caf\u{e9}"));
1623 let args: Vec<OsString> = ["cc", "", "it's", "$HOME", "a*b"]
1624 .into_iter()
1625 .map(OsString::from)
1626 .collect();
1627 assert_eq!(shell_words(&args), "cc '' 'it'\\''s' '$HOME' 'a*b'");
1628 }
1629
1630 #[test]
1634 fn text_escapes_backslashes_and_control_characters() {
1635 let cases = [
1636 ("\\", "\\\\"),
1637 ("\n", "\\n"),
1638 ("\t", "\\t"),
1639 ("\r", "\\r"),
1640 ("\u{0}", "\\u{0}"),
1641 ("\u{1}", "\\u{1}"),
1642 ("\u{1b}", "\\u{1b}"),
1643 ("\u{1f}", "\\u{1f}"),
1644 ("\u{7f}", "\\u{7f}"),
1645 ("\u{85}", "\\u{85}"),
1646 ("\u{9f}", "\\u{9f}"),
1647 ("\u{2028}", "\\u{2028}"),
1648 ("\u{2029}", "\\u{2029}"),
1649 ("a\nb\\c", "a\\nb\\\\c"),
1650 ];
1651 for (text, escaped) in cases {
1652 assert_eq!(escape_text(text), escaped, "{text:?}");
1653 }
1654 }
1655
1656 #[test]
1660 fn text_keeps_every_other_character() {
1661 for text in [
1662 "plain /work/main.c",
1663 "it's \"quoted\" $HOME",
1664 "caf\u{e9}",
1665 "�",
1666 "\u{a0}",
1667 "\u{200b}",
1668 "\u{1f600}",
1669 "",
1670 ] {
1671 assert_eq!(escape_text(text), text, "{text:?}");
1672 }
1673 }
1674
1675 #[test]
1678 fn escapes_keep_different_strings_apart() {
1679 let pairs = [
1680 ("\n", "\\n"),
1681 ("\t", "\\t"),
1682 ("\r", "\\r"),
1683 ("\u{1b}", "\\u{1b}"),
1684 ("\u{0}", "\\u{0}"),
1685 ("\u{2028}", "\\u{2028}"),
1686 ("a\\", "a\\\\"),
1687 ];
1688 for (first, second) in pairs {
1689 assert_ne!(first, second);
1690 assert_ne!(
1691 escape_text(first),
1692 escape_text(second),
1693 "{first:?} {second:?}"
1694 );
1695 }
1696 }
1697
1698 #[test]
1701 fn arguments_are_escaped_before_they_are_quoted() {
1702 let args: Vec<OsString> = ["a\nb", "back\\slash", "it's\t"]
1703 .into_iter()
1704 .map(OsString::from)
1705 .collect();
1706 assert_eq!(shell_words(&args), "'a\\nb' 'back\\\\slash' 'it'\\''s\\t'");
1707 }
1708}