ntopng/include/Bitmap.h
Ivan Nardi 8ee8b740ea
First batch of make cppcheck clean up (#10878)
Rework the `cppcheck:` recipe so it is usable in practice:
  - `--enable=all` -> `--enable=warning,performance,portability`
    (drops the `style`/`information`/`unusedFunction` groups, which produced
    hundreds of opinion-level hits)
  - drop `--force` (was re-analyzing every file once per #ifdef combination;
    single files took 40+ min). Analyzes the default build config only.
  - add `-j $(shell nproc)` + `--cppcheck-build-dir=.cppcheck-build` for
    parallelism and incremental caching; `mkdir -p` the cache dir in the recipe
  - suppress checks that are noise for this codebase:
      * useInitializationList  - micro perf, POD members
      * duplInheritedMember    - intentional non-virtual name shadowing
        (operator[], swap, enqueue, incUses, lua, ...)
      * noCopyConstructor / noOperatorEq - the flagged classes
        (NetworkInterface, Ntop, Flow, ...) are non-copyable by design and
        always held by pointer; the fix cppcheck suggests (add operator=)
        is meaningless for them
  - .gitignore: ignore the new .cppcheck-build/ cache directory

FlowAlertsLoader::registerRisk (src/FlowAlertsLoader.cpp)
  Missing `else`: `alert_to_risk[alert_type.id] = risk` was executed even when
  `alert_type.id >= MAX_DEFINED_FLOW_ALERT_TYPE` -> out-of-bounds array write.
  The sibling registerAlert() already had the `else`.

Uninitialized ndpi_protocol structs (src/NetworkInterface.cpp x6,
src/LuaEngineInterface.cpp x1)
  Local `ndpi_protocol` values were only partially initialized (proto.* set,
  but breed/fpc/state/category/custom_category_userdata left indeterminate)
  and then passed by value to get_ndpi_full_proto_name() /
  get_ndpi_proto_category(). Added `memset(&x, 0, sizeof(x))` at each
  declaration, matching the existing convention elsewhere in the tree.

Uninitialized locals
  - src/ParserInterface.cpp: `src2dst_direction` was read on the
    `flow == NULL` path (getFlow() not called). Initialize to a defined value;
    the value is not otherwise observable on that path.
  - include/Bitmap.h (toHexString): if `buf_len <= 0` the first loop never
    runs and `strlen(buf)` reads uninitialized memory; also `strlen(buf) - 2`
    underflows (unsigned) when the string is shorter than 2 bytes. Null-
    terminate up front and hoist strlen into a `size_t`, iterate with
    `pos + 2 < len`.

src/NetworkInterface.cpp incNumHosts()/decNumHosts()
  `if (isShuttingDown() || (!host->isUnicastHost())) return;` - the second
  term is always false, the function already returned on `!isUnicastHost()`
  a few lines above. Dropped it.

include/NetworkInterface.h getActiveFlowsStats()
  Declaration and definition disagreed on the first two parameter *names*
  (`stats, status_stats` vs `ndpi_stats, stats`); types matched. Renamed the
  header params to match the implementation.

No behavioural change; each argument was already non-negative.

  - Interface id (`get_id()` returns int; kept int because 3 call sites test
    `== -1`) formatted with %u in redis-key macros -> cast the argument
    `(u_int)` at the call site:
      include/AutonomousSystem.h, include/Country.h,
      include/ObservationPoint.h, include/VLAN.h,
      src/BroadcastDomains.cpp (x2), src/HostPools.cpp, src/LocalHost.cpp,
      src/LuaEngineInterface.cpp (x3), src/NetworkInterface.cpp (x2),
      src/SyslogParserInterface.cpp
  - src/HTTPserver.cpp: `%d` with get_http_port()/get_https_port() (u_int)
    -> `%u`; the scanf-width builder `"%%%u[^|]..."` fed `int` macros -> `%d`
  - src/Flow.cpp: `"%u.%u.%u.%u"` with `int` octets from a `%d` sscanf -> `%d`;
    `%u` (arg 13) with get_protocol_category() enum -> cast `(u_int)`
  - src/MacManufacturers.cpp: `int _mac[3]` scanned with `%02x`
    (wants `unsigned int*`) -> declare `u_int _mac[3]`
  - src/StatsManager.cpp: `%lu` with `static_cast<long int>(key)` epoch values
    -> `%ld` (respects the explicit signed cast)
  - src/Trace.cpp: `"%s.%u"` with loop `int i` / `i + 1` -> `%d`
  - src/Prefs.cpp: `%u` in usage() help text fed CONST_DEFAULT_* /
    MAX_NUM_* / CLICKHOUSE_MAX_* int macros -> cast `(u_int)`

std::string / std::vector parameters taken by value, changed to `const &`
(declaration and definition kept in sync; none are virtual or overrides, so
callers are source-compatible):

  - AggregatedFlowsStats::setInfoKey
  - Flow::setL7JSON
  - CustomFlowLuaScriptAlert::setAlertMessage
  - CustomHostLuaScriptAlert::setAlertMessage, ctor (_msg)
  - ScanRealtimeAlert ctor (_alerts, std::vector)
  - CustomHostLuaScript::allocAlert (_msg)
  - OtherAlertableEntity::getAlertCachedValue / setAlertCacheValue /
    triggerAlert / releaseAlert (key, value)
  - HostAlert::init and HostAlert(HostCheckID, ...) ctor (_check_name)
  - Ntop::luaFlowCheckInfo / luaHostCheckInfo (check_name)
  - Ntop::incBlacklisHits (listname)
  - Ntop::setLuaCache (key, val)
2026-09-01 08:36:01 +02:00

152 lines
3.9 KiB
C++

/*
*
* (C) 2013-26 - ntop.org
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
*/
#ifndef _BITMAP_H_
#define _BITMAP_H_
#include "ntop_includes.h"
/**
* @brief Generic bitmap class template building a bitmap as multiple 64-bit
* bitmaps
* @tparam N Number of u_int64_t elements in the bitmap array
*/
template <size_t N>
class Bitmap {
private:
u_int64_t bitmap[N];
public:
Bitmap() { reset(); }
Bitmap(char* list) {
reset();
setBits(list);
};
static inline u_int numBits() { return N * 64; };
void reset() { memset(bitmap, 0, sizeof(bitmap)); }
void setBit(u_int16_t id) {
size_t idx = id >> 6;
u_int8_t offset = id & 0x3F;
if (idx < N) bitmap[idx] |= ((u_int64_t)1) << offset;
}
void setBits(char* list) {
char *item, *tmp = NULL;
item = strtok_r(list, ",", &tmp);
while (item) {
int id = atoi(item);
setBit(id);
item = strtok_r(NULL, ",", &tmp);
}
}
void clearBit(u_int16_t id) {
size_t idx = id >> 6; /* id / 64 */
u_int8_t offset = id & 0x3F; /* id % 64 */
if (idx < N) bitmap[idx] &= ~(((u_int64_t)1) << offset);
}
bool isSetBit(u_int16_t id) const {
size_t idx = id >> 6;
u_int8_t offset = id & 0x3F;
if (idx < N) return (((bitmap[idx] >> offset) & 1) ? true : false);
return false;
}
/* Return the first bit set, starting from start */
int getNext(u_int16_t start) {
size_t start_idx = start >> 6;
u_int8_t start_offset = start & 0x3F;
for (size_t i = start_idx; i < N; i++) {
int bit =
Utils::bitmapGetNext(bitmap[i], (i == start_idx) ? start_offset : 0);
if (bit >= 0) {
return (i << 6) + bit;
}
}
return -1;
}
void bitmapOr(const Bitmap<N> b) {
for (size_t i = 0; i < N; i++) {
bitmap[i] |= b.bitmap[i];
}
}
void set(const Bitmap<N>* b) { memcpy(bitmap, b->bitmap, sizeof(bitmap)); }
bool equal(const Bitmap<N>* b) const {
return (memcmp(bitmap, b->bitmap, sizeof(bitmap)) == 0);
}
/* Returns the 64-bit value at position idx */
u_int64_t getBits64(size_t idx = 0) const {
return (idx < N) ? bitmap[idx] : 0;
}
/* Sets the 64-bit value at position idx */
void setBits64(u_int64_t val, size_t idx = 0) {
if (idx < N) bitmap[idx] = val;
}
void lua(lua_State* vm, const char* label) const;
const char* toHexString(char* buf, ssize_t buf_len) const {
char* ptr = buf;
ssize_t remaining = buf_len;
if (buf_len > 0) buf[0] = '\0';
/* Write hex values in reverse order (most significant first) */
for (int i = N - 1; i >= 0; i--) {
int written =
snprintf(ptr, remaining, "%016lX", (unsigned long)bitmap[i]);
if (written >= remaining) break;
ptr += written;
remaining -= written;
}
/* Remove heading zeroes but keep HEX byte-aligned (SQLite doesn't like
* heading zeroes when inserting blob literals) */
u_int shifts = 0;
size_t buf_slen = strlen(buf);
for (u_int pos = 0; pos + 2 < buf_slen; pos += 2) {
u_int8_t cur_byte = 0;
sscanf(&buf[pos], "%02hhX", &cur_byte);
if (cur_byte > 0) break;
shifts += 2;
}
if (shifts > 0) memmove(buf, &buf[shifts], buf_len - shifts);
return buf;
}
};
#endif /* _BITMAP_H_ */