Skip to content

Commit

Permalink
refactor: Change remaining names and fix compiler warnings (#10)
Browse files Browse the repository at this point in the history
  • Loading branch information
hparzych authored Sep 25, 2023
1 parent 6a22783 commit e6e10b5
Show file tree
Hide file tree
Showing 19 changed files with 280 additions and 281 deletions.
6 changes: 3 additions & 3 deletions ebpfdiscoverysrv/src/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,13 @@

static ebpfdiscovery::Discovery discoveryInstance;

std::atomic<bool> is_shutting_down;
std::atomic<bool> isShuttingDown;

static void handleUnixExitSignal(int signo) {
if (is_shutting_down) {
if (isShuttingDown) {
return;
}
is_shutting_down = true;
isShuttingDown = true;

discoveryInstance.stopRun();
}
Expand Down
1 change: 0 additions & 1 deletion libebpfdiscovery/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ list(
SOURCES
src/Config.cpp
src/Discovery.cpp
src/Log.cpp
src/Session.cpp
src/StringFunctions.cpp
)
Expand Down
16 changes: 9 additions & 7 deletions libebpfdiscovery/headers/ebpfdiscovery/Discovery.h
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ class Discovery {
Discovery(const DiscoveryConfig config);
~Discovery();

bool isLoaded() noexcept;
void load();
void unload() noexcept;

Expand All @@ -43,21 +44,22 @@ class Discovery {
void handleNewEvent(DiscoveryEvent event);

void handleNewDataEvent(DiscoveryEvent& event);
void handleBufferLookupSuccess(DiscoverySavedBuffer& saved_buffer, DiscoveryEvent& event);
void handleExistingSession(SavedSessionsCacheType::iterator it, std::string_view& buffer_view, DiscoveryEvent& event);
void handleNewSession(std::string_view& buffer_view, DiscoveryEvent& event);
void handleBufferLookupSuccess(DiscoverySavedBuffer& savedBuffer, DiscoveryEvent& event);
void handleExistingSession(SavedSessionsCacheType::iterator it, std::string_view& bufferView, DiscoveryEvent& event);
void handleNewSession(std::string_view& bufferView, DiscoveryEvent& event);
void handleCloseEvent(DiscoveryEvent& event);
void handleSuccessfulParse(const Session& session, const DiscoverySessionMeta& session_meta);
void handleSuccessfulParse(const Session& session, const DiscoverySessionMeta& sessionMeta);

int bpfDiscoveryResetConfig();
int bpfDiscoveryResumeCollecting();
int bpfDiscoveryDeleteSession(const DiscoveryTrackedSessionKey& tracked_session_key);
int bpfDiscoveryDeleteSession(const DiscoveryTrackedSessionKey& trackedSessionKey);

DiscoveryConfig config;

std::atomic<bool> running;
bpf_object_open_opts bpf_open_opts;
discovery_bpf* bpf_obj;
std::atomic<bool> loaded;
discovery_bpf* discoverySkel;
bpf_object_open_opts discoverySkelOpenOpts;
SavedSessionsCacheType savedSessions;
};

Expand Down
14 changes: 0 additions & 14 deletions libebpfdiscovery/headers/ebpfdiscovery/Log.h

This file was deleted.

99 changes: 66 additions & 33 deletions libebpfdiscovery/src/Discovery.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

#include "ebpfdiscovery/Discovery.h"

#include "ebpfdiscovery/Log.h"
#include "StringFunctions.h"
#include "ebpfdiscovery/Session.h"

extern "C" {
Expand All @@ -24,18 +24,35 @@ extern "C" {

namespace ebpfdiscovery {

static void printSession(const Session& session, const DiscoverySessionMeta& meta) {
const auto& request{session.parser.result};
std::cout << request.method << " " << request.host << request.url;

if (const auto& xForwardedFor{request.xForwardedFor}; !xForwardedFor.empty()) {
std::cout << " X-Forwarded-For: " << '"' << xForwardedFor << '"';
} else if (discoverySessionFlagsIsIPv4(meta.flags)) {
if (auto srcIpv4{ipv4ToString(meta.sourceIPData)}; !srcIpv4.empty())
std::cout << " srcIpv4: " << '"' << srcIpv4 << '"';
} else if (discoverySessionFlagsIsIPv6(meta.flags)) {
if (auto srcIpv6{ipv6ToString(meta.sourceIPData)}; !srcIpv6.empty())
std::cout << " srcIpv6: " << '"' << srcIpv6 << '"';
}

std::cout << '\n';
}

Discovery::Discovery() : Discovery(DiscoveryConfig{}) {
}

Discovery::Discovery(const DiscoveryConfig config) : bpf_open_opts{.sz = sizeof(bpf_open_opts)}, savedSessions(MAX_SESSIONS) {
Discovery::Discovery(const DiscoveryConfig config) : savedSessions(DISCOVERY_MAX_SESSIONS) {
}

Discovery::~Discovery() {
unload();
}

int Discovery::run() {
if (bpf_obj == nullptr) {
if (!isLoaded()) {
return -1;
}

Expand All @@ -51,7 +68,7 @@ int Discovery::run() {

void Discovery::fetchEvents() {
DiscoveryEvent event;
while (bpf_map__lookup_and_delete_elem(bpf_obj->maps.eventsToUserspaceQueueMap, NULL, 0, &event, sizeof(event), BPF_ANY) == 0) {
while (bpf_map__lookup_and_delete_elem(discoverySkel->maps.eventsToUserspaceQueueMap, NULL, 0, &event, sizeof(event), BPF_ANY) == 0) {
handleNewEvent(std::move(event));
}
}
Expand All @@ -68,36 +85,41 @@ void Discovery::handleNewEvent(DiscoveryEvent event) {
void Discovery::handleNewDataEvent(DiscoveryEvent& event) {
DiscoverySavedBuffer savedBuffer;
auto lookup_result{bpf_map__lookup_elem(
bpf_obj->maps.savedBuffersMap, &event.dataKey, sizeof(DiscoverySavedBufferKey), &savedBuffer, sizeof(savedBuffer), BPF_ANY)};
discoverySkel->maps.savedBuffersMap,
&event.dataKey,
sizeof(DiscoverySavedBufferKey),
&savedBuffer,
sizeof(savedBuffer),
BPF_ANY)};
if (lookup_result != 0) {
return;
}

handleBufferLookupSuccess(savedBuffer, event);
}

void Discovery::handleBufferLookupSuccess(DiscoverySavedBuffer& saved_buffer, DiscoveryEvent& event) {
std::string_view buffer_view(saved_buffer.data, saved_buffer.length);
bpf_map__delete_elem(bpf_obj->maps.savedBuffersMap, &event.dataKey, sizeof(DiscoverySavedBufferKey), BPF_ANY);
void Discovery::handleBufferLookupSuccess(DiscoverySavedBuffer& savedBuffer, DiscoveryEvent& event) {
std::string_view bufferView(savedBuffer.data, savedBuffer.length);
bpf_map__delete_elem(discoverySkel->maps.savedBuffersMap, &event.dataKey, sizeof(DiscoverySavedBufferKey), BPF_ANY);

auto it{savedSessions.find(event.dataKey)};
if (it != savedSessions.end()) {
handleExistingSession(it, buffer_view, event);
handleExistingSession(it, bufferView, event);
return;
}

handleNewSession(buffer_view, event);
handleNewSession(bufferView, event);
}

void Discovery::handleExistingSession(SavedSessionsCacheType::iterator it, std::string_view& buffer_view, DiscoveryEvent& event) {
savedSessions.update(it, [buffer_view = std::move(buffer_view)](auto& session) { session.parser.parse(std::move(buffer_view)); });
if (it->second.parser.is_invalid_state()) {
void Discovery::handleExistingSession(SavedSessionsCacheType::iterator it, std::string_view& bufferView, DiscoveryEvent& event) {
savedSessions.update(it, [bufferView = std::move(bufferView)](auto& session) { session.parser.parse(std::move(bufferView)); });
if (it->second.parser.isInvalidState()) {
bpfDiscoveryDeleteSession(event.dataKey);
savedSessions.erase(it);
return;
}

if (!it->second.parser.is_finished()) {
if (!it->second.parser.isFinished()) {
// We expect more data buffers to come
return;
}
Expand All @@ -106,20 +128,20 @@ void Discovery::handleExistingSession(SavedSessionsCacheType::iterator it, std::
savedSessions.update(it, [](auto& session) { session.reset(); });
}

void Discovery::handleNewSession(std::string_view& buffer_view, DiscoveryEvent& event) {
void Discovery::handleNewSession(std::string_view& bufferView, DiscoveryEvent& event) {
Session session;
session.parser.parse(std::move(buffer_view));
if (session.parser.is_invalid_state()) {
session.parser.parse(std::move(bufferView));
if (session.parser.isInvalidState()) {
bpfDiscoveryDeleteSession(event.dataKey);
return;
}

if (!session.parser.is_finished() && !discoveryEventFlagsIsNoMoreData(event.flags)) {
if (!session.parser.isFinished() && !discoveryEventFlagsIsNoMoreData(event.flags)) {
saveSession(event.dataKey, std::move(session));
return;
}

if (!session.parser.is_finished()) {
if (!session.parser.isFinished()) {
return;
}

Expand All @@ -134,43 +156,54 @@ void Discovery::handleCloseEvent(DiscoveryEvent& event) {

int Discovery::bpfDiscoveryResumeCollecting() {
static uint32_t zero{0};
DiscoveryGlobalState shared_global_state;
DiscoveryGlobalState discoveryGlobalState{};
return bpf_map__update_elem(
bpf_obj->maps.globalStateMap, &zero, sizeof(zero), &shared_global_state, sizeof(shared_global_state), BPF_EXIST);
discoverySkel->maps.globalStateMap, &zero, sizeof(zero), &discoveryGlobalState, sizeof(discoveryGlobalState), BPF_EXIST);
}

int Discovery::bpfDiscoveryResetConfig() {
return bpfDiscoveryResumeCollecting();
}

bool Discovery::isLoaded() noexcept {
return discoverySkel != nullptr && loaded;
}

void Discovery::load() {
if (int res{ensure_core_btf(&bpf_open_opts)}) {
LIBBPF_OPTS(bpf_object_open_opts, openOpts);
discoverySkelOpenOpts = openOpts;

if (int res{ensure_core_btf(&openOpts)}) {
throw std::runtime_error("Failed to fetch necessary BTF for CO-RE: " + std::string(strerror(-res)));
}

bpf_obj = discovery_bpf__open_opts(&bpf_open_opts);
if (bpf_obj == nullptr) {
discoverySkel = discovery_bpf__open_opts(&openOpts);
if (discoverySkel == nullptr) {
throw std::runtime_error("Failed to open BPF object.");
}

if (int res{discovery_bpf__load(bpf_obj)}) {
if (int res{discovery_bpf__load(discoverySkel)}) {
throw std::runtime_error("Failed to load BPF object: " + std::to_string(res));
}

if (int res{discovery_bpf__attach(bpf_obj)}) {
if (int res{discovery_bpf__attach(discoverySkel)}) {
throw std::runtime_error("Failed to attach BPF object: " + std::to_string(res));
}

if (int res{bpfDiscoveryResumeCollecting()}) {
throw std::runtime_error("Failed to set config of BPF program: " + std::to_string(res));
}

loaded = true;
}

void Discovery::unload() noexcept {
if (bpf_obj != nullptr) {
discovery_bpf__destroy(bpf_obj);
stopRun();
loaded = false;
if (discoverySkel != nullptr) {
discovery_bpf__destroy(discoverySkel);
}
cleanup_core_btf(&bpf_open_opts);
cleanup_core_btf(&discoverySkelOpenOpts);
}

void Discovery::stopRun() {
Expand All @@ -181,12 +214,12 @@ void Discovery::handleSuccessfulParse(const Session& session, const DiscoverySes
printSession(session, meta);
}

void Discovery::saveSession(const DiscoverySavedSessionKey& session_key, const Session& session) {
savedSessions.insert(session_key, session);
void Discovery::saveSession(const DiscoverySavedSessionKey& sessionKey, const Session& session) {
savedSessions.insert(sessionKey, session);
}

int Discovery::bpfDiscoveryDeleteSession(const DiscoveryTrackedSessionKey& tracked_session_key) {
return bpf_map__delete_elem(bpf_obj->maps.trackedSessionsMap, &tracked_session_key, sizeof(tracked_session_key), BPF_ANY);
int Discovery::bpfDiscoveryDeleteSession(const DiscoveryTrackedSessionKey& trackedSessionKey) {
return bpf_map__delete_elem(discoverySkel->maps.trackedSessionsMap, &trackedSessionKey, sizeof(trackedSessionKey), BPF_ANY);
}

} // namespace ebpfdiscovery
27 changes: 0 additions & 27 deletions libebpfdiscovery/src/Log.cpp

This file was deleted.

10 changes: 5 additions & 5 deletions libebpfdiscoveryshared/headers/ebpfdiscoveryshared/Constants.h
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
// SPDX-License-Identifier: GPL-2.0
#pragma once

#define BUFFER_MAX_DATA_SIZE 10240 // 10 KiB
#define MAX_SESSIONS 8192
#define EVENT_QUEUE_SIZE 512
#define DISCOVERY_BUFFER_MAX_DATA_SIZE 10240 // 10 KiB
#define DISCOVERY_MAX_SESSIONS 8192
#define DISCOVERY_EVENT_QUEUE_SIZE 512

#define MAX_HTTP_REQUEST_LENGTH BUFFER_MAX_DATA_SIZE
#define MIN_HTTP_REQUEST_LENGTH 16
#define DISCOVERY_MAX_HTTP_REQUEST_LENGTH DISCOVERY_BUFFER_MAX_DATA_SIZE
#define DISCOVERY_MIN_HTTP_REQUEST_LENGTH 16
2 changes: 1 addition & 1 deletion libebpfdiscoveryshared/headers/ebpfdiscoveryshared/Types.h
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ struct DiscoverySockIPv6 {

struct DiscoverySavedBuffer {
__u32 length;
char data[BUFFER_MAX_DATA_SIZE];
char data[DISCOVERY_BUFFER_MAX_DATA_SIZE];
};

/*
Expand Down
30 changes: 30 additions & 0 deletions libebpfdiscoveryskel/src/DataFunctions.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// SPDX-License-Identifier: GPL-2.0
#pragma once

#include "ebpfdiscoveryshared/Constants.h"

#include "vmlinux.h"

#include <bpf/bpf_helpers.h>

__attribute__((always_inline)) inline static int dataProbeIsEqualToString(const char* src, const char* str, size_t len) {
char ch;
for (size_t i = 0; i < len; ++i) {
int result = bpf_probe_read(&ch, sizeof(char), (char*)src + i);
if (result < 0) {
return result;
}

if (ch != str[i] || ch == '\0') {
return i + 1;
}
}
return len;
}

__attribute__((always_inline)) inline static bool dataProbeIsBeginningOfHttpRequest(const char* ptr, size_t len) {
// We expect only GET and POST requests. We expect request URI's to start with a slash as absolute urls are mainly used in
// requests to proxy servers.
return len >= DISCOVERY_MIN_HTTP_REQUEST_LENGTH &&
(dataProbeIsEqualToString(ptr, "GET /", 5) || dataProbeIsEqualToString(ptr, "POST /", 6));
}
17 changes: 0 additions & 17 deletions libebpfdiscoveryskel/src/DataReading.h

This file was deleted.

Loading

0 comments on commit e6e10b5

Please sign in to comment.