diff --git a/collector/lib/AbortHandler.cpp b/collector/lib/AbortHandler.cpp index ff108df782..2c2dbafa08 100644 --- a/collector/lib/AbortHandler.cpp +++ b/collector/lib/AbortHandler.cpp @@ -74,8 +74,9 @@ extern "C" void AbortHandler(int signum) { } } - if (n_frames == max_frames) + if (n_frames == max_frames) { write(STDERR_FILENO, "[truncated]\n", 13); + } // Write a message to stderr using only reentrant functions. num_bytes = snprintf(message_buffer, message_buffer_size, diff --git a/collector/lib/CollectorConfig.cpp b/collector/lib/CollectorConfig.cpp index 965ec60727..a876c872f7 100644 --- a/collector/lib/CollectorConfig.cpp +++ b/collector/lib/CollectorConfig.cpp @@ -237,8 +237,9 @@ void CollectorConfig::InitCollectorConfig(CollectorArgs* args) { } for (const std::string& str : ignored_networks.value()) { - if (str.empty()) + if (str.empty()) { continue; + } std::optional net = IPNet::parse(str); @@ -251,8 +252,9 @@ void CollectorConfig::InitCollectorConfig(CollectorArgs* args) { } for (const std::string& str : non_aggregated_networks.value()) { - if (str.empty()) + if (str.empty()) { continue; + } std::optional net = IPNet::parse(str); diff --git a/collector/lib/CollectorService.cpp b/collector/lib/CollectorService.cpp index 4b41300d9d..7c7e8faa1a 100644 --- a/collector/lib/CollectorService.cpp +++ b/collector/lib/CollectorService.cpp @@ -130,7 +130,9 @@ void CollectorService::RunForever() { CLOG(INFO) << "Shutting down collector."; - if (net_status_notifier) net_status_notifier->Stop(); + if (net_status_notifier) { + net_status_notifier->Stop(); + } // Shut down these first since they access the system inspector object. exporter.stop(); server.close(); diff --git a/collector/lib/CollectorStatsExporter.cpp b/collector/lib/CollectorStatsExporter.cpp index a78a4d3b8c..5d5306a123 100644 --- a/collector/lib/CollectorStatsExporter.cpp +++ b/collector/lib/CollectorStatsExporter.cpp @@ -241,12 +241,21 @@ void CollectorStatsExporter::run() { nUserspace += userspace; - if (counters.userspace) counters.userspace->Set(userspace); + if (counters.userspace) { + counters.userspace->Set(userspace); + } - if (counters.parse_micros_total) counters.parse_micros_total->Set(parse_micros_total); - if (counters.process_micros_total) counters.process_micros_total->Set(process_micros_total); + if (counters.parse_micros_total) { + counters.parse_micros_total->Set(parse_micros_total); + } - if (counters.parse_micros_avg) counters.parse_micros_avg->Set(userspace ? parse_micros_total / userspace : 0); + if (counters.process_micros_total) { + counters.process_micros_total->Set(process_micros_total); + } + + if (counters.parse_micros_avg) { + counters.parse_micros_avg->Set(userspace ? parse_micros_total / userspace : 0); + } } userspaceEvents->Set(nUserspace); diff --git a/collector/lib/Containers.h b/collector/lib/Containers.h index 33960614c5..271fac9a6e 100644 --- a/collector/lib/Containers.h +++ b/collector/lib/Containers.h @@ -22,7 +22,9 @@ using MappedType = WithConst; template ValueType* Find(C& container, const typename C::key_type& key) { auto it = container.find(key); - if (it == container.end()) return nullptr; + if (it == container.end()) { + return nullptr; + } return &*it; } @@ -37,7 +39,9 @@ bool Contains(const C& container, const typename C::key_type& key) { template MappedType* Lookup(M& map, const typename M::key_type& key) { auto* val = Find(map, key); - if (!val) return nullptr; + if (!val) { + return nullptr; + } return &val->second; } diff --git a/collector/lib/DuplexGRPC.h b/collector/lib/DuplexGRPC.h index 89df5c7c12..425488328f 100644 --- a/collector/lib/DuplexGRPC.h +++ b/collector/lib/DuplexGRPC.h @@ -506,7 +506,9 @@ class DuplexClient : public virtual IDuplexClient { while (result && op_res.op != op_desc.op) { result = ProcessSingle(nullptr, deadline, &op_res); } - if (!result) return result; + if (!result) { + return result; + } return Result(op_res.ok); } @@ -561,14 +563,18 @@ class DuplexClientReaderWriter : public DuplexClientWriter { auto deadline = ToDeadline(time_spec); auto result = PollAll(DuplexClient::CAN_READ, deadline); - if (!result) return result; + if (!result) { + return result; + } // We can read, but the read buffer is not valid -> there has been an error. This is the last read. if (!read_buf_valid_) { return Result(Status::ERROR); } - if (obj) *obj = std::move(read_buf_); + if (obj) { + *obj = std::move(read_buf_); + } ReadNext(); return Result(Status::OK); @@ -666,7 +672,9 @@ class DuplexClientReaderWriter : public DuplexClientWriter { this->SetFlags(Done(Op::SHUTDOWN)); } - if (flags_out) *flags_out = this->flags_; + if (flags_out) { + *flags_out = this->flags_; + } return Result(next_status); } diff --git a/collector/lib/FileSystem.h b/collector/lib/FileSystem.h index ee4acf8be4..3d36cabc98 100644 --- a/collector/lib/FileSystem.h +++ b/collector/lib/FileSystem.h @@ -93,14 +93,18 @@ class DirHandle : public ResourceWrapper { DirHandle(FDHandle&& fd) : ResourceWrapper(fdopendir(fd.release())) {} FDHandle openat(const char* path, int mode) const { - if (!valid()) return -1; + if (!valid()) { + return -1; + } return ::openat(dirfd(get()), path, mode); } int fd() const { return ::dirfd(get()); } struct dirent* read() { - if (!valid()) return nullptr; + if (!valid()) { + return nullptr; + } return readdir(get()); } diff --git a/collector/lib/NRadix.cpp b/collector/lib/NRadix.cpp index f3966962fc..911be3b140 100644 --- a/collector/lib/NRadix.cpp +++ b/collector/lib/NRadix.cpp @@ -61,14 +61,18 @@ bool NRadixTree::Insert(const IPNet& network) const { next = node->left_; } - if (!next) break; + if (!next) { + break; + } bit >>= 1; node = next; if (bit == 0) { // We have walked 128 bits, stop. - if (++i >= Address::kU64MaxLen) break; + if (++i >= Address::kU64MaxLen) { + break; + } // Reset and move to lower part. bit = 0x8000000000000000ULL; @@ -105,7 +109,9 @@ bool NRadixTree::Insert(const IPNet& network) const { if (bit == 0) { // We have walked all 128 bits, stop. - if (++i >= Address::kU64MaxLen) break; + if (++i >= Address::kU64MaxLen) { + break; + } bit = 0x8000000000000000ULL; if (network.bits() >= 64) { @@ -120,7 +126,9 @@ bool NRadixTree::Insert(const IPNet& network) const { } IPNet NRadixTree::Find(const IPNet& network) const { - if (network.IsNull()) return {}; + if (network.IsNull()) { + return {}; + } if (network.bits() == 0) { CLOG(ERROR) << "Cannot handle CIDR " << network << " with /0, in network tree"; @@ -148,7 +156,9 @@ IPNet NRadixTree::Find(const IPNet& network) const { // All network bits are traversed. If a supernet was found along the way, `ret` holds it, // else there does not exist any supernet containing the search network/address. - if (!(*net_mask_p & bit)) break; + if (!(*net_mask_p & bit)) { + break; + } bit >>= 1; @@ -177,7 +187,9 @@ IPNet NRadixTree::Find(const Address& addr) const { } void getAll(nRadixNode* node, std::vector& ret) { - if (!node) return; + if (!node) { + return; + } if (node->value_) { ret.push_back(*node->value_); @@ -199,14 +211,20 @@ bool isAnyIPNetSubsetUtil(Address::Family family, const nRadixNode* n1, const nR // If we have found networks from both trees belonging to same family, we have the answer. if (containing_net && contained_net) { if (family == Address::Family::UNKNOWN) { - if (containing_net->family() == contained_net->family()) return true; + if (containing_net->family() == contained_net->family()) { + return true; + } } else { - if (containing_net->family() == family && contained_net->family() == family) return true; + if (containing_net->family() == family && contained_net->family() == family) { + return true; + } } } // There are no more networks down the path in second tree, so stop. - if (!n2) return false; + if (!n2) { + return false; + } if (n1 && n1->value_) { containing_net = n1->value_; diff --git a/collector/lib/NRadix.h b/collector/lib/NRadix.h index 606b905b73..5cec2663ae 100644 --- a/collector/lib/NRadix.h +++ b/collector/lib/NRadix.h @@ -54,7 +54,9 @@ struct nRadixNode { } nRadixNode& operator=(const nRadixNode& other) { - if (this == &other) return *this; + if (this == &other) { + return *this; + } auto* new_node = new nRadixNode(other); std::swap(*new_node, *this); delete new_node; @@ -92,7 +94,9 @@ class NRadixTree { } NRadixTree& operator=(const NRadixTree& other) { - if (this == &other) return *this; + if (this == &other) { + return *this; + } delete root_; // This calls the node copy constructor which in turn copies all the nodes. root_ = new nRadixNode(*other.root_); diff --git a/collector/lib/NetworkConnection.h b/collector/lib/NetworkConnection.h index bb1a9f91be..e51486fe6b 100644 --- a/collector/lib/NetworkConnection.h +++ b/collector/lib/NetworkConnection.h @@ -227,7 +227,9 @@ class IPNet { } size_t Hash() const { - if (is_addr_) return HashAll(address_.array(), mask_, bits_); + if (is_addr_) { + return HashAll(address_.array(), mask_, bits_); + } return HashAll(mask_, bits_); } @@ -411,11 +413,19 @@ inline bool IsRelevantEndpoint(const Endpoint& ep) { // operating systems adhere to the IANA-recommended range. Therefore, the return value is not a bool, but instead an // int which indicates the confidence that the port is in fact ephemeral. inline int IsEphemeralPort(uint16_t port) { - if (port >= 49152) return 4; // IANA range - if (port >= 32768) return 3; // Modern Linux kernel range - if (port >= 1025 && port <= 5000) return 2; // FreeBSD (partial) + Windows <=XP range - if (port == 1024) return 1; // FreeBSD - return 0; // not ephemeral according to any range + if (port >= 49152) { + return 4; // IANA range + } + if (port >= 32768) { + return 3; // Modern Linux kernel range + } + if (port >= 1025 && port <= 5000) { + return 2; // FreeBSD (partial) + Windows <=XP range + } + if (port == 1024) { + return 1; // FreeBSD + } + return 0; // not ephemeral according to any range } // PrivateIPv4Networks return private IPv4 networks. diff --git a/collector/lib/NetworkConnectionInfoServiceComm.cpp b/collector/lib/NetworkConnectionInfoServiceComm.cpp index 0f822a3b5e..3c9353b9dd 100644 --- a/collector/lib/NetworkConnectionInfoServiceComm.cpp +++ b/collector/lib/NetworkConnectionInfoServiceComm.cpp @@ -38,13 +38,16 @@ bool NetworkConnectionInfoServiceComm::WaitForConnectionReady(const std::functio void NetworkConnectionInfoServiceComm::TryCancel() { WITH_LOCK(context_mutex_) { - if (context_) context_->TryCancel(); + if (context_) { + context_->TryCancel(); + } } } std::unique_ptr> NetworkConnectionInfoServiceComm::PushNetworkConnectionInfoOpenStream(std::function receive_func) { - if (!context_) + if (!context_) { ResetClientContext(); + } if (channel_) { return DuplexClient::CreateWithReadCallback( diff --git a/collector/lib/NetworkSignalHandler.cpp b/collector/lib/NetworkSignalHandler.cpp index 9aab28ddd6..9e35003960 100644 --- a/collector/lib/NetworkSignalHandler.cpp +++ b/collector/lib/NetworkSignalHandler.cpp @@ -55,7 +55,9 @@ NetworkSignalHandler::NetworkSignalHandler(sinsp* inspector, std::shared_ptr NetworkSignalHandler::GetConnection(sinsp_evt* evt) { auto* fd_info = evt->get_fd_info(); - if (!fd_info) return std::nullopt; + if (!fd_info) { + return std::nullopt; + } // With collect_connection_status_ set, we can prevent reporting of asynchronous // connections which fail. @@ -117,13 +119,17 @@ std::optional NetworkSignalHandler::GetConnection(sinsp_evt* evt) { const Endpoint* remote = is_server ? &client : &server; const std::string* container_id = event_extractor_->get_container_id(evt); - if (!container_id) return std::nullopt; + if (!container_id) { + return std::nullopt; + } return {Connection(*container_id, *local, *remote, l4proto, is_server)}; } SignalHandler::Result NetworkSignalHandler::HandleSignal(sinsp_evt* evt) { auto modifier = modifiers[evt->get_type()]; - if (modifier == Modifier::INVALID) return SignalHandler::IGNORED; + if (modifier == Modifier::INVALID) { + return SignalHandler::IGNORED; + } auto result = GetConnection(evt); if (!result.has_value() || !IsRelevantConnection(*result)) { diff --git a/collector/lib/NetworkStatusNotifier.cpp b/collector/lib/NetworkStatusNotifier.cpp index d944b30b93..d6f93c1567 100644 --- a/collector/lib/NetworkStatusNotifier.cpp +++ b/collector/lib/NetworkStatusNotifier.cpp @@ -317,7 +317,9 @@ void NetworkStatusNotifier::RunSingleAfterglow(IDuplexClientWriterm_args.begin(); it != system_inspector_threadinfo_->m_args.end();) { args << *it++; - if (it != system_inspector_threadinfo_->m_args.end()) args << " "; + if (it != system_inspector_threadinfo_->m_args.end()) { + args << " "; + } } return args.str(); } diff --git a/collector/lib/ProcessSignalFormatter.cpp b/collector/lib/ProcessSignalFormatter.cpp index 4b923a0fcc..c56edff95f 100644 --- a/collector/lib/ProcessSignalFormatter.cpp +++ b/collector/lib/ProcessSignalFormatter.cpp @@ -37,11 +37,15 @@ static EventMap process_signals = { }; std::string extract_proc_args(sinsp_threadinfo* tinfo) { - if (tinfo->m_args.empty()) return ""; + if (tinfo->m_args.empty()) { + return ""; + } std::ostringstream args; for (auto it = tinfo->m_args.begin(); it != tinfo->m_args.end();) { args << *it++; - if (it != tinfo->m_args.end()) args << " "; + if (it != tinfo->m_args.end()) { + args << " "; + } } return args.str(); } @@ -67,7 +71,9 @@ const SignalStreamMessage* ProcessSignalFormatter::ToProtoMessage(sinsp_evt* eve } ProcessSignal* process_signal = CreateProcessSignal(event); - if (!process_signal) return nullptr; + if (!process_signal) { + return nullptr; + } Signal* signal = Allocate(); signal->set_allocated_process_signal(process_signal); @@ -86,7 +92,9 @@ const SignalStreamMessage* ProcessSignalFormatter::ToProtoMessage(sinsp_threadin } ProcessSignal* process_signal = CreateProcessSignal(tinfo); - if (!process_signal) return nullptr; + if (!process_signal) { + return nullptr; + } Signal* signal = Allocate(); signal->set_allocated_process_signal(process_signal); @@ -121,14 +129,22 @@ ProcessSignal* ProcessSignalFormatter::CreateProcessSignal(sinsp_evt* event) { } // set process arguments - if (const char* args = event_extractor_->get_proc_args(event)) signal->set_args(args); + if (const char* args = event_extractor_->get_proc_args(event)) { + signal->set_args(args); + } // set pid - if (const int64_t* pid = event_extractor_->get_pid(event)) signal->set_pid(*pid); + if (const int64_t* pid = event_extractor_->get_pid(event)) { + signal->set_pid(*pid); + } // set user and group id credentials - if (const uint32_t* uid = event_extractor_->get_uid(event)) signal->set_uid(*uid); - if (const uint32_t* gid = event_extractor_->get_gid(event)) signal->set_gid(*gid); + if (const uint32_t* uid = event_extractor_->get_uid(event)) { + signal->set_uid(*uid); + } + if (const uint32_t* gid = event_extractor_->get_gid(event)) { + signal->set_gid(*gid); + } // set time auto timestamp = Allocate(); @@ -256,7 +272,9 @@ bool ProcessSignalFormatter::ValidateProcessDetails(sinsp_evt* event) { int ProcessSignalFormatter::GetTotalStringLength(const std::vector& lineage) { int totalStringLength = 0; - for (LineageInfo l : lineage) totalStringLength += l.parent_exec_file_path().size(); + for (LineageInfo l : lineage) { + totalStringLength += l.parent_exec_file_path().size(); + } return totalStringLength; } @@ -271,17 +289,25 @@ void ProcessSignalFormatter::CountLineage(const std::vector& lineag void ProcessSignalFormatter::GetProcessLineage(sinsp_threadinfo* tinfo, std::vector& lineage) { - if (tinfo == NULL) return; + if (tinfo == NULL) { + return; + } sinsp_threadinfo* mt = NULL; if (tinfo->is_main_thread()) { mt = tinfo; } else { mt = tinfo->get_main_thread(); - if (mt == NULL) return; + if (mt == NULL) { + return; + } } sinsp_threadinfo::visitor_func_t visitor = [this, &lineage](sinsp_threadinfo* pt) { - if (pt == NULL) return false; - if (pt->m_pid == 0) return false; + if (pt == NULL) { + return false; + } + if (pt->m_pid == 0) { + return false; + } // // Collection of process lineage information should stop at the container @@ -302,7 +328,9 @@ void ProcessSignalFormatter::GetProcessLineage(sinsp_threadinfo* tinfo, return false; } - if (pt->m_vpid == -1) return false; + if (pt->m_vpid == -1) { + return false; + } // Collapse parent child processes that have the same path if (lineage.empty() || (lineage.back().parent_exec_file_path() != pt->m_exepath)) { @@ -313,7 +341,9 @@ void ProcessSignalFormatter::GetProcessLineage(sinsp_threadinfo* tinfo, } // Limit max number of ancestors - if (lineage.size() >= 10) return false; + if (lineage.size() >= 10) { + return false; + } return true; }; diff --git a/collector/lib/ProcfsScraper.cpp b/collector/lib/ProcfsScraper.cpp index ecaf7e6c29..b7b075c93b 100644 --- a/collector/lib/ProcfsScraper.cpp +++ b/collector/lib/ProcfsScraper.cpp @@ -24,12 +24,16 @@ namespace { // rep_find applies find n times, always advancing past the found character in each subsequent application. std::string_view::size_type rep_find(int n, std::string_view str, char c) { - if (n <= 0) return std::string_view::npos; + if (n <= 0) { + return std::string_view::npos; + } std::string_view::size_type pos = 0; while (--n > 0) { pos = str.find(c, pos); - if (pos == std::string_view::npos) return std::string_view::npos; + if (pos == std::string_view::npos) { + return std::string_view::npos; + } pos++; } return str.find(c, pos); @@ -37,7 +41,9 @@ std::string_view::size_type rep_find(int n, std::string_view str, char c) { // nextfield advances to the next field in a space-delimited string. const char* nextfield(const char* p, const char* endp) { - while (p < endp && *p && !std::isspace(*p)) p++; + while (p < endp && *p && !std::isspace(*p)) { + p++; + } while (p < endp && *p && std::isspace(*++p)) ; return (p < endp && *p) ? p : nullptr; @@ -58,18 +64,28 @@ const char* rep_nextfield(int n, const char* p, const char* endp) { bool ReadINode(int dirfd, const char* path, const char* prefix, ino_t* inode) { char linkbuf[64]; ssize_t nread = readlinkat(dirfd, path, linkbuf, sizeof(linkbuf)); - if (nread <= 0 || nread >= ssizeof(linkbuf) - 1) return false; + if (nread <= 0 || nread >= ssizeof(linkbuf) - 1) { + return false; + } linkbuf[nread] = '\0'; - if (linkbuf[nread - 1] != ']') return false; + if (linkbuf[nread - 1] != ']') { + return false; + } size_t prefix_len = std::strlen(prefix); - if (std::strncmp(linkbuf, prefix, prefix_len) != 0) return false; - if (std::strncmp(linkbuf + prefix_len, ":[", 2) != 0) return false; + if (std::strncmp(linkbuf, prefix, prefix_len) != 0) { + return false; + } + if (std::strncmp(linkbuf + prefix_len, ":[", 2) != 0) { + return false; + } // Parse inode value as decimal char* endp; uintmax_t parsed = std::strtoumax(linkbuf + prefix_len + 2, &endp, 10); - if (*endp != ']') return false; + if (*endp != ']') { + return false; + } *inode = static_cast(parsed); return true; } @@ -113,10 +129,14 @@ bool GetSocketINodes(int dirfd, uint64_t pid, UnorderedSet* sock_ino } while (auto curr = fd_dir.read()) { - if (!std::isdigit(curr->d_name[0])) continue; // only look at fd entries, ignore '.' and '..'. + if (!std::isdigit(curr->d_name[0])) { + continue; // only look at fd entries, ignore '.' and '..'. + } ino_t inode; - if (!ReadINode(fd_dir.fd(), curr->d_name, "socket", &inode)) continue; // ignore non-socket fds + if (!ReadINode(fd_dir.fd(), curr->d_name, "socket", &inode)) { + continue; // ignore non-socket fds + } sock_inodes->emplace(inode, pid); } @@ -128,15 +148,21 @@ bool GetSocketINodes(int dirfd, uint64_t pid, UnorderedSet* sock_ino // the cgroup. std::optional GetContainerID(int dirfd) { FileHandle cgroups_file(FDHandle(openat(dirfd, "cgroup", O_RDONLY)), "r"); - if (!cgroups_file.valid()) return {}; + if (!cgroups_file.valid()) { + return {}; + } thread_local char* linebuf; thread_local size_t linebuf_cap; ssize_t line_len; while ((line_len = getline(&linebuf, &linebuf_cap, cgroups_file.get())) != -1) { - if (!line_len) continue; - if (linebuf[line_len - 1] == '\n') line_len--; + if (!line_len) { + continue; + } + if (linebuf[line_len - 1] == '\n') { + line_len--; + } std::string_view line(linebuf, line_len); auto short_container_id = ExtractContainerID(line); @@ -154,13 +180,17 @@ std::optional GetContainerID(int dirfd) { // IsHexChar checks if the given character is an (uppercase) hexadecimal character. bool IsHexChar(char c) { - if (std::isdigit(c)) return true; + if (std::isdigit(c)) { + return true; + } return c >= 'A' && c <= 'F'; } // HexCharToVal returns the numeric value of a single (uppercase) hexadecimal digit. unsigned char HexCharToVal(char c) { - if (std::isdigit(c)) return c - '0'; + if (std::isdigit(c)) { + return c - '0'; + } return 10 + (c - 'A'); } @@ -176,7 +206,9 @@ int ReadHexBytes(const char* p, const char* endp, void* buf, int chunk_size, int for (; i < num_bytes && p < endp - 2; i++) { char high = *p++; char low = *p++; - if (!IsHexChar(high) || !IsHexChar(low)) break; + if (!IsHexChar(high) || !IsHexChar(low)) { + break; + } *bbuf++ = HexCharToVal(high) << 4 | HexCharToVal(low); if (reverse && i % chunk_size == chunk_size - 1) { @@ -217,13 +249,19 @@ const char* ParseEndpoint(const char* p, const char* endp, Address::Family famil int addr_len = Address::Length(family); int nread = ReadHexBytes(p, endp, addr_data.data(), 4, addr_len / 4, needs_byteorder_swap); - if (nread != addr_len) return nullptr; + if (nread != addr_len) { + return nullptr; + } p += nread * 2; - if (*p++ != ':') return nullptr; + if (*p++ != ':') { + return nullptr; + } uint16_t port; nread = ReadHexBytes(p, endp, &port, sizeof(port), 1, needs_byteorder_swap); - if (nread != sizeof(port)) return nullptr; + if (nread != sizeof(port)) { + return nullptr; + } p += nread * 2; *endpoint = Endpoint(Address(family, addr_data), port); @@ -233,35 +271,53 @@ const char* ParseEndpoint(const char* p, const char* endp, Address::Family famil // ParseConnLine parses an entire line in the `net/tcp[6]` file. bool ParseConnLine(const char* p, const char* endp, Address::Family family, ConnLineData* data) { // Strip leading spaces. - while (std::isspace(*p)) p++; + while (std::isspace(*p)) { + p++; + } // 0: sl p = nextfield(p, endp); - if (!p) return false; + if (!p) { + return false; + } // 1: local_address p = ParseEndpoint(p, endp, family, &data->local); - if (!p) return false; + if (!p) { + return false; + } p = nextfield(p, endp); - if (!p) return false; + if (!p) { + return false; + } // 2: rem_address p = ParseEndpoint(p, endp, family, &data->remote); - if (!p) return false; + if (!p) { + return false; + } p = nextfield(p, endp); - if (!p) return false; + if (!p) { + return false; + } // 3: st int nread = ReadHexBytes(p, endp, &data->state, 1, 1, false); - if (nread != 1) return false; + if (nread != 1) { + return false; + } p += nread * 2; p = rep_nextfield(6, p, endp); - if (!p) return false; + if (!p) { + return false; + } // 9: inode char* parse_endp; uintmax_t inode = strtoumax(p, &parse_endp, 10); - if (*parse_endp && !std::isspace(*parse_endp)) return false; + if (*parse_endp && !std::isspace(*parse_endp)) { + return false; + } data->inode = static_cast(inode); return true; @@ -270,11 +326,15 @@ bool ParseConnLine(const char* p, const char* endp, Address::Family family, Conn // LocalIsServer returns true if the connection between local and remote looks like the local end is the server (taking // the set of listening endpoints into account), and false otherwise. bool LocalIsServer(const Endpoint& local, const Endpoint& remote, const UnorderedSet& listen_endpoints) { - if (Contains(listen_endpoints, local)) return true; + if (Contains(listen_endpoints, local)) { + return true; + } // Check if we are listening on the given port on any interface. Endpoint local_any(Address::Any(local.address().family()), local.port()); - if (Contains(listen_endpoints, local_any)) return true; + if (Contains(listen_endpoints, local_any)) { + return true; + } // We didn't find an entry for listening on this address, but closing a listen socket does not terminate established // connections. We hence have to resort to inspecting the port number to see which one seems more likely to be @@ -287,13 +347,17 @@ bool ReadConnectionsFromFile(Address::Family family, L4Proto l4proto, std::FILE* UnorderedMap* connections, UnorderedMap* listen_endpoints) { char line[512]; - if (!std::fgets(line, sizeof(line), f)) return false; // ignore the first *header) line. + if (!std::fgets(line, sizeof(line), f)) { + return false; // ignore the first *header) line. + } UnorderedSet all_listen_endpoints; while (std::fgets(line, sizeof(line), f)) { ConnLineData data; - if (!ParseConnLine(line, line + sizeof(line), family, &data)) continue; + if (!ParseConnLine(line, line + sizeof(line), family, &data)) { + continue; + } if (data.state == TCP_LISTEN) { // listen socket all_listen_endpoints.insert(data.local); if (data.inode && listen_endpoints) { @@ -307,7 +371,9 @@ bool ReadConnectionsFromFile(Address::Family family, L4Proto l4proto, std::FILE* continue; } - if (!data.inode) continue; // socket was closed or otherwise unavailable + if (!data.inode) { + continue; // socket was closed or otherwise unavailable + } auto& conn_info = (*connections)[data.inode]; conn_info.local = data.local; conn_info.remote = data.remote; @@ -367,15 +433,21 @@ void ResolveSocketInodes(const SocketsByContainer& sockets_by_container, const C const auto& container_id = container_sockets.first; for (const auto& netns_sockets : container_sockets.second) { const auto* ns_network_data = Lookup(conns_by_ns, netns_sockets.first); - if (!ns_network_data) continue; + if (!ns_network_data) { + continue; + } for (const auto& socket : netns_sockets.second) { if (const auto* conn = Lookup(ns_network_data->connections, socket.inode())) { Connection connection(container_id, conn->local, conn->remote, conn->l4proto, conn->is_server); - if (!IsRelevantConnection(connection)) continue; + if (!IsRelevantConnection(connection)) { + continue; + } connections->push_back(std::move(connection)); } else if (listen_endpoints) { if (const auto* ep = Lookup(ns_network_data->listen_endpoints, socket.inode())) { - if (!IsRelevantEndpoint(ep->endpoint)) continue; + if (!IsRelevantEndpoint(ep->endpoint)) { + continue; + } std::shared_ptr process; @@ -408,7 +480,9 @@ bool ReadContainerConnections(const char* proc_path, std::shared_ptrd_name[0])) continue; // only look for entries + if (!std::isdigit(curr->d_name[0])) { + continue; // only look for entries + } long long pid = strtoll(curr->d_name, 0, 10); FDHandle dirfd = procdir.openat(curr->d_name, O_RDONLY); @@ -482,8 +556,9 @@ bool ReadProcessExe(const char* process_id, int dirfd, std::string& comm, std::s comm = exe_path = buffer; - if (buffer[0] == '/') + if (buffer[0] == '/') { comm = strrchr(buffer, '/') + 1; + } return true; } diff --git a/collector/lib/RateLimit.cpp b/collector/lib/RateLimit.cpp index 785f3235d0..d65d6b3630 100644 --- a/collector/lib/RateLimit.cpp +++ b/collector/lib/RateLimit.cpp @@ -22,15 +22,21 @@ int64_t Limiter::Tokens(TokenBucket* b) { } bool Limiter::AllowN(TokenBucket* b, int64_t n) { - if (!b->last_time) fill_bucket(b); + if (!b->last_time) { + fill_bucket(b); + } int64_t refill = refill_count(b); b->tokens += refill * burst_size_; b->last_time += refill * refill_time_; - if (b->tokens >= burst_size_) fill_bucket(b); + if (b->tokens >= burst_size_) { + fill_bucket(b); + } - if (n > b->tokens) return false; + if (n > b->tokens) { + return false; + } b->tokens -= n; diff --git a/collector/lib/StoppableThread.h b/collector/lib/StoppableThread.h index dc1ea80ef1..4a2151a6f1 100644 --- a/collector/lib/StoppableThread.h +++ b/collector/lib/StoppableThread.h @@ -18,7 +18,9 @@ class StoppableThread { public: template bool Start(Args&&... args) { - if (!prepareStart()) return false; + if (!prepareStart()) { + return false; + } return doStart(new std::thread(std::forward(args)...)); } void Stop(); diff --git a/collector/lib/Utility.cpp b/collector/lib/Utility.cpp index 792d6582e0..4cb69bb6bc 100644 --- a/collector/lib/Utility.cpp +++ b/collector/lib/Utility.cpp @@ -96,31 +96,37 @@ std::string Base64Decode(std::string const& encoded_string) { char_array_4[i++] = encoded_string[in_]; in_++; if (i == 4) { - for (i = 0; i < 4; i++) + for (i = 0; i < 4; i++) { char_array_4[i] = base64_chars.find(char_array_4[i]); + } char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; - for (i = 0; (i < 3); i++) + for (i = 0; (i < 3); i++) { ret += char_array_3[i]; + } i = 0; } } if (i) { - for (j = i; j < 4; j++) + for (j = i; j < 4; j++) { char_array_4[j] = 0; + } - for (j = 0; j < 4; j++) + for (j = 0; j < 4; j++) { char_array_4[j] = base64_chars.find(char_array_4[j]); + } char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; - for (j = 0; (j < i - 1); j++) ret += char_array_3[j]; + for (j = 0; (j < i - 1); j++) { + ret += char_array_3[j]; + } } return ret; @@ -128,7 +134,9 @@ std::string Base64Decode(std::string const& encoded_string) { std::string GetHostPath(const std::string& file) { const char* host_root = std::getenv("COLLECTOR_HOST_ROOT"); - if (!host_root) host_root = ""; + if (!host_root) { + host_root = ""; + } std::string host_file(host_root); // Check if we are joining paths without a seperator, if (host_file.length() && file.length() && @@ -141,7 +149,9 @@ std::string GetHostPath(const std::string& file) { const char* GetSNIHostname() { const char* hostname = std::getenv("SNI_HOSTNAME"); - if (hostname && *hostname) return hostname; + if (hostname && *hostname) { + return hostname; + } // if the environment variable is not defined, then default // to sensor.stackrox diff --git a/collector/lib/system-inspector/Service.cpp b/collector/lib/system-inspector/Service.cpp index 39fefb10dd..99b9fd2cbf 100644 --- a/collector/lib/system-inspector/Service.cpp +++ b/collector/lib/system-inspector/Service.cpp @@ -141,7 +141,9 @@ sinsp_evt* Service::GetNext() { auto parse_start = NowMicros(); auto res = inspector_->next(&event); - if (res != SCAP_SUCCESS || event == nullptr) return nullptr; + if (res != SCAP_SUCCESS || event == nullptr) { + return nullptr; + } #ifdef TRACE_SINSP_EVENTS // Do not allow to change sinsp events tracing at runtime, as the output @@ -157,7 +159,9 @@ sinsp_evt* Service::GetNext() { } #endif - if (event->get_category() & EC_INTERNAL) return nullptr; + if (event->get_category() & EC_INTERNAL) { + return nullptr; + } HostInfo& host_info = HostInfo::Instance(); @@ -269,7 +273,6 @@ void Service::Run(const std::atomic& control) { if (!signal_handler.ShouldHandle(evt)) { continue; } - LogUnreasonableEventTime(process_start, evt); auto result = signal_handler.handler->HandleSignal(evt); if (result == SignalHandler::NEEDS_REFRESH) { @@ -340,7 +343,9 @@ void Service::CleanUp() { auto& request = pending_process_requests_.front(); auto callback = request.second.lock(); - if (callback) (*callback)(0); + if (callback) { + (*callback)(0); + } pending_process_requests_.pop_front(); } @@ -349,7 +354,9 @@ void Service::CleanUp() { bool Service::GetStats(system_inspector::Stats* stats) const { std::lock_guard libsinsp_lock(libsinsp_mutex_); std::lock_guard running_lock(running_mutex_); - if (!running_ || !inspector_) return false; + if (!running_ || !inspector_) { + return false; + } scap_stats kernel_stats; std::shared_ptr userspace_stats; @@ -364,8 +371,9 @@ bool Service::GetStats(system_inspector::Stats* stats) const { stats->nPreemptions = kernel_stats.n_preemptions; stats->nThreadCacheSize = inspector_->m_thread_manager->get_thread_count(); - if (userspace_stats != nullptr) + if (userspace_stats != nullptr) { stats->nDropsThreadCache = userspace_stats->m_n_drops_full_threadtable; + } return true; } diff --git a/collector/test/ConnTrackerTest.cpp b/collector/test/ConnTrackerTest.cpp index 84a40ff93c..83e07445a6 100644 --- a/collector/test/ConnTrackerTest.cpp +++ b/collector/test/ConnTrackerTest.cpp @@ -1223,16 +1223,18 @@ TEST(ConnTrackerTest, TestUpdateOldStateActiveExpiredConnectionRemovedFromOldSta void GetNextAddress(int address_parts[4], int& port) { for (int i = 0; i < 4; i++) { address_parts[i]++; - if (address_parts[i] < 256) + if (address_parts[i] < 256) { break; - else { + } else { address_parts[i] = 0; } } if (address_parts[3] == 256) { port++; - for (int i = 0; i < 4; i++) address_parts[i] = 0; + for (int i = 0; i < 4; i++) { + address_parts[i] = 0; + } } } @@ -1258,9 +1260,13 @@ void CreateFakeState(ConnMap& afterglow_state, int num_endpoints, int num_connec afterglow_state.insert({tempConn1, ConnStatus(time_micros, false)}); afterglow_state.insert({tempConn2, ConnStatus(time_micros, false)}); connection_idx += 2; - if (connection_idx > num_connections) break; + if (connection_idx > num_connections) { + break; + } + } + if (connection_idx > num_connections) { + break; } - if (connection_idx > num_connections) break; } } diff --git a/collector/test/NetworkStatusNotifierTest.cpp b/collector/test/NetworkStatusNotifierTest.cpp index 8cbcced306..c6834c6ba1 100644 --- a/collector/test/NetworkStatusNotifierTest.cpp +++ b/collector/test/NetworkStatusNotifierTest.cpp @@ -42,8 +42,9 @@ class Semaphore { void acquire() { std::unique_lock lock(mutex_); - while (value_ <= 0) + while (value_ <= 0) { cond_.wait(lock); + } value_--; } @@ -52,9 +53,11 @@ class Semaphore { auto deadline = std::chrono::steady_clock::now() + rel_time; std::unique_lock lock(mutex_); - while (value_ <= 0) - if (cond_.wait_until(lock, deadline) == std::cv_status::timeout) + while (value_ <= 0) { + if (cond_.wait_until(lock, deadline) == std::cv_status::timeout) { return false; + } + } value_--; return true; } diff --git a/collector/test/ProtoAllocatorTest.cpp b/collector/test/ProtoAllocatorTest.cpp index 8809714412..f0bdf0b9c3 100644 --- a/collector/test/ProtoAllocatorTest.cpp +++ b/collector/test/ProtoAllocatorTest.cpp @@ -11,8 +11,9 @@ namespace { TEST(ProtoAllocator, OverflowDefaultPool) { ProtoAllocator allocator; - for (unsigned int i = 0; i <= ProtoAllocator::kDefaultPoolSize / sizeof(sensor::NetworkConnectionInfoMessage); i++) + for (unsigned int i = 0; i <= ProtoAllocator::kDefaultPoolSize / sizeof(sensor::NetworkConnectionInfoMessage); i++) { allocator.AllocateRoot(); + } allocator.Reset(); }