strawberry/src/fleet.cpp
trvon 8411c70ba8
macOS: build and test fixes found re-validating on the Mac (57/57 green)
- fleet.cpp: HOST_NAME_MAX is Linux-only; use a 256-byte buffer (the
  POSIX/RFC 1035 limit gethostname() truncates to).
- test_replay: two dangling pointers - victim(run(...)) returned a pointer
  into a temporary report destroyed at the end of the statement. Passed on
  Linux by allocator luck; failed deterministically on macOS for every seed.
- test_yara_scanner: a brace initializer with a comma inside assert() (the
  macro splits it on macOS), and ::close needs <unistd.h> outside the
  Linux-only block.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 08:35:34 -07:00

60 lines
2 KiB
C++

#include "strawberry/fleet.hpp"
#include <climits>
#include <unistd.h>
#include "strawberry/hash_utils.hpp"
#include "strawberry/proc_read.hpp"
namespace strawberry::fleet {
namespace {
bool is_ws(char c) {
return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\v' || c == '\f';
}
std::string_view trim(std::string_view s) {
while (!s.empty() && is_ws(s.front())) s.remove_prefix(1);
while (!s.empty() && is_ws(s.back())) s.remove_suffix(1);
return s;
}
std::string hashed(std::string_view tag, std::string_view value) {
std::string s = "strawberry/node-uid/v1/";
s.append(tag);
s.push_back('\n');
s.append(value);
std::string hex = HashUtils::sha256_data(reinterpret_cast<const unsigned char*>(s.data()), s.size());
return hex.substr(0, kNodeUidHexLen);
}
} // namespace
std::string node_uid_from(std::string_view operator_id,
std::string_view machine_id,
std::string_view hostname) noexcept {
try {
const std::string_view op = trim(operator_id);
if (!op.empty()) return hashed("operator", op);
const std::string_view mid = trim(machine_id);
if (!mid.empty()) return hashed("machine", mid);
const std::string_view host = trim(hostname);
if (!host.empty()) return hashed("hostname", host);
return std::string(kNodeUnknown);
} catch (...) {
return std::string(kNodeUnknown);
}
}
std::string read_node_uid(std::string_view operator_id, const std::string& machine_id_path) {
const std::string machine_id = read_small_file(machine_id_path).value_or("");
// HOST_NAME_MAX is Linux-only (macOS has no such macro); 255 is the POSIX/RFC 1035 limit
// gethostname() truncates to on every platform we build for.
char buf[256] = {0};
if (gethostname(buf, sizeof(buf)) != 0) buf[0] = '\0';
buf[sizeof(buf) - 1] = '\0';
return node_uid_from(operator_id, machine_id, std::string_view(buf));
}
} // namespace strawberry::fleet