Merge branch 'topic/timw/clang-tidy-fixes'

* topic/timw/clang-tidy-fixes: (41 commits)
  Deprecate BRO_PLUGIN_INSTALL_PATH constant
  Make constants in IP::ParseResult uppercase, deprecate the old ones
  Fix comparison against CapLen results in IPTunnel
  Fix clang-tidy cppcoreguidelines-virtual-class-destructor warnings in headers
  Fix clang-tidy cppcoreguidelines-macro-usage warnings in headers
  Fix clang-tidy modernize-use-using warnings in headers
  Fix clang-tidy modernize-use-transparent-functors warnings in headers
  Fix clang-tidy modernize-use-override warnings in headers
  Fix clang-tidy modernize-use-nullptr warnings in headers
  Fix clang-tidy modernize-use-equals-delete warnings in headers
  Fix clang-tidy modernize-use-emplace warnings in headers
  Fix clang-tidy modernize-use-default-member-init warnings in headers
  Fix clang-tidy modernize-use-bool-literals warnings in headers
  Fix clang-tidy modernize-return-braced-init-list warnings in headers
  Fix clang-tidy modernize-type-traits warnings in headers
  Fix clang-tidy modernize-redundnat-void-arg warnings in headers
  Fix clang-tidy modernize-pass-by-value warnings in headers
  Fix clang-tidy modernize-loop-convert warnings in headers
  Fix clang-tidy modernize-macro-to-enum warnings in headers
  Fix clang-tidy performance-unnecessary-copy-initialization warnings in headers
  ...
This commit is contained in:
Tim Wojtulewicz 2025-06-23 10:36:38 -07:00
commit 8d92ad472c
195 changed files with 832 additions and 672 deletions

View file

@ -10,6 +10,7 @@ Checks: [-*,
cppcoreguidelines-virtual-class-destructor, cppcoreguidelines-virtual-class-destructor,
# Skipping these temporarily because they are very noisy # Skipping these temporarily because they are very noisy
-bugprone-forward-declaration-namespace,
-bugprone-narrowing-conversions, -bugprone-narrowing-conversions,
-bugprone-unchecked-optional-access, -bugprone-unchecked-optional-access,
-performance-unnecessary-value-param, -performance-unnecessary-value-param,
@ -63,3 +64,10 @@ Checks: [-*,
-modernize-use-std-numbers, -modernize-use-std-numbers,
-modernize-use-std-print, -modernize-use-std-print,
] ]
HeaderFilterRegex: '.h'
ExcludeHeaderFilterRegex: '.*(auxil|3rdparty)/.*'
SystemHeaders: false
CheckOptions:
- key: modernize-use-default-member-init.UseAssignment
value: 'true'

18
CHANGES
View file

@ -1,3 +1,21 @@
8.0.0-dev.489 | 2025-06-23 10:36:38 -0700
* Deprecate BRO_PLUGIN_INSTALL_PATH constant (Tim Wojtulewicz, Corelight)
* Make constants in IP::ParseResult uppercase, deprecate the old ones (Tim Wojtulewicz, Corelight)
* Fix comparison against CapLen results in IPTunnel (Tim Wojtulewicz, Corelight)
* Fix clang-tidy warnings in headers (Tim Wojtulewicz, Corelight)
* Change clang-tidy configuration to also scan headers (Tim Wojtulewicz, Corelight)
* Don't pass local source/binary directory to zeek_add_plugin for Redis backend (Tim Wojtulewicz, Corelight)
* Update bifcl/binpac/gen-zam submodules with clang-tidy fixes (Tim Wojtulewicz, Corelight)
* Avoid linting headers in external paths (Tim Wojtulewicz, Corelight)
8.0.0-dev.447 | 2025-06-22 15:49:11 +0200 8.0.0-dev.447 | 2025-06-22 15:49:11 +0200
* GH-4594: Align WebSocket error in cluster with one in Broker (Benjamin Bannier, Corelight) * GH-4594: Align WebSocket error in cluster with one in Broker (Benjamin Bannier, Corelight)

View file

@ -1083,7 +1083,7 @@ set(USE_GEOIP false)
find_package(LibMMDB) find_package(LibMMDB)
if (LIBMMDB_FOUND) if (LIBMMDB_FOUND)
set(USE_GEOIP true) set(USE_GEOIP true)
include_directories(BEFORE ${LibMMDB_INCLUDE_DIR}) include_directories(BEFORE SYSTEM ${LibMMDB_INCLUDE_DIR})
list(APPEND OPTLIBS ${LibMMDB_LIBRARY}) list(APPEND OPTLIBS ${LibMMDB_LIBRARY})
endif () endif ()
@ -1091,7 +1091,7 @@ set(USE_KRB5 false)
find_package(LibKrb5) find_package(LibKrb5)
if (LIBKRB5_FOUND) if (LIBKRB5_FOUND)
set(USE_KRB5 true) set(USE_KRB5 true)
include_directories(BEFORE ${LibKrb5_INCLUDE_DIR}) include_directories(BEFORE SYSTEM ${LibKrb5_INCLUDE_DIR})
list(APPEND OPTLIBS ${LibKrb5_LIBRARY}) list(APPEND OPTLIBS ${LibKrb5_LIBRARY})
endif () endif ()
@ -1124,7 +1124,7 @@ endif ()
# dependencies which tend to be in standard system locations and thus cause the # dependencies which tend to be in standard system locations and thus cause the
# system OpenSSL headers to still be picked up even if one specifies # system OpenSSL headers to still be picked up even if one specifies
# --with-openssl (which may be common). # --with-openssl (which may be common).
include_directories(BEFORE ${OPENSSL_INCLUDE_DIR}) include_directories(BEFORE SYSTEM ${OPENSSL_INCLUDE_DIR})
# Determine if libfts is external to libc, i.e. musl # Determine if libfts is external to libc, i.e. musl
find_package(FTS) find_package(FTS)

View file

@ -1 +1 @@
8.0.0-dev.447 8.0.0-dev.489

@ -1 +1 @@
Subproject commit 82eb0ce207ef9d11bda880d3ff1287f9cd3b769e Subproject commit 7f9204a4b294a8cacfff94409b79af2186fe6752

@ -1 +1 @@
Subproject commit e1bb4309129abc475250d36ca6822624cd3036bb Subproject commit 482afe31fb1e8b533f262b8f175d89d4cd972dda

@ -1 +1 @@
Subproject commit f113c5f3220263eca87c3ffaafae43fda3295ae3 Subproject commit 0af9a348847e94c1a35cd026b13adecc40dcbaa1

2
cmake

@ -1 +1 @@
Subproject commit 26f313a644e4430b0f2bd8dfbb1c992757ed84ae Subproject commit e2211bc960fcd2ff8c50d8649ed4eca0d4a9c35c

View file

@ -2,10 +2,11 @@
#pragma once #pragma once
#define ZEEK_SCRIPT_INSTALL_PATH "@ZEEK_SCRIPT_INSTALL_PATH@" constexpr char ZEEK_SCRIPT_INSTALL_PATH[] = "@ZEEK_SCRIPT_INSTALL_PATH@";
#define BRO_PLUGIN_INSTALL_PATH "@ZEEK_PLUGIN_DIR@" [[deprecated("Remove in v8.1. Use ZEEK_PLUGIN_INSTALL_PATH")]] constexpr char BRO_PLUGIN_INSTALL_PATH[] =
#define ZEEK_PLUGIN_INSTALL_PATH "@ZEEK_PLUGIN_DIR@" "@ZEEK_PLUGIN_DIR@";
#define DEFAULT_ZEEKPATH "@DEFAULT_ZEEKPATH@" constexpr char ZEEK_PLUGIN_INSTALL_PATH[] = "@ZEEK_PLUGIN_DIR@";
#define ZEEK_SPICY_MODULE_PATH "@ZEEK_SPICY_MODULE_PATH@" constexpr char DEFAULT_ZEEKPATH[] = "@DEFAULT_ZEEKPATH@";
#define ZEEK_SPICY_LIBRARY_PATH "@ZEEK_SPICY_LIBRARY_PATH@" constexpr char ZEEK_SPICY_MODULE_PATH[] = "@ZEEK_SPICY_MODULE_PATH@";
#define ZEEK_SPICY_DATA_PATH "@ZEEK_SPICY_DATA_PATH@" constexpr char ZEEK_SPICY_LIBRARY_PATH[] = "@ZEEK_SPICY_LIBRARY_PATH@";
constexpr char ZEEK_SPICY_DATA_PATH[] = "@ZEEK_SPICY_DATA_PATH@";

View file

@ -1,4 +1,6 @@
// See the file "COPYING" in the main distribution directory for copyright. // See the file "COPYING" in the main distribution directory for copyright.
// NOLINTBEGIN(modernize-macro-to-enum)
// NOLINTBEGIN(cppcoreguidelines-macro-usage)
#pragma once #pragma once
@ -306,3 +308,6 @@
/* compiled with Spicy support */ /* compiled with Spicy support */
#cmakedefine HAVE_SPICY #cmakedefine HAVE_SPICY
// NOLINTEND(cppcoreguidelines-macro-usage)
// NOLINTEND(modernize-macro-to-enum)

View file

