diff --git a/src/loader/utils/stats.c b/src/loader/utils/stats.c new file mode 100644 index 0000000..96715e0 --- /dev/null +++ b/src/loader/utils/stats.c @@ -0,0 +1,48 @@ +#include + +/** + * Calculates and displays packet counters/stats. + * + * @param stats_map The stats map BPF FD. + * @param cpus The amount of CPUs the host has. + * + * @return 0 on success or 1 on failure. + */ +int CalculateStats(int stats_map, int cpus) +{ + u32 key = 0; + + stats_t stats[MAX_CPUS]; + memset(stats, 0, sizeof(stats)); + + u64 allowed = 0; + u64 dropped = 0; + u64 passed = 0; + + if (bpf_map_lookup_elem(stats_map, &key, stats) != 0) + { + return EXIT_FAILURE; + } + + for (int i = 0; i < cpus; i++) + { + // Although this should NEVER happen, I'm seeing very strange behavior in the following GitHub issue. + // https://github.com/gamemann/XDP-Firewall/issues/10 + // Therefore, before accessing stats[i], make sure the pointer to the specific CPU ID is not NULL. + if (&stats[i] == NULL) + { + fprintf(stderr, "Stats array at CPU ID #%d is NULL! Skipping...\n", i); + + continue; + } + + allowed += stats[i].allowed; + dropped += stats[i].dropped; + passed += stats[i].passed; + } + + fflush(stdout); + fprintf(stdout, "\rAllowed: %llu | Dropped: %llu | Passed: %llu", allowed, dropped, passed); + + return EXIT_SUCCESS; +} \ No newline at end of file diff --git a/src/loader/utils/stats.h b/src/loader/utils/stats.h new file mode 100644 index 0000000..02e607c --- /dev/null +++ b/src/loader/utils/stats.h @@ -0,0 +1,13 @@ +#pragma once + +#include +#include +#include + +#include + +#include +#include +#include + +int CalculateStats(int stats_map, int cpus); \ No newline at end of file