diff --git a/.clang-tidy b/.clang-tidy index 77889d4f90..82ea5c2108 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -1,6 +1,7 @@ Checks: [-*, bugprone-*, performance-*, + modernize-*, # Enable a very limited number of the cppcoreguidelines checkers. # See the notes for some of the rest of them below. @@ -12,6 +13,7 @@ Checks: [-*, -bugprone-narrowing-conversions, -bugprone-unchecked-optional-access, -performance-unnecessary-value-param, + -modernize-use-equals-default, # The following cause either lots of pointless or advisory warnings -bugprone-easily-swappable-parameters, @@ -26,11 +28,19 @@ Checks: [-*, # and so this one generates a lot of warnings. -bugprone-switch-missing-default-case, - # These report warnings that are rather difficult to fix. + # These report warnings that are rather difficult to fix or are things + # we simply don't want to fix. -bugprone-undefined-memory-manipulation, -bugprone-pointer-arithmetic-on-polymorphic-object, -bugprone-empty-catch, -bugprone-exception-escape, + -modernize-avoid-c-arrays, + -modernize-concat-nested-namespaces, + -modernize-raw-string-literal, + -modernize-use-auto, + -modernize-use-nodiscard, + -modernize-use-ranges, + -modernize-use-trailing-return-type, # This one returns a bunch of findings in DFA and the sqlite library. # We're unlikely to fix either of them. @@ -45,4 +55,11 @@ Checks: [-*, #cppcoreguidelines-pro-type-cstyle-cast, #cppcoreguidelines-pro-type-static-cast-downcast, #cppcoreguidelines-special-member-functions, + + # These are features in newer version of C++ that we don't have + # access to yet. + -modernize-use-starts-ends-with, + -modernize-use-std-format, + -modernize-use-std-numbers, + -modernize-use-std-print, ] diff --git a/CHANGES b/CHANGES index 2ad3a55229..b2c41af80d 100644 --- a/CHANGES +++ b/CHANGES @@ -1,3 +1,13 @@ +8.0.0-dev.406 | 2025-06-06 11:45:33 -0700 + + * Move initialization of RandTest members to header (Tim Wojtulewicz, Corelight) + + * Update .clang-tidy to have modernize-* enabled with some exclusions (Tim Wojtulewicz, Corelight) + + * Fix clang-tidy modernize findings (Tim Wojtulewicz, Corelight) + + * Update bifcl submodule with clang-tidy fixes [nomail] (Tim Wojtulewicz, Corelight) + 8.0.0-dev.389 | 2025-06-06 10:43:07 -0700 * Make Zeekygen docs generation (-X) imply parse-only (-a) (Christian Kreibich, Corelight) diff --git a/VERSION b/VERSION index aef9280438..1fb077a4b5 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -8.0.0-dev.389 +8.0.0-dev.406 diff --git a/auxil/bifcl b/auxil/bifcl index 49e956cd27..82eb0ce207 160000 --- a/auxil/bifcl +++ b/auxil/bifcl @@ -1 +1 @@ -Subproject commit 49e956cd278ad0ca72040536ff606f4bb8d4224f +Subproject commit 82eb0ce207ef9d11bda880d3ff1287f9cd3b769e diff --git a/src/Attr.cc b/src/Attr.cc index 82605d4da6..038d5ac1fb 100644 --- a/src/Attr.cc +++ b/src/Attr.cc @@ -136,9 +136,9 @@ void Attr::DescribeReST(ODesc* d, bool shorten) const { expr->Eval(nullptr)->Describe(&dd); std::string s = dd.Description(); - for ( size_t i = 0; i < s.size(); ++i ) - if ( s[i] == '\n' ) - s[i] = ' '; + for ( auto& c : s ) + if ( c == '\n' ) + c = ' '; add_long_expr_string(d, s, shorten); } diff --git a/src/DNS_Mapping.cc b/src/DNS_Mapping.cc index 4d7c6ff01d..db23fbd023 100644 --- a/src/DNS_Mapping.cc +++ b/src/DNS_Mapping.cc @@ -128,7 +128,7 @@ void DNS_Mapping::Init(struct hostent* h) { names.emplace_back(h->h_name); if ( h->h_addr_list ) { - for ( int i = 0; h->h_addr_list[i] != NULL; ++i ) { + for ( int i = 0; h->h_addr_list[i] != nullptr; ++i ) { if ( h->h_addrtype == AF_INET ) addrs.emplace_back(IPv4, (uint32_t*)h->h_addr_list[i], IPAddr::Network); else if ( h->h_addrtype == AF_INET6 ) @@ -203,11 +203,11 @@ TEST_CASE("dns_mapping init host") { struct hostent he; he.h_name = util::copy_string("testing.home"); - he.h_aliases = NULL; + he.h_aliases = nullptr; he.h_addrtype = AF_INET; he.h_length = sizeof(in_addr); - std::vector addrs = {&in4, NULL}; + std::vector addrs = {&in4, nullptr}; he.h_addr_list = reinterpret_cast(addrs.data()); DNS_Mapping mapping("testing.home", &he, 123, T_A); @@ -241,11 +241,11 @@ TEST_CASE("dns_mapping init addr") { struct hostent he; he.h_name = util::copy_string("testing.home"); - he.h_aliases = NULL; + he.h_aliases = nullptr; he.h_addrtype = AF_INET; he.h_length = sizeof(in_addr); - std::vector addrs = {&in4, NULL}; + std::vector addrs = {&in4, nullptr}; he.h_addr_list = reinterpret_cast(addrs.data()); DNS_Mapping mapping(addr, &he, 123); @@ -282,11 +282,11 @@ TEST_CASE("dns_mapping save reload") { struct hostent he; he.h_name = util::copy_string("testing.home"); - he.h_aliases = NULL; + he.h_aliases = nullptr; he.h_addrtype = AF_INET; he.h_length = sizeof(in_addr); - std::vector addrs = {&in4, NULL}; + std::vector addrs = {&in4, nullptr}; he.h_addr_list = reinterpret_cast(addrs.data()); // Create a temporary file in memory and fseek to the end of it so we're at @@ -350,11 +350,11 @@ TEST_CASE("dns_mapping multiple addresses") { struct hostent he; he.h_name = util::copy_string("testing.home"); - he.h_aliases = NULL; + he.h_aliases = nullptr; he.h_addrtype = AF_INET; he.h_length = sizeof(in_addr); - std::vector addrs = {&in4_1, &in4_2, NULL}; + std::vector addrs = {&in4_1, &in4_2, nullptr}; he.h_addr_list = reinterpret_cast(addrs.data()); DNS_Mapping mapping("testing.home", &he, 123, T_A); @@ -382,11 +382,11 @@ TEST_CASE("dns_mapping ipv6") { struct hostent he; he.h_name = util::copy_string("testing.home"); - he.h_aliases = NULL; + he.h_aliases = nullptr; he.h_addrtype = AF_INET6; he.h_length = sizeof(in6_addr); - std::vector addrs = {&in6, NULL}; + std::vector addrs = {&in6, nullptr}; he.h_addr_list = reinterpret_cast(addrs.data()); DNS_Mapping mapping(addr, &he, 123); diff --git a/src/DNS_Mgr.cc b/src/DNS_Mgr.cc index f43a9688a7..e9e58208df 100644 --- a/src/DNS_Mgr.cc +++ b/src/DNS_Mgr.cc @@ -189,7 +189,7 @@ void DNS_Request::MakeRequest(ares_channel channel, DNS_Mgr* mgr) { // back in the same request if use ares_getaddrinfo() so we can store them both // in the same mapping. ares_addrinfo_hints hints = {ARES_AI_CANONNAME, AF_UNSPEC, 0, 0}; - ares_getaddrinfo(channel, host.c_str(), NULL, &hints, addrinfo_cb, req_data.release()); + ares_getaddrinfo(channel, host.c_str(), nullptr, &hints, addrinfo_cb, req_data.release()); } else { std::string query_host; @@ -214,7 +214,7 @@ void DNS_Request::MakeRequest(ares_channel channel, DNS_Mgr* mgr) { // Store this so it can be destroyed when the request is destroyed. this->query_rec = std::move(dnsrec); - ares_send_dnsrec(channel, query_rec.get(), query_cb, req_data.release(), NULL); + ares_send_dnsrec(channel, query_rec.get(), query_cb, req_data.release(), nullptr); } } @@ -302,7 +302,7 @@ static void addrinfo_cb(void* arg, int status, int timeouts, struct ares_addrinf else { std::vector addrs; std::vector addrs6; - for ( ares_addrinfo_node* entry = result->nodes; entry != NULL; entry = entry->ai_next ) { + for ( ares_addrinfo_node* entry = result->nodes; entry != nullptr; entry = entry->ai_next ) { if ( entry->ai_family == AF_INET ) { struct sockaddr_in* addr = reinterpret_cast(entry->ai_addr); addrs.push_back(&addr->sin_addr); @@ -315,7 +315,7 @@ static void addrinfo_cb(void* arg, int status, int timeouts, struct ares_addrinf if ( ! addrs.empty() ) { // Push a null on the end so the addr list has a final point during later parsing. - addrs.push_back(NULL); + addrs.push_back(nullptr); struct hostent he{}; he.h_name = util::copy_string(result->name); @@ -330,7 +330,7 @@ static void addrinfo_cb(void* arg, int status, int timeouts, struct ares_addrinf if ( ! addrs6.empty() ) { // Push a null on the end so the addr list has a final point during later parsing. - addrs6.push_back(NULL); + addrs6.push_back(nullptr); struct hostent he{}; he.h_name = util::copy_string(result->name); @@ -389,7 +389,7 @@ static void query_cb(void* arg, ares_status_t status, size_t timeouts, const are if ( type == ARES_REC_TYPE_PTR ) { const char* txt = ares_dns_rr_get_str(rr, ARES_RR_PTR_DNAME); - if ( txt == NULL ) { + if ( txt == nullptr ) { // According to the c-ares docs, this can happen but only in cases of "misuse". We // still need to check for it though. error = true; @@ -411,7 +411,7 @@ static void query_cb(void* arg, ares_status_t status, size_t timeouts, const are // TODO: We only process the first abin in the response. There might be more. size_t abin_len; const unsigned char* abin = ares_dns_rr_get_abin(rr, ARES_RR_TXT_DATA, 0, &abin_len); - if ( abin == NULL ) { + if ( abin == nullptr ) { // According to the c-ares docs, this can happen but only in cases of "misuse". We // still need to check for it though. error = true; @@ -1306,9 +1306,9 @@ double DNS_Mgr::GetNextTimeout() { return -1; struct timeval tv; - struct timeval* tvp = ares_timeout(channel, NULL, &tv); + struct timeval* tvp = ares_timeout(channel, nullptr, &tv); - // If you pass NULL as the max time argument to ares_timeout, it will return null if there + // If you pass nullptr as the max time argument to ares_timeout, it will return null if there // isn't anything waiting to be processed. if ( ! tvp ) return -1; diff --git a/src/DebugCmds.cc b/src/DebugCmds.cc index 47136e299c..6bfb08f581 100644 --- a/src/DebugCmds.cc +++ b/src/DebugCmds.cc @@ -60,7 +60,7 @@ static void lookup_global_symbols_regex(const string& orig_regex, vector& m for ( const auto& sym : syms ) { ID* nextid = sym.second.get(); if ( ! func_only || nextid->GetType()->Tag() == TYPE_FUNC ) - if ( ! regexec(&re, nextid->Name(), 0, 0, 0) ) + if ( ! regexec(&re, nextid->Name(), 0, nullptr, 0) ) matches.push_back(nextid); } } @@ -336,19 +336,19 @@ int dbg_cmd_break(DebugCmd cmd, const vector& args) { if ( string_is_regex(args[0]) ) { vector choices; choose_global_symbols_regex(args[0], choices, true); - for ( unsigned int i = 0; i < choices.size(); ++i ) - locstrings.emplace_back(choices[i]->Name()); + for ( const auto& choice : choices ) + locstrings.emplace_back(choice->Name()); } else locstrings.push_back(args[0]); - for ( unsigned int strindex = 0; strindex < locstrings.size(); ++strindex ) { - debug_msg("Setting breakpoint on %s:\n", locstrings[strindex].c_str()); - vector plrs = parse_location_string(locstrings[strindex]); + for ( const auto& loc_str : locstrings ) { + debug_msg("Setting breakpoint on %s:\n", loc_str.c_str()); + vector plrs = parse_location_string(loc_str); for ( const auto& plr : plrs ) { DbgBreakpoint* bp = new DbgBreakpoint(); bp->SetID(g_debugger_state.NextBPID()); - if ( ! bp->SetLocation(plr, locstrings[strindex]) ) { + if ( ! bp->SetLocation(plr, loc_str) ) { debug_msg("Breakpoint not set.\n"); delete bp; } diff --git a/src/DebugLogger.cc b/src/DebugLogger.cc index e3184afa6c..518c698862 100644 --- a/src/DebugLogger.cc +++ b/src/DebugLogger.cc @@ -44,7 +44,7 @@ void DebugLogger::OpenDebugLog(const char* filename) { } } - util::detail::setvbuf(file, NULL, _IOLBF, 0); + util::detail::setvbuf(file, nullptr, _IOLBF, 0); } else file = stderr; @@ -90,9 +90,9 @@ void DebugLogger::EnableStreams(const char* s) { std::string ltok{util::strreplace(util::strtolower(tok), "_", "-")}; if ( strcasecmp("all", tok) == 0 ) { - for ( int i = 0; i < NUM_DBGS; ++i ) { - streams[i].enabled = true; - enabled_streams.insert(streams[i].prefix); + for ( auto& strm : streams ) { + strm.enabled = true; + enabled_streams.insert(strm.prefix); } all = true; @@ -130,7 +130,7 @@ void DebugLogger::EnableStreams(const char* s) { reporter->FatalError("unknown debug stream '%s', try -B help.\n", tok); next: - tok = strtok(0, ","); + tok = strtok(nullptr, ","); } delete[] tmp; diff --git a/src/Dict.cc b/src/Dict.cc index 3ef5047337..14caafb6c1 100644 --- a/src/Dict.cc +++ b/src/Dict.cc @@ -39,7 +39,7 @@ TEST_CASE("dict operation") { dict.Remove(key2); CHECK(dict.Length() == 0); uint32_t* lookup2 = dict.Lookup(key2); - CHECK(lookup2 == (uint32_t*)0); + CHECK(lookup2 == (uint32_t*)nullptr); delete key2; CHECK(dict.MaxLength() == 1); @@ -89,7 +89,7 @@ TEST_CASE("dict nthentry") { // NthEntry returns null for unordered dicts uint32_t* lookup = unordered.NthEntry(0); - CHECK(lookup == (uint32_t*)0); + CHECK(lookup == (uint32_t*)nullptr); // Ordered dicts are based on order of insertion, nothing about the // data itself diff --git a/src/Discard.cc b/src/Discard.cc index 8ad64a880e..07c55fc874 100644 --- a/src/Discard.cc +++ b/src/Discard.cc @@ -134,7 +134,7 @@ Val* Discarder::BuildData(const u_char* data, int hdrlen, int len, int caplen) { caplen -= hdrlen; data += hdrlen; - len = std::max(std::min(std::min(len, caplen), discarder_maxlen), 0); + len = std::max(std::min({len, caplen, discarder_maxlen}), 0); return new StringVal(new String(data, len, true)); } diff --git a/src/EventHandler.cc b/src/EventHandler.cc index 2d60aed663..57cc0703c6 100644 --- a/src/EventHandler.cc +++ b/src/EventHandler.cc @@ -65,8 +65,8 @@ void EventHandler::Call(Args* vl, bool no_remote, double ts) { xs.Reserve(vl->size()); bool valid_args = true; - for ( size_t index = 0; index < vl->size(); ++index ) { - if ( ! xs.Add((*vl)[index]) ) { + for ( const auto& v : *vl ) { + if ( ! xs.Add(v) ) { valid_args = false; auto_publish.clear(); reporter->Error("failed auto-remote event '%s', disabled", Name()); diff --git a/src/EventTrace.cc b/src/EventTrace.cc index c348bcd023..33301e9fb8 100644 --- a/src/EventTrace.cc +++ b/src/EventTrace.cc @@ -51,7 +51,7 @@ static std::string escape_string(const u_char* b, int len) { return res + "\""; } -ValTrace::ValTrace(const ValPtr& _v) : v(_v) { +ValTrace::ValTrace(ValPtr _v) : v(std::move(_v)) { t = v->GetType(); switch ( t->Tag() ) { diff --git a/src/EventTrace.h b/src/EventTrace.h index 2c86efb7b2..eb3bd17cd8 100644 --- a/src/EventTrace.h +++ b/src/EventTrace.h @@ -45,7 +45,7 @@ using DeltaVector = std::vector>; // be readily compared against future instances. class ValTrace { public: - ValTrace(const ValPtr& v); + ValTrace(ValPtr v); ~ValTrace() = default; const ValPtr& GetVal() const { return v; } diff --git a/src/File.cc b/src/File.cc index 63b761de56..e63a9a6a7e 100644 --- a/src/File.cc +++ b/src/File.cc @@ -180,7 +180,7 @@ void File::SetBuf(bool arg_buffered) { if ( ! f ) return; - if ( util::detail::setvbuf(f, NULL, arg_buffered ? _IOFBF : _IOLBF, 0) != 0 ) + if ( util::detail::setvbuf(f, nullptr, arg_buffered ? _IOFBF : _IOLBF, 0) != 0 ) reporter->Error("setvbuf failed"); buffered = arg_buffered; diff --git a/src/Func.cc b/src/Func.cc index c612f0b979..a476521b55 100644 --- a/src/Func.cc +++ b/src/Func.cc @@ -696,8 +696,8 @@ StmtPtr ScriptFunc::AddInits(StmtPtr body, const std::vector& inits) { auto stmt_series = with_location_of(make_intrusive(), body); auto init = with_location_of(make_intrusive(inits), body); - stmt_series->Stmts().push_back(std::move(init)); - stmt_series->Stmts().push_back(std::move(body)); + stmt_series->Stmts().emplace_back(std::move(init)); + stmt_series->Stmts().emplace_back(std::move(body)); return stmt_series; } diff --git a/src/IP.cc b/src/IP.cc index c9d7807e76..b8e20ab6cb 100644 --- a/src/IP.cc +++ b/src/IP.cc @@ -457,8 +457,8 @@ static inline bool isIPv6ExtHeader(uint8_t type) { } IPv6_Hdr_Chain::~IPv6_Hdr_Chain() { - for ( size_t i = 0; i < chain.size(); ++i ) - delete chain[i]; + for ( auto& c : chain ) + delete c; delete homeAddr; delete finalDst; } @@ -702,9 +702,9 @@ IPv6_Hdr_Chain* IPv6_Hdr_Chain::Copy(const ip6_hdr* new_hdr) const { const u_char* new_data = (const u_char*)new_hdr; const u_char* old_data = chain[0]->Data(); - for ( size_t i = 0; i < chain.size(); ++i ) { - int off = chain[i]->Data() - old_data; - rval->chain.push_back(new IPv6_Hdr(chain[i]->Type(), new_data + off)); + for ( const auto& c : chain ) { + int off = c->Data() - old_data; + rval->chain.push_back(new IPv6_Hdr(c->Type(), new_data + off)); } return rval; diff --git a/src/IPAddr.cc b/src/IPAddr.cc index a8517daaa9..c22498b22b 100644 --- a/src/IPAddr.cc +++ b/src/IPAddr.cc @@ -205,8 +205,8 @@ bool IPAddr::ConvertString(const char* s, in6_addr* result) { if ( s[n] != '\0' ) return false; - for ( auto i = 0; i < 4; ++i ) - if ( a[i] < 0 || a[i] > 255 ) + for ( int num : a ) + if ( num < 0 || num > 255 ) return false; uint32_t addr = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3]; diff --git a/src/PolicyFile.cc b/src/PolicyFile.cc index 323c0fd89f..fb75d8afa3 100644 --- a/src/PolicyFile.cc +++ b/src/PolicyFile.cc @@ -121,8 +121,8 @@ bool LoadPolicyFileText(const char* policy_filename, const std::optionallines.size()); ++i ) - assert(pf->lines[i][0] != '\n'); + for ( const auto& l : pf->lines ) + assert(l[0] != '\n'); return true; } diff --git a/src/PrefixTable.cc b/src/PrefixTable.cc index a30dcc1568..95fff9e09c 100644 --- a/src/PrefixTable.cc +++ b/src/PrefixTable.cc @@ -19,8 +19,8 @@ prefix_t* PrefixTable::MakePrefix(const IPAddr& addr, int width) { } IPPrefix PrefixTable::PrefixToIPPrefix(prefix_t* prefix) { - return IPPrefix(IPAddr(IPv6, reinterpret_cast(&prefix->add.sin6), IPAddr::Network), prefix->bitlen, - true); + return {IPAddr(IPv6, reinterpret_cast(&prefix->add.sin6), IPAddr::Network), + static_cast(prefix->bitlen), true}; } void* PrefixTable::Insert(const IPAddr& addr, int width, void* data) { diff --git a/src/RE.cc b/src/RE.cc index 1ece4ebe2b..5b3aa944ea 100644 --- a/src/RE.cc +++ b/src/RE.cc @@ -19,7 +19,7 @@ zeek::detail::NFA_Machine* zeek::detail::nfa = nullptr; bool zeek::detail::case_insensitive = false; bool zeek::detail::re_single_line = false; -extern int RE_parse(void); +extern int RE_parse(); extern void RE_set_input(const char* str); extern void RE_done_with_scan(); @@ -271,8 +271,8 @@ void Specific_RE_Matcher::Dump(FILE* f) { dfa->Dump(f); } inline void RE_Match_State::AddMatches(const AcceptingSet& as, MatchPos position) { using am_idx = std::pair; - for ( AcceptingSet::const_iterator it = as.begin(); it != as.end(); ++it ) - accepted_matches.insert(am_idx(*it, position)); + for ( const auto& entry : as ) + accepted_matches.insert(am_idx(entry, position)); } bool RE_Match_State::Match(const u_char* bv, int n, bool bol, bool eol, bool clear) { diff --git a/src/RandTest.cc b/src/RandTest.cc index 9d53ddefe3..c97c586d02 100644 --- a/src/RandTest.cc +++ b/src/RandTest.cc @@ -17,6 +17,7 @@ #include "zeek/RandTest.h" #include +#include constexpr double log2of10 = 3.32192809488736234787; @@ -28,18 +29,6 @@ constexpr double RT_INCIRC = 281474943156225.0; namespace zeek::detail { -RandTest::RandTest() { - totalc = 0; - mp = 0; - sccfirst = 1; - inmont = mcount = 0; - cexp = montex = montey = montepi = sccu0 = scclast = scct1 = scct2 = scct3 = 0.0; - - for ( int i = 0; i < 256; i++ ) { - ccount[i] = 0; - } -} - void RandTest::add(const void* buf, int bufl) { const unsigned char* bp = static_cast(buf); int oc; diff --git a/src/RandTest.h b/src/RandTest.h index f422cdbbe3..29a1e89944 100644 --- a/src/RandTest.h +++ b/src/RandTest.h @@ -16,20 +16,30 @@ namespace detail { class RandTest { public: - RandTest(); void add(const void* buf, int bufl); void end(double* r_ent, double* r_chisq, double* r_mean, double* r_montepicalc, double* r_scc); private: friend class zeek::EntropyVal; - int64_t ccount[256]; /* Bins to count occurrences of values */ - int64_t totalc; /* Total bytes counted */ - int mp; - int sccfirst; + int64_t ccount[256] = {0}; /* Bins to count occurrences of values */ + int64_t totalc = 0; /* Total bytes counted */ + int mp = 0; + int sccfirst = 1; unsigned int monte[RT_MONTEN] = {0}; - int64_t inmont, mcount; - double cexp, montex, montey, montepi, sccu0, scclast, scct1, scct2, scct3; + + int64_t inmont = 0; + int64_t mcount = 0; + + double cexp = 0.0; + double montex = 0.0; + double montey = 0.0; + double montepi = 0.0; + double sccu0 = 0.0; + double scclast = 0.0; + double scct1 = 0.0; + double scct2 = 0.0; + double scct3 = 0.0; }; } // namespace detail diff --git a/src/Reassem.cc b/src/Reassem.cc index e4fdf7fd8c..7efa34b42d 100644 --- a/src/Reassem.cc +++ b/src/Reassem.cc @@ -243,12 +243,7 @@ uint64_t DataBlockList::Trim(uint64_t seq, uint64_t max_old, DataBlockList* old_ } Reassembler::Reassembler(uint64_t init_seq, ReassemblerType reassem_type) - : block_list(this), - old_block_list(this), - last_reassem_seq(init_seq), - trim_seq(init_seq), - max_old_blocks(0), - rtype(reassem_type) {} + : block_list(this), old_block_list(this), last_reassem_seq(init_seq), trim_seq(init_seq), rtype(reassem_type) {} void Reassembler::CheckOverlap(const DataBlockList& list, uint64_t seq, uint64_t len, const u_char* data) { if ( list.Empty() ) diff --git a/src/RuleAction.cc b/src/RuleAction.cc index 1aabae37a1..2a11115dc1 100644 --- a/src/RuleAction.cc +++ b/src/RuleAction.cc @@ -92,15 +92,15 @@ void RuleActionEvent::DoAction(const Rule* parent, RuleEndpointState* state, con if ( handler ) { zeek::Args args; args.reserve(msg ? 3 : 2); - args.push_back({AdoptRef{}, rule_matcher->BuildRuleStateValue(parent, state)}); + args.emplace_back(AdoptRef{}, rule_matcher->BuildRuleStateValue(parent, state)); if ( msg ) - args.push_back(msg); + args.emplace_back(msg); if ( data ) - args.push_back(make_intrusive(len, reinterpret_cast(data))); + args.emplace_back(make_intrusive(len, reinterpret_cast(data))); else - args.push_back(zeek::val_mgr->EmptyString()); + args.emplace_back(zeek::val_mgr->EmptyString()); if ( want_end_of_match ) { auto* match = state->FindRulePatternMatch(parent); diff --git a/src/RuleMatcher.cc b/src/RuleMatcher.cc index 4ef2211de4..ed26ee7688 100644 --- a/src/RuleMatcher.cc +++ b/src/RuleMatcher.cc @@ -106,8 +106,8 @@ RuleHdrTest::RuleHdrTest(RuleHdrTest& h) { prefix_vals = h.prefix_vals; - for ( int j = 0; j < Rule::TYPES; ++j ) { - for ( PatternSet* orig_set : h.psets[j] ) { + for ( const auto& pset : h.psets ) { + for ( PatternSet* orig_set : pset ) { PatternSet* copied_set = new PatternSet; copied_set->re = nullptr; copied_set->ids = orig_set->ids; @@ -133,8 +133,8 @@ RuleHdrTest::~RuleHdrTest() { delete val; delete vals; - for ( int i = 0; i < Rule::TYPES; ++i ) { - for ( auto pset : psets[i] ) { + for ( auto& pset_list : psets ) { + for ( auto& pset : pset_list ) { delete pset->re; delete pset; } @@ -515,10 +515,10 @@ static inline bool match_or(const maskedvalue_list& mvals, uint32_t v, FuncT com // Evaluate a prefix list (matches if at least one value matches). template static inline bool match_or(const vector& prefixes, const IPAddr& a, FuncT comp) { - for ( size_t i = 0; i < prefixes.size(); ++i ) { + for ( const auto& pfx : prefixes ) { IPAddr masked(a); - masked.Mask(prefixes[i].LengthIPv6()); - if ( comp(masked, prefixes[i].Prefix()) ) + masked.Mask(pfx.LengthIPv6()); + if ( comp(masked, pfx.Prefix()) ) return true; } return false; @@ -538,10 +538,10 @@ static inline bool match_not_and(const maskedvalue_list& mvals, uint32_t v, Func // Evaluate a prefix list (doesn't match if any value matches). template static inline bool match_not_and(const vector& prefixes, const IPAddr& a, FuncT comp) { - for ( size_t i = 0; i < prefixes.size(); ++i ) { + for ( const auto& pfx : prefixes ) { IPAddr masked(a); - masked.Mask(prefixes[i].LengthIPv6()); - if ( comp(masked, prefixes[i].Prefix()) ) + masked.Mask(pfx.LengthIPv6()); + if ( comp(masked, pfx.Prefix()) ) return false; } return true; @@ -549,17 +549,17 @@ static inline bool match_not_and(const vector& prefixes, const IPAddr& static inline bool compare(const maskedvalue_list& mvals, uint32_t v, RuleHdrTest::Comp comp) { switch ( comp ) { - case RuleHdrTest::EQ: return match_or(mvals, v, std::equal_to()); break; + case RuleHdrTest::EQ: return match_or(mvals, v, std::equal_to<>()); break; - case RuleHdrTest::NE: return match_not_and(mvals, v, std::equal_to()); break; + case RuleHdrTest::NE: return match_not_and(mvals, v, std::equal_to<>()); break; - case RuleHdrTest::LT: return match_or(mvals, v, std::less()); break; + case RuleHdrTest::LT: return match_or(mvals, v, std::less<>()); break; - case RuleHdrTest::GT: return match_or(mvals, v, std::greater()); break; + case RuleHdrTest::GT: return match_or(mvals, v, std::greater<>()); break; - case RuleHdrTest::LE: return match_or(mvals, v, std::less_equal()); break; + case RuleHdrTest::LE: return match_or(mvals, v, std::less_equal<>()); break; - case RuleHdrTest::GE: return match_or(mvals, v, std::greater_equal()); break; + case RuleHdrTest::GE: return match_or(mvals, v, std::greater_equal<>()); break; default: reporter->InternalError("unknown RuleHdrTest comparison type"); break; } @@ -568,17 +568,17 @@ static inline bool compare(const maskedvalue_list& mvals, uint32_t v, RuleHdrTes static inline bool compare(const vector& prefixes, const IPAddr& a, RuleHdrTest::Comp comp) { switch ( comp ) { - case RuleHdrTest::EQ: return match_or(prefixes, a, std::equal_to()); break; + case RuleHdrTest::EQ: return match_or(prefixes, a, std::equal_to<>()); break; - case RuleHdrTest::NE: return match_not_and(prefixes, a, std::equal_to()); break; + case RuleHdrTest::NE: return match_not_and(prefixes, a, std::equal_to<>()); break; - case RuleHdrTest::LT: return match_or(prefixes, a, std::less()); break; + case RuleHdrTest::LT: return match_or(prefixes, a, std::less<>()); break; - case RuleHdrTest::GT: return match_or(prefixes, a, std::greater()); break; + case RuleHdrTest::GT: return match_or(prefixes, a, std::greater<>()); break; - case RuleHdrTest::LE: return match_or(prefixes, a, std::less_equal()); break; + case RuleHdrTest::LE: return match_or(prefixes, a, std::less_equal<>()); break; - case RuleHdrTest::GE: return match_or(prefixes, a, std::greater_equal()); break; + case RuleHdrTest::GE: return match_or(prefixes, a, std::greater_equal<>()); break; default: reporter->InternalError("unknown RuleHdrTest comparison type"); break; } @@ -1083,12 +1083,12 @@ void RuleMatcher::GetStats(Stats* stats, RuleHdrTest* hdr_test) const { DFA_State_Cache::Stats cstats; - for ( int i = 0; i < Rule::TYPES; ++i ) { - for ( const auto& set : hdr_test->psets[i] ) { - assert(set->re); + for ( const auto& pset_list : hdr_test->psets ) { + for ( const auto& pset : pset_list ) { + assert(pset->re); ++stats->matchers; - set->re->DFA()->Cache()->GetStats(&cstats); + pset->re->DFA()->Cache()->GetStats(&cstats); stats->dfa_states += cstats.dfa_states; stats->computed += cstats.computed; @@ -1183,7 +1183,9 @@ static bool val_to_maskedval(Val* v, maskedvalue_list* append_to, vectorAsSubNet().Prefix().GetBytes(&n); v->AsSubNetVal()->Mask().CopyIPv6(m); - for ( unsigned int i = 0; i < 4; ++i ) + // Intentionally leaving this as a normal loop because it's more descriptive. + // NOLINTNEXTLINE(modernize-loop-convert) + for ( unsigned int i = 0; i < 4; i++ ) m[i] = ntohl(m[i]); bool is_v4_mask = m[0] == 0xffffffff && m[1] == m[0] && m[2] == m[0]; diff --git a/src/RunState.cc b/src/RunState.cc index 14af43dba3..e168cdb1fb 100644 --- a/src/RunState.cc +++ b/src/RunState.cc @@ -376,8 +376,8 @@ void get_final_stats() { void delete_run() { util::detail::set_processing_status("TERMINATING", "delete_run"); - for ( int i = 0; i < zeek::detail::NUM_ADDR_ANONYMIZATION_METHODS; ++i ) - delete zeek::detail::ip_anonymizer[i]; + for ( auto& anon : zeek::detail::ip_anonymizer ) + delete anon; } double check_pseudo_time(const Packet* pkt) { diff --git a/src/Scope.cc b/src/Scope.cc index 26e67b0b26..6be15e9cb6 100644 --- a/src/Scope.cc +++ b/src/Scope.cc @@ -182,6 +182,6 @@ ScopePtr pop_scope() { ScopePtr current_scope() { return top_scope; } -ScopePtr global_scope() { return scopes.empty() ? 0 : scopes.front(); } +ScopePtr global_scope() { return scopes.empty() ? nullptr : scopes.front(); } } // namespace zeek::detail diff --git a/src/SmithWaterman.cc b/src/SmithWaterman.cc index 1f6248bfc0..10b0385bae 100644 --- a/src/SmithWaterman.cc +++ b/src/SmithWaterman.cc @@ -425,7 +425,7 @@ Substring::Vec* smith_waterman(const String* s1, const String* s2, SWParams& par if ( current->swn_byte_assigned ) current->swn_score = score_tl; else - current->swn_score = std::max(std::max(score_t, score_l), score_tl); + current->swn_score = std::max({score_t, score_l, score_tl}); // Establish predecessor chain according to neighbor // with best score. diff --git a/src/Stats.cc b/src/Stats.cc index be90c5ae7e..3096249171 100644 --- a/src/Stats.cc +++ b/src/Stats.cc @@ -194,14 +194,13 @@ void ProfileLogger::Log() { file->Write(util::fmt("%0.6f Threads: current=%zu\n", run_state::network_time, thread_mgr->NumThreads())); const threading::Manager::msg_stats_list& thread_stats = thread_mgr->GetMsgThreadStats(); - for ( threading::Manager::msg_stats_list::const_iterator i = thread_stats.begin(); i != thread_stats.end(); ++i ) { - threading::MsgThread::Stats s = i->second; + for ( const auto& [name, s] : thread_stats ) { file->Write(util::fmt("%0.6f %-25s in=%" PRIu64 " out=%" PRIu64 " pending=%" PRIu64 "/%" PRIu64 " (#queue r/w: in=%" PRIu64 "/%" PRIu64 " out=%" PRIu64 "/%" PRIu64 ")" "\n", - run_state::network_time, i->first.c_str(), s.sent_in, s.sent_out, s.pending_in, - s.pending_out, s.queue_in_stats.num_reads, s.queue_in_stats.num_writes, - s.queue_out_stats.num_reads, s.queue_out_stats.num_writes)); + run_state::network_time, name.c_str(), s.sent_in, s.sent_out, s.pending_in, s.pending_out, + s.queue_in_stats.num_reads, s.queue_in_stats.num_writes, s.queue_out_stats.num_reads, + s.queue_out_stats.num_writes)); } auto cs = broker_mgr->GetStatistics(); @@ -288,7 +287,7 @@ void PacketProfiler::ProfilePkt(double t, unsigned int bytes) { struct rusage res; struct timeval ptimestamp; getrusage(RUSAGE_SELF, &res); - gettimeofday(&ptimestamp, 0); + gettimeofday(&ptimestamp, nullptr); util::get_memory_usage(&last_mem, nullptr); last_Utime = res.ru_utime.tv_sec + res.ru_utime.tv_usec / 1e6; @@ -303,7 +302,7 @@ void PacketProfiler::ProfilePkt(double t, unsigned int bytes) { struct rusage res; struct timeval ptimestamp; getrusage(RUSAGE_SELF, &res); - gettimeofday(&ptimestamp, 0); + gettimeofday(&ptimestamp, nullptr); double curr_Utime = res.ru_utime.tv_sec + res.ru_utime.tv_usec / 1e6; double curr_Stime = res.ru_stime.tv_sec + res.ru_stime.tv_usec / 1e6; diff --git a/src/Trigger.cc b/src/Trigger.cc index eacf631bf9..dafc12e405 100644 --- a/src/Trigger.cc +++ b/src/Trigger.cc @@ -162,8 +162,8 @@ void Trigger::Terminate() { Trigger::~Trigger() { DBG_LOG(DBG_NOTIFIERS, "%s: deleting", Name()); - for ( ValCache::iterator i = cache.begin(); i != cache.end(); ++i ) - Unref(i->second); + for ( auto& [_, trigger] : cache ) + Unref(trigger); Unref(frame); UnregisterAll(); @@ -457,9 +457,8 @@ void Manager::Process() { TriggerList tmp; pending = &tmp; - for ( TriggerList::iterator i = orig->begin(); i != orig->end(); ++i ) { - Trigger* t = *i; - (*i)->Eval(); + for ( auto* t : *orig ) { + t->Eval(); Unref(t); } diff --git a/src/Type.cc b/src/Type.cc index c00f0951af..cc0842bba9 100644 --- a/src/Type.cc +++ b/src/Type.cc @@ -756,9 +756,7 @@ void FuncType::DescribeReST(ODesc* d, bool roles_only) const { void FuncType::AddPrototype(Prototype p) { prototypes.emplace_back(std::move(p)); } std::optional FuncType::FindPrototype(const RecordType& args) const { - for ( auto i = 0u; i < prototypes.size(); ++i ) { - const auto& p = prototypes[i]; - + for ( const auto& p : prototypes ) { if ( args.NumFields() != p.args->NumFields() ) continue; @@ -904,7 +902,7 @@ public: auto v = init_expr->Eval(nullptr); if ( ! v ) { reporter->Error("failed &default in record creation"); - return ZVal(); + return {}; } if ( coerce_type ) @@ -913,7 +911,7 @@ public: else if ( init_type->Tag() == TYPE_VECTOR ) concretize_if_unspecified(cast_intrusive(v), init_type->Yield()); - return ZVal(v, init_type); + return {v, init_type}; } bool IsDeferrable() const override { return false; } @@ -932,7 +930,7 @@ class RecordFieldInit final : public FieldInit { public: RecordFieldInit(RecordTypePtr _init_type) : init_type(std::move(_init_type)) {} - ZVal Generate() const override { return ZVal(new RecordVal(init_type)); } + ZVal Generate() const override { return {new RecordVal(init_type)}; } bool IsDeferrable() const override { assert(! run_state::is_parsing); @@ -950,7 +948,7 @@ public: TableFieldInit(TableTypePtr _init_type, detail::AttributesPtr _attrs) : init_type(std::move(_init_type)), attrs(std::move(_attrs)) {} - ZVal Generate() const override { return ZVal(new TableVal(init_type, attrs)); } + ZVal Generate() const override { return {new TableVal(init_type, attrs)}; } private: TableTypePtr init_type; @@ -963,7 +961,7 @@ class VectorFieldInit final : public FieldInit { public: VectorFieldInit(VectorTypePtr _init_type) : init_type(std::move(_init_type)) {} - ZVal Generate() const override { return ZVal(new VectorVal(init_type)); } + ZVal Generate() const override { return {new VectorVal(init_type)}; } private: VectorTypePtr init_type; @@ -1661,8 +1659,8 @@ const char* EnumType::Lookup(zeek_int_t value) const { EnumType::enum_name_list EnumType::Names() const { enum_name_list n; - for ( auto iter = names.begin(); iter != names.end(); ++iter ) - n.emplace_back(iter->first, iter->second); + for ( const auto& [name, value] : names ) + n.emplace_back(name, value); return n; } diff --git a/src/UID.cc b/src/UID.cc index f18ac0208a..d082d01e56 100644 --- a/src/UID.cc +++ b/src/UID.cc @@ -12,8 +12,7 @@ namespace zeek { void UID::Set(zeek_uint_t bits, const uint64_t* v, size_t n) { initialized = true; - for ( size_t i = 0; i < UID_LEN; ++i ) - uid[i] = 0; + memset(uid, 0, sizeof(uid)); if ( bits > UID_LEN * 64 ) bits = UID_LEN * 64; @@ -33,8 +32,8 @@ std::string UID::Base62(std::string prefix) const { reporter->InternalError("use of uninitialized UID"); char tmp[sizeof(uid) * 8 + 1]; // enough for even binary representation - for ( size_t i = 0; i < UID_LEN; ++i ) - prefix.append(util::uitoa_n(uid[i], tmp, sizeof(tmp), 62)); + for ( const auto& digit : uid ) + prefix.append(util::uitoa_n(digit, tmp, sizeof(tmp), 62)); return prefix; } diff --git a/src/Val.cc b/src/Val.cc index 19dd67fcd2..08d6fee0cc 100644 --- a/src/Val.cc +++ b/src/Val.cc @@ -738,8 +738,8 @@ IPAddr SubNetVal::Mask() const { // We need to special-case a mask width of zero, since // the compiler doesn't guarantee that 1 << 32 yields 0. uint32_t m[4]; - for ( unsigned int i = 0; i < 4; ++i ) - m[i] = 0; + for ( uint32_t& digit : m ) + digit = 0; IPAddr rval(IPv6, m, IPAddr::Host); return rval; } @@ -1638,7 +1638,7 @@ bool detail::TablePatternMatcher::MatchAll(const StringValPtr& s) { void detail::TablePatternMatcher::Build() { matcher_yields.clear(); - matcher_yields.push_back(nullptr); + matcher_yields.emplace_back(nullptr); auto& tbl_dict = *tbl->Get(); auto& tbl_hash = *tbl->GetTableHash(); @@ -2141,7 +2141,7 @@ bool TableVal::Contains(const IPAddr& addr) const { return false; } - return (subnets->Lookup(addr, 128, false) != 0); + return (subnets->Lookup(addr, 128, false) != nullptr); } VectorValPtr TableVal::LookupSubnets(const SubNetVal* search) { diff --git a/src/Var.cc b/src/Var.cc index 5df4746aa4..6e9a74a754 100644 --- a/src/Var.cc +++ b/src/Var.cc @@ -438,9 +438,9 @@ static Attr* find_attr(const std::vector* al, AttrTag tag) { if ( ! al ) return nullptr; - for ( size_t i = 0; i < al->size(); ++i ) - if ( (*al)[i]->Tag() == tag ) - return (*al)[i].get(); + for ( const auto& attr : *al ) + if ( attr->Tag() == tag ) + return attr.get(); return nullptr; } diff --git a/src/ZeekString.cc b/src/ZeekString.cc index f720e57977..4d63345e3f 100644 --- a/src/ZeekString.cc +++ b/src/ZeekString.cc @@ -352,8 +352,8 @@ String::Vec* String::VecFromPolicy(VectorVal* vec) { char* String::VecToString(const Vec* vec) { std::string result("["); - for ( String::VecCIt it = vec->begin(); it != vec->end(); ++it ) { - result += (*it)->CheckString(); + for ( const auto* str : *vec ) { + result += str->CheckString(); result += ","; } @@ -442,10 +442,7 @@ String* concatenate(String::CVec& v) { String* concatenate(String::Vec& v) { String::CVec cv; - - for ( String::VecIt it = v.begin(); it != v.end(); ++it ) - cv.push_back(*it); - + std::copy(v.begin(), v.end(), std::back_inserter(cv)); return concatenate(cv); } diff --git a/src/analyzer/Analyzer.cc b/src/analyzer/Analyzer.cc index 406d4440d3..f1ef9ed459 100644 --- a/src/analyzer/Analyzer.cc +++ b/src/analyzer/Analyzer.cc @@ -116,8 +116,8 @@ Analyzer::~Analyzer() { assert(finished); assert(new_children.empty()); - LOOP_OVER_CHILDREN(i) - delete *i; + for ( Analyzer* a : children ) + delete a; SupportAnalyzer* next = nullptr; @@ -139,9 +139,9 @@ void Analyzer::Init() {} void Analyzer::InitChildren() { AppendNewChildren(); - LOOP_OVER_CHILDREN(i) { - (*i)->Init(); - (*i)->InitChildren(); + for ( Analyzer* a : children ) { + a->Init(); + a->InitChildren(); } } @@ -157,9 +157,9 @@ void Analyzer::Done() { AppendNewChildren(); - LOOP_OVER_CHILDREN(i) - if ( ! (*i)->finished ) - (*i)->Done(); + for ( Analyzer* a : children ) + if ( ! a->finished ) + a->Done(); for ( SupportAnalyzer* a = orig_supporters; a; a = a->sibling ) if ( ! a->finished ) @@ -424,25 +424,25 @@ bool Analyzer::IsPreventedChildAnalyzer(const zeek::Tag& tag) const { bool Analyzer::HasChildAnalyzer(const zeek::Tag& tag) const { return GetChildAnalyzer(tag) != nullptr; } Analyzer* Analyzer::GetChildAnalyzer(const zeek::Tag& tag) const { - LOOP_OVER_CHILDREN(i) - if ( (*i)->tag == tag && ! ((*i)->removing || (*i)->finished) ) - return *i; + for ( Analyzer* a : children ) + if ( a->tag == tag && ! (a->removing || a->finished) ) + return a; - LOOP_OVER_GIVEN_CHILDREN(i, new_children) - if ( (*i)->tag == tag && ! ((*i)->removing || (*i)->finished) ) - return *i; + for ( Analyzer* a : new_children ) + if ( a->tag == tag && ! (a->removing || a->finished) ) + return a; return nullptr; } Analyzer* Analyzer::GetChildAnalyzer(const std::string& name) const { - LOOP_OVER_CHILDREN(i) - if ( (*i)->GetAnalyzerName() == name && ! ((*i)->removing || (*i)->finished) ) - return *i; + for ( Analyzer* a : children ) + if ( a->GetAnalyzerName() == name && ! (a->removing || a->finished) ) + return a; - LOOP_OVER_GIVEN_CHILDREN(i, new_children) - if ( (*i)->GetAnalyzerName() == name && ! ((*i)->removing || (*i)->finished) ) - return *i; + for ( Analyzer* a : new_children ) + if ( a->GetAnalyzerName() == name && ! (a->removing || a->finished) ) + return a; return nullptr; } @@ -451,15 +451,13 @@ Analyzer* Analyzer::FindChild(ID arg_id) { if ( id == arg_id && ! (removing || finished) ) return this; - LOOP_OVER_CHILDREN(i) { - Analyzer* child = (*i)->FindChild(arg_id); - if ( child ) + for ( Analyzer* a : children ) { + if ( Analyzer* child = a->FindChild(arg_id) ) return child; } - LOOP_OVER_GIVEN_CHILDREN(i, new_children) { - Analyzer* child = (*i)->FindChild(arg_id); - if ( child ) + for ( Analyzer* a : new_children ) { + if ( Analyzer* child = a->FindChild(arg_id) ) return child; } @@ -470,15 +468,13 @@ Analyzer* Analyzer::FindChild(zeek::Tag arg_tag) { if ( tag == arg_tag && ! (removing || finished) ) return this; - LOOP_OVER_CHILDREN(i) { - Analyzer* child = (*i)->FindChild(arg_tag); - if ( child ) + for ( Analyzer* a : children ) { + if ( Analyzer* child = a->FindChild(arg_tag) ) return child; } - LOOP_OVER_GIVEN_CHILDREN(i, new_children) { - Analyzer* child = (*i)->FindChild(arg_tag); - if ( child ) + for ( Analyzer* a : new_children ) { + if ( Analyzer* child = a->FindChild(arg_tag) ) return child; } @@ -607,11 +603,11 @@ void Analyzer::EndOfData(bool is_orig) { void Analyzer::FlipRoles() { DBG_LOG(DBG_ANALYZER, "%s FlipRoles()", fmt_analyzer(this).c_str()); - LOOP_OVER_CHILDREN(i) - (*i)->FlipRoles(); + for ( Analyzer* a : children ) + a->FlipRoles(); - LOOP_OVER_GIVEN_CHILDREN(i, new_children) - (*i)->FlipRoles(); + for ( Analyzer* a : new_children ) + a->FlipRoles(); for ( SupportAnalyzer* a = orig_supporters; a; a = a->sibling ) a->FlipRoles(); @@ -707,14 +703,14 @@ void Analyzer::CancelTimers() { } void Analyzer::AppendNewChildren() { - LOOP_OVER_GIVEN_CHILDREN(i, new_children) - children.push_back(*i); + for ( Analyzer* a : new_children ) + children.push_back(a); new_children.clear(); } void Analyzer::UpdateConnVal(RecordVal* conn_val) { - LOOP_OVER_CHILDREN(i) - (*i)->UpdateConnVal(conn_val); + for ( Analyzer* a : children ) + a->UpdateConnVal(conn_val); } const RecordValPtr& Analyzer::ConnVal() { return conn->GetVal(); } diff --git a/src/analyzer/Manager.cc b/src/analyzer/Manager.cc index 4cd42420a7..980e15d4b3 100644 --- a/src/analyzer/Manager.cc +++ b/src/analyzer/Manager.cc @@ -388,8 +388,8 @@ bool Manager::ApplyScheduledAnalyzers(Connection* conn, bool init, packet_analys tag_set expected = GetScheduled(conn); - for ( tag_set::iterator it = expected.begin(); it != expected.end(); ++it ) { - Analyzer* analyzer = analyzer_mgr->InstantiateAnalyzer(*it, conn); + for ( const auto& tag : expected ) { + Analyzer* analyzer = analyzer_mgr->InstantiateAnalyzer(tag, conn); if ( ! analyzer ) continue; @@ -397,9 +397,9 @@ bool Manager::ApplyScheduledAnalyzers(Connection* conn, bool init, packet_analys parent->AddChildAnalyzer(analyzer, init); if ( scheduled_analyzer_applied ) - conn->EnqueueEvent(scheduled_analyzer_applied, nullptr, conn->GetVal(), it->AsVal()); + conn->EnqueueEvent(scheduled_analyzer_applied, nullptr, conn->GetVal(), tag.AsVal()); - DBG_ANALYZER_ARGS(conn, "activated %s analyzer as scheduled", analyzer_mgr->GetComponentName(*it).c_str()); + DBG_ANALYZER_ARGS(conn, "activated %s analyzer as scheduled", analyzer_mgr->GetComponentName(tag).c_str()); } return expected.size(); diff --git a/src/analyzer/protocol/bittorrent/BitTorrentTracker.cc b/src/analyzer/protocol/bittorrent/BitTorrentTracker.cc index dc4b8acce4..4e9398519a 100644 --- a/src/analyzer/protocol/bittorrent/BitTorrentTracker.cc +++ b/src/analyzer/protocol/bittorrent/BitTorrentTracker.cc @@ -195,7 +195,7 @@ void BitTorrentTracker_Analyzer::EndpointEOF(bool is_orig) { analyzer::tcp::TCP_ApplicationAnalyzer::EndpointEOF(is_orig); } -void BitTorrentTracker_Analyzer::InitBencParser(void) { +void BitTorrentTracker_Analyzer::InitBencParser() { benc_stack.clear(); benc_count.clear(); @@ -304,7 +304,7 @@ bool BitTorrentTracker_Analyzer::ParseRequest(char* line) { void BitTorrentTracker_Analyzer::RequestGet(char* uri) { req_val_uri = new StringVal(uri); } -void BitTorrentTracker_Analyzer::EmitRequest(void) { +void BitTorrentTracker_Analyzer::EmitRequest() { AnalyzerConfirmation(); if ( bt_tracker_request ) @@ -443,7 +443,7 @@ void BitTorrentTracker_Analyzer::ResponseBenc(int name_len, char* name, detail:: res_val_benc->Assign(std::move(name_), std::move(benc_value)); } -void BitTorrentTracker_Analyzer::ResponseBody(void) { +void BitTorrentTracker_Analyzer::ResponseBody() { switch ( ResponseParseBenc() ) { case 0: EmitResponse(); @@ -466,7 +466,7 @@ void BitTorrentTracker_Analyzer::ResponseBody(void) { } \ } -int BitTorrentTracker_Analyzer::ResponseParseBenc(void) { +int BitTorrentTracker_Analyzer::ResponseParseBenc() { auto INC_COUNT = [this]() { unsigned int count = benc_count.back(); benc_count.pop_back(); @@ -696,7 +696,7 @@ int BitTorrentTracker_Analyzer::ResponseParseBenc(void) { return -2; // need more data } -void BitTorrentTracker_Analyzer::EmitResponse(void) { +void BitTorrentTracker_Analyzer::EmitResponse() { AnalyzerConfirmation(); if ( bt_tracker_response ) diff --git a/src/analyzer/protocol/dce-rpc/dce_rpc-auth.pac b/src/analyzer/protocol/dce-rpc/dce_rpc-auth.pac index 30ca0eeaec..b9f80d02d9 100644 --- a/src/analyzer/protocol/dce-rpc/dce_rpc-auth.pac +++ b/src/analyzer/protocol/dce-rpc/dce_rpc-auth.pac @@ -10,9 +10,9 @@ refine connection DCE_RPC_Conn += { %} %init{ - ntlm = 0; - gssapi = 0; - krb = 0; + ntlm = nullptr; + gssapi = nullptr; + krb = nullptr; %} %cleanup{ diff --git a/src/analyzer/protocol/dce-rpc/dce_rpc-protocol.pac b/src/analyzer/protocol/dce-rpc/dce_rpc-protocol.pac index c044110584..329e2bdc4f 100644 --- a/src/analyzer/protocol/dce-rpc/dce_rpc-protocol.pac +++ b/src/analyzer/protocol/dce-rpc/dce_rpc-protocol.pac @@ -204,7 +204,7 @@ flow DCE_RPC_Flow(is_orig: bool) { { // first frag, but not last so we start a flowbuffer auto it = fb.emplace(${header.call_id}, - std::unique_ptr(new FlowBuffer())); + std::make_unique()); auto& flowbuf = it.first->second; flowbuf->NewFrame(0, true); flowbuf->BufferData(frag.begin(), frag.end()); diff --git a/src/analyzer/protocol/dhcp/dhcp-options.pac b/src/analyzer/protocol/dhcp/dhcp-options.pac index 810bb0a6e8..2e14c953a5 100644 --- a/src/analyzer/protocol/dhcp/dhcp-options.pac +++ b/src/analyzer/protocol/dhcp/dhcp-options.pac @@ -756,12 +756,11 @@ refine flow DHCP_Flow += { uint16 i = 0; - for ( auto ptrsubopt = ${v.relay_agent_inf}->begin(); - ptrsubopt != ${v.relay_agent_inf}->end(); ++ptrsubopt ) + for ( const auto& ptrsubopt : *${v.relay_agent_inf} ) { auto r = zeek::make_intrusive(zeek::BifType::Record::DHCP::SubOpt); - r->Assign(0, (*ptrsubopt)->code()); - r->Assign(1, to_stringval((*ptrsubopt)->value())); + r->Assign(0, ptrsubopt->code()); + r->Assign(1, to_stringval(ptrsubopt->value())); relay_agent_sub_opt->Assign(i, std::move(r)); ++i; diff --git a/src/analyzer/protocol/dns/DNS.cc b/src/analyzer/protocol/dns/DNS.cc index dc0132bbfd..98204320f8 100644 --- a/src/analyzer/protocol/dns/DNS.cc +++ b/src/analyzer/protocol/dns/DNS.cc @@ -699,8 +699,8 @@ bool DNS_Interpreter::ParseRR_EDNS(detail::DNS_MsgInfo* msg, const u_char*& data bits_left -= 8; } - for ( uint8_t i = 0; i < 4; i++ ) { - addr[i] = htonl(addr[i]); + for ( uint32_t& a : addr ) { + a = htonl(a); } opt.ecs_addr = make_intrusive(addr); } @@ -1372,7 +1372,9 @@ bool DNS_Interpreter::ParseRR_A(detail::DNS_MsgInfo* msg, const u_char*& data, i bool DNS_Interpreter::ParseRR_AAAA(detail::DNS_MsgInfo* msg, const u_char*& data, int& len, int rdlength) { uint32_t addr[4]; - for ( int i = 0; i < 4; ++i ) { + // Intentionally leaving this as a normal loop because it's more descriptive. + // NOLINTNEXTLINE(modernize-loop-convert) + for ( size_t i = 0; i < 4; i++ ) { addr[i] = htonl(ExtractLong(data, len)); if ( len < 0 ) { diff --git a/src/analyzer/protocol/ftp/functions.bif b/src/analyzer/protocol/ftp/functions.bif index 235cb630ab..9c7e067862 100644 --- a/src/analyzer/protocol/ftp/functions.bif +++ b/src/analyzer/protocol/ftp/functions.bif @@ -20,8 +20,8 @@ static zeek::RecordValPtr parse_port(const std::string& line) { good = true; - for ( int i = 0; i < 6; ++i ) - if ( bytes[i] < 0 || bytes[i] > 255 ) + for ( int b : bytes ) + if ( b < 0 || b > 255 ) { good = false; break; @@ -75,19 +75,19 @@ static zeek::RecordValPtr parse_eftp(const char* line) if ( *line && *line != delimiter ) { const char* nptr = strchr(line, delimiter); - if ( nptr == NULL ) + if ( nptr == nullptr ) nptr = line + strlen(line); std::string s(line, nptr-line); // extract IP address struct in6_addr result; - good = zeek::IPAddr::ConvertString(s.c_str(), &result) ? 1 : 0; + good = zeek::IPAddr::ConvertString(s.c_str(), &result); if ( good ) addr = zeek::IPAddr(result); } line = strchr(line, delimiter); - if ( line != NULL ) + if ( line != nullptr ) { ++line; // now the port port = strtol(line, &next_delim, 10); diff --git a/src/analyzer/protocol/gssapi/gssapi-analyzer.pac b/src/analyzer/protocol/gssapi/gssapi-analyzer.pac index 42a098b383..5e07776a30 100644 --- a/src/analyzer/protocol/gssapi/gssapi-analyzer.pac +++ b/src/analyzer/protocol/gssapi/gssapi-analyzer.pac @@ -6,8 +6,8 @@ refine connection GSSAPI_Conn += { %} %init{ - ntlm=0; - krb5=0; + ntlm = nullptr; + krb5 = nullptr; %} %cleanup{ @@ -15,14 +15,14 @@ refine connection GSSAPI_Conn += { { ntlm->Done(); delete ntlm; - ntlm=0; + ntlm = nullptr; } if ( krb5 ) { krb5->Done(); delete krb5; - krb5=0; + krb5 = nullptr; } %} @@ -50,7 +50,7 @@ refine connection GSSAPI_Conn += { { krb5->DeliverPacket(${val.krb.blob}.length(), ${val.krb.blob}.begin(), - is_orig, 0, 0, 0); + is_orig, 0, nullptr, 0); } } diff --git a/src/analyzer/protocol/http/HTTP.cc b/src/analyzer/protocol/http/HTTP.cc index 724d024a7e..ca430a73e1 100644 --- a/src/analyzer/protocol/http/HTTP.cc +++ b/src/analyzer/protocol/http/HTTP.cc @@ -1631,11 +1631,11 @@ void HTTP_Analyzer::SkipEntityData(bool is_orig) { } bool is_reserved_URI_char(unsigned char ch) { // see RFC 3986 (definition of URI) - return strchr(":/?#[]@!$&'()*+,;=", ch) != 0; + return strchr(":/?#[]@!$&'()*+,;=", ch) != nullptr; } bool is_unreserved_URI_char(unsigned char ch) { // see RFC 3986 (definition of URI) - return isalnum(ch) != 0 || strchr("-_.!~*\'()", ch) != 0; + return isalnum(ch) != 0 || strchr("-_.!~*\'()", ch) != nullptr; } void escape_URI_char(unsigned char ch, unsigned char*& p) { diff --git a/src/analyzer/protocol/http/functions.bif b/src/analyzer/protocol/http/functions.bif index f7c71acab1..f06495257e 100644 --- a/src/analyzer/protocol/http/functions.bif +++ b/src/analyzer/protocol/http/functions.bif @@ -52,5 +52,5 @@ function unescape_URI%(URI: string%): string const u_char* line = URI->Bytes(); const u_char* const line_end = line + URI->Len(); - return zeek::make_intrusive(zeek::analyzer::http::unescape_URI(line, line_end, 0)); + return zeek::make_intrusive(zeek::analyzer::http::unescape_URI(line, line_end, nullptr)); %} diff --git a/src/analyzer/protocol/irc/IRC.cc b/src/analyzer/protocol/irc/IRC.cc index 61c33c6683..e5aaca7ac5 100644 --- a/src/analyzer/protocol/irc/IRC.cc +++ b/src/analyzer/protocol/irc/IRC.cc @@ -125,8 +125,7 @@ void IRC_Analyzer::DeliverStream(int length, const u_char* line, bool orig) { pos = myline.length(); command = myline.substr(0, pos); - for ( size_t i = 0; i < command.size(); ++i ) - command[i] = toupper(command[i]); + command = util::to_upper(command); // Adjust for the no-parameter case if ( pos == myline.length() ) @@ -743,9 +742,8 @@ void IRC_Analyzer::DeliverStream(int length, const u_char* line, bool orig) { string empty_string = ""; - for ( unsigned int i = 0; i < users.size(); ++i ) { + for ( auto nick : users ) { auto info = make_intrusive(irc_join_info); - string nick = users[i]; string mode = "none"; if ( nick[0] == '@' ) { diff --git a/src/analyzer/protocol/krb/krb-analyzer.pac b/src/analyzer/protocol/krb/krb-analyzer.pac index 3df0367a9b..98f14d26af 100644 --- a/src/analyzer/protocol/krb/krb-analyzer.pac +++ b/src/analyzer/protocol/krb/krb-analyzer.pac @@ -37,9 +37,8 @@ zeek::RecordValPtr proc_krb_kdc_req_arguments(KRB_KDC_REQ* msg, const ZeekAnalyz if ( msg->padata()->has_padata() ) rv->Assign(2, proc_padata(msg->padata()->padata()->padata(), zeek_analyzer, false)); - for ( uint i = 0; i < msg->body_args()->size(); ++i ) + for ( KRB_REQ_Arg* element : *(msg->body_args()) ) { - KRB_REQ_Arg* element = (*msg->body_args())[i]; switch ( element->seq_meta()->index() ) { case 0: @@ -127,35 +126,35 @@ bool proc_error_arguments(zeek::RecordVal* rv, const std::vector if ( stime_i ) rv->Assign(3, GetTimeFromAsn1((*args)[stime_i]->args()->stime(), stime_usecs)); - for ( uint i = 0; i < args->size(); ++i ) + for ( KRB_ERROR_Arg* arg : *args ) { - switch ( (*args)[i]->seq_meta()->index() ) + switch ( arg->seq_meta()->index() ) { case 0: - rv->Assign(0, asn1_integer_to_val((*args)[i]->args()->pvno(), zeek::TYPE_COUNT)); + rv->Assign(0, asn1_integer_to_val(arg->args()->pvno(), zeek::TYPE_COUNT)); break; case 1: - rv->Assign(1, asn1_integer_to_val((*args)[i]->args()->msg_type(), zeek::TYPE_COUNT)); + rv->Assign(1, asn1_integer_to_val(arg->args()->msg_type(), zeek::TYPE_COUNT)); break; // ctime/stime handled above case 7: - rv->Assign(5, to_stringval((*args)[i]->args()->crealm()->encoding()->content())); + rv->Assign(5, to_stringval(arg->args()->crealm()->encoding()->content())); break; case 8: - rv->Assign(6, GetStringFromPrincipalName((*args)[i]->args()->cname())); + rv->Assign(6, GetStringFromPrincipalName(arg->args()->cname())); break; case 9: - rv->Assign(7, to_stringval((*args)[i]->args()->realm()->encoding()->content())); + rv->Assign(7, to_stringval(arg->args()->realm()->encoding()->content())); break; case 10: - rv->Assign(8, GetStringFromPrincipalName((*args)[i]->args()->sname())); + rv->Assign(8, GetStringFromPrincipalName(arg->args()->sname())); break; case 11: - rv->Assign(9, to_stringval((*args)[i]->args()->e_text()->encoding()->content())); + rv->Assign(9, to_stringval(arg->args()->e_text()->encoding()->content())); break; case 12: if ( error_code == KDC_ERR_PREAUTH_REQUIRED ) - rv->Assign(10, proc_padata((*args)[i]->args()->e_data()->padata(), NULL, true)); + rv->Assign(10, proc_padata(arg->args()->e_data()->padata(), nullptr, true)); break; default: break; @@ -307,27 +306,15 @@ refine connection KRB_Conn += { { switch ( ${msg.safe_body.args[i].seq_meta.index} ) { + case 0: + rv->Assign(3, to_stringval(${msg.safe_body.args[i].args.user_data.encoding.content})); + break; case 1: timestamp_i = i; break; case 2: timestamp_usecs = binary_to_int64(${msg.safe_body.args[i].args.usec.encoding.content}); break; - default: - break; - } - } - - if ( timestamp_i ) - rv->Assign(4, GetTimeFromAsn1(${msg.safe_body.args[timestamp_i].args.timestamp}, timestamp_usecs)); - - for ( uint i = 0; i < ${msg.safe_body.args}->size(); ++i ) - { - switch ( ${msg.safe_body.args[i].seq_meta.index} ) - { - case 0: - rv->Assign(3, to_stringval(${msg.safe_body.args[i].args.user_data.encoding.content})); - break; case 3: rv->Assign(5, asn1_integer_to_val(${msg.safe_body.args[i].args.seq_number}, zeek::TYPE_COUNT)); break; @@ -341,6 +328,10 @@ refine connection KRB_Conn += { break; } } + + if ( timestamp_i ) + rv->Assign(4, GetTimeFromAsn1(${msg.safe_body.args[timestamp_i].args.timestamp}, timestamp_usecs)); + zeek::BifEvent::enqueue_krb_safe(zeek_analyzer(), zeek_analyzer()->Conn(), ${msg.is_orig}, std::move(rv)); } return true; diff --git a/src/analyzer/protocol/krb/krb-padata.pac b/src/analyzer/protocol/krb/krb-padata.pac index 9266f9ee51..e2ab24d959 100644 --- a/src/analyzer/protocol/krb/krb-padata.pac +++ b/src/analyzer/protocol/krb/krb-padata.pac @@ -18,9 +18,8 @@ zeek::VectorValPtr proc_padata(const KRB_PA_Data_Sequence* data, const ZeekAnaly if ( ! data->data()->has_padata() ) return vv; - for ( uint i = 0; i < data->data()->padata_elems()->size(); ++i) + for ( KRB_PA_Data* element : *(data->data()->padata_elems()) ) { - KRB_PA_Data* element = (*data->data()->padata_elems())[i]; uint64_t data_type = element->data_type(); if ( is_error && ( data_type == PA_PW_AS_REQ || data_type == PA_PW_AS_REP ) ) diff --git a/src/analyzer/protocol/krb/krb-types.pac b/src/analyzer/protocol/krb/krb-types.pac index 64fabec380..71464a7c8d 100644 --- a/src/analyzer/protocol/krb/krb-types.pac +++ b/src/analyzer/protocol/krb/krb-types.pac @@ -30,8 +30,8 @@ zeek::ValPtr GetStringFromPrincipalName(const KRB_Principal_Name* pname) zeek::VectorValPtr proc_cipher_list(const Array* list) { auto ciphers = zeek::make_intrusive(zeek::id::index_vec); - for ( uint i = 0; i < list->data()->size(); ++i ) - ciphers->Assign(ciphers->Size(), asn1_integer_to_val((*list->data())[i], zeek::TYPE_COUNT)); + for ( const auto& data : *(list->data()) ) + ciphers->Assign(ciphers->Size(), asn1_integer_to_val(data, zeek::TYPE_COUNT)); return ciphers; } @@ -39,10 +39,8 @@ zeek::VectorValPtr proc_host_address_list(const ZeekAnalyzer a, const KRB_Host_A { auto addrs = zeek::make_intrusive(zeek::id::find_type("KRB::Host_Address_Vector")); - for ( uint i = 0; i < list->addresses()->size(); ++i ) - { - addrs->Assign(addrs->Size(), proc_host_address(a, (*list->addresses())[i])); - } + for ( const auto& addr : *(list->addresses()) ) + addrs->Assign(addrs->Size(), proc_host_address(a, addr)); return addrs; } @@ -98,11 +96,8 @@ zeek::VectorValPtr proc_tickets(const KRB_Ticket_Sequence* list) { auto tickets = zeek::make_intrusive(zeek::id::find_type("KRB::Ticket_Vector")); - for ( uint i = 0; i < list->tickets()->size(); ++i ) - { - KRB_Ticket* element = (*list->tickets())[i]; + for ( KRB_Ticket* element : *(list->tickets()) ) tickets->Assign(tickets->Size(), proc_ticket(element)); - } return tickets; } diff --git a/src/analyzer/protocol/login/Login.cc b/src/analyzer/protocol/login/Login.cc index ee06843d5d..c3b9f74c9d 100644 --- a/src/analyzer/protocol/login/Login.cc +++ b/src/analyzer/protocol/login/Login.cc @@ -180,7 +180,7 @@ void Login_Analyzer::AuthenticationDialog(bool orig, char* line) { const char* prompt = IsLoginPrompt(line); bool is_timeout = IsTimeout(line); if ( prompt && ! IsSuccessMsg(line) && ! is_timeout ) { - is_VMS = strstr(line, "Username:") != 0; + is_VMS = strstr(line, "Username:") != nullptr; // If we see multiple login prompts, presume that // each is consuming one line of typeahead. diff --git a/src/analyzer/protocol/modbus/modbus-analyzer.pac b/src/analyzer/protocol/modbus/modbus-analyzer.pac index 03a124045f..95cf8c5796 100644 --- a/src/analyzer/protocol/modbus/modbus-analyzer.pac +++ b/src/analyzer/protocol/modbus/modbus-analyzer.pac @@ -524,14 +524,14 @@ refine flow ModbusTCP_Flow += { { auto vect = zeek::make_intrusive(zeek::BifType::Vector::ModbusFileRecordRequests); - for ( unsigned int i = 0; i < (${message.references}->size()); ++i ) + for ( const auto& ref : *(${message.references}) ) { auto r = zeek::make_intrusive(zeek::BifType::Record::ModbusFileRecordRequest); - r->Assign(0, zeek::val_mgr->Count(${message.references[i].ref_type})); - r->Assign(1, zeek::val_mgr->Count(${message.references[i].file_num})); - r->Assign(2, zeek::val_mgr->Count(${message.references[i].record_num})); - r->Assign(3, zeek::val_mgr->Count(${message.references[i].record_len})); + r->Assign(0, zeek::val_mgr->Count(${ref.ref_type})); + r->Assign(1, zeek::val_mgr->Count(${ref.file_num})); + r->Assign(2, zeek::val_mgr->Count(${ref.record_num})); + r->Assign(3, zeek::val_mgr->Count(${ref.record_len})); vect->Append(r); } @@ -551,13 +551,13 @@ refine flow ModbusTCP_Flow += { { auto vect = zeek::make_intrusive(zeek::BifType::Vector::ModbusFileRecordResponses); - for ( unsigned int i = 0; i < (${message.references}->size()); ++i ) + for ( const auto& ref : *(${message.references}) ) { auto r = zeek::make_intrusive(zeek::BifType::Record::ModbusFileRecordResponse); - r->Assign(0, zeek::val_mgr->Count(${message.references[i].file_len})); - r->Assign(1, zeek::val_mgr->Count(${message.references[i].ref_type})); - r->Assign(2, to_stringval(${message.references[i].record_data})); + r->Assign(0, zeek::val_mgr->Count(${ref.file_len})); + r->Assign(1, zeek::val_mgr->Count(${ref.ref_type})); + r->Assign(2, to_stringval(${ref.record_data})); vect->Append(r); } @@ -577,14 +577,14 @@ refine flow ModbusTCP_Flow += { { auto vect = zeek::make_intrusive(zeek::BifType::Vector::ModbusFileReferences); - for ( unsigned int i = 0; i < (${message.references}->size()); ++i ) + for ( const auto& ref : *(${message.references}) ) { auto r = zeek::make_intrusive(zeek::BifType::Record::ModbusFileReference); - r->Assign(0, zeek::val_mgr->Count(${message.references[i].ref_type})); - r->Assign(1, zeek::val_mgr->Count(${message.references[i].file_num})); - r->Assign(2, zeek::val_mgr->Count(${message.references[i].record_num})); - r->Assign(3, zeek::val_mgr->Count(${message.references[i].record_length})); - r->Assign(4, to_stringval(${message.references[i].record_data})); + r->Assign(0, zeek::val_mgr->Count(${ref.ref_type})); + r->Assign(1, zeek::val_mgr->Count(${ref.file_num})); + r->Assign(2, zeek::val_mgr->Count(${ref.record_num})); + r->Assign(3, zeek::val_mgr->Count(${ref.record_length})); + r->Assign(4, to_stringval(${ref.record_data})); vect->Append(r); } @@ -604,14 +604,14 @@ refine flow ModbusTCP_Flow += { { auto vect = zeek::make_intrusive(zeek::BifType::Vector::ModbusFileReferences); - for ( unsigned int i = 0; i < (${message.references}->size()); ++i ) + for ( const auto& ref : *(${message.references}) ) { auto r = zeek::make_intrusive(zeek::BifType::Record::ModbusFileReference); - r->Assign(0, zeek::val_mgr->Count(${message.references[i].ref_type})); - r->Assign(1, zeek::val_mgr->Count(${message.references[i].file_num})); - r->Assign(2, zeek::val_mgr->Count(${message.references[i].record_num})); - r->Assign(3, zeek::val_mgr->Count(${message.references[i].record_length})); - r->Assign(4, to_stringval(${message.references[i].record_data})); + r->Assign(0, zeek::val_mgr->Count(${ref.ref_type})); + r->Assign(1, zeek::val_mgr->Count(${ref.file_num})); + r->Assign(2, zeek::val_mgr->Count(${ref.record_num})); + r->Assign(3, zeek::val_mgr->Count(${ref.record_length})); + r->Assign(4, to_stringval(${ref.record_data})); vect->Append(r); } diff --git a/src/analyzer/protocol/pop3/POP3.cc b/src/analyzer/protocol/pop3/POP3.cc index e1a3e240aa..c4179b354e 100644 --- a/src/analyzer/protocol/pop3/POP3.cc +++ b/src/analyzer/protocol/pop3/POP3.cc @@ -784,8 +784,7 @@ int POP3_Analyzer::ParseCmd(std::string cmd) { if ( c == '+' || c == '-' ) cmd = cmd.substr(1); - for ( size_t i = 0; i < cmd.size(); ++i ) - cmd[i] = toupper(cmd[i]); + cmd = util::to_upper(cmd); if ( ! cmd.compare(pop3_cmd_word[code]) ) return code; diff --git a/src/analyzer/protocol/radius/radius-analyzer.pac b/src/analyzer/protocol/radius/radius-analyzer.pac index a998aafc71..7abf8f243e 100644 --- a/src/analyzer/protocol/radius/radius-analyzer.pac +++ b/src/analyzer/protocol/radius/radius-analyzer.pac @@ -12,17 +12,17 @@ refine flow RADIUS_Flow += { result->Assign(1, ${msg.trans_id}); result->Assign(2, to_stringval(${msg.authenticator})); - if ( ${msg.attributes}->size() ) + if ( ! ${msg.attributes}->empty() ) { auto attributes = zeek::make_intrusive(zeek::BifType::Table::RADIUS::Attributes); - for ( uint i = 0; i < ${msg.attributes}->size(); ++i ) + for ( const auto& attr : *(${msg.attributes}) ) { - auto index = zeek::val_mgr->Count(${msg.attributes[i].code}); + auto index = zeek::val_mgr->Count(${attr.code}); // Do we already have a vector of attributes for this type? auto current = attributes->FindOrDefault(index); - zeek::ValPtr val = to_stringval(${msg.attributes[i].value}); + zeek::ValPtr val = to_stringval(${attr.value}); if ( current ) { diff --git a/src/analyzer/protocol/rdp/rdp-analyzer.pac b/src/analyzer/protocol/rdp/rdp-analyzer.pac index 184fe668c0..56bed9dbe3 100644 --- a/src/analyzer/protocol/rdp/rdp-analyzer.pac +++ b/src/analyzer/protocol/rdp/rdp-analyzer.pac @@ -132,28 +132,28 @@ refine flow RDP_Flow += { if ( ! rdp_client_network_data ) return false; - if ( ${cnetwork.channel_def_array}->size() ) + if ( ! ${cnetwork.channel_def_array}->empty() ) { auto channels = zeek::make_intrusive(zeek::BifType::Vector::RDP::ClientChannelList); - for ( uint i = 0; i < ${cnetwork.channel_def_array}->size(); ++i ) + for ( const auto& cdef : *${cnetwork.channel_def_array} ) { auto channel_def = zeek::make_intrusive(zeek::BifType::Record::RDP::ClientChannelDef); - channel_def->Assign(0, to_stringval(${cnetwork.channel_def_array[i].name})); - channel_def->Assign(1, ${cnetwork.channel_def_array[i].options}); + channel_def->Assign(0, to_stringval(${cdef.name})); + channel_def->Assign(1, ${cdef.options}); - channel_def->Assign(2, ${cnetwork.channel_def_array[i].CHANNEL_OPTION_INITIALIZED}); - channel_def->Assign(3, ${cnetwork.channel_def_array[i].CHANNEL_OPTION_ENCRYPT_RDP}); - channel_def->Assign(4, ${cnetwork.channel_def_array[i].CHANNEL_OPTION_ENCRYPT_SC}); - channel_def->Assign(5, ${cnetwork.channel_def_array[i].CHANNEL_OPTION_ENCRYPT_CS}); - channel_def->Assign(6, ${cnetwork.channel_def_array[i].CHANNEL_OPTION_PRI_HIGH}); - channel_def->Assign(7, ${cnetwork.channel_def_array[i].CHANNEL_OPTION_PRI_MED}); - channel_def->Assign(8, ${cnetwork.channel_def_array[i].CHANNEL_OPTION_PRI_LOW}); - channel_def->Assign(9, ${cnetwork.channel_def_array[i].CHANNEL_OPTION_COMPRESS_RDP}); - channel_def->Assign(10, ${cnetwork.channel_def_array[i].CHANNEL_OPTION_COMPRESS}); - channel_def->Assign(11, ${cnetwork.channel_def_array[i].CHANNEL_OPTION_SHOW_PROTOCOL}); - channel_def->Assign(12, ${cnetwork.channel_def_array[i].REMOTE_CONTROL_PERSISTENT}); + channel_def->Assign(2, ${cdef.CHANNEL_OPTION_INITIALIZED}); + channel_def->Assign(3, ${cdef.CHANNEL_OPTION_ENCRYPT_RDP}); + channel_def->Assign(4, ${cdef.CHANNEL_OPTION_ENCRYPT_SC}); + channel_def->Assign(5, ${cdef.CHANNEL_OPTION_ENCRYPT_CS}); + channel_def->Assign(6, ${cdef.CHANNEL_OPTION_PRI_HIGH}); + channel_def->Assign(7, ${cdef.CHANNEL_OPTION_PRI_MED}); + channel_def->Assign(8, ${cdef.CHANNEL_OPTION_PRI_LOW}); + channel_def->Assign(9, ${cdef.CHANNEL_OPTION_COMPRESS_RDP}); + channel_def->Assign(10, ${cdef.CHANNEL_OPTION_COMPRESS}); + channel_def->Assign(11, ${cdef.CHANNEL_OPTION_SHOW_PROTOCOL}); + channel_def->Assign(12, ${cdef.REMOTE_CONTROL_PERSISTENT}); channels->Assign(channels->Size(), std::move(channel_def)); } diff --git a/src/analyzer/protocol/smb/smb-common.pac b/src/analyzer/protocol/smb/smb-common.pac index 05e9545642..ca33570c80 100644 --- a/src/analyzer/protocol/smb/smb-common.pac +++ b/src/analyzer/protocol/smb/smb-common.pac @@ -239,35 +239,35 @@ enum SMB_Status { function determine_transaction_type(header: SMB_Header, name: SMB_string): TransactionType %{ - if ( name == NULL ) + if ( name == nullptr ) { return SMB_UNKNOWN; } - if ( (${header.unicode} && ${name.u.s}->size() > 10 && ${name.u.s[0]} == '\\' && - ${name.u.s[2]} == 'P' && - ${name.u.s[4]} == 'I' && - ${name.u.s[6]} == 'P' && - ${name.u.s[8]} == 'E' && + if ( (${header.unicode} && ${name.u.s}->size() > 10 && ${name.u.s[0]} == '\\' && + ${name.u.s[2]} == 'P' && + ${name.u.s[4]} == 'I' && + ${name.u.s[6]} == 'P' && + ${name.u.s[8]} == 'E' && ${name.u.s[10]} == '\\') || - (!${header.unicode} && ${name.a}->size() > 5 && ${name.a}->val()->at(0) == '\\' && - ${name.a}->val()->at(1) == 'P' && + (!${header.unicode} && ${name.a}->size() > 5 && ${name.a}->val()->at(0) == '\\' && + ${name.a}->val()->at(1) == 'P' && ${name.a}->val()->at(2) == 'I' && - ${name.a}->val()->at(3) == 'P' && - ${name.a}->val()->at(4) == 'E' && + ${name.a}->val()->at(3) == 'P' && + ${name.a}->val()->at(4) == 'E' && ${name.a}->val()->at(5) == '\\') ) { - if ( (${header.unicode} && ${name.u.s}->size() > 22 && ${name.u.s[12]} == 'L' && - ${name.u.s[14]} == 'A' && - ${name.u.s[16]} == 'N' && - ${name.u.s[18]} == 'M' && - ${name.u.s[20]} == 'A' && + if ( (${header.unicode} && ${name.u.s}->size() > 22 && ${name.u.s[12]} == 'L' && + ${name.u.s[14]} == 'A' && + ${name.u.s[16]} == 'N' && + ${name.u.s[18]} == 'M' && + ${name.u.s[20]} == 'A' && ${name.u.s[22]} == 'N') || - (!${header.unicode} && ${name.a}->size() > 11 && ${name.a}->val()->at(6) == 'L' && - ${name.a}->val()->at(7) == 'A' && - ${name.a}->val()->at(8) == 'N' && - ${name.a}->val()->at(9) == 'M' && - ${name.a}->val()->at(10) == 'A' && + (!${header.unicode} && ${name.a}->size() > 11 && ${name.a}->val()->at(6) == 'L' && + ${name.a}->val()->at(7) == 'A' && + ${name.a}->val()->at(8) == 'N' && + ${name.a}->val()->at(9) == 'M' && + ${name.a}->val()->at(10) == 'A' && ${name.a}->val()->at(11) == 'N') ) { return SMB_RAP; diff --git a/src/analyzer/protocol/smb/smb-gssapi.pac b/src/analyzer/protocol/smb/smb-gssapi.pac index 812ada277b..20a7062205 100644 --- a/src/analyzer/protocol/smb/smb-gssapi.pac +++ b/src/analyzer/protocol/smb/smb-gssapi.pac @@ -6,8 +6,8 @@ refine connection SMB_Conn += { %} %init{ - gssapi = 0; - ntlm = 0; + gssapi = nullptr; + ntlm = nullptr; %} %cleanup{ diff --git a/src/analyzer/protocol/smb/smb-strings.pac b/src/analyzer/protocol/smb/smb-strings.pac index d94ec195d2..9c50d3234b 100644 --- a/src/analyzer/protocol/smb/smb-strings.pac +++ b/src/analyzer/protocol/smb/smb-strings.pac @@ -59,7 +59,7 @@ refine connection SMB_Conn += { %} %init{ - me = 0; + me = nullptr; %} function store_this_unicode_string(s: SMB_unicode_string): bool diff --git a/src/analyzer/protocol/smb/smb1-com-negotiate.pac b/src/analyzer/protocol/smb/smb1-com-negotiate.pac index 2a42dbf05c..57529a507f 100644 --- a/src/analyzer/protocol/smb/smb1-com-negotiate.pac +++ b/src/analyzer/protocol/smb/smb1-com-negotiate.pac @@ -147,7 +147,7 @@ refine connection SMB_Conn += { type SMB_dialect = record { buffer_format : uint8; # must be 0x2 for dialect - name : SMB_string(0,0); + name : SMB_string(false, 0); }; type SMB1_negotiate_request(header: SMB_Header) = record { diff --git a/src/analyzer/protocol/ssl/SSL.cc b/src/analyzer/protocol/ssl/SSL.cc index 3e447b9415..9da93888d5 100644 --- a/src/analyzer/protocol/ssl/SSL.cc +++ b/src/analyzer/protocol/ssl/SSL.cc @@ -139,13 +139,13 @@ std::optional> SSL_Analyzer::TLS12_PRF(const std::string& se #ifdef OPENSSL_HAVE_KDF_H #if defined(OPENSSL_VERSION_MAJOR) && (OPENSSL_VERSION_MAJOR >= 3) // alloc context + params - EVP_KDF* kdf = EVP_KDF_fetch(NULL, "TLS1-PRF", NULL); + EVP_KDF* kdf = EVP_KDF_fetch(nullptr, "TLS1-PRF", nullptr); EVP_KDF_CTX* kctx = EVP_KDF_CTX_new(kdf); OSSL_PARAM params[4], *p = params; EVP_KDF_free(kdf); #else /* OSSL 3 */ // alloc buffers - EVP_PKEY_CTX* pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_TLS1_PRF, NULL); + EVP_PKEY_CTX* pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_TLS1_PRF, nullptr); #endif /* OSSL 3 */ // prepare seed: seed = label + rnd1 + rnd2 @@ -297,7 +297,7 @@ bool SSL_Analyzer::TryDecryptApplicationData(int len, const u_char* data, bool i EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new(); EVP_CIPHER_CTX_init(ctx); - EVP_CipherInit(ctx, EVP_aes_256_gcm(), NULL, NULL, 0); + EVP_CipherInit(ctx, EVP_aes_256_gcm(), nullptr, nullptr, 0); encrypted += 8; // FIXME: is this because of nonce and aead tag? @@ -335,13 +335,13 @@ bool SSL_Analyzer::TryDecryptApplicationData(int len, const u_char* data, bool i 16); // see OpenSSL manpage - 16 is the block size for the supported cipher int decrypted_len = 0; - EVP_DecryptUpdate(ctx, NULL, &decrypted_len, s_aead_tag.data(), s_aead_tag.size()); + EVP_DecryptUpdate(ctx, nullptr, &decrypted_len, s_aead_tag.data(), s_aead_tag.size()); EVP_DecryptUpdate(ctx, decrypted.data(), &decrypted_len, encrypted, encrypted_len); assert(static_cast(decrypted_len) <= decrypted.size()); decrypted.resize(decrypted_len); int res = 0; - if ( res = EVP_DecryptFinal(ctx, NULL, &res); res == 0 ) { + if ( res = EVP_DecryptFinal(ctx, nullptr, &res); res == 0 ) { DBG_LOG(DBG_ANALYZER, "Decryption failed with return code: %d. Invalid key?\n", res); EVP_CIPHER_CTX_free(ctx); return false; diff --git a/src/analyzer/protocol/ssl/dtls-analyzer.pac b/src/analyzer/protocol/ssl/dtls-analyzer.pac index be60fdfc77..8ab3b9aa41 100644 --- a/src/analyzer/protocol/ssl/dtls-analyzer.pac +++ b/src/analyzer/protocol/ssl/dtls-analyzer.pac @@ -59,7 +59,7 @@ refine connection SSL_Conn += { return true; } - if ( i->message_handshake_sequence != ${rec.message_seq} || i->message_length != length || i->buffer == 0 ) + if ( i->message_handshake_sequence != ${rec.message_seq} || i->message_length != length || i->buffer == nullptr ) { // cannot resume reassembling. Let's abandon the current data and try anew... delete [] i->buffer; diff --git a/src/analyzer/protocol/ssl/ssl-analyzer.pac b/src/analyzer/protocol/ssl/ssl-analyzer.pac index 768e7b2fdc..2ff27e630c 100644 --- a/src/analyzer/protocol/ssl/ssl-analyzer.pac +++ b/src/analyzer/protocol/ssl/ssl-analyzer.pac @@ -132,14 +132,14 @@ refine typeattr V2Error += &let { refine typeattr V2ClientHello += &let { proc : bool = $context.connection.proc_client_hello(client_version, 0, - challenge, session_id, 0, ciphers, 0); + challenge, session_id, nullptr, ciphers, nullptr); }; refine typeattr V2ServerHello += &let { check_v2 : bool = $context.connection.proc_check_v2_server_hello_version(server_version); proc : bool = $context.connection.proc_server_hello(server_version, true, - conn_id_data, 0, 0, ciphers, 0) &requires(check_v2) &if(check_v2 == true); + conn_id_data, nullptr, nullptr, ciphers, 0) &requires(check_v2) &if(check_v2 == true); cert : bool = $context.connection.proc_v2_certificate(rec.is_orig, cert_data) &requires(proc) &requires(check_v2) &if(check_v2 == true); diff --git a/src/analyzer/protocol/ssl/tls-handshake-analyzer.pac b/src/analyzer/protocol/ssl/tls-handshake-analyzer.pac index 825827b15c..9916ea1b96 100644 --- a/src/analyzer/protocol/ssl/tls-handshake-analyzer.pac +++ b/src/analyzer/protocol/ssl/tls-handshake-analyzer.pac @@ -686,19 +686,18 @@ refine connection Handshake_Conn += { refine typeattr ClientHello += &let { proc : bool = $context.connection.proc_client_hello(client_version, gmt_unix_time, random_bytes, - session_id, csuits, 0, cmeths); + session_id, csuits, nullptr, cmeths); }; refine typeattr ServerHello += &let { proc : bool = $context.connection.proc_server_hello(server_version, - false, random_bytes, session_id, cipher_suite, 0, + false, random_bytes, session_id, cipher_suite, nullptr, compression_method); }; refine typeattr ServerHello13 += &let { proc : bool = $context.connection.proc_server_hello(server_version, - false, random, 0, cipher_suite, 0, - 0); + false, random, nullptr, cipher_suite, nullptr, 0); }; diff --git a/src/analyzer/protocol/ssl/tls-handshake-protocol.pac b/src/analyzer/protocol/ssl/tls-handshake-protocol.pac index 86fa538006..2e2271779a 100644 --- a/src/analyzer/protocol/ssl/tls-handshake-protocol.pac +++ b/src/analyzer/protocol/ssl/tls-handshake-protocol.pac @@ -807,19 +807,19 @@ type SSLExtension(rec: HandshakeRecord) = record { # Pretty code ahead. Deal with the fact that perhaps extensions are # not really present and we do not want to fail because of that. ext: case type of { - EXT_APPLICATION_LAYER_PROTOCOL_NEGOTIATION -> apnl: ApplicationLayerProtocolNegotiationExtension(rec)[] &until($element == 0 || $element != 0); - EXT_ELLIPTIC_CURVES -> elliptic_curves: EllipticCurves(rec)[] &until($element == 0 || $element != 0); - EXT_EC_POINT_FORMATS -> ec_point_formats: EcPointFormats(rec)[] &until($element == 0 || $element != 0); -# EXT_STATUS_REQUEST -> status_request: StatusRequest(rec)[] &until($element == 0 || $element != 0); - EXT_SERVER_NAME -> server_name: ServerNameExt(rec)[] &until($element == 0 || $element != 0); - EXT_SIGNATURE_ALGORITHMS -> signature_algorithm: SignatureAlgorithm(rec)[] &until($element == 0 || $element != 0); - EXT_SIGNED_CERTIFICATE_TIMESTAMP -> certificate_timestamp: SignedCertificateTimestampList(rec)[] &until($element == 0 || $element != 0); - EXT_KEY_SHARE -> key_share: KeyShare(rec, this)[] &until($element == 0 || $element != 0); - EXT_KEY_SHARE_OLD -> key_share_old: KeyShare(rec, this)[] &until($element == 0 || $element != 0); - EXT_SUPPORTED_VERSIONS -> supported_versions_selector: SupportedVersionsSelector(rec, data_len)[] &until($element == 0 || $element != 0); - EXT_PSK_KEY_EXCHANGE_MODES -> psk_key_exchange_modes: PSKKeyExchangeModes(rec)[] &until($element == 0 || $element != 0); - EXT_PRE_SHARED_KEY -> pre_shared_key: PreSharedKey(rec)[] &until($element == 0 || $element != 0); - EXT_CONNECTION_ID -> connection_id: ConnectionId(rec)[] &until($element == 0 || $element != 0); + EXT_APPLICATION_LAYER_PROTOCOL_NEGOTIATION -> apnl: ApplicationLayerProtocolNegotiationExtension(rec)[] &until($element == nullptr || $element != nullptr); + EXT_ELLIPTIC_CURVES -> elliptic_curves: EllipticCurves(rec)[] &until($element == nullptr || $element != nullptr); + EXT_EC_POINT_FORMATS -> ec_point_formats: EcPointFormats(rec)[] &until($element == nullptr || $element != nullptr); +# EXT_STATUS_REQUEST -> status_request: StatusRequest(rec)[] &until($element == nullptr || $element != nullptr); + EXT_SERVER_NAME -> server_name: ServerNameExt(rec)[] &until($element == nullptr || $element != nullptr); + EXT_SIGNATURE_ALGORITHMS -> signature_algorithm: SignatureAlgorithm(rec)[] &until($element == nullptr || $element != nullptr); + EXT_SIGNED_CERTIFICATE_TIMESTAMP -> certificate_timestamp: SignedCertificateTimestampList(rec)[] &until($element == nullptr || $element != nullptr); + EXT_KEY_SHARE -> key_share: KeyShare(rec, this)[] &until($element == nullptr || $element != nullptr); + EXT_KEY_SHARE_OLD -> key_share_old: KeyShare(rec, this)[] &until($element == nullptr || $element != nullptr); + EXT_SUPPORTED_VERSIONS -> supported_versions_selector: SupportedVersionsSelector(rec, data_len)[] &until($element == nullptr || $element != nullptr); + EXT_PSK_KEY_EXCHANGE_MODES -> psk_key_exchange_modes: PSKKeyExchangeModes(rec)[] &until($element == nullptr || $element != nullptr); + EXT_PRE_SHARED_KEY -> pre_shared_key: PreSharedKey(rec)[] &until($element == nullptr || $element != nullptr); + EXT_CONNECTION_ID -> connection_id: ConnectionId(rec)[] &until($element == nullptr || $element != nullptr); default -> data: bytestring &restofdata; }; } &length=data_len+4 &exportsourcedata; @@ -1102,4 +1102,3 @@ refine connection Handshake_Conn += { return true; %} }; - diff --git a/src/analyzer/protocol/zip/ZIP.cc b/src/analyzer/protocol/zip/ZIP.cc index 11be1e1a7a..fd9b8f4e12 100644 --- a/src/analyzer/protocol/zip/ZIP.cc +++ b/src/analyzer/protocol/zip/ZIP.cc @@ -11,12 +11,12 @@ ZIP_Analyzer::ZIP_Analyzer(Connection* conn, bool orig, Method arg_method) method = arg_method; zip = new z_stream; - zip->zalloc = 0; - zip->zfree = 0; - zip->opaque = 0; - zip->next_out = 0; + zip->zalloc = nullptr; + zip->zfree = nullptr; + zip->opaque = nullptr; + zip->next_out = nullptr; zip->avail_out = 0; - zip->next_in = 0; + zip->next_in = nullptr; zip->avail_in = 0; // "32" is a gross overload hack that means "check it diff --git a/src/binpac-lib.pac b/src/binpac-lib.pac index 93669a98e5..ed129268b9 100644 --- a/src/binpac-lib.pac +++ b/src/binpac-lib.pac @@ -20,7 +20,7 @@ function bytestring_caseprefix(s1: const_bytestring, s2: const_charptr): bool function bytestring_to_int(s: const_bytestring, base: int): int %{ - return strtol((const char*) std_str(s).c_str(), 0, base); + return strtol((const char*) std_str(s).c_str(), nullptr, base); %} function bytestring_to_double(s: const_bytestring): double diff --git a/src/broker/Data.cc b/src/broker/Data.cc index 1d44e38874..e888c14034 100644 --- a/src/broker/Data.cc +++ b/src/broker/Data.cc @@ -530,15 +530,15 @@ struct type_checker { else { indices_to_check.reserve(indices->size()); - for ( size_t i = 0; i < indices->size(); ++i ) - indices_to_check.emplace_back(&(*indices)[i]); + for ( const auto& idx : *indices ) + indices_to_check.emplace_back(&idx); } } else { indices_to_check.reserve(indices->size()); - for ( size_t i = 0; i < indices->size(); ++i ) - indices_to_check.emplace_back(&(*indices)[i]); + for ( const auto& idx : *indices ) + indices_to_check.emplace_back(&idx); } } else @@ -580,15 +580,15 @@ struct type_checker { else { indices_to_check.reserve(indices->size()); - for ( size_t i = 0; i < indices->size(); ++i ) - indices_to_check.emplace_back(&(*indices)[i]); + for ( const auto& idx : *indices ) + indices_to_check.emplace_back(&idx); } } else { indices_to_check.reserve(indices->size()); - for ( size_t i = 0; i < indices->size(); ++i ) - indices_to_check.emplace_back(&(*indices)[i]); + for ( const auto& idx : *indices ) + indices_to_check.emplace_back(&idx); } } else diff --git a/src/broker/Manager.cc b/src/broker/Manager.cc index e182764085..06cbb431be 100644 --- a/src/broker/Manager.cc +++ b/src/broker/Manager.cc @@ -775,7 +775,7 @@ void Manager::Peer(const string& addr, uint16_t port, double retry) { auto secs = broker::timeout::seconds(static_cast(retry)); bstate->endpoint.peer_nosync(addr, port, secs); - bstate->outbound_peerings.emplace(broker::network_info(addr, port)); + bstate->outbound_peerings.emplace(addr, port); auto counts_as_iosource = get_option("Broker::peer_counts_as_iosource")->AsBool(); @@ -1160,7 +1160,7 @@ RecordVal* Manager::MakeEvent(ValPList* args, zeek::detail::Frame* frame) { zeek::Args cargs; cargs.reserve(args->size()); for ( auto* a : *args ) - cargs.push_back({zeek::NewRef{}, a}); + cargs.emplace_back(zeek::NewRef{}, a); return MakeEvent(ArgsSpan{cargs}, frame)->Ref()->AsRecordVal(); } diff --git a/src/cluster/serializer/broker/Serializer.cc b/src/cluster/serializer/broker/Serializer.cc index e0bdcde4b2..1d036caa65 100644 --- a/src/cluster/serializer/broker/Serializer.cc +++ b/src/cluster/serializer/broker/Serializer.cc @@ -82,10 +82,8 @@ std::optional detail::to_broker_event(const detail::Event& for ( const auto& m : *meta ) { if ( auto res = zeek::Broker::detail::val_to_data(m.Val().get()); res.has_value() ) { - broker::vector entry(2); - entry[0] = static_cast(m.Id()); - entry[1] = res.value(); - broker_meta.push_back(std::move(entry)); + broker::vector entry{static_cast(m.Id()), res.value()}; + broker_meta.emplace_back(std::move(entry)); } else { // Just for sanity - we should never get here. diff --git a/src/digest.cc b/src/digest.cc index ab80baaa18..75b8bc0511 100644 --- a/src/digest.cc +++ b/src/digest.cc @@ -57,7 +57,7 @@ HashDigestState* hash_init(HashAlgorithm alg) { default: reporter->InternalError("Unknown hash algorithm passed to hash_init"); } - if ( ! EVP_DigestInit_ex(c, md, NULL) ) + if ( ! EVP_DigestInit_ex(c, md, nullptr) ) reporter->InternalError("EVP_DigestInit failed"); return to_opaque_ptr(c); @@ -74,7 +74,7 @@ void hash_final(HashDigestState* c, u_char* md) { } void hash_final_no_free(HashDigestState* c, u_char* md) { - if ( ! EVP_DigestFinal(to_native_ptr(c), md, NULL) ) + if ( ! EVP_DigestFinal(to_native_ptr(c), md, nullptr) ) reporter->InternalError("EVP_DigestFinal failed"); } diff --git a/src/file_analysis/Analyzer.cc b/src/file_analysis/Analyzer.cc index 913a78e5a7..c5ed3aff03 100644 --- a/src/file_analysis/Analyzer.cc +++ b/src/file_analysis/Analyzer.cc @@ -24,7 +24,7 @@ void Analyzer::SetAnalyzerTag(const zeek::Tag& arg_tag) { } Analyzer::Analyzer(zeek::Tag arg_tag, RecordValPtr arg_args, File* arg_file) - : tag(arg_tag), + : tag(std::move(arg_tag)), args(std::move(arg_args)), file(arg_file), got_stream_delivery(false), diff --git a/src/file_analysis/FileReassembler.cc b/src/file_analysis/FileReassembler.cc index 7745bcdc75..fae2626451 100644 --- a/src/file_analysis/FileReassembler.cc +++ b/src/file_analysis/FileReassembler.cc @@ -11,7 +11,7 @@ namespace zeek::file_analysis { class File; FileReassembler::FileReassembler(File* f, uint64_t starting_offset) - : Reassembler(starting_offset, REASSEM_FILE), the_file(f), flushing(false) {} + : Reassembler(starting_offset, REASSEM_FILE), the_file(f) {} uint64_t FileReassembler::Flush() { if ( flushing ) diff --git a/src/file_analysis/FileTimer.cc b/src/file_analysis/FileTimer.cc index d5714617a0..688a9e7927 100644 --- a/src/file_analysis/FileTimer.cc +++ b/src/file_analysis/FileTimer.cc @@ -7,8 +7,8 @@ namespace zeek::file_analysis::detail { -FileTimer::FileTimer(double t, const std::string& id, double interval) - : zeek::detail::Timer(t + interval, zeek::detail::TIMER_FILE_ANALYSIS_INACTIVITY), file_id(id) { +FileTimer::FileTimer(double t, std::string id, double interval) + : zeek::detail::Timer(t + interval, zeek::detail::TIMER_FILE_ANALYSIS_INACTIVITY), file_id(std::move(id)) { DBG_LOG(DBG_FILE_ANALYSIS, "New %f second timeout timer for %s", interval, file_id.c_str()); } diff --git a/src/file_analysis/FileTimer.h b/src/file_analysis/FileTimer.h index af2dac1395..690a3d6253 100644 --- a/src/file_analysis/FileTimer.h +++ b/src/file_analysis/FileTimer.h @@ -19,7 +19,7 @@ public: * @param id the file identifier which will be checked for inactivity. * @param interval amount of time after \a t to check for inactivity. */ - FileTimer(double t, const std::string& id, double interval); + FileTimer(double t, std::string id, double interval); /** * Check inactivity of file_analysis::File corresponding to #file_id, diff --git a/src/file_analysis/Manager.cc b/src/file_analysis/Manager.cc index 85a3e83ba4..d67621c201 100644 --- a/src/file_analysis/Manager.cc +++ b/src/file_analysis/Manager.cc @@ -24,8 +24,8 @@ Manager::Manager() max_files(0) {} Manager::~Manager() { - for ( MIMEMap::iterator i = mime_types.begin(); i != mime_types.end(); i++ ) - delete i->second; + for ( const auto& [_, tag] : mime_types ) + delete tag; // Have to assume that too much of Zeek has been shutdown by this point // to do anything more than reclaim memory. @@ -473,12 +473,12 @@ VectorValPtr GenMIMEMatchesVal(const zeek::detail::RuleMatcher::MIME_Matches& m) static auto mime_match = id::find_type("mime_match"); auto rval = make_intrusive(mime_matches); - for ( zeek::detail::RuleMatcher::MIME_Matches::const_iterator it = m.begin(); it != m.end(); ++it ) { + for ( const auto& [index, match] : m ) { auto element = make_intrusive(mime_match); - for ( set::const_iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2 ) { - element->Assign(0, it->first); - element->Assign(1, *it2); + for ( const string& match_str : match ) { + element->Assign(0, index); + element->Assign(1, match_str); } rval->Assign(rval->Size(), std::move(element)); diff --git a/src/file_analysis/analyzer/extract/Extract.cc b/src/file_analysis/analyzer/extract/Extract.cc index 458f5f91e1..d5eb6263ac 100644 --- a/src/file_analysis/analyzer/extract/Extract.cc +++ b/src/file_analysis/analyzer/extract/Extract.cc @@ -11,10 +11,10 @@ namespace zeek::file_analysis::detail { -Extract::Extract(RecordValPtr args, file_analysis::File* file, const std::string& arg_filename, uint64_t arg_limit, +Extract::Extract(RecordValPtr args, file_analysis::File* file, std::string arg_filename, uint64_t arg_limit, bool arg_limit_includes_missing) : file_analysis::Analyzer(file_mgr->GetComponentTag("EXTRACT"), std::move(args), file), - filename(arg_filename), + filename(std::move(arg_filename)), limit(arg_limit), written(0), limit_includes_missing(arg_limit_includes_missing) { diff --git a/src/file_analysis/analyzer/extract/Extract.h b/src/file_analysis/analyzer/extract/Extract.h index 4d11047655..733bb91527 100644 --- a/src/file_analysis/analyzer/extract/Extract.h +++ b/src/file_analysis/analyzer/extract/Extract.h @@ -64,7 +64,7 @@ protected: * @param arg_limit the maximum allowed file size. * @param arg_limit_includes_missing missing bytes count towards limit if true. */ - Extract(RecordValPtr args, file_analysis::File* file, const std::string& arg_filename, uint64_t arg_limit, + Extract(RecordValPtr args, file_analysis::File* file, std::string arg_filename, uint64_t arg_limit, bool arg_limit_includes_missing); private: diff --git a/src/file_analysis/analyzer/pe/pe-analyzer.pac b/src/file_analysis/analyzer/pe/pe-analyzer.pac index 6b34babe8c..bf2a637e25 100644 --- a/src/file_analysis/analyzer/pe/pe-analyzer.pac +++ b/src/file_analysis/analyzer/pe/pe-analyzer.pac @@ -31,7 +31,7 @@ zeek::TableValPtr characteristics_to_zeek(uint32_t c, uint8_t len) if ( ((c >> i) & 0x1) == 1 ) { auto ch = zeek::val_mgr->Count((1<Assign(std::move(ch), 0); + char_set->Assign(std::move(ch), nullptr); } } @@ -172,7 +172,7 @@ refine flow File += { // Strip null characters from the end of the section name. u_char* first_null = (u_char*) memchr(${h.name}.data(), 0, ${h.name}.length()); uint16 name_len; - if ( first_null == NULL ) + if ( first_null == nullptr ) name_len = ${h.name}.length(); else name_len = first_null - ${h.name}.data(); diff --git a/src/file_analysis/analyzer/x509/OCSP.cc b/src/file_analysis/analyzer/x509/OCSP.cc index 8fead1edf4..f021ec4791 100644 --- a/src/file_analysis/analyzer/x509/OCSP.cc +++ b/src/file_analysis/analyzer/x509/OCSP.cc @@ -125,7 +125,7 @@ bool OCSP::EndOfFile() { const unsigned char* ocsp_char = reinterpret_cast(ocsp_data.data()); if ( request ) { - OCSP_REQUEST* req = d2i_OCSP_REQUEST(NULL, &ocsp_char, ocsp_data.size()); + OCSP_REQUEST* req = d2i_OCSP_REQUEST(nullptr, &ocsp_char, ocsp_data.size()); if ( ! req ) { reporter->Weird(GetFile(), "openssl_ocsp_request_parse_error"); @@ -136,7 +136,7 @@ bool OCSP::EndOfFile() { OCSP_REQUEST_free(req); } else { - OCSP_RESPONSE* resp = d2i_OCSP_RESPONSE(NULL, &ocsp_char, ocsp_data.size()); + OCSP_RESPONSE* resp = d2i_OCSP_RESPONSE(nullptr, &ocsp_char, ocsp_data.size()); if ( ! resp ) { reporter->Weird(GetFile(), "openssl_ocsp_response_parse_error"); diff --git a/src/file_analysis/analyzer/x509/X509.cc b/src/file_analysis/analyzer/x509/X509.cc index b12e95c89f..0e60f45789 100644 --- a/src/file_analysis/analyzer/x509/X509.cc +++ b/src/file_analysis/analyzer/x509/X509.cc @@ -65,7 +65,7 @@ bool X509::EndOfFile() { // ok, now we can try to parse the certificate with openssl. Should // be rather straightforward... - ::X509* ssl_cert = d2i_X509(NULL, &cert_char, cert_data.size()); + ::X509* ssl_cert = d2i_X509(nullptr, &cert_char, cert_data.size()); if ( ! ssl_cert ) { reporter->Weird(GetFile(), "x509_cert_parse_error"); return false; @@ -155,7 +155,7 @@ RecordValPtr X509::ParseCertificate(X509Val* cert_val, file_analysis::File* f) { // if the string is longer than 255, that will be our null-termination, // otherwise i2t does null-terminate. ASN1_OBJECT* algorithm; - X509_PUBKEY_get0_param(&algorithm, NULL, NULL, NULL, X509_get_X509_PUBKEY(ssl_cert)); + X509_PUBKEY_get0_param(&algorithm, nullptr, nullptr, nullptr, X509_get_X509_PUBKEY(ssl_cert)); if ( ! i2t_ASN1_OBJECT(buf, 255, algorithm) ) buf[0] = 0; @@ -165,7 +165,7 @@ RecordValPtr X509::ParseCertificate(X509Val* cert_val, file_analysis::File* f) { i2a_ASN1_OBJECT(bio, ssl_cert->sig_alg->algorithm); #else const ASN1_OBJECT* alg; - X509_ALGOR_get0(&alg, NULL, NULL, X509_get0_tbs_sigalg(ssl_cert)); + X509_ALGOR_get0(&alg, nullptr, nullptr, X509_get0_tbs_sigalg(ssl_cert)); i2a_ASN1_OBJECT(bio, alg); #endif len = BIO_gets(bio, buf, sizeof(buf)); @@ -180,13 +180,13 @@ RecordValPtr X509::ParseCertificate(X509Val* cert_val, file_analysis::File* f) { if ( OBJ_obj2nid(algorithm) == NID_md5WithRSAEncryption ) { ASN1_OBJECT* copy = OBJ_dup(algorithm); // the next line will destroy the original algorithm. - X509_PUBKEY_set0_param(X509_get_X509_PUBKEY(ssl_cert), OBJ_nid2obj(NID_rsaEncryption), 0, NULL, NULL, 0); + X509_PUBKEY_set0_param(X509_get_X509_PUBKEY(ssl_cert), OBJ_nid2obj(NID_rsaEncryption), 0, nullptr, nullptr, 0); algorithm = copy; // we do not have to worry about freeing algorithm in that case - since it will be // re-assigned using set0_param and the cert will take ownership. } else - algorithm = 0; + algorithm = nullptr; if ( ! i2t_ASN1_OBJECT(buf, 255, OBJ_nid2obj(X509_get_signature_nid(ssl_cert))) ) buf[0] = 0; @@ -195,7 +195,7 @@ RecordValPtr X509::ParseCertificate(X509Val* cert_val, file_analysis::File* f) { // Things we can do when we have the key... EVP_PKEY* pkey = X509_extract_key(ssl_cert); - if ( pkey != NULL ) { + if ( pkey != nullptr ) { if ( EVP_PKEY_base_id(pkey) == EVP_PKEY_DSA ) pX509Cert->Assign(9, "dsa"); @@ -204,7 +204,7 @@ RecordValPtr X509::ParseCertificate(X509Val* cert_val, file_analysis::File* f) { #if OPENSSL_VERSION_NUMBER < 0x30000000L const BIGNUM* e = nullptr; - RSA_get0_key(EVP_PKEY_get0_RSA(pkey), NULL, &e, NULL); + RSA_get0_key(EVP_PKEY_get0_RSA(pkey), nullptr, &e, nullptr); #else BIGNUM* e = nullptr; EVP_PKEY_get_bn_param(pkey, OSSL_PKEY_PARAM_RSA_E, &e); @@ -216,10 +216,10 @@ RecordValPtr X509::ParseCertificate(X509Val* cert_val, file_analysis::File* f) { BN_free(e); e = nullptr; #endif - if ( exponent != NULL ) { + if ( exponent != nullptr ) { pX509Cert->Assign(11, exponent); OPENSSL_free(exponent); - exponent = NULL; + exponent = nullptr; } } #ifndef OPENSSL_NO_EC @@ -232,7 +232,7 @@ RecordValPtr X509::ParseCertificate(X509Val* cert_val, file_analysis::File* f) { // set key algorithm back. We do not have to free the value that we created because (I // think) it comes out of a static array from OpenSSL memory. if ( algorithm ) - X509_PUBKEY_set0_param(X509_get_X509_PUBKEY(ssl_cert), algorithm, 0, NULL, NULL, 0); + X509_PUBKEY_set0_param(X509_get_X509_PUBKEY(ssl_cert), algorithm, 0, nullptr, nullptr, 0); unsigned int length = KeyLength(pkey); if ( length > 0 ) @@ -259,9 +259,9 @@ X509_STORE* X509::GetRootStore(TableVal* root_certs) { StringVal* sv = val->AsStringVal(); assert(sv); const uint8_t* data = sv->Bytes(); - ::X509* x = d2i_X509(NULL, &data, sv->Len()); + ::X509* x = d2i_X509(nullptr, &data, sv->Len()); if ( ! x ) { - emit_builtin_error(util::fmt("Root CA error: %s", ERR_error_string(ERR_get_error(), NULL))); + emit_builtin_error(util::fmt("Root CA error: %s", ERR_error_string(ERR_get_error(), nullptr))); return nullptr; } @@ -443,7 +443,7 @@ StringValPtr X509::KeyCurve(EVP_PKEY* key) { #if OPENSSL_VERSION_NUMBER < 0x30000000L const EC_GROUP* group; int nid; - if ( (group = EC_KEY_get0_group(EVP_PKEY_get0_EC_KEY(key))) == NULL ) + if ( (group = EC_KEY_get0_group(EVP_PKEY_get0_EC_KEY(key))) == nullptr ) // I guess we could not parse this return nullptr; @@ -468,13 +468,13 @@ StringValPtr X509::KeyCurve(EVP_PKEY* key) { } unsigned int X509::KeyLength(EVP_PKEY* key) { - assert(key != NULL); + assert(key != nullptr); switch ( EVP_PKEY_base_id(key) ) { case EVP_PKEY_RSA: { #if OPENSSL_VERSION_NUMBER < 0x30000000L const BIGNUM* n = nullptr; - RSA_get0_key(EVP_PKEY_get0_RSA(key), &n, NULL, NULL); + RSA_get0_key(EVP_PKEY_get0_RSA(key), &n, nullptr, nullptr); return BN_num_bits(n); #else BIGNUM* n = nullptr; @@ -488,7 +488,7 @@ unsigned int X509::KeyLength(EVP_PKEY* key) { case EVP_PKEY_DSA: { #if OPENSSL_VERSION_NUMBER < 0x30000000L const BIGNUM* p; - DSA_get0_pqg(EVP_PKEY_get0_DSA(key), &p, NULL, NULL); + DSA_get0_pqg(EVP_PKEY_get0_DSA(key), &p, nullptr, nullptr); return BN_num_bits(p); #else BIGNUM* p = nullptr; @@ -516,7 +516,7 @@ unsigned int X509::KeyLength(EVP_PKEY* key) { return 0; } - if ( ! EC_GROUP_get_order(group, ec_order, NULL) ) { + if ( ! EC_GROUP_get_order(group, ec_order, nullptr) ) { // could not get ec-group-order BN_free(ec_order); return 0; @@ -539,7 +539,7 @@ unsigned int X509::KeyLength(EVP_PKEY* key) { X509Val::X509Val(::X509* arg_certificate) : OpaqueVal(x509_opaque_type) { certificate = arg_certificate; } -X509Val::X509Val() : OpaqueVal(x509_opaque_type) { certificate = 0; } +X509Val::X509Val() : OpaqueVal(x509_opaque_type) { certificate = nullptr; } X509Val::~X509Val() { if ( certificate ) @@ -578,7 +578,7 @@ bool X509Val::DoUnserializeData(BrokerDataView data) { auto s = data.ToString(); auto opensslbuf = reinterpret_cast(s.data()); - certificate = d2i_X509(NULL, &opensslbuf, s.size()); + certificate = d2i_X509(nullptr, &opensslbuf, s.size()); return certificate != nullptr; } diff --git a/src/file_analysis/analyzer/x509/X509Common.cc b/src/file_analysis/analyzer/x509/X509Common.cc index 9722e393d5..a1ed4f6d91 100644 --- a/src/file_analysis/analyzer/x509/X509Common.cc +++ b/src/file_analysis/analyzer/x509/X509Common.cc @@ -180,7 +180,7 @@ void X509Common::ParseSignedCertificateTimestamps(X509_EXTENSION* ext) { unsigned char* ext_val_second_pointer = ext_val_copy; memcpy(ext_val_copy, ext_val->data, ext_val->length); - ASN1_OCTET_STRING* inner = d2i_ASN1_OCTET_STRING(NULL, (const unsigned char**)&ext_val_copy, ext_val->length); + ASN1_OCTET_STRING* inner = d2i_ASN1_OCTET_STRING(nullptr, (const unsigned char**)&ext_val_copy, ext_val->length); if ( ! inner ) { OPENSSL_free(ext_val_second_pointer); reporter->Error("X509::ParseSignedCertificateTimestamps could not parse inner octet string"); diff --git a/src/file_analysis/analyzer/x509/functions.bif b/src/file_analysis/analyzer/x509/functions.bif index 8a13f4d446..3be7dcd41d 100644 --- a/src/file_analysis/analyzer/x509/functions.bif +++ b/src/file_analysis/analyzer/x509/functions.bif @@ -31,8 +31,8 @@ STACK_OF(X509)* x509_get_untrusted_stack(zeek::VectorVal* certs_vec) if ( ! untrusted_certs ) { zeek::emit_builtin_error(zeek::util::fmt("Untrusted certificate stack initialization error: %s", - ERR_error_string(ERR_get_error(),NULL))); - return 0; + ERR_error_string(ERR_get_error(), nullptr))); + return nullptr; } for ( int i = 1; i < (int) certs_vec->Size(); ++i ) // start at 1 - 0 is host cert @@ -48,7 +48,7 @@ STACK_OF(X509)* x509_get_untrusted_stack(zeek::VectorVal* certs_vec) { sk_X509_free(untrusted_certs); zeek::emit_builtin_error("No certificate in opaque in stack"); - return 0; + return nullptr; } sk_X509_push(untrusted_certs, x); @@ -73,10 +73,10 @@ X509* x509_get_ocsp_signer(const STACK_OF(X509)* certs, else if ( resp_id->type == V_OCSP_RESPID_KEY ) key = resp_id->value.byKey; else - return 0; + return nullptr; #else if ( ! OCSP_resp_get0_id(basic_resp, &key, &name) ) - return 0; + return nullptr; #endif if ( name ) @@ -85,7 +85,7 @@ X509* x509_get_ocsp_signer(const STACK_OF(X509)* certs, // Just like OpenSSL, we just support SHA-1 lookups and bail out otherwise. if ( key->length != SHA_DIGEST_LENGTH ) - return 0; + return nullptr; unsigned char* key_hash = key->data; @@ -93,7 +93,7 @@ X509* x509_get_ocsp_signer(const STACK_OF(X509)* certs, { unsigned char digest[SHA_DIGEST_LENGTH]; X509* cert = sk_X509_value(certs, i); - if ( ! X509_pubkey_digest(cert, EVP_sha1(), digest, NULL) ) + if ( ! X509_pubkey_digest(cert, EVP_sha1(), digest, nullptr) ) // digest failed for this certificate, try with next continue; @@ -102,7 +102,7 @@ X509* x509_get_ocsp_signer(const STACK_OF(X509)* certs, return cert; } - return 0; + return nullptr; } // Convert hash algorithm registry numbers to the OpenSSL EVP_MD. @@ -304,21 +304,21 @@ function x509_ocsp_verify%(certs: x509_opaque_vector, ocsp_reply: string, root_c // from here, always goto cleanup. Initialize all other required variables... time_t vtime = (time_t) verify_time; - OCSP_BASICRESP *basic = 0; - OCSP_SINGLERESP *single = 0; - X509_STORE_CTX *csc = 0; - OCSP_CERTID *certid = 0; + OCSP_BASICRESP *basic = nullptr; + OCSP_SINGLERESP *single = nullptr; + X509_STORE_CTX *csc = nullptr; + OCSP_CERTID *certid = nullptr; stack_st_X509* ocsp_certs = nullptr; int status = -1; int out = -1; int result = -1; - X509* issuer_certificate = 0; - X509* signer = 0; + X509* issuer_certificate = nullptr; + X509* signer = nullptr; ASN1_GENERALIZEDTIME* thisUpdate = nullptr; ASN1_GENERALIZEDTIME* nextUpdate = nullptr; int type = -1; - OCSP_RESPONSE *resp = d2i_OCSP_RESPONSE(NULL, &start, ocsp_reply->Len()); + OCSP_RESPONSE *resp = d2i_OCSP_RESPONSE(nullptr, &start, ocsp_reply->Len()); if ( ! resp ) { @@ -348,7 +348,7 @@ function x509_ocsp_verify%(certs: x509_opaque_vector, ocsp_reply: string, root_c // the lookup. // Yay. - issuer_certificate = 0; + issuer_certificate = nullptr; for ( int i = 0; i < sk_X509_num(untrusted_certs); i++) { OCSP_basic_add1_cert(basic, sk_X509_value(untrusted_certs, i)); @@ -404,10 +404,10 @@ function x509_ocsp_verify%(certs: x509_opaque_vector, ocsp_reply: string, root_c // We pass OCSP_NOVERIFY to let OCSP_basic_verify skip the chain verification. // With that, it only verifies the signature of the basic response and we are responsible // for the chain ourselves. We have to do that since we cannot get OCSP_basic_verify to use our timestamp. - out = OCSP_basic_verify(basic, NULL, ctx, OCSP_NOVERIFY); + out = OCSP_basic_verify(basic, nullptr, ctx, OCSP_NOVERIFY); if ( out < 1 ) { - rval = x509_result_record(out, ERR_error_string(ERR_get_error(),NULL)); + rval = x509_result_record(out, ERR_error_string(ERR_get_error(), nullptr)); goto x509_ocsp_cleanup; } @@ -421,7 +421,7 @@ function x509_ocsp_verify%(certs: x509_opaque_vector, ocsp_reply: string, root_c // into accepting. if ( issuer_certificate ) - certid = OCSP_cert_to_id(NULL, cert, issuer_certificate); + certid = OCSP_cert_to_id(nullptr, cert, issuer_certificate); else { // issuer not in list sent by server, check store @@ -434,7 +434,7 @@ function x509_ocsp_verify%(certs: x509_opaque_vector, ocsp_reply: string, root_c goto x509_ocsp_cleanup; } - certid = OCSP_cert_to_id(NULL, cert,X509_OBJECT_get0_X509( obj)); + certid = OCSP_cert_to_id(nullptr, cert,X509_OBJECT_get0_X509( obj)); X509_OBJECT_free(obj); } @@ -457,7 +457,7 @@ function x509_ocsp_verify%(certs: x509_opaque_vector, ocsp_reply: string, root_c return x509_result_record(-1, "OCSP reply is not for host certificate"); // next - check freshness of proof... - type = OCSP_single_get0_status(single, NULL, NULL, &thisUpdate, &nextUpdate); + type = OCSP_single_get0_status(single, nullptr, nullptr, &thisUpdate, &nextUpdate); if ( type == -1 ) { @@ -774,7 +774,7 @@ function sct_verify%(cert: opaque of x509, logid: string, log_key: string, signa goto sct_verify_err; } - if ( ! EVP_DigestVerifyInit(mdctx, NULL, hash, NULL, key) ) + if ( ! EVP_DigestVerifyInit(mdctx, nullptr, hash, nullptr, key) ) { errstr = "Could not init signature verification"; goto sct_verify_err; diff --git a/src/input/Manager.cc b/src/input/Manager.cc index 19e074eeab..94eae7490c 100644 --- a/src/input/Manager.cc +++ b/src/input/Manager.cc @@ -51,16 +51,16 @@ static void input_hash_delete_func(void* val) { class Manager::Stream { public: string name; - bool removed; + bool removed = false; StreamType stream_type; // to distinguish between event and table streams - EnumVal* type; - ReaderFrontend* reader; - TableVal* config; + EnumVal* type = nullptr; + ReaderFrontend* reader = nullptr; + TableVal* config = nullptr; EventHandlerPtr error_event; - RecordVal* description; + RecordVal* description = nullptr; virtual ~Stream(); @@ -68,8 +68,7 @@ protected: Stream(StreamType t); }; -Manager::Stream::Stream(StreamType t) - : name(), removed(), stream_type(t), type(), reader(), config(), error_event(), description() {} +Manager::Stream::Stream(StreamType t) : stream_type(t) {} Manager::Stream::~Stream() { Unref(type); @@ -80,18 +79,18 @@ Manager::Stream::~Stream() { class Manager::TableStream final : public Manager::Stream { public: - unsigned int num_idx_fields; - unsigned int num_val_fields; - bool want_record; + unsigned int num_idx_fields = 0; + unsigned int num_val_fields = 0; + bool want_record = false; - TableVal* tab; - RecordType* rtype; - RecordType* itype; + TableVal* tab = nullptr; + RecordType* rtype = nullptr; + RecordType* itype = nullptr; - PDict* currDict; - PDict* lastDict; + PDict* currDict = nullptr; + PDict* lastDict = nullptr; - Func* pred; + Func* pred = nullptr; EventHandlerPtr event; @@ -103,7 +102,7 @@ class Manager::EventStream final : public Manager::Stream { public: EventHandlerPtr event; - RecordType* fields; + RecordType* fields = nullptr; unsigned int num_fields; bool want_record; @@ -119,21 +118,9 @@ public: ~AnalysisStream() override = default; }; -Manager::TableStream::TableStream() - : Manager::Stream::Stream(TABLE_STREAM), - num_idx_fields(), - num_val_fields(), - want_record(), - tab(), - rtype(), - itype(), - currDict(), - lastDict(), - pred(), - event() {} +Manager::TableStream::TableStream() : Manager::Stream::Stream(TABLE_STREAM) {} -Manager::EventStream::EventStream() - : Manager::Stream::Stream(EVENT_STREAM), event(), fields(), num_fields(), want_record() {} +Manager::EventStream::EventStream() : Manager::Stream::Stream(EVENT_STREAM) {} Manager::EventStream::~EventStream() { if ( fields ) @@ -169,9 +156,9 @@ Manager::Manager() : plugin::ComponentManager("Input", "Reader } Manager::~Manager() { - for ( map::iterator s = readers.begin(); s != readers.end(); ++s ) { - delete s->second; - delete s->first; + for ( auto& [frontend, stream] : readers ) { + delete stream; + delete frontend; } } @@ -1439,8 +1426,8 @@ int Manager::SendEventStreamEvent(Stream* i, EnumVal* type, const Value* const* if ( convert_error ) { // we have an error somewhere in our out_vals. Just delete all of them. - for ( list::const_iterator it = out_vals.begin(), end = out_vals.end(); it != end; ++it ) - Unref(*it); + for ( auto* val : out_vals ) + Unref(val); } else SendEvent(stream->event, out_vals); @@ -1712,8 +1699,8 @@ void Manager::SendEvent(EventHandlerPtr ev, list events) const { DBG_LOG(DBG_INPUT, "SendEvent with %" PRIuPTR " vals (list)", events.size()); #endif - for ( list::iterator i = events.begin(); i != events.end(); i++ ) - vl.emplace_back(AdoptRef{}, *i); + for ( auto* val : events ) + vl.emplace_back(AdoptRef{}, val); if ( ev ) event_mgr.Enqueue(ev, std::move(vl), util::detail::SOURCE_LOCAL); @@ -2167,9 +2154,9 @@ Val* Manager::ValueToVal(const Stream* i, const Value* val, Type* request_type, } Manager::Stream* Manager::FindStream(const string& name) const { - for ( auto s = readers.begin(); s != readers.end(); ++s ) { - if ( (*s).second->name == name ) - return (*s).second; + for ( const auto& [_, stream] : readers ) { + if ( stream->name == name ) + return stream; } return nullptr; @@ -2186,12 +2173,12 @@ Manager::Stream* Manager::FindStream(ReaderFrontend* reader) const { // Function is called on Zeek shutdown. // Signal all frontends that they will cease operation. void Manager::Terminate() { - for ( map::iterator i = readers.begin(); i != readers.end(); ++i ) { - if ( i->second->removed ) + for ( const auto& [_, stream] : readers ) { + if ( stream->removed ) continue; - i->second->removed = true; - i->second->reader->Stop(); + stream->removed = true; + stream->reader->Stop(); } } diff --git a/src/input/readers/ascii/Ascii.cc b/src/input/readers/ascii/Ascii.cc index 0468e166e7..78f225a93d 100644 --- a/src/input/readers/ascii/Ascii.cc +++ b/src/input/readers/ascii/Ascii.cc @@ -17,17 +17,14 @@ using zeek::threading::Value; namespace zeek::input::reader::detail { -FieldMapping::FieldMapping(const string& arg_name, const TypeTag& arg_type, int arg_position) - : name(arg_name), type(arg_type), subtype(TYPE_ERROR) { - position = arg_position; +FieldMapping::FieldMapping(string arg_name, const TypeTag& arg_type, int arg_position) + : name(std::move(arg_name)), type(arg_type), subtype(TYPE_ERROR), position(arg_position) { secondary_position = -1; present = true; } -FieldMapping::FieldMapping(const string& arg_name, const TypeTag& arg_type, const TypeTag& arg_subtype, - int arg_position) - : name(arg_name), type(arg_type), subtype(arg_subtype) { - position = arg_position; +FieldMapping::FieldMapping(string arg_name, const TypeTag& arg_type, const TypeTag& arg_subtype, int arg_position) + : name(std::move(arg_name)), type(arg_type), subtype(arg_subtype), position(arg_position) { secondary_position = -1; present = true; } diff --git a/src/input/readers/ascii/Ascii.h b/src/input/readers/ascii/Ascii.h index 73aa3f84e8..a6d24e419f 100644 --- a/src/input/readers/ascii/Ascii.h +++ b/src/input/readers/ascii/Ascii.h @@ -23,8 +23,8 @@ struct FieldMapping { int secondary_position = -1; // for ports: pos of the second field bool present = false; - FieldMapping(const std::string& arg_name, const TypeTag& arg_type, int arg_position); - FieldMapping(const std::string& arg_name, const TypeTag& arg_type, const TypeTag& arg_subtype, int arg_position); + FieldMapping(std::string arg_name, const TypeTag& arg_type, int arg_position); + FieldMapping(std::string arg_name, const TypeTag& arg_type, const TypeTag& arg_subtype, int arg_position); FieldMapping(const FieldMapping& arg); FieldMapping() = default; diff --git a/src/input/readers/benchmark/Benchmark.cc b/src/input/readers/benchmark/Benchmark.cc index 48010bb5b6..ea19017145 100644 --- a/src/input/readers/benchmark/Benchmark.cc +++ b/src/input/readers/benchmark/Benchmark.cc @@ -66,7 +66,7 @@ std::string Benchmark::RandomString(const int len) { double Benchmark::CurrTime() { struct timeval tv; - if ( gettimeofday(&tv, 0) != 0 ) { + if ( gettimeofday(&tv, nullptr) != 0 ) { FatalError(Fmt("Could not get time: %d", errno)); } diff --git a/src/input/readers/raw/Plugin.cc b/src/input/readers/raw/Plugin.cc index f42f4a9ff2..6c1193fc0e 100644 --- a/src/input/readers/raw/Plugin.cc +++ b/src/input/readers/raw/Plugin.cc @@ -22,6 +22,6 @@ void Plugin::InitPreScript() {} void Plugin::Done() {} -std::unique_lock Plugin::ForkMutex() { return std::unique_lock(fork_mutex, std::defer_lock); } +std::unique_lock Plugin::ForkMutex() { return {fork_mutex, std::defer_lock}; } } // namespace zeek::plugin::detail::Zeek_RawReader diff --git a/src/input/readers/raw/Raw.cc b/src/input/readers/raw/Raw.cc index 6dec5c6bcd..3a4eff0c93 100644 --- a/src/input/readers/raw/Raw.cc +++ b/src/input/readers/raw/Raw.cc @@ -368,7 +368,7 @@ bool Raw::DoInit(const ReaderInfo& info, int num_fields, const Field* const* fie it = info.config.find("offset"); // we want to seek to a given offset inside the file if ( it != info.config.end() && ! execute && (Info().mode == MODE_STREAM || Info().mode == MODE_MANUAL) ) { std::string offset_s = it->second; - offset = strtoll(offset_s.c_str(), 0, 10); + offset = strtoll(offset_s.c_str(), nullptr, 10); } else if ( it != info.config.end() ) { Error( diff --git a/src/input/readers/sqlite/SQLite.cc b/src/input/readers/sqlite/SQLite.cc index 3d22189a66..d389168df3 100644 --- a/src/input/readers/sqlite/SQLite.cc +++ b/src/input/readers/sqlite/SQLite.cc @@ -40,9 +40,9 @@ void SQLite::DoClose() { sqlite3_finalize(st); st = nullptr; - if ( db != 0 ) { + if ( db != nullptr ) { sqlite3_close(db); - db = 0; + db = nullptr; } } @@ -88,14 +88,14 @@ bool SQLite::DoInit(const ReaderInfo& info, int arg_num_fields, const threading: else query = it->second; - if ( checkError(sqlite3_open_v2(fullpath.c_str(), &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_NOMUTEX, NULL)) ) + if ( checkError(sqlite3_open_v2(fullpath.c_str(), &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_NOMUTEX, nullptr)) ) return false; num_fields = arg_num_fields; fields = arg_fields; // create the prepared select statement that we will re-use forever... - if ( checkError(sqlite3_prepare_v2(db, query.c_str(), query.size() + 1, &st, NULL)) ) { + if ( checkError(sqlite3_prepare_v2(db, query.c_str(), query.size() + 1, &st, nullptr)) ) { return false; } @@ -159,7 +159,7 @@ Value* SQLite::EntryToVal(sqlite3_stmt* st, const threading::Field* field, int p if ( subpos != -1 ) { const char* text = (const char*)sqlite3_column_text(st, subpos); - if ( text == 0 ) + if ( text == nullptr ) Error("Port protocol definition did not contain text"); else { std::string s(text, sqlite3_column_bytes(st, subpos)); diff --git a/src/iosource/Component.cc b/src/iosource/Component.cc index 3aa7610e0b..1fd1815a94 100644 --- a/src/iosource/Component.cc +++ b/src/iosource/Component.cc @@ -23,8 +23,8 @@ PktSrcComponent::PktSrcComponent(const std::string& arg_name, const std::string& const std::vector& PktSrcComponent::Prefixes() const { return prefixes; } bool PktSrcComponent::HandlesPrefix(const std::string& prefix) const { - for ( std::vector::const_iterator i = prefixes.begin(); i != prefixes.end(); i++ ) { - if ( *i == prefix ) + for ( const auto& pfx : prefixes ) { + if ( pfx == prefix ) return true; } @@ -42,11 +42,11 @@ void PktSrcComponent::DoDescribe(ODesc* d) const { std::string prefs; - for ( std::vector::const_iterator i = prefixes.begin(); i != prefixes.end(); i++ ) { + for ( const auto& pfx : prefixes ) { if ( prefs.size() ) prefs += ", "; - prefs += '"' + *i + '"'; + prefs += '"' + pfx + '"'; } d->Add("interface prefix"); @@ -80,8 +80,8 @@ PktDumperComponent::factory_callback PktDumperComponent::Factory() const { retur const std::vector& PktDumperComponent::Prefixes() const { return prefixes; } bool PktDumperComponent::HandlesPrefix(const std::string& prefix) const { - for ( std::vector::const_iterator i = prefixes.begin(); i != prefixes.end(); i++ ) { - if ( *i == prefix ) + for ( const auto& pfx : prefixes ) { + if ( pfx == prefix ) return true; } @@ -93,11 +93,11 @@ void PktDumperComponent::DoDescribe(ODesc* d) const { std::string prefs; - for ( std::vector::const_iterator i = prefixes.begin(); i != prefixes.end(); i++ ) { + for ( const auto& pfx : prefixes ) { if ( prefs.size() ) prefs += ", "; - prefs += '"' + *i + '"'; + prefs += '"' + pfx + '"'; } d->Add("dumper prefix"); diff --git a/src/iosource/Manager.cc b/src/iosource/Manager.cc index 8e0f4d106d..96750f7051 100644 --- a/src/iosource/Manager.cc +++ b/src/iosource/Manager.cc @@ -64,9 +64,9 @@ Manager::~Manager() { sources.clear(); - for ( PktDumperList::iterator i = pkt_dumpers.begin(); i != pkt_dumpers.end(); ++i ) { - (*i)->Done(); - delete *i; + for ( PktDumper* dumper : pkt_dumpers ) { + dumper->Done(); + delete dumper; } pkt_dumpers.clear(); @@ -189,7 +189,7 @@ void Manager::Poll(ReadySources* ready, double timeout, IOSource* timeout_src) { struct timespec kqueue_timeout; ConvertTimeout(timeout, kqueue_timeout); - int ret = kevent(event_queue, NULL, 0, events.data(), events.size(), &kqueue_timeout); + int ret = kevent(event_queue, nullptr, 0, events.data(), events.size(), &kqueue_timeout); if ( ret == -1 ) { // Ignore interrupts since we may catch one during shutdown and we don't want the // error to get printed. @@ -249,18 +249,18 @@ bool Manager::RegisterFd(int fd, IOSource* src, int flags) { if ( (flags & IOSource::READ) != 0 ) { if ( fd_map.count(fd) == 0 ) { new_events.push_back({}); - EV_SET(&(new_events.back()), fd, EVFILT_READ, EV_ADD, 0, 0, NULL); + EV_SET(&(new_events.back()), fd, EVFILT_READ, EV_ADD, 0, 0, nullptr); } } if ( (flags & IOSource::WRITE) != 0 ) { if ( write_fd_map.count(fd) == 0 ) { new_events.push_back({}); - EV_SET(&(new_events.back()), fd, EVFILT_WRITE, EV_ADD, 0, 0, NULL); + EV_SET(&(new_events.back()), fd, EVFILT_WRITE, EV_ADD, 0, 0, nullptr); } } if ( ! new_events.empty() ) { - int ret = kevent(event_queue, new_events.data(), new_events.size(), NULL, 0, NULL); + int ret = kevent(event_queue, new_events.data(), new_events.size(), nullptr, 0, nullptr); if ( ret != -1 ) { DBG_LOG(DBG_MAINLOOP, "Registered fd %d from %s", fd, src->Tag()); for ( const auto& a : new_events ) @@ -289,18 +289,18 @@ bool Manager::UnregisterFd(int fd, IOSource* src, int flags) { if ( (flags & IOSource::READ) != 0 ) { if ( fd_map.count(fd) != 0 ) { new_events.push_back({}); - EV_SET(&(new_events.back()), fd, EVFILT_READ, EV_DELETE, 0, 0, NULL); + EV_SET(&(new_events.back()), fd, EVFILT_READ, EV_DELETE, 0, 0, nullptr); } } if ( (flags & IOSource::WRITE) != 0 ) { if ( write_fd_map.count(fd) != 0 ) { new_events.push_back({}); - EV_SET(&(new_events.back()), fd, EVFILT_WRITE, EV_DELETE, 0, 0, NULL); + EV_SET(&(new_events.back()), fd, EVFILT_WRITE, EV_DELETE, 0, 0, nullptr); } } if ( ! new_events.empty() ) { - int ret = kevent(event_queue, new_events.data(), new_events.size(), NULL, 0, NULL); + int ret = kevent(event_queue, new_events.data(), new_events.size(), nullptr, 0, nullptr); if ( ret != -1 ) { DBG_LOG(DBG_MAINLOOP, "Unregistered fd %d from %s", fd, src->Tag()); for ( const auto& a : new_events ) diff --git a/src/logging/Manager.cc b/src/logging/Manager.cc index e4a2b879b4..40b9bc4118 100644 --- a/src/logging/Manager.cc +++ b/src/logging/Manager.cc @@ -64,7 +64,7 @@ using DelayInfoPtr = std::shared_ptr; class LogDelayTokenVal : public OpaqueVal { public: explicit LogDelayTokenVal(DelayTokenType token) : OpaqueVal(zeek::detail::log_delay_token_type), token(token) {} - virtual ~LogDelayTokenVal() = default; + ~LogDelayTokenVal() override {}; ValPtr DoClone(CloneState* state) override; @@ -108,8 +108,8 @@ class DelayInfo { public: static const DelayInfoPtr nil; - explicit DelayInfo(const WriteContext& ctx, const zeek::ValPtr token_val, double expire_time) - : ctx(ctx), token_val(token_val), expire_time(expire_time) {} + explicit DelayInfo(WriteContext ctx, const zeek::ValPtr token_val, double expire_time) + : ctx(std::move(ctx)), token_val(token_val), expire_time(expire_time) {} // No copy or assignment of DelayInfo itself, should // always be managed through a shared pointer. @@ -351,9 +351,7 @@ Manager::Filter::~Filter() { Manager::Stream::~Stream() { Unref(columns); - for ( WriterMap::iterator i = writers.begin(); i != writers.end(); i++ ) { - WriterInfo* winfo = i->second; - + for ( auto& [_, winfo] : writers ) { if ( winfo->rotation_timer ) zeek::detail::timer_mgr->Cancel(winfo->rotation_timer); @@ -363,8 +361,8 @@ Manager::Stream::~Stream() { delete winfo; } - for ( list::iterator f = filters.begin(); f != filters.end(); ++f ) - delete *f; + for ( Filter* f : filters ) + delete f; if ( delay_timer ) zeek::detail::timer_mgr->Cancel(delay_timer); @@ -491,8 +489,8 @@ Manager::Manager() } Manager::~Manager() { - for ( vector::iterator s = streams.begin(); s != streams.end(); ++s ) - delete *s; + for ( Stream* s : streams ) + delete s; } void Manager::InitPostScript() { @@ -524,13 +522,11 @@ Manager::Stream* Manager::FindStream(EnumVal* id) { } Manager::WriterInfo* Manager::FindWriter(WriterFrontend* writer) { - for ( vector::iterator s = streams.begin(); s != streams.end(); ++s ) { - if ( ! *s ) + for ( Stream* s : streams ) { + if ( ! s ) continue; - for ( Stream::WriterMap::iterator i = (*s)->writers.begin(); i != (*s)->writers.end(); i++ ) { - WriterInfo* winfo = i->second; - + for ( const auto& [_, winfo] : s->writers ) { if ( winfo->writer == writer ) return winfo; } @@ -563,16 +559,16 @@ bool Manager::CheckFilterWriterConflict(const WriterInfo* winfo, const Filter* f void Manager::RemoveDisabledWriters(Stream* stream) { list disabled; - for ( Stream::WriterMap::iterator j = stream->writers.begin(); j != stream->writers.end(); j++ ) { - if ( j->second->writer->Disabled() ) { - j->second->writer->Stop(); - delete j->second; - disabled.push_back(j->first); + for ( const auto& [index, winfo] : stream->writers ) { + if ( winfo->writer->Disabled() ) { + winfo->writer->Stop(); + delete winfo; + disabled.push_back(index); } } - for ( list::iterator j = disabled.begin(); j != disabled.end(); j++ ) - stream->writers.erase(*j); + for ( const auto& index : disabled ) + stream->writers.erase(index); } bool Manager::CreateStream(EnumVal* id, RecordVal* sval) { @@ -681,9 +677,7 @@ bool Manager::RemoveStream(unsigned int idx) { if ( ! stream ) return false; - for ( Stream::WriterMap::iterator i = stream->writers.begin(); i != stream->writers.end(); i++ ) { - WriterInfo* winfo = i->second; - + for ( const auto& [_, winfo] : stream->writers ) { DBG_LOG(DBG_LOGGING, "Removed writer '%s' from stream '%s'", winfo->writer->Name(), stream->name.c_str()); winfo->writer->Stop(); @@ -1550,9 +1544,9 @@ detail::LogRecord Manager::RecordToLogRecord(const Stream* stream, Filter* filte // potentially be nested inside other records. list& indices = filter->indices[i]; - for ( list::iterator j = indices.begin(); j != indices.end(); ++j ) { + for ( int index : indices ) { auto vr = val->AsRecord(); - val = vr->RawOptField(*j); + val = vr->RawOptField(index); if ( ! val ) { // Value, or any of its parents, is not set. @@ -1560,7 +1554,7 @@ detail::LogRecord Manager::RecordToLogRecord(const Stream* stream, Filter* filte break; } - vt = cast_intrusive(vr->GetType())->GetFieldType(*j).get(); + vt = cast_intrusive(vr->GetType())->GetFieldType(index).get(); } if ( val ) @@ -1856,21 +1850,19 @@ bool Manager::WriteFromRemote(EnumVal* id, EnumVal* writer, const string& path, void Manager::SendAllWritersTo(const broker::endpoint_info& ei) { auto et = id::find_type("Log::Writer")->AsEnumType(); - for ( vector::iterator s = streams.begin(); s != streams.end(); ++s ) { - Stream* stream = (*s); - + for ( Stream* stream : streams ) { if ( ! (stream && stream->enable_remote) ) continue; - for ( Stream::WriterMap::iterator i = stream->writers.begin(); i != stream->writers.end(); i++ ) { - WriterFrontend* writer = i->second->writer; - const auto& writer_val = et->GetEnumVal(i->first.first); + for ( const auto& [index, winfo] : stream->writers ) { + WriterFrontend* writer = winfo->writer; + const auto& writer_val = et->GetEnumVal(index.first); std::vector fields(writer->GetFields().size()); for ( size_t i = 0; i < writer->GetFields().size(); i++ ) fields[i] = &writer->GetFields()[i]; - broker_mgr->PublishLogCreate((*s)->id, writer_val.get(), *i->second->info, fields.size(), fields.data(), + broker_mgr->PublishLogCreate(stream->id, writer_val.get(), *(winfo->info), fields.size(), fields.data(), ei); } } @@ -1881,8 +1873,8 @@ bool Manager::SetBuf(EnumVal* id, bool enabled) { if ( ! stream ) return false; - for ( Stream::WriterMap::iterator i = stream->writers.begin(); i != stream->writers.end(); i++ ) - i->second->writer->SetBuf(enabled); + for ( const auto& [_, winfo] : stream->writers ) + winfo->writer->SetBuf(enabled); RemoveDisabledWriters(stream); @@ -1897,8 +1889,8 @@ bool Manager::Flush(EnumVal* id) { if ( ! stream->enabled ) return true; - for ( Stream::WriterMap::iterator i = stream->writers.begin(); i != stream->writers.end(); i++ ) - i->second->writer->Flush(run_state::network_time); + for ( const auto& [_, winfo] : stream->writers ) + winfo->writer->Flush(run_state::network_time); RemoveDisabledWriters(stream); @@ -1906,12 +1898,12 @@ bool Manager::Flush(EnumVal* id) { } void Manager::Terminate() { - for ( vector::iterator s = streams.begin(); s != streams.end(); ++s ) { - if ( ! *s ) + for ( Stream* s : streams ) { + if ( ! s ) continue; - for ( Stream::WriterMap::iterator i = (*s)->writers.begin(); i != (*s)->writers.end(); i++ ) - i->second->writer->Stop(); + for ( const auto& [_, winfo] : s->writers ) + winfo->writer->Stop(); } } diff --git a/src/logging/WriterBackend.cc b/src/logging/WriterBackend.cc index 46750cd7a4..70ab8591b4 100644 --- a/src/logging/WriterBackend.cc +++ b/src/logging/WriterBackend.cc @@ -61,8 +61,8 @@ public: broker::data WriterBackend::WriterInfo::ToBroker() const { auto t = broker::table(); - for ( config_map::const_iterator i = config.begin(); i != config.end(); ++i ) { - t.emplace(std::string{i->first}, std::string{i->second}); + for ( const auto& [key, value] : config ) { + t.emplace(std::string{key}, std::string{value}); } auto bppf = post_proc_func ? post_proc_func : ""; @@ -185,12 +185,12 @@ bool WriterBackend::Write(int arg_num_fields, zeek::Span reco } // Double-check all the types match. - for ( size_t j = 0; j < records.size(); j++ ) { + for ( const auto& record : records ) { for ( int i = 0; i < num_fields; ++i ) { - if ( records[j][i].type != fields[i]->type ) { + if ( record[i].type != fields[i]->type ) { #ifdef DEBUG const char* msg = Fmt("Field #%d type doesn't match in WriterBackend::Write() (%d vs. %d)", i, - records[j][i].type, fields[i]->type); + record[i].type, fields[i]->type); Debug(DBG_LOGGING, msg); #endif DisableFrontend(); @@ -212,10 +212,9 @@ bool WriterBackend::Write(int arg_num_fields, zeek::Span reco std::vector valps; valps.reserve(num_fields); - for ( size_t j = 0; j < records.size(); j++ ) { - auto& write_vals = records[j]; + for ( auto& record : records ) { for ( int f = 0; f < num_fields; f++ ) - valps.emplace_back(&write_vals[f]); + valps.emplace_back(&record[f]); success = DoWrite(num_fields, fields, &valps[0]); diff --git a/src/logging/writers/ascii/Ascii.cc b/src/logging/writers/ascii/Ascii.cc index 5d96786b90..3d43964422 100644 --- a/src/logging/writers/ascii/Ascii.cc +++ b/src/logging/writers/ascii/Ascii.cc @@ -255,11 +255,11 @@ bool Ascii::InitFilterOptions() { const WriterInfo& info = Info(); // Set per-filter configuration options. - for ( WriterInfo::config_map::const_iterator i = info.config.begin(); i != info.config.end(); ++i ) { - if ( strcmp(i->first, "tsv") == 0 ) { - if ( strcmp(i->second, "T") == 0 ) + for ( const auto& [key, value] : info.config ) { + if ( strcmp(key, "tsv") == 0 ) { + if ( strcmp(value, "T") == 0 ) tsv = true; - else if ( strcmp(i->second, "F") == 0 ) + else if ( strcmp(value, "F") == 0 ) tsv = false; else { Error("invalid value for 'tsv', must be a string and either \"T\" or \"F\""); @@ -267,18 +267,18 @@ bool Ascii::InitFilterOptions() { } } - else if ( strcmp(i->first, "gzip_level") == 0 ) { - gzip_level = atoi(i->second); + else if ( strcmp(key, "gzip_level") == 0 ) { + gzip_level = atoi(value); if ( gzip_level < 0 || gzip_level > 9 ) { Error("invalid value for 'gzip_level', must be a number between 0 and 9."); return false; } } - else if ( strcmp(i->first, "use_json") == 0 ) { - if ( strcmp(i->second, "T") == 0 ) + else if ( strcmp(key, "use_json") == 0 ) { + if ( strcmp(value, "T") == 0 ) use_json = true; - else if ( strcmp(i->second, "F") == 0 ) + else if ( strcmp(value, "F") == 0 ) use_json = false; else { Error("invalid value for 'use_json', must be a string and either \"T\" or \"F\""); @@ -286,10 +286,10 @@ bool Ascii::InitFilterOptions() { } } - else if ( strcmp(i->first, "enable_utf_8") == 0 ) { - if ( strcmp(i->second, "T") == 0 ) + else if ( strcmp(key, "enable_utf_8") == 0 ) { + if ( strcmp(value, "T") == 0 ) enable_utf_8 = true; - else if ( strcmp(i->second, "F") == 0 ) + else if ( strcmp(value, "F") == 0 ) enable_utf_8 = false; else { Error("invalid value for 'enable_utf_8', must be a string and either \"T\" or \"F\""); @@ -297,10 +297,10 @@ bool Ascii::InitFilterOptions() { } } - else if ( strcmp(i->first, "output_to_stdout") == 0 ) { - if ( strcmp(i->second, "T") == 0 ) + else if ( strcmp(key, "output_to_stdout") == 0 ) { + if ( strcmp(value, "T") == 0 ) output_to_stdout = true; - else if ( strcmp(i->second, "F") == 0 ) + else if ( strcmp(value, "F") == 0 ) output_to_stdout = false; else { Error( @@ -310,28 +310,28 @@ bool Ascii::InitFilterOptions() { } } - else if ( strcmp(i->first, "separator") == 0 ) - separator.assign(i->second); + else if ( strcmp(key, "separator") == 0 ) + separator.assign(value); - else if ( strcmp(i->first, "set_separator") == 0 ) - set_separator.assign(i->second); + else if ( strcmp(key, "set_separator") == 0 ) + set_separator.assign(value); - else if ( strcmp(i->first, "empty_field") == 0 ) - empty_field.assign(i->second); + else if ( strcmp(key, "empty_field") == 0 ) + empty_field.assign(value); - else if ( strcmp(i->first, "unset_field") == 0 ) - unset_field.assign(i->second); + else if ( strcmp(key, "unset_field") == 0 ) + unset_field.assign(value); - else if ( strcmp(i->first, "meta_prefix") == 0 ) - meta_prefix.assign(i->second); + else if ( strcmp(key, "meta_prefix") == 0 ) + meta_prefix.assign(value); - else if ( strcmp(i->first, "json_timestamps") == 0 ) - json_timestamps.assign(i->second); + else if ( strcmp(key, "json_timestamps") == 0 ) + json_timestamps.assign(value); - else if ( strcmp(i->first, "json_include_unset_fields") == 0 ) { - if ( strcmp(i->second, "T") == 0 ) + else if ( strcmp(key, "json_include_unset_fields") == 0 ) { + if ( strcmp(value, "T") == 0 ) json_include_unset_fields = true; - else if ( strcmp(i->second, "F") == 0 ) + else if ( strcmp(value, "F") == 0 ) json_include_unset_fields = false; else { Error( @@ -341,8 +341,8 @@ bool Ascii::InitFilterOptions() { } } - else if ( strcmp(i->first, "gzip_file_extension") == 0 ) - gzip_file_extension.assign(i->second); + else if ( strcmp(key, "gzip_file_extension") == 0 ) + gzip_file_extension.assign(value); } if ( ! InitFormatter() ) diff --git a/src/logging/writers/none/None.cc b/src/logging/writers/none/None.cc index 73affacb9d..e2ba96aae0 100644 --- a/src/logging/writers/none/None.cc +++ b/src/logging/writers/none/None.cc @@ -20,13 +20,13 @@ bool None::DoInit(const WriterInfo& info, int num_fields, const threading::Field std::vector> keys; - for ( WriterInfo::config_map::const_iterator i = info.config.begin(); i != info.config.end(); i++ ) - keys.emplace_back(i->first, i->second); + for ( const auto& [key, value] : info.config ) + keys.emplace_back(key, value); std::sort(keys.begin(), keys.end()); - for ( std::vector>::const_iterator i = keys.begin(); i != keys.end(); i++ ) - std::cout << " config[" << (*i).first << "] = " << (*i).second << "\n"; + for ( const auto& [key, value] : keys ) + std::cout << " config[" << key << "] = " << value << "\n"; for ( int i = 0; i < num_fields; i++ ) { const threading::Field* field = fields[i]; diff --git a/src/logging/writers/sqlite/SQLite.cc b/src/logging/writers/sqlite/SQLite.cc index 02871c1cfd..d397c2d086 100644 --- a/src/logging/writers/sqlite/SQLite.cc +++ b/src/logging/writers/sqlite/SQLite.cc @@ -32,12 +32,12 @@ SQLite::SQLite(WriterFrontend* frontend) : WriterBackend(frontend), fields(), nu } SQLite::~SQLite() { - if ( db != 0 ) { + if ( db != nullptr ) { sqlite3_finalize(st); if ( ! sqlite3_close(db) ) Error("Sqlite could not close connection"); - db = 0; + db = nullptr; } delete io; @@ -126,7 +126,7 @@ bool SQLite::DoInit(const WriterInfo& info, int arg_num_fields, const Field* con tablename = it->second; if ( checkError(sqlite3_open_v2(fullpath.string().c_str(), &db, - SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX, NULL)) ) + SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX, nullptr)) ) return false; char* errorMsg = nullptr; @@ -134,16 +134,16 @@ bool SQLite::DoInit(const WriterInfo& info, int arg_num_fields, const Field* con switch ( synchronous ) { case BifEnum::LogSQLite::SQLiteSynchronous::SQLITE_SYNCHRONOUS_DEFAULT: res = SQLITE_OK; break; case BifEnum::LogSQLite::SQLiteSynchronous::SQLITE_SYNCHRONOUS_OFF: - res = sqlite3_exec(db, "PRAGMA synchronous=OFF;", NULL, NULL, &errorMsg); + res = sqlite3_exec(db, "PRAGMA synchronous=OFF;", nullptr, nullptr, &errorMsg); break; case BifEnum::LogSQLite::SQLiteSynchronous::SQLITE_SYNCHRONOUS_NORMAL: - res = sqlite3_exec(db, "PRAGMA synchronous=NORMAL;", NULL, NULL, &errorMsg); + res = sqlite3_exec(db, "PRAGMA synchronous=NORMAL;", nullptr, nullptr, &errorMsg); break; case BifEnum::LogSQLite::SQLiteSynchronous::SQLITE_SYNCHRONOUS_FULL: - res = sqlite3_exec(db, "PRAGMA synchronous=FULL;", NULL, NULL, &errorMsg); + res = sqlite3_exec(db, "PRAGMA synchronous=FULL;", nullptr, nullptr, &errorMsg); break; case BifEnum::LogSQLite::SQLiteSynchronous::SQLITE_SYNCHRONOUS_EXTRA: - res = sqlite3_exec(db, "PRAGMA synchronous=EXTRA;", NULL, NULL, &errorMsg); + res = sqlite3_exec(db, "PRAGMA synchronous=EXTRA;", nullptr, nullptr, &errorMsg); break; default: Error("Invalid LogSQLite::synchronous enum"); return false; } @@ -157,22 +157,22 @@ bool SQLite::DoInit(const WriterInfo& info, int arg_num_fields, const Field* con switch ( journal_mode ) { case BifEnum::LogSQLite::SQLiteJournalMode::SQLITE_JOURNAL_MODE_DEFAULT: res = SQLITE_OK; break; case BifEnum::LogSQLite::SQLiteJournalMode::SQLITE_JOURNAL_MODE_DELETE: - res = sqlite3_exec(db, "PRAGMA journal_mode=DELETE;", NULL, NULL, &errorMsg); + res = sqlite3_exec(db, "PRAGMA journal_mode=DELETE;", nullptr, nullptr, &errorMsg); break; case BifEnum::LogSQLite::SQLiteJournalMode::SQLITE_JOURNAL_MODE_TRUNCATE: - res = sqlite3_exec(db, "PRAGMA journal_mode=TRUNCATE;", NULL, NULL, &errorMsg); + res = sqlite3_exec(db, "PRAGMA journal_mode=TRUNCATE;", nullptr, nullptr, &errorMsg); break; case BifEnum::LogSQLite::SQLiteJournalMode::SQLITE_JOURNAL_MODE_PERSIST: - res = sqlite3_exec(db, "PRAGMA journal_mode=PERSIST;", NULL, NULL, &errorMsg); + res = sqlite3_exec(db, "PRAGMA journal_mode=PERSIST;", nullptr, nullptr, &errorMsg); break; case BifEnum::LogSQLite::SQLiteJournalMode::SQLITE_JOURNAL_MODE_MEMORY: - res = sqlite3_exec(db, "PRAGMA journal_mode=MEMORY;", NULL, NULL, &errorMsg); + res = sqlite3_exec(db, "PRAGMA journal_mode=MEMORY;", nullptr, nullptr, &errorMsg); break; case BifEnum::LogSQLite::SQLiteJournalMode::SQLITE_JOURNAL_MODE_WAL: - res = sqlite3_exec(db, "PRAGMA journal_mode=WAL;", NULL, NULL, &errorMsg); + res = sqlite3_exec(db, "PRAGMA journal_mode=WAL;", nullptr, nullptr, &errorMsg); break; case BifEnum::LogSQLite::SQLiteJournalMode::SQLITE_JOURNAL_MODE_OFF: - res = sqlite3_exec(db, "PRAGMA journal_mode=OFF;", NULL, NULL, &errorMsg); + res = sqlite3_exec(db, "PRAGMA journal_mode=OFF;", nullptr, nullptr, &errorMsg); break; default: Error("Invalid LogSQLite::journal_mode enum"); return false; } @@ -194,7 +194,7 @@ bool SQLite::DoInit(const WriterInfo& info, int arg_num_fields, const Field* con // sadly sqlite3 has no other method for escaping stuff. That I know of. char* fieldname = sqlite3_mprintf("%Q", fields[i]->name); - if ( fieldname == 0 ) { + if ( fieldname == nullptr ) { InternalError("Could not malloc memory"); return false; } @@ -219,7 +219,7 @@ bool SQLite::DoInit(const WriterInfo& info, int arg_num_fields, const Field* con create += "\n);"; errorMsg = nullptr; - res = sqlite3_exec(db, create.c_str(), NULL, NULL, &errorMsg); + res = sqlite3_exec(db, create.c_str(), nullptr, nullptr, &errorMsg); if ( res != SQLITE_OK ) { Error(Fmt("Error executing table creation statement: %s", errorMsg)); sqlite3_free(errorMsg); @@ -243,7 +243,7 @@ bool SQLite::DoInit(const WriterInfo& info, int arg_num_fields, const Field* con insert += "?"; char* fieldname = sqlite3_mprintf("%Q", fields[i]->name); - if ( fieldname == 0 ) { + if ( fieldname == nullptr ) { InternalError("Could not malloc memory"); return false; } @@ -257,7 +257,7 @@ bool SQLite::DoInit(const WriterInfo& info, int arg_num_fields, const Field* con insert = names + insert; - if ( checkError(sqlite3_prepare_v2(db, insert.c_str(), insert.size() + 1, &st, NULL)) ) + if ( checkError(sqlite3_prepare_v2(db, insert.c_str(), insert.size() + 1, &st, nullptr)) ) return false; return true; diff --git a/src/packet_analysis/protocol/gtpv1/gtpv1-analyzer.pac b/src/packet_analysis/protocol/gtpv1/gtpv1-analyzer.pac index eead7bbdc0..c4b4cc8499 100644 --- a/src/packet_analysis/protocol/gtpv1/gtpv1-analyzer.pac +++ b/src/packet_analysis/protocol/gtpv1/gtpv1-analyzer.pac @@ -244,10 +244,8 @@ void CreatePDP_Request(const ZeekPacketAnalyzer& a, zeek::Connection* c, const G bool second_nsapi = false; bool second_gsn_addr = false; - for ( size_t i = 0; i < v->size(); ++i ) + for ( InformationElement* ie : *v ) { - const InformationElement* ie = (*v)[i]; - switch ( ie->type() ) { case GTPv1::TYPE_IMSI: rv->Assign(0, BuildIMSI(ie)); @@ -322,7 +320,7 @@ void CreatePDP_Request(const ZeekPacketAnalyzer& a, zeek::Connection* c, const G rv->Assign(21, BuildPrivateExt(ie)); break; default: - a->Weird("gtp_invalid_info_element", nullptr, zeek::util::fmt("%d", (*v)[i]->type())); + a->Weird("gtp_invalid_info_element", nullptr, zeek::util::fmt("%d", ie->type())); break; } } @@ -342,10 +340,8 @@ void CreatePDP_Response(const ZeekPacketAnalyzer& a, zeek::Connection* c, const bool second_gsn_addr = false; - for ( size_t i = 0; i < v->size(); ++i ) + for ( InformationElement* ie : *v ) { - const InformationElement* ie = (*v)[i]; - switch ( ie->type() ) { case GTPv1::TYPE_CAUSE: rv->Assign(0, BuildCause(ie)); @@ -390,7 +386,7 @@ void CreatePDP_Response(const ZeekPacketAnalyzer& a, zeek::Connection* c, const rv->Assign(12, BuildPrivateExt(ie)); break; default: - a->Weird("gtp_invalid_info_element", nullptr, zeek::util::fmt("%d", (*v)[i]->type())); + a->Weird("gtp_invalid_info_element", nullptr, zeek::util::fmt("%d", ie->type())); break; } } @@ -410,10 +406,8 @@ void UpdatePDP_Request(const ZeekPacketAnalyzer& a, zeek::Connection* c, const G bool second_gsn_addr = false; - for ( size_t i = 0; i < v->size(); ++i ) + for ( InformationElement* ie : *v ) { - const InformationElement* ie = (*v)[i]; - switch ( ie->type() ) { case GTPv1::TYPE_IMSI: rv->Assign(0, BuildIMSI(ie)); @@ -467,7 +461,7 @@ void UpdatePDP_Request(const ZeekPacketAnalyzer& a, zeek::Connection* c, const G rv->Assign(15, BuildEndUserAddr(ie)); break; default: - a->Weird("gtp_invalid_info_element", nullptr, zeek::util::fmt("%d", (*v)[i]->type())); + a->Weird("gtp_invalid_info_element", nullptr, zeek::util::fmt("%d", ie->type())); break; } } @@ -487,10 +481,8 @@ void UpdatePDP_Response(const ZeekPacketAnalyzer& a, zeek::Connection* c, const bool second_gsn_addr = false; - for ( size_t i = 0; i < v->size(); ++i ) + for ( InformationElement* ie : *v ) { - const InformationElement* ie = (*v)[i]; - switch ( ie->type() ) { case GTPv1::TYPE_CAUSE: rv->Assign(0, BuildCause(ie)); @@ -526,7 +518,7 @@ void UpdatePDP_Response(const ZeekPacketAnalyzer& a, zeek::Connection* c, const rv->Assign(9, BuildPrivateExt(ie)); break; default: - a->Weird("gtp_invalid_info_element", nullptr, zeek::util::fmt("%d", (*v)[i]->type())); + a->Weird("gtp_invalid_info_element", nullptr, zeek::util::fmt("%d", ie->type())); break; } } @@ -537,17 +529,15 @@ void UpdatePDP_Response(const ZeekPacketAnalyzer& a, zeek::Connection* c, const void DeletePDP_Request(const ZeekPacketAnalyzer& a, zeek::Connection* c, const GTPv1_Header* pdu) { if ( ! ::gtpv1_delete_pdp_ctx_request ) - return; + return; auto rv = zeek::make_intrusive( zeek::BifType::Record::gtp_delete_pdp_ctx_request_elements); const vector * v = pdu->delete_pdp_ctx_request(); - for ( size_t i = 0; i < v->size(); ++i ) + for ( InformationElement* ie : *v ) { - const InformationElement* ie = (*v)[i]; - switch ( ie->type() ) { case GTPv1::TYPE_TEARDOWN_IND: rv->Assign(0, BuildTeardownInd(ie)); @@ -559,7 +549,7 @@ void DeletePDP_Request(const ZeekPacketAnalyzer& a, zeek::Connection* c, const G rv->Assign(2, BuildPrivateExt(ie)); break; default: - a->Weird("gtp_invalid_info_element", nullptr, zeek::util::fmt("%d", (*v)[i]->type())); + a->Weird("gtp_invalid_info_element", nullptr, zeek::util::fmt("%d", ie->type())); break; } } @@ -570,17 +560,15 @@ void DeletePDP_Request(const ZeekPacketAnalyzer& a, zeek::Connection* c, const G void DeletePDP_Response(const ZeekPacketAnalyzer& a, zeek::Connection* c, const GTPv1_Header* pdu) { if ( ! ::gtpv1_delete_pdp_ctx_response ) - return; + return; auto rv = zeek::make_intrusive( zeek::BifType::Record::gtp_delete_pdp_ctx_response_elements); const vector * v = pdu->delete_pdp_ctx_response(); - for ( size_t i = 0; i < v->size(); ++i ) + for ( InformationElement* ie : *v ) { - const InformationElement* ie = (*v)[i]; - switch ( ie->type() ) { case GTPv1::TYPE_CAUSE: rv->Assign(0, BuildCause(ie)); @@ -589,7 +577,7 @@ void DeletePDP_Response(const ZeekPacketAnalyzer& a, zeek::Connection* c, const rv->Assign(1, BuildPrivateExt(ie)); break; default: - a->Weird("gtp_invalid_info_element", nullptr, zeek::util::fmt("%d", (*v)[i]->type())); + a->Weird("gtp_invalid_info_element", nullptr, zeek::util::fmt("%d", ie->type())); break; } } diff --git a/src/packet_analysis/protocol/tcp/Stats.cc b/src/packet_analysis/protocol/tcp/Stats.cc index a19d0ca09d..180d79396d 100644 --- a/src/packet_analysis/protocol/tcp/Stats.cc +++ b/src/packet_analysis/protocol/tcp/Stats.cc @@ -7,7 +7,7 @@ namespace zeek::packet_analysis::TCP { TCPStateStats::TCPStateStats() { - for ( int i = 0; i < analyzer::tcp::TCP_ENDPOINT_RESET + 1; ++i ) + for ( int i = 0; i < analyzer::tcp::TCP_ENDPOINT_RESET + 1; ++i ) // NOLINT for ( int j = 0; j < analyzer::tcp::TCP_ENDPOINT_RESET + 1; ++j ) state_cnt[i][j] = 0; } diff --git a/src/packet_analysis/protocol/tcp/TCPSessionAdapter.cc b/src/packet_analysis/protocol/tcp/TCPSessionAdapter.cc index 714782eb8e..7722b5198d 100644 --- a/src/packet_analysis/protocol/tcp/TCPSessionAdapter.cc +++ b/src/packet_analysis/protocol/tcp/TCPSessionAdapter.cc @@ -43,8 +43,8 @@ TCPSessionAdapter::TCPSessionAdapter(Connection* conn) : packet_analysis::IP::Se } TCPSessionAdapter::~TCPSessionAdapter() { - LOOP_OVER_GIVEN_CHILDREN(i, packet_children) - delete *i; + for ( Analyzer* a : packet_children ) + delete a; delete orig; delete resp; @@ -52,8 +52,8 @@ TCPSessionAdapter::~TCPSessionAdapter() { void TCPSessionAdapter::Init() { Analyzer::Init(); - LOOP_OVER_GIVEN_CHILDREN(i, packet_children) - (*i)->Init(); + for ( Analyzer* a : packet_children ) + a->Init(); } void TCPSessionAdapter::Done() { @@ -62,8 +62,8 @@ void TCPSessionAdapter::Done() { if ( run_state::terminating && connection_pending && is_active && ! BothClosed() ) Event(connection_pending); - LOOP_OVER_GIVEN_CHILDREN(i, packet_children) - (*i)->Done(); + for ( Analyzer* a : packet_children ) + a->Done(); orig->Done(); resp->Done(); @@ -644,9 +644,8 @@ analyzer::Analyzer* TCPSessionAdapter::FindChild(analyzer::ID arg_id) { if ( child ) return child; - LOOP_OVER_GIVEN_CHILDREN(i, packet_children) { - analyzer::Analyzer* child = (*i)->FindChild(arg_id); - if ( child ) + for ( Analyzer* a : packet_children ) { + if ( analyzer::Analyzer* child = a->FindChild(arg_id) ) return child; } @@ -659,9 +658,8 @@ analyzer::Analyzer* TCPSessionAdapter::FindChild(zeek::Tag arg_tag) { if ( child ) return child; - LOOP_OVER_GIVEN_CHILDREN(i, packet_children) { - analyzer::Analyzer* child = (*i)->FindChild(arg_tag); - if ( child ) + for ( Analyzer* a : packet_children ) { + if ( analyzer::Analyzer* child = a->FindChild(arg_tag) ) return child; } @@ -1046,8 +1044,8 @@ void TCPSessionAdapter::UpdateConnVal(RecordVal* conn_val) { Analyzer::UpdateConnVal(conn_val); // Have to do packet_children ourselves. - LOOP_OVER_GIVEN_CHILDREN(i, packet_children) - (*i)->UpdateConnVal(conn_val); + for ( Analyzer* a : packet_children ) + a->UpdateConnVal(conn_val); } void TCPSessionAdapter::AttemptTimer(double /* t */) { @@ -1182,11 +1180,12 @@ FilePtr TCPSessionAdapter::GetContentsFile(unsigned int direction) const { void TCPSessionAdapter::ConnectionClosed(analyzer::tcp::TCP_Endpoint* endpoint, analyzer::tcp::TCP_Endpoint* peer, bool gen_event) { const analyzer::analyzer_list& children(GetChildren()); - LOOP_OVER_CONST_CHILDREN(i) - // Using this type of cast here is nasty (will crash if - // we inadvertently have a child analyzer that's not a - // TCP_ApplicationAnalyzer), but we have to ... - static_cast(*i)->ConnectionClosed(endpoint, peer, gen_event); + + for ( Analyzer* a : children ) + // Using this type of cast here is nasty (will crash if + // we inadvertently have a child analyzer that's not a + // TCP_ApplicationAnalyzer), but we have to ... + static_cast(a)->ConnectionClosed(endpoint, peer, gen_event); if ( DataPending(endpoint) ) { // Don't close out the connection yet, there's still data to @@ -1266,9 +1265,10 @@ void TCPSessionAdapter::ConnectionClosed(analyzer::tcp::TCP_Endpoint* endpoint, void TCPSessionAdapter::ConnectionFinished(bool half_finished) { const analyzer::analyzer_list& children(GetChildren()); - LOOP_OVER_CONST_CHILDREN(i) - // Again, nasty - see TCPSessionAdapter::ConnectionClosed. - static_cast(*i)->ConnectionFinished(half_finished); + + for ( Analyzer* a : children ) + // Again, nasty - see TCPSessionAdapter::ConnectionClosed. + static_cast(a)->ConnectionFinished(half_finished); if ( half_finished ) Event(connection_half_finished); @@ -1282,8 +1282,8 @@ void TCPSessionAdapter::ConnectionReset() { Event(connection_reset); const analyzer::analyzer_list& children(GetChildren()); - LOOP_OVER_CONST_CHILDREN(i) - static_cast(*i)->ConnectionReset(); + for ( Analyzer* a : children ) + static_cast(a)->ConnectionReset(); is_active = 0; } @@ -1312,8 +1312,8 @@ void TCPSessionAdapter::EndpointEOF(analyzer::tcp::TCP_Reassembler* endp) { EnqueueConnEvent(connection_EOF, ConnVal(), val_mgr->Bool(endp->IsOrig())); const analyzer::analyzer_list& children(GetChildren()); - LOOP_OVER_CONST_CHILDREN(i) - static_cast(*i)->EndpointEOF(endp->IsOrig()); + for ( Analyzer* a : children ) + static_cast(a)->EndpointEOF(endp->IsOrig()); if ( close_deferred ) { if ( DataPending(endp->Endpoint()) ) { @@ -1331,8 +1331,8 @@ void TCPSessionAdapter::EndpointEOF(analyzer::tcp::TCP_Reassembler* endp) { void TCPSessionAdapter::PacketWithRST() { const analyzer::analyzer_list& children(GetChildren()); - LOOP_OVER_CONST_CHILDREN(i) - static_cast(*i)->PacketWithRST(); + for ( Analyzer* a : children ) + static_cast(a)->PacketWithRST(); } void TCPSessionAdapter::CheckPIA_FirstPacket(bool is_orig, const IP_Hdr* ip) { diff --git a/src/plugin/Component.cc b/src/plugin/Component.cc index e363066dfd..6160484dcf 100644 --- a/src/plugin/Component.cc +++ b/src/plugin/Component.cc @@ -11,9 +11,8 @@ namespace zeek::plugin { Tag::type_t Component::type_counter(0); -Component::Component(component::Type arg_type, const std::string& arg_name, Tag::subtype_t tag_subtype, - EnumTypePtr etype) - : type(arg_type), name(arg_name), tag(etype, 1, 0), etype(std::move(etype)), tag_subtype(tag_subtype) { +Component::Component(component::Type arg_type, std::string arg_name, Tag::subtype_t tag_subtype, EnumTypePtr etype) + : type(arg_type), name(std::move(arg_name)), tag(etype, 1, 0), etype(std::move(etype)), tag_subtype(tag_subtype) { canon_name = util::canonify_name(name); canon_name_val = make_intrusive(canon_name); } diff --git a/src/plugin/Component.h b/src/plugin/Component.h index 9a28d21a0d..6975f77092 100644 --- a/src/plugin/Component.h +++ b/src/plugin/Component.h @@ -66,8 +66,7 @@ public: * @param etype An enum type that describes the type for the tag in * script-land. */ - Component(component::Type type, const std::string& name, Tag::subtype_t tag_subtype = 0, - EnumTypePtr etype = nullptr); + Component(component::Type type, std::string name, Tag::subtype_t tag_subtype = 0, EnumTypePtr etype = nullptr); /** * Destructor. diff --git a/src/plugin/Manager.cc b/src/plugin/Manager.cc index 59328b32a6..a718295fa9 100644 --- a/src/plugin/Manager.cc +++ b/src/plugin/Manager.cc @@ -213,7 +213,7 @@ bool Manager::ActivateDynamicPluginInternal(const std::string& name, bool ok_if_ glob_t gl; - if ( glob(dypattern.c_str(), 0, 0, &gl) == 0 ) { + if ( glob(dypattern.c_str(), 0, nullptr, &gl) == 0 ) { for ( size_t i = 0; i < gl.gl_pathc; i++ ) { const char* path = gl.gl_pathv[i]; @@ -440,9 +440,8 @@ void Manager::ExtendZeekPathForPlugins() { void Manager::InitPreScript() { assert(! init); - for ( plugin_list::iterator i = Manager::ActivePluginsInternal()->begin(); - i != Manager::ActivePluginsInternal()->end(); i++ ) { - (*i)->DoConfigure(); + for ( Plugin* plugin : *Manager::ActivePluginsInternal() ) { + plugin->DoConfigure(); } // Sort plugins by name to make sure we have a deterministic order. @@ -452,10 +451,9 @@ void Manager::InitPreScript() { // order. ActivePluginsInternal()->sort(plugin_cmp); - for ( plugin_list::iterator i = Manager::ActivePluginsInternal()->begin(); - i != Manager::ActivePluginsInternal()->end(); i++ ) { - (*i)->InitializeComponents(); - (*i)->InitPreScript(); + for ( Plugin* plugin : *Manager::ActivePluginsInternal() ) { + plugin->InitializeComponents(); + plugin->InitPreScript(); } init = true; @@ -464,13 +462,12 @@ void Manager::InitPreScript() { void Manager::InitBifs() { bif_init_func_map* bifs = BifFilesInternal(); - for ( plugin_list::iterator i = Manager::ActivePluginsInternal()->begin(); - i != Manager::ActivePluginsInternal()->end(); i++ ) { - bif_init_func_map::const_iterator b = bifs->find(util::strtolower((*i)->Name())); + for ( Plugin* plugin : *Manager::ActivePluginsInternal() ) { + bif_init_func_map::const_iterator b = bifs->find(util::strtolower(plugin->Name())); if ( b != bifs->end() ) { - for ( bif_init_func_list::const_iterator j = b->second->begin(); j != b->second->end(); ++j ) - (**j)(*i); + for ( const auto& func : *(b->second) ) + func(plugin); } } } @@ -478,25 +475,22 @@ void Manager::InitBifs() { void Manager::InitPostScript() { assert(init); - for ( plugin_list::iterator i = Manager::ActivePluginsInternal()->begin(); - i != Manager::ActivePluginsInternal()->end(); i++ ) - (*i)->InitPostScript(); + for ( Plugin* plugin : *Manager::ActivePluginsInternal() ) + plugin->InitPostScript(); } void Manager::InitPreExecution() { assert(init); - for ( plugin_list::iterator i = Manager::ActivePluginsInternal()->begin(); - i != Manager::ActivePluginsInternal()->end(); i++ ) - (*i)->InitPreExecution(); + for ( Plugin* plugin : *Manager::ActivePluginsInternal() ) + plugin->InitPreExecution(); } void Manager::FinishPlugins() { assert(init); - for ( plugin_list::iterator i = Manager::ActivePluginsInternal()->begin(); - i != Manager::ActivePluginsInternal()->end(); i++ ) - (*i)->Done(); + for ( Plugin* plugin : *Manager::ActivePluginsInternal() ) + plugin->Done(); Manager::ActivePluginsInternal()->clear(); @@ -510,18 +504,18 @@ Manager::inactive_plugin_list Manager::InactivePlugins() const { inactive_plugin_list inactives; - for ( dynamic_plugin_map::const_iterator i = dynamic_plugins.begin(); i != dynamic_plugins.end(); i++ ) { + for ( const auto& [index, plugin] : dynamic_plugins ) { bool found = false; - for ( plugin_list::const_iterator j = all->begin(); j != all->end(); j++ ) { - if ( (*i).first == util::strtolower((*j)->Name()) ) { + for ( Plugin* plugin : *all ) { + if ( index == util::strtolower(plugin->Name()) ) { found = true; break; } } if ( ! found ) - inactives.emplace_back(*i); + inactives.emplace_back(index, plugin); } return inactives; @@ -595,9 +589,9 @@ void Manager::EnableHook(HookType hook, Plugin* plugin, int prio) { hook_list* l = hooks[hook]; - for ( hook_list::iterator i = l->begin(); i != l->end(); i++ ) { + for ( const auto& [_, hook_plugin] : *l ) { // Already enabled for this plugin. - if ( (*i).second == plugin ) + if ( hook_plugin == plugin ) return; } @@ -646,9 +640,7 @@ int Manager::HookLoadFile(const Plugin::LoadType type, const string& file, const int rc = -1; if ( l ) - for ( hook_list::iterator i = l->begin(); i != l->end(); ++i ) { - Plugin* p = (*i).second; - + for ( const auto& [_, p] : *l ) { rc = p->HookLoadFile(type, file, resolved); if ( rc >= 0 ) @@ -677,9 +669,7 @@ std::pair> Manager::HookLoadFileExtended(const P std::pair> rc = {-1, std::nullopt}; if ( l ) - for ( hook_list::iterator i = l->begin(); i != l->end(); ++i ) { - Plugin* p = (*i).second; - + for ( const auto& [_, p] : *l ) { rc = p->HookLoadFileExtended(type, file, resolved); if ( rc.first >= 0 ) @@ -713,9 +703,7 @@ std::pair Manager::HookCallFunction(const Func* func, zeek::detail std::pair rval{false, nullptr}; if ( l ) { - for ( hook_list::iterator i = l->begin(); i != l->end(); ++i ) { - Plugin* p = (*i).second; - + for ( const auto& [_, p] : *l ) { rval = p->HookFunctionCall(func, parent, vecargs); if ( rval.first ) @@ -742,9 +730,7 @@ bool Manager::HookQueueEvent(Event* event) const { bool result = false; if ( l ) - for ( hook_list::iterator i = l->begin(); i != l->end(); ++i ) { - Plugin* p = (*i).second; - + for ( const auto& [_, p] : *l ) { if ( p->HookQueueEvent(event) ) { result = true; break; @@ -766,8 +752,7 @@ void Manager::HookDrainEvents() const { hook_list* l = hooks[HOOK_DRAIN_EVENTS]; if ( l ) - for ( hook_list::iterator i = l->begin(); i != l->end(); ++i ) { - Plugin* p = (*i).second; + for ( const auto& [_, p] : *l ) { p->HookDrainEvents(); } @@ -786,8 +771,7 @@ void Manager::HookSetupAnalyzerTree(Connection* conn) const { hook_list* l = hooks[HOOK_SETUP_ANALYZER_TREE]; if ( l ) { - for ( hook_list::iterator i = l->begin(); i != l->end(); ++i ) { - Plugin* p = (*i).second; + for ( const auto& [_, p] : *l ) { p->HookSetupAnalyzerTree(conn); } } @@ -808,8 +792,7 @@ void Manager::HookUpdateNetworkTime(double network_time) const { hook_list* l = hooks[HOOK_UPDATE_NETWORK_TIME]; if ( l ) - for ( hook_list::iterator i = l->begin(); i != l->end(); ++i ) { - Plugin* p = (*i).second; + for ( const auto& [_, p] : *l ) { p->HookUpdateNetworkTime(network_time); } @@ -828,8 +811,7 @@ void Manager::HookObjDtor(void* obj) const { hook_list* l = hooks[HOOK_OBJ_DTOR]; if ( l ) - for ( hook_list::iterator i = l->begin(); i != l->end(); ++i ) { - Plugin* p = (*i).second; + for ( const auto& [_, p] : *l ) { p->HookObjDtor(obj); } @@ -856,8 +838,7 @@ void Manager::HookLogInit(const std::string& writer, const std::string& instanti hook_list* l = hooks[HOOK_LOG_INIT]; if ( l ) - for ( hook_list::iterator i = l->begin(); i != l->end(); ++i ) { - Plugin* p = (*i).second; + for ( const auto& [_, p] : *l ) { p->HookLogInit(writer, instantiating_filter, local, remote, info, num_fields, fields); } @@ -885,9 +866,7 @@ bool Manager::HookLogWrite(const std::string& writer, const std::string& filter, bool result = true; if ( l ) - for ( hook_list::iterator i = l->begin(); i != l->end(); ++i ) { - Plugin* p = (*i).second; - + for ( const auto& [_, p] : *l ) { if ( ! p->HookLogWrite(writer, filter, info, num_fields, fields, vals) ) { result = false; break; @@ -924,9 +903,7 @@ bool Manager::HookReporter(const std::string& prefix, const EventHandlerPtr even bool result = true; if ( l ) { - for ( hook_list::iterator i = l->begin(); i != l->end(); ++i ) { - Plugin* p = (*i).second; - + for ( const auto& [_, p] : *l ) { if ( ! p->HookReporter(prefix, event, conn, addl, location, location1, location2, time, message) ) { result = false; break; @@ -951,8 +928,7 @@ void Manager::HookUnprocessedPacket(const Packet* packet) const { hook_list* l = hooks[HOOK_UNPROCESSED_PACKET]; if ( l ) - for ( hook_list::iterator i = l->begin(); i != l->end(); ++i ) { - Plugin* p = (*i).second; + for ( const auto& [_, p] : *l ) { p->HookUnprocessedPacket(packet); } @@ -976,9 +952,7 @@ bool Manager::HookPublishEvent(zeek::cluster::Backend& backend, const std::strin bool result = true; if ( l ) { - for ( hook_list::iterator i = l->begin(); i != l->end(); ++i ) { - Plugin* p = (*i).second; - + for ( const auto& [_, p] : *l ) { if ( ! p->HookPublishEvent(backend, topic, event) ) { result = false; break; diff --git a/src/plugin/Plugin.cc b/src/plugin/Plugin.cc index ad0ea84a0d..e779c4e306 100644 --- a/src/plugin/Plugin.cc +++ b/src/plugin/Plugin.cc @@ -396,17 +396,17 @@ void Plugin::Describe(ODesc* d) const { if ( d->IsShort() ) return; - for ( component_list::const_iterator i = components.begin(); i != components.end(); i++ ) { - (*i)->Describe(d); + for ( Component* component : components ) { + component->Describe(d); d->Add("\n"); } bif_item_list items = BifItems(); - for ( bif_item_list::const_iterator i = items.begin(); i != items.end(); i++ ) { + for ( const auto& item : items ) { const char* type = nullptr; - switch ( (*i).GetType() ) { + switch ( item.GetType() ) { case BifItem::FUNCTION: type = "Function"; break; case BifItem::EVENT: type = "Event"; break; @@ -424,16 +424,13 @@ void Plugin::Describe(ODesc* d) const { d->Add("["); d->Add(type); d->Add("] "); - d->Add((*i).GetID()); + d->Add(item.GetID()); d->Add("\n"); } hook_list hooks = EnabledHooks(); - for ( hook_list::iterator i = hooks.begin(); i != hooks.end(); i++ ) { - HookType hook = (*i).first; - int prio = (*i).second; - + for ( const auto& [hook, prio] : hooks ) { d->Add(" Implements "); d->Add(hook_name(hook)); d->Add(" (priority "); diff --git a/src/probabilistic/BitVector.cc b/src/probabilistic/BitVector.cc index 8b7a9e428e..f1d6208ab1 100644 --- a/src/probabilistic/BitVector.cc +++ b/src/probabilistic/BitVector.cc @@ -17,15 +17,16 @@ BitVector::block_type BitVector::bits_per_block = std::numeric_limitsHash(key); - for ( size_t i = 0; i < h.size(); ++i ) - bits->Set(h[i] % bits->Size()); + for ( unsigned long long i : h ) + bits->Set(i % bits->Size()); } bool BasicBloomFilter::Decrement(const zeek::detail::HashKey* key) { @@ -176,8 +176,8 @@ bool BasicBloomFilter::Decrement(const zeek::detail::HashKey* key) { size_t BasicBloomFilter::Count(const zeek::detail::HashKey* key) const { detail::Hasher::digest_vector h = hasher->Hash(key); - for ( size_t i = 0; i < h.size(); ++i ) { - if ( ! (*bits)[h[i] % bits->Size()] ) + for ( unsigned long long i : h ) { + if ( ! (*bits)[i % bits->Size()] ) return 0; } @@ -267,8 +267,8 @@ std::string CountingBloomFilter::InternalState() const { return util::fmt("%" PR void CountingBloomFilter::Add(const zeek::detail::HashKey* key) { detail::Hasher::digest_vector h = hasher->Hash(key); - for ( size_t i = 0; i < h.size(); ++i ) - cells->Increment(h[i] % cells->Size()); + for ( unsigned long long i : h ) + cells->Increment(i % cells->Size()); } bool CountingBloomFilter::Decrement(const zeek::detail::HashKey* key) { @@ -278,8 +278,8 @@ bool CountingBloomFilter::Decrement(const zeek::detail::HashKey* key) { detail::Hasher::digest_vector h = hasher->Hash(key); - for ( size_t i = 0; i < h.size(); ++i ) - cells->Decrement(h[i] % cells->Size()); + for ( unsigned long long i : h ) + cells->Decrement(i % cells->Size()); return true; } @@ -289,8 +289,8 @@ size_t CountingBloomFilter::Count(const zeek::detail::HashKey* key) const { detail::CounterVector::size_type min = std::numeric_limits::max(); - for ( size_t i = 0; i < h.size(); ++i ) { - detail::CounterVector::size_type cnt = cells->Count(h[i] % cells->Size()); + for ( unsigned long long i : h ) { + detail::CounterVector::size_type cnt = cells->Count(i % cells->Size()); if ( cnt < min ) min = cnt; } diff --git a/src/probabilistic/Hasher.cc b/src/probabilistic/Hasher.cc index 632b3543aa..8b93bc9b4b 100644 --- a/src/probabilistic/Hasher.cc +++ b/src/probabilistic/Hasher.cc @@ -68,10 +68,8 @@ std::unique_ptr Hasher::Unserialize(BrokerDataView data) { std::unique_ptr hasher; switch ( type ) { - case Default: hasher.reset(new DefaultHasher(k, {h1, h2})); break; - - case Double: hasher.reset(new DoubleHasher(k, {h1, h2})); break; - + case Default: hasher = std::make_unique(k, Hasher::seed_t{h1, h2}); break; + case Double: hasher = std::make_unique(k, Hasher::seed_t{h1, h2}); break; default: break; } diff --git a/src/script_opt/CPP/Exprs.cc b/src/script_opt/CPP/Exprs.cc index e3e78caef4..d0562d7a7e 100644 --- a/src/script_opt/CPP/Exprs.cc +++ b/src/script_opt/CPP/Exprs.cc @@ -141,7 +141,7 @@ string CPPCompile::GenExpr(const Expr* e, GenType gt, bool top_level) { default: // Intended to catch errors in overlooking the possible // expressions that might appear. - return string("EXPR"); + return "EXPR"; } } @@ -825,7 +825,7 @@ string CPPCompile::GenVal(const ValPtr& v) { auto it = t->InternalType(); if ( tag == TYPE_BOOL ) - return string(v->IsZero() ? "false" : "true"); + return v->IsZero() ? "false" : "true"; if ( tag == TYPE_ENUM ) return GenEnum(t, v); diff --git a/src/script_opt/Inline.cc b/src/script_opt/Inline.cc index 410ceec678..ebdeb2e5d3 100644 --- a/src/script_opt/Inline.cc +++ b/src/script_opt/Inline.cc @@ -281,7 +281,7 @@ void Inliner::CoalesceEventHandlers(ScriptFuncPtr func, const std::vector(ie), bp); - merged_body->Stmts().push_back(std::move(ie_s)); + merged_body->Stmts().emplace_back(std::move(ie_s)); } auto inlined_func = make_intrusive(merged_body, new_scope, func); diff --git a/src/script_opt/ProfileFunc.cc b/src/script_opt/ProfileFunc.cc index 463b29ab53..df221a223e 100644 --- a/src/script_opt/ProfileFunc.cc +++ b/src/script_opt/ProfileFunc.cc @@ -101,7 +101,7 @@ ProfileFunc::ProfileFunc(const Expr* e, bool _abs_rec_fields) { } TraversalCode ProfileFunc::PreStmt(const Stmt* s) { - stmts.push_back({NewRef{}, const_cast(s)}); + stmts.emplace_back(NewRef{}, const_cast(s)); switch ( s->Tag() ) { case STMT_INIT: @@ -185,7 +185,7 @@ TraversalCode ProfileFunc::PreStmt(const Stmt* s) { } TraversalCode ProfileFunc::PreExpr(const Expr* e) { - exprs.push_back({NewRef{}, const_cast(e)}); + exprs.emplace_back(NewRef{}, const_cast(e)); TrackType(e->GetType()); @@ -1476,7 +1476,7 @@ std::string func_name_at_loc(std::string fname, const Location* loc) { TraversalCode SetBlockLineNumbers::PreStmt(const Stmt* s) { auto loc = const_cast(s->GetLocationInfo()); UpdateLocInfo(loc); - block_line_range.emplace_back(std::pair{loc->first_line, loc->last_line}); + block_line_range.emplace_back(loc->first_line, loc->last_line); return TC_CONTINUE; } @@ -1535,7 +1535,7 @@ ASTBlockAnalyzer::ASTBlockAnalyzer(std::vector& funcs) { auto body_loc = body->GetLocationInfo(); fn = func_name_at_loc(fn, body_loc); - parents.emplace_back(std::pair{fn, fn}); + parents.emplace_back(fn, fn); func_name_prefix = fn + ":"; body->Traverse(this); parents.pop_back(); @@ -1555,7 +1555,7 @@ TraversalCode ASTBlockAnalyzer::PreStmt(const Stmt* s) { auto ls = BuildExpandedDescription(loc); if ( is_compound_stmt(s) ) - parents.push_back(std::pair{LocWithFunc(loc), std::move(ls)}); + parents.emplace_back(LocWithFunc(loc), std::move(ls)); return TC_CONTINUE; } diff --git a/src/script_opt/Reduce.cc b/src/script_opt/Reduce.cc index 5808c5f2de..44afdafd4a 100644 --- a/src/script_opt/Reduce.cc +++ b/src/script_opt/Reduce.cc @@ -376,7 +376,7 @@ NameExprPtr Reducer::GenInlineBlockName(const IDPtr& id) { void Reducer::PushInlineBlock() { ++inline_block_level; - block_locals.emplace_back(std::unordered_map()); + block_locals.emplace_back(); } void Reducer::PopInlineBlock() { diff --git a/src/script_opt/ZAM/BuiltIn.cc b/src/script_opt/ZAM/BuiltIn.cc index 8238e122e3..5a2c9983d6 100644 --- a/src/script_opt/ZAM/BuiltIn.cc +++ b/src/script_opt/ZAM/BuiltIn.cc @@ -269,7 +269,7 @@ bool SortZBI::Build(ZAMCompiler* zam, const NameExpr* n, const ExprPList& args) auto comp_func = comp_val->AsNameExpr(); auto comp_type = comp_func->GetType()->AsFuncType(); - if ( comp_type->Yield()->Tag() != TYPE_INT || ! comp_type->ParamList()->AllMatch(elt_type, 0) || + if ( comp_type->Yield()->Tag() != TYPE_INT || ! comp_type->ParamList()->AllMatch(elt_type, false) || comp_type->ParamList()->GetTypes().size() != 2 ) return false; @@ -312,8 +312,7 @@ bool MultiZBI::Build(ZAMCompiler* zam, const NameExpr* n, const ExprPList& args) std::vector consts; std::vector v; - for ( auto i = 0U; i < args.size(); ++i ) { - auto a = args[i]; + for ( const auto& a : args ) { if ( a->Tag() == EXPR_NAME ) v.push_back(zam->FrameSlot(a->AsNameExpr())); else @@ -402,9 +401,9 @@ bool MultiZBI::Build(ZAMCompiler* zam, const NameExpr* n, const ExprPList& args) BiFArgsType MultiZBI::ComputeArgsType(const ExprPList& args) const { zeek_uint_t mask = 0; - for ( auto i = 0U; i < args.size(); ++i ) { + for ( const auto& a : args ) { mask <<= 1; - if ( args[i]->Tag() == EXPR_CONST ) + if ( a->Tag() == EXPR_CONST ) mask |= 1; } diff --git a/src/script_opt/ZAM/Inst-Gen.cc b/src/script_opt/ZAM/Inst-Gen.cc index 9788995bb9..37eaa01d45 100644 --- a/src/script_opt/ZAM/Inst-Gen.cc +++ b/src/script_opt/ZAM/Inst-Gen.cc @@ -6,9 +6,9 @@ namespace zeek::detail { -ZInstI ZAMCompiler::GenInst(ZOp op) { return ZInstI(op); } +ZInstI ZAMCompiler::GenInst(ZOp op) { return {op}; } -ZInstI ZAMCompiler::GenInst(ZOp op, const NameExpr* v1) { return ZInstI(op, Frame1Slot(v1, op)); } +ZInstI ZAMCompiler::GenInst(ZOp op, const NameExpr* v1) { return {op, Frame1Slot(v1, op)}; } ZInstI ZAMCompiler::GenInst(ZOp op, const NameExpr* v1, int i) { auto z = ZInstI(op, Frame1Slot(v1, op), i); @@ -24,46 +24,42 @@ ZInstI ZAMCompiler::GenInst(ZOp op, const ConstExpr* c, const NameExpr* v1, int ZInstI ZAMCompiler::GenInst(ZOp op, const NameExpr* v1, const NameExpr* v2) { int nv2 = FrameSlot(v2); - return ZInstI(op, Frame1Slot(v1, op), nv2); + return {op, Frame1Slot(v1, op), nv2}; } ZInstI ZAMCompiler::GenInst(ZOp op, const NameExpr* v1, const NameExpr* v2, const NameExpr* v3) { int nv2 = FrameSlot(v2); int nv3 = FrameSlot(v3); - return ZInstI(op, Frame1Slot(v1, op), nv2, nv3); + return {op, Frame1Slot(v1, op), nv2, nv3}; } ZInstI ZAMCompiler::GenInst(ZOp op, const NameExpr* v1, const NameExpr* v2, const NameExpr* v3, const NameExpr* v4) { int nv2 = FrameSlot(v2); int nv3 = FrameSlot(v3); int nv4 = FrameSlot(v4); - return ZInstI(op, Frame1Slot(v1, op), nv2, nv3, nv4); + return {op, Frame1Slot(v1, op), nv2, nv3, nv4}; } -ZInstI ZAMCompiler::GenInst(ZOp op, const ConstExpr* ce) { return ZInstI(op, ce); } +ZInstI ZAMCompiler::GenInst(ZOp op, const ConstExpr* ce) { return {op, ce}; } -ZInstI ZAMCompiler::GenInst(ZOp op, const NameExpr* v1, const ConstExpr* ce) { - return ZInstI(op, Frame1Slot(v1, op), ce); -} +ZInstI ZAMCompiler::GenInst(ZOp op, const NameExpr* v1, const ConstExpr* ce) { return {op, Frame1Slot(v1, op), ce}; } -ZInstI ZAMCompiler::GenInst(ZOp op, const ConstExpr* ce, const NameExpr* v1) { - return ZInstI(op, Frame1Slot(v1, op), ce); -} +ZInstI ZAMCompiler::GenInst(ZOp op, const ConstExpr* ce, const NameExpr* v1) { return {op, Frame1Slot(v1, op), ce}; } ZInstI ZAMCompiler::GenInst(ZOp op, const NameExpr* v1, const ConstExpr* ce, const NameExpr* v2) { int nv2 = FrameSlot(v2); - return ZInstI(op, Frame1Slot(v1, op), nv2, ce); + return {op, Frame1Slot(v1, op), nv2, ce}; } ZInstI ZAMCompiler::GenInst(ZOp op, const NameExpr* v1, const NameExpr* v2, const ConstExpr* ce) { int nv2 = FrameSlot(v2); - return ZInstI(op, Frame1Slot(v1, op), nv2, ce); + return {op, Frame1Slot(v1, op), nv2, ce}; } ZInstI ZAMCompiler::GenInst(ZOp op, const NameExpr* v1, const NameExpr* v2, const NameExpr* v3, const ConstExpr* ce) { int nv2 = FrameSlot(v2); int nv3 = FrameSlot(v3); - return ZInstI(op, Frame1Slot(v1, op), nv2, nv3, ce); + return {op, Frame1Slot(v1, op), nv2, nv3, ce}; } ZInstI ZAMCompiler::GenInst(ZOp op, const NameExpr* v1, const NameExpr* v2, const ConstExpr* ce, const NameExpr* v3) { @@ -71,7 +67,7 @@ ZInstI ZAMCompiler::GenInst(ZOp op, const NameExpr* v1, const NameExpr* v2, cons // us from needing to implement a redundant constructor. int nv2 = FrameSlot(v2); int nv3 = FrameSlot(v3); - return ZInstI(op, Frame1Slot(v1, op), nv2, nv3, ce); + return {op, Frame1Slot(v1, op), nv2, nv3, ce}; } ZInstI ZAMCompiler::GenInst(ZOp op, const NameExpr* v1, const ConstExpr* c, int i) { diff --git a/src/script_opt/ZAM/ZInst.cc b/src/script_opt/ZAM/ZInst.cc index 3911f557dc..b9bfe5c451 100644 --- a/src/script_opt/ZAM/ZInst.cc +++ b/src/script_opt/ZAM/ZInst.cc @@ -26,7 +26,7 @@ void ZInst::Dump(FILE* f, const string& prefix, const string& id1, const string& const string& id4) const { fprintf(f, "%s ", ZOP_name(op)); // fprintf(f, "(%s) ", op_type_name(op_type)); - if ( t && 0 ) + if ( t && false ) fprintf(f, "(%s) ", type_name(t->Tag())); switch ( op_type ) { diff --git a/src/spicy/manager.cc b/src/spicy/manager.cc index a18942916e..37ae792956 100644 --- a/src/spicy/manager.cc +++ b/src/spicy/manager.cc @@ -532,7 +532,7 @@ void Manager::analyzerError(file_analysis::Analyzer* a, const std::string& msg, reporter->PopLocation(); if ( a ) - a->SetSkip(1); // Imitate what AnalyzerError() does for protocol analyzers. + a->SetSkip(true); // Imitate what AnalyzerError() does for protocol analyzers. } void Manager::analyzerError(packet_analysis::Analyzer* a, const std::string& msg, const std::string& location) { @@ -861,7 +861,7 @@ void Manager::searchModules(const std::string& paths) { detail::Location Manager::makeLocation(const std::string& fname) { auto x = _locations.insert(fname); - return detail::Location(x.first->c_str(), 0, 0, 0, 0); + return {x.first->c_str(), 0, 0, 0, 0}; } void Manager::autoDiscoverModules() { diff --git a/src/storage/backend/redis/Redis.cc b/src/storage/backend/redis/Redis.cc index 4b2fae68ab..97fd4f3c3e 100644 --- a/src/storage/backend/redis/Redis.cc +++ b/src/storage/backend/redis/Redis.cc @@ -21,8 +21,8 @@ namespace { class Tracer { public: - Tracer(const std::string& where) : where(where) {} // DBG_LOG(zeek::DBG_STORAGE, "%s", where.c_str()); } - ~Tracer() {} // DBG_LOG(zeek::DBG_STORAGE, "%s done", where.c_str()); } + Tracer(std::string where) : where(std::move(where)) {} // DBG_LOG(zeek::DBG_STORAGE, "%s", where.c_str()); } + ~Tracer() {} // DBG_LOG(zeek::DBG_STORAGE, "%s done", where.c_str()); } std::string where; }; @@ -416,7 +416,7 @@ OperationResult Redis::DoPut(ResultCallback* cb, ValPtr key, ValPtr value, bool format.append(" NX"); format += " %f %b"; - status = redisAsyncCommand(async_ctx, redisZADD, NULL, format.c_str(), key_prefix.data(), expiration_time, + status = redisAsyncCommand(async_ctx, redisZADD, nullptr, format.c_str(), key_prefix.data(), expiration_time, key_data->data(), key_data->size()); if ( connected && status == REDIS_ERR ) return {ReturnCode::OPERATION_FAILED, util::fmt("ZADD operation failed: %s", async_ctx->errstr)}; @@ -488,8 +488,8 @@ void Redis::DoExpire(double current_network_time) { expire_running = true; - int status = redisAsyncCommand(async_ctx, redisGeneric, NULL, "ZRANGEBYSCORE %s_expire -inf %f", key_prefix.data(), - current_network_time); + int status = redisAsyncCommand(async_ctx, redisGeneric, nullptr, "ZRANGEBYSCORE %s_expire -inf %f", + key_prefix.data(), current_network_time); if ( status == REDIS_ERR ) { // TODO: do something with the error? @@ -526,7 +526,7 @@ void Redis::DoExpire(double current_network_time) { // redisAsyncCommand usually takes a printf-style string, except the parser used by // hiredis doesn't handle lengths passed with strings correctly (it hangs indefinitely). // Use util::fmt here instead it handles it. - status = redisAsyncCommand(async_ctx, redisGeneric, NULL, + status = redisAsyncCommand(async_ctx, redisGeneric, nullptr, util::fmt("DEL %s:%.*s", key_prefix.data(), static_cast(e.size()), e.data())); ++active_ops; Poll(); @@ -540,7 +540,7 @@ void Redis::DoExpire(double current_network_time) { freeReplyObject(reply); // Remove all of the elements from the range-set that match the time range. - redisAsyncCommand(async_ctx, redisGeneric, NULL, "ZREMRANGEBYSCORE %s_expire -inf %f", key_prefix.data(), + redisAsyncCommand(async_ctx, redisGeneric, nullptr, "ZREMRANGEBYSCORE %s_expire -inf %f", key_prefix.data(), current_network_time); ++active_ops; @@ -685,7 +685,7 @@ void Redis::SendInfoRequest() { DBG_LOG(DBG_STORAGE, "Redis backend: Sending INFO request"); // Request the INFO block from the server that should contain the version information. - int status = redisAsyncCommand(async_ctx, redisINFO, NULL, "INFO server"); + int status = redisAsyncCommand(async_ctx, redisINFO, nullptr, "INFO server"); if ( status == REDIS_ERR ) { // TODO: do something with the error? @@ -709,11 +709,11 @@ void Redis::OnConnect(int status) { // If the username and/or password are set, send an AUTH command. Fail to // connect if the authentication fails. We want to pause here while opening. if ( ! username.empty() && ! password.empty() ) { - status = redisAsyncCommand(async_ctx, redisAUTH, NULL, "AUTH %s %s", username.c_str(), password.c_str()); + status = redisAsyncCommand(async_ctx, redisAUTH, nullptr, "AUTH %s %s", username.c_str(), password.c_str()); made_auth_request = true; } else if ( ! password.empty() ) { - status = redisAsyncCommand(async_ctx, redisAUTH, NULL, "AUTH %s", password.c_str()); + status = redisAsyncCommand(async_ctx, redisAUTH, nullptr, "AUTH %s", password.c_str()); made_auth_request = true; } diff --git a/src/storage/backend/sqlite/SQLite.cc b/src/storage/backend/sqlite/SQLite.cc index 309407bb6c..785bdafbb5 100644 --- a/src/storage/backend/sqlite/SQLite.cc +++ b/src/storage/backend/sqlite/SQLite.cc @@ -29,7 +29,7 @@ OperationResult SQLite::RunPragma(std::string_view name, std::optional(stmt.size()), &ps, NULL)); + CheckError(sqlite3_prepare_v2(stmt_db, stmt.c_str(), static_cast(stmt.size()), &ps, nullptr)); prep_res.code != ReturnCode::SUCCESS ) { Close(nullptr); return prep_res; @@ -250,7 +250,7 @@ OperationResult SQLite::DoClose(ResultCallback* cb) { update_expiry_last_run_stmt.reset(); char* errmsg; - if ( int res = sqlite3_exec(db, "pragma optimize", NULL, NULL, &errmsg); + if ( int res = sqlite3_exec(db, "pragma optimize", nullptr, nullptr, &errmsg); res != SQLITE_OK && res != SQLITE_BUSY ) { // We're shutting down so capture the error message here for informational // reasons, but don't do anything else with it. diff --git a/src/supervisor/Supervisor.cc b/src/supervisor/Supervisor.cc index 38e02c8073..665efd1bb8 100644 --- a/src/supervisor/Supervisor.cc +++ b/src/supervisor/Supervisor.cc @@ -1170,7 +1170,7 @@ std::optional Supervisor::CreateStem(bool supervisor_mode) sh.pid = pid; sh.stdout_pipe = std::move(fork_res.stdout_pipe); sh.stderr_pipe = std::move(fork_res.stderr_pipe); - return std::optional(std::move(sh)); + return {std::move(sh)}; } static BifEnum::Supervisor::ClusterRole role_str_to_enum(std::string_view r) { diff --git a/src/threading/BasicThread.cc b/src/threading/BasicThread.cc index 94f3232a51..8bf58d4858 100644 --- a/src/threading/BasicThread.cc +++ b/src/threading/BasicThread.cc @@ -168,7 +168,7 @@ void* BasicThread::launcher(void* arg) { sigdelset(&mask_set, SIGILL); sigdelset(&mask_set, SIGSEGV); sigdelset(&mask_set, SIGBUS); - int res = pthread_sigmask(SIG_BLOCK, &mask_set, 0); + int res = pthread_sigmask(SIG_BLOCK, &mask_set, nullptr); assert(res == 0); #endif diff --git a/src/threading/Manager.cc b/src/threading/Manager.cc index 8fcf6605ac..5b16e6b6d2 100644 --- a/src/threading/Manager.cc +++ b/src/threading/Manager.cc @@ -54,7 +54,7 @@ void Manager::InitPostScript() { m.second = 0; MsgThread::Stats thread_stats; - for ( const auto& t : thread_mgr->msg_threads ) { + for ( auto* t : thread_mgr->msg_threads ) { t->GetStats(&thread_stats); thread_mgr->current_bucketed_messages.pending_in_total += thread_stats.pending_in; @@ -140,16 +140,16 @@ void Manager::Terminate() { // Signal all to stop. - for ( all_thread_list::iterator i = all_threads.begin(); i != all_threads.end(); i++ ) - (*i)->SignalStop(); + for ( auto* t : all_threads ) + t->SignalStop(); - for ( all_thread_list::iterator i = all_threads.begin(); i != all_threads.end(); i++ ) - (*i)->WaitForStop(); + for ( auto* t : all_threads ) + t->WaitForStop(); // Then join them all. - for ( all_thread_list::iterator i = all_threads.begin(); i != all_threads.end(); i++ ) { - (*i)->Join(); - delete *i; + for ( auto* t : all_threads ) { + t->Join(); + delete t; } all_threads.clear(); @@ -183,8 +183,8 @@ void Manager::AddMsgThread(MsgThread* thread) { void Manager::KillThreads() { DBG_LOG(DBG_THREADING, "Killing threads ..."); - for ( all_thread_list::iterator i = all_threads.begin(); i != all_threads.end(); i++ ) - (*i)->Kill(); + for ( auto* t : all_threads ) + t->Kill(); } void Manager::KillThread(BasicThread* thread) { @@ -199,15 +199,12 @@ void Manager::SendHeartbeats() { // Since this is a regular timer, this is also an ideal place to check whether we have // and dead threads and to delete them. all_thread_list to_delete; - for ( all_thread_list::iterator i = all_threads.begin(); i != all_threads.end(); i++ ) { - BasicThread* t = *i; - + for ( auto* t : all_threads ) { if ( t->Killed() ) to_delete.push_back(t); } - for ( all_thread_list::iterator i = to_delete.begin(); i != to_delete.end(); i++ ) { - BasicThread* t = *i; + for ( auto* t : to_delete ) { t->WaitForStop(); all_threads.remove(t); @@ -290,9 +287,7 @@ void Manager::Flush() { did_process = false; - for ( msg_thread_list::iterator i = msg_threads.begin(); i != msg_threads.end(); i++ ) { - MsgThread* t = *i; - + for ( auto* t : msg_threads ) { if ( do_beat ) t->Heartbeat(); @@ -316,15 +311,12 @@ void Manager::Flush() { all_thread_list to_delete; - for ( all_thread_list::iterator i = all_threads.begin(); i != all_threads.end(); i++ ) { - BasicThread* t = *i; - + for ( auto* t : all_threads ) { if ( t->Killed() ) to_delete.push_back(t); } - for ( all_thread_list::iterator i = to_delete.begin(); i != to_delete.end(); i++ ) { - BasicThread* t = *i; + for ( auto* t : to_delete ) { t->WaitForStop(); all_threads.remove(t); @@ -346,9 +338,7 @@ void Manager::Flush() { const threading::Manager::msg_stats_list& threading::Manager::GetMsgThreadStats() { stats.clear(); - for ( msg_thread_list::iterator i = msg_threads.begin(); i != msg_threads.end(); i++ ) { - MsgThread* t = *i; - + for ( auto* t : msg_threads ) { MsgThread::Stats s; t->GetStats(&s); diff --git a/src/util.cc b/src/util.cc index e8b33bf59c..19551b6d60 100644 --- a/src/util.cc +++ b/src/util.cc @@ -409,7 +409,7 @@ void init_random_seed(const char* read_file, const char* write_file, bool use_em pos += nbytes / sizeof(uint32_t); #else // Gather up some entropy. - gettimeofday((struct timeval*)(buf.data() + pos), 0); + gettimeofday((struct timeval*)(buf.data() + pos), nullptr); pos += sizeof(struct timeval) / sizeof(uint32_t); // use urandom. For reasons see e.g. http://www.2uo.de/myths-about-urandom/ @@ -664,8 +664,8 @@ string normalize_path(std::string_view path) { } } - for ( auto it = final_components.begin(); it != final_components.end(); ++it ) { - new_path.append(*it); + for ( const auto& comp : final_components ) { + new_path.append(comp); new_path.append("/"); } @@ -681,8 +681,8 @@ string without_zeekpath_component(std::string_view path) { const auto paths = tokenize_string(zeek_path(), path_list_separator[0]); - for ( size_t i = 0; i < paths.size(); ++i ) { - string common = normalize_path(paths[i]); + for ( const auto& p : paths ) { + string common = normalize_path(p); if ( rval.find(common) != 0 ) continue; @@ -1817,8 +1817,8 @@ string find_file(const string& filename, const string& path_set, const string& o if ( ! opt_ext.empty() ) ext.push_back(opt_ext); - for ( size_t n = 0; n < paths.size(); ++n ) { - string f = find_file_in_path(filename, paths[n], ext); + for ( const auto& p : paths ) { + string f = find_file_in_path(filename, p, ext); if ( ! f.empty() ) return f; @@ -1833,8 +1833,8 @@ string find_script_file(const string& filename, const string& path_set) { vector ext = {".zeek"}; - for ( size_t n = 0; n < paths.size(); ++n ) { - string f = find_file_in_path(filename, paths[n], ext); + for ( const auto& p : paths ) { + string f = find_file_in_path(filename, p, ext); if ( ! f.empty() ) return f; @@ -1853,7 +1853,7 @@ double current_time(bool real) { tv.tv_sec = ms.count() / 1000; tv.tv_usec = (ms.count() % 1000) * 1000; #else - if ( gettimeofday(&tv, 0) < 0 ) + if ( gettimeofday(&tv, nullptr) < 0 ) reporter->InternalError("gettimeofday failed in current_time()"); #endif double t = double(tv.tv_sec) + double(tv.tv_usec) / 1e6; @@ -1942,7 +1942,7 @@ uint64_t calculate_unique_id(size_t pool) { memset(&unique, 0, sizeof(unique)); // Make valgrind happy. gethostname(unique.hostname, 120); unique.hostname[sizeof(unique.hostname) - 1] = '\0'; - gettimeofday(&unique.time, 0); + gettimeofday(&unique.time, nullptr); unique.pool = (uint64_t)pool; unique.pid = getpid(); unique.rnd = static_cast(detail::random_number()); diff --git a/src/zeek-setup.cc b/src/zeek-setup.cc index 68bc62647c..5d42b27f38 100644 --- a/src/zeek-setup.cc +++ b/src/zeek-setup.cc @@ -472,7 +472,7 @@ static void set_signal_mask(bool do_block) { sigaddset(&mask_set, SIGTERM); sigaddset(&mask_set, SIGINT); - int res = pthread_sigmask(do_block ? SIG_BLOCK : SIG_UNBLOCK, &mask_set, 0); + int res = pthread_sigmask(do_block ? SIG_BLOCK : SIG_UNBLOCK, &mask_set, nullptr); assert(res == 0); } diff --git a/src/zeekygen/Configuration.cc b/src/zeekygen/Configuration.cc index 021bfd0982..579b258555 100644 --- a/src/zeekygen/Configuration.cc +++ b/src/zeekygen/Configuration.cc @@ -29,8 +29,8 @@ static TargetFactory create_target_factory() { return rval; } -Config::Config(const string& arg_file, const string& delim) - : file(arg_file), targets(), target_factory(create_target_factory()) { +Config::Config(string arg_file, const string& delim) + : file(std::move(arg_file)), targets(), target_factory(create_target_factory()) { if ( file.empty() ) return; @@ -72,18 +72,18 @@ Config::Config(const string& arg_file, const string& delim) } Config::~Config() { - for ( size_t i = 0; i < targets.size(); ++i ) - delete targets[i]; + for ( auto* t : targets ) + delete t; } void Config::FindDependencies(const vector& infos) { - for ( size_t i = 0; i < targets.size(); ++i ) - targets[i]->FindDependencies(infos); + for ( auto* t : targets ) + t->FindDependencies(infos); } void Config::GenerateDocs() const { - for ( size_t i = 0; i < targets.size(); ++i ) - targets[i]->Generate(); + for ( auto* t : targets ) + t->Generate(); } time_t Config::GetModificationTime() const { diff --git a/src/zeekygen/Configuration.h b/src/zeekygen/Configuration.h index 2256e0fde7..802001b24d 100644 --- a/src/zeekygen/Configuration.h +++ b/src/zeekygen/Configuration.h @@ -26,7 +26,7 @@ public: * an empty string most methods are a no-op. * @param delim The delimiter between target fields. */ - explicit Config(const std::string& file, const std::string& delim = "\t"); + explicit Config(std::string file, const std::string& delim = "\t"); /** * Destructor, cleans up targets created when parsing config file. diff --git a/src/zeekygen/IdentifierInfo.cc b/src/zeekygen/IdentifierInfo.cc index 702f187890..0bce8a49f5 100644 --- a/src/zeekygen/IdentifierInfo.cc +++ b/src/zeekygen/IdentifierInfo.cc @@ -81,9 +81,9 @@ vector IdentifierInfo::GetFieldComments(const string& field) const { list IdentifierInfo::GetRedefs(const string& from_script) const { list rval; - for ( redef_list::const_iterator it = redefs.begin(); it != redefs.end(); ++it ) { - if ( from_script == (*it)->from_script ) - rval.push_back(*(*it)); + for ( Redefinition* redef : redefs ) { + if ( from_script == redef->from_script ) + rval.push_back(*redef); } return rval; diff --git a/src/zeekygen/Manager.cc b/src/zeekygen/Manager.cc index 4afa22354f..038a183775 100644 --- a/src/zeekygen/Manager.cc +++ b/src/zeekygen/Manager.cc @@ -93,8 +93,8 @@ Manager::Manager(const string& arg_config, const string& command) } Manager::~Manager() { - for ( size_t i = 0; i < all_info.size(); ++i ) - delete all_info[i]; + for ( auto* info : all_info ) + delete info; } void Manager::InitPreScript() { @@ -106,8 +106,8 @@ void Manager::InitPostScript() { if ( disabled ) return; - for ( size_t i = 0; i < all_info.size(); ++i ) - all_info[i]->InitPostScript(); + for ( auto* info : all_info ) + info->InitPostScript(); config.FindDependencies(all_info); } @@ -179,8 +179,8 @@ void Manager::ScriptDependency(const string& path, const string& dep) { script_info->AddDependency(depname); DBG_LOG(DBG_ZEEKYGEN, "Added script dependency %s for %s", depname.c_str(), name.c_str()); - for ( size_t i = 0; i < comment_buffer.size(); ++i ) - DbgAndWarn(util::fmt("Discarded extraneous Zeekygen comment: %s", comment_buffer[i].c_str())); + for ( const auto& cmnt : comment_buffer ) + DbgAndWarn(util::fmt("Discarded extraneous Zeekygen comment: %s", cmnt.c_str())); } void Manager::ModuleUsage(const string& path, const string& module) { diff --git a/src/zeekygen/PackageInfo.cc b/src/zeekygen/PackageInfo.cc index 6291d5cde3..062f891930 100644 --- a/src/zeekygen/PackageInfo.cc +++ b/src/zeekygen/PackageInfo.cc @@ -12,7 +12,7 @@ using namespace std; namespace zeek::zeekygen::detail { -PackageInfo::PackageInfo(const string& arg_name) : Info(), pkg_name(arg_name), readme() { +PackageInfo::PackageInfo(string arg_name) : Info(), pkg_name(std::move(arg_name)), readme() { string readme_file = util::find_file(pkg_name + "/README", util::zeek_path()); if ( readme_file.empty() ) @@ -35,8 +35,8 @@ PackageInfo::PackageInfo(const string& arg_name) : Info(), pkg_name(arg_name), r string PackageInfo::DoReStructuredText(bool roles_only) const { string rval = util::fmt(":doc:`%s `\n\n", pkg_name.c_str(), pkg_name.c_str()); - for ( size_t i = 0; i < readme.size(); ++i ) - rval += " " + readme[i] + "\n"; + for ( const auto& r : readme ) + rval += " " + r + "\n"; return rval; } diff --git a/src/zeekygen/PackageInfo.h b/src/zeekygen/PackageInfo.h index 574a709fe4..5f1f8c07f9 100644 --- a/src/zeekygen/PackageInfo.h +++ b/src/zeekygen/PackageInfo.h @@ -20,7 +20,7 @@ public: * @param name The name of the Zeek script package (relative path from a * component within ZEEKPATH). */ - explicit PackageInfo(const std::string& name); + explicit PackageInfo(std::string name); /** * @return The content of the package's README file, each line being diff --git a/src/zeekygen/ReStructuredTextTable.cc b/src/zeekygen/ReStructuredTextTable.cc index b68dbb86b9..26d5eb5364 100644 --- a/src/zeekygen/ReStructuredTextTable.cc +++ b/src/zeekygen/ReStructuredTextTable.cc @@ -40,16 +40,16 @@ string ReStructuredTextTable::MakeBorder(const vector& col_sizes, char b string ReStructuredTextTable::AsString(char border) const { string rval = MakeBorder(longest_row_in_column, border); - for ( size_t row = 0; row < rows.size(); ++row ) { + for ( const auto& row : rows ) { for ( size_t col = 0; col < num_cols; ++col ) { if ( col > 0 ) { - size_t last = rows[row][col - 1].size(); + size_t last = row[col - 1].size(); size_t longest = longest_row_in_column[col - 1]; size_t whitespace = longest - last + 1; rval += string(whitespace, ' '); } - rval += rows[row][col]; + rval += row[col]; } rval += "\n"; diff --git a/src/zeekygen/ScriptInfo.cc b/src/zeekygen/ScriptInfo.cc index 8495b384f1..103c7e273a 100644 --- a/src/zeekygen/ScriptInfo.cc +++ b/src/zeekygen/ScriptInfo.cc @@ -23,17 +23,17 @@ bool IdInfoComp::operator()(const IdentifierInfo* lhs, const IdentifierInfo* rhs static vector summary_comment(const vector& cmnts) { vector rval; - for ( size_t i = 0; i < cmnts.size(); ++i ) { - size_t end = end_of_first_sentence(cmnts[i]); + for ( const auto& cmnt : cmnts ) { + size_t end = end_of_first_sentence(cmnt); if ( end == string::npos ) { - if ( is_all_whitespace(cmnts[i]) ) + if ( is_all_whitespace(cmnt) ) break; - rval.push_back(cmnts[i]); + rval.push_back(cmnt); } else { - rval.push_back(cmnts[i].substr(0, end + 1)); + rval.push_back(cmnt.substr(0, end + 1)); break; } } @@ -68,12 +68,12 @@ static string make_summary(const string& heading, char underline, char border, c ReStructuredTextTable table(2); - for ( id_info_list::const_iterator it = id_list.begin(); it != id_list.end(); ++it ) { - auto* id = (*it)->GetID(); + for ( IdentifierInfo* info : id_list ) { + auto* id = info->GetID(); ODesc d; d.SetQuotes(true); id->DescribeReSTShort(&d); - add_summary_rows(d, summary_comment((*it)->GetComments()), &table); + add_summary_rows(d, summary_comment(info->GetComments()), &table); } return make_heading(heading, underline) + table.AsString(border) + "\n"; @@ -86,14 +86,14 @@ static string make_redef_summary(const string& heading, char underline, char bor ReStructuredTextTable table(2); - for ( id_info_set::const_iterator it = id_set.begin(); it != id_set.end(); ++it ) { - auto* id = (*it)->GetID(); + for ( IdentifierInfo* info : id_set ) { + auto* id = info->GetID(); ODesc d; d.SetQuotes(true); id->DescribeReSTShort(&d); using redef_list = std::list; - redef_list redefs = (*it)->GetRedefs(from_script); + redef_list redefs = info->GetRedefs(from_script); for ( redef_list::const_iterator iit = redefs.begin(); iit != redefs.end(); ++iit ) { add_summary_rows(d, summary_comment(iit->comments), &table); @@ -199,8 +199,8 @@ static string make_details(const string& heading, char underline, const id_info_ string rval = make_heading(heading, underline); - for ( id_info_list::const_iterator it = id_list.begin(); it != id_list.end(); ++it ) { - rval += (*it)->ReStructuredText(); + for ( IdentifierInfo* info : id_list ) { + rval += info->ReStructuredText(); rval += "\n\n"; } @@ -213,18 +213,18 @@ static string make_redef_details(const string& heading, char underline, const id string rval = make_heading(heading, underline); - for ( id_info_set::const_iterator it = id_set.begin(); it != id_set.end(); ++it ) { - rval += (*it)->ReStructuredText(true); + for ( IdentifierInfo* info : id_set ) { + rval += info->ReStructuredText(true); rval += "\n\n"; } return rval; } -ScriptInfo::ScriptInfo(const string& arg_name, const string& arg_path) +ScriptInfo::ScriptInfo(string arg_name, string arg_path) : Info(), - name(arg_name), - path(arg_path), + name(std::move(arg_name)), + path(std::move(arg_path)), is_pkg_loader(util::detail::is_package_loader(name)), dependencies(), module_usages(), @@ -337,13 +337,13 @@ string ScriptInfo::DoReStructuredText(bool roles_only) const { rval += ":tocdepth: 3\n\n"; rval += make_heading(name, '='); - for ( string_set::const_iterator it = module_usages.begin(); it != module_usages.end(); ++it ) - rval += ".. zeek:namespace:: " + *it + "\n"; + for ( const auto& usage : module_usages ) + rval += ".. zeek:namespace:: " + usage + "\n"; rval += "\n"; - for ( size_t i = 0; i < comments.size(); ++i ) - rval += comments[i] + "\n"; + for ( const auto& cmnt : comments ) + rval += cmnt + "\n"; rval += "\n"; @@ -410,15 +410,15 @@ string ScriptInfo::DoReStructuredText(bool roles_only) const { time_t ScriptInfo::DoGetModificationTime() const { time_t most_recent = get_mtime(path); - for ( string_set::const_iterator it = dependencies.begin(); it != dependencies.end(); ++it ) { - Info* info = zeek::detail::zeekygen_mgr->GetScriptInfo(*it); + for ( const auto& dep : dependencies ) { + Info* info = zeek::detail::zeekygen_mgr->GetScriptInfo(dep); if ( ! info ) { - string pkg_name = *it + "/__load__.zeek"; + string pkg_name = dep + "/__load__.zeek"; info = zeek::detail::zeekygen_mgr->GetScriptInfo(pkg_name); if ( ! info ) - reporter->InternalWarning("Zeekygen failed to get mtime of %s", it->c_str()); + reporter->InternalWarning("Zeekygen failed to get mtime of %s", dep.c_str()); continue; } diff --git a/src/zeekygen/ScriptInfo.h b/src/zeekygen/ScriptInfo.h index 1a1f2a0ea9..4cee34b096 100644 --- a/src/zeekygen/ScriptInfo.h +++ b/src/zeekygen/ScriptInfo.h @@ -32,7 +32,7 @@ public: * @param name Name of script: a path relative to a component in ZEEKPATH. * @param path Absolute path to the script. */ - ScriptInfo(const std::string& name, const std::string& path); + ScriptInfo(std::string name, std::string path); /** * Associate a Zeekygen summary comment ("##!") with the script. diff --git a/src/zeekygen/Target.cc b/src/zeekygen/Target.cc index d9fcbd4b68..66ea327823 100644 --- a/src/zeekygen/Target.cc +++ b/src/zeekygen/Target.cc @@ -174,8 +174,8 @@ template static vector filter_matches(const vector& from, Target* t) { vector rval; - for ( size_t i = 0; i < from.size(); ++i ) { - T* d = dynamic_cast(from[i]); + for ( Info* f : from ) { + T* d = dynamic_cast(f); if ( ! d ) continue; @@ -189,7 +189,7 @@ static vector filter_matches(const vector& from, Target* t) { return rval; } -TargetFile::TargetFile(const string& arg_name) : name(arg_name), f() { +TargetFile::TargetFile(string arg_name) : name(std::move(arg_name)), f() { if ( name.find('/') != string::npos ) { string dir = util::SafeDirname(name).result; @@ -210,7 +210,8 @@ TargetFile::~TargetFile() { DBG_LOG(DBG_ZEEKYGEN, "Wrote out-of-date target '%s'", name.c_str()); } -Target::Target(const string& arg_name, const string& arg_pattern) : name(arg_name), pattern(arg_pattern), prefix() { +Target::Target(string arg_name, string arg_pattern) + : name(std::move(arg_name)), pattern(std::move(arg_pattern)), prefix() { size_t pos = pattern.find('*'); if ( pos == 0 || pos == string::npos ) @@ -339,19 +340,18 @@ void PackageTarget::DoFindDependencies(const vector& infos) { if ( pkg_deps.empty() ) reporter->FatalError("No match for Zeekygen target '%s' pattern '%s'", Name().c_str(), Pattern().c_str()); - for ( size_t i = 0; i < infos.size(); ++i ) { - ScriptInfo* script = dynamic_cast(infos[i]); + for ( Info* info : infos ) { + ScriptInfo* script = dynamic_cast(info); if ( ! script ) continue; - for ( size_t j = 0; j < pkg_deps.size(); ++j ) { - if ( strncmp(script->Name().c_str(), pkg_deps[j]->Name().c_str(), pkg_deps[j]->Name().size()) != 0 ) + for ( const auto& dep : pkg_deps ) { + if ( strncmp(script->Name().c_str(), dep->Name().c_str(), dep->Name().size()) != 0 ) continue; - DBG_LOG(DBG_ZEEKYGEN, "Script %s associated with package %s", script->Name().c_str(), - pkg_deps[j]->Name().c_str()); - pkg_manifest[pkg_deps[j]].push_back(script); + DBG_LOG(DBG_ZEEKYGEN, "Script %s associated with package %s", script->Name().c_str(), dep->Name().c_str()); + pkg_manifest[dep].push_back(script); script_deps.push_back(script); } } @@ -366,26 +366,26 @@ void PackageTarget::DoGenerate() const { fprintf(file.f, ":orphan:\n\n"); - for ( manifest_t::const_iterator it = pkg_manifest.begin(); it != pkg_manifest.end(); ++it ) { - string header = util::fmt("Package: %s", it->first->Name().c_str()); + for ( const auto& [pkg, info_vec] : pkg_manifest ) { + string header = util::fmt("Package: %s", pkg->Name().c_str()); header += "\n" + string(header.size(), '='); fprintf(file.f, "%s\n\n", header.c_str()); - vector readme = it->first->GetReadme(); + vector readme = pkg->GetReadme(); - for ( size_t i = 0; i < readme.size(); ++i ) - fprintf(file.f, "%s\n", readme[i].c_str()); + for ( const auto& r : readme ) + fprintf(file.f, "%s\n", r.c_str()); fprintf(file.f, "\n"); - for ( size_t i = 0; i < it->second.size(); ++i ) { - fprintf(file.f, ":doc:`/scripts/%s`\n\n", it->second[i]->Name().c_str()); + for ( ScriptInfo* info : info_vec ) { + fprintf(file.f, ":doc:`/scripts/%s`\n\n", info->Name().c_str()); - vector cmnts = it->second[i]->GetComments(); + vector cmnts = info->GetComments(); - for ( size_t j = 0; j < cmnts.size(); ++j ) - fprintf(file.f, " %s\n", cmnts[j].c_str()); + for ( const auto& cmnt : cmnts ) + fprintf(file.f, " %s\n", cmnt.c_str()); fprintf(file.f, "\n"); } @@ -405,8 +405,8 @@ void PackageIndexTarget::DoGenerate() const { TargetFile file(Name()); - for ( size_t i = 0; i < pkg_deps.size(); ++i ) - fprintf(file.f, "%s\n", pkg_deps[i]->ReStructuredText().c_str()); + for ( PackageInfo* info : pkg_deps ) + fprintf(file.f, "%s\n", info->ReStructuredText().c_str()); } void ScriptTarget::DoFindDependencies(const vector& infos) { @@ -418,9 +418,9 @@ void ScriptTarget::DoFindDependencies(const vector& infos) { if ( ! IsDir() ) return; - for ( size_t i = 0; i < script_deps.size(); ++i ) { - if ( util::detail::is_package_loader(script_deps[i]->Name()) ) { - string pkg_dir = util::SafeDirname(script_deps[i]->Name()).result; + for ( ScriptInfo* d : script_deps ) { + if ( util::detail::is_package_loader(d->Name()) ) { + string pkg_dir = util::SafeDirname(d->Name()).result; string target_file = Name() + pkg_dir + "/index.rst"; Target* t = new PackageTarget(target_file, pkg_dir); t->FindDependencies(infos); @@ -441,7 +441,7 @@ vector dir_contents_recursive(string dir) { char* scan_path[2] = {dir.data(), nullptr}; - FTS* fts = fts_open(scan_path, FTS_NOCHDIR, 0); + FTS* fts = fts_open(scan_path, FTS_NOCHDIR, nullptr); if ( ! fts ) { reporter->Error("fts_open failure: %s", strerror(errno)); @@ -472,23 +472,23 @@ void ScriptTarget::DoGenerate() const { set targets; vector dir_contents = dir_contents_recursive(Name()); - for ( size_t i = 0; i < script_deps.size(); ++i ) { - string target_filename = Name() + script_deps[i]->Name() + ".rst"; + for ( ScriptInfo* d : script_deps ) { + string target_filename = Name() + d->Name() + ".rst"; targets.insert(target_filename); vector dep; - dep.push_back(script_deps[i]); + dep.push_back(d); if ( zeek::detail::zeekygen_mgr->IsUpToDate(target_filename, dep) ) continue; TargetFile file(target_filename); - fprintf(file.f, "%s\n", script_deps[i]->ReStructuredText().c_str()); + fprintf(file.f, "%s\n", d->ReStructuredText().c_str()); } - for ( size_t i = 0; i < pkg_deps.size(); ++i ) { - targets.insert(pkg_deps[i]->Name()); - pkg_deps[i]->Generate(); + for ( Target* tgt : pkg_deps ) { + targets.insert(tgt->Name()); + tgt->Generate(); } for ( const auto& f : dir_contents ) { @@ -511,8 +511,9 @@ void ScriptTarget::DoGenerate() const { TargetFile file(Name()); - for ( size_t i = 0; i < script_deps.size(); ++i ) - fprintf(file.f, "%s\n", script_deps[i]->ReStructuredText().c_str()); + for ( ScriptInfo* d : script_deps ) { + fprintf(file.f, "%s\n", d->ReStructuredText().c_str()); + } } void ScriptSummaryTarget::DoGenerate() const { @@ -521,9 +522,7 @@ void ScriptSummaryTarget::DoGenerate() const { TargetFile file(Name()); - for ( size_t i = 0; i < script_deps.size(); ++i ) { - ScriptInfo* d = dynamic_cast(script_deps[i]); - + for ( ScriptInfo* d : script_deps ) { if ( ! d ) continue; @@ -531,8 +530,8 @@ void ScriptSummaryTarget::DoGenerate() const { vector cmnts = d->GetComments(); - for ( size_t i = 0; i < cmnts.size(); ++i ) - fprintf(file.f, " %s\n", cmnts[i].c_str()); + for ( const string& cmnt : cmnts ) + fprintf(file.f, " %s\n", cmnt.c_str()); fprintf(file.f, "\n"); } @@ -547,9 +546,7 @@ void ScriptIndexTarget::DoGenerate() const { fprintf(file.f, ".. toctree::\n"); fprintf(file.f, " :maxdepth: 1\n\n"); - for ( size_t i = 0; i < script_deps.size(); ++i ) { - ScriptInfo* d = dynamic_cast(script_deps[i]); - + for ( ScriptInfo* d : script_deps ) { if ( ! d ) continue; @@ -570,8 +567,8 @@ void IdentifierTarget::DoGenerate() const { TargetFile file(Name()); - for ( size_t i = 0; i < id_deps.size(); ++i ) - fprintf(file.f, "%s\n\n", id_deps[i]->ReStructuredText().c_str()); + for ( IdentifierInfo* info : id_deps ) + fprintf(file.f, "%s\n\n", info->ReStructuredText().c_str()); } } // namespace zeek::zeekygen::detail diff --git a/src/zeekygen/Target.h b/src/zeekygen/Target.h index 4612869095..9251c58105 100644 --- a/src/zeekygen/Target.h +++ b/src/zeekygen/Target.h @@ -28,7 +28,7 @@ struct TargetFile { * directories that don't already exist. * */ - explicit TargetFile(const std::string& arg_name); + explicit TargetFile(std::string arg_name); /** * Close the file. @@ -53,7 +53,7 @@ public: * @param arg_pattern pattern of info objects the target depends upon. Only * exact string and simple prefix matching is currently allowed. */ - Target(const std::string& arg_name, const std::string& arg_pattern); + Target(std::string arg_name, std::string arg_pattern); /** * Dtor. diff --git a/src/zeekygen/utils.cc b/src/zeekygen/utils.cc index ae1b5b4015..8e4b2fadfa 100644 --- a/src/zeekygen/utils.cc +++ b/src/zeekygen/utils.cc @@ -3,6 +3,7 @@ #include "zeek/zeekygen/utils.h" #include +#include #include #include "zeek/Func.h" @@ -112,11 +113,8 @@ size_t end_of_first_sentence(const string& s) { } bool is_all_whitespace(const string& s) { - for ( size_t i = 0; i < s.size(); ++i ) - if ( ! isspace(s[i]) ) - return false; - - return true; + auto it = std::find_if(s.begin(), s.end(), [](char c) { return ! isspace(c); }); + return it == s.end(); } string redef_indication(const string& from_script) {