@ -20,14 +20,14 @@ namespace zeek::detail {
// TODO: Anon.h may not be the right place to put these functions ... // TODO: Anon.h may not be the right place to put these functions ...
enum ip_addr_anonymization_class_t { enum ip_addr_anonymization_class_t : uint8_t {
ORIG_ADDR, // client address ORIG_ADDR, // client address
RESP_ADDR, // server address RESP_ADDR, // server address
OTHER_ADDR, OTHER_ADDR,
NUM_ADDR_ANONYMIZATION_CLASSES, NUM_ADDR_ANONYMIZATION_CLASSES,
}; };
enum ip_addr_anonymization_method_t { enum ip_addr_anonymization_method_t : uint8_t {
KEEP_ORIG_ADDR, KEEP_ORIG_ADDR,
SEQUENTIALLY_NUMBERED, SEQUENTIALLY_NUMBERED,
RANDOM_MD5, RANDOM_MD5,

View file

@ -24,7 +24,7 @@ namespace detail {
class Expr; class Expr;
using ExprPtr = IntrusivePtr<Expr>; using ExprPtr = IntrusivePtr<Expr>;
enum AttrTag { enum AttrTag : uint8_t {
ATTR_OPTIONAL, ATTR_OPTIONAL,
ATTR_DEFAULT, ATTR_DEFAULT,
ATTR_DEFAULT_INSERT, // insert default value on failed lookups ATTR_DEFAULT_INSERT, // insert default value on failed lookups

View file

@ -465,15 +465,15 @@ set(MAIN_SRCS
digest.h) digest.h)
set(THIRD_PARTY_SRCS set(THIRD_PARTY_SRCS
3rdparty/zeek_inet_ntop.c $<$<BOOL:USE_SQLITE>:3rdparty/sqlite3.c>
3rdparty/bsd-getopt-long.c
3rdparty/ConvertUTF.c 3rdparty/ConvertUTF.c
3rdparty/bsd-getopt-long.c
3rdparty/in_cksum.cc 3rdparty/in_cksum.cc
3rdparty/modp_numtoa.c 3rdparty/modp_numtoa.c
3rdparty/patricia.c 3rdparty/patricia.c
3rdparty/setsignal.c 3rdparty/setsignal.c
$<$<BOOL:USE_SQLITE>:3rdparty/sqlite3.c> 3rdparty/strsep.c
3rdparty/strsep.c) 3rdparty/zeek_inet_ntop.c)
if (USE_SQLITE AND WNOERROR_FLAG) if (USE_SQLITE AND WNOERROR_FLAG)
set_source_files_properties(3rdparty/sqlite3.c PROPERTIES COMPILE_FLAGS ${WNOERROR_FLAG}) set_source_files_properties(3rdparty/sqlite3.c PROPERTIES COMPILE_FLAGS ${WNOERROR_FLAG})

View file

@ -27,9 +27,6 @@ class RecordVal;
using ValPtr = IntrusivePtr<Val>; using ValPtr = IntrusivePtr<Val>;
using RecordValPtr = IntrusivePtr<RecordVal>; using RecordValPtr = IntrusivePtr<RecordVal>;
namespace session {
class Manager;
}
namespace detail { namespace detail {
class Specific_RE_Matcher; class Specific_RE_Matcher;
@ -45,7 +42,7 @@ namespace packet_analysis::IP {
class SessionAdapter; class SessionAdapter;
} }
enum ConnEventToFlag { enum ConnEventToFlag : uint8_t {
NUL_IN_LINE, NUL_IN_LINE,
SINGULAR_CR, SINGULAR_CR,
SINGULAR_LF, SINGULAR_LF,

View file

@ -1414,6 +1414,8 @@ TableValPtr DNS_Mgr::empty_addr_set() {
return make_intrusive<TableVal>(std::move(s)); return make_intrusive<TableVal>(std::move(s));
} }
DNS_Mgr::AsyncRequest::AsyncRequest(const IPAddr& addr) : addr(addr), type(T_PTR) {}
////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////

View file

@ -16,12 +16,15 @@
// These are defined in ares headers but we don't want to have to include // These are defined in ares headers but we don't want to have to include
// those headers here and create install dependencies on them. // those headers here and create install dependencies on them.
struct ares_channeldata; struct ares_channeldata;
typedef struct ares_channeldata* ares_channel; using ares_channel = struct ares_channeldata*;
#ifndef T_PTR #ifndef T_PTR
// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
#define T_PTR 12 #define T_PTR 12
#endif #endif
#ifndef T_TXT #ifndef T_TXT
// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
#define T_TXT 16 #define T_TXT 16
#endif #endif
@ -54,7 +57,7 @@ class DNS_Mapping;
using DNS_MappingPtr = std::shared_ptr<DNS_Mapping>; using DNS_MappingPtr = std::shared_ptr<DNS_Mapping>;
class DNS_Request; class DNS_Request;
enum DNS_MgrMode { enum DNS_MgrMode : uint8_t {
DNS_PRIME, // used to prime the cache DNS_PRIME, // used to prime the cache
DNS_FORCE, // internal error if cache miss DNS_FORCE, // internal error if cache miss
DNS_DEFAULT, // lookup names as they're requested DNS_DEFAULT, // lookup names as they're requested
@ -320,7 +323,7 @@ protected:
bool processed = false; bool processed = false;
AsyncRequest(std::string host, int request_type) : host(std::move(host)), type(request_type) {} AsyncRequest(std::string host, int request_type) : host(std::move(host)), type(request_type) {}
AsyncRequest(const IPAddr& addr) : addr(addr), type(T_PTR) {} AsyncRequest(const IPAddr& addr);
void Resolved(const std::string& name); void Resolved(const std::string& name);
void Resolved(TableValPtr addrs); void Resolved(TableValPtr addrs);

View file

@ -12,9 +12,9 @@ namespace zeek::detail {
class Stmt; class Stmt;
class ParseLocationRec; class ParseLocationRec;
enum BreakCode { BC_NO_HIT, BC_HIT, BC_HIT_AND_DELETE }; enum BreakCode : uint8_t { BC_NO_HIT, BC_HIT, BC_HIT_AND_DELETE };
class DbgBreakpoint { class DbgBreakpoint {
enum Kind { BP_STMT = 0, BP_FUNC, BP_LINE, BP_TIME }; enum Kind : uint8_t { BP_STMT = 0, BP_FUNC, BP_LINE, BP_TIME };
public: public:
DbgBreakpoint(); DbgBreakpoint();

View file

@ -35,7 +35,7 @@ class DbgWatch;
class DbgDisplay; class DbgDisplay;
// This needs to be defined before we do the includes that come after it. // This needs to be defined before we do the includes that come after it.
enum ParseLocationRecType { PLR_UNKNOWN, PLR_FILE_AND_LINE, PLR_FUNCTION }; enum ParseLocationRecType : uint8_t { PLR_UNKNOWN, PLR_FILE_AND_LINE, PLR_FUNCTION };
class ParseLocationRec { class ParseLocationRec {
public: public:
ParseLocationRecType type; ParseLocationRecType type;

View file

@ -605,4 +605,6 @@ int dbg_cmd_trace(DebugCmd cmd, const vector<string>& args) {
return 0; return 0;
} }
int num_debug_cmds() { return static_cast<int>(g_DebugCmdInfos.size()); }
} // namespace zeek::detail } // namespace zeek::detail

View file

@ -51,7 +51,7 @@ extern DebugCmdInfoQueue g_DebugCmdInfos;
void init_global_dbg_constants(); void init_global_dbg_constants();
#define num_debug_cmds() (static_cast<int>(g_DebugCmdInfos.size())) extern int num_debug_cmds();
// Looks up the info record and returns it; if cmd is not found returns 0. // Looks up the info record and returns it; if cmd is not found returns 0.
const DebugCmdInfo* get_debug_cmd_info(DebugCmd cmd); const DebugCmdInfo* get_debug_cmd_info(DebugCmd cmd);
@ -68,6 +68,7 @@ int find_all_matching_cmds(const std::string& prefix, const char* array_of_match
// These functions return <= 0 if failure, > 0 for success. // These functions return <= 0 if failure, > 0 for success.
// More particular return values are command-specific: see comments w/function. // More particular return values are command-specific: see comments w/function.
// NOLINTNEXTLINE(modernize-use-using)
typedef int DbgCmdFn(DebugCmd cmd, const std::vector<std::string>& args); typedef int DbgCmdFn(DebugCmd cmd, const std::vector<std::string>& args);
DbgCmdFn dbg_cmd_backtrace; DbgCmdFn dbg_cmd_backtrace;

View file

@ -7,6 +7,7 @@
#ifdef DEBUG #ifdef DEBUG
#include <cstdint>
#include <cstdio> #include <cstdio>
#include <set> #include <set>
#include <string> #include <string>
@ -15,6 +16,7 @@
#include <unistd.h> // Needed to ignore __attribute__((format(printf))) on MSVC #include <unistd.h> // Needed to ignore __attribute__((format(printf))) on MSVC
#endif #endif
// NOLINTBEGIN(cppcoreguidelines-macro-usage)
#define DBG_LOG(stream, ...) \ #define DBG_LOG(stream, ...) \
if ( ::zeek::detail::debug_logger.IsEnabled(stream) ) \ if ( ::zeek::detail::debug_logger.IsEnabled(stream) ) \
::zeek::detail::debug_logger.Log(stream, __VA_ARGS__) ::zeek::detail::debug_logger.Log(stream, __VA_ARGS__)
@ -25,6 +27,7 @@
#define DBG_POP(stream) ::zeek::detail::debug_logger.PopIndent(stream) #define DBG_POP(stream) ::zeek::detail::debug_logger.PopIndent(stream)
#define PLUGIN_DBG_LOG(plugin, ...) ::zeek::detail::debug_logger.Log(plugin, __VA_ARGS__) #define PLUGIN_DBG_LOG(plugin, ...) ::zeek::detail::debug_logger.Log(plugin, __VA_ARGS__)
// NOLINTEND(cppcoreguidelines-macro-usage)
namespace zeek { namespace zeek {
@ -35,7 +38,7 @@ class Plugin;
// To add a new debugging stream, add a constant here as well as // To add a new debugging stream, add a constant here as well as
// an entry to DebugLogger::streams in DebugLogger.cc. // an entry to DebugLogger::streams in DebugLogger.cc.
enum DebugStream { enum DebugStream : uint8_t {
DBG_SERIAL, // Serialization DBG_SERIAL, // Serialization
DBG_RULES, // Signature matching DBG_RULES, // Signature matching
DBG_STRING, // String code DBG_STRING, // String code
@ -67,10 +70,10 @@ namespace detail {
class DebugLogger { class DebugLogger {
public: public:
// Output goes to stderr per default. // Output goes to stderr per default.
DebugLogger() : file(nullptr), all(false), verbose(false) {}; DebugLogger() = default;
~DebugLogger(); ~DebugLogger();
void OpenDebugLog(const char* filename = 0); void OpenDebugLog(const char* filename = nullptr);
void Log(DebugStream stream, const char* fmt, ...) __attribute__((format(printf, 3, 4))); void Log(DebugStream stream, const char* fmt, ...) __attribute__((format(printf, 3, 4)));
void Log(const plugin::Plugin& plugin, const char* fmt, ...) __attribute__((format(printf, 3, 4))); void Log(const plugin::Plugin& plugin, const char* fmt, ...) __attribute__((format(printf, 3, 4)));
@ -98,14 +101,14 @@ public:
void ShowStreamsHelp(); void ShowStreamsHelp();
private: private:
FILE* file; FILE* file = nullptr;
bool all; bool all = false;
bool verbose; bool verbose = false;
struct Stream { struct Stream {
const char* prefix; const char* prefix = nullptr;
int indent; int indent = 0;
bool enabled; bool enabled = false;
}; };
std::set<std::string> enabled_streams; std::set<std::string> enabled_streams;
@ -123,9 +126,11 @@ extern DebugLogger debug_logger;
} // namespace zeek } // namespace zeek
#else #else
// NOLINTBEGIN(cppcoreguidelines-macro-usage)
#define DBG_LOG(...) #define DBG_LOG(...)
#define DBG_LOG_VERBOSE(...) #define DBG_LOG_VERBOSE(...)
#define DBG_PUSH(stream) #define DBG_PUSH(stream)
#define DBG_POP(stream) #define DBG_POP(stream)
#define PLUGIN_DBG_LOG(plugin, ...) #define PLUGIN_DBG_LOG(plugin, ...)
// NOLINTEND(cppcoreguidelines-macro-usage)
#endif #endif

View file

@ -18,12 +18,12 @@ class IPPrefix;
class File; class File;
class Type; class Type;
enum DescType { enum DescType : uint8_t {
DESC_READABLE, DESC_READABLE,
DESC_BINARY, DESC_BINARY,
}; };
enum DescStyle { enum DescStyle : uint8_t {
STANDARD_STYLE, STANDARD_STYLE,
RAW_STYLE, RAW_STYLE,
}; };

View file

@ -30,7 +30,7 @@ namespace zeek {
template<typename T> template<typename T>
class Dictionary; class Dictionary;
enum DictOrder { ORDERED, UNORDERED }; enum DictOrder : uint8_t { ORDERED, UNORDERED };
// A dict_delete_func that just calls delete. // A dict_delete_func that just calls delete.
extern void generic_delete_func(void*); extern void generic_delete_func(void*);
@ -628,7 +628,7 @@ public:
if ( max_entries < num_entries ) if ( max_entries < num_entries )
max_entries = num_entries; max_entries = num_entries;
if ( num_entries > ThresholdEntries() ) if ( num_entries > ThresholdEntries() )
SizeUp(); SizeUp(); // NOLINT(bugprone-branch-clone)
// if space_distance is too great, performance decreases. we need to sizeup for // if space_distance is too great, performance decreases. we need to sizeup for
// performance. // performance.
@ -790,11 +790,14 @@ public:
int ExpectedCapacity() const { return bucket_capacity; } int ExpectedCapacity() const { return bucket_capacity; }
// Debugging // Debugging
#define DUMPIF(f) \
if ( f ) \
Dump(1)
#ifdef ZEEK_DICT_DEBUG #ifdef ZEEK_DICT_DEBUG
void DumpIfInvalid(bool valid) const {
if ( ! valid ) {
Dump(1);
abort();
}
}
void AssertValid() const { void AssertValid() const {
bool valid = true; bool valid = true;
int n = num_entries; int n = num_entries;
@ -805,8 +808,7 @@ public:
n--; n--;
valid = (n == 0); valid = (n == 0);
ASSERT(valid); DumpIfInvalid(valid);
DUMPIF(! valid);
// entries must clustered together // entries must clustered together
for ( int i = 1; i < Capacity(); i++ ) { for ( int i = 1; i < Capacity(); i++ ) {
@ -815,29 +817,28 @@ public:
if ( table[i - 1].Empty() ) { if ( table[i - 1].Empty() ) {
valid = (table[i].distance == 0); valid = (table[i].distance == 0);
ASSERT(valid); DumpIfInvalid(valid);
DUMPIF(! valid);
} }
else { else {
valid = (table[i].bucket >= table[i - 1].bucket); valid = (table[i].bucket >= table[i - 1].bucket);
ASSERT(valid); DumpIfInvalid(valid);
DUMPIF(! valid);
if ( table[i].bucket == table[i - 1].bucket ) { if ( table[i].bucket == table[i - 1].bucket ) {
valid = (table[i].distance == table[i - 1].distance + 1); valid = (table[i].distance == table[i - 1].distance + 1);
ASSERT(valid); DumpIfInvalid(valid);
DUMPIF(! valid);
} }
else { else {
valid = (table[i].distance <= table[i - 1].distance); valid = (table[i].distance <= table[i - 1].distance);
ASSERT(valid); DumpIfInvalid(valid);
DUMPIF(! valid);
} }
} }
} }
} }
#endif // ZEEK_DICT_DEBUG #endif // ZEEK_DICT_DEBUG
static constexpr size_t DICT_NUM_DISTANCES = 5;
void Dump(int level = 0) const { void Dump(int level = 0) const {
int key_size = 0; int key_size = 0;
for ( int i = 0; i < Capacity(); i++ ) { for ( int i = 0; i < Capacity(); i++ ) {
@ -848,7 +849,6 @@ public:
continue; continue;
} }
#define DICT_NUM_DISTANCES 5
int distances[DICT_NUM_DISTANCES]; int distances[DICT_NUM_DISTANCES];
int max_distance = 0; int max_distance = 0;
DistanceStats(max_distance, distances, DICT_NUM_DISTANCES); DistanceStats(max_distance, distances, DICT_NUM_DISTANCES);
@ -858,9 +858,9 @@ public:
Capacity(), Length(), MaxLength(), (double)Length() / (table ? Capacity() : 1), max_distance, Capacity(), Length(), MaxLength(), (double)Length() / (table ? Capacity() : 1), max_distance,
key_size / (Length() ? Length() : 1), log2_buckets, remaps, remap_end); key_size / (Length() ? Length() : 1), log2_buckets, remaps, remap_end);
if ( Length() > 0 ) { if ( Length() > 0 ) {
for ( int i = 0; i < DICT_NUM_DISTANCES - 1; i++ ) for ( size_t i = 0; i < DICT_NUM_DISTANCES - 1; i++ )
printf("[%d]%2d%% ", i, 100 * distances[i] / Length()); printf("[%zu]%2d%% ", i, 100 * distances[i] / Length());
printf("[%d+]%2d%% ", DICT_NUM_DISTANCES - 1, 100 * distances[DICT_NUM_DISTANCES - 1] / Length()); printf("[%zu+]%2d%% ", DICT_NUM_DISTANCES - 1, 100 * distances[DICT_NUM_DISTANCES - 1] / Length());
} }
else else
printf("\n"); printf("\n");
@ -880,7 +880,7 @@ public:
} }
} }
void DistanceStats(int& max_distance, int* distances = 0, int num_distances = 0) const { void DistanceStats(int& max_distance, int* distances = nullptr, int num_distances = 0) const {
max_distance = 0; max_distance = 0;
for ( int i = 0; i < num_distances; i++ ) for ( int i = 0; i < num_distances; i++ )
distances[i] = 0; distances[i] = 0;
@ -937,8 +937,9 @@ public:
for ( int idx = 0; idx < Capacity(); idx++ ) for ( int idx = 0; idx < Capacity(); idx++ )
if ( ! table[idx].Empty() ) { if ( ! table[idx].Empty() ) {
std::string s((char*)table[idx].GetKey(), table[idx].key_size); std::string s((char*)table[idx].GetKey(), table[idx].key_size);
f << s << std::endl; f << s << "\n";
} }
f << std::flush;
} }
} }

View file

@ -104,6 +104,8 @@ public:
return *this; return *this;
} }
const EventHandlerPtr& operator=(const EventHandlerPtr& h) { const EventHandlerPtr& operator=(const EventHandlerPtr& h) {
if ( this == &h )
return *this;
handler = h.handler; handler = h.handler;
return *this; return *this;
} }

View file

@ -18,7 +18,7 @@
namespace zeek { namespace zeek {
// The different kinds of event groups that exist. // The different kinds of event groups that exist.
enum class EventGroupKind { enum class EventGroupKind : uint8_t {
Attribute, Attribute,
Module, Module,
}; };

View file

@ -292,7 +292,7 @@ public:
// Adds to the trace an update for the given value. // Adds to the trace an update for the given value.
void AddDelta(ValPtr val, std::string rhs, bool needs_lhs, bool is_first_def) { void AddDelta(ValPtr val, std::string rhs, bool needs_lhs, bool is_first_def) {
auto& d = is_post ? post_deltas : deltas; auto& d = is_post ? post_deltas : deltas;
d.emplace_back(DeltaGen(val, rhs, needs_lhs, is_first_def)); d.emplace_back(val, rhs, needs_lhs, is_first_def);
} }
// Initially we analyze events pre-execution. When this flag // Initially we analyze events pre-execution. When this flag

View file

@ -2782,7 +2782,7 @@ static void report_field_deprecation(const RecordType* rt, const Expr* e, int fi
} }
FieldExpr::FieldExpr(ExprPtr arg_op, const char* arg_field_name) FieldExpr::FieldExpr(ExprPtr arg_op, const char* arg_field_name)
: UnaryExpr(EXPR_FIELD, std::move(arg_op)), field_name(util::copy_string(arg_field_name)), td(nullptr), field(0) { : UnaryExpr(EXPR_FIELD, std::move(arg_op)), field_name(util::copy_string(arg_field_name)) {
if ( IsError() ) if ( IsError() )
return; return;
@ -2863,7 +2863,7 @@ void FieldExpr::ExprDescribe(ODesc* d) const {
} }
HasFieldExpr::HasFieldExpr(ExprPtr arg_op, const char* arg_field_name) HasFieldExpr::HasFieldExpr(ExprPtr arg_op, const char* arg_field_name)
: UnaryExpr(EXPR_HAS_FIELD, std::move(arg_op)), field_name(arg_field_name), field(0) { : UnaryExpr(EXPR_HAS_FIELD, std::move(arg_op)), field_name(arg_field_name) {
if ( IsError() ) if ( IsError() )
return; return;

View file

@ -33,7 +33,7 @@ using ScopePtr = IntrusivePtr<Scope>;
using ScriptFuncPtr = IntrusivePtr<ScriptFunc>; using ScriptFuncPtr = IntrusivePtr<ScriptFunc>;
using FunctionIngredientsPtr = std::shared_ptr<FunctionIngredients>; using FunctionIngredientsPtr = std::shared_ptr<FunctionIngredients>;
enum ExprTag : int { enum ExprTag : int8_t {
EXPR_ANY = -1, EXPR_ANY = -1,
EXPR_NAME, EXPR_NAME,
EXPR_CONST, EXPR_CONST,
@ -232,10 +232,12 @@ public:
bool IsParen() const { return paren; } bool IsParen() const { return paren; }
// These are used by script optimization for AST analysis. // These are used by script optimization for AST analysis.
// NOLINTBEGIN(bugprone-macro-parentheses)
#define ZEEK_EXPR_ACCESSOR_DECLS(ctype) \ #define ZEEK_EXPR_ACCESSOR_DECLS(ctype) \
const ctype* As##ctype() const; \ const ctype* As##ctype() const; \
ctype* As##ctype(); \ ctype* As##ctype(); \
IntrusivePtr<ctype> As##ctype##Ptr(); IntrusivePtr<ctype> As##ctype##Ptr();
// NOLINTEND(bugprone-macro-parentheses)
ZEEK_EXPR_ACCESSOR_DECLS(AddToExpr) ZEEK_EXPR_ACCESSOR_DECLS(AddToExpr)
ZEEK_EXPR_ACCESSOR_DECLS(AssignExpr) ZEEK_EXPR_ACCESSOR_DECLS(AssignExpr)
@ -253,7 +255,7 @@ public:
ZEEK_EXPR_ACCESSOR_DECLS(NameExpr) ZEEK_EXPR_ACCESSOR_DECLS(NameExpr)
ZEEK_EXPR_ACCESSOR_DECLS(RefExpr) ZEEK_EXPR_ACCESSOR_DECLS(RefExpr)
void Describe(ODesc* d) const override final; void Describe(ODesc* d) const final;
virtual TraversalCode Traverse(TraversalCallback* cb) const = 0; virtual TraversalCode Traverse(TraversalCallback* cb) const = 0;
@ -511,8 +513,8 @@ public:
bool HasReducedOps(Reducer* c) const override; bool HasReducedOps(Reducer* c) const override;
ExprPtr Reduce(Reducer* c, StmtPtr& red_stmt) override; ExprPtr Reduce(Reducer* c, StmtPtr& red_stmt) override;
ExprPtr GetOp1() const override final { return op; } ExprPtr GetOp1() const final { return op; }
void SetOp1(ExprPtr _op) override final { op = std::move(_op); } void SetOp1(ExprPtr _op) final { op = std::move(_op); }
protected: protected:
UnaryExpr(ExprTag arg_tag, ExprPtr arg_op); UnaryExpr(ExprTag arg_tag, ExprPtr arg_op);
@ -547,11 +549,11 @@ public:
bool HasReducedOps(Reducer* c) const override; bool HasReducedOps(Reducer* c) const override;
ExprPtr Reduce(Reducer* c, StmtPtr& red_stmt) override; ExprPtr Reduce(Reducer* c, StmtPtr& red_stmt) override;
ExprPtr GetOp1() const override final { return op1; } ExprPtr GetOp1() const final { return op1; }
ExprPtr GetOp2() const override final { return op2; } ExprPtr GetOp2() const final { return op2; }
void SetOp1(ExprPtr _op) override final { op1 = std::move(_op); } void SetOp1(ExprPtr _op) final { op1 = std::move(_op); }
void SetOp2(ExprPtr _op) override final { op2 = std::move(_op); } void SetOp2(ExprPtr _op) final { op2 = std::move(_op); }
protected: protected:
BinaryExpr(ExprTag arg_tag, ExprPtr arg_op1, ExprPtr arg_op2) BinaryExpr(ExprTag arg_tag, ExprPtr arg_op1, ExprPtr arg_op2)
@ -930,13 +932,13 @@ public:
ExprPtr Reduce(Reducer* c, StmtPtr& red_stmt) override; ExprPtr Reduce(Reducer* c, StmtPtr& red_stmt) override;
StmtPtr ReduceToSingletons(Reducer* c) override; StmtPtr ReduceToSingletons(Reducer* c) override;
ExprPtr GetOp1() const override final { return op1; } ExprPtr GetOp1() const final { return op1; }
ExprPtr GetOp2() const override final { return op2; } ExprPtr GetOp2() const final { return op2; }
ExprPtr GetOp3() const override final { return op3; } ExprPtr GetOp3() const final { return op3; }
void SetOp1(ExprPtr _op) override final { op1 = std::move(_op); } void SetOp1(ExprPtr _op) final { op1 = std::move(_op); }
void SetOp2(ExprPtr _op) override final { op2 = std::move(_op); } void SetOp2(ExprPtr _op) final { op2 = std::move(_op); }
void SetOp3(ExprPtr _op) override final { op3 = std::move(_op); } void SetOp3(ExprPtr _op) final { op3 = std::move(_op); }
protected: protected:
void ExprDescribe(ODesc* d) const override; void ExprDescribe(ODesc* d) const override;
@ -1144,8 +1146,8 @@ protected:
void ExprDescribe(ODesc* d) const override; void ExprDescribe(ODesc* d) const override;
const char* field_name; const char* field_name;
const TypeDecl* td; const TypeDecl* td = nullptr;
int field; // -1 = attributes int field = -1;
}; };
// "rec?$fieldname" is true if the value of $fieldname in rec is not nil. // "rec?$fieldname" is true if the value of $fieldname in rec is not nil.
@ -1169,8 +1171,8 @@ protected:
void ExprDescribe(ODesc* d) const override; void ExprDescribe(ODesc* d) const override;
const char* field_name; const char* field_name = nullptr;
int field; int field = -1;
}; };
class RecordConstructorExpr final : public Expr { class RecordConstructorExpr final : public Expr {
@ -1398,11 +1400,11 @@ public:
bool HasReducedOps(Reducer* c) const override; bool HasReducedOps(Reducer* c) const override;
ExprPtr Reduce(Reducer* c, StmtPtr& red_stmt) override; ExprPtr Reduce(Reducer* c, StmtPtr& red_stmt) override;
ExprPtr GetOp1() const override final; ExprPtr GetOp1() const final;
ExprPtr GetOp2() const override final; ExprPtr GetOp2() const final;
void SetOp1(ExprPtr _op) override final; void SetOp1(ExprPtr _op) final;
void SetOp2(ExprPtr _op) override final; void SetOp2(ExprPtr _op) final;
protected: protected:
void ExprDescribe(ODesc* d) const override; void ExprDescribe(ODesc* d) const override;
@ -1597,8 +1599,8 @@ public:
ExprPtr Reduce(Reducer* c, StmtPtr& red_stmt) override; ExprPtr Reduce(Reducer* c, StmtPtr& red_stmt) override;
StmtPtr ReduceToSingletons(Reducer* c) override; StmtPtr ReduceToSingletons(Reducer* c) override;
ExprPtr GetOp1() const override final { return args; } ExprPtr GetOp1() const final { return args; }
void SetOp1(ExprPtr _op) override final { args = {NewRef{}, _op->AsListExpr()}; } void SetOp1(ExprPtr _op) final { args = {NewRef{}, _op->AsListExpr()}; }
protected: protected:
void ExprDescribe(ODesc* d) const override; void ExprDescribe(ODesc* d) const override;

View file

@ -57,7 +57,7 @@ class Func : public Obj {
public: public:
static inline const FuncPtr nil; static inline const FuncPtr nil;
enum Kind { SCRIPT_FUNC, BUILTIN_FUNC }; enum Kind : uint8_t { SCRIPT_FUNC, BUILTIN_FUNC };
explicit Func(Kind arg_kind) : kind(arg_kind) {} explicit Func(Kind arg_kind) : kind(arg_kind) {}
@ -351,7 +351,7 @@ public:
protected: protected:
BuiltinFunc() { BuiltinFunc() {
func = nullptr; func = nullptr;
is_pure = 0; is_pure = false;
} }
built_in_func func; built_in_func func;

View file

@ -213,7 +213,7 @@ private:
friend ValPtr BifFunc::md5_hmac_bif(zeek::detail::Frame* frame, const Args*); friend ValPtr BifFunc::md5_hmac_bif(zeek::detail::Frame* frame, const Args*);
}; };
enum HashKeyTag { HASH_KEY_INT, HASH_KEY_DOUBLE, HASH_KEY_STRING }; enum HashKeyTag : uint8_t { HASH_KEY_INT, HASH_KEY_DOUBLE, HASH_KEY_STRING };
constexpr int NUM_HASH_KEYS = HASH_KEY_STRING + 1; constexpr int NUM_HASH_KEYS = HASH_KEY_STRING + 1;

View file

@ -38,14 +38,14 @@ class Attributes;
class Expr; class Expr;
using ExprPtr = IntrusivePtr<Expr>; using ExprPtr = IntrusivePtr<Expr>;
enum InitClass { enum InitClass : uint8_t {
INIT_NONE, INIT_NONE,
INIT_FULL, INIT_FULL,
INIT_EXTRA, INIT_EXTRA,
INIT_REMOVE, INIT_REMOVE,
INIT_SKIP, INIT_SKIP,
}; };
enum IDScope { SCOPE_FUNCTION, SCOPE_MODULE, SCOPE_GLOBAL }; enum IDScope : uint8_t { SCOPE_FUNCTION, SCOPE_MODULE, SCOPE_GLOBAL };
class ID; class ID;
using IDPtr = IntrusivePtr<ID>; using IDPtr = IntrusivePtr<ID>;

View file

@ -33,6 +33,7 @@ class FragReassembler;
} }
#ifndef IPPROTO_MOBILITY #ifndef IPPROTO_MOBILITY
// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
#define IPPROTO_MOBILITY 135 #define IPPROTO_MOBILITY 135
#endif #endif
@ -355,7 +356,7 @@ public:
*/ */
const u_char* Payload() const { const u_char* Payload() const {
if ( ip4 ) if ( ip4 )
return ((const u_char*)ip4) + ip4->ip_hl * 4; return ((const u_char*)ip4) + (ip4->ip_hl * static_cast<std::ptrdiff_t>(4));
return ((const u_char*)ip6) + ip6_hdrs->TotalLength(); return ((const u_char*)ip6) + ip6_hdrs->TotalLength();
} }
@ -366,7 +367,7 @@ public:
*/ */
const ip6_mobility* MobilityHeader() const { const ip6_mobility* MobilityHeader() const {
if ( ip4 ) if ( ip4 )
return nullptr; return nullptr; // NOLINT(bugprone-branch-clone)
else if ( (*ip6_hdrs)[ip6_hdrs->Size() - 1]->Type() != IPPROTO_MOBILITY ) else if ( (*ip6_hdrs)[ip6_hdrs->Size() - 1]->Type() != IPPROTO_MOBILITY )
return nullptr; return nullptr;
else else

View file

@ -38,12 +38,16 @@ public:
ConnKey(const ConnKey& rhs) { *this = rhs; } ConnKey(const ConnKey& rhs) { *this = rhs; }
ConnKey(Val* v); ConnKey(Val* v);
// FIXME: This is getting reworked as part of the connection tuple changes. Suppress
// the clang-tidy warning for the time being.
// NOLINTBEGIN(bugprone-suspicious-memory-comparison)
bool operator<(const ConnKey& rhs) const { return memcmp(this, &rhs, sizeof(ConnKey)) < 0; } bool operator<(const ConnKey& rhs) const { return memcmp(this, &rhs, sizeof(ConnKey)) < 0; }
bool operator<=(const ConnKey& rhs) const { return memcmp(this, &rhs, sizeof(ConnKey)) <= 0; } bool operator<=(const ConnKey& rhs) const { return memcmp(this, &rhs, sizeof(ConnKey)) <= 0; }
bool operator==(const ConnKey& rhs) const { return memcmp(this, &rhs, sizeof(ConnKey)) == 0; } bool operator==(const ConnKey& rhs) const { return memcmp(this, &rhs, sizeof(ConnKey)) == 0; }
bool operator!=(const ConnKey& rhs) const { return memcmp(this, &rhs, sizeof(ConnKey)) != 0; } bool operator!=(const ConnKey& rhs) const { return memcmp(this, &rhs, sizeof(ConnKey)) != 0; }
bool operator>=(const ConnKey& rhs) const { return memcmp(this, &rhs, sizeof(ConnKey)) >= 0; } bool operator>=(const ConnKey& rhs) const { return memcmp(this, &rhs, sizeof(ConnKey)) >= 0; }
bool operator>(const ConnKey& rhs) const { return memcmp(this, &rhs, sizeof(ConnKey)) > 0; } bool operator>(const ConnKey& rhs) const { return memcmp(this, &rhs, sizeof(ConnKey)) > 0; }
// NOLINTEND(bugprone-suspicious-memory-comparison)
ConnKey& operator=(const ConnKey& rhs); ConnKey& operator=(const ConnKey& rhs);
@ -68,7 +72,7 @@ public:
/** /**
* Byte order. * Byte order.
*/ */
enum ByteOrder { Host, Network }; enum ByteOrder : uint8_t { Host, Network };
/** /**
* Constructs the unspecified IPv6 address (all 128 bits zeroed). * Constructs the unspecified IPv6 address (all 128 bits zeroed).
@ -432,7 +436,7 @@ inline IPAddr::IPAddr(Family family, const uint32_t* bytes, ByteOrder order) {
if ( order == Host ) { if ( order == Host ) {
for ( unsigned int i = 0; i < 4; ++i ) { for ( unsigned int i = 0; i < 4; ++i ) {
uint32_t* p = (uint32_t*)&in6.s6_addr[i * 4]; uint32_t* p = (uint32_t*)&in6.s6_addr[i * static_cast<ptrdiff_t>(4)];
*p = htonl(*p); *p = htonl(*p);
} }
} }

View file

@ -30,7 +30,7 @@
namespace zeek { namespace zeek {
enum class ListOrder : int { ORDERED, UNORDERED }; enum class ListOrder : uint8_t { ORDERED, UNORDERED };
template<typename T, ListOrder Order = ListOrder::ORDERED> template<typename T, ListOrder Order = ListOrder::ORDERED>
class List { class List {
@ -38,7 +38,7 @@ public:
constexpr static int DEFAULT_LIST_SIZE = 10; constexpr static int DEFAULT_LIST_SIZE = 10;
constexpr static int LIST_GROWTH_FACTOR = 2; constexpr static int LIST_GROWTH_FACTOR = 2;
~List() { free(entries); } ~List() { free(static_cast<void*>(entries)); }
explicit List(int size = 0) { explicit List(int size = 0) {
num_entries = 0; num_entries = 0;
@ -50,6 +50,7 @@ public:
max_entries = size; max_entries = size;
// NOLINTNEXTLINE(bugprone-sizeof-expression)
entries = (T*)util::safe_malloc(max_entries * sizeof(T)); entries = (T*)util::safe_malloc(max_entries * sizeof(T));
} }
@ -58,6 +59,7 @@ public:
num_entries = b.num_entries; num_entries = b.num_entries;
if ( max_entries ) if ( max_entries )
// NOLINTNEXTLINE(bugprone-sizeof-expression)
entries = (T*)util::safe_malloc(max_entries * sizeof(T)); entries = (T*)util::safe_malloc(max_entries * sizeof(T));
else else
entries = nullptr; entries = nullptr;
@ -66,7 +68,7 @@ public:
entries[i] = b.entries[i]; entries[i] = b.entries[i];
} }
List(List&& b) { List(List&& b) noexcept {
entries = b.entries; entries = b.entries;
num_entries = b.num_entries; num_entries = b.num_entries;
max_entries = b.max_entries; max_entries = b.max_entries;
@ -77,7 +79,9 @@ public:
List(const T* arr, int n) { List(const T* arr, int n) {
num_entries = max_entries = n; num_entries = max_entries = n;
// NOLINTNEXTLINE(bugprone-sizeof-expression)
entries = (T*)util::safe_malloc(max_entries * sizeof(T)); entries = (T*)util::safe_malloc(max_entries * sizeof(T));
// NOLINTNEXTLINE(bugprone-bitwise-pointer-cast,bugprone-multi-level-implicit-pointer-conversion,bugprone-sizeof-expression)
memcpy(entries, arr, n * sizeof(T)); memcpy(entries, arr, n * sizeof(T));
} }
@ -87,12 +91,13 @@ public:
if ( this == &b ) if ( this == &b )
return *this; return *this;
free(entries); free(static_cast<void*>(entries));
max_entries = b.max_entries; max_entries = b.max_entries;
num_entries = b.num_entries; num_entries = b.num_entries;
if ( max_entries ) if ( max_entries )
// NOLINTNEXTLINE(bugprone-sizeof-expression)
entries = (T*)util::safe_malloc(max_entries * sizeof(T)); entries = (T*)util::safe_malloc(max_entries * sizeof(T));
else else
entries = nullptr; entries = nullptr;
@ -103,11 +108,11 @@ public:
return *this; return *this;
} }
List& operator=(List&& b) { List& operator=(List&& b) noexcept {
if ( this == &b ) if ( this == &b )
return *this; return *this;
free(entries); free(static_cast<void*>(entries));
entries = b.entries; entries = b.entries;
num_entries = b.num_entries; num_entries = b.num_entries;
max_entries = b.max_entries; max_entries = b.max_entries;
@ -122,7 +127,7 @@ public:
void clear() // remove all entries void clear() // remove all entries
{ {
free(entries); free(static_cast<void*>(entries));
entries = nullptr; entries = nullptr;
num_entries = max_entries = 0; num_entries = max_entries = 0;
} }
@ -138,6 +143,7 @@ public:
new_size = num_entries; // do not lose any entries new_size = num_entries; // do not lose any entries
if ( new_size != max_entries ) { if ( new_size != max_entries ) {
// NOLINTNEXTLINE(bugprone-sizeof-expression)
entries = (T*)util::safe_realloc((void*)entries, sizeof(T) * new_size); entries = (T*)util::safe_realloc((void*)entries, sizeof(T) * new_size);
if ( entries ) if ( entries )
max_entries = new_size; max_entries = new_size;
@ -315,6 +321,7 @@ using name_list = PList<char>;
} // namespace zeek } // namespace zeek
// Macro to visit each list element in turn. // Macro to visit each list element in turn.
// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
#define loop_over_list(list, iterator) \ #define loop_over_list(list, iterator) \
int iterator; \ int iterator; \
for ( iterator = 0; iterator < (list).length(); ++iterator ) for ( (iterator) = 0; (iterator) < (list).length(); ++(iterator) )

View file

@ -72,7 +72,7 @@ static zeek::ValPtr mmdb_getvalue(MMDB_entry_data_s* entry_data, int status, int
return nullptr; return nullptr;
} }
MMDB::MMDB() : mmdb{}, file_info{}, reported_error{false}, last_check{zeek::run_state::network_time} {} MMDB::MMDB() : mmdb{}, file_info{}, last_check{zeek::run_state::network_time} {}
MMDB::~MMDB() { Close(); } MMDB::~MMDB() { Close(); }

View file

@ -64,20 +64,20 @@ private:
std::string filename; std::string filename;
MMDB_s mmdb; MMDB_s mmdb;
struct stat file_info; struct stat file_info;
bool reported_error; // to ensure we emit builtin errors during opening only once. bool reported_error = false; // to ensure we emit builtin errors during opening only once.
double last_check; double last_check;
}; };
class LocDB : public MMDB { class LocDB : public MMDB {
public: public:
bool OpenFromScriptConfig(); bool OpenFromScriptConfig() override;
std::string_view Description() { return "GeoIP location database"; } std::string_view Description() override { return "GeoIP location database"; }
}; };
class AsnDB : public MMDB { class AsnDB : public MMDB {
public: public:
bool OpenFromScriptConfig(); bool OpenFromScriptConfig() override;
std::string_view Description() { return "GeoIP ASN database"; } std::string_view Description() override { return "GeoIP ASN database"; }
}; };
#endif // USE_GEOIP #endif // USE_GEOIP

View file

@ -5,16 +5,16 @@
#include "zeek/List.h" #include "zeek/List.h"
#include "zeek/Obj.h" #include "zeek/Obj.h"
#define NO_ACCEPT 0 constexpr int NO_ACCEPT = 0;
#define NO_UPPER_BOUND -1 constexpr int NO_UPPER_BOUND = -1;
#define SYM_BOL 256 constexpr int SYM_BOL = 256;
#define SYM_EOL 257 constexpr int SYM_EOL = 257;
#define NUM_SYM 258 constexpr int NUM_SYM = 258;
#define SYM_EPSILON 259 constexpr int SYM_EPSILON = 259;
#define SYM_CCL 260 constexpr int SYM_CCL = 260;
namespace zeek { namespace zeek {

View file

@ -99,6 +99,8 @@ extern Registry registry;
*/ */
class Modifiable { class Modifiable {
public: public:
virtual ~Modifiable();
/** /**
* Calling this method signals to all registered receivers that the * Calling this method signals to all registered receivers that the
* object has been modified. * object has been modified.
@ -111,8 +113,6 @@ public:
protected: protected:
friend class Registry; friend class Registry;
virtual ~Modifiable();
// Number of currently registered receivers. // Number of currently registered receivers.
uint64_t num_receivers = 0; uint64_t num_receivers = 0;
}; };

View file

@ -92,10 +92,12 @@ public:
const detail::Location* expr_location = nullptr) const; const detail::Location* expr_location = nullptr) const;
// Report internal errors. // Report internal errors.
void BadTag(const char* msg, const char* t1 = nullptr, const char* t2 = nullptr) const; [[noreturn]] void BadTag(const char* msg, const char* t1 = nullptr, const char* t2 = nullptr) const;
// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
#define CHECK_TAG(t1, t2, text, tag_to_text_func) \ #define CHECK_TAG(t1, t2, text, tag_to_text_func) \
{ \ { \
if ( t1 != t2 ) \ if ( (t1) != (t2) ) \
BadTag(text, tag_to_text_func(t1), tag_to_text_func(t2)); \ BadTag(text, tag_to_text_func(t1), tag_to_text_func(t2)); \
} }

View file

@ -88,6 +88,8 @@ private:
std::unordered_map<std::string, Factory*> _types; std::unordered_map<std::string, Factory*> _types;
}; };
// NOLINTBEGIN(cppcoreguidelines-macro-usage)
/** /**
* Macro to insert into an OpaqueVal-derived class's declaration. Overrides the "new" serialization methods * Macro to insert into an OpaqueVal-derived class's declaration. Overrides the "new" serialization methods
* DoSerializeData and DoUnserializeData. * DoSerializeData and DoUnserializeData.
@ -100,12 +102,15 @@ private:
const char* OpaqueName() const override { return #T; } \ const char* OpaqueName() const override { return #T; } \
static zeek::OpaqueValPtr OpaqueInstantiate() { return zeek::make_intrusive<T>(); } static zeek::OpaqueValPtr OpaqueInstantiate() { return zeek::make_intrusive<T>(); }
#define __OPAQUE_MERGE(a, b) a##b #define __OPAQUE_MERGE(a, b) a##b
#define __OPAQUE_ID(x) __OPAQUE_MERGE(_opaque, x) #define __OPAQUE_ID(x) __OPAQUE_MERGE(_opaque, x)
/** Macro to insert into an OpaqueVal-derived class's implementation file. */ /** Macro to insert into an OpaqueVal-derived class's implementation file. */
#define IMPLEMENT_OPAQUE_VALUE(T) static zeek::OpaqueMgr::Register<T> __OPAQUE_ID(__LINE__)(#T); #define IMPLEMENT_OPAQUE_VALUE(T) static zeek::OpaqueMgr::Register<T> __OPAQUE_ID(__LINE__)(#T);
// NOLINTEND(cppcoreguidelines-macro-usage)
/** /**
* Base class for all opaque values. Opaque values are types that are managed * Base class for all opaque values. Opaque values are types that are managed
* completely internally, with no further script-level operators provided * completely internally, with no further script-level operators provided
@ -229,14 +234,14 @@ public:
static void hmac(const T& vlist, u_char key[ZEEK_MD5_DIGEST_LENGTH], u_char result[ZEEK_MD5_DIGEST_LENGTH]) { static void hmac(const T& vlist, u_char key[ZEEK_MD5_DIGEST_LENGTH], u_char result[ZEEK_MD5_DIGEST_LENGTH]) {
digest(vlist, result); digest(vlist, result);
for ( int i = 0; i < ZEEK_MD5_DIGEST_LENGTH; ++i ) for ( size_t i = 0; i < ZEEK_MD5_DIGEST_LENGTH; ++i )
result[i] ^= key[i]; result[i] ^= key[i];
detail::internal_md5(result, ZEEK_MD5_DIGEST_LENGTH, result); detail::internal_md5(result, ZEEK_MD5_DIGEST_LENGTH, result);
} }
MD5Val(); MD5Val();
~MD5Val(); ~MD5Val() override;
ValPtr DoClone(CloneState* state) override; ValPtr DoClone(CloneState* state) override;
@ -264,7 +269,7 @@ public:
} }
SHA1Val(); SHA1Val();
~SHA1Val(); ~SHA1Val() override;
ValPtr DoClone(CloneState* state) override; ValPtr DoClone(CloneState* state) override;
@ -292,7 +297,7 @@ public:
} }
SHA256Val(); SHA256Val();
~SHA256Val(); ~SHA256Val() override;
ValPtr DoClone(CloneState* state) override; ValPtr DoClone(CloneState* state) override;
@ -328,6 +333,10 @@ public:
explicit BloomFilterVal(probabilistic::BloomFilter* bf); explicit BloomFilterVal(probabilistic::BloomFilter* bf);
~BloomFilterVal() override; ~BloomFilterVal() override;
// Disable.
BloomFilterVal(const BloomFilterVal&) = delete;
BloomFilterVal& operator=(const BloomFilterVal&) = delete;
ValPtr DoClone(CloneState* state) override; ValPtr DoClone(CloneState* state) override;
const TypePtr& Type() const { return type; } const TypePtr& Type() const { return type; }
@ -350,10 +359,6 @@ protected:
DECLARE_OPAQUE_VALUE_DATA(BloomFilterVal) DECLARE_OPAQUE_VALUE_DATA(BloomFilterVal)
private: private:
// Disable.
BloomFilterVal(const BloomFilterVal&);
BloomFilterVal& operator=(const BloomFilterVal&);
TypePtr type; TypePtr type;
detail::CompositeHash* hash; detail::CompositeHash* hash;
probabilistic::BloomFilter* bloom_filter; probabilistic::BloomFilter* bloom_filter;

View file

@ -57,9 +57,9 @@ public:
void UnsetFlags(int flags); void UnsetFlags(int flags);
private: private:
int fds[2]; int fds[2] = {-1, -1};
int flags[2]; int flags[2] = {0};
int status_flags[2]; int status_flags[2] = {0};
}; };
/** /**
@ -119,7 +119,7 @@ public:
void Swap() { swapped = ! swapped; } void Swap() { swapped = ! swapped; }
private: private:
Pipe pipes[2]; Pipe pipes[2]; // NOLINT(modernize-use-default-member-init)
bool swapped = false; bool swapped = false;
}; };

View file

@ -15,7 +15,7 @@
using cce_func = int (*)(int); using cce_func = int (*)(int);
// This method is automatically generated by flex and shouldn't be namespaced // This method is automatically generated by flex and shouldn't be namespaced
extern int re_lex(void); extern int re_lex();
namespace zeek { namespace zeek {
@ -46,7 +46,7 @@ using MatchPos = uint64_t;
using AcceptingMatchSet = std::map<AcceptIdx, MatchPos>; using AcceptingMatchSet = std::map<AcceptIdx, MatchPos>;
using string_list = name_list; using string_list = name_list;
enum match_type { MATCH_ANYWHERE, MATCH_EXACTLY }; enum match_type : uint8_t { MATCH_ANYWHERE, MATCH_EXACTLY };
// A "specific" RE matcher will match one type of pattern: either // A "specific" RE matcher will match one type of pattern: either
// MATCH_ANYWHERE or MATCH_EXACTLY. // MATCH_ANYWHERE or MATCH_EXACTLY.

View file

@ -14,7 +14,7 @@ namespace zeek {
// Whenever subclassing the Reassembler class // Whenever subclassing the Reassembler class
// you should add to this for known subclasses. // you should add to this for known subclasses.
enum ReassemblerType { enum ReassemblerType : uint8_t {
REASSEM_UNKNOWN, REASSEM_UNKNOWN,
REASSEM_TCP, REASSEM_TCP,
REASSEM_FRAG, REASSEM_FRAG,
@ -44,7 +44,7 @@ public:
memcpy(block, other.block, size); memcpy(block, other.block, size);
} }
DataBlock(DataBlock&& other) { DataBlock(DataBlock&& other) noexcept {
seq = other.seq; seq = other.seq;
upper = other.upper; upper = other.upper;
block = other.block; block = other.block;
@ -64,7 +64,7 @@ public:
return *this; return *this;
} }
DataBlock& operator=(DataBlock&& other) { DataBlock& operator=(DataBlock&& other) noexcept {
if ( this == &other ) if ( this == &other )
return *this; return *this;

View file

@ -165,12 +165,10 @@ public:
// stack of location so that the most recent is always the one that // stack of location so that the most recent is always the one that
// will be assumed to be the current one. The pointer must remain // will be assumed to be the current one. The pointer must remain
// valid until the location is popped. // valid until the location is popped.
void PushLocation(const detail::Location* location) { void PushLocation(const detail::Location* location) { locations.emplace_back(location, nullptr); }
locations.push_back(std::pair<const detail::Location*, const detail::Location*>(location, 0));
}
void PushLocation(const detail::Location* loc1, const detail::Location* loc2) { void PushLocation(const detail::Location* loc1, const detail::Location* loc2) {
locations.push_back(std::pair<const detail::Location*, const detail::Location*>(loc1, loc2)); locations.emplace_back(loc1, loc2);
} }
// Removes the top-most location information from stack. // Removes the top-most location information from stack.
@ -304,15 +302,15 @@ private:
bool PermitFlowWeird(const char* name, const IPAddr& o, const IPAddr& r); bool PermitFlowWeird(const char* name, const IPAddr& o, const IPAddr& r);
bool PermitExpiredConnWeird(const char* name, const RecordVal& conn_id); bool PermitExpiredConnWeird(const char* name, const RecordVal& conn_id);
enum class PermitWeird { Allow, Deny, Unknown }; enum class PermitWeird : uint8_t { Allow, Deny, Unknown };
PermitWeird CheckGlobalWeirdLists(const char* name); PermitWeird CheckGlobalWeirdLists(const char* name);
bool EmitToStderr(bool flag); bool EmitToStderr(bool flag);
int errors; int errors;
int in_error_handler;
bool via_events; bool via_events;
bool syslog_open; bool syslog_open;
int in_error_handler;
bool info_to_stderr; bool info_to_stderr;
bool warnings_to_stderr; bool warnings_to_stderr;
bool errors_to_stderr; bool errors_to_stderr;

View file

@ -36,7 +36,7 @@ public:
const char* ID() const { return id; } const char* ID() const { return id; }
unsigned int Index() const { return idx; } unsigned int Index() const { return idx; }
enum PatternType { enum PatternType : uint8_t {
FILE_MAGIC, FILE_MAGIC,
PAYLOAD, PAYLOAD,
HTTP_REQUEST, HTTP_REQUEST,

View file

@ -22,7 +22,12 @@ public:
virtual void PrintDebug() = 0; virtual void PrintDebug() = 0;
}; };
enum RuleStateKind { RULE_STATE_ESTABLISHED = 1, RULE_STATE_ORIG = 2, RULE_STATE_RESP = 4, RULE_STATE_STATELESS = 8 }; enum RuleStateKind : uint8_t {
RULE_STATE_ESTABLISHED = 1,
RULE_STATE_ORIG = 2,
RULE_STATE_RESP = 4,
RULE_STATE_STATELESS = 8
};
// Implements the "tcp-state" keyword. // Implements the "tcp-state" keyword.
class RuleConditionTCPState : public RuleCondition { class RuleConditionTCPState : public RuleCondition {
@ -53,7 +58,7 @@ private:
// Implements "ip-options". // Implements "ip-options".
class RuleConditionIPOptions : public RuleCondition { class RuleConditionIPOptions : public RuleCondition {
public: public:
enum Options { enum Options : uint8_t {
OPT_LSRR = 1, OPT_LSRR = 1,
OPT_LSRRE = 2, OPT_LSRRE = 2,
OPT_RR = 4, OPT_RR = 4,
@ -83,7 +88,7 @@ public:
// Implements "payload-size". // Implements "payload-size".
class RuleConditionPayloadSize : public RuleCondition { class RuleConditionPayloadSize : public RuleCondition {
public: public:
enum Comp { RULE_LE, RULE_GE, RULE_LT, RULE_GT, RULE_EQ, RULE_NE }; enum Comp : uint8_t { RULE_LE, RULE_GE, RULE_LT, RULE_GT, RULE_EQ, RULE_NE };
RuleConditionPayloadSize(uint32_t arg_val, Comp arg_comp) { RuleConditionPayloadSize(uint32_t arg_val, Comp arg_comp) {
val = arg_val; val = arg_val;

View file

@ -3,6 +3,7 @@
#pragma once #pragma once
#include <sys/types.h> // for u_char #include <sys/types.h> // for u_char
#include <cstdint>
#include <functional> #include <functional>
#include <map> #include <map>
#include <set> #include <set>
@ -22,9 +23,9 @@
extern void rules_error(const char* msg); extern void rules_error(const char* msg);
extern void rules_error(const char* msg, const char* addl); extern void rules_error(const char* msg, const char* addl);
extern void rules_error(zeek::detail::Rule* id, const char* msg); extern void rules_error(zeek::detail::Rule* id, const char* msg);
extern int rules_lex(void); extern int rules_lex();
extern int rules_parse(void); extern int rules_parse();
extern "C" int rules_wrap(void); extern "C" int rules_wrap();
extern int rules_line_number; extern int rules_line_number;
extern const char* current_rule_file; extern const char* current_rule_file;
@ -78,8 +79,8 @@ extern uint32_t id_to_uint(const char* id);
class RuleHdrTest { class RuleHdrTest {
public: public:
// Note: Adapt RuleHdrTest::PrintDebug() when changing these enums. // Note: Adapt RuleHdrTest::PrintDebug() when changing these enums.
enum Comp { LE, GE, LT, GT, EQ, NE }; enum Comp : uint8_t { LE, GE, LT, GT, EQ, NE };
enum Prot { NOPROT, IP, IPv6, ICMP, ICMPv6, TCP, UDP, NEXT, IPSrc, IPDst }; enum Prot : uint8_t { NOPROT, IP, IPv6, ICMP, ICMPv6, TCP, UDP, NEXT, IPSrc, IPDst };
RuleHdrTest(Prot arg_prot, uint32_t arg_offset, uint32_t arg_size, Comp arg_comp, maskedvalue_list* arg_vals); RuleHdrTest(Prot arg_prot, uint32_t arg_offset, uint32_t arg_size, Comp arg_comp, maskedvalue_list* arg_vals);
RuleHdrTest(Prot arg_prot, Comp arg_comp, std::vector<IPPrefix> arg_v); RuleHdrTest(Prot arg_prot, Comp arg_comp, std::vector<IPPrefix> arg_v);
@ -111,13 +112,11 @@ private:
friend class RuleMatcher; friend class RuleMatcher;
struct PatternSet { struct PatternSet {
PatternSet() : re() {}
// If we're above the 'RE_level' (see RuleMatcher), this // If we're above the 'RE_level' (see RuleMatcher), this
// expr contains all patterns on this node. If we're on // expr contains all patterns on this node. If we're on
// 'RE_level', it additionally contains all patterns // 'RE_level', it additionally contains all patterns
// of any of its children. // of any of its children.
Specific_RE_Matcher* re; Specific_RE_Matcher* re = nullptr;
// All the patterns and their rule indices. // All the patterns and their rule indices.
string_list patterns; string_list patterns;
@ -267,7 +266,7 @@ public:
* Ordered from greatest to least strength. Matches of the same strength * Ordered from greatest to least strength. Matches of the same strength
* will be in the set in lexicographic order of the MIME type string. * will be in the set in lexicographic order of the MIME type string.
*/ */
using MIME_Matches = std::map<int, std::set<std::string>, std::greater<int>>; using MIME_Matches = std::map<int, std::set<std::string>, std::greater<>>;
/** /**
* Matches a chunk of data against file magic signatures. * Matches a chunk of data against file magic signatures.

View file

@ -37,7 +37,7 @@ public:
template<typename N, typename I> template<typename N, typename I>
void Insert(N&& name, I&& id) { void Insert(N&& name, I&& id) {
local[std::forward<N>(name)] = std::forward<I>(id); local[std::forward<N>(name)] = id;
ordered_vars.push_back(std::forward<I>(id)); ordered_vars.push_back(std::forward<I>(id));
} }

View file

@ -20,8 +20,6 @@ using namespace std;
namespace zeek::detail { namespace zeek::detail {
ScriptCoverageManager::ScriptCoverageManager() : ignoring(0), delim('\t') {}
void ScriptCoverageManager::AddStmt(Stmt* s) { void ScriptCoverageManager::AddStmt(Stmt* s) {
if ( ignoring != 0 || analysis_options.gen_ZAM ) if ( ignoring != 0 || analysis_options.gen_ZAM )
return; return;

View file

@ -19,9 +19,6 @@ using ObjPtr = IntrusivePtr<Obj>;
*/ */
class ScriptCoverageManager { class ScriptCoverageManager {
public: public:
ScriptCoverageManager();
virtual ~ScriptCoverageManager() = default;
/** /**
* Imports Zeek script Stmt usage information from file pointed to by * Imports Zeek script Stmt usage information from file pointed to by
* environment variable ZEEK_PROFILER_FILE. * environment variable ZEEK_PROFILER_FILE.
@ -64,12 +61,12 @@ private:
* Indicates whether new statements will not be considered as part of * Indicates whether new statements will not be considered as part of
* coverage statistics because it was marked with the @no-test tag. * coverage statistics because it was marked with the @no-test tag.
*/ */
uint32_t ignoring; uint32_t ignoring = 0;
/** /**
* The character to use to delimit ScriptCoverageManager output files. Default is '\t'. * The character to use to delimit ScriptCoverageManager output files. Default is '\t'.
*/ */
char delim; char delim = '\t';
/** /**
* This maps Stmt location-desc pairs to the total number of times that * This maps Stmt location-desc pairs to the total number of times that

View file

@ -12,10 +12,7 @@
namespace zeek::detail { namespace zeek::detail {
const float SerializationFormat::GROWTH_FACTOR = 2.5; constexpr float SerializationFormat::GROWTH_FACTOR = 2.5;
SerializationFormat::SerializationFormat()
: output(), output_size(), output_pos(), input(), input_len(), input_pos(), bytes_written(), bytes_read() {}
SerializationFormat::~SerializationFormat() { free(output); } SerializationFormat::~SerializationFormat() { free(output); }

View file

@ -20,7 +20,7 @@ namespace detail {
// Abstract base class. // Abstract base class.
class SerializationFormat { class SerializationFormat {
public: public:
SerializationFormat(); SerializationFormat() = default;
virtual ~SerializationFormat(); virtual ~SerializationFormat();
// Unserialization. // Unserialization.
@ -88,16 +88,16 @@ protected:
static const uint32_t INITIAL_SIZE = 65536; static const uint32_t INITIAL_SIZE = 65536;
static const float GROWTH_FACTOR; static const float GROWTH_FACTOR;
char* output; char* output = nullptr;
uint32_t output_size; uint32_t output_size = 0;
uint32_t output_pos; uint32_t output_pos = 0;
const char* input; const char* input = nullptr;
uint32_t input_len; uint32_t input_len = 0;
uint32_t input_pos; uint32_t input_pos = 0;
int bytes_written; int bytes_written = 0;
int bytes_read; int bytes_read = 0;
}; };
class BinarySerializationFormat final : public SerializationFormat { class BinarySerializationFormat final : public SerializationFormat {

View file

@ -40,6 +40,8 @@ public:
using BSSAlignVec = std::vector<BSSAlign>; using BSSAlignVec = std::vector<BSSAlign>;
Substring() = delete;
explicit Substring(const std::string& string) : String(string), _num(), _new(false) {} explicit Substring(const std::string& string) : String(string), _num(), _new(false) {}
explicit Substring(const String& string) : String(string), _num(), _new(false) {} explicit Substring(const String& string) : String(string), _num(), _new(false) {}
@ -75,8 +77,6 @@ public:
private: private:
using DataMap = std::map<std::string, void*>; using DataMap = std::map<std::string, void*>;
Substring();
// The alignments registered for this substring. // The alignments registered for this substring.
BSSAlignVec _aligns; BSSAlignVec _aligns;
@ -106,7 +106,7 @@ private:
// We support two modes of operation: finding a single optimal alignment, // We support two modes of operation: finding a single optimal alignment,
// and repeated alignments. // and repeated alignments.
// //
enum SWVariant { enum SWVariant : uint8_t {
SW_SINGLE = 0, // return a single, optimum alignment SW_SINGLE = 0, // return a single, optimum alignment
SW_MULTIPLE = 1, // find repeated, non-overlapping alignments SW_MULTIPLE = 1, // find repeated, non-overlapping alignments
}; };

View file

@ -20,7 +20,7 @@ public:
using element_type = T; using element_type = T;
using value_type = typename std::remove_cv<T>::type; using value_type = std::remove_cv_t<T>;
using index_type = size_t; using index_type = size_t;

View file

@ -642,7 +642,7 @@ void SwitchStmt::Init() {
} }
SwitchStmt::SwitchStmt(ExprPtr index, case_list* arg_cases) SwitchStmt::SwitchStmt(ExprPtr index, case_list* arg_cases)
: ExprStmt(STMT_SWITCH, std::move(index)), cases(arg_cases), default_case_idx(-1) { : ExprStmt(STMT_SWITCH, std::move(index)), cases(arg_cases) {
Init(); Init();
bool have_exprs = false; bool have_exprs = false;

View file

@ -21,6 +21,8 @@ class ZAMCompiler; // for "friend" declarations
class ExprListStmt : public Stmt { class ExprListStmt : public Stmt {
public: public:
~ExprListStmt() override;
const ListExpr* ExprList() const { return l.get(); } const ListExpr* ExprList() const { return l.get(); }
const ListExprPtr& ExprListPtr() const { return l; } const ListExprPtr& ExprListPtr() const { return l; }
@ -35,8 +37,6 @@ public:
protected: protected:
ExprListStmt(StmtTag t, ListExprPtr arg_l); ExprListStmt(StmtTag t, ListExprPtr arg_l);
~ExprListStmt() override;
ValPtr Exec(Frame* f, StmtFlowType& flow) override; ValPtr Exec(Frame* f, StmtFlowType& flow) override;
virtual ValPtr DoExec(std::vector<ValPtr> vals, StmtFlowType& flow) = 0; virtual ValPtr DoExec(std::vector<ValPtr> vals, StmtFlowType& flow) = 0;
@ -220,9 +220,9 @@ protected:
// the matching type-based case if it defines one. // the matching type-based case if it defines one.
std::pair<int, ID*> FindCaseLabelMatch(const Val* v) const; std::pair<int, ID*> FindCaseLabelMatch(const Val* v) const;
case_list* cases; case_list* cases = nullptr;
int default_case_idx; int default_case_idx = -1;
CompositeHash* comp_hash; CompositeHash* comp_hash = nullptr;
std::unordered_map<const Val*, int> case_label_value_map; std::unordered_map<const Val*, int> case_label_value_map;
PDict<int> case_label_hash_map; PDict<int> case_label_hash_map;
std::vector<std::pair<ID*, int>> case_label_type_list; std::vector<std::pair<ID*, int>> case_label_type_list;

View file

@ -2,10 +2,12 @@
#pragma once #pragma once
#include <cstdint>
namespace zeek::detail { namespace zeek::detail {
// These are in a separate file to break circular dependences // These are in a separate file to break circular dependences
enum StmtTag { enum StmtTag : uint8_t {
STMT_ALARM, // Does no longer exist but kept to create enums consistent. STMT_ALARM, // Does no longer exist but kept to create enums consistent.
STMT_PRINT, STMT_PRINT,
STMT_EVENT, STMT_EVENT,
@ -33,7 +35,7 @@ enum StmtTag {
#define NUM_STMTS (int(STMT_STD_FUNCTION) + 1) #define NUM_STMTS (int(STMT_STD_FUNCTION) + 1)
}; };
enum StmtFlowType { enum StmtFlowType : uint8_t {
FLOW_NEXT, // continue on to next statement FLOW_NEXT, // continue on to next statement
FLOW_LOOP, // go to top of loop FLOW_LOOP, // go to top of loop
FLOW_BREAK, // break out of loop FLOW_BREAK, // break out of loop

View file

@ -136,9 +136,9 @@ public:
static unsigned int* CurrentTimers() { return current_timers; } static unsigned int* CurrentTimers() { return current_timers; }
// IOSource API methods // IOSource API methods
virtual double GetNextTimeout() override; double GetNextTimeout() override;
virtual void Process() override; void Process() override;
virtual const char* Tag() override { return "TimerMgr"; } const char* Tag() override { return "TimerMgr"; }
/** /**
* Performs some extra initialization on a timer manager. This shouldn't * Performs some extra initialization on a timer manager. This shouldn't

View file

@ -2,16 +2,19 @@
#pragma once #pragma once
#include <cstdint>
namespace zeek::detail { namespace zeek::detail {
class TraversalCallback; class TraversalCallback;
enum TraversalCode { enum TraversalCode : uint8_t {
TC_CONTINUE = 0, TC_CONTINUE = 0,
TC_ABORTALL = 1, TC_ABORTALL = 1,
TC_ABORTSTMT = 2, TC_ABORTSTMT = 2,
}; };
// NOLINTBEGIN(cppcoreguidelines-macro-usage)
#define HANDLE_TC_STMT_PRE(code) \ #define HANDLE_TC_STMT_PRE(code) \
{ \ { \
switch ( code ) { \ switch ( code ) { \
@ -44,4 +47,6 @@ enum TraversalCode {
#define HANDLE_TC_ATTR_PRE(code) HANDLE_TC_STMT_PRE(code) #define HANDLE_TC_ATTR_PRE(code) HANDLE_TC_STMT_PRE(code)
#define HANDLE_TC_ATTR_POST(code) return (code); #define HANDLE_TC_ATTR_POST(code) return (code);
// NOLINTEND(cppcoreguidelines-macro-usage)
} // namespace zeek::detail } // namespace zeek::detail

View file

@ -169,7 +169,7 @@ private:
class Manager final : public iosource::IOSource { class Manager final : public iosource::IOSource {
public: public:
Manager(); Manager();
~Manager(); ~Manager() override;
void InitPostScript(); void InitPostScript();

View file

@ -145,7 +145,7 @@ protected:
*/ */
class EncapsulationStack { class EncapsulationStack {
public: public:
EncapsulationStack() : conns(nullptr) {} EncapsulationStack() = default;
EncapsulationStack(const EncapsulationStack& other) { EncapsulationStack(const EncapsulationStack& other) {
if ( other.conns ) if ( other.conns )
@ -241,7 +241,7 @@ public:
void Pop(); void Pop();
protected: protected:
std::vector<EncapsulatingConn>* conns; std::vector<EncapsulatingConn>* conns = nullptr;
}; };
} // namespace zeek } // namespace zeek

View file

@ -59,7 +59,7 @@ public:
} // namespace detail } // namespace detail
// Zeek types. // Zeek types.
enum TypeTag { enum TypeTag : uint8_t {
TYPE_VOID, // 0 TYPE_VOID, // 0
TYPE_BOOL, // 1 TYPE_BOOL, // 1
TYPE_INT, // 2 TYPE_INT, // 2
@ -91,9 +91,9 @@ extern const char* type_name(TypeTag t);
constexpr bool is_network_order(TypeTag tag) noexcept { return tag == TYPE_PORT; } constexpr bool is_network_order(TypeTag tag) noexcept { return tag == TYPE_PORT; }
enum FunctionFlavor { FUNC_FLAVOR_FUNCTION, FUNC_FLAVOR_EVENT, FUNC_FLAVOR_HOOK }; enum FunctionFlavor : uint8_t { FUNC_FLAVOR_FUNCTION, FUNC_FLAVOR_EVENT, FUNC_FLAVOR_HOOK };
enum InternalTypeTag : uint16_t { enum InternalTypeTag : uint8_t {
TYPE_INTERNAL_VOID, TYPE_INTERNAL_VOID,
TYPE_INTERNAL_INT, TYPE_INTERNAL_INT,
TYPE_INTERNAL_UNSIGNED, TYPE_INTERNAL_UNSIGNED,
@ -356,6 +356,8 @@ protected:
class IndexType : public Type { class IndexType : public Type {
public: public:
~IndexType() override = default;
int MatchesIndex(detail::ListExpr* index) const override; int MatchesIndex(detail::ListExpr* index) const override;
const TypeListPtr& GetIndices() const { return indices; } const TypeListPtr& GetIndices() const { return indices; }
@ -391,8 +393,6 @@ protected:
is_pattern_index = types.size() == 1 && types[0]->Tag() == TYPE_PATTERN; is_pattern_index = types.size() == 1 && types[0]->Tag() == TYPE_PATTERN;
} }
~IndexType() override = default;
void DoDescribe(ODesc* d) const override; void DoDescribe(ODesc* d) const override;
TypeListPtr indices; TypeListPtr indices;
@ -406,7 +406,7 @@ class TableType : public IndexType {
public: public:
TableType(TypeListPtr ind, TypePtr yield); TableType(TypeListPtr ind, TypePtr yield);
~TableType(); ~TableType() override;
/** /**
* Assesses whether an &expire_func attribute's function type is compatible * Assesses whether an &expire_func attribute's function type is compatible

View file

@ -85,6 +85,9 @@ inline UID::UID(const UID& other) {
} }
inline UID& UID::operator=(const UID& other) { inline UID& UID::operator=(const UID& other) {
if ( this == &other )
return *this;
memmove(uid, other.uid, sizeof(uid)); memmove(uid, other.uid, sizeof(uid));
initialized = other.initialized; initialized = other.initialized;
return *this; return *this;

View file

@ -18,12 +18,12 @@
// We have four different port name spaces: TCP, UDP, ICMP, and UNKNOWN. // We have four different port name spaces: TCP, UDP, ICMP, and UNKNOWN.
// We distinguish between them based on the bits specified in the *_PORT_MASK // We distinguish between them based on the bits specified in the *_PORT_MASK
// entries specified below. // entries specified below.
#define NUM_PORT_SPACES 4 constexpr int NUM_PORT_SPACES = 4;
#define PORT_SPACE_MASK 0x30000 constexpr uint32_t PORT_SPACE_MASK = 0x30000;
#define TCP_PORT_MASK 0x10000 constexpr uint32_t TCP_PORT_MASK = 0x10000;
#define UDP_PORT_MASK 0x20000 constexpr uint32_t UDP_PORT_MASK = 0x20000;
#define ICMP_PORT_MASK 0x30000 constexpr uint32_t ICMP_PORT_MASK = 0x30000;
namespace zeek { namespace zeek {
@ -157,6 +157,7 @@ public:
return cast_intrusive<T>(type); return cast_intrusive<T>(type);
} }
// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
#define UNDERLYING_ACCESSOR_DECL(ztype, ctype, name) ctype name() const; #define UNDERLYING_ACCESSOR_DECL(ztype, ctype, name) ctype name() const;
UNDERLYING_ACCESSOR_DECL(detail::IntValImplementation, zeek_int_t, AsInt) UNDERLYING_ACCESSOR_DECL(detail::IntValImplementation, zeek_int_t, AsInt)
@ -433,12 +434,12 @@ public:
// Same as for IntVal: no Get() method needed. // Same as for IntVal: no Get() method needed.
}; };
#define Microseconds 1e-6 constexpr double Microseconds = 1e-6;
#define Milliseconds 1e-3 constexpr double Milliseconds = 1e-3;
#define Seconds 1.0 constexpr double Seconds = 1.0;
#define Minutes (60 * Seconds) constexpr double Minutes = (60 * Seconds);
#define Hours (60 * Minutes) constexpr double Hours = (60 * Minutes);
#define Days (24 * Hours) constexpr double Days = (24 * Hours);
class IntervalVal final : public detail::DoubleValImplementation { class IntervalVal final : public detail::DoubleValImplementation {
public: public:
@ -1056,7 +1057,7 @@ protected:
double CallExpireFunc(ListValPtr idx); double CallExpireFunc(ListValPtr idx);
// Enum for the different kinds of changes an &on_change handler can see // Enum for the different kinds of changes an &on_change handler can see
enum OnChangeType { ELEMENT_NEW, ELEMENT_CHANGED, ELEMENT_REMOVED, ELEMENT_EXPIRED }; enum OnChangeType : uint8_t { ELEMENT_NEW, ELEMENT_CHANGED, ELEMENT_REMOVED, ELEMENT_EXPIRED };
// Calls &change_func. // Calls &change_func.
void CallChangeFunc(const ValPtr& index, const ValPtr& old_value, OnChangeType tpe); void CallChangeFunc(const ValPtr& index, const ValPtr& old_value, OnChangeType tpe);
@ -1717,6 +1718,7 @@ private:
std::vector<TypePtr>* yield_types = nullptr; std::vector<TypePtr>* yield_types = nullptr;
}; };
// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
#define UNDERLYING_ACCESSOR_DEF(ztype, ctype, name) \ #define UNDERLYING_ACCESSOR_DEF(ztype, ctype, name) \
inline ctype Val::name() const { return static_cast<const ztype*>(this)->Get(); } inline ctype Val::name() const { return static_cast<const ztype*>(this)->Get(); }

View file

@ -22,7 +22,7 @@ class Stmt;
using StmtPtr = IntrusivePtr<Stmt>; using StmtPtr = IntrusivePtr<Stmt>;
using ScopePtr = IntrusivePtr<Scope>; using ScopePtr = IntrusivePtr<Scope>;
enum DeclType { enum DeclType : uint8_t {
VAR_REGULAR, VAR_REGULAR,
VAR_CONST, VAR_CONST,
VAR_REDEF, VAR_REDEF,

View file

@ -3,6 +3,7 @@
#pragma once #pragma once
#include <sys/types.h> #include <sys/types.h>
#include <cstdint>
#include <iosfwd> #include <iosfwd>
#include <string> #include <string>
#include <string_view> #include <string_view>
@ -103,7 +104,7 @@ public:
*/ */
std::string_view ToStdStringView() const; std::string_view ToStdStringView() const;
enum render_style { enum render_style : uint8_t {
ESC_NONE = 0, ESC_NONE = 0,
ESC_ESC = (1 << 1), // '\' -> "\\" ESC_ESC = (1 << 1), // '\' -> "\\"
ESC_QUOT = (1 << 2), // '"' -> "\"", ''' -> "\'" ESC_QUOT = (1 << 2), // '"' -> "\"", ''' -> "\'"

View file

@ -772,6 +772,8 @@ private:
static ID id_counter; static ID id_counter;
}; };
// NOLINTBEGIN(cppcoreguidelines-macro-usage)
/** /**
* Convenience macro to add a new timer. * Convenience macro to add a new timer.
*/ */
@ -781,25 +783,28 @@ private:
/** /**
* Internal convenience macro to iterate over the list of child analyzers. * Internal convenience macro to iterate over the list of child analyzers.
*/ */
#define LOOP_OVER_CHILDREN(var) for ( auto var = children.begin(); var != children.end(); ++var ) #define LOOP_OVER_CHILDREN(var) for ( auto(var) = children.begin(); (var) != children.end(); ++(var) )
/** /**
* Internal convenience macro to iterate over the constant list of child * Internal convenience macro to iterate over the constant list of child
* analyzers. * analyzers.
*/ */
#define LOOP_OVER_CONST_CHILDREN(var) for ( auto var = children.cbegin(); var != children.cend(); ++var ) #define LOOP_OVER_CONST_CHILDREN(var) for ( auto(var) = children.cbegin(); (var) != children.cend(); ++(var) )
/** /**
* Convenience macro to iterate over a given list of child analyzers. * Convenience macro to iterate over a given list of child analyzers.
*/ */
#define LOOP_OVER_GIVEN_CHILDREN(var, the_kids) for ( auto var = the_kids.begin(); var != the_kids.end(); ++var ) #define LOOP_OVER_GIVEN_CHILDREN(var, the_kids) \
for ( auto(var) = (the_kids).begin(); (var) != (the_kids).end(); ++(var) )
/** /**
* Convenience macro to iterate over a given constant list of child * Convenience macro to iterate over a given constant list of child
* analyzers. * analyzers.
*/ */
#define LOOP_OVER_GIVEN_CONST_CHILDREN(var, the_kids) \ #define LOOP_OVER_GIVEN_CONST_CHILDREN(var, the_kids) \
for ( auto var = the_kids.cbegin(); var != the_kids.cend(); ++var ) for ( auto(var) = (the_kids).cbegin(); (var) != (the_kids).cend(); ++(var) )
// NOLINTEND(cppcoreguidelines-macro-usage)
/** /**
* Support analyzer preprocess input before it reaches an analyzer's main * Support analyzer preprocess input before it reaches an analyzer's main
@ -892,9 +897,21 @@ private:
}; };
// The following need to be consistent with zeek.init. // The following need to be consistent with zeek.init.
#define CONTENTS_NONE 0 constexpr int CONTENTS_NONE = 0;
#define CONTENTS_ORIG 1 constexpr int CONTENTS_ORIG = 1;
#define CONTENTS_RESP 2 constexpr int CONTENTS_RESP = 2;
#define CONTENTS_BOTH 3 constexpr int CONTENTS_BOTH = 3;
} // namespace zeek::analyzer } // namespace zeek::analyzer
[[deprecated("Remove in v8.1. Use version in zeek::analyzer namespace.")]] constexpr int CONTENTS_NONE =
zeek::analyzer::CONTENTS_NONE;
[[deprecated("Remove in v8.1. Use version in zeek::analyzer namespace.")]] constexpr int CONTENTS_ORIG =
zeek::analyzer::CONTENTS_ORIG;
[[deprecated("Remove in v8.1. Use version in zeek::analyzer namespace.")]] constexpr int CONTENTS_RESP =
zeek::analyzer::CONTENTS_RESP;
[[deprecated("Remove in v8.1. Use version in zeek::analyzer namespace.")]] constexpr int CONTENTS_BOTH =
zeek::analyzer::CONTENTS_BOTH;

View file

@ -386,15 +386,18 @@ extern analyzer::Manager* analyzer_mgr;
// Macros for analyzer debug logging which include the connection id into the // Macros for analyzer debug logging which include the connection id into the
// message. // message.
// NOLINTBEGIN(cppcoreguidelines-macro-usage)
#ifdef DEBUG #ifdef DEBUG
#define DBG_ANALYZER(conn, txt) \ #define DBG_ANALYZER(conn, txt) \
DBG_LOG(zeek::DBG_ANALYZER, "%s " txt, \ DBG_LOG(zeek::DBG_ANALYZER, "%s " txt, \
fmt_conn_id(conn->OrigAddr(), ntohs(conn->OrigPort()), conn->RespAddr(), ntohs(conn->RespPort()))); fmt_conn_id((conn)->OrigAddr(), ntohs((conn)->OrigPort()), (conn)->RespAddr(), \
ntohs((conn)->RespPort())));
#define DBG_ANALYZER_ARGS(conn, fmt, ...) \ #define DBG_ANALYZER_ARGS(conn, fmt, ...) \
DBG_LOG(zeek::DBG_ANALYZER, "%s " fmt, \ DBG_LOG(zeek::DBG_ANALYZER, "%s " fmt, \
fmt_conn_id(conn->OrigAddr(), ntohs(conn->OrigPort()), conn->RespAddr(), ntohs(conn->RespPort())), \ fmt_conn_id((conn)->OrigAddr(), ntohs((conn)->OrigPort()), (conn)->RespAddr(), ntohs((conn)->RespPort())), \
##__VA_ARGS__); ##__VA_ARGS__);
#else #else
#define DBG_ANALYZER(conn, txt) #define DBG_ANALYZER(conn, txt)
#define DBG_ANALYZER_ARGS(conn, fmt, ...) #define DBG_ANALYZER_ARGS(conn, fmt, ...)
#endif #endif
// NOLINTEND(cppcoreguidelines-macro-usage)

View file

@ -6,7 +6,7 @@
#include "zeek/analyzer/protocol/tcp/TCP.h" #include "zeek/analyzer/protocol/tcp/TCP.h"
#define BTTRACKER_BUF 2048 constexpr uint32_t BTTRACKER_BUF = 2048;
namespace zeek { namespace zeek {
@ -20,7 +20,7 @@ namespace analyzer::bittorrent {
namespace detail { namespace detail {
enum BTT_States { enum BTT_States : uint8_t {
BTT_REQ_GET, BTT_REQ_GET,
BTT_REQ_HEADER, BTT_REQ_HEADER,
BTT_REQ_DONE, BTT_REQ_DONE,
@ -32,9 +32,15 @@ enum BTT_States {
}; };
// "benc" = Bencode ("Bee-Encode"), per http://en.wikipedia.org/wiki/Bencode // "benc" = Bencode ("Bee-Encode"), per http://en.wikipedia.org/wiki/Bencode
enum BTT_BencTypes { BENC_TYPE_INT = 0, BENC_TYPE_STR = 1, BENC_TYPE_DIR = 2, BENC_TYPE_LIST = 3, BENC_TYPE_NONE = 10 }; enum BTT_BencTypes : uint8_t {
BENC_TYPE_INT = 0,
BENC_TYPE_STR = 1,
BENC_TYPE_DIR = 2,
BENC_TYPE_LIST = 3,
BENC_TYPE_NONE = 10
};
enum BTT_BencStates { enum BTT_BencStates : uint8_t {
BENC_STATE_EMPTY, BENC_STATE_EMPTY,
BENC_STATE_INT1, BENC_STATE_INT1,
BENC_STATE_INT2, BENC_STATE_INT2,

View file

@ -4,7 +4,7 @@
%include zeek.pac %include zeek.pac
%extern{ %extern{
#define MSGLEN_LIMIT 0x40000 constexpr uint32_t MSGLEN_LIMIT = 0x40000;
#include "zeek/analyzer/protocol/bittorrent/events.bif.h" #include "zeek/analyzer/protocol/bittorrent/events.bif.h"
%} %}

View file

@ -11,19 +11,7 @@
namespace zeek::analyzer::conn_size { namespace zeek::analyzer::conn_size {
ConnSize_Analyzer::ConnSize_Analyzer(Connection* c) ConnSize_Analyzer::ConnSize_Analyzer(Connection* c) : Analyzer("CONNSIZE", c) { start_time = c->StartTime(); }
: Analyzer("CONNSIZE", c),
orig_bytes(),
resp_bytes(),
orig_pkts(),
resp_pkts(),
orig_bytes_thresh(),
resp_bytes_thresh(),
orig_pkts_thresh(),
resp_pkts_thresh(),
duration_thresh() {
start_time = c->StartTime();
}
void ConnSize_Analyzer::Init() { void ConnSize_Analyzer::Init() {
Analyzer::Init(); Analyzer::Init();

View file

@ -32,18 +32,18 @@ protected:
void ThresholdEvent(EventHandlerPtr f, uint64_t threshold, bool is_orig); void ThresholdEvent(EventHandlerPtr f, uint64_t threshold, bool is_orig);
uint64_t orig_bytes; uint64_t orig_bytes = 0;
uint64_t resp_bytes; uint64_t resp_bytes = 0;
uint64_t orig_pkts; uint64_t orig_pkts = 0;
uint64_t resp_pkts; uint64_t resp_pkts = 0;
uint64_t orig_bytes_thresh; uint64_t orig_bytes_thresh = 0;
uint64_t resp_bytes_thresh; uint64_t resp_bytes_thresh = 0;
uint64_t orig_pkts_thresh; uint64_t orig_pkts_thresh = 0;
uint64_t resp_pkts_thresh; uint64_t resp_pkts_thresh = 0;
double start_time; double start_time = 0.0;
double duration_thresh; double duration_thresh = 0.0;
}; };
// Exposed to make it available to script optimization. // Exposed to make it available to script optimization.

View file

@ -7,7 +7,7 @@
namespace zeek::analyzer::dns { namespace zeek::analyzer::dns {
namespace detail { namespace detail {
enum DNS_Opcode { enum DNS_Opcode : uint8_t {
DNS_OP_QUERY = 0, ///< standard query DNS_OP_QUERY = 0, ///< standard query
DNS_OP_IQUERY = 1, ///< reverse query DNS_OP_IQUERY = 1, ///< reverse query
@ -22,16 +22,17 @@ enum DNS_Opcode {
NETBIOS_REFRESH = 8, NETBIOS_REFRESH = 8,
}; };
enum DNS_Code { enum DNS_Code : uint16_t {
DNS_CODE_OK = 0, ///< no error DNS_CODE_OK = 0, ///< no error
DNS_CODE_FORMAT_ERR = 1, ///< format error DNS_CODE_FORMAT_ERR = 1, ///< format error
DNS_CODE_SERVER_FAIL = 2, ///< server failure DNS_CODE_SERVER_FAIL = 2, ///< server failure
DNS_CODE_NAME_ERR = 3, ///< no such domain DNS_CODE_NAME_ERR = 3, ///< no such domain
DNS_CODE_NOT_IMPL = 4, ///< not implemented DNS_CODE_NOT_IMPL = 4, ///< not implemented
DNS_CODE_REFUSED = 5, ///< refused DNS_CODE_REFUSED = 5, ///< refused
DNS_CODE_RESERVED = 65535, ///< Force clang-tidy to accept this enum being 16 bits
}; };
enum RR_Type { enum RR_Type : uint16_t {
TYPE_A = 1, ///< host address TYPE_A = 1, ///< host address
TYPE_NS = 2, ///< authoritative name server TYPE_NS = 2, ///< authoritative name server
TYPE_CNAME = 5, ///< canonical name TYPE_CNAME = 5, ///< canonical name
@ -80,10 +81,13 @@ enum RR_Type {
TYPE_BINDS = 65534, ///< Bind9's Private Type Rec for signaling state of signing process TYPE_BINDS = 65534, ///< Bind9's Private Type Rec for signaling state of signing process
}; };
#define DNS_CLASS_IN 1 enum DNS_Class : uint16_t {
#define DNS_CLASS_ANY 255 DNS_CLASS_IN = 1,
DNS_CLASS_ANY = 255,
DNS_CLASS_RESERVED = 65535, ///< Force clang-tidy to accept this enum being 16 bits
};
enum DNS_AnswerType { enum DNS_AnswerType : uint8_t {
DNS_QUESTION, DNS_QUESTION,
DNS_ANSWER, DNS_ANSWER,
DNS_AUTHORITY, DNS_AUTHORITY,
@ -92,7 +96,7 @@ enum DNS_AnswerType {
// https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml // https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml
// DNS EDNS0 Option Codes (OPT) // DNS EDNS0 Option Codes (OPT)
enum EDNS_OPT_Type { enum EDNS_OPT_Type : uint16_t {
TYPE_LLQ = 1, ///< https://www.iana.org/go/draft-sekar-dns-llq-06 TYPE_LLQ = 1, ///< https://www.iana.org/go/draft-sekar-dns-llq-06
TYPE_UL = 2, ///< http://files.dns-sd.org/draft-sekar-dns-ul.txt TYPE_UL = 2, ///< http://files.dns-sd.org/draft-sekar-dns-ul.txt
TYPE_NSID = 3, ///< RFC5001 TYPE_NSID = 3, ///< RFC5001
@ -112,7 +116,7 @@ enum EDNS_OPT_Type {
TYPE_DEVICE_ID = 26946 ///< https://docs.umbrella.com/developer/networkdevices-api/identifying-dns-traffic2 TYPE_DEVICE_ID = 26946 ///< https://docs.umbrella.com/developer/networkdevices-api/identifying-dns-traffic2
}; };
enum DNSSEC_Algo { enum DNSSEC_Algo : uint8_t {
reserved0 = 0, reserved0 = 0,
RSA_MD5 = 1, ///< [RFC2537] NOT RECOMMENDED RSA_MD5 = 1, ///< [RFC2537] NOT RECOMMENDED
Diffie_Hellman = 2, ///< [RFC2539] Diffie_Hellman = 2, ///< [RFC2539]
@ -134,7 +138,7 @@ enum DNSSEC_Algo {
reserved255 = 255, reserved255 = 255,
}; };
enum DNSSEC_Digest { enum DNSSEC_Digest : uint8_t {
reserved = 0, reserved = 0,
SHA1 = 1, ///< [RFC3110] MANDATORY SHA1 = 1, ///< [RFC3110] MANDATORY
SHA256 = 2, SHA256 = 2,
@ -144,7 +148,7 @@ enum DNSSEC_Digest {
///< all keys are defined in RFC draft ///< all keys are defined in RFC draft
///< https://datatracker.ietf.org/doc/html/draft-ietf-dnsop-svcb-https-07#section-14.3.2 ///< https://datatracker.ietf.org/doc/html/draft-ietf-dnsop-svcb-https-07#section-14.3.2
enum SVCPARAM_Key { enum SVCPARAM_Key : uint8_t {
mandatory = 0, mandatory = 0,
alpn = 1, alpn = 1,
no_default_alpn = 2, no_default_alpn = 2,
@ -392,7 +396,7 @@ protected:
bool is_netbios; bool is_netbios;
}; };
enum TCP_DNS_state { enum TCP_DNS_state : uint8_t {
DNS_LEN_HI, ///< looking for the high-order byte of the length DNS_LEN_HI, ///< looking for the high-order byte of the length
DNS_LEN_LO, ///< looking for the low-order byte of the length DNS_LEN_LO, ///< looking for the low-order byte of the length
DNS_MESSAGE_BUFFER, ///< building up the message in the buffer DNS_MESSAGE_BUFFER, ///< building up the message in the buffer

View file

@ -14,15 +14,13 @@
namespace zeek::analyzer::ftp { namespace zeek::analyzer::ftp {
FTP_Analyzer::FTP_Analyzer(Connection* conn) : analyzer::tcp::TCP_ApplicationAnalyzer("FTP", conn) { FTP_Analyzer::FTP_Analyzer(Connection* conn) : analyzer::tcp::TCP_ApplicationAnalyzer("FTP", conn) {
pending_reply = 0;
nvt_orig = new analyzer::login::NVT_Analyzer(conn, true); nvt_orig = new analyzer::login::NVT_Analyzer(conn, true);
nvt_orig->SetIsNULSensitive(true); nvt_orig->SetIsNULSensitive(true);
nvt_orig->SetCRLFAsEOL(LF_as_EOL); nvt_orig->SetCRLFAsEOL(tcp::LF_as_EOL);
nvt_resp = new analyzer::login::NVT_Analyzer(conn, false); nvt_resp = new analyzer::login::NVT_Analyzer(conn, false);
nvt_resp->SetIsNULSensitive(true); nvt_resp->SetIsNULSensitive(true);
nvt_resp->SetCRLFAsEOL(LF_as_EOL); nvt_resp->SetCRLFAsEOL(tcp::LF_as_EOL);
nvt_resp->SetPeer(nvt_orig); nvt_resp->SetPeer(nvt_orig);
nvt_orig->SetPeer(nvt_resp); nvt_orig->SetPeer(nvt_resp);

View file

@ -22,7 +22,7 @@ public:
protected: protected:
analyzer::login::NVT_Analyzer* nvt_orig; analyzer::login::NVT_Analyzer* nvt_orig;
analyzer::login::NVT_Analyzer* nvt_resp; analyzer::login::NVT_Analyzer* nvt_resp;
uint32_t pending_reply; // code associated with multi-line reply, or 0 uint32_t pending_reply = 0; // code associated with multi-line reply, or 0
std::string auth_requested; // AUTH method requested std::string auth_requested; // AUTH method requested
bool tls_active = false; // starttls active bool tls_active = false; // starttls active
}; };
@ -36,8 +36,7 @@ protected:
*/ */
class FTP_ADAT_Analyzer final : public analyzer::SupportAnalyzer { class FTP_ADAT_Analyzer final : public analyzer::SupportAnalyzer {
public: public:
FTP_ADAT_Analyzer(Connection* conn, bool arg_orig) FTP_ADAT_Analyzer(Connection* conn, bool arg_orig) : SupportAnalyzer("FTP_ADAT", conn, arg_orig) {}
: SupportAnalyzer("FTP_ADAT", conn, arg_orig), first_token(true) {}
void DeliverStream(int len, const u_char* data, bool orig) override; void DeliverStream(int len, const u_char* data, bool orig) override;
@ -45,7 +44,7 @@ protected:
// Used by the client-side analyzer to tell if it needs to peek at the // Used by the client-side analyzer to tell if it needs to peek at the
// initial context token and do sanity checking (i.e. does it look like // initial context token and do sanity checking (i.e. does it look like
// a TLS/SSL handshake token). // a TLS/SSL handshake token).
bool first_token; bool first_token = true;
}; };
} // namespace zeek::analyzer::ftp } // namespace zeek::analyzer::ftp

View file

@ -15,7 +15,7 @@
namespace zeek::analyzer::http { namespace zeek::analyzer::http {
enum CHUNKED_TRANSFER_STATE { enum CHUNKED_TRANSFER_STATE : uint8_t {
NON_CHUNKED_TRANSFER, NON_CHUNKED_TRANSFER,
BEFORE_CHUNK, BEFORE_CHUNK,
EXPECT_CHUNK_SIZE, EXPECT_CHUNK_SIZE,
@ -44,7 +44,7 @@ public:
bool Undelivered(int64_t len); bool Undelivered(int64_t len);
int64_t BodyLength() const { return body_length; } int64_t BodyLength() const { return body_length; }
int64_t HeaderLength() const { return header_length; } int64_t HeaderLength() const { return header_length; }
void SkipBody() { deliver_body = 0; } void SkipBody() { deliver_body = false; }
const std::string& FileID() const { return precomputed_file_id; } const std::string& FileID() const { return precomputed_file_id; }
protected: protected:
@ -59,7 +59,7 @@ protected:
int expect_body; int expect_body;
int64_t body_length; int64_t body_length;
int64_t header_length; int64_t header_length;
enum { IDENTITY, GZIP, COMPRESS, DEFLATE } encoding; enum : uint8_t { IDENTITY, GZIP, COMPRESS, DEFLATE } encoding;
analyzer::zip::ZIP_Analyzer* zip; analyzer::zip::ZIP_Analyzer* zip;
bool deliver_body; bool deliver_body;
bool is_partial_content; bool is_partial_content;
@ -81,7 +81,7 @@ protected:
void SubmitAllHeaders() override; void SubmitAllHeaders() override;
}; };
enum { enum : uint8_t {
HTTP_BODY_NOT_EXPECTED, HTTP_BODY_NOT_EXPECTED,
HTTP_BODY_EXPECTED, HTTP_BODY_EXPECTED,
HTTP_BODY_MAYBE, HTTP_BODY_MAYBE,

View file

@ -16,11 +16,11 @@ namespace irc {
* \brief Main class for analyzing IRC traffic. * \brief Main class for analyzing IRC traffic.
*/ */
class IRC_Analyzer final : public analyzer::tcp::TCP_ApplicationAnalyzer { class IRC_Analyzer final : public analyzer::tcp::TCP_ApplicationAnalyzer {
enum { enum : uint8_t {
WAIT_FOR_REGISTRATION, WAIT_FOR_REGISTRATION,
REGISTERED, REGISTERED,
}; };
enum { enum : uint8_t {
NO_ZIP, NO_ZIP,
ACCEPT_ZIP, ACCEPT_ZIP,
ZIP_LOADED, ZIP_LOADED,

View file

@ -17,10 +17,10 @@ namespace zeek::analyzer::krb {
class KRB_Analyzer final : public analyzer::Analyzer { class KRB_Analyzer final : public analyzer::Analyzer {
public: public:
explicit KRB_Analyzer(Connection* conn); explicit KRB_Analyzer(Connection* conn);
virtual ~KRB_Analyzer(); ~KRB_Analyzer() override;
virtual void Done(); void Done() override;
virtual void DeliverPacket(int len, const u_char* data, bool orig, uint64_t seq, const IP_Hdr* ip, int caplen); void DeliverPacket(int len, const u_char* data, bool orig, uint64_t seq, const IP_Hdr* ip, int caplen) override;
static analyzer::Analyzer* Instantiate(Connection* conn) { return new KRB_Analyzer(conn); } static analyzer::Analyzer* Instantiate(Connection* conn) { return new KRB_Analyzer(conn); }

View file

@ -24,7 +24,7 @@ static RE_Matcher* re_login_timeouts;
static RE_Matcher* init_RE(ListVal* l); static RE_Matcher* init_RE(ListVal* l);
Login_Analyzer::Login_Analyzer(const char* name, Connection* conn) Login_Analyzer::Login_Analyzer(const char* name, Connection* conn)
: analyzer::tcp::TCP_ApplicationAnalyzer(name, conn), user_text() { : analyzer::tcp::TCP_ApplicationAnalyzer(name, conn) {
state = LOGIN_STATE_AUTHENTICATE; state = LOGIN_STATE_AUTHENTICATE;
num_user_lines_seen = lines_scanned = 0; num_user_lines_seen = lines_scanned = 0;
// Set last_failure_num_user_lines so we will always generate // Set last_failure_num_user_lines so we will always generate

View file

@ -6,7 +6,7 @@
namespace zeek::analyzer::login { namespace zeek::analyzer::login {
enum login_state { enum login_state : uint8_t {
LOGIN_STATE_AUTHENTICATE, // trying to authenticate LOGIN_STATE_AUTHENTICATE, // trying to authenticate
LOGIN_STATE_LOGGED_IN, // successful authentication LOGIN_STATE_LOGGED_IN, // successful authentication
LOGIN_STATE_SKIP, // skip any further processing LOGIN_STATE_SKIP, // skip any further processing
@ -14,10 +14,14 @@ enum login_state {
}; };
// If no action by this many lines, we're definitely confused. // If no action by this many lines, we're definitely confused.
#define MAX_AUTHENTICATE_LINES 50 constexpr int MAX_AUTHENTICATE_LINES = 50;
// Maximum # lines look after login for failure. // Maximum # lines look after login for failure.
#define MAX_LOGIN_LOOKAHEAD 10 constexpr int MAX_LOGIN_LOOKAHEAD = 10;
// If we have more user text than this unprocessed, we complain about
// excessive typeahead.
constexpr int MAX_USER_TEXT = 12;
class Login_Analyzer : public analyzer::tcp::TCP_ApplicationAnalyzer { class Login_Analyzer : public analyzer::tcp::TCP_ApplicationAnalyzer {
public: public:
@ -61,10 +65,7 @@ protected:
bool HaveTypeahead() const { return num_user_text > 0; } bool HaveTypeahead() const { return num_user_text > 0; }
void FlushEmptyTypeahead(); void FlushEmptyTypeahead();
// If we have more user text than this unprocessed, we complain about char* user_text[MAX_USER_TEXT] = {nullptr};
// excessive typeahead.
#define MAX_USER_TEXT 12
char* user_text[MAX_USER_TEXT];
int user_text_first, user_text_last; // indices into user_text int user_text_first, user_text_last; // indices into user_text
int num_user_text; // number of entries in user_text int num_user_text; // number of entries in user_text

View file

@ -316,8 +316,7 @@ void TelnetBinaryOption::InconsistentOption(unsigned int /* type */) {
} // namespace detail } // namespace detail
NVT_Analyzer::NVT_Analyzer(Connection* conn, bool orig) NVT_Analyzer::NVT_Analyzer(Connection* conn, bool orig) : analyzer::tcp::ContentLine_Analyzer("NVT", conn, orig) {}
: analyzer::tcp::ContentLine_Analyzer("NVT", conn, orig), options() {}
NVT_Analyzer::~NVT_Analyzer() { NVT_Analyzer::~NVT_Analyzer() {
for ( int i = 0; i < num_options; ++i ) for ( int i = 0; i < num_options; ++i )
@ -413,7 +412,7 @@ void NVT_Analyzer::DeliverChunk(int& len, const u_char*& data) {
switch ( c ) { switch ( c ) {
case '\r': case '\r':
if ( CRLFAsEOL() & CR_as_EOL ) { if ( CRLFAsEOL() & tcp::CR_as_EOL ) {
buf[offset] = '\0'; buf[offset] = '\0';
ForwardStream(offset, buf, IsOrig()); ForwardStream(offset, buf, IsOrig());
offset = 0; offset = 0;
@ -424,7 +423,7 @@ void NVT_Analyzer::DeliverChunk(int& len, const u_char*& data) {
case '\n': case '\n':
if ( last_char == '\r' ) { if ( last_char == '\r' ) {
if ( CRLFAsEOL() & CR_as_EOL ) if ( CRLFAsEOL() & tcp::CR_as_EOL )
// we already emitted, skip // we already emitted, skip
; ;
else { else {
@ -435,7 +434,7 @@ void NVT_Analyzer::DeliverChunk(int& len, const u_char*& data) {
} }
} }
else if ( CRLFAsEOL() & LF_as_EOL ) { else if ( CRLFAsEOL() & tcp::LF_as_EOL ) {
buf[offset] = '\0'; buf[offset] = '\0';
ForwardStream(offset, buf, IsOrig()); ForwardStream(offset, buf, IsOrig());
offset = 0; offset = 0;
@ -475,7 +474,7 @@ void NVT_Analyzer::DeliverChunk(int& len, const u_char*& data) {
default: buf[offset++] = c; break; default: buf[offset++] = c; break;
} }
if ( ! (CRLFAsEOL() & CR_as_EOL) && last_char == '\r' && c != '\n' && c != '\0' ) { if ( ! (CRLFAsEOL() & tcp::CR_as_EOL) && last_char == '\r' && c != '\n' && c != '\0' ) {
if ( Conn()->FlagEvent(SINGULAR_CR) ) if ( Conn()->FlagEvent(SINGULAR_CR) )
Weird("line_terminated_with_single_CR"); Weird("line_terminated_with_single_CR");
} }

View file

@ -164,7 +164,7 @@ protected:
int encrypting_mode = 0; int encrypting_mode = 0;
char* auth_name = nullptr; char* auth_name = nullptr;
TelnetOption* options[NUM_TELNET_OPTIONS]; TelnetOption* options[NUM_TELNET_OPTIONS] = {nullptr};
int num_options = 0; int num_options = 0;
}; };

View file

@ -9,7 +9,7 @@ namespace zeek::analyzer::login {
class Rsh_Analyzer; class Rsh_Analyzer;
enum rsh_state { enum rsh_state : uint8_t {
RSH_FIRST_NULL, // waiting to see first NUL RSH_FIRST_NULL, // waiting to see first NUL
RSH_CLIENT_USER_NAME, // scanning client user name up to NUL RSH_CLIENT_USER_NAME, // scanning client user name up to NUL
RSH_SERVER_USER_NAME, // scanning server user name up to NUL RSH_SERVER_USER_NAME, // scanning server user name up to NUL

View file

@ -9,7 +9,7 @@ namespace zeek::analyzer::login {
class Rlogin_Analyzer; class Rlogin_Analyzer;
enum rlogin_state { enum rlogin_state : uint8_t {
RLOGIN_FIRST_NULL, // waiting to see first NUL RLOGIN_FIRST_NULL, // waiting to see first NUL
RLOGIN_CLIENT_USER_NAME, // scanning client user name up to NUL RLOGIN_CLIENT_USER_NAME, // scanning client user name up to NUL
RLOGIN_SERVER_USER_NAME, // scanning server user name up to NUL RLOGIN_SERVER_USER_NAME, // scanning server user name up to NUL

View file

@ -30,19 +30,19 @@ namespace analyzer::mime {
// MIME Constants // MIME Constants
#define HT '\011' constexpr char HT = '\011';
#define SP '\040' constexpr char SP = '\040';
#define CR '\015' constexpr char CR = '\015';
#define LF '\012' constexpr char LF = '\012';
enum MIME_CONTENT_TYPE { enum MIME_CONTENT_TYPE : uint8_t {
CONTENT_TYPE_MULTIPART, CONTENT_TYPE_MULTIPART,
CONTENT_TYPE_MESSAGE, CONTENT_TYPE_MESSAGE,
CONTENT_TYPE_TEXT, CONTENT_TYPE_TEXT,
CONTENT_TYPE_OTHER, // image | audio | video | application | <other> CONTENT_TYPE_OTHER, // image | audio | video | application | <other>
}; };
enum MIME_EVENT_TYPE { enum MIME_EVENT_TYPE : uint8_t {
MIME_EVENT_ILLEGAL_FORMAT, MIME_EVENT_ILLEGAL_FORMAT,
MIME_EVENT_ILLEGAL_ENCODING, MIME_EVENT_ILLEGAL_ENCODING,
MIME_EVENT_CONTENT_GAP, MIME_EVENT_CONTENT_GAP,

View file

@ -69,7 +69,7 @@ protected:
size_t buf_len; // size off msg_buf size_t buf_len; // size off msg_buf
}; };
#define NCP_TCPIP_HEADER_LENGTH 8 constexpr int NCP_TCPIP_HEADER_LENGTH = 8;
class NCP_FrameBuffer : public FrameBuffer { class NCP_FrameBuffer : public FrameBuffer {
public: public:

View file

@ -7,7 +7,7 @@
namespace zeek::analyzer::netbios_ssn { namespace zeek::analyzer::netbios_ssn {
namespace detail { namespace detail {
enum NetbiosSSN_Opcode { enum NetbiosSSN_Opcode : uint8_t {
NETBIOS_SSN_MSG = 0x0, NETBIOS_SSN_MSG = 0x0,
NETBIOS_DGM_DIRECT_UNIQUE = 0x10, NETBIOS_DGM_DIRECT_UNIQUE = 0x10,
NETBIOS_DGM_DIRECT_GROUP = 0x11, NETBIOS_DGM_DIRECT_GROUP = 0x11,
@ -59,7 +59,7 @@ struct NetbiosDGM_RawMsgHdr {
uint16_t offset; uint16_t offset;
}; };
enum NetbiosSSN_State { enum NetbiosSSN_State : uint8_t {
NETBIOS_SSN_TYPE, // looking for type field NETBIOS_SSN_TYPE, // looking for type field
NETBIOS_SSN_FLAGS, // looking for flag field NETBIOS_SSN_FLAGS, // looking for flag field
NETBIOS_SSN_LEN_HI, // looking for high-order byte of length NETBIOS_SSN_LEN_HI, // looking for high-order byte of length

View file

@ -1,10 +1,10 @@
%extern{ %extern{
#include <cmath> #include <cmath>
#define FRAC_16 pow(2,-16) #define FRAC_16 std::pow(2,-16)
#define FRAC_32 pow(2,-32) #define FRAC_32 std::pow(2,-32)
// NTP defines the epoch from 1900, not 1970 // NTP defines the epoch from 1900, not 1970
#define EPOCH_OFFSET -2208988800 constexpr double EPOCH_OFFSET = -2208988800;
%} %}
%header{ %header{

View file

@ -14,7 +14,7 @@
namespace zeek::analyzer::pia { namespace zeek::analyzer::pia {
PIA::PIA(analyzer::Analyzer* arg_as_analyzer) : state(INIT), as_analyzer(arg_as_analyzer), conn(), current_packet() {} PIA::PIA(analyzer::Analyzer* arg_as_analyzer) : as_analyzer(arg_as_analyzer), current_packet() {}
PIA::~PIA() { ClearBuffer(&pkt_buffer); } PIA::~PIA() { ClearBuffer(&pkt_buffer); }

View file

@ -73,7 +73,8 @@ protected:
void PIA_DeliverPacket(int len, const u_char* data, bool is_orig, uint64_t seq, const IP_Hdr* ip, int caplen, void PIA_DeliverPacket(int len, const u_char* data, bool is_orig, uint64_t seq, const IP_Hdr* ip, int caplen,
bool clear_state); bool clear_state);
enum State { INIT, BUFFERING, MATCHING_ONLY, SKIPPING } state; enum State : uint8_t { INIT, BUFFERING, MATCHING_ONLY, SKIPPING };
State state = INIT;
// Buffers one chunk of data. Used both for packet payload (incl. // Buffers one chunk of data. Used both for packet payload (incl.
// sequence numbers for TCP) and chunks of a reassembled stream. // sequence numbers for TCP) and chunks of a reassembled stream.
@ -114,8 +115,8 @@ private:
// Joint backend for the two public FirstPacket() methods. // Joint backend for the two public FirstPacket() methods.
void FirstPacket(bool is_orig, const std::optional<TransportProto>& proto, const IP_Hdr* ip); void FirstPacket(bool is_orig, const std::optional<TransportProto>& proto, const IP_Hdr* ip);
analyzer::Analyzer* as_analyzer; analyzer::Analyzer* as_analyzer = nullptr;
Connection* conn; Connection* conn = nullptr;
DataBlock current_packet; DataBlock current_packet;
}; };
@ -166,7 +167,7 @@ protected:
} }
void DeliverPacket(int len, const u_char* data, bool is_orig, uint64_t seq, const IP_Hdr* ip, int caplen) override { void DeliverPacket(int len, const u_char* data, bool is_orig, uint64_t seq, const IP_Hdr* ip, int caplen) override {
Analyzer::DeliverPacket(len, data, is_orig, seq, ip, caplen); TCP_ApplicationAnalyzer::DeliverPacket(len, data, is_orig, seq, ip, caplen);
PIA_DeliverPacket(len, data, is_orig, seq, ip, caplen, false); PIA_DeliverPacket(len, data, is_orig, seq, ip, caplen, false);
} }

View file

@ -19,11 +19,11 @@
namespace zeek::analyzer::pop3 { namespace zeek::analyzer::pop3 {
namespace detail { namespace detail {
enum POP3_Cmd { enum POP3_Cmd : uint8_t {
#include "POP3_cmd.def" #include "POP3_cmd.def"
}; };
enum POP3_MasterState { enum POP3_MasterState : uint8_t {
POP3_START, POP3_START,
POP3_AUTHORIZATION, POP3_AUTHORIZATION,
POP3_TRANSACTION, POP3_TRANSACTION,
@ -31,7 +31,7 @@ enum POP3_MasterState {
POP3_FINISHED, POP3_FINISHED,
}; };
enum POP3_State { enum POP3_State : uint8_t {
START, START,
USER, USER,
PASS, PASS,
@ -57,7 +57,7 @@ enum POP3_State {
END, END,
}; };
enum POP3_SubState { enum POP3_SubState : uint8_t {
POP3_OK, POP3_OK,
POP3_WOK, POP3_WOK,
}; };

View file

@ -1,12 +1,12 @@
refine connection RDPEUDP_Conn += { refine connection RDPEUDP_Conn += {
%member{ %member{
enum RDPEUDP_STATE { enum RDPEUDP_STATE : uint8_t {
NEED_SYN = 0x1, NEED_SYN = 0x1,
NEED_SYNACK = 0x2, NEED_SYNACK = 0x2,
NED_ACK = 0x3, NED_ACK = 0x3,
ESTABLISHED = 0x4, ESTABLISHED = 0x4,
}; };
enum RDPUDP_VERSION_INFO_FLAG { enum RDPUDP_VERSION_INFO_FLAG : uint16_t {
RDPUDP_PROTOCOL_VERSION_1 = 0x0001, RDPUDP_PROTOCOL_VERSION_1 = 0x0001,
RDPUDP_PROTOCOL_VERSION_2 = 0x0002, RDPUDP_PROTOCOL_VERSION_2 = 0x0002,
RDPUDP_PROTOCOL_VERSION_3 = 0x0101 RDPUDP_PROTOCOL_VERSION_3 = 0x0101

View file

@ -69,7 +69,7 @@ refine flow RFB_Flow += {
refine connection RFB_Conn += { refine connection RFB_Conn += {
%member{ %member{
enum ServerState { enum ServerState : uint8_t {
SERVER_VERSION = 0, SERVER_VERSION = 0,
SERVER_AUTH_TYPE = 1, SERVER_AUTH_TYPE = 1,
SERVER_AUTH_TYPE37 = 2, SERVER_AUTH_TYPE37 = 2,
@ -84,7 +84,7 @@ refine connection RFB_Conn += {
SERVER_INVALID =100, SERVER_INVALID =100,
}; };
enum ClientState { enum ClientState : uint8_t {
CLIENT_VERSION = 0, CLIENT_VERSION = 0,
CLIENT_AUTH_SELECTION = 1, CLIENT_AUTH_SELECTION = 1,
CLIENT_AUTH_VNC_RESPONSE = 2, CLIENT_AUTH_VNC_RESPONSE = 2,

View file

@ -625,7 +625,7 @@ void Contents_RPC::DeliverStream(int len, const u_char* data, bool orig) {
} }
RPC_Analyzer::RPC_Analyzer(const char* name, Connection* conn, detail::RPC_Interpreter* arg_interp) RPC_Analyzer::RPC_Analyzer(const char* name, Connection* conn, detail::RPC_Interpreter* arg_interp)
: analyzer::tcp::TCP_ApplicationAnalyzer(name, conn), interp(arg_interp), orig_rpc(), resp_rpc() { : analyzer::tcp::TCP_ApplicationAnalyzer(name, conn), interp(arg_interp) {
if ( Conn()->ConnTransport() == TRANSPORT_UDP ) if ( Conn()->ConnTransport() == TRANSPORT_UDP )
ADD_ANALYZER_TIMER(&RPC_Analyzer::ExpireTimer, run_state::network_time + zeek::detail::rpc_timeout, true, ADD_ANALYZER_TIMER(&RPC_Analyzer::ExpireTimer, run_state::network_time + zeek::detail::rpc_timeout, true,
zeek::detail::TIMER_RPC_EXPIRE); zeek::detail::TIMER_RPC_EXPIRE);

View file

@ -7,17 +7,17 @@
namespace zeek::analyzer::rpc { namespace zeek::analyzer::rpc {
namespace detail { namespace detail {
enum { enum : uint8_t {
RPC_CALL = 0, RPC_CALL = 0,
RPC_REPLY = 1, RPC_REPLY = 1,
}; };
enum { enum : uint8_t {
RPC_MSG_ACCEPTED = 0, RPC_MSG_ACCEPTED = 0,
RPC_MSG_DENIED = 1, RPC_MSG_DENIED = 1,
}; };
enum { enum : uint8_t {
RPC_SUCCESS = 0, RPC_SUCCESS = 0,
RPC_PROG_UNAVAIL = 1, RPC_PROG_UNAVAIL = 1,
RPC_PROG_MISMATCH = 2, RPC_PROG_MISMATCH = 2,
@ -26,12 +26,12 @@ enum {
RPC_SYSTEM_ERR = 5, RPC_SYSTEM_ERR = 5,
}; };
enum { enum : uint8_t {
RPC_MISMATCH = 0, RPC_MISMATCH = 0,
RPC_AUTH_ERROR = 1, RPC_AUTH_ERROR = 1,
}; };
enum { enum : uint8_t {
RPC_AUTH_BADCRED = 1, RPC_AUTH_BADCRED = 1,
RPC_AUTH_REJECTEDCRED = 2, RPC_AUTH_REJECTEDCRED = 2,
RPC_AUTH_BADVERF = 3, RPC_AUTH_BADVERF = 3,
@ -39,7 +39,7 @@ enum {
RPC_AUTH_TOOWEAK = 5, RPC_AUTH_TOOWEAK = 5,
}; };
enum { enum : uint8_t {
RPC_AUTH_NULL = 0, RPC_AUTH_NULL = 0,
RPC_AUTH_UNIX = 1, RPC_AUTH_UNIX = 1,
RPC_AUTH_SHORT = 2, RPC_AUTH_SHORT = 2,
@ -196,14 +196,14 @@ public:
~Contents_RPC() override = default; ~Contents_RPC() override = default;
protected: protected:
enum state_t { enum state_t : uint8_t {
WAIT_FOR_MESSAGE, WAIT_FOR_MESSAGE,
WAIT_FOR_MARKER, WAIT_FOR_MARKER,
WAIT_FOR_DATA, WAIT_FOR_DATA,
WAIT_FOR_LAST_DATA, WAIT_FOR_LAST_DATA,
}; };
enum resync_state_t { enum resync_state_t : uint8_t {
NEED_RESYNC, NEED_RESYNC,
RESYNC_WAIT_FOR_MSG_START, RESYNC_WAIT_FOR_MSG_START,
RESYNC_WAIT_FOR_FULL_MSG, RESYNC_WAIT_FOR_FULL_MSG,
@ -250,8 +250,8 @@ protected:
detail::RPC_Interpreter* interp; detail::RPC_Interpreter* interp;
Contents_RPC* orig_rpc; Contents_RPC* orig_rpc = nullptr;
Contents_RPC* resp_rpc; Contents_RPC* resp_rpc = nullptr;
}; };
} // namespace zeek::analyzer::rpc } // namespace zeek::analyzer::rpc

View file

@ -42,7 +42,7 @@ struct BDATCmd parse_bdat_arg(int length, const char* arg);
* *
* Helper class to avoid true/false parameters. * Helper class to avoid true/false parameters.
*/ */
enum class ChunkType { enum class ChunkType : uint8_t {
None, None,
Intermediate, Intermediate,
Last, Last,

View file

@ -16,12 +16,12 @@ namespace detail {
class SMTP_BDAT_Analyzer; class SMTP_BDAT_Analyzer;
enum SMTP_Cmd { enum SMTP_Cmd : uint8_t {
#include "SMTP_cmd.def" #include "SMTP_cmd.def"
}; };
// State is updated on every SMTP reply. // State is updated on every SMTP reply.
enum SMTP_State { enum SMTP_State : uint8_t {
SMTP_CONNECTED, // 0: before the opening message SMTP_CONNECTED, // 0: before the opening message
SMTP_INITIATED, // 1: after opening message 220, EHLO/HELO expected SMTP_INITIATED, // 1: after opening message 220, EHLO/HELO expected
SMTP_NOT_AVAILABLE, // 2: after opening message 554, etc. SMTP_NOT_AVAILABLE, // 2: after opening message 554, etc.
@ -50,7 +50,7 @@ public:
void ConnectionFinished(bool half_finished) override; void ConnectionFinished(bool half_finished) override;
void Undelivered(uint64_t seq, int len, bool orig) override; void Undelivered(uint64_t seq, int len, bool orig) override;
void SkipData() { skip_data = 1; } // skip delivery of data lines void SkipData() { skip_data = true; } // skip delivery of data lines
static analyzer::Analyzer* Instantiate(Connection* conn) { return new SMTP_Analyzer(conn); } static analyzer::Analyzer* Instantiate(Connection* conn) { return new SMTP_Analyzer(conn); }

View file

@ -10,10 +10,10 @@ namespace zeek::analyzer::snmp {
class SNMP_Analyzer final : public analyzer::Analyzer { class SNMP_Analyzer final : public analyzer::Analyzer {
public: public:
explicit SNMP_Analyzer(Connection* conn); explicit SNMP_Analyzer(Connection* conn);
virtual ~SNMP_Analyzer(); ~SNMP_Analyzer() override;
virtual void Done(); void Done() override;
virtual void DeliverPacket(int len, const u_char* data, bool orig, uint64_t seq, const IP_Hdr* ip, int caplen); void DeliverPacket(int len, const u_char* data, bool orig, uint64_t seq, const IP_Hdr* ip, int caplen) override;
static analyzer::Analyzer* InstantiateAnalyzer(Connection* conn) { return new SNMP_Analyzer(conn); } static analyzer::Analyzer* InstantiateAnalyzer(Connection* conn) { return new SNMP_Analyzer(conn); }

View file

@ -8,8 +8,8 @@
namespace zeek::analyzer::tcp { namespace zeek::analyzer::tcp {
#define CR_as_EOL 1 constexpr int CR_as_EOL = 1;
#define LF_as_EOL 2 constexpr int LF_as_EOL = 2;
// Slightly smaller than 16MB so that the buffer is not unnecessarily resized to 32M. // Slightly smaller than 16MB so that the buffer is not unnecessarily resized to 32M.
constexpr auto DEFAULT_MAX_LINE_LENGTH = 16 * 1024 * 1024 - 100; constexpr auto DEFAULT_MAX_LINE_LENGTH = 16 * 1024 * 1024 - 100;
@ -122,3 +122,9 @@ protected:
}; };
} // namespace zeek::analyzer::tcp } // namespace zeek::analyzer::tcp
// These were previously #defined, so they have to be outside of the namespace.
[[deprecated("Remove in v8.1, use the version in the zeek:::analyzer::tcp namespace")]] constexpr int CR_as_EOL =
zeek::analyzer::tcp::CR_as_EOL;
[[deprecated("Remove in v8.1, use the version in the zeek:::analyzer::tcp namespace")]] constexpr int LF_as_EOL =
zeek::analyzer::tcp::LF_as_EOL;

View file

@ -195,8 +195,7 @@ RecordVal* TCPStats_Endpoint::BuildStats() {
return stats; return stats;
} }
TCPStats_Analyzer::TCPStats_Analyzer(Connection* c) TCPStats_Analyzer::TCPStats_Analyzer(Connection* c) : TCP_ApplicationAnalyzer("TCPSTATS", c) {}
: TCP_ApplicationAnalyzer("TCPSTATS", c), orig_stats(), resp_stats() {}
TCPStats_Analyzer::~TCPStats_Analyzer() { TCPStats_Analyzer::~TCPStats_Analyzer() {
delete orig_stats; delete orig_stats;

Some files were not shown because too many files have changed in this diff Show more