diff --git a/src/Anon.cc b/src/Anon.cc index 9df45b2480..d86df56759 100644 --- a/src/Anon.cc +++ b/src/Anon.cc @@ -20,7 +20,7 @@ AnonymizeIPAddr* zeek::detail::ip_anonymizer[NUM_ADDR_ANONYMIZATION_METHODS] = { static uint32_t rand32() { - return ((zeek::random_number() & 0xffff) << 16) | (zeek::random_number() & 0xffff); + return ((zeek::util::random_number() & 0xffff) << 16) | (zeek::util::random_number() & 0xffff); } // From tcpdpriv. @@ -104,7 +104,7 @@ ipaddr32_t AnonymizeIPAddr_RandomMD5::anonymize(ipaddr32_t input) uint8_t digest[16]; ipaddr32_t output = 0; - hmac_md5(sizeof(input), (u_char*)(&input), digest); + zeek::util::hmac_md5(sizeof(input), (u_char*)(&input), digest); for ( int i = 0; i < 4; ++i ) output = (output << 8) | digest[i]; @@ -132,7 +132,7 @@ ipaddr32_t AnonymizeIPAddr_PrefixMD5::anonymize(ipaddr32_t input) prefix.prefix = htonl((input & ~(prefix_mask>>i)) | (1<<(31-i))); // HK(PAD(x_0 ... x_{i-1})). - hmac_md5(sizeof(prefix), (u_char*) &prefix, digest); + zeek::util::hmac_md5(sizeof(prefix), (u_char*) &prefix, digest); // f_{i-1} = LSB(HK(PAD(x_0 ... x_{i-1}))). ipaddr32_t bit_mask = (digest[0] & 1) << (31-i); diff --git a/src/Base64.cc b/src/Base64.cc index 7f1a17e50a..a50f6121d3 100644 --- a/src/Base64.cc +++ b/src/Base64.cc @@ -193,7 +193,7 @@ int Base64Converter::Decode(int len, const char* data, int* pblen, char** pbuf) else { if ( ++errored == 1 ) - IllegalEncoding(fmt("character %d ignored by Base64 decoding", (int) (data[dlen]))); + IllegalEncoding(zeek::util::fmt("character %d ignored by Base64 decoding", (int) (data[dlen]))); } ++dlen; @@ -210,7 +210,8 @@ int Base64Converter::Done(int* pblen, char** pbuf) if ( base64_group_next != 0 ) { if ( base64_group_next < 4 ) - IllegalEncoding(fmt("incomplete base64 group, padding with %d bits of 0", (4-base64_group_next) * 6)); + IllegalEncoding(zeek::util::fmt("incomplete base64 group, padding with %d bits of 0", + (4-base64_group_next) * 6)); Decode(4 - base64_group_next, padding, pblen, pbuf); return -1; } diff --git a/src/CCL.cc b/src/CCL.cc index 2ca3f5b4fc..6c015c6a55 100644 --- a/src/CCL.cc +++ b/src/CCL.cc @@ -48,7 +48,7 @@ void CCL::Sort() unsigned int CCL::MemoryAllocation() const { - return padded_sizeof(*this) + padded_sizeof(*syms) + pad_size(syms->size() * sizeof(int_list::value_type)); + return padded_sizeof(*this) + padded_sizeof(*syms) + zeek::util::pad_size(syms->size() * sizeof(int_list::value_type)); } } // namespace zeek::detail diff --git a/src/CompHash.h b/src/CompHash.h index b46fff9bf1..50c72482d2 100644 --- a/src/CompHash.h +++ b/src/CompHash.h @@ -36,7 +36,7 @@ public: zeek::ListValPtr RecoverVals(const zeek::detail::HashKey* k) const { return RecoverVals(*k); } - unsigned int MemoryAllocation() const { return padded_sizeof(*this) + pad_size(size); } + unsigned int MemoryAllocation() const { return padded_sizeof(*this) + zeek::util::pad_size(size); } protected: std::unique_ptr ComputeSingletonHash(const zeek::Val* v, bool type_check) const; diff --git a/src/Conn.cc b/src/Conn.cc index 5d1ff7ca77..deb32b1097 100644 --- a/src/Conn.cc +++ b/src/Conn.cc @@ -439,7 +439,7 @@ void Connection::AppendAddl(const char* str) const char* old = cv->GetField(6)->AsString()->CheckString(); const char* format = *old ? "%s %s" : "%s%s"; - cv->Assign(6, zeek::make_intrusive(fmt(format, old, str))); + cv->Assign(6, zeek::make_intrusive(zeek::util::fmt(format, old, str))); } // Returns true if the character at s separates a version number. @@ -535,7 +535,7 @@ void Connection::EnqueueEvent(zeek::EventHandlerPtr f, zeek::analyzer::Analyzer* zeek::Args args) { // "this" is passed as a cookie for the event - zeek::event_mgr.Enqueue(f, std::move(args), SOURCE_LOCAL, a ? a->GetID() : 0, this); + zeek::event_mgr.Enqueue(f, std::move(args), zeek::util::SOURCE_LOCAL, a ? a->GetID() : 0, this); } void Connection::Weird(const char* name, const char* addl) diff --git a/src/DFA.cc b/src/DFA.cc index b1cc02cdb9..09aed30c25 100644 --- a/src/DFA.cc +++ b/src/DFA.cc @@ -284,9 +284,9 @@ void DFA_State::Stats(unsigned int* computed, unsigned int* uncomputed) unsigned int DFA_State::Size() { return sizeof(*this) - + pad_size(sizeof(DFA_State*) * num_sym) - + (accept ? pad_size(sizeof(int) * accept->size()) : 0) - + (nfa_states ? pad_size(sizeof(NFA_State*) * nfa_states->length()) : 0) + + zeek::util::pad_size(sizeof(DFA_State*) * num_sym) + + (accept ? zeek::util::pad_size(sizeof(int) * accept->size()) : 0) + + (nfa_states ? zeek::util::pad_size(sizeof(NFA_State*) * nfa_states->length()) : 0) + (meta_ec ? meta_ec->Size() : 0); } @@ -373,7 +373,7 @@ void DFA_State_Cache::GetStats(Stats* s) ++s->dfa_states; s->nfa_states += e->NFAStateNum(); e->Stats(&s->computed, &s->uncomputed); - s->mem += pad_size(e->Size()) + padded_sizeof(*e); + s->mem += zeek::util::pad_size(e->Size()) + padded_sizeof(*e); } } diff --git a/src/DNS_Mgr.cc b/src/DNS_Mgr.cc index fdcce40d0b..20381fa8e1 100644 --- a/src/DNS_Mgr.cc +++ b/src/DNS_Mgr.cc @@ -58,7 +58,7 @@ namespace zeek::detail { class DNS_Mgr_Request { public: DNS_Mgr_Request(const char* h, int af, bool is_txt) - : host(copy_string(h)), fam(af), qtype(is_txt ? 16 : 0), addr(), + : host(zeek::util::copy_string(h)), fam(af), qtype(is_txt ? 16 : 0), addr(), request_pending() { } @@ -140,7 +140,7 @@ public: if ( req_host && num_addrs == 0) return false; // nothing to expire - return current_time() > (creation_time + req_ttl); + return zeek::util::current_time() > (creation_time + req_ttl); } int Type() const { return map_type; } @@ -187,11 +187,11 @@ static zeek::TableValPtr empty_addr_set() DNS_Mapping::DNS_Mapping(const char* host, struct hostent* h, uint32_t ttl) { Init(h); - req_host = copy_string(host); + req_host = zeek::util::copy_string(host); req_ttl = ttl; if ( names && ! names[0] ) - names[0] = copy_string(host); + names[0] = zeek::util::copy_string(host); } DNS_Mapping::DNS_Mapping(const zeek::IPAddr& addr, struct hostent* h, uint32_t ttl) @@ -231,13 +231,13 @@ DNS_Mapping::DNS_Mapping(FILE* f) failed = static_cast(failed_local); if ( is_req_host ) - req_host = copy_string(req_buf); + req_host = zeek::util::copy_string(req_buf); else req_addr = zeek::IPAddr(req_buf); num_names = 1; names = new char*[num_names]; - names[0] = copy_string(name_buf); + names[0] = zeek::util::copy_string(name_buf); if ( num_addrs > 0 ) { @@ -318,7 +318,7 @@ void DNS_Mapping::Init(struct hostent* h) { no_mapping = false; init_failed = false; - creation_time = current_time(); + creation_time = zeek::util::current_time(); host_val = nullptr; addrs_val = nullptr; @@ -331,7 +331,7 @@ void DNS_Mapping::Init(struct hostent* h) map_type = h->h_addrtype; num_names = 1; // for now, just use official name names = new char*[num_names]; - names[0] = h->h_name ? copy_string(h->h_name) : nullptr; + names[0] = h->h_name ? zeek::util::copy_string(h->h_name) : nullptr; for ( num_addrs = 0; h->h_addr_list[num_addrs]; ++num_addrs ) ; @@ -411,7 +411,7 @@ void DNS_Mgr::InitSource() // script-layer option to configure the DNS resolver as it may not be // configured to the user's desired address at the time when we need to to // the lookup. - auto dns_resolver = zeekenv("ZEEK_DNS_RESOLVER"); + auto dns_resolver = zeek::util::zeekenv("ZEEK_DNS_RESOLVER"); auto dns_resolver_addr = dns_resolver ? zeek::IPAddr(dns_resolver) : zeek::IPAddr(); char err[NB_DNS_ERRSIZE]; @@ -1204,7 +1204,7 @@ void DNS_Mgr::IssueAsyncRequests() continue; } - req->time = current_time(); + req->time = zeek::util::current_time(); asyncs_timeouts.push(req); ++asyncs_pending; @@ -1350,7 +1350,7 @@ void DNS_Mgr::Process() { AsyncRequest* req = asyncs_timeouts.top(); - if ( req->time + DNS_TIMEOUT > current_time() && ! zeek::net::terminating ) + if ( req->time + DNS_TIMEOUT > zeek::util::current_time() && ! zeek::net::terminating ) break; if ( ! req->processed ) diff --git a/src/DNS_Mgr.h b/src/DNS_Mgr.h index 3efb9bd648..90d2fa7359 100644 --- a/src/DNS_Mgr.h +++ b/src/DNS_Mgr.h @@ -62,7 +62,7 @@ public: zeek::ValPtr LookupAddr(const zeek::IPAddr& addr); // Define the directory where to store the data. - void SetDir(const char* arg_dir) { dir = copy_string(arg_dir); } + void SetDir(const char* arg_dir) { dir = zeek::util::copy_string(arg_dir); } void Verify(); void Resolve(); diff --git a/src/Debug.cc b/src/Debug.cc index bd04044115..ea717051a4 100644 --- a/src/Debug.cc +++ b/src/Debug.cc @@ -119,7 +119,7 @@ FILE* TraceState::SetTraceFile(const char* filename) { FILE* newfile; - if ( streq(filename, "-") ) + if ( zeek::util::streq(filename, "-") ) newfile = stderr; else newfile = fopen(filename, "w"); @@ -179,7 +179,7 @@ int TraceState::LogTrace(const char* fmt, ...) if ( ! loc.filename ) { - loc.filename = copy_string(""); + loc.filename = zeek::util::copy_string(""); loc.last_line = 0; } @@ -377,7 +377,7 @@ vector parse_location_string(const string& s) if ( ! sscanf(line_string.c_str(), "%d", &plr.line) ) plr.type = PLR_UNKNOWN; - string path(find_script_file(filename, bro_path())); + string path(zeek::util::find_script_file(filename, zeek::util::zeek_path())); if ( path.empty() ) { @@ -555,7 +555,7 @@ int dbg_execute_command(const char* cmd) if ( ! cmd ) return 0; - if ( streq(cmd, "") ) // do the GDB command completion + if ( zeek::util::streq(cmd, "") ) // do the GDB command completion { #ifdef HAVE_READLINE int i; @@ -581,7 +581,7 @@ int dbg_execute_command(const char* cmd) return 0; } - char* localcmd = copy_string(cmd); + char* localcmd = zeek::util::copy_string(cmd); string opstring; vector arguments; @@ -768,7 +768,7 @@ string get_context_description(const zeek::detail::Stmt* stmt, const zeek::detai loc = *stmt->GetLocationInfo(); else { - loc.filename = copy_string(""); + loc.filename = zeek::util::copy_string(""); loc.last_line = 0; } @@ -831,7 +831,7 @@ int dbg_handle_debug_input() // readline uses malloc, and we want to be consistent // with it. - input_line = (char*) safe_malloc(1024); + input_line = (char*) zeek::util::safe_malloc(1024); input_line[1023] = 0; // ### Maybe it's not always stdin. input_line = fgets(input_line, 1023, stdin); diff --git a/src/DebugCmds.cc b/src/DebugCmds.cc index 83a485a60a..431098765d 100644 --- a/src/DebugCmds.cc +++ b/src/DebugCmds.cc @@ -37,7 +37,7 @@ static bool string_is_regex(const string& s) static void lookup_global_symbols_regex(const string& orig_regex, vector& matches, bool func_only = false) { - if ( streq(orig_regex.c_str(), "") ) + if ( zeek::util::streq(orig_regex.c_str(), "") ) return; string regex = "^"; diff --git a/src/DebugLogger.cc b/src/DebugLogger.cc index d6a8f3fead..c89adb19bb 100644 --- a/src/DebugLogger.cc +++ b/src/DebugLogger.cc @@ -49,7 +49,7 @@ void DebugLogger::OpenDebugLog(const char* filename) { if ( filename ) { - filename = log_file_name(filename); + filename = zeek::util::log_file_name(filename); file = fopen(filename, "w"); if ( ! file ) @@ -93,7 +93,7 @@ void DebugLogger::ShowStreamsHelp() void DebugLogger::EnableStreams(const char* s) { char* brkt; - char* tmp = copy_string(s); + char* tmp = zeek::util::copy_string(s); char* tok = strtok(tmp, ","); while ( tok ) @@ -159,7 +159,7 @@ void DebugLogger::Log(DebugStream stream, const char* fmt, ...) return; fprintf(file, "%17.06f/%17.06f [%s] ", - zeek::net::network_time, current_time(true), g->prefix); + zeek::net::network_time, zeek::util::current_time(true), g->prefix); for ( int i = g->indent; i > 0; --i ) fputs(" ", file); @@ -176,13 +176,13 @@ void DebugLogger::Log(DebugStream stream, const char* fmt, ...) void DebugLogger::Log(const zeek::plugin::Plugin& plugin, const char* fmt, ...) { std::string tok = std::string("plugin-") + plugin.Name(); - tok = strreplace(tok, "::", "-"); + tok = zeek::util::strreplace(tok, "::", "-"); if ( enabled_streams.find(tok) == enabled_streams.end() ) return; fprintf(file, "%17.06f/%17.06f [plugin %s] ", - zeek::net::network_time, current_time(true), plugin.Name().c_str()); + zeek::net::network_time, zeek::util::current_time(true), plugin.Name().c_str()); va_list ap; va_start(ap, fmt); diff --git a/src/Desc.cc b/src/Desc.cc index 773f99940a..3632476c7c 100644 --- a/src/Desc.cc +++ b/src/Desc.cc @@ -27,7 +27,7 @@ ODesc::ODesc(desc_type t, zeek::File* arg_f) if ( f == nullptr ) { size = DEFAULT_SIZE; - base = safe_malloc(size); + base = zeek::util::safe_malloc(size); ((char*) base)[0] = '\0'; offset = 0; } @@ -335,7 +335,7 @@ void ODesc::AddBytes(const void* bytes, unsigned int n) if ( p.first ) { AddBytesRaw(s, p.first - s); - get_escaped_string(this, p.first, p.second, true); + zeek::util::get_escaped_string(this, p.first, p.second, true); s = p.first + p.second; } else @@ -388,7 +388,7 @@ void ODesc::Grow(unsigned int n) while ( offset + n + SLOP >= size ) size *= 2; - base = safe_realloc(base, size); + base = zeek::util::safe_realloc(base, size); } void ODesc::Clear() @@ -400,7 +400,7 @@ void ODesc::Clear() { free(base); size = DEFAULT_SIZE; - base = safe_malloc(size); + base = zeek::util::safe_malloc(size); ((char*) base)[0] = '\0'; } } diff --git a/src/EquivClass.cc b/src/EquivClass.cc index c5272daccb..c9f01c455f 100644 --- a/src/EquivClass.cc +++ b/src/EquivClass.cc @@ -189,7 +189,7 @@ void EquivClass::Dump(FILE* f) int EquivClass::Size() const { - return padded_sizeof(*this) + pad_size(sizeof(int) * size * (ccl_flags ? 5 : 4)); + return padded_sizeof(*this) + zeek::util::pad_size(sizeof(int) * size * (ccl_flags ? 5 : 4)); } } // namespace zeek::detail diff --git a/src/Event.cc b/src/Event.cc index f7f33d7843..1a1ef98acc 100644 --- a/src/Event.cc +++ b/src/Event.cc @@ -19,7 +19,7 @@ zeek::EventMgr& mgr = zeek::event_mgr; namespace zeek { Event::Event(EventHandlerPtr arg_handler, zeek::Args arg_args, - SourceID arg_src, zeek::analyzer::ID arg_aid, Obj* arg_obj) + zeek::util::SourceID arg_src, zeek::analyzer::ID arg_aid, Obj* arg_obj) : handler(arg_handler), args(std::move(arg_args)), src(arg_src), @@ -48,7 +48,7 @@ void Event::Describe(ODesc* d) const void Event::Dispatch(bool no_remote) { - if ( src == SOURCE_BROKER ) + if ( src == zeek::util::SOURCE_BROKER ) no_remote = true; if ( handler->ErrorHandler() ) @@ -75,7 +75,7 @@ void Event::Dispatch(bool no_remote) EventMgr::EventMgr() { head = tail = nullptr; - current_src = SOURCE_LOCAL; + current_src = zeek::util::SOURCE_LOCAL; current_aid = 0; src_val = nullptr; draining = false; @@ -122,7 +122,7 @@ void EventMgr::QueueEvent(const EventHandlerPtr &h, val_list* vl, } void EventMgr::Enqueue(const EventHandlerPtr& h, zeek::Args vl, - SourceID src, zeek::analyzer::ID aid, Obj* obj) + zeek::util::SourceID src, zeek::analyzer::ID aid, Obj* obj) { QueueEvent(new Event(h, std::move(vl), src, aid, obj)); } @@ -225,7 +225,7 @@ void EventMgr::Process() // here to the current time since otherwise it won't move forward. zeek::iosource::PktSrc* pkt_src = zeek::iosource_mgr->GetPktSrc(); if ( ! pkt_src || ! pkt_src->IsOpen() || zeek::net::reading_live ) - zeek::net::detail::net_update_time(current_time()); + zeek::net::detail::net_update_time(zeek::util::current_time()); queue_flare.Extinguish(); diff --git a/src/Event.h b/src/Event.h index 05691fa443..392c2f6147 100644 --- a/src/Event.h +++ b/src/Event.h @@ -19,13 +19,13 @@ namespace zeek { class Event final : public zeek::Obj { public: Event(EventHandlerPtr handler, zeek::Args args, - SourceID src = SOURCE_LOCAL, zeek::analyzer::ID aid = 0, + zeek::util::SourceID src = zeek::util::SOURCE_LOCAL, zeek::analyzer::ID aid = 0, zeek::Obj* obj = nullptr); void SetNext(Event* n) { next_event = n; } Event* NextEvent() const { return next_event; } - SourceID Source() const { return src; } + zeek::util::SourceID Source() const { return src; } zeek::analyzer::ID Analyzer() const { return aid; } EventHandlerPtr Handler() const { return handler; } const zeek::Args& Args() const { return args; } @@ -41,7 +41,7 @@ protected: EventHandlerPtr handler; zeek::Args args; - SourceID src; + zeek::util::SourceID src; zeek::analyzer::ID aid; zeek::Obj* obj; Event* next_event; @@ -62,7 +62,7 @@ public: // arguments when there's no handlers to consume them). [[deprecated("Remove in v4.1. Use Enqueue() instead.")]] void QueueEventFast(const EventHandlerPtr &h, val_list vl, - SourceID src = SOURCE_LOCAL, zeek::analyzer::ID aid = 0, + zeek::util::SourceID src = zeek::util::SOURCE_LOCAL, zeek::analyzer::ID aid = 0, zeek::detail::TimerMgr* mgr = nullptr, zeek::Obj* obj = nullptr); // Queues an event if there's an event handler (or remote consumer). This @@ -73,7 +73,7 @@ public: // existence check. [[deprecated("Remove in v4.1. Use Enqueue() instead.")]] void QueueEvent(const EventHandlerPtr &h, val_list vl, - SourceID src = SOURCE_LOCAL, zeek::analyzer::ID aid = 0, + zeek::util::SourceID src = zeek::util::SOURCE_LOCAL, zeek::analyzer::ID aid = 0, zeek::detail::TimerMgr* mgr = nullptr, zeek::Obj* obj = nullptr); // Same as QueueEvent, except taking the event's argument list via a @@ -82,7 +82,7 @@ public: // each of its elements. [[deprecated("Remove in v4.1. Use Enqueue() instead.")]] void QueueEvent(const EventHandlerPtr &h, val_list* vl, - SourceID src = SOURCE_LOCAL, zeek::analyzer::ID aid = 0, + zeek::util::SourceID src = zeek::util::SOURCE_LOCAL, zeek::analyzer::ID aid = 0, zeek::detail::TimerMgr* mgr = nullptr, zeek::Obj* obj = nullptr); /** @@ -98,7 +98,7 @@ public: * reference to until dispatching the event. */ void Enqueue(const EventHandlerPtr& h, zeek::Args vl, - SourceID src = SOURCE_LOCAL, zeek::analyzer::ID aid = 0, + zeek::util::SourceID src = zeek::util::SOURCE_LOCAL, zeek::analyzer::ID aid = 0, zeek::Obj* obj = nullptr); /** @@ -119,7 +119,7 @@ public: bool HasEvents() const { return head != nullptr; } // Returns the source ID of last raised event. - SourceID CurrentSource() const { return current_src; } + zeek::util::SourceID CurrentSource() const { return current_src; } // Returns the ID of the analyzer which raised the last event, or 0 if // non-analyzer event. @@ -143,7 +143,7 @@ protected: Event* head; Event* tail; - SourceID current_src; + zeek::util::SourceID current_src; zeek::analyzer::ID current_aid; zeek::RecordVal* src_val; bool draining; diff --git a/src/Expr.cc b/src/Expr.cc index 3ba0cd77b5..97b2ca8853 100644 --- a/src/Expr.cc +++ b/src/Expr.cc @@ -1265,8 +1265,8 @@ AddToExpr::AddToExpr(ExprPtr arg_op1, ExprPtr arg_op2) } else if ( bt1 != bt2 && bt1 != zeek::TYPE_ANY ) - ExprError(fmt("incompatible vector append: %s and %s", - type_name(bt1), type_name(bt2))); + ExprError(zeek::util::fmt("incompatible vector append: %s and %s", + type_name(bt1), type_name(bt2))); else SetType(op1->GetType()); @@ -1487,12 +1487,12 @@ ValPtr DivideExpr::AddrFold(Val* v1, Val* v2) const if ( a.GetFamily() == IPv4 ) { if ( mask > 32 ) - RuntimeError(fmt("bad IPv4 subnet prefix length: %" PRIu32, mask)); + RuntimeError(zeek::util::fmt("bad IPv4 subnet prefix length: %" PRIu32, mask)); } else { if ( mask > 128 ) - RuntimeError(fmt("bad IPv6 subnet prefix length: %" PRIu32, mask)); + RuntimeError(zeek::util::fmt("bad IPv6 subnet prefix length: %" PRIu32, mask)); } return zeek::make_intrusive(a, mask); @@ -2249,8 +2249,8 @@ bool AssignExpr::TypeCheckArithmetics(TypeTag bt1, TypeTag bt2) { if ( ! IsArithmetic(bt2) ) { - ExprError(fmt("assignment of non-arithmetic value to arithmetic (%s/%s)", - type_name(bt1), type_name(bt2))); + ExprError(zeek::util::fmt("assignment of non-arithmetic value to arithmetic (%s/%s)", + type_name(bt1), type_name(bt2))); return false; } @@ -2459,7 +2459,7 @@ bool AssignExpr::IsRecordElement(TypeDecl* td) const { const NameExpr* n = (const NameExpr*) op1.get(); td->type = op2->GetType(); - td->id = copy_string(n->Id()->Name()); + td->id = zeek::util::copy_string(n->Id()->Name()); } return true; @@ -2519,8 +2519,8 @@ IndexExpr::IndexExpr(ExprPtr arg_op1, ListExprPtr arg_op2, bool arg_is_slice) if ( match_type == DOES_NOT_MATCH_INDEX ) { std::string error_msg = - fmt("expression with type '%s' is not a type that can be indexed", - type_name(op1->GetType()->Tag())); + zeek::util::fmt("expression with type '%s' is not a type that can be indexed", + type_name(op1->GetType()->Tag())); SetError(error_msg.data()); } @@ -2806,7 +2806,7 @@ void IndexExpr::Assign(Frame* f, ValPtr v) const auto& vt = v->GetType(); auto vtt = vt->Tag(); std::string tn = vtt == zeek::TYPE_RECORD ? vt->GetName() : type_name(vtt); - RuntimeErrorWithCallStack(fmt( + RuntimeErrorWithCallStack(zeek::util::fmt( "vector index assignment failed for invalid type '%s', value: %s", tn.data(), d.Description())); } @@ -2828,7 +2828,7 @@ void IndexExpr::Assign(Frame* f, ValPtr v) const auto& vt = v->GetType(); auto vtt = vt->Tag(); std::string tn = vtt == zeek::TYPE_RECORD ? vt->GetName() : type_name(vtt); - RuntimeErrorWithCallStack(fmt( + RuntimeErrorWithCallStack(zeek::util::fmt( "table index assignment failed for invalid type '%s', value: %s", tn.data(), d.Description())); } @@ -2875,7 +2875,7 @@ TraversalCode IndexExpr::Traverse(TraversalCallback* cb) const FieldExpr::FieldExpr(ExprPtr arg_op, const char* arg_field_name) : UnaryExpr(EXPR_FIELD, std::move(arg_op)), - field_name(copy_string(arg_field_name)), td(nullptr), field(0) + field_name(zeek::util::copy_string(arg_field_name)), td(nullptr), field(0) { if ( IsError() ) return; @@ -3036,7 +3036,7 @@ RecordConstructorExpr::RecordConstructorExpr(ListExprPtr constructor_list) FieldAssignExpr* field = (FieldAssignExpr*) e; const auto& field_type = field->GetType(); - char* field_name = copy_string(field->FieldName()); + char* field_name = zeek::util::copy_string(field->FieldName()); record_types->push_back(new TypeDecl(field_name, field_type)); } @@ -3315,7 +3315,7 @@ ValPtr SetConstructorExpr::InitVal(const zeek::Type* t, ValPtr aggr) const if ( ! element || ! tval->Assign(std::move(element), nullptr) ) { - Error(fmt("initialization type mismatch in set"), e); + Error(zeek::util::fmt("initialization type mismatch in set"), e); return nullptr; } } @@ -3387,7 +3387,7 @@ ValPtr VectorConstructorExpr::Eval(Frame* f) const if ( ! vec->Assign(i, e->Eval(f)) ) { - RuntimeError(fmt("type mismatch at index %d", i)); + RuntimeError(zeek::util::fmt("type mismatch at index %d", i)); return nullptr; } } @@ -3413,7 +3413,7 @@ ValPtr VectorConstructorExpr::InitVal(const zeek::Type* t, ValPtr aggr) const if ( ! v || ! vec->Assign(i, std::move(v)) ) { - Error(fmt("initialization type mismatch at index %d", i), e); + Error(zeek::util::fmt("initialization type mismatch at index %d", i), e); return nullptr; } } @@ -3460,7 +3460,7 @@ bool FieldAssignExpr::IsRecordElement(TypeDecl* td) const if ( td ) { td->type = op->GetType(); - td->id = copy_string(field_name.c_str()); + td->id = zeek::util::copy_string(field_name.c_str()); } return true; @@ -3584,8 +3584,8 @@ RecordCoerceExpr::RecordCoerceExpr(ExprPtr arg_op, zeek::RecordTypePtr r) int t_i = t_r->FieldOffset(sub_r->FieldName(i)); if ( t_i < 0 ) { - ExprError(fmt("orphaned field \"%s\" in record coercion", - sub_r->FieldName(i))); + ExprError(zeek::util::fmt("orphaned field \"%s\" in record coercion", + sub_r->FieldName(i))); break; } @@ -3626,7 +3626,7 @@ RecordCoerceExpr::RecordCoerceExpr(ExprPtr arg_op, zeek::RecordTypePtr r) if ( ! is_arithmetic_promotable(sup_t_i.get(), sub_t_i.get()) && ! is_record_promotable(sup_t_i.get(), sub_t_i.get()) ) { - std::string error_msg = fmt( + std::string error_msg = zeek::util::fmt( "type clash for field \"%s\"", sub_r->FieldName(i)); Error(error_msg.c_str(), sub_t_i.get()); SetError(); @@ -3646,7 +3646,7 @@ RecordCoerceExpr::RecordCoerceExpr(ExprPtr arg_op, zeek::RecordTypePtr r) { if ( ! t_r->FieldDecl(i)->GetAttr(ATTR_OPTIONAL) ) { - std::string error_msg = fmt( + std::string error_msg = zeek::util::fmt( "non-optional field \"%s\" missing", t_r->FieldName(i)); Error(error_msg.c_str()); SetError(); @@ -4010,7 +4010,7 @@ ValPtr InExpr::Fold(Val* v1, Val* v2) const // Could do better here e.g. Boyer-Moore if done repeatedly. auto s = reinterpret_cast(s1->CheckString()); - auto res = strstr_n(s2->Len(), s2->Bytes(), s1->Len(), s) != -1; + auto res = zeek::util::strstr_n(s2->Len(), s2->Bytes(), s1->Len(), s) != -1; return zeek::val_mgr->Bool(res); } @@ -4096,7 +4096,7 @@ CallExpr::CallExpr(ExprPtr arg_func, ListExprPtr arg_args, bool in_hook) // run-time errors when we apply this analysis during // parsing. Really we should instead do it after we've // parsed the entire set of scripts. - streq(((NameExpr*) func.get())->Id()->Name(), "fmt") && + zeek::util::streq(((NameExpr*) func.get())->Id()->Name(), "fmt") && // The following is needed because fmt might not yet // be bound as a name. did_builtin_init && @@ -4594,7 +4594,7 @@ ValPtr ListExpr::InitVal(const zeek::Type* t, ValPtr aggr) const if ( ! vec->Assign(i, e->Eval(nullptr)) ) { - e->Error(fmt("type mismatch at index %d", i)); + e->Error(zeek::util::fmt("type mismatch at index %d", i)); return nullptr; } } diff --git a/src/File.cc b/src/File.cc index 2243c30337..4d675863d8 100644 --- a/src/File.cc +++ b/src/File.cc @@ -68,8 +68,8 @@ File::File(FILE* arg_f, const char* arg_name, const char* arg_access) { Init(); f = arg_f; - name = copy_string(arg_name); - access = copy_string(arg_access); + name = zeek::util::copy_string(arg_name); + access = zeek::util::copy_string(arg_access); t = zeek::base_type(zeek::TYPE_STRING); is_open = (f != nullptr); } @@ -78,15 +78,15 @@ File::File(const char* arg_name, const char* arg_access) { Init(); f = nullptr; - name = copy_string(arg_name); - access = copy_string(arg_access); + name = zeek::util::copy_string(arg_name); + access = zeek::util::copy_string(arg_access); t = zeek::base_type(zeek::TYPE_STRING); - if ( streq(name, "/dev/stdin") ) + if ( zeek::util::streq(name, "/dev/stdin") ) f = stdin; - else if ( streq(name, "/dev/stdout") ) + else if ( zeek::util::streq(name, "/dev/stdout") ) f = stdout; - else if ( streq(name, "/dev/stderr") ) + else if ( zeek::util::streq(name, "/dev/stderr") ) f = stderr; if ( f ) @@ -119,7 +119,7 @@ const char* File::Name() const bool File::Open(FILE* file, const char* mode) { static bool fds_maximized = false; - open_time = zeek::net::network_time ? zeek::net::network_time : current_time(); + open_time = zeek::net::network_time ? zeek::net::network_time : zeek::util::current_time(); if ( ! fds_maximized ) { @@ -282,7 +282,7 @@ zeek::RecordVal* File::Rotate() static auto rotate_info = zeek::id::find_type("rotate_info"); auto* info = new zeek::RecordVal(rotate_info); - FILE* newf = rotate_file(name, info); + FILE* newf = zeek::util::rotate_file(name, info); if ( ! newf ) { diff --git a/src/Flare.cc b/src/Flare.cc index b0b35f46ae..3dddef3a99 100644 --- a/src/Flare.cc +++ b/src/Flare.cc @@ -19,7 +19,7 @@ Flare::Flare() abort(); char buf[256]; - bro_strerror_r(errno, buf, sizeof(buf)); + zeek::util::zeek_strerror_r(errno, buf, sizeof(buf)); if ( zeek::reporter ) zeek::reporter->FatalErrorWithCore("unexpected pipe %s failure: %s", which, buf); diff --git a/src/Func.cc b/src/Func.cc index 076fdb1564..c2b272577d 100644 --- a/src/Func.cc +++ b/src/Func.cc @@ -108,12 +108,12 @@ std::string render_call_stack() arg_desc += d.Description(); } - rval += fmt("#%d %s(%s)", lvl, name, arg_desc.data()); + rval += zeek::util::fmt("#%d %s(%s)", lvl, name, arg_desc.data()); if ( ci.call ) { auto loc = ci.call->GetLocationInfo(); - rval += fmt(" at %s:%d", loc->filename, loc->first_line); + rval += zeek::util::fmt(" at %s:%d", loc->filename, loc->first_line); } ++lvl; @@ -700,7 +700,7 @@ bool check_built_in_call(BuiltinFunc* f, zeek::detail::CallExpr* call) const zeek::detail::Expr* fmt_str_arg = args[0]; if ( fmt_str_arg->GetType()->Tag() != zeek::TYPE_STRING ) { - call->Error("first argument to fmt() needs to be a format string"); + call->Error("first argument to zeek::util::fmt() needs to be a format string"); return false; } @@ -729,7 +729,7 @@ bool check_built_in_call(BuiltinFunc* f, zeek::detail::CallExpr* call) if ( args.length() != num_fmt + 1 ) { - call->Error("mismatch between format string to fmt() and number of arguments passed"); + call->Error("mismatch between format string to zeek::util::fmt() and number of arguments passed"); return false; } } diff --git a/src/Hash.h b/src/Hash.h index efec2d5a96..2ac2b422ff 100644 --- a/src/Hash.h +++ b/src/Hash.h @@ -199,7 +199,7 @@ private: inline static uint8_t shared_hmac_md5_key[16]; inline static bool seeds_initialized = false; - friend void ::hmac_md5(size_t size, const unsigned char* bytes, unsigned char digest[16]); + friend void zeek::util::hmac_md5(size_t size, const unsigned char* bytes, unsigned char digest[16]); friend BifReturnVal zeek::BifFunc::md5_hmac_bif(zeek::detail::Frame* frame, const zeek::Args*); }; @@ -258,7 +258,7 @@ public: int Size() const { return size; } hash_t Hash() const { return hash; } - unsigned int MemoryAllocation() const { return padded_sizeof(*this) + pad_size(size); } + unsigned int MemoryAllocation() const { return padded_sizeof(*this) + zeek::util::pad_size(size); } static hash_t HashBytes(const void* bytes, int size); protected: diff --git a/src/ID.cc b/src/ID.cc index f607ab23c2..f924fe04ea 100644 --- a/src/ID.cc +++ b/src/ID.cc @@ -107,7 +107,7 @@ namespace zeek::detail { ID::ID(const char* arg_name, IDScope arg_scope, bool arg_is_export) { - name = copy_string(arg_name); + name = zeek::util::copy_string(arg_name); scope = arg_scope; is_export = arg_is_export; is_option = false; @@ -309,9 +309,9 @@ std::string ID::GetDeprecationWarning() const result = depr_attr->DeprecationMessage(); if ( result.empty() ) - return fmt("deprecated (%s)", Name()); + return zeek::util::fmt("deprecated (%s)", Name()); else - return fmt("deprecated (%s): %s", Name(), result.c_str()); + return zeek::util::fmt("deprecated (%s): %s", Name(), result.c_str()); } void ID::AddAttrs(AttributesPtr a) @@ -614,10 +614,10 @@ void ID::DescribeReST(ODesc* d, bool roles_only) const ODesc expr_desc; ir->init_expr->Describe(&expr_desc); redef_str = expr_desc.Description(); - redef_str = strreplace(redef_str, "\n", " "); + redef_str = zeek::util::strreplace(redef_str, "\n", " "); d->Add(":Redefinition: "); - d->Add(fmt("from :doc:`/scripts/%s`", ir->from_script.data())); + d->Add(zeek::util::fmt("from :doc:`/scripts/%s`", ir->from_script.data())); d->NL(); d->PushIndent(); diff --git a/src/IP.cc b/src/IP.cc index 277ec67b3d..8cab761c21 100644 --- a/src/IP.cc +++ b/src/IP.cc @@ -284,7 +284,7 @@ zeek::RecordValPtr IPv6_Hdr::ToVal(zeek::VectorValPtr chain) const } default: - zeek::reporter->Weird("unknown_mobility_type", fmt("%d", mob->ip6mob_type)); + zeek::reporter->Weird("unknown_mobility_type", zeek::util::fmt("%d", mob->ip6mob_type)); break; } @@ -632,7 +632,7 @@ void IPv6_Hdr_Chain::ProcessRoutingHeader(const struct ip6_rthdr* r, uint16_t le default: zeek::reporter->Weird(SrcAddr(), DstAddr(), "unknown_routing_type", - fmt("%d", r->ip6r_type)); + zeek::util::fmt("%d", r->ip6r_type)); break; } } diff --git a/src/List.h b/src/List.h index 95733f01b4..2e09b7e34e 100644 --- a/src/List.h +++ b/src/List.h @@ -51,7 +51,7 @@ public: max_entries = size; - entries = (T*) safe_malloc(max_entries * sizeof(T)); + entries = (T*) zeek::util::safe_malloc(max_entries * sizeof(T)); } List(const List& b) @@ -60,7 +60,7 @@ public: num_entries = b.num_entries; if ( max_entries ) - entries = (T*) safe_malloc(max_entries * sizeof(T)); + entries = (T*) zeek::util::safe_malloc(max_entries * sizeof(T)); else entries = nullptr; @@ -81,7 +81,7 @@ public: List(const T* arr, int n) { num_entries = max_entries = n; - entries = (T*) safe_malloc(max_entries * sizeof(T)); + entries = (T*) zeek::util::safe_malloc(max_entries * sizeof(T)); memcpy(entries, arr, n * sizeof(T)); } @@ -98,7 +98,7 @@ public: num_entries = b.num_entries; if ( max_entries ) - entries = (T *) safe_malloc(max_entries * sizeof(T)); + entries = (T *) zeek::util::safe_malloc(max_entries * sizeof(T)); else entries = nullptr; @@ -148,7 +148,7 @@ public: if ( new_size != max_entries ) { - entries = (T*) safe_realloc((void*) entries, sizeof(T) * new_size); + entries = (T*) zeek::util::safe_realloc((void*) entries, sizeof(T) * new_size); if ( entries ) max_entries = new_size; else @@ -159,7 +159,7 @@ public: } int MemoryAllocation() const - { return padded_sizeof(*this) + pad_size(max_entries * sizeof(T)); } + { return padded_sizeof(*this) + zeek::util::pad_size(max_entries * sizeof(T)); } void push_front(const T& a) { diff --git a/src/Net.cc b/src/Net.cc index 249a56b042..108bdaa4f8 100644 --- a/src/Net.cc +++ b/src/Net.cc @@ -80,7 +80,7 @@ RETSIGTYPE watchdog(int /* signo */) // handler and the allocation routines are not // reentrant. - double ct = current_time(); + double ct = zeek::util::current_time(); int int_ct = int(ct); int frac_ct = int((ct - int_ct) * 1e6); @@ -234,7 +234,7 @@ void net_packet_dispatch(double t, const zeek::Packet* pkt, zeek::iosource::PktS if ( load_freq == 0 ) load_freq = uint32_t(0xffffffff) / uint32_t(load_sample_freq); - if ( uint32_t(zeek::random_number() & 0xffffffff) < load_freq ) + if ( uint32_t(zeek::util::random_number() & 0xffffffff) < load_freq ) { // Drain the queued timer events so they're not // charged against this sample. @@ -263,7 +263,7 @@ void net_packet_dispatch(double t, const zeek::Packet* pkt, zeek::iosource::PktS void net_run() { - set_processing_status("RUNNING", "net_run"); + zeek::util::set_processing_status("RUNNING", "net_run"); std::vector ready; ready.reserve(zeek::iosource_mgr->TotalSize()); @@ -281,7 +281,7 @@ void net_run() if ( ! ready.empty() || loop_counter++ % 100 == 0 ) { DBG_LOG(zeek::DBG_MAINLOOP, "realtime=%.6f ready_count=%zu", - current_time(), ready.size()); + zeek::util::current_time(), ready.size()); if ( ! ready.empty() ) loop_counter = 0; @@ -307,7 +307,7 @@ void net_run() // date on timers and events. Because we only // have timers as sources, going to sleep here // doesn't risk blocking on other inputs. - net_update_time(current_time()); + net_update_time(zeek::util::current_time()); expire_timers(); } @@ -364,7 +364,7 @@ void net_get_final_stats() void net_finish(int drain_events) { - set_processing_status("TERMINATING", "net_finish"); + zeek::util::set_processing_status("TERMINATING", "net_finish"); if ( drain_events ) { @@ -389,7 +389,7 @@ void net_finish(int drain_events) void net_delete() { - set_processing_status("TERMINATING", "net_delete"); + zeek::util::set_processing_status("TERMINATING", "net_delete"); delete zeek::sessions; diff --git a/src/Obj.cc b/src/Obj.cc index 4c7f367992..0060774490 100644 --- a/src/Obj.cc +++ b/src/Obj.cc @@ -45,7 +45,7 @@ void Location::Describe(zeek::ODesc* d) const bool Location::operator==(const Location& l) const { if ( filename == l.filename || - (filename && l.filename && streq(filename, l.filename)) ) + (filename && l.filename && zeek::util::streq(filename, l.filename)) ) return first_line == l.first_line && last_line == l.last_line; else return false; @@ -137,7 +137,7 @@ bool Obj::SetLocationInfo(const detail::Location* start, const detail::Location* if ( ! start || ! end ) return false; - if ( end->filename && ! streq(start->filename, end->filename) ) + if ( end->filename && ! zeek::util::streq(start->filename, end->filename) ) return false; if ( location && (start == &zeek::detail::no_location || end == &zeek::detail::no_location) ) diff --git a/src/Options.cc b/src/Options.cc index 747591a19b..9c1f22d4db 100644 --- a/src/Options.cc +++ b/src/Options.cc @@ -66,7 +66,7 @@ void zeek::Options::filter_supervised_node_options() bool zeek::fake_dns() { - return zeekenv("ZEEK_DNS_FAKE"); + return zeek::util::zeekenv("ZEEK_DNS_FAKE"); } extern const char* zeek_version(); @@ -121,16 +121,16 @@ void zeek::usage(const char* prog, int code) #endif fprintf(stderr, " --test | run unit tests ('--test -h' for help, only when compiling with ENABLE_ZEEK_UNIT_TESTS)\n"); - fprintf(stderr, " $ZEEKPATH | file search path (%s)\n", bro_path().c_str()); - fprintf(stderr, " $ZEEK_PLUGIN_PATH | plugin search path (%s)\n", bro_plugin_path()); - fprintf(stderr, " $ZEEK_PLUGIN_ACTIVATE | plugins to always activate (%s)\n", bro_plugin_activate()); - fprintf(stderr, " $ZEEK_PREFIXES | prefix list (%s)\n", bro_prefixes().c_str()); + fprintf(stderr, " $ZEEKPATH | file search path (%s)\n", zeek::util::zeek_path().c_str()); + fprintf(stderr, " $ZEEK_PLUGIN_PATH | plugin search path (%s)\n", zeek::util::zeek_plugin_path()); + fprintf(stderr, " $ZEEK_PLUGIN_ACTIVATE | plugins to always activate (%s)\n", zeek::util::zeek_plugin_activate()); + fprintf(stderr, " $ZEEK_PREFIXES | prefix list (%s)\n", zeek::util::zeek_prefixes().c_str()); fprintf(stderr, " $ZEEK_DNS_FAKE | disable DNS lookups (%s)\n", zeek::fake_dns() ? "on" : "off"); fprintf(stderr, " $ZEEK_SEED_FILE | file to load seeds from (not set)\n"); fprintf(stderr, " $ZEEK_LOG_SUFFIX | ASCII log file extension (.%s)\n", zeek::logging::writer::detail::Ascii::LogExt().c_str()); fprintf(stderr, " $ZEEK_PROFILER_FILE | Output file for script execution statistics (not set)\n"); - fprintf(stderr, " $ZEEK_DISABLE_ZEEKYGEN | Disable Zeekygen documentation support (%s)\n", zeekenv("ZEEK_DISABLE_ZEEKYGEN") ? "set" : "not set"); - fprintf(stderr, " $ZEEK_DNS_RESOLVER | IPv4/IPv6 address of DNS resolver to use (%s)\n", zeekenv("ZEEK_DNS_RESOLVER") ? zeekenv("ZEEK_DNS_RESOLVER") : "not set, will use first IPv4 address from /etc/resolv.conf"); + fprintf(stderr, " $ZEEK_DISABLE_ZEEKYGEN | Disable Zeekygen documentation support (%s)\n", zeek::util::zeekenv("ZEEK_DISABLE_ZEEKYGEN") ? "set" : "not set"); + fprintf(stderr, " $ZEEK_DNS_RESOLVER | IPv4/IPv6 address of DNS resolver to use (%s)\n", zeek::util::zeekenv("ZEEK_DNS_RESOLVER") ? zeek::util::zeekenv("ZEEK_DNS_RESOLVER") : "not set, will use first IPv4 address from /etc/resolv.conf"); fprintf(stderr, " $ZEEK_DEBUG_LOG_STDERR | Use stderr for debug logs generated via the -B flag"); fprintf(stderr, "\n"); @@ -236,8 +236,8 @@ zeek::Options zeek::parse_cmdline(int argc, char** argv) }; char opts[256]; - safe_strncpy(opts, "B:e:f:G:H:I:i:j::n:p:r:s:T:t:U:w:X:CDFNPQSWabdhv", - sizeof(opts)); + zeek::util::safe_strncpy(opts, "B:e:f:G:H:I:i:j::n:p:r:s:T:t:U:w:X:CDFNPQSWabdhv", + sizeof(opts)); #ifdef USE_PERFTOOLS_DEBUG strncat(opts, "mM", 2); @@ -431,7 +431,7 @@ zeek::Options zeek::parse_cmdline(int argc, char** argv) if ( path->empty() ) return; - *path = normalize_path(*path); + *path = zeek::util::normalize_path(*path); if ( (*path)[0] == '/' || (*path)[0] == '~' ) // Absolute path @@ -440,7 +440,7 @@ zeek::Options zeek::parse_cmdline(int argc, char** argv) if ( (*path)[0] != '.' ) { // Look up file in ZEEKPATH - auto res = find_script_file(*path, bro_path()); + auto res = zeek::util::find_script_file(*path, zeek::util::zeek_path()); if ( res.empty() ) { diff --git a/src/PacketDumper.cc b/src/PacketDumper.cc index 141d041b8f..97a477b21a 100644 --- a/src/PacketDumper.cc +++ b/src/PacketDumper.cc @@ -33,7 +33,7 @@ void PacketDumper::DumpPacket(const struct pcap_pkthdr* hdr, void PacketDumper::SortTimeStamp(struct timeval* timestamp) { - if ( time_compare(&last_timestamp, timestamp) > 0 ) + if ( zeek::util::time_compare(&last_timestamp, timestamp) > 0 ) *timestamp = last_timestamp; else last_timestamp = *timestamp; diff --git a/src/PacketFilter.cc b/src/PacketFilter.cc index d7cdcbedfa..bc7ef14db0 100644 --- a/src/PacketFilter.cc +++ b/src/PacketFilter.cc @@ -20,7 +20,7 @@ void PacketFilter::AddSrc(const zeek::IPAddr& src, uint32_t tcp_flags, double pr { Filter* f = new Filter; f->tcp_flags = tcp_flags; - f->probability = probability * static_cast(zeek::max_random()); + f->probability = probability * static_cast(zeek::util::max_random()); auto prev = static_cast(src_filter.Insert(src, 128, f)); delete prev; } @@ -29,7 +29,7 @@ void PacketFilter::AddSrc(zeek::Val* src, uint32_t tcp_flags, double probability { Filter* f = new Filter; f->tcp_flags = tcp_flags; - f->probability = probability * static_cast(zeek::max_random()); + f->probability = probability * static_cast(zeek::util::max_random()); auto prev = static_cast(src_filter.Insert(src, f)); delete prev; } @@ -38,7 +38,7 @@ void PacketFilter::AddDst(const zeek::IPAddr& dst, uint32_t tcp_flags, double pr { Filter* f = new Filter; f->tcp_flags = tcp_flags; - f->probability = probability * static_cast(zeek::max_random()); + f->probability = probability * static_cast(zeek::util::max_random()); auto prev = static_cast(dst_filter.Insert(dst, 128, f)); delete prev; } @@ -47,7 +47,7 @@ void PacketFilter::AddDst(zeek::Val* dst, uint32_t tcp_flags, double probability { Filter* f = new Filter; f->tcp_flags = tcp_flags; - f->probability = probability * static_cast(zeek::max_random()); + f->probability = probability * static_cast(zeek::util::max_random()); auto prev = static_cast(dst_filter.Insert(dst, f)); delete prev; } @@ -115,7 +115,7 @@ bool PacketFilter::MatchFilter(const Filter& f, const zeek::IP_Hdr& ip, return false; } - return zeek::random_number() < f.probability; + return zeek::util::random_number() < f.probability; } } // namespace zeek::detail diff --git a/src/Pipe.cc b/src/Pipe.cc index ae5c2a155e..d21d89967d 100644 --- a/src/Pipe.cc +++ b/src/Pipe.cc @@ -12,7 +12,7 @@ using namespace zeek::detail; static void pipe_fail(int eno) { char tmp[256]; - bro_strerror_r(eno, tmp, sizeof(tmp)); + zeek::util::zeek_strerror_r(eno, tmp, sizeof(tmp)); if ( zeek::reporter ) zeek::reporter->FatalError("Pipe failure: %s", tmp); diff --git a/src/PolicyFile.cc b/src/PolicyFile.cc index 0bc4e4e9bc..5346d9f21a 100644 --- a/src/PolicyFile.cc +++ b/src/PolicyFile.cc @@ -84,7 +84,7 @@ bool LoadPolicyFileText(const char* policy_filename) if ( fstat(fileno(f), &st) != 0 ) { char buf[256]; - bro_strerror_r(errno, buf, sizeof(buf)); + zeek::util::zeek_strerror_r(errno, buf, sizeof(buf)); zeek::reporter->Error("fstat failed on %s: %s", policy_filename, buf); fclose(f); return false; diff --git a/src/PrefixTable.cc b/src/PrefixTable.cc index 03fe19d56c..052baa3da4 100644 --- a/src/PrefixTable.cc +++ b/src/PrefixTable.cc @@ -6,7 +6,7 @@ namespace zeek::detail { prefix_t* PrefixTable::MakePrefix(const zeek::IPAddr& addr, int width) { - prefix_t* prefix = (prefix_t*) safe_malloc(sizeof(prefix_t)); + prefix_t* prefix = (prefix_t*) zeek::util::safe_malloc(sizeof(prefix_t)); addr.CopyIPv6(&prefix->add.sin6); prefix->family = AF_INET6; diff --git a/src/RE.cc b/src/RE.cc index e98d707c4e..1e1bcadc2b 100644 --- a/src/RE.cc +++ b/src/RE.cc @@ -423,21 +423,21 @@ unsigned int Specific_RE_Matcher::MemoryAllocation() const for ( int i = 0; i < ccl_list.length(); ++i ) size += ccl_list[i]->MemoryAllocation(); - size += pad_size(sizeof(CCL*) * ccl_dict.size()); + size += zeek::util::pad_size(sizeof(CCL*) * ccl_dict.size()); for ( const auto& entry : ccl_dict ) { - size += padded_sizeof(std::string) + pad_size(sizeof(std::string::value_type) * entry.first.size()); + size += padded_sizeof(std::string) + zeek::util::pad_size(sizeof(std::string::value_type) * entry.first.size()); size += entry.second->MemoryAllocation(); } for ( const auto& entry : defs ) { - size += padded_sizeof(std::string) + pad_size(sizeof(std::string::value_type) * entry.first.size()); - size += padded_sizeof(std::string) + pad_size(sizeof(std::string::value_type) * entry.second.size()); + size += padded_sizeof(std::string) + zeek::util::pad_size(sizeof(std::string::value_type) * entry.first.size()); + size += padded_sizeof(std::string) + zeek::util::pad_size(sizeof(std::string::value_type) * entry.second.size()); } return size + padded_sizeof(*this) - + (pattern_text ? pad_size(strlen(pattern_text) + 1) : 0) + + (pattern_text ? zeek::util::pad_size(strlen(pattern_text) + 1) : 0) + ccl_list.MemoryAllocation() - padded_sizeof(ccl_list) + equiv_class.Size() - padded_sizeof(EquivClass) + (dfa ? dfa->MemoryAllocation() : 0) // this is ref counted; consider the bytes here? diff --git a/src/RE.h b/src/RE.h index 9cb55bab6f..6f9d4d7dd0 100644 --- a/src/RE.h +++ b/src/RE.h @@ -59,7 +59,7 @@ public: void MakeCaseInsensitive(); - void SetPat(const char* pat) { pattern_text = copy_string(pat); } + void SetPat(const char* pat) { pattern_text = zeek::util::copy_string(pat); } bool Compile(bool lazy = false); diff --git a/src/Reporter.cc b/src/Reporter.cc index cedafd59cd..5306df72a0 100644 --- a/src/Reporter.cc +++ b/src/Reporter.cc @@ -126,7 +126,7 @@ void Reporter::FatalError(const char* fmt, ...) va_end(ap); - set_processing_status("TERMINATED", "fatal_error"); + zeek::util::set_processing_status("TERMINATED", "fatal_error"); fflush(stderr); fflush(stdout); _exit(1); @@ -142,7 +142,7 @@ void Reporter::FatalErrorWithCore(const char* fmt, ...) va_end(ap); - set_processing_status("TERMINATED", "fatal_error"); + zeek::util::set_processing_status("TERMINATED", "fatal_error"); abort(); } @@ -195,7 +195,7 @@ void Reporter::InternalError(const char* fmt, ...) va_end(ap); - set_processing_status("TERMINATED", "internal_error"); + zeek::util::set_processing_status("TERMINATED", "internal_error"); abort(); } @@ -562,7 +562,8 @@ void Reporter::DoLog(const char* prefix, EventHandlerPtr event, FILE* out, vl.reserve(vl_size); if ( time ) - vl.emplace_back(zeek::make_intrusive(zeek::net::network_time ? zeek::net::network_time : current_time())); + vl.emplace_back(zeek::make_intrusive( + zeek::net::network_time ? zeek::net::network_time : zeek::util::current_time())); vl.emplace_back(zeek::make_intrusive(buffer)); diff --git a/src/Rule.cc b/src/Rule.cc index c32fcdb29b..b08849314f 100644 --- a/src/Rule.cc +++ b/src/Rule.cc @@ -75,7 +75,7 @@ void Rule::AddPattern(const char* str, Rule::PatternType type, uint32_t offset, uint32_t depth) { Pattern* p = new Pattern; - p->pattern = copy_string(str); + p->pattern = zeek::util::copy_string(str); p->type = type; p->id = ++pattern_counter; p->offset = offset; @@ -88,7 +88,7 @@ void Rule::AddPattern(const char* str, Rule::PatternType type, void Rule::AddRequires(const char* id, bool opposite_direction, bool negate) { Precond* p = new Precond; - p->id = copy_string(id); + p->id = zeek::util::copy_string(id); p->rule = nullptr; p->opposite_dir = opposite_direction; p->negate = negate; diff --git a/src/Rule.h b/src/Rule.h index 837e8ac399..3a48f2c288 100644 --- a/src/Rule.h +++ b/src/Rule.h @@ -24,7 +24,7 @@ class Rule { public: Rule(const char* arg_id, const zeek::detail::Location& arg_location) { - id = copy_string(arg_id); + id = zeek::util::copy_string(arg_id); idx = rule_counter++; location = arg_location; active = true; diff --git a/src/RuleAction.cc b/src/RuleAction.cc index 5d8e13e32e..b99a2697bd 100644 --- a/src/RuleAction.cc +++ b/src/RuleAction.cc @@ -16,7 +16,7 @@ namespace zeek::detail { RuleActionEvent::RuleActionEvent(const char* arg_msg) { - msg = copy_string(arg_msg); + msg = zeek::util::copy_string(arg_msg); } void RuleActionEvent::DoAction(const Rule* parent, RuleEndpointState* state, @@ -38,7 +38,7 @@ void RuleActionEvent::PrintDebug() RuleActionMIME::RuleActionMIME(const char* arg_mime, int arg_strength) { - mime = copy_string(arg_mime); + mime = zeek::util::copy_string(arg_mime); strength = arg_strength; } diff --git a/src/RuleMatcher.cc b/src/RuleMatcher.cc index ea05cc8ed8..ef76fa9510 100644 --- a/src/RuleMatcher.cc +++ b/src/RuleMatcher.cc @@ -113,7 +113,7 @@ RuleHdrTest::RuleHdrTest(RuleHdrTest& h) copied_set->re = nullptr; copied_set->ids = orig_set->ids; for ( const auto& pattern : orig_set->patterns ) - copied_set->patterns.push_back(copy_string(pattern)); + copied_set->patterns.push_back(zeek::util::copy_string(pattern)); delete copied_set; // TODO: Why do we create copied_set only to then // never use it? @@ -261,7 +261,7 @@ bool RuleMatcher::ReadFiles(const std::vector& files) for ( const auto& f : files ) { - rules_in = open_file(find_file(f, bro_path(), ".sig")); + rules_in = zeek::util::open_file(zeek::util::find_file(f, zeek::util::zeek_path(), ".sig")); if ( ! rules_in ) { @@ -673,8 +673,8 @@ RuleMatcher::MIME_Matches* RuleMatcher::Match(RuleFileMagicState* state, #ifdef DEBUG if ( debug_logger.IsEnabled(zeek::DBG_RULES) ) { - const char* s = fmt_bytes(reinterpret_cast(data), - min(40, static_cast(len))); + const char* s = zeek::util::fmt_bytes(reinterpret_cast(data), + min(40, static_cast(len))); DBG_LOG(zeek::DBG_RULES, "Matching %s rules on |%s%s|", Rule::TypeToString(Rule::FILE_MAGIC), s, len > 40 ? "..." : ""); @@ -871,7 +871,7 @@ void RuleMatcher::Match(RuleEndpointState* state, Rule::PatternType type, if ( debug_logger.IsEnabled(zeek::DBG_RULES) ) { const char* s = - fmt_bytes((const char *) data, min(40, data_len)); + zeek::util::fmt_bytes((const char *) data, min(40, data_len)); DBG_LOG(zeek::DBG_RULES, "Matching %s rules [%d,%d] on |%s%s|", Rule::TypeToString(type), bol, eol, s, @@ -1234,12 +1234,12 @@ void RuleMatcher::DumpStats(zeek::File* f) Stats stats; GetStats(&stats); - f->Write(fmt("%.6f computed dfa states = %d; classes = ??; " - "computed trans. = %d; matchers = %d; mem = %d\n", - zeek::net::network_time, stats.dfa_states, stats.computed, - stats.matchers, stats.mem)); - f->Write(fmt("%.6f DFA cache hits = %d; misses = %d\n", zeek::net::network_time, - stats.hits, stats.misses)); + f->Write(zeek::util::fmt("%.6f computed dfa states = %d; classes = ??; " + "computed trans. = %d; matchers = %d; mem = %d\n", + zeek::net::network_time, stats.dfa_states, stats.computed, + stats.matchers, stats.mem)); + f->Write(zeek::util::fmt("%.6f DFA cache hits = %d; misses = %d\n", zeek::net::network_time, + stats.hits, stats.misses)); DumpStateStats(f, root); } @@ -1256,14 +1256,14 @@ void RuleMatcher::DumpStateStats(zeek::File* f, RuleHdrTest* hdr_test) RuleHdrTest::PatternSet* set = hdr_test->psets[i][j]; assert(set->re); - f->Write(fmt("%.6f %d DFA states in %s group %d from sigs ", zeek::net::network_time, - set->re->DFA()->NumStates(), - Rule::TypeToString((Rule::PatternType)i), j)); + f->Write(zeek::util::fmt("%.6f %d DFA states in %s group %d from sigs ", zeek::net::network_time, + set->re->DFA()->NumStates(), + Rule::TypeToString((Rule::PatternType)i), j)); for ( const auto& id : set->ids ) { Rule* r = Rule::rule_table[id - 1]; - f->Write(fmt("%s ", r->ID())); + f->Write(zeek::util::fmt("%s ", r->ID())); } f->Write("\n"); @@ -1399,7 +1399,7 @@ char* id_to_str(const char* id) return dst; error: - char* dummy = copy_string(""); + char* dummy = zeek::util::copy_string(""); return dummy; } diff --git a/src/ScriptCoverageManager.cc b/src/ScriptCoverageManager.cc index 2a30743a78..bd15556944 100644 --- a/src/ScriptCoverageManager.cc +++ b/src/ScriptCoverageManager.cc @@ -39,7 +39,7 @@ void ScriptCoverageManager::AddStmt(zeek::detail::Stmt* s) bool ScriptCoverageManager::ReadStats() { - char* bf = zeekenv("ZEEK_PROFILER_FILE"); + char* bf = zeek::util::zeekenv("ZEEK_PROFILER_FILE"); if ( ! bf ) return false; @@ -56,7 +56,7 @@ bool ScriptCoverageManager::ReadStats() ss.clear(); std::vector lines; - tokenize_string(file_contents, "\n", &lines); + zeek::util::tokenize_string(file_contents, "\n", &lines); string delimiter; delimiter = delim; @@ -66,7 +66,7 @@ bool ScriptCoverageManager::ReadStats() continue; std::vector line_components; - tokenize_string(line, delimiter, &line_components); + zeek::util::tokenize_string(line, delimiter, &line_components); if ( line_components.size() != 3 ) { @@ -80,7 +80,7 @@ bool ScriptCoverageManager::ReadStats() pair location_desc(std::move(location), std::move(desc)); uint64_t count; - atoi_n(cnt.size(), cnt.c_str(), nullptr, 10, count); + zeek::util::atoi_n(cnt.size(), cnt.c_str(), nullptr, 10, count); usage_map.emplace(std::move(location_desc), count); } @@ -89,14 +89,14 @@ bool ScriptCoverageManager::ReadStats() bool ScriptCoverageManager::WriteStats() { - char* bf = zeekenv("ZEEK_PROFILER_FILE"); + char* bf = zeek::util::zeekenv("ZEEK_PROFILER_FILE"); if ( ! bf ) return false; - SafeDirname dirname{bf}; + zeek::util::SafeDirname dirname{bf}; - if ( ! ensure_intermediate_dirs(dirname.result.data()) ) + if ( ! zeek::util::ensure_intermediate_dirs(dirname.result.data()) ) { zeek::reporter->Error("Failed to open ZEEK_PROFILER_FILE destination '%s' for writing", bf); return false; diff --git a/src/SerializationFormat.cc b/src/SerializationFormat.cc index 9f538fd8ed..e41aaaf778 100644 --- a/src/SerializationFormat.cc +++ b/src/SerializationFormat.cc @@ -45,7 +45,7 @@ void SerializationFormat::StartWrite() if ( ! output ) { - output = (char*)safe_malloc(INITIAL_SIZE); + output = (char*)zeek::util::safe_malloc(INITIAL_SIZE); output_size = INITIAL_SIZE; } @@ -85,7 +85,7 @@ bool SerializationFormat::WriteData(const void* b, size_t count) while ( output_pos + count > output_size ) output_size *= GROWTH_FACTOR; - output = (char*)safe_realloc(output, output_size); + output = (char*)zeek::util::safe_realloc(output, output_size); memcpy(output + output_pos, b, count); output_pos += count; @@ -180,7 +180,7 @@ bool BinarySerializationFormat::Read(double* d, const char* tag) bool BinarySerializationFormat::Read(char* v, const char* tag) { bool ret = ReadData(v, 1); - DBG_LOG(zeek::DBG_SERIAL, "Read char %s [%s]", fmt_bytes(v, 1), tag); + DBG_LOG(zeek::DBG_SERIAL, "Read char %s [%s]", zeek::util::fmt_bytes(v, 1), tag); return ret; } @@ -218,7 +218,7 @@ bool BinarySerializationFormat::Read(char** str, int* len, const char* tag) *str = s; - DBG_LOG(zeek::DBG_SERIAL, "Read %d bytes |%s| [%s]", l, fmt_bytes(*str, l), tag); + DBG_LOG(zeek::DBG_SERIAL, "Read %d bytes |%s| [%s]", l, zeek::util::fmt_bytes(*str, l), tag); return true; } @@ -303,7 +303,7 @@ bool BinarySerializationFormat::Read(struct in6_addr* addr, const char* tag) bool BinarySerializationFormat::Write(char v, const char* tag) { - DBG_LOG(zeek::DBG_SERIAL, "Write char %s [%s]", fmt_bytes(&v, 1), tag); + DBG_LOG(zeek::DBG_SERIAL, "Write char %s [%s]", zeek::util::fmt_bytes(&v, 1), tag); return WriteData(&v, 1); } @@ -434,7 +434,7 @@ bool BinarySerializationFormat::WriteSeparator() bool BinarySerializationFormat::Write(const char* buf, int len, const char* tag) { - DBG_LOG(zeek::DBG_SERIAL, "Write bytes |%s| [%s]", fmt_bytes(buf, len), tag); + DBG_LOG(zeek::DBG_SERIAL, "Write bytes |%s| [%s]", zeek::util::fmt_bytes(buf, len), tag); uint32_t l = htonl(len); return WriteData(&l, sizeof(l)) && WriteData(buf, len); } diff --git a/src/Sessions.cc b/src/Sessions.cc index 85465423a4..18585ecf42 100644 --- a/src/Sessions.cc +++ b/src/Sessions.cc @@ -450,7 +450,7 @@ void NetSessions::DoNextPacket(double t, const zeek::Packet* pkt, const zeek::IP if ( gre_version != 0 && gre_version != 1 ) { Weird("unknown_gre_version", ip_hdr, encapsulation, - fmt("%d", gre_version)); + zeek::util::fmt("%d", gre_version)); return; } @@ -528,7 +528,7 @@ void NetSessions::DoNextPacket(double t, const zeek::Packet* pkt, const zeek::IP { // Enhanced GRE payload must be PPP. Weird("egre_protocol_type", ip_hdr, encapsulation, - fmt("%d", proto_typ)); + zeek::util::fmt("%d", proto_typ)); return; } } @@ -661,7 +661,7 @@ void NetSessions::DoNextPacket(double t, const zeek::Packet* pkt, const zeek::IP } default: - Weird("unknown_protocol", pkt, encapsulation, fmt("%d", proto)); + Weird("unknown_protocol", pkt, encapsulation, zeek::util::fmt("%d", proto)); return; } @@ -1331,7 +1331,7 @@ void NetSessions::Weird(const char* name, const zeek::Packet* pkt, dump_this_packet = true; if ( encap && encap->LastType() != BifEnum::Tunnel::NONE ) - zeek::reporter->Weird(fmt("%s_in_tunnel", name), addl); + zeek::reporter->Weird(zeek::util::fmt("%s_in_tunnel", name), addl); else zeek::reporter->Weird(name, addl); } @@ -1341,7 +1341,7 @@ void NetSessions::Weird(const char* name, const zeek::IP_Hdr* ip, { if ( encap && encap->LastType() != BifEnum::Tunnel::NONE ) zeek::reporter->Weird(ip->SrcAddr(), ip->DstAddr(), - fmt("%s_in_tunnel", name), addl); + zeek::util::fmt("%s_in_tunnel", name), addl); else zeek::reporter->Weird(ip->SrcAddr(), ip->DstAddr(), name, addl); } diff --git a/src/SmithWaterman.cc b/src/SmithWaterman.cc index 86e17fc8d6..b773283608 100644 --- a/src/SmithWaterman.cc +++ b/src/SmithWaterman.cc @@ -359,7 +359,7 @@ static void sw_collect_multiple(Substring::Vec* result, { if ( (*it2)->DoesCover(*it3) ) { - delete_each(new_al); + zeek::util::delete_each(new_al); delete new_al; new_al = nullptr; goto end_loop; @@ -367,7 +367,7 @@ static void sw_collect_multiple(Substring::Vec* result, if ( (*it3)->DoesCover(*it2) ) { - delete_each(old_al); + zeek::util::delete_each(old_al); delete old_al; *it = 0; goto end_loop; diff --git a/src/Stats.cc b/src/Stats.cc index 1c26bc9b5e..76d5e823e2 100644 --- a/src/Stats.cc +++ b/src/Stats.cc @@ -75,7 +75,7 @@ void ProfileLogger::Log() // Connections have been flushed already. return; - file->Write(fmt("%.06f ------------------------\n", zeek::net::network_time)); + file->Write(zeek::util::fmt("%.06f ------------------------\n", zeek::net::network_time)); // Do expensive profiling only occasionally. bool expensive = false; @@ -90,14 +90,14 @@ void ProfileLogger::Log() struct timeval tv_stime = r.ru_stime; uint64_t total, malloced; - get_memory_usage(&total, &malloced); + zeek::util::get_memory_usage(&total, &malloced); static unsigned int first_total = 0; static double first_rtime = 0; static double first_utime = 0; static double first_stime = 0; - double rtime = current_time(); + double rtime = zeek::util::current_time(); double utime = double(tv_utime.tv_sec) + double(tv_utime.tv_usec) / 1e6; double stime = double(tv_stime.tv_sec) + double(tv_stime.tv_usec) / 1e6; @@ -108,26 +108,26 @@ void ProfileLogger::Log() first_utime = utime; first_stime = stime; - file->Write(fmt("%.06f Command line: ", zeek::net::network_time )); + file->Write(zeek::util::fmt("%.06f Command line: ", zeek::net::network_time )); for ( int i = 0; i < bro_argc; i++ ) { file->Write(bro_argv[i]); file->Write(" "); } - file->Write(fmt("\n%.06f ------------------------\n", zeek::net::network_time)); + file->Write(zeek::util::fmt("\n%.06f ------------------------\n", zeek::net::network_time)); } - file->Write(fmt("%.06f Memory: total=%" PRId64 "K total_adj=%" PRId64 "K malloced: %" PRId64 "K\n", + file->Write(zeek::util::fmt("%.06f Memory: total=%" PRId64 "K total_adj=%" PRId64 "K malloced: %" PRId64 "K\n", zeek::net::network_time, total / 1024, (total - first_total) / 1024, malloced / 1024)); - file->Write(fmt("%.06f Run-time: user+sys=%.1f user=%.1f sys=%.1f real=%.1f\n", + file->Write(zeek::util::fmt("%.06f Run-time: user+sys=%.1f user=%.1f sys=%.1f real=%.1f\n", zeek::net::network_time, (utime + stime) - (first_utime + first_stime), utime - first_utime, stime - first_stime, rtime - first_rtime)); int conn_mem_use = expensive ? sessions->ConnectionMemoryUsage() : 0; - file->Write(fmt("%.06f Conns: total=%" PRIu64 " current=%" PRIu64 "/%" PRIi32 " mem=%" PRIi32 "K avg=%.1f table=%" PRIu32 "K connvals=%" PRIu32 "K\n", + file->Write(zeek::util::fmt("%.06f Conns: total=%" PRIu64 " current=%" PRIu64 "/%" PRIi32 " mem=%" PRIi32 "K avg=%.1f table=%" PRIu32 "K connvals=%" PRIu32 "K\n", zeek::net::network_time, Connection::TotalConnections(), Connection::CurrentConnections(), @@ -141,7 +141,7 @@ void ProfileLogger::Log() SessionStats s; sessions->GetStats(s); - file->Write(fmt("%.06f Conns: tcp=%zu/%zu udp=%zu/%zu icmp=%zu/%zu\n", + file->Write(zeek::util::fmt("%.06f Conns: tcp=%zu/%zu udp=%zu/%zu icmp=%zu/%zu\n", zeek::net::network_time, s.num_TCP_conns, s.max_TCP_conns, s.num_UDP_conns, s.max_UDP_conns, @@ -149,11 +149,11 @@ void ProfileLogger::Log() )); sessions->tcp_stats.PrintStats(file, - fmt("%.06f TCP-States:", zeek::net::network_time)); + zeek::util::fmt("%.06f TCP-States:", zeek::net::network_time)); // Alternatively, if you prefer more compact output... /* - file->Write(fmt("%.8f TCP-States: I=%d S=%d SA=%d SR=%d E=%d EF=%d ER=%d F=%d P=%d\n", + file->Write(zeek::util::fmt("%.8f TCP-States: I=%d S=%d SA=%d SR=%d E=%d EF=%d ER=%d F=%d P=%d\n", zeek::net::network_time, sessions->tcp_stats.StateInactive(), sessions->tcp_stats.StateRequest(), @@ -167,10 +167,10 @@ void ProfileLogger::Log() )); */ - file->Write(fmt("%.06f Connections expired due to inactivity: %" PRIu64 "\n", + file->Write(zeek::util::fmt("%.06f Connections expired due to inactivity: %" PRIu64 "\n", zeek::net::network_time, killed_by_inactivity)); - file->Write(fmt("%.06f Total reassembler data: %" PRIu64 "K\n", zeek::net::network_time, + file->Write(zeek::util::fmt("%.06f Total reassembler data: %" PRIu64 "K\n", zeek::net::network_time, Reassembler::TotalMemoryAllocation() / 1024)); // Signature engine. @@ -179,12 +179,12 @@ void ProfileLogger::Log() zeek::detail::RuleMatcher::Stats stats; zeek::detail::rule_matcher->GetStats(&stats); - file->Write(fmt("%06f RuleMatcher: matchers=%d nfa_states=%d dfa_states=%d " + file->Write(zeek::util::fmt("%06f RuleMatcher: matchers=%d nfa_states=%d dfa_states=%d " "ncomputed=%d mem=%dK\n", zeek::net::network_time, stats.matchers, stats.nfa_states, stats.dfa_states, stats.computed, stats.mem / 1024)); } - file->Write(fmt("%.06f Timers: current=%d max=%d lag=%.2fs\n", + file->Write(zeek::util::fmt("%.06f Timers: current=%d max=%d lag=%.2fs\n", zeek::net::network_time, zeek::detail::timer_mgr->Size(), zeek::detail::timer_mgr->PeakSize(), zeek::net::network_time - zeek::detail::timer_mgr->LastTimestamp())); @@ -192,7 +192,7 @@ void ProfileLogger::Log() zeek::detail::DNS_Mgr::Stats dstats; zeek::detail::dns_mgr->GetStats(&dstats); - file->Write(fmt("%.06f DNS_Mgr: requests=%lu succesful=%lu failed=%lu pending=%lu cached_hosts=%lu cached_addrs=%lu\n", + file->Write(zeek::util::fmt("%.06f DNS_Mgr: requests=%lu succesful=%lu failed=%lu pending=%lu cached_hosts=%lu cached_addrs=%lu\n", zeek::net::network_time, dstats.requests, dstats.successful, dstats.failed, dstats.pending, dstats.cached_hosts, dstats.cached_addresses)); @@ -200,25 +200,25 @@ void ProfileLogger::Log() zeek::detail::trigger::Manager::Stats tstats; zeek::detail::trigger_mgr->GetStats(&tstats); - file->Write(fmt("%.06f Triggers: total=%lu pending=%lu\n", zeek::net::network_time, tstats.total, tstats.pending)); + file->Write(zeek::util::fmt("%.06f Triggers: total=%lu pending=%lu\n", zeek::net::network_time, tstats.total, tstats.pending)); unsigned int* current_timers = zeek::detail::TimerMgr::CurrentTimers(); for ( int i = 0; i < zeek::detail::NUM_TIMER_TYPES; ++i ) { if ( current_timers[i] ) - file->Write(fmt("%.06f %s = %d\n", zeek::net::network_time, + file->Write(zeek::util::fmt("%.06f %s = %d\n", zeek::net::network_time, zeek::detail::timer_type_to_string(static_cast(i)), current_timers[i])); } - file->Write(fmt("%0.6f Threads: current=%d\n", zeek::net::network_time, zeek::thread_mgr->NumThreads())); + file->Write(zeek::util::fmt("%0.6f Threads: current=%d\n", zeek::net::network_time, zeek::thread_mgr->NumThreads())); const threading::Manager::msg_stats_list& thread_stats = zeek::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; - file->Write(fmt("%0.6f %-25s in=%" PRIu64 " out=%" PRIu64 " pending=%" PRIu64 "/%" PRIu64 + file->Write(zeek::util::fmt("%0.6f %-25s in=%" PRIu64 " out=%" PRIu64 " pending=%" PRIu64 "/%" PRIu64 " (#queue r/w: in=%" PRIu64 "/%" PRIu64 " out=%" PRIu64 "/%" PRIu64 ")" "\n", zeek::net::network_time, @@ -232,7 +232,7 @@ void ProfileLogger::Log() auto cs = broker_mgr->GetStatistics(); - file->Write(fmt("%0.6f Comm: peers=%zu stores=%zu " + file->Write(zeek::util::fmt("%0.6f Comm: peers=%zu stores=%zu " "pending_queries=%zu " "events_in=%zu events_out=%zu " "logs_in=%zu logs_out=%zu " @@ -253,7 +253,7 @@ void ProfileLogger::Log() int total_table_entries = 0; int total_table_rentries = 0; - file->Write(fmt("%.06f Global_sizes > 100k: %dK\n", + file->Write(zeek::util::fmt("%.06f Global_sizes > 100k: %dK\n", zeek::net::network_time, mem / 1024)); for ( const auto& global : globals ) @@ -294,12 +294,12 @@ void ProfileLogger::Log() if ( print ) { - file->Write(fmt("%.06f %s = %dK", + file->Write(zeek::util::fmt("%.06f %s = %dK", zeek::net::network_time, id->Name(), size / 1024)); if ( entries >= 0 ) - file->Write(fmt(" (%d/%d entries)\n", + file->Write(zeek::util::fmt(" (%d/%d entries)\n", entries, rentries)); else file->Write("\n"); @@ -307,9 +307,9 @@ void ProfileLogger::Log() } } - file->Write(fmt("%.06f Global_sizes total: %dK\n", + file->Write(zeek::util::fmt("%.06f Global_sizes total: %dK\n", zeek::net::network_time, mem / 1024)); - file->Write(fmt("%.06f Total number of table entries: %d/%d\n", + file->Write(zeek::util::fmt("%.06f Total number of table entries: %d/%d\n", zeek::net::network_time, total_table_entries, total_table_rentries)); } @@ -329,16 +329,16 @@ void ProfileLogger::SegmentProfile(const char* name, const zeek::detail::Locatio double dtime, int dmem) { if ( name ) - file->Write(fmt("%.06f segment-%s dt=%.06f dmem=%d\n", + file->Write(zeek::util::fmt("%.06f segment-%s dt=%.06f dmem=%d\n", zeek::net::network_time, name, dtime, dmem)); else if ( loc ) - file->Write(fmt("%.06f segment-%s:%d dt=%.06f dmem=%d\n", + file->Write(zeek::util::fmt("%.06f segment-%s:%d dt=%.06f dmem=%d\n", zeek::net::network_time, loc->filename ? loc->filename : "nofile", loc->first_line, dtime, dmem)); else - file->Write(fmt("%.06f segment-XXX dt=%.06f dmem=%d\n", + file->Write(zeek::util::fmt("%.06f segment-XXX dt=%.06f dmem=%d\n", zeek::net::network_time, dtime, dmem)); } @@ -442,7 +442,7 @@ void PacketProfiler::ProfilePkt(double t, unsigned int bytes) getrusage(RUSAGE_SELF, &res); gettimeofday(&ptimestamp, 0); - get_memory_usage(&last_mem, nullptr); + zeek::util::get_memory_usage(&last_mem, nullptr); last_Utime = res.ru_utime.tv_sec + res.ru_utime.tv_usec / 1e6; last_Stime = res.ru_stime.tv_sec + res.ru_stime.tv_usec / 1e6; last_Rtime = ptimestamp.tv_sec + ptimestamp.tv_usec / 1e6; @@ -466,14 +466,14 @@ void PacketProfiler::ProfilePkt(double t, unsigned int bytes) ptimestamp.tv_sec + ptimestamp.tv_usec / 1e6; uint64_t curr_mem; - get_memory_usage(&curr_mem, nullptr); + zeek::util::get_memory_usage(&curr_mem, nullptr); - file->Write(fmt("%.06f %.03f %" PRIu64 " %" PRIu64 " %.03f %.03f %.03f %" PRIu64 "\n", - t, time-last_timestamp, pkt_cnt, byte_cnt, - curr_Rtime - last_Rtime, - curr_Utime - last_Utime, - curr_Stime - last_Stime, - curr_mem - last_mem)); + file->Write(zeek::util::fmt("%.06f %.03f %" PRIu64 " %" PRIu64 " %.03f %.03f %.03f %" PRIu64 "\n", + t, time-last_timestamp, pkt_cnt, byte_cnt, + curr_Rtime - last_Rtime, + curr_Utime - last_Utime, + curr_Stime - last_Stime, + curr_mem - last_mem)); last_Utime = curr_Utime; last_Stime = curr_Stime; diff --git a/src/Stmt.cc b/src/Stmt.cc index 34e6cba8e2..af792b4491 100644 --- a/src/Stmt.cc +++ b/src/Stmt.cc @@ -143,7 +143,7 @@ void Stmt::AccessStats(ODesc* d) const if ( d->IncludeStats() ) { d->Add("(@"); - d->Add(last_access ? fmt_access_time(last_access) : ""); + d->Add(last_access ? zeek::util::fmt_access_time(last_access) : ""); d->Add(" #"); d->Add(access_count); d->Add(")"); diff --git a/src/Tag.cc b/src/Tag.cc index fc9036150f..a3741eac84 100644 --- a/src/Tag.cc +++ b/src/Tag.cc @@ -92,7 +92,7 @@ zeek::EnumVal* Tag::AsEnumVal(zeek::EnumType* etype) const std::string Tag::AsString() const { - return fmt("%" PRIu32 "/%" PRIu32, type, subtype); + return zeek::util::fmt("%" PRIu32 "/%" PRIu32, type, subtype); } } // namespace zeek diff --git a/src/Timer.cc b/src/Timer.cc index ce502fe5e9..bf3795efc9 100644 --- a/src/Timer.cc +++ b/src/Timer.cc @@ -97,7 +97,7 @@ void TimerMgr::Process() // move forward and the timers won't fire correctly. iosource::PktSrc* pkt_src = zeek::iosource_mgr->GetPktSrc(); if ( ! pkt_src || ! pkt_src->IsOpen() || zeek::net::reading_live || zeek::net::net_is_processing_suspended() ) - zeek::net::detail::net_update_time(current_time()); + zeek::net::detail::net_update_time(zeek::util::current_time()); // Just advance the timer manager based on the current network time. This won't actually // change the time, but will dispatch any timers that need dispatching. diff --git a/src/Trigger.cc b/src/Trigger.cc index 891024522a..a6f57108a8 100644 --- a/src/Trigger.cc +++ b/src/Trigger.cc @@ -313,7 +313,7 @@ bool Trigger::Eval() assert(trigger->attached == this); #ifdef DEBUG - const char* pname = copy_string(trigger->Name()); + const char* pname = zeek::util::copy_string(trigger->Name()); DBG_LOG(zeek::DBG_NOTIFIERS, "%s: trigger has parent %s, caching result", Name(), pname); delete [] pname; #endif @@ -366,7 +366,7 @@ void Trigger::Timeout() assert(trigger->attached == this); #ifdef DEBUG - const char* pname = copy_string(trigger->Name()); + const char* pname = zeek::util::copy_string(trigger->Name()); DBG_LOG(zeek::DBG_NOTIFIERS, "%s: trigger has parent %s, caching timeout result", Name(), pname); delete [] pname; #endif @@ -426,7 +426,7 @@ void Trigger::Attach(Trigger *trigger) assert(! trigger->delayed); #ifdef DEBUG - const char* pname = copy_string(trigger->Name()); + const char* pname = zeek::util::copy_string(trigger->Name()); DBG_LOG(zeek::DBG_NOTIFIERS, "%s: attaching to %s", Name(), pname); delete [] pname; #endif @@ -486,8 +486,8 @@ void Trigger::Modified(zeek::notifier::detail::Modifiable* m) const char* Trigger::Name() const { assert(location); - return fmt("%s:%d-%d", location->filename, - location->first_line, location->last_line); + return zeek::util::fmt("%s:%d-%d", location->filename, + location->first_line, location->last_line); } diff --git a/src/Type.cc b/src/Type.cc index 5fc412a0fa..5d650f5877 100644 --- a/src/Type.cc +++ b/src/Type.cc @@ -266,7 +266,7 @@ void Type::Describe(ODesc* d) const void Type::DescribeReST(ODesc* d, bool roles_only) const { - d->Add(fmt(":zeek:type:`%s`", type_name(Tag()))); + d->Add(zeek::util::fmt(":zeek:type:`%s`", type_name(Tag()))); } void Type::SetError() @@ -339,7 +339,7 @@ unsigned int TypeList::MemoryAllocation() const for ( const auto& t : types ) size += t->MemoryAllocation(); - size += pad_size(types.capacity() * sizeof(decltype(types)::value_type)); + size += zeek::util::pad_size(types.capacity() * sizeof(decltype(types)::value_type)); return Type::MemoryAllocation() + padded_sizeof(*this) - padded_sizeof(Type) @@ -553,8 +553,8 @@ FuncType::FuncType(RecordTypePtr arg_args, else if ( has_default_arg ) { - const char* err_str = fmt("required parameter '%s' must precede " - "default parameters", td->id); + const char* err_str = zeek::util::fmt("required parameter '%s' must precede " + "default parameters", td->id); args->Error(err_str); } @@ -621,8 +621,8 @@ bool FuncType::CheckArgs(const std::vector& args, if ( my_args.size() != args.size() ) { - Warn(fmt("Wrong number of arguments for function. Expected %zu, got %zu.", - args.size(), my_args.size())); + Warn(zeek::util::fmt("Wrong number of arguments for function. Expected %zu, got %zu.", + args.size(), my_args.size())); return false; } @@ -631,8 +631,8 @@ bool FuncType::CheckArgs(const std::vector& args, for ( size_t i = 0; i < my_args.size(); ++i ) if ( ! same_type(args[i], my_args[i], is_init) ) { - Warn(fmt("Type mismatch in function argument #%zu. Expected %s, got %s.", - i, type_name(args[i]->Tag()), type_name(my_args[i]->Tag()))); + Warn(zeek::util::fmt("Type mismatch in function argument #%zu. Expected %s, got %s.", + i, type_name(args[i]->Tag()), type_name(my_args[i]->Tag()))); success = false; } @@ -719,7 +719,7 @@ std::optional FuncType::FindPrototype(const RecordType& arg const auto& desired_type = args.GetFieldType(i); if ( ! same_type(ptype, desired_type) || - ! streq(args.FieldName(i), p.args->FieldName(i)) ) + ! zeek::util::streq(args.FieldName(i), p.args->FieldName(i)) ) { matched = false; break; @@ -744,7 +744,7 @@ TypeDecl::TypeDecl(const TypeDecl& other) type = other.type; attrs = other.attrs; - id = copy_string(other.id); + id = zeek::util::copy_string(other.id); } TypeDecl::~TypeDecl() @@ -821,7 +821,7 @@ int RecordType::FieldOffset(const char* field) const loop_over_list(*types, i) { TypeDecl* td = (*types)[i]; - if ( streq(td->id, field) ) + if ( zeek::util::streq(td->id, field) ) return i; } @@ -1045,7 +1045,7 @@ void RecordType::DescribeFieldsReST(ODesc* d, bool func_args) const d->Add(""); else { - if ( num_fields == 1 && streq(td->id, "va_args") && + if ( num_fields == 1 && zeek::util::streq(td->id, "va_args") && td->type->Tag() == TYPE_ANY ) // This was a BIF using variable argument list d->Add("..."); @@ -1122,11 +1122,11 @@ string RecordType::GetFieldDeprecationWarning(int field, bool has_check) const result = deprecation->DeprecationMessage(); if ( result.empty() ) - return fmt("deprecated (%s%s$%s)", GetName().c_str(), has_check ? "?" : "", - FieldName(field)); + return zeek::util::fmt("deprecated (%s%s$%s)", GetName().c_str(), has_check ? "?" : "", + FieldName(field)); else - return fmt("deprecated (%s%s$%s): %s", GetName().c_str(), has_check ? "?" : "", - FieldName(field), result.c_str()); + return zeek::util::fmt("deprecated (%s%s$%s): %s", GetName().c_str(), has_check ? "?" : "", + FieldName(field), result.c_str()); } return ""; @@ -1182,7 +1182,7 @@ void OpaqueType::Describe(ODesc* d) const void OpaqueType::DescribeReST(ODesc* d, bool roles_only) const { - d->Add(fmt(":zeek:type:`%s` of %s", type_name(Tag()), name.c_str())); + d->Add(zeek::util::fmt(":zeek:type:`%s` of %s", type_name(Tag()), name.c_str())); } EnumType::EnumType(const string& name) @@ -1373,9 +1373,9 @@ void EnumType::DescribeReST(ODesc* d, bool roles_only) const d->PushIndent(); if ( roles_only ) - d->Add(fmt(":zeek:enum:`%s`", it->second.c_str())); + d->Add(zeek::util::fmt(":zeek:enum:`%s`", it->second.c_str())); else - d->Add(fmt(".. zeek:enum:: %s %s", it->second.c_str(), GetName().c_str())); + d->Add(zeek::util::fmt(".. zeek:enum:: %s %s", it->second.c_str(), GetName().c_str())); using zeekygen::IdentifierInfo; IdentifierInfo* doc = zeekygen_mgr->GetIdentifierInfo(it->second); @@ -1491,12 +1491,12 @@ void VectorType::Describe(ODesc* d) const void VectorType::DescribeReST(ODesc* d, bool roles_only) const { - d->Add(fmt(":zeek:type:`%s` of ", type_name(Tag()))); + d->Add(zeek::util::fmt(":zeek:type:`%s` of ", type_name(Tag()))); if ( yield_type->GetName().empty() ) yield_type->DescribeReST(d, roles_only); else - d->Add(fmt(":zeek:type:`%s`", yield_type->GetName().c_str())); + d->Add(zeek::util::fmt(":zeek:type:`%s`", yield_type->GetName().c_str())); } // Returns true if t1 is initialization-compatible with t2 (i.e., if an @@ -1628,7 +1628,7 @@ bool same_type(const Type& arg_t1, const Type& arg_t2, const TypeDecl* td1 = rt1->FieldDecl(i); const TypeDecl* td2 = rt2->FieldDecl(i); - if ( (match_record_field_names && ! streq(td1->id, td2->id)) || + if ( (match_record_field_names && ! zeek::util::streq(td1->id, td2->id)) || ! same_type(td1->type, td2->type, is_init, match_record_field_names) ) return false; } @@ -1856,8 +1856,8 @@ TypePtr merge_types(const TypePtr& arg_t1, // there creating clones of the type, so safer to compare name. if ( t1->GetName() != t2->GetName() ) { - std::string msg = fmt("incompatible enum types: '%s' and '%s'", - t1->GetName().data(), t2->GetName().data()); + std::string msg = zeek::util::fmt("incompatible enum types: '%s' and '%s'", + t1->GetName().data(), t2->GetName().data()); t1->Error(msg.data(), t2); return nullptr; @@ -1875,10 +1875,10 @@ TypePtr merge_types(const TypePtr& arg_t1, // actually see those changes from the redef. return id->GetType(); - std::string msg = fmt("incompatible enum types: '%s' and '%s'" - " ('%s' enum type ID is invalid)", - t1->GetName().data(), t2->GetName().data(), - t1->GetName().data()); + std::string msg = zeek::util::fmt("incompatible enum types: '%s' and '%s'" + " ('%s' enum type ID is invalid)", + t1->GetName().data(), t2->GetName().data(), + t1->GetName().data()); t1->Error(msg.data(), t2); return nullptr; } @@ -1967,14 +1967,14 @@ TypePtr merge_types(const TypePtr& arg_t1, const TypeDecl* td2 = rt2->FieldDecl(i); auto tdl3_i = merge_types(td1->type, td2->type); - if ( ! streq(td1->id, td2->id) || ! tdl3_i ) + if ( ! zeek::util::streq(td1->id, td2->id) || ! tdl3_i ) { t1->Error("incompatible record fields", t2); delete tdl3; return nullptr; } - tdl3->push_back(new TypeDecl(copy_string(td1->id), std::move(tdl3_i))); + tdl3->push_back(new TypeDecl(zeek::util::copy_string(td1->id), std::move(tdl3_i))); } return zeek::make_intrusive(tdl3); diff --git a/src/UID.cc b/src/UID.cc index 96add1c377..fe2de22de9 100644 --- a/src/UID.cc +++ b/src/UID.cc @@ -24,7 +24,7 @@ void UID::Set(bro_uint_t bits, const uint64_t* v, size_t n) size_t size = res.rem ? res.quot + 1 : res.quot; for ( size_t i = 0; i < size; ++i ) - uid[i] = v && i < n ? v[i] : calculate_unique_id(); + uid[i] = v && i < n ? v[i] : zeek::util::calculate_unique_id(); if ( res.rem ) uid[0] >>= 64 - res.rem; @@ -37,7 +37,7 @@ std::string UID::Base62(std::string prefix) const char tmp[sizeof(uid) * 8 + 1]; // enough for even binary representation for ( size_t i = 0; i < BRO_UID_LEN; ++i ) - prefix.append(uitoa_n(uid[i], tmp, sizeof(tmp), 62)); + prefix.append(zeek::util::uitoa_n(uid[i], tmp, sizeof(tmp), 62)); return prefix; } diff --git a/src/Val.cc b/src/Val.cc index 4063b98552..f54b3eb06e 100644 --- a/src/Val.cc +++ b/src/Val.cc @@ -421,7 +421,7 @@ detail::ID* Val::GetID() const void Val::SetID(detail::ID* id) { delete [] bound_id; - bound_id = id ? copy_string(id->Name()) : nullptr; + bound_id = id ? zeek::util::copy_string(id->Name()) : nullptr; } #endif @@ -558,7 +558,7 @@ static void BuildJSON(zeek::threading::formatter::JSON::NullDoubleWriter& writer ODesc d; d.SetStyle(RAW_STYLE); val->Describe(&d); - writer.String(json_escape_utf8(string(reinterpret_cast(d.Bytes()), d.Len()))); + writer.String(zeek::util::json_escape_utf8(std::string(reinterpret_cast(d.Bytes()), d.Len()))); break; } @@ -1331,7 +1331,7 @@ unsigned int ListVal::MemoryAllocation() const for ( const auto& val : vals ) size += val->MemoryAllocation(); - size += pad_size(vals.capacity() * sizeof(decltype(vals)::value_type)); + size += zeek::util::pad_size(vals.capacity() * sizeof(decltype(vals)::value_type)); return size + padded_sizeof(*this) + type->MemoryAllocation(); } @@ -2445,7 +2445,7 @@ void TableVal::Describe(ODesc* d) const if ( d->IsReadable() && ! d->IsShort() && d->IncludeStats() ) { d->Add(" @"); - d->Add(fmt_access_time(v->ExpireAccessTime())); + d->Add(zeek::util::fmt_access_time(v->ExpireAccessTime())); } } @@ -3174,7 +3174,7 @@ unsigned int RecordVal::MemoryAllocation() const size += v->MemoryAllocation(); } - size += pad_size(vl.capacity() * sizeof(ValPtr)); + size += zeek::util::pad_size(vl.capacity() * sizeof(ValPtr)); size += padded_sizeof(vl); return size + padded_sizeof(*this); } diff --git a/src/Var.cc b/src/Var.cc index fdecd52fd3..8c4395b5ea 100644 --- a/src/Var.cc +++ b/src/Var.cc @@ -84,7 +84,7 @@ static bool add_prototype(const zeek::detail::IDPtr& id, zeek::Type* t, if ( alt_args->FieldDecl(i)->attrs ) { - alt_ft->Error(fmt("alternate function prototype arguments may not have attributes: arg '%s'", field), canon_ft); + alt_ft->Error(zeek::util::fmt("alternate function prototype arguments may not have attributes: arg '%s'", field), canon_ft); return false; } @@ -92,7 +92,7 @@ static bool add_prototype(const zeek::detail::IDPtr& id, zeek::Type* t, if ( o < 0 ) { - alt_ft->Error(fmt("alternate function prototype arg '%s' not found in canonical prototype", field), canon_ft); + alt_ft->Error(zeek::util::fmt("alternate function prototype arg '%s' not found in canonical prototype", field), canon_ft); return false; } @@ -469,12 +469,12 @@ static std::optional func_type_check(const zeek::Func auto msg = ad->DeprecationMessage(); if ( msg.empty() ) - impl->Warn(fmt("use of deprecated parameter '%s'", - rval->args->FieldName(i)), - decl, true); + impl->Warn(zeek::util::fmt("use of deprecated parameter '%s'", + rval->args->FieldName(i)), + decl, true); else - impl->Warn(fmt("use of deprecated parameter '%s': %s", - rval->args->FieldName(i), msg.data()), + impl->Warn(zeek::util::fmt("use of deprecated parameter '%s': %s", + rval->args->FieldName(i), msg.data()), decl, true); } @@ -553,11 +553,11 @@ void begin_func(zeek::detail::IDPtr id, const char* module_name, if ( prototype->deprecated ) { if ( prototype->deprecation_msg.empty() ) - t->Warn(fmt("use of deprecated '%s' prototype", id->Name()), + t->Warn(zeek::util::fmt("use of deprecated '%s' prototype", id->Name()), prototype->args.get(), true); else - t->Warn(fmt("use of deprecated '%s' prototype: %s", - id->Name(), prototype->deprecation_msg.data()), + t->Warn(zeek::util::fmt("use of deprecated '%s' prototype: %s", + id->Name(), prototype->deprecation_msg.data()), prototype->args.get(), true); } } @@ -648,7 +648,7 @@ void begin_func(zeek::detail::IDPtr id, const char* module_name, if ( hide ) // Note the illegal '-' in hidden name implies we haven't // clobbered any local variable names. - local_name = fmt("%s-hidden", local_name); + local_name = zeek::util::fmt("%s-hidden", local_name); arg_id = zeek::detail::install_ID(local_name, module_name, false, false); arg_id->SetType(arg_i->type); diff --git a/src/ZeekString.cc b/src/ZeekString.cc index b261b4d626..27d03090f2 100644 --- a/src/ZeekString.cc +++ b/src/ZeekString.cc @@ -279,7 +279,7 @@ void String::ToUpper() unsigned int String::MemoryAllocation() const { - return padded_sizeof(*this) + pad_size(n + final_NUL); + return padded_sizeof(*this) + zeek::util::pad_size(n + final_NUL); } String* String::GetSubstring(int start, int len) const @@ -296,7 +296,7 @@ String* String::GetSubstring(int start, int len) const int String::FindSubstring(const String* s) const { - return strstr_n(n, b, s->Len(), s->Bytes()); + return zeek::util::strstr_n(n, b, s->Len(), s->Bytes()); } String::Vec* String::Split(const String::IdxVec& indices) const diff --git a/src/analyzer/Analyzer.cc b/src/analyzer/Analyzer.cc index b24dc88ae4..6d51786523 100644 --- a/src/analyzer/Analyzer.cc +++ b/src/analyzer/Analyzer.cc @@ -232,7 +232,7 @@ void Analyzer::NextPacket(int len, const u_char* data, bool is_orig, uint64_t se } catch ( binpac::Exception const &e ) { - ProtocolViolation(fmt("Binpac exception: %s", e.c_msg())); + ProtocolViolation(zeek::util::fmt("Binpac exception: %s", e.c_msg())); } } } @@ -255,7 +255,7 @@ void Analyzer::NextStream(int len, const u_char* data, bool is_orig) } catch ( binpac::Exception const &e ) { - ProtocolViolation(fmt("Binpac exception: %s", e.c_msg())); + ProtocolViolation(zeek::util::fmt("Binpac exception: %s", e.c_msg())); } } } @@ -278,7 +278,7 @@ void Analyzer::NextUndelivered(uint64_t seq, int len, bool is_orig) } catch ( binpac::Exception const &e ) { - ProtocolViolation(fmt("Binpac exception: %s", e.c_msg())); + ProtocolViolation(zeek::util::fmt("Binpac exception: %s", e.c_msg())); } } } @@ -648,14 +648,14 @@ void Analyzer::DeliverPacket(int len, const u_char* data, bool is_orig, { DBG_LOG(zeek::DBG_ANALYZER, "%s DeliverPacket(%d, %s, %" PRIu64", %p, %d) [%s%s]", fmt_analyzer(this).c_str(), len, is_orig ? "T" : "F", seq, ip, caplen, - fmt_bytes((const char*) data, min(40, len)), len > 40 ? "..." : ""); + zeek::util::fmt_bytes((const char*) data, min(40, len)), len > 40 ? "..." : ""); } void Analyzer::DeliverStream(int len, const u_char* data, bool is_orig) { DBG_LOG(zeek::DBG_ANALYZER, "%s DeliverStream(%d, %s) [%s%s]", fmt_analyzer(this).c_str(), len, is_orig ? "T" : "F", - fmt_bytes((const char*) data, min(40, len)), len > 40 ? "..." : ""); + zeek::util::fmt_bytes((const char*) data, min(40, len)), len > 40 ? "..." : ""); } void Analyzer::Undelivered(uint64_t seq, int len, bool is_orig) @@ -714,10 +714,10 @@ void Analyzer::ProtocolViolation(const char* reason, const char* data, int len) if ( data && len ) { - const char *tmp = copy_string(reason); - r = zeek::make_intrusive(fmt("%s [%s%s]", tmp, - fmt_bytes(data, min(40, len)), - len > 40 ? "..." : "")); + const char *tmp = zeek::util::copy_string(reason); + r = zeek::make_intrusive(zeek::util::fmt("%s [%s%s]", tmp, + zeek::util::fmt_bytes(data, min(40, len)), + len > 40 ? "..." : "")); delete [] tmp; } else diff --git a/src/analyzer/Analyzer.h b/src/analyzer/Analyzer.h index 938d3b3f0d..62aa4a6695 100644 --- a/src/analyzer/Analyzer.h +++ b/src/analyzer/Analyzer.h @@ -637,7 +637,7 @@ protected: * and ID. */ static std::string fmt_analyzer(const Analyzer* a) - { return std::string(a->GetAnalyzerName()) + fmt("[%d]", a->GetID()); } + { return std::string(a->GetAnalyzerName()) + zeek::util::fmt("[%d]", a->GetID()); } /** * Associates a connection with this analyzer. Must be called if diff --git a/src/analyzer/protocol/ayiya/AYIYA.cc b/src/analyzer/protocol/ayiya/AYIYA.cc index 7bc78fa050..901b8392a6 100644 --- a/src/analyzer/protocol/ayiya/AYIYA.cc +++ b/src/analyzer/protocol/ayiya/AYIYA.cc @@ -31,7 +31,7 @@ void AYIYA_Analyzer::DeliverPacket(int len, const u_char* data, bool orig, uint6 } catch ( const binpac::Exception& e ) { - ProtocolViolation(fmt("Binpac exception: %s", e.c_msg())); + ProtocolViolation(zeek::util::fmt("Binpac exception: %s", e.c_msg())); } } diff --git a/src/analyzer/protocol/bittorrent/BitTorrent.cc b/src/analyzer/protocol/bittorrent/BitTorrent.cc index 9f4a0cce1a..789ef6913a 100644 --- a/src/analyzer/protocol/bittorrent/BitTorrent.cc +++ b/src/analyzer/protocol/bittorrent/BitTorrent.cc @@ -59,8 +59,8 @@ void BitTorrent_Analyzer::DeliverStream(int len, const u_char* data, bool orig) Parent()->RemoveChildAnalyzer(this); else { - DeliverWeird(fmt("Stopping BitTorrent analysis: protocol violation (%s)", - e.c_msg()), orig); + DeliverWeird(zeek::util::fmt("Stopping BitTorrent analysis: protocol violation (%s)", + e.c_msg()), orig); this_stop = true; if ( stop_orig && stop_resp ) ProtocolViolation("BitTorrent: content gap and/or protocol violation"); diff --git a/src/analyzer/protocol/bittorrent/BitTorrentTracker.cc b/src/analyzer/protocol/bittorrent/BitTorrentTracker.cc index 2dc3bd7293..34297178d7 100644 --- a/src/analyzer/protocol/bittorrent/BitTorrentTracker.cc +++ b/src/analyzer/protocol/bittorrent/BitTorrentTracker.cc @@ -322,7 +322,7 @@ bool BitTorrentTracker_Analyzer::ParseRequest(char* line) case detail::BTT_REQ_DONE: if ( *line ) { - auto msg = fmt("Got post request data: %s\n", line); + auto msg = zeek::util::fmt("Got post request data: %s\n", line); Weird("bittorrent_tracker_data_post_request", msg); DeliverWeird(msg, true); } diff --git a/src/analyzer/protocol/bittorrent/bittorrent-analyzer.pac b/src/analyzer/protocol/bittorrent/bittorrent-analyzer.pac index 456fbeaaa5..8a30c93e4a 100644 --- a/src/analyzer/protocol/bittorrent/bittorrent-analyzer.pac +++ b/src/analyzer/protocol/bittorrent/bittorrent-analyzer.pac @@ -49,7 +49,7 @@ flow BitTorrent_Flow(is_orig: bool) { function validate_message_length(len: uint32): bool %{ if ( len > MSGLEN_LIMIT ) - throw Exception(fmt("message length prefix exceeds limit: %u > %u", + throw Exception(zeek::util::fmt("message length prefix exceeds limit: %u > %u", len, MSGLEN_LIMIT)); return true; %} diff --git a/src/analyzer/protocol/dce-rpc/DCE_RPC.cc b/src/analyzer/protocol/dce-rpc/DCE_RPC.cc index 52c8ffb070..f01983880b 100644 --- a/src/analyzer/protocol/dce-rpc/DCE_RPC.cc +++ b/src/analyzer/protocol/dce-rpc/DCE_RPC.cc @@ -61,7 +61,7 @@ void DCE_RPC_Analyzer::DeliverStream(int len, const u_char* data, bool orig) } catch ( const binpac::Exception& e ) { - ProtocolViolation(fmt("Binpac exception: %s", e.c_msg())); + ProtocolViolation(zeek::util::fmt("Binpac exception: %s", e.c_msg())); } } diff --git a/src/analyzer/protocol/dce-rpc/dce_rpc-auth.pac b/src/analyzer/protocol/dce-rpc/dce_rpc-auth.pac index 7175304349..1aa845156e 100644 --- a/src/analyzer/protocol/dce-rpc/dce_rpc-auth.pac +++ b/src/analyzer/protocol/dce-rpc/dce_rpc-auth.pac @@ -43,7 +43,7 @@ refine connection DCE_RPC_Conn += { ntlm->DeliverStream(${auth.blob}.length(), ${auth.blob}.begin(), is_orig); break; default: - bro_analyzer()->Weird("unknown_dce_rpc_auth_type", fmt("%d", ${auth.type})); + bro_analyzer()->Weird("unknown_dce_rpc_auth_type", zeek::util::fmt("%d", ${auth.type})); break; } diff --git a/src/analyzer/protocol/dhcp/DHCP.cc b/src/analyzer/protocol/dhcp/DHCP.cc index 6f945125c7..0371a0e4dc 100644 --- a/src/analyzer/protocol/dhcp/DHCP.cc +++ b/src/analyzer/protocol/dhcp/DHCP.cc @@ -32,7 +32,7 @@ void DHCP_Analyzer::DeliverPacket(int len, const u_char* data, } catch ( const binpac::Exception& e ) { - ProtocolViolation(fmt("Binpac exception: %s", e.c_msg())); + ProtocolViolation(zeek::util::fmt("Binpac exception: %s", e.c_msg())); } } diff --git a/src/analyzer/protocol/dhcp/dhcp-analyzer.pac b/src/analyzer/protocol/dhcp/dhcp-analyzer.pac index fe6c893971..54dc969565 100644 --- a/src/analyzer/protocol/dhcp/dhcp-analyzer.pac +++ b/src/analyzer/protocol/dhcp/dhcp-analyzer.pac @@ -44,7 +44,7 @@ refine flow DHCP_Flow += { // the message options. if ( ${msg.cookie} != 0x63825363 ) { - connection()->bro_analyzer()->ProtocolViolation(fmt("bad cookie (%d)", ${msg.cookie})); + connection()->bro_analyzer()->ProtocolViolation(zeek::util::fmt("bad cookie (%d)", ${msg.cookie})); return false; } diff --git a/src/analyzer/protocol/dnp3/DNP3.cc b/src/analyzer/protocol/dnp3/DNP3.cc index 48e8d82943..1f11cb6406 100644 --- a/src/analyzer/protocol/dnp3/DNP3.cc +++ b/src/analyzer/protocol/dnp3/DNP3.cc @@ -350,7 +350,7 @@ bool DNP3_Base::CheckCRC(int len, const u_char* data, const u_char* crc16, const if ( crc16[0] == (crc & 0xff) && crc16[1] == (crc & 0xff00) >> 8 ) return true; - analyzer->Weird(fmt("dnp3_corrupt_%s_checksum", where)); + analyzer->Weird(zeek::util::fmt("dnp3_corrupt_%s_checksum", where)); return false; } diff --git a/src/analyzer/protocol/dns/DNS.cc b/src/analyzer/protocol/dns/DNS.cc index be1ac96f91..7fa206d27c 100644 --- a/src/analyzer/protocol/dns/DNS.cc +++ b/src/analyzer/protocol/dns/DNS.cc @@ -352,7 +352,7 @@ bool DNS_Interpreter::ParseAnswer(detail::DNS_MsgInfo* msg, msg->BuildAnswerVal() ); - analyzer->Weird("DNS_RR_unknown_type", fmt("%d", msg->atype)); + analyzer->Weird("DNS_RR_unknown_type", zeek::util::fmt("%d", msg->atype)); data += rdlength; len -= rdlength; status = true; @@ -980,7 +980,7 @@ bool DNS_Interpreter::ParseRR_RRSIG(detail::DNS_MsgInfo* msg, switch ( dsa ) { case detail::RSA_MD5: - analyzer->Weird("DNSSEC_RRSIG_NotRecommended_ZoneSignAlgo", fmt("%d", algo)); + analyzer->Weird("DNSSEC_RRSIG_NotRecommended_ZoneSignAlgo", zeek::util::fmt("%d", algo)); break; case detail::Diffie_Hellman: break; @@ -1005,16 +1005,16 @@ bool DNS_Interpreter::ParseRR_RRSIG(detail::DNS_MsgInfo* msg, case detail::ECDSA_curveP384withSHA384: break; case detail::Indirect: - analyzer->Weird("DNSSEC_RRSIG_Indirect_ZoneSignAlgo", fmt("%d", algo)); + analyzer->Weird("DNSSEC_RRSIG_Indirect_ZoneSignAlgo", zeek::util::fmt("%d", algo)); break; case detail::PrivateDNS: - analyzer->Weird("DNSSEC_RRSIG_PrivateDNS_ZoneSignAlgo", fmt("%d", algo)); + analyzer->Weird("DNSSEC_RRSIG_PrivateDNS_ZoneSignAlgo", zeek::util::fmt("%d", algo)); break; case detail::PrivateOID: - analyzer->Weird("DNSSEC_RRSIG_PrivateOID_ZoneSignAlgo", fmt("%d", algo)); + analyzer->Weird("DNSSEC_RRSIG_PrivateOID_ZoneSignAlgo", zeek::util::fmt("%d", algo)); break; default: - analyzer->Weird("DNSSEC_RRSIG_unknown_ZoneSignAlgo", fmt("%d", algo)); + analyzer->Weird("DNSSEC_RRSIG_unknown_ZoneSignAlgo", zeek::util::fmt("%d", algo)); break; } @@ -1069,18 +1069,18 @@ bool DNS_Interpreter::ParseRR_DNSKEY(detail::DNS_MsgInfo* msg, // flags bit 8: revoked // flags bit 15: Secure Entry Point, key signing key if ( (dflags & 0xfe7e) != 0 ) - analyzer->Weird("DNSSEC_DNSKEY_Invalid_Flag", fmt("%d", dflags)); + analyzer->Weird("DNSSEC_DNSKEY_Invalid_Flag", zeek::util::fmt("%d", dflags)); // flags bit 7, 8, and 15 all set if ( (dflags & 0x0181) == 0x0181 ) - analyzer->Weird("DNSSEC_DNSKEY_Revoked_KSK", fmt("%d", dflags)); + analyzer->Weird("DNSSEC_DNSKEY_Revoked_KSK", zeek::util::fmt("%d", dflags)); if ( dprotocol != 3 ) - analyzer->Weird("DNSSEC_DNSKEY_Invalid_Protocol", fmt("%d", dprotocol)); + analyzer->Weird("DNSSEC_DNSKEY_Invalid_Protocol", zeek::util::fmt("%d", dprotocol)); switch ( dsa ) { case detail::RSA_MD5: - analyzer->Weird("DNSSEC_DNSKEY_NotRecommended_ZoneSignAlgo", fmt("%d", dalgorithm)); + analyzer->Weird("DNSSEC_DNSKEY_NotRecommended_ZoneSignAlgo", zeek::util::fmt("%d", dalgorithm)); break; case detail::Diffie_Hellman: break; @@ -1105,16 +1105,16 @@ bool DNS_Interpreter::ParseRR_DNSKEY(detail::DNS_MsgInfo* msg, case detail::ECDSA_curveP384withSHA384: break; case detail::Indirect: - analyzer->Weird("DNSSEC_DNSKEY_Indirect_ZoneSignAlgo", fmt("%d", dalgorithm)); + analyzer->Weird("DNSSEC_DNSKEY_Indirect_ZoneSignAlgo", zeek::util::fmt("%d", dalgorithm)); break; case detail::PrivateDNS: - analyzer->Weird("DNSSEC_DNSKEY_PrivateDNS_ZoneSignAlgo", fmt("%d", dalgorithm)); + analyzer->Weird("DNSSEC_DNSKEY_PrivateDNS_ZoneSignAlgo", zeek::util::fmt("%d", dalgorithm)); break; case detail::PrivateOID: - analyzer->Weird("DNSSEC_DNSKEY_PrivateOID_ZoneSignAlgo", fmt("%d", dalgorithm)); + analyzer->Weird("DNSSEC_DNSKEY_PrivateOID_ZoneSignAlgo", zeek::util::fmt("%d", dalgorithm)); break; default: - analyzer->Weird("DNSSEC_DNSKEY_unknown_ZoneSignAlgo", fmt("%d", dalgorithm)); + analyzer->Weird("DNSSEC_DNSKEY_unknown_ZoneSignAlgo", zeek::util::fmt("%d", dalgorithm)); break; } @@ -1168,7 +1168,7 @@ bool DNS_Interpreter::ParseRR_NSEC(detail::DNS_MsgInfo* msg, if ( bmlen == 0 ) { - analyzer->Weird("DNSSEC_NSEC_bitmapLen0", fmt("%d", win_blck)); + analyzer->Weird("DNSSEC_NSEC_bitmapLen0", zeek::util::fmt("%d", win_blck)); break; } @@ -1243,7 +1243,7 @@ bool DNS_Interpreter::ParseRR_NSEC3(detail::DNS_MsgInfo* msg, if ( bmlen == 0 ) { - analyzer->Weird("DNSSEC_NSEC3_bitmapLen0", fmt("%d", win_blck)); + analyzer->Weird("DNSSEC_NSEC3_bitmapLen0", zeek::util::fmt("%d", win_blck)); break; } @@ -1307,10 +1307,10 @@ bool DNS_Interpreter::ParseRR_DS(detail::DNS_MsgInfo* msg, case detail::SHA384: break; case detail::reserved: - analyzer->Weird("DNSSEC_DS_ResrevedDigestType", fmt("%d", ds_dtype)); + analyzer->Weird("DNSSEC_DS_ResrevedDigestType", zeek::util::fmt("%d", ds_dtype)); break; default: - analyzer->Weird("DNSSEC_DS_unknown_DigestType", fmt("%d", ds_dtype)); + analyzer->Weird("DNSSEC_DS_unknown_DigestType", zeek::util::fmt("%d", ds_dtype)); break; } @@ -1856,13 +1856,13 @@ void Contents_DNS::ProcessChunk(int& len, const u_char*& data, bool orig) if ( buf_len < msg_size ) { buf_len = msg_size; - msg_buf = (u_char*) safe_realloc((void*) msg_buf, buf_len); + msg_buf = (u_char*) zeek::util::safe_realloc((void*) msg_buf, buf_len); } } else { buf_len = msg_size; - msg_buf = (u_char*) safe_malloc(buf_len); + msg_buf = (u_char*) zeek::util::safe_malloc(buf_len); } ++data; diff --git a/src/analyzer/protocol/finger/Finger.cc b/src/analyzer/protocol/finger/Finger.cc index 7325477af8..86ff1e4060 100644 --- a/src/analyzer/protocol/finger/Finger.cc +++ b/src/analyzer/protocol/finger/Finger.cc @@ -50,12 +50,12 @@ void Finger_Analyzer::DeliverStream(int length, const u_char* data, bool is_orig if ( ! finger_request ) return; - line = skip_whitespace(line, end_of_line); + line = zeek::util::skip_whitespace(line, end_of_line); // Check for /W. int long_cnt = (line + 2 <= end_of_line && line[0] == '/' && toupper(line[1]) == 'W'); if ( long_cnt ) - line = skip_whitespace(line+2, end_of_line); + line = zeek::util::skip_whitespace(line+2, end_of_line); assert(line <= end_of_line); size_t n = end_of_line >= line ? end_of_line - line : 0; // just to be sure if assertions aren't on. diff --git a/src/analyzer/protocol/ftp/FTP.cc b/src/analyzer/protocol/ftp/FTP.cc index 0f33df249a..d64108bd93 100644 --- a/src/analyzer/protocol/ftp/FTP.cc +++ b/src/analyzer/protocol/ftp/FTP.cc @@ -84,9 +84,9 @@ void FTP_Analyzer::DeliverStream(int length, const u_char* data, bool orig) const char* cmd; zeek::StringVal* cmd_str; - line = skip_whitespace(line, end_of_line); - get_word(end_of_line - line, line, cmd_len, cmd); - line = skip_whitespace(line + cmd_len, end_of_line); + line = zeek::util::skip_whitespace(line, end_of_line); + zeek::util::get_word(end_of_line - line, line, cmd_len, cmd); + line = zeek::util::skip_whitespace(line + cmd_len, end_of_line); if ( cmd_len == 0 ) { @@ -125,7 +125,7 @@ void FTP_Analyzer::DeliverStream(int length, const u_char* data, bool orig) length > 3 && line[3] == ' ' ) { // This is the end of the reply. - line = skip_whitespace(line + 3, end_of_line); + line = zeek::util::skip_whitespace(line + 3, end_of_line); pending_reply = 0; cont_resp = 0; } @@ -140,7 +140,7 @@ void FTP_Analyzer::DeliverStream(int length, const u_char* data, bool orig) if ( reply_code > 0 && length > 3 && line[3] == '-' ) { // a continued reply pending_reply = reply_code; - line = skip_whitespace(line + 4, end_of_line); + line = zeek::util::skip_whitespace(line + 4, end_of_line); cont_resp = 1; } else @@ -152,7 +152,7 @@ void FTP_Analyzer::DeliverStream(int length, const u_char* data, bool orig) (const char*) data, length); if ( line < end_of_line ) - line = skip_whitespace(line, end_of_line); + line = zeek::util::skip_whitespace(line, end_of_line); else line = end_of_line; @@ -210,12 +210,12 @@ void FTP_ADAT_Analyzer::DeliverStream(int len, const u_char* data, bool orig) { int cmd_len; const char* cmd; - line = skip_whitespace(line, end_of_line); - get_word(len, line, cmd_len, cmd); + line = zeek::util::skip_whitespace(line, end_of_line); + zeek::util::get_word(len, line, cmd_len, cmd); if ( strncmp(cmd, "ADAT", cmd_len) == 0 ) { - line = skip_whitespace(line + cmd_len, end_of_line); + line = zeek::util::skip_whitespace(line + cmd_len, end_of_line); zeek::StringVal encoded(end_of_line - line, line); decoded_adat = zeek::detail::decode_base64(encoded.AsString(), nullptr, Conn()); @@ -286,7 +286,7 @@ void FTP_ADAT_Analyzer::DeliverStream(int len, const u_char* data, bool orig) if ( len > 3 && line[0] == '-' ) line++; - line = skip_whitespace(line, end_of_line); + line = zeek::util::skip_whitespace(line, end_of_line); if ( end_of_line - line >= 5 && strncmp(line, "ADAT=", 5) == 0 ) { diff --git a/src/analyzer/protocol/ftp/functions.bif b/src/analyzer/protocol/ftp/functions.bif index 42f830723b..c4223334d7 100644 --- a/src/analyzer/protocol/ftp/functions.bif +++ b/src/analyzer/protocol/ftp/functions.bif @@ -206,7 +206,7 @@ function fmt_ftp_port%(a: addr, p: port%): string { uint32_t a = ntohl(addr[0]); uint32_t pn = p->Port(); - return zeek::make_intrusive(fmt("%d,%d,%d,%d,%d,%d", + return zeek::make_intrusive(zeek::util::fmt("%d,%d,%d,%d,%d,%d", a >> 24, (a >> 16) & 0xff, (a >> 8) & 0xff, a & 0xff, pn >> 8, pn & 0xff)); diff --git a/src/analyzer/protocol/gssapi/GSSAPI.cc b/src/analyzer/protocol/gssapi/GSSAPI.cc index 8e4d69038c..e9dc7a7b0a 100644 --- a/src/analyzer/protocol/gssapi/GSSAPI.cc +++ b/src/analyzer/protocol/gssapi/GSSAPI.cc @@ -45,7 +45,7 @@ void GSSAPI_Analyzer::DeliverStream(int len, const u_char* data, bool orig) } catch ( const binpac::Exception& e ) { - ProtocolViolation(fmt("Binpac exception: %s", e.c_msg())); + ProtocolViolation(zeek::util::fmt("Binpac exception: %s", e.c_msg())); } } diff --git a/src/analyzer/protocol/gtpv1/GTPv1.cc b/src/analyzer/protocol/gtpv1/GTPv1.cc index 06ec4cfe28..c5aa6e89bc 100644 --- a/src/analyzer/protocol/gtpv1/GTPv1.cc +++ b/src/analyzer/protocol/gtpv1/GTPv1.cc @@ -32,7 +32,7 @@ void GTPv1_Analyzer::DeliverPacket(int len, const u_char* data, bool orig, uint6 } catch ( const binpac::Exception& e ) { - ProtocolViolation(fmt("Binpac exception: %s", e.c_msg())); + ProtocolViolation(zeek::util::fmt("Binpac exception: %s", e.c_msg())); } } diff --git a/src/analyzer/protocol/gtpv1/gtpv1-analyzer.pac b/src/analyzer/protocol/gtpv1/gtpv1-analyzer.pac index 3ccab06b25..dd33d639f3 100644 --- a/src/analyzer/protocol/gtpv1/gtpv1-analyzer.pac +++ b/src/analyzer/protocol/gtpv1/gtpv1-analyzer.pac @@ -323,7 +323,7 @@ void CreatePDP_Request(const BroAnalyzer& a, const GTPv1_Header* pdu) rv->Assign(21, BuildPrivateExt(ie)); break; default: - a->Weird("gtp_invalid_info_element", fmt("%d", (*v)[i]->type())); + a->Weird("gtp_invalid_info_element", zeek::util::fmt("%d", (*v)[i]->type())); break; } } @@ -392,7 +392,7 @@ void CreatePDP_Response(const BroAnalyzer& a, const GTPv1_Header* pdu) rv->Assign(12, BuildPrivateExt(ie)); break; default: - a->Weird("gtp_invalid_info_element", fmt("%d", (*v)[i]->type())); + a->Weird("gtp_invalid_info_element", zeek::util::fmt("%d", (*v)[i]->type())); break; } } @@ -470,7 +470,7 @@ void UpdatePDP_Request(const BroAnalyzer& a, const GTPv1_Header* pdu) rv->Assign(15, BuildEndUserAddr(ie)); break; default: - a->Weird("gtp_invalid_info_element", fmt("%d", (*v)[i]->type())); + a->Weird("gtp_invalid_info_element", zeek::util::fmt("%d", (*v)[i]->type())); break; } } @@ -530,7 +530,7 @@ void UpdatePDP_Response(const BroAnalyzer& a, const GTPv1_Header* pdu) rv->Assign(9, BuildPrivateExt(ie)); break; default: - a->Weird("gtp_invalid_info_element", fmt("%d", (*v)[i]->type())); + a->Weird("gtp_invalid_info_element", zeek::util::fmt("%d", (*v)[i]->type())); break; } } @@ -564,7 +564,7 @@ void DeletePDP_Request(const BroAnalyzer& a, const GTPv1_Header* pdu) rv->Assign(2, BuildPrivateExt(ie)); break; default: - a->Weird("gtp_invalid_info_element", fmt("%d", (*v)[i]->type())); + a->Weird("gtp_invalid_info_element", zeek::util::fmt("%d", (*v)[i]->type())); break; } } @@ -595,7 +595,7 @@ void DeletePDP_Response(const BroAnalyzer& a, const GTPv1_Header* pdu) rv->Assign(1, BuildPrivateExt(ie)); break; default: - a->Weird("gtp_invalid_info_element", fmt("%d", (*v)[i]->type())); + a->Weird("gtp_invalid_info_element", zeek::util::fmt("%d", (*v)[i]->type())); break; } } diff --git a/src/analyzer/protocol/http/HTTP.cc b/src/analyzer/protocol/http/HTTP.cc index 6fd3b7cff2..4056285a07 100644 --- a/src/analyzer/protocol/http/HTTP.cc +++ b/src/analyzer/protocol/http/HTTP.cc @@ -115,7 +115,7 @@ void HTTP_Entity::Deliver(int len, const char* data, bool trailing_CRLF) switch ( chunked_transfer_state ) { case EXPECT_CHUNK_SIZE: ASSERT(trailing_CRLF); - if ( ! atoi_n(len, data, nullptr, 16, expect_data_length) ) + if ( ! zeek::util::atoi_n(len, data, nullptr, 16, expect_data_length) ) { http_message->Weird("HTTP_bad_chunk_size"); expect_data_length = 0; @@ -373,7 +373,7 @@ void HTTP_Entity::SubmitHeader(zeek::analyzer::mime::MIME_Header* h) if ( ! zeek::analyzer::mime::is_null_data_chunk(vt) ) { int64_t n; - if ( atoi_n(vt.length, vt.data, nullptr, 10, n) ) + if ( zeek::util::atoi_n(vt.length, vt.data, nullptr, 10, n) ) { content_length = n; @@ -435,8 +435,8 @@ void HTTP_Entity::SubmitHeader(zeek::analyzer::mime::MIME_Header* h) instance_length_str.c_str()); int64_t f, l; - atoi_n(first_byte_pos.size(), first_byte_pos.c_str(), nullptr, 10, f); - atoi_n(last_byte_pos.size(), last_byte_pos.c_str(), nullptr, 10, l); + zeek::util::atoi_n(first_byte_pos.size(), first_byte_pos.c_str(), nullptr, 10, f); + zeek::util::atoi_n(last_byte_pos.size(), last_byte_pos.c_str(), nullptr, 10, l); int64_t len = l - f + 1; if ( DEBUG_http ) @@ -446,9 +446,9 @@ void HTTP_Entity::SubmitHeader(zeek::analyzer::mime::MIME_Header* h) { if ( instance_length_str != "*" ) { - if ( ! atoi_n(instance_length_str.size(), - instance_length_str.c_str(), nullptr, 10, - instance_length) ) + if ( ! zeek::util::atoi_n(instance_length_str.size(), + instance_length_str.c_str(), nullptr, 10, + instance_length) ) instance_length = 0; } @@ -1095,7 +1095,7 @@ void HTTP_Analyzer::Undelivered(uint64_t seq, int len, bool is_orig) { if ( msg ) msg->SubmitEvent(zeek::analyzer::mime::MIME_EVENT_CONTENT_GAP, - fmt("seq=%" PRIu64", len=%d", seq, len)); + zeek::util::fmt("seq=%" PRIu64", len=%d", seq, len)); } // Check if the content gap falls completely within a message body @@ -1198,7 +1198,7 @@ const char* HTTP_Analyzer::PrefixWordMatch(const char* line, return nullptr; const char* orig_line = line; - line = skip_whitespace(line, end_of_line); + line = zeek::util::skip_whitespace(line, end_of_line); if ( line == orig_line ) // Word didn't end at prefix. @@ -1242,7 +1242,7 @@ int HTTP_Analyzer::HTTP_RequestLine(const char* line, const char* end_of_line) goto error; } - rest = skip_whitespace(end_of_method, end_of_line); + rest = zeek::util::skip_whitespace(end_of_method, end_of_line); if ( rest == end_of_method ) goto error; @@ -1293,7 +1293,7 @@ bool HTTP_Analyzer::ParseRequest(const char* line, const char* end_of_line) for ( version_start = end_of_uri; version_start < end_of_line; ++version_start ) { end_of_uri = version_start; - version_start = skip_whitespace(version_start, end_of_line); + version_start = zeek::util::skip_whitespace(version_start, end_of_line); if ( PrefixMatch(version_start, end_of_line, "HTTP/") ) break; } @@ -1313,7 +1313,7 @@ bool HTTP_Analyzer::ParseRequest(const char* line, const char* end_of_line) version_start)); version_end = version_start + 3; - if ( skip_whitespace(version_end, end_of_line) != end_of_line ) + if ( zeek::util::skip_whitespace(version_end, end_of_line) != end_of_line ) HTTP_Event("crud after HTTP version is ignored", zeek::analyzer::mime::to_string_val(line, end_of_line)); } @@ -1409,7 +1409,7 @@ void HTTP_Analyzer::HTTP_Request() request_method, TruncateURI(request_URI), TruncateURI(unescaped_URI), - zeek::make_intrusive(fmt("%.1f", request_version.ToDouble())) + zeek::make_intrusive(zeek::util::fmt("%.1f", request_version.ToDouble())) ); } @@ -1418,7 +1418,7 @@ void HTTP_Analyzer::HTTP_Reply() if ( http_reply ) EnqueueConnEvent(http_reply, ConnVal(), - zeek::make_intrusive(fmt("%.1f", reply_version.ToDouble())), + zeek::make_intrusive(zeek::util::fmt("%.1f", reply_version.ToDouble())), zeek::val_mgr->Count(reply_code), reply_reason_phrase ? reply_reason_phrase : @@ -1537,7 +1537,7 @@ int HTTP_Analyzer::HTTP_ReplyLine(const char* line, const char* end_of_line) return 0; } - rest = skip_whitespace(rest, end_of_line); + rest = zeek::util::skip_whitespace(rest, end_of_line); if ( rest + 3 > end_of_line ) { @@ -1560,7 +1560,7 @@ int HTTP_Analyzer::HTTP_ReplyLine(const char* line, const char* end_of_line) return 1; } - rest = skip_whitespace(rest, end_of_line); + rest = zeek::util::skip_whitespace(rest, end_of_line); reply_reason_phrase = zeek::make_intrusive(end_of_line - rest, (const char *) rest); @@ -1718,8 +1718,8 @@ bool is_unreserved_URI_char(unsigned char ch) void escape_URI_char(unsigned char ch, unsigned char*& p) { *p++ = '%'; - *p++ = encode_hex((ch >> 4) & 0xf); - *p++ = encode_hex(ch & 0xf); + *p++ = zeek::util::encode_hex((ch >> 4) & 0xf); + *p++ = zeek::util::encode_hex(ch & 0xf); } zeek::String* unescape_URI(const u_char* line, const u_char* line_end, @@ -1766,8 +1766,8 @@ zeek::String* unescape_URI(const u_char* line, const u_char* line_end, else if ( isxdigit(line[0]) && isxdigit(line[1]) ) { - *URI_p++ = (decode_hex(line[0]) << 4) + - decode_hex(line[1]); + *URI_p++ = (zeek::util::decode_hex(line[0]) << 4) + + zeek::util::decode_hex(line[1]); ++line; // place line at the last hex digit } @@ -1792,11 +1792,11 @@ zeek::String* unescape_URI(const u_char* line, const u_char* line_end, // It could just be ASCII encoded into this // unicode escaping structure. if ( ! (line[1] == '0' && line[2] == '0' ) ) - *URI_p++ = (decode_hex(line[1]) << 4) + - decode_hex(line[2]); + *URI_p++ = (zeek::util::decode_hex(line[1]) << 4) + + zeek::util::decode_hex(line[2]); - *URI_p++ = (decode_hex(line[3]) << 4) + - decode_hex(line[4]); + *URI_p++ = (zeek::util::decode_hex(line[3]) << 4) + + zeek::util::decode_hex(line[4]); line += 4; } diff --git a/src/analyzer/protocol/ident/Ident.cc b/src/analyzer/protocol/ident/Ident.cc index 0e47358140..9207ea8517 100644 --- a/src/analyzer/protocol/ident/Ident.cc +++ b/src/analyzer/protocol/ident/Ident.cc @@ -112,7 +112,7 @@ void Ident_Analyzer::DeliverStream(int length, const u_char* data, bool is_orig) return; } - line = skip_whitespace(line + 1, end_of_line); + line = zeek::util::skip_whitespace(line + 1, end_of_line); int restlen = end_of_line - line; int is_error; @@ -132,7 +132,7 @@ void Ident_Analyzer::DeliverStream(int length, const u_char* data, bool is_orig) return; } - line = skip_whitespace(line, end_of_line); + line = zeek::util::skip_whitespace(line, end_of_line); if ( line >= end_of_line || line[0] != ':' ) { @@ -140,7 +140,7 @@ void Ident_Analyzer::DeliverStream(int length, const u_char* data, bool is_orig) return; } - line = skip_whitespace(line + 1, end_of_line); + line = zeek::util::skip_whitespace(line + 1, end_of_line); if ( is_error ) { @@ -176,7 +176,7 @@ void Ident_Analyzer::DeliverStream(int length, const u_char* data, bool is_orig) new zeek::String((const u_char*) sys_type, sys_end - sys_type + 1, true); - line = skip_whitespace(colon + 1, end_of_line); + line = zeek::util::skip_whitespace(colon + 1, end_of_line); EnqueueConnEvent(ident_reply, ConnVal(), @@ -214,7 +214,7 @@ const char* Ident_Analyzer::ParsePort(const char* line, const char* end_of_line, { int n = 0; - line = skip_whitespace(line, end_of_line); + line = zeek::util::skip_whitespace(line, end_of_line); if ( line >= end_of_line || ! isdigit(*line) ) return nullptr; @@ -227,7 +227,7 @@ const char* Ident_Analyzer::ParsePort(const char* line, const char* end_of_line, } while ( line < end_of_line && isdigit(*line) ); - line = skip_whitespace(line, end_of_line); + line = zeek::util::skip_whitespace(line, end_of_line); if ( n < 0 || n > 65535 ) { diff --git a/src/analyzer/protocol/imap/IMAP.cc b/src/analyzer/protocol/imap/IMAP.cc index e9cbc1e81e..3ed2fb4712 100644 --- a/src/analyzer/protocol/imap/IMAP.cc +++ b/src/analyzer/protocol/imap/IMAP.cc @@ -61,7 +61,7 @@ void IMAP_Analyzer::DeliverStream(int len, const u_char* data, bool orig) } catch ( const binpac::Exception& e ) { - ProtocolViolation(fmt("Binpac exception: %s", e.c_msg())); + ProtocolViolation(zeek::util::fmt("Binpac exception: %s", e.c_msg())); } } diff --git a/src/analyzer/protocol/krb/KRB.cc b/src/analyzer/protocol/krb/KRB.cc index 51ccdc3c78..95251efb39 100644 --- a/src/analyzer/protocol/krb/KRB.cc +++ b/src/analyzer/protocol/krb/KRB.cc @@ -83,7 +83,7 @@ void KRB_Analyzer::DeliverPacket(int len, const u_char* data, bool orig, } catch ( const binpac::Exception& e ) { - ProtocolViolation(fmt("Binpac exception: %s", e.c_msg())); + ProtocolViolation(zeek::util::fmt("Binpac exception: %s", e.c_msg())); } } @@ -117,13 +117,13 @@ zeek::StringValPtr KRB_Analyzer::GetAuthenticationInfo(const zeek::String* princ return nullptr; } - auto tkt = static_cast(safe_malloc(sizeof(krb5_ticket))); + auto tkt = static_cast(zeek::util::safe_malloc(sizeof(krb5_ticket))); memset(tkt, 0, sizeof(krb5_ticket)); tkt->server = sprinc; tkt->enc_part.enctype = enctype; - auto ctd = static_cast(safe_malloc(ciphertext->Len())); + auto ctd = static_cast(zeek::util::safe_malloc(ciphertext->Len())); memcpy(ctd, ciphertext->Bytes(), ciphertext->Len()); tkt->enc_part.ciphertext.data = ctd; tkt->enc_part.ciphertext.length = ciphertext->Len(); diff --git a/src/analyzer/protocol/krb/KRB_TCP.cc b/src/analyzer/protocol/krb/KRB_TCP.cc index 6acf7f166f..eafe39f342 100644 --- a/src/analyzer/protocol/krb/KRB_TCP.cc +++ b/src/analyzer/protocol/krb/KRB_TCP.cc @@ -53,7 +53,7 @@ void KRB_Analyzer::DeliverStream(int len, const u_char* data, bool orig) } catch ( const binpac::Exception& e ) { - ProtocolViolation(fmt("Binpac exception: %s", e.c_msg())); + ProtocolViolation(zeek::util::fmt("Binpac exception: %s", e.c_msg())); } } diff --git a/src/analyzer/protocol/krb/krb-types.pac b/src/analyzer/protocol/krb/krb-types.pac index 2246f7a90c..071a336200 100644 --- a/src/analyzer/protocol/krb/krb-types.pac +++ b/src/analyzer/protocol/krb/krb-types.pac @@ -18,9 +18,9 @@ zeek::ValPtr GetStringFromPrincipalName(const KRB_Principal_Name* pname) if ( pname->data()->size() == 1 ) return to_stringval(pname->data()[0][0]->encoding()->content()); if ( pname->data()->size() == 2 ) - return zeek::make_intrusive(fmt("%s/%s", (char *) pname->data()[0][0]->encoding()->content().begin(), (char *)pname->data()[0][1]->encoding()->content().begin())); + return zeek::make_intrusive(zeek::util::fmt("%s/%s", (char *) pname->data()[0][0]->encoding()->content().begin(), (char *)pname->data()[0][1]->encoding()->content().begin())); if ( pname->data()->size() == 3 ) // if the name-string has a third value, this will just append it, else this will return unknown as the principal name - return zeek::make_intrusive(fmt("%s/%s/%s", (char *) pname->data()[0][0]->encoding()->content().begin(), (char *)pname->data()[0][1]->encoding()->content().begin(), (char *)pname->data()[0][2]->encoding()->content().begin())); + return zeek::make_intrusive(zeek::util::fmt("%s/%s/%s", (char *) pname->data()[0][0]->encoding()->content().begin(), (char *)pname->data()[0][1]->encoding()->content().begin(), (char *)pname->data()[0][2]->encoding()->content().begin())); return zeek::make_intrusive("unknown"); } diff --git a/src/analyzer/protocol/login/Login.cc b/src/analyzer/protocol/login/Login.cc index 2182be23e4..0f734eb897 100644 --- a/src/analyzer/protocol/login/Login.cc +++ b/src/analyzer/protocol/login/Login.cc @@ -323,14 +323,14 @@ void Login_Analyzer::SetEnv(bool orig, char* name, char* val) else { - if ( streq(name, "USER") ) + if ( zeek::util::streq(name, "USER") ) { if ( username ) { const zeek::String* u = username->AsString(); const zeek::byte_vec ub = u->Bytes(); const char* us = (const char*) ub; - if ( ! streq(val, us) ) + if ( ! zeek::util::streq(val, us) ) Confused("multiple_USERs", val); Unref(username); } @@ -339,19 +339,19 @@ void Login_Analyzer::SetEnv(bool orig, char* name, char* val) username = new zeek::StringVal(val); } - else if ( login_terminal && streq(name, "TERM") ) + else if ( login_terminal && zeek::util::streq(name, "TERM") ) EnqueueConnEvent(login_terminal, ConnVal(), zeek::make_intrusive(val) ); - else if ( login_display && streq(name, "DISPLAY") ) + else if ( login_display && zeek::util::streq(name, "DISPLAY") ) EnqueueConnEvent(login_display, ConnVal(), zeek::make_intrusive(val) ); - else if ( login_prompt && streq(name, "TTYPROMPT") ) + else if ( login_prompt && zeek::util::streq(name, "TTYPROMPT") ) EnqueueConnEvent(login_prompt, ConnVal(), zeek::make_intrusive(val) @@ -562,7 +562,7 @@ void Login_Analyzer::AddUserText(const char* line) if ( ++user_text_last == MAX_USER_TEXT ) user_text_last = 0; - user_text[user_text_last] = copy_string(line); + user_text[user_text_last] = zeek::util::copy_string(line); ++num_user_text; } @@ -612,7 +612,7 @@ bool Login_Analyzer::MatchesTypeahead(const char* line) const if ( i == MAX_USER_TEXT ) i = 0; - if ( streq(user_text[i], line) ) + if ( zeek::util::streq(user_text[i], line) ) return true; } diff --git a/src/analyzer/protocol/login/NVT.cc b/src/analyzer/protocol/login/NVT.cc index c49f8d717b..22f8d3e957 100644 --- a/src/analyzer/protocol/login/NVT.cc +++ b/src/analyzer/protocol/login/NVT.cc @@ -251,7 +251,7 @@ void TelnetAuthenticateOption::RecvSubOption(u_char* data, int len) case AUTHENTICATION_NAME: { char* auth_name = new char[len]; - safe_strncpy(auth_name, (char*) data + 1, len); + zeek::util::safe_strncpy(auth_name, (char*) data + 1, len); endp->SetAuthName(auth_name); } break; diff --git a/src/analyzer/protocol/login/RSH.cc b/src/analyzer/protocol/login/RSH.cc index ae687cd4e5..6a852fc4ff 100644 --- a/src/analyzer/protocol/login/RSH.cc +++ b/src/analyzer/protocol/login/RSH.cc @@ -171,7 +171,7 @@ void Rsh_Analyzer::DeliverStream(int len, const u_char* data, bool orig) zeek::Args vl; vl.reserve(4 + orig); const char* line = (const char*) data; - line = skip_whitespace(line); + line = zeek::util::skip_whitespace(line); vl.emplace_back(ConnVal()); if ( client_name ) diff --git a/src/analyzer/protocol/mime/MIME.cc b/src/analyzer/protocol/mime/MIME.cc index d84c1f404a..07efdcdaeb 100644 --- a/src/analyzer/protocol/mime/MIME.cc +++ b/src/analyzer/protocol/mime/MIME.cc @@ -1083,8 +1083,8 @@ void MIME_Entity::DecodeQuotedPrintable(int len, const char* data) if ( i + 2 < len ) { int a, b; - a = decode_hex(data[i+1]); - b = decode_hex(data[i+2]); + a = zeek::util::decode_hex(data[i+1]); + b = zeek::util::decode_hex(data[i+2]); if ( a >= 0 && b >= 0 ) { @@ -1114,7 +1114,7 @@ void MIME_Entity::DecodeQuotedPrintable(int len, const char* data) else { - IllegalEncoding(fmt("control characters in quoted-printable encoding: %d", (int) (data[i]))); + IllegalEncoding(zeek::util::fmt("control characters in quoted-printable encoding: %d", (int) (data[i]))); DataOctet(data[i]); } } diff --git a/src/analyzer/protocol/modbus/modbus-analyzer.pac b/src/analyzer/protocol/modbus/modbus-analyzer.pac index 13117ffbb6..4f34184a05 100644 --- a/src/analyzer/protocol/modbus/modbus-analyzer.pac +++ b/src/analyzer/protocol/modbus/modbus-analyzer.pac @@ -203,7 +203,7 @@ refine flow ModbusTCP_Flow += { if ( ${message.byte_count} % 2 != 0 ) { connection()->bro_analyzer()->ProtocolViolation( - fmt("invalid value for modbus read holding register response byte count %d", ${message.byte_count})); + zeek::util::fmt("invalid value for modbus read holding register response byte count %d", ${message.byte_count})); return false; } @@ -247,7 +247,7 @@ refine flow ModbusTCP_Flow += { if ( ${message.byte_count} % 2 != 0 ) { connection()->bro_analyzer()->ProtocolViolation( - fmt("invalid value for modbus read input register response byte count %d", ${message.byte_count})); + zeek::util::fmt("invalid value for modbus read input register response byte count %d", ${message.byte_count})); return false; } @@ -283,7 +283,7 @@ refine flow ModbusTCP_Flow += { val = 1; else { - connection()->bro_analyzer()->ProtocolViolation(fmt("invalid value for modbus write single coil request %d", + connection()->bro_analyzer()->ProtocolViolation(zeek::util::fmt("invalid value for modbus write single coil request %d", ${message.value})); return false; } @@ -310,7 +310,7 @@ refine flow ModbusTCP_Flow += { val = 1; else { - connection()->bro_analyzer()->ProtocolViolation(fmt("invalid value for modbus write single coil response %d", + connection()->bro_analyzer()->ProtocolViolation(zeek::util::fmt("invalid value for modbus write single coil response %d", ${message.value})); return false; } @@ -391,7 +391,7 @@ refine flow ModbusTCP_Flow += { if ( ${message.byte_count} % 2 != 0 ) { connection()->bro_analyzer()->ProtocolViolation( - fmt("invalid value for modbus write multiple registers request byte count %d", ${message.byte_count})); + zeek::util::fmt("invalid value for modbus write multiple registers request byte count %d", ${message.byte_count})); return false; } @@ -576,7 +576,7 @@ refine flow ModbusTCP_Flow += { if ( ${message.write_byte_count} % 2 != 0 ) { connection()->bro_analyzer()->ProtocolViolation( - fmt("invalid value for modbus read write multiple registers request write byte count %d", ${message.write_byte_count})); + zeek::util::fmt("invalid value for modbus read write multiple registers request write byte count %d", ${message.write_byte_count})); return false; } @@ -608,7 +608,7 @@ refine flow ModbusTCP_Flow += { if ( ${message.byte_count} % 2 != 0 ) { connection()->bro_analyzer()->ProtocolViolation( - fmt("invalid value for modbus read write multiple registers response byte count %d", ${message.byte_count})); + zeek::util::fmt("invalid value for modbus read write multiple registers response byte count %d", ${message.byte_count})); return false; } @@ -652,7 +652,7 @@ refine flow ModbusTCP_Flow += { if ( ${message.byte_count} % 2 != 0 ) { connection()->bro_analyzer()->ProtocolViolation( - fmt("invalid value for modbus read FIFO queue response byte count %d", ${message.byte_count})); + zeek::util::fmt("invalid value for modbus read FIFO queue response byte count %d", ${message.byte_count})); return false; } diff --git a/src/analyzer/protocol/mqtt/MQTT.cc b/src/analyzer/protocol/mqtt/MQTT.cc index a549200317..82524ac112 100644 --- a/src/analyzer/protocol/mqtt/MQTT.cc +++ b/src/analyzer/protocol/mqtt/MQTT.cc @@ -46,7 +46,7 @@ void MQTT_Analyzer::DeliverStream(int len, const u_char* data, bool orig) } catch ( const binpac::Exception& e ) { - ProtocolViolation(fmt("Binpac exception: %s", e.c_msg())); + ProtocolViolation(zeek::util::fmt("Binpac exception: %s", e.c_msg())); } } diff --git a/src/analyzer/protocol/mysql/MySQL.cc b/src/analyzer/protocol/mysql/MySQL.cc index 0d87fe21b4..789e71bce3 100644 --- a/src/analyzer/protocol/mysql/MySQL.cc +++ b/src/analyzer/protocol/mysql/MySQL.cc @@ -53,7 +53,7 @@ void MySQL_Analyzer::DeliverStream(int len, const u_char* data, bool orig) } catch ( const binpac::Exception& e ) { - ProtocolViolation(fmt("Binpac exception: %s", e.c_msg())); + ProtocolViolation(zeek::util::fmt("Binpac exception: %s", e.c_msg())); } } diff --git a/src/analyzer/protocol/ncp/NCP.cc b/src/analyzer/protocol/ncp/NCP.cc index b3740764c4..a566e27827 100644 --- a/src/analyzer/protocol/ncp/NCP.cc +++ b/src/analyzer/protocol/ncp/NCP.cc @@ -43,7 +43,7 @@ void NCP_Session::Deliver(bool is_orig, int len, const u_char* data) } catch ( const binpac::Exception& e ) { - analyzer->ProtocolViolation(fmt("Binpac exception: %s", e.c_msg())); + analyzer->ProtocolViolation(zeek::util::fmt("Binpac exception: %s", e.c_msg())); } } diff --git a/src/analyzer/protocol/netbios/NetbiosSSN.cc b/src/analyzer/protocol/netbios/NetbiosSSN.cc index 362d2474b8..00566d0607 100644 --- a/src/analyzer/protocol/netbios/NetbiosSSN.cc +++ b/src/analyzer/protocol/netbios/NetbiosSSN.cc @@ -105,7 +105,7 @@ void NetbiosSSN_Interpreter::ParseMessage(unsigned int type, unsigned int flags, break; default: - analyzer->Weird("unknown_netbios_type", fmt("0x%x", type)); + analyzer->Weird("unknown_netbios_type", zeek::util::fmt("0x%x", type)); break; } } @@ -146,7 +146,7 @@ void NetbiosSSN_Interpreter::ParseMessageTCP(const u_char* data, int len, NetbiosSSN_RawMsgHdr hdr(data, len); if ( hdr.length > unsigned(len) ) - analyzer->Weird("excess_netbios_hdr_len", fmt("(%d > %d)", + analyzer->Weird("excess_netbios_hdr_len", zeek::util::fmt("(%d > %d)", hdr.length, len)); else if ( hdr.length < unsigned(len) ) @@ -164,12 +164,12 @@ void NetbiosSSN_Interpreter::ParseMessageUDP(const u_char* data, int len, NetbiosDGM_RawMsgHdr hdr(data, len); if ( unsigned(hdr.length-14) > unsigned(len) ) - analyzer->Weird("excess_netbios_hdr_len", fmt("(%d > %d)", + analyzer->Weird("excess_netbios_hdr_len", zeek::util::fmt("(%d > %d)", hdr.length, len)); else if ( hdr.length < unsigned(len) ) { - analyzer->Weird("deficit_netbios_hdr_len", fmt("(%d < %d)", + analyzer->Weird("deficit_netbios_hdr_len", zeek::util::fmt("(%d < %d)", hdr.length, len)); len = hdr.length; } diff --git a/src/analyzer/protocol/ntlm/NTLM.cc b/src/analyzer/protocol/ntlm/NTLM.cc index cb15ac5434..1bc4e69ea7 100644 --- a/src/analyzer/protocol/ntlm/NTLM.cc +++ b/src/analyzer/protocol/ntlm/NTLM.cc @@ -45,7 +45,7 @@ void NTLM_Analyzer::DeliverStream(int len, const u_char* data, bool orig) } catch ( const binpac::Exception& e ) { - ProtocolViolation(fmt("Binpac exception: %s", e.c_msg())); + ProtocolViolation(zeek::util::fmt("Binpac exception: %s", e.c_msg())); } } diff --git a/src/analyzer/protocol/ntp/NTP.cc b/src/analyzer/protocol/ntp/NTP.cc index df4ca6888f..805c70c90a 100644 --- a/src/analyzer/protocol/ntp/NTP.cc +++ b/src/analyzer/protocol/ntp/NTP.cc @@ -34,7 +34,7 @@ void NTP_Analyzer::DeliverPacket(int len, const u_char* data, bool orig, } catch ( const binpac::Exception& e ) { - ProtocolViolation(fmt("Binpac exception: %s", e.c_msg())); + ProtocolViolation(zeek::util::fmt("Binpac exception: %s", e.c_msg())); } } diff --git a/src/analyzer/protocol/pop3/POP3.cc b/src/analyzer/protocol/pop3/POP3.cc index dcfa2543cd..316ab8b355 100644 --- a/src/analyzer/protocol/pop3/POP3.cc +++ b/src/analyzer/protocol/pop3/POP3.cc @@ -91,7 +91,7 @@ static std::string trim_whitespace(const char* in) char* out = new char[n + 1]; char* out_p = out; - in = skip_whitespace(in); + in = zeek::util::skip_whitespace(in); while ( *in ) { @@ -245,7 +245,7 @@ static std::string commands[] = { void POP3_Analyzer::NotAllowed(const char* cmd, const char* state) { POP3Event(pop3_unexpected, true, cmd, - fmt("not allowed in other state than '%s'", state)); + zeek::util::fmt("not allowed in other state than '%s'", state)); } void POP3_Analyzer::ProcessClientCmd() @@ -320,7 +320,7 @@ void POP3_Analyzer::ProcessClientCmd() state = detail::APOP; subState = detail::POP3_WOK; - char* arg1 = copy_string(message); + char* arg1 = zeek::util::copy_string(message); char* e; for ( e = arg1; *e && *e != ' ' && *e != '\t'; ++e ) ; @@ -354,7 +354,7 @@ void POP3_Analyzer::ProcessClientCmd() { state = detail::AUTH; POP3Event(pop3_unexpected, true, cmd, - fmt("unknown AUTH method %s", message)); + zeek::util::fmt("unknown AUTH method %s", message)); } subState = detail::POP3_WOK; @@ -634,11 +634,11 @@ void POP3_Analyzer::ProcessReply(int length, const char* line) { if ( ! waitingForAuthentication ) { - ProtocolViolation(fmt("unknown server command (%s)", - (tokens.size() > 0 ? - tokens[0].c_str() : - "???")), - line, length); + ProtocolViolation(zeek::util::fmt("unknown server command (%s)", + (tokens.size() > 0 ? + tokens[0].c_str() : + "???")), + line, length); Weird("pop3_server_command_unknown"); if ( subState == detail::POP3_WOK ) diff --git a/src/analyzer/protocol/radius/RADIUS.cc b/src/analyzer/protocol/radius/RADIUS.cc index 44ff6dbffc..7dd3c3c0cd 100644 --- a/src/analyzer/protocol/radius/RADIUS.cc +++ b/src/analyzer/protocol/radius/RADIUS.cc @@ -35,7 +35,7 @@ void RADIUS_Analyzer::DeliverPacket(int len, const u_char* data, } catch ( const binpac::Exception& e ) { - ProtocolViolation(fmt("Binpac exception: %s", e.c_msg())); + ProtocolViolation(zeek::util::fmt("Binpac exception: %s", e.c_msg())); } } diff --git a/src/analyzer/protocol/rdp/RDP.cc b/src/analyzer/protocol/rdp/RDP.cc index a5e594ad4b..4656b43ca6 100644 --- a/src/analyzer/protocol/rdp/RDP.cc +++ b/src/analyzer/protocol/rdp/RDP.cc @@ -88,7 +88,7 @@ void RDP_Analyzer::DeliverStream(int len, const u_char* data, bool orig) } catch ( const binpac::Exception& e ) { - ProtocolViolation(fmt("Binpac exception: %s", e.c_msg())); + ProtocolViolation(zeek::util::fmt("Binpac exception: %s", e.c_msg())); } } } diff --git a/src/analyzer/protocol/rdp/RDPEUDP.cc b/src/analyzer/protocol/rdp/RDPEUDP.cc index 76845a3d09..9224aef78e 100644 --- a/src/analyzer/protocol/rdp/RDPEUDP.cc +++ b/src/analyzer/protocol/rdp/RDPEUDP.cc @@ -32,7 +32,7 @@ void RDP_Analyzer::DeliverPacket(int len, const u_char* data, bool orig, } catch ( const binpac::Exception& e ) { - ProtocolViolation(fmt("Binpac exception: %s", e.c_msg())); + ProtocolViolation(zeek::util::fmt("Binpac exception: %s", e.c_msg())); } } diff --git a/src/analyzer/protocol/rfb/RFB.cc b/src/analyzer/protocol/rfb/RFB.cc index 79cd66f38d..8ffd6abf6f 100644 --- a/src/analyzer/protocol/rfb/RFB.cc +++ b/src/analyzer/protocol/rfb/RFB.cc @@ -63,7 +63,7 @@ void RFB_Analyzer::DeliverStream(int len, const u_char* data, bool orig) } catch ( const binpac::Exception& e ) { - ProtocolViolation(fmt("Binpac exception: %s", e.c_msg())); + ProtocolViolation(zeek::util::fmt("Binpac exception: %s", e.c_msg())); invalid = true; } } diff --git a/src/analyzer/protocol/rfb/rfb-analyzer.pac b/src/analyzer/protocol/rfb/rfb-analyzer.pac index 36bf163ce4..ed149ab693 100644 --- a/src/analyzer/protocol/rfb/rfb-analyzer.pac +++ b/src/analyzer/protocol/rfb/rfb-analyzer.pac @@ -181,7 +181,7 @@ refine connection RFB_Conn += { else { // Shouldn't be a possible. - bro_analyzer()->ProtocolViolation(fmt("invalid RFB security type %u", msg->sectype())); + bro_analyzer()->ProtocolViolation(zeek::util::fmt("invalid RFB security type %u", msg->sectype())); } return true; @@ -235,7 +235,7 @@ refine connection RFB_Conn += { } else { - bro_analyzer()->ProtocolViolation(fmt("unknown RFB auth selection: %u", ${msg.type})); + bro_analyzer()->ProtocolViolation(zeek::util::fmt("unknown RFB auth selection: %u", ${msg.type})); } return true; @@ -277,7 +277,7 @@ refine connection RFB_Conn += { // Failed server_state = SERVER_AUTH_FAILURE; else - bro_analyzer()->ProtocolViolation(fmt("invalid RFB auth result: %u", ${msg.result})); + bro_analyzer()->ProtocolViolation(zeek::util::fmt("invalid RFB auth result: %u", ${msg.result})); return true; %} @@ -309,7 +309,7 @@ refine connection RFB_Conn += { function handle_invalid_data(client: bool) : bool %{ - throw binpac::Exception(fmt("invalid data from RFB %s", client ? "client" : "server")); + throw binpac::Exception(zeek::util::fmt("invalid data from RFB %s", client ? "client" : "server")); return true; %} diff --git a/src/analyzer/protocol/rpc/MOUNT.cc b/src/analyzer/protocol/rpc/MOUNT.cc index 93800cdc07..a6e71b86e6 100644 --- a/src/analyzer/protocol/rpc/MOUNT.cc +++ b/src/analyzer/protocol/rpc/MOUNT.cc @@ -19,7 +19,7 @@ namespace detail { bool MOUNT_Interp::RPC_BuildCall(RPC_CallInfo* c, const u_char*& buf, int& n) { if ( c->Program() != 100005 ) - Weird("bad_RPC_program", fmt("%d", c->Program())); + Weird("bad_RPC_program", zeek::util::fmt("%d", c->Program())); uint32_t proc = c->Proc(); // The call arguments, depends on the call type obviously ... @@ -50,7 +50,7 @@ bool MOUNT_Interp::RPC_BuildCall(RPC_CallInfo* c, const u_char*& buf, int& n) n = 0; } else - Weird("unknown_MOUNT_request", fmt("%u", proc)); + Weird("unknown_MOUNT_request", zeek::util::fmt("%u", proc)); // Return 1 so that replies to unprocessed calls will still // be processed, and the return status extracted. diff --git a/src/analyzer/protocol/rpc/NFS.cc b/src/analyzer/protocol/rpc/NFS.cc index 20f35221f2..366d778839 100644 --- a/src/analyzer/protocol/rpc/NFS.cc +++ b/src/analyzer/protocol/rpc/NFS.cc @@ -19,7 +19,7 @@ namespace detail { bool NFS_Interp::RPC_BuildCall(RPC_CallInfo* c, const u_char*& buf, int& n) { if ( c->Program() != 100003 ) - Weird("bad_RPC_program", fmt("%d", c->Program())); + Weird("bad_RPC_program", zeek::util::fmt("%d", c->Program())); uint32_t proc = c->Proc(); // The call arguments, depends on the call type obviously ... @@ -104,7 +104,7 @@ bool NFS_Interp::RPC_BuildCall(RPC_CallInfo* c, const u_char*& buf, int& n) n = 0; } else - Weird("unknown_NFS_request", fmt("%u", proc)); + Weird("unknown_NFS_request", zeek::util::fmt("%u", proc)); // Return 1 so that replies to unprocessed calls will still // be processed, and the return status extracted. diff --git a/src/analyzer/protocol/rpc/RPC.cc b/src/analyzer/protocol/rpc/RPC.cc index 22c935d2b9..d950a67228 100644 --- a/src/analyzer/protocol/rpc/RPC.cc +++ b/src/analyzer/protocol/rpc/RPC.cc @@ -535,7 +535,7 @@ bool Contents_RPC::CheckResync(int& len, const u_char*& data, bool orig) DEBUG_MSG("%.6f RPC resync: " "discard small pieces: %d\n", zeek::net::network_time, len); - Conn()->Weird("RPC_resync", fmt("discard %d bytes\n", len)); + Conn()->Weird("RPC_resync", zeek::util::fmt("discard %d bytes\n", len)); } NeedResync(); @@ -678,7 +678,7 @@ void Contents_RPC::DeliverStream(int len, const u_char* data, bool orig) // zeek::net::network_time, IsOrig(), marker, last_frag, msg_buf.GetExpected(), msg_buf.GetProcessed(), len); if ( ! msg_buf.AddToExpected(marker) ) - Conn()->Weird("RPC_message_too_long", fmt("%" PRId64, msg_buf.GetExpected())); + Conn()->Weird("RPC_message_too_long", zeek::util::fmt("%" PRId64, msg_buf.GetExpected())); if ( last_frag ) state = WAIT_FOR_LAST_DATA; diff --git a/src/analyzer/protocol/sip/SIP.cc b/src/analyzer/protocol/sip/SIP.cc index 36136b6e13..e3b4f37352 100644 --- a/src/analyzer/protocol/sip/SIP.cc +++ b/src/analyzer/protocol/sip/SIP.cc @@ -39,7 +39,7 @@ void SIP_Analyzer::DeliverPacket(int len, const u_char* data, bool orig, } catch ( const binpac::Exception& e ) { - ProtocolViolation(fmt("Binpac exception: %s", e.c_msg())); + ProtocolViolation(zeek::util::fmt("Binpac exception: %s", e.c_msg())); } } diff --git a/src/analyzer/protocol/sip/SIP_TCP.cc b/src/analyzer/protocol/sip/SIP_TCP.cc index f86092307b..af564d112b 100644 --- a/src/analyzer/protocol/sip/SIP_TCP.cc +++ b/src/analyzer/protocol/sip/SIP_TCP.cc @@ -55,7 +55,7 @@ void SIP_Analyzer::DeliverStream(int len, const u_char* data, bool orig) } catch ( const binpac::Exception& e ) { - ProtocolViolation(fmt("Binpac exception: %s", e.c_msg())); + ProtocolViolation(zeek::util::fmt("Binpac exception: %s", e.c_msg())); } } diff --git a/src/analyzer/protocol/smb/SMB.cc b/src/analyzer/protocol/smb/SMB.cc index 18fdd76579..92ef6ab4af 100644 --- a/src/analyzer/protocol/smb/SMB.cc +++ b/src/analyzer/protocol/smb/SMB.cc @@ -81,7 +81,7 @@ void SMB_Analyzer::DeliverStream(int len, const u_char* data, bool orig) } catch ( const binpac::Exception& e ) { - ProtocolViolation(fmt("Binpac exception: %s", e.c_msg())); + ProtocolViolation(zeek::util::fmt("Binpac exception: %s", e.c_msg())); NeedResync(); } } diff --git a/src/analyzer/protocol/smtp/SMTP.cc b/src/analyzer/protocol/smtp/SMTP.cc index bd12d4d4be..f288230368 100644 --- a/src/analyzer/protocol/smtp/SMTP.cc +++ b/src/analyzer/protocol/smtp/SMTP.cc @@ -85,7 +85,7 @@ void SMTP_Analyzer::Undelivered(uint64_t seq, int len, bool is_orig) if ( len <= 0 ) return; - const char* buf = fmt("seq = %" PRIu64", len = %d", seq, len); + const char* buf = zeek::util::fmt("seq = %" PRIu64", len = %d", seq, len); int buf_len = strlen(buf); Unexpected(is_orig, "content gap", buf_len, buf); @@ -240,8 +240,8 @@ void SMTP_Analyzer::ProcessLine(int length, const char* line, bool orig) expect_sender = false; expect_recver = true; - get_word(length, line, cmd_len, cmd); - line = skip_whitespace(line + cmd_len, end_of_line); + zeek::util::get_word(length, line, cmd_len, cmd); + line = zeek::util::skip_whitespace(line + cmd_len, end_of_line); cmd_code = ParseCmd(cmd_len, cmd); if ( cmd_code == -1 ) @@ -299,8 +299,8 @@ void SMTP_Analyzer::ProcessLine(int length, const char* line, bool orig) { reply_code = -1; Unexpected(is_sender, "reply code out of range", length, line); - ProtocolViolation(fmt("reply code %d out of range", - reply_code), line, length); + ProtocolViolation(zeek::util::fmt("reply code %d out of range", + reply_code), line, length); } else @@ -319,12 +319,12 @@ void SMTP_Analyzer::ProcessLine(int length, const char* line, bool orig) if ( reply_code >= 0 && length > 3 && line[3] == '-' ) { // A continued reply. pending_reply = reply_code; - line = skip_whitespace(line+4, end_of_line); + line = zeek::util::skip_whitespace(line+4, end_of_line); } else { // This is the end of the reply. - line = skip_whitespace(line+3, end_of_line); + line = zeek::util::skip_whitespace(line+3, end_of_line); pending_reply = 0; expect_sender = true; @@ -366,7 +366,7 @@ void SMTP_Analyzer::ProcessLine(int length, const char* line, bool orig) const char* ext; int ext_len; - get_word(end_of_line - line, line, ext_len, ext); + zeek::util::get_word(end_of_line - line, line, ext_len, ext); ProcessExtension(ext_len, ext); } } diff --git a/src/analyzer/protocol/snmp/SNMP.cc b/src/analyzer/protocol/snmp/SNMP.cc index 2d3aae5888..53d859f71c 100644 --- a/src/analyzer/protocol/snmp/SNMP.cc +++ b/src/analyzer/protocol/snmp/SNMP.cc @@ -36,7 +36,7 @@ void SNMP_Analyzer::DeliverPacket(int len, const u_char* data, bool orig, } catch ( const binpac::Exception& e ) { - ProtocolViolation(fmt("Binpac exception: %s", e.c_msg())); + ProtocolViolation(zeek::util::fmt("Binpac exception: %s", e.c_msg())); } } diff --git a/src/analyzer/protocol/snmp/snmp-analyzer.pac b/src/analyzer/protocol/snmp/snmp-analyzer.pac index 738ca3f912..4aa9d7bd4f 100644 --- a/src/analyzer/protocol/snmp/snmp-analyzer.pac +++ b/src/analyzer/protocol/snmp/snmp-analyzer.pac @@ -397,7 +397,7 @@ refine connection SNMP_Conn += { // Unwind now to stop parsing because it's definitely the // wrong protocol and parsing further could be expensive. // Upper layer of analyzer will catch and call ProtocolViolation(). - throw binpac::Exception(fmt("Got ASN.1 tag %d, expect %d", + throw binpac::Exception(zeek::util::fmt("Got ASN.1 tag %d, expect %d", rec->tag(), expect)); return false; %} @@ -412,7 +412,7 @@ refine connection SNMP_Conn += { // order bit is set. return true; - throw binpac::Exception(fmt("ASN.1 integer width overflow: %d", len)); + throw binpac::Exception(zeek::util::fmt("ASN.1 integer width overflow: %d", len)); return false; %} diff --git a/src/analyzer/protocol/socks/SOCKS.cc b/src/analyzer/protocol/socks/SOCKS.cc index 437b05b8ab..328463912b 100644 --- a/src/analyzer/protocol/socks/SOCKS.cc +++ b/src/analyzer/protocol/socks/SOCKS.cc @@ -80,7 +80,7 @@ void SOCKS_Analyzer::DeliverStream(int len, const u_char* data, bool orig) } catch ( const binpac::Exception& e ) { - ProtocolViolation(fmt("Binpac exception: %s", e.c_msg())); + ProtocolViolation(zeek::util::fmt("Binpac exception: %s", e.c_msg())); } } } diff --git a/src/analyzer/protocol/socks/socks-analyzer.pac b/src/analyzer/protocol/socks/socks-analyzer.pac index fa341cbab1..a0b16e30d3 100644 --- a/src/analyzer/protocol/socks/socks-analyzer.pac +++ b/src/analyzer/protocol/socks/socks-analyzer.pac @@ -70,14 +70,14 @@ refine connection SOCKS_Conn += { %{ if ( ${request.reserved} != 0 ) { - bro_analyzer()->ProtocolViolation(fmt("invalid value in reserved field: %d", ${request.reserved})); + bro_analyzer()->ProtocolViolation(zeek::util::fmt("invalid value in reserved field: %d", ${request.reserved})); bro_analyzer()->SetSkip(true); return false; } if ( (${request.command} == 0) || (${request.command} > 3) ) { - bro_analyzer()->ProtocolViolation(fmt("undefined value in command field: %d", ${request.command})); + bro_analyzer()->ProtocolViolation(zeek::util::fmt("undefined value in command field: %d", ${request.command})); bro_analyzer()->SetSkip(true); return false; } @@ -102,7 +102,7 @@ refine connection SOCKS_Conn += { break; default: - bro_analyzer()->ProtocolViolation(fmt("invalid SOCKSv5 addr type: %d", ${request.remote_name.addr_type})); + bro_analyzer()->ProtocolViolation(zeek::util::fmt("invalid SOCKSv5 addr type: %d", ${request.remote_name.addr_type})); return false; } @@ -142,7 +142,7 @@ refine connection SOCKS_Conn += { break; default: - bro_analyzer()->ProtocolViolation(fmt("invalid SOCKSv5 addr type: %d", ${reply.bound.addr_type})); + bro_analyzer()->ProtocolViolation(zeek::util::fmt("invalid SOCKSv5 addr type: %d", ${reply.bound.addr_type})); return false; } @@ -175,13 +175,13 @@ refine connection SOCKS_Conn += { function socks5_unsupported_authentication_method(auth_method: uint8): bool %{ - zeek::reporter->Weird(bro_analyzer()->Conn(), "socks5_unsupported_authentication_method", fmt("%d", auth_method)); + zeek::reporter->Weird(bro_analyzer()->Conn(), "socks5_unsupported_authentication_method", zeek::util::fmt("%d", auth_method)); return true; %} function socks5_unsupported_authentication_version(auth_method: uint8, version: uint8): bool %{ - zeek::reporter->Weird(bro_analyzer()->Conn(), "socks5_unsupported_authentication", fmt("method %d, version %d", auth_method, version)); + zeek::reporter->Weird(bro_analyzer()->Conn(), "socks5_unsupported_authentication", zeek::util::fmt("method %d, version %d", auth_method, version)); return true; %} @@ -196,7 +196,7 @@ refine connection SOCKS_Conn += { function version_error(version: uint8): bool %{ - bro_analyzer()->ProtocolViolation(fmt("unsupported/unknown SOCKS version %d", version)); + bro_analyzer()->ProtocolViolation(zeek::util::fmt("unsupported/unknown SOCKS version %d", version)); return true; %} diff --git a/src/analyzer/protocol/ssh/SSH.cc b/src/analyzer/protocol/ssh/SSH.cc index 34d4bd97a5..518f175cbb 100644 --- a/src/analyzer/protocol/ssh/SSH.cc +++ b/src/analyzer/protocol/ssh/SSH.cc @@ -69,7 +69,7 @@ void SSH_Analyzer::DeliverStream(int len, const u_char* data, bool orig) } catch ( const binpac::Exception& e ) { - ProtocolViolation(fmt("Binpac exception: %s", e.c_msg())); + ProtocolViolation(zeek::util::fmt("Binpac exception: %s", e.c_msg())); } auto encrypted_len = interp->get_encrypted_bytes_in_current_segment(); diff --git a/src/analyzer/protocol/ssl/DTLS.cc b/src/analyzer/protocol/ssl/DTLS.cc index f62e21dbce..787c5c46b8 100644 --- a/src/analyzer/protocol/ssl/DTLS.cc +++ b/src/analyzer/protocol/ssl/DTLS.cc @@ -66,7 +66,7 @@ void DTLS_Analyzer::SendHandshake(uint16_t raw_tls_version, uint8_t msg_type, ui } catch ( const binpac::Exception& e ) { - ProtocolViolation(fmt("Binpac exception: %s", e.c_msg())); + ProtocolViolation(zeek::util::fmt("Binpac exception: %s", e.c_msg())); } } diff --git a/src/analyzer/protocol/ssl/SSL.cc b/src/analyzer/protocol/ssl/SSL.cc index d922e98003..2330fa4000 100644 --- a/src/analyzer/protocol/ssl/SSL.cc +++ b/src/analyzer/protocol/ssl/SSL.cc @@ -67,7 +67,7 @@ void SSL_Analyzer::DeliverStream(int len, const u_char* data, bool orig) } catch ( const binpac::Exception& e ) { - ProtocolViolation(fmt("Binpac exception: %s", e.c_msg())); + ProtocolViolation(zeek::util::fmt("Binpac exception: %s", e.c_msg())); } } @@ -80,7 +80,7 @@ void SSL_Analyzer::SendHandshake(uint16_t raw_tls_version, const u_char* begin, } catch ( const binpac::Exception& e ) { - ProtocolViolation(fmt("Binpac exception: %s", e.c_msg())); + ProtocolViolation(zeek::util::fmt("Binpac exception: %s", e.c_msg())); } } diff --git a/src/analyzer/protocol/ssl/dtls-analyzer.pac b/src/analyzer/protocol/ssl/dtls-analyzer.pac index 990f1841b1..c650483332 100644 --- a/src/analyzer/protocol/ssl/dtls-analyzer.pac +++ b/src/analyzer/protocol/ssl/dtls-analyzer.pac @@ -55,7 +55,7 @@ refine connection SSL_Conn += { if ( length > MAX_DTLS_HANDSHAKE_RECORD ) { - bro_analyzer()->ProtocolViolation(fmt("DTLS record length %" PRId64 " larger than allowed maximum.", length)); + bro_analyzer()->ProtocolViolation(zeek::util::fmt("DTLS record length %" PRId64 " larger than allowed maximum.", length)); return true; } @@ -97,13 +97,13 @@ refine connection SSL_Conn += { // copy data from fragment to buffer if ( ${rec.data}.length() != flength ) { - bro_analyzer()->ProtocolViolation(fmt("DTLS handshake record length does not match packet length")); + bro_analyzer()->ProtocolViolation(zeek::util::fmt("DTLS handshake record length does not match packet length")); return true; } if ( foffset + flength > length ) { - bro_analyzer()->ProtocolViolation(fmt("DTLS handshake fragment trying to write past end of buffer")); + bro_analyzer()->ProtocolViolation(zeek::util::fmt("DTLS handshake fragment trying to write past end of buffer")); return true; } @@ -124,7 +124,7 @@ refine connection SSL_Conn += { uint64 total_length = i->message_last_sequence - i->message_first_sequence; if ( total_length > 30 ) { - bro_analyzer()->ProtocolViolation(fmt("DTLS Message fragmented over more than 30 pieces. Cannot reassemble.")); + bro_analyzer()->ProtocolViolation(zeek::util::fmt("DTLS Message fragmented over more than 30 pieces. Cannot reassemble.")); return true; } @@ -147,4 +147,3 @@ refine typeattr SSLRecord += &let { refine typeattr Handshake += &let { proc: bool = $context.connection.proc_handshake(rec, this); }; - diff --git a/src/analyzer/protocol/ssl/dtls-protocol.pac b/src/analyzer/protocol/ssl/dtls-protocol.pac index c54a62f251..ded8549388 100644 --- a/src/analyzer/protocol/ssl/dtls-protocol.pac +++ b/src/analyzer/protocol/ssl/dtls-protocol.pac @@ -74,7 +74,7 @@ refine connection SSL_Conn += { { reported_errors_++; if ( reported_errors_ <= zeek::BifConst::SSL::dtls_max_reported_version_errors ) - bro_analyzer()->ProtocolViolation(fmt("Invalid version in DTLS connection. Packet reported version: %d", version)); + bro_analyzer()->ProtocolViolation(zeek::util::fmt("Invalid version in DTLS connection. Packet reported version: %d", version)); } if ( invalid_version_count_ > zeek::BifConst::SSL::dtls_max_version_errors ) diff --git a/src/analyzer/protocol/ssl/proc-client-hello.pac b/src/analyzer/protocol/ssl/proc-client-hello.pac index c879b6e29a..af98a08c71 100644 --- a/src/analyzer/protocol/ssl/proc-client-hello.pac +++ b/src/analyzer/protocol/ssl/proc-client-hello.pac @@ -8,7 +8,7 @@ %{ if ( ! version_ok(version) ) { - bro_analyzer()->ProtocolViolation(fmt("unsupported client SSL version 0x%04x", version)); + bro_analyzer()->ProtocolViolation(zeek::util::fmt("unsupported client SSL version 0x%04x", version)); bro_analyzer()->SetSkip(true); } else diff --git a/src/analyzer/protocol/ssl/proc-server-hello.pac b/src/analyzer/protocol/ssl/proc-server-hello.pac index f49eacbc68..092090c2f8 100644 --- a/src/analyzer/protocol/ssl/proc-server-hello.pac +++ b/src/analyzer/protocol/ssl/proc-server-hello.pac @@ -8,7 +8,7 @@ %{ if ( ! version_ok(version) ) { - bro_analyzer()->ProtocolViolation(fmt("unsupported server SSL version 0x%04x", version)); + bro_analyzer()->ProtocolViolation(zeek::util::fmt("unsupported server SSL version 0x%04x", version)); bro_analyzer()->SetSkip(true); } diff --git a/src/analyzer/protocol/ssl/ssl-dtls-analyzer.pac b/src/analyzer/protocol/ssl/ssl-dtls-analyzer.pac index ae4a86b460..126f4ce58b 100644 --- a/src/analyzer/protocol/ssl/ssl-dtls-analyzer.pac +++ b/src/analyzer/protocol/ssl/ssl-dtls-analyzer.pac @@ -38,7 +38,7 @@ refine connection SSL_Conn += { %} function proc_unknown_record(rec: SSLRecord) : bool %{ - bro_analyzer()->ProtocolViolation(fmt("unknown SSL record type (%d) from %s", + bro_analyzer()->ProtocolViolation(zeek::util::fmt("unknown SSL record type (%d) from %s", ${rec.content_type}, orig_label(${rec.is_orig}).c_str())); return true; @@ -84,7 +84,7 @@ refine connection SSL_Conn += { %{ if ( version != SSLv20 ) { - bro_analyzer()->ProtocolViolation(fmt("Invalid version in SSL server hello. Version: %d", version)); + bro_analyzer()->ProtocolViolation(zeek::util::fmt("Invalid version in SSL server hello. Version: %d", version)); bro_analyzer()->SetSkip(true); return false; } diff --git a/src/analyzer/protocol/ssl/ssl-dtls-protocol.pac b/src/analyzer/protocol/ssl/ssl-dtls-protocol.pac index a72e1d5938..d75e6a97b9 100644 --- a/src/analyzer/protocol/ssl/ssl-dtls-protocol.pac +++ b/src/analyzer/protocol/ssl/ssl-dtls-protocol.pac @@ -32,7 +32,7 @@ enum AnalyzerState { return string("ENCRYPTED"); default: - return string(fmt("UNKNOWN (%d)", state_nr)); + return string(zeek::util::fmt("UNKNOWN (%d)", state_nr)); } } %} diff --git a/src/analyzer/protocol/ssl/ssl-protocol.pac b/src/analyzer/protocol/ssl/ssl-protocol.pac index 5f86f997ab..0235611aa6 100644 --- a/src/analyzer/protocol/ssl/ssl-protocol.pac +++ b/src/analyzer/protocol/ssl/ssl-protocol.pac @@ -154,7 +154,7 @@ refine connection SSL_Conn += { if ( version != SSLv30 && version != TLSv10 && version != TLSv11 && version != TLSv12 ) { - bro_analyzer()->ProtocolViolation(fmt("Invalid version late in TLS connection. Packet reported version: %d", version)); + bro_analyzer()->ProtocolViolation(zeek::util::fmt("Invalid version late in TLS connection. Packet reported version: %d", version)); bro_analyzer()->SetSkip(true); return UNKNOWN_VERSION; } @@ -171,7 +171,7 @@ refine connection SSL_Conn += { if ( version != SSLv20 && version != SSLv30 && version != TLSv10 && version != TLSv11 && version != TLSv12 ) { - bro_analyzer()->ProtocolViolation(fmt("Invalid version in SSL client hello. Version: %d", version)); + bro_analyzer()->ProtocolViolation(zeek::util::fmt("Invalid version in SSL client hello. Version: %d", version)); bro_analyzer()->SetSkip(true); return UNKNOWN_VERSION; } @@ -188,7 +188,7 @@ refine connection SSL_Conn += { else // this is not SSL or TLS. { - bro_analyzer()->ProtocolViolation(fmt("Invalid headers in SSL connection. Head1: %d, head2: %d, head3: %d", head1, head2, head3)); + bro_analyzer()->ProtocolViolation(zeek::util::fmt("Invalid headers in SSL connection. Head1: %d, head2: %d, head3: %d", head1, head2, head3)); bro_analyzer()->SetSkip(true); return UNKNOWN_VERSION; } @@ -198,7 +198,7 @@ refine connection SSL_Conn += { if ( version != SSLv30 && version != TLSv10 && version != TLSv11 && version != TLSv12 ) { - bro_analyzer()->ProtocolViolation(fmt("Invalid version in TLS connection. Version: %d", version)); + bro_analyzer()->ProtocolViolation(zeek::util::fmt("Invalid version in TLS connection. Version: %d", version)); bro_analyzer()->SetSkip(true); return UNKNOWN_VERSION; } @@ -209,7 +209,7 @@ refine connection SSL_Conn += { return version; } - bro_analyzer()->ProtocolViolation(fmt("Invalid type in TLS connection. Version: %d, Type: %d", version, head0)); + bro_analyzer()->ProtocolViolation(zeek::util::fmt("Invalid type in TLS connection. Version: %d, Type: %d", version, head0)); bro_analyzer()->SetSkip(true); return UNKNOWN_VERSION; %} diff --git a/src/analyzer/protocol/ssl/tls-handshake-analyzer.pac b/src/analyzer/protocol/ssl/tls-handshake-analyzer.pac index 6089e42eb7..41972c9614 100644 --- a/src/analyzer/protocol/ssl/tls-handshake-analyzer.pac +++ b/src/analyzer/protocol/ssl/tls-handshake-analyzer.pac @@ -55,7 +55,7 @@ refine connection Handshake_Conn += { { // This should be impossible due to the binpac parser // and protocol description - bro_analyzer()->ProtocolViolation(fmt("Impossible extension length: %zu", length)); + bro_analyzer()->ProtocolViolation(zeek::util::fmt("Impossible extension length: %zu", length)); bro_analyzer()->SetSkip(true); return true; } @@ -203,7 +203,7 @@ refine connection Handshake_Conn += { ServerName* servername = (*list)[i]; if ( servername->name_type() != 0 ) { - bro_analyzer()->Weird("ssl_ext_unknown_server_name_type", fmt("%d", servername->name_type())); + bro_analyzer()->Weird("ssl_ext_unknown_server_name_type", zeek::util::fmt("%d", servername->name_type())); continue; } @@ -288,7 +288,7 @@ refine connection Handshake_Conn += { function proc_unknown_handshake(hs: HandshakeRecord, is_orig: bool) : bool %{ - bro_analyzer()->ProtocolViolation(fmt("unknown handshake message (%d) from %s", + bro_analyzer()->ProtocolViolation(zeek::util::fmt("unknown handshake message (%d) from %s", ${hs.msg_type}, orig_label(is_orig).c_str())); return true; %} diff --git a/src/analyzer/protocol/tcp/TCP.cc b/src/analyzer/protocol/tcp/TCP.cc index b680e805ff..a6273076ac 100644 --- a/src/analyzer/protocol/tcp/TCP.cc +++ b/src/analyzer/protocol/tcp/TCP.cc @@ -1387,7 +1387,7 @@ int TCP_Analyzer::ParseTCPOptions(const struct tcphdr* tcp, bool is_orig) else { add_option_data(option_record, o, length); - Weird("tcp_option_mss_invalid_len", fmt("%d", length)); + Weird("tcp_option_mss_invalid_len", zeek::util::fmt("%d", length)); } break; @@ -1401,7 +1401,7 @@ int TCP_Analyzer::ParseTCPOptions(const struct tcphdr* tcp, bool is_orig) else { add_option_data(option_record, o, length); - Weird("tcp_option_window_scale_invalid_len", fmt("%d", length)); + Weird("tcp_option_window_scale_invalid_len", zeek::util::fmt("%d", length)); } break; @@ -1410,7 +1410,7 @@ int TCP_Analyzer::ParseTCPOptions(const struct tcphdr* tcp, bool is_orig) if ( length != 2 ) { add_option_data(option_record, o, length); - Weird("tcp_option_sack_invalid_len", fmt("%d", length)); + Weird("tcp_option_sack_invalid_len", zeek::util::fmt("%d", length)); } break; @@ -1432,7 +1432,7 @@ int TCP_Analyzer::ParseTCPOptions(const struct tcphdr* tcp, bool is_orig) else { add_option_data(option_record, o, length); - Weird("tcp_option_sack_blocks_invalid_len", fmt("%d", length)); + Weird("tcp_option_sack_blocks_invalid_len", zeek::util::fmt("%d", length)); } break; @@ -1448,7 +1448,7 @@ int TCP_Analyzer::ParseTCPOptions(const struct tcphdr* tcp, bool is_orig) else { add_option_data(option_record, o, length); - Weird("tcp_option_timestamps_invalid_len", fmt("%d", length)); + Weird("tcp_option_timestamps_invalid_len", zeek::util::fmt("%d", length)); } break; @@ -1906,7 +1906,7 @@ void TCP_ApplicationAnalyzer::DeliverPacket(int len, const u_char* data, Analyzer::DeliverPacket(len, data, is_orig, seq, ip, caplen); DBG_LOG(zeek::DBG_ANALYZER, "TCP_ApplicationAnalyzer ignoring DeliverPacket(%d, %s, %" PRIu64", %p, %d) [%s%s]", len, is_orig ? "T" : "F", seq, ip, caplen, - fmt_bytes((const char*) data, std::min(40, len)), len > 40 ? "..." : ""); + zeek::util::fmt_bytes((const char*) data, std::min(40, len)), len > 40 ? "..." : ""); } void TCP_ApplicationAnalyzer::SetEnv(bool /* is_orig */, char* name, char* val) diff --git a/src/analyzer/protocol/tcp/TCP_Endpoint.cc b/src/analyzer/protocol/tcp/TCP_Endpoint.cc index 93c21eec78..ddc36e3df7 100644 --- a/src/analyzer/protocol/tcp/TCP_Endpoint.cc +++ b/src/analyzer/protocol/tcp/TCP_Endpoint.cc @@ -233,7 +233,7 @@ bool TCP_Endpoint::DataSent(double t, uint64_t seq, int len, int caplen, if ( fwrite(data, 1, len, f) < unsigned(len) ) { char buf[256]; - bro_strerror_r(errno, buf, sizeof(buf)); + zeek::util::zeek_strerror_r(errno, buf, sizeof(buf)); zeek::reporter->Error("TCP contents write failed: %s", buf); if ( contents_file_write_failure ) diff --git a/src/analyzer/protocol/tcp/TCP_Reassembler.cc b/src/analyzer/protocol/tcp/TCP_Reassembler.cc index 754c87fe2b..3926bf8d4f 100644 --- a/src/analyzer/protocol/tcp/TCP_Reassembler.cc +++ b/src/analyzer/protocol/tcp/TCP_Reassembler.cc @@ -365,7 +365,7 @@ void TCP_Reassembler::RecordBlock(const zeek::DataBlock& b, const zeek::FilePtr& void TCP_Reassembler::RecordGap(uint64_t start_seq, uint64_t upper_seq, const zeek::FilePtr& f) { - if ( f->Write(fmt("\n<>\n", upper_seq - start_seq)) ) + if ( f->Write(zeek::util::fmt("\n<>\n", upper_seq - start_seq)) ) return; zeek::reporter->Error("TCP_Reassembler contents gap write failed"); diff --git a/src/analyzer/protocol/udp/UDP.cc b/src/analyzer/protocol/udp/UDP.cc index 8f250deeb1..c66feb1fe4 100644 --- a/src/analyzer/protocol/udp/UDP.cc +++ b/src/analyzer/protocol/udp/UDP.cc @@ -124,7 +124,7 @@ void UDP_Analyzer::DeliverPacket(int len, const u_char* data, bool is_orig, int ulen = ntohs(up->uh_ulen); if ( ulen != len ) - Weird("UDP_datagram_length_mismatch", fmt("%d != %d", ulen, len)); + Weird("UDP_datagram_length_mismatch", zeek::util::fmt("%d != %d", ulen, len)); len -= sizeof(struct udphdr); ulen -= sizeof(struct udphdr); diff --git a/src/analyzer/protocol/xmpp/XMPP.cc b/src/analyzer/protocol/xmpp/XMPP.cc index c3919b2b0f..8651c3f615 100644 --- a/src/analyzer/protocol/xmpp/XMPP.cc +++ b/src/analyzer/protocol/xmpp/XMPP.cc @@ -60,7 +60,7 @@ void XMPP_Analyzer::DeliverStream(int len, const u_char* data, bool orig) } catch ( const binpac::Exception& e ) { - ProtocolViolation(fmt("Binpac exception: %s", e.c_msg())); + ProtocolViolation(zeek::util::fmt("Binpac exception: %s", e.c_msg())); } } diff --git a/src/broker/Manager.cc b/src/broker/Manager.cc index 3f0fa3d12f..cb60344ec0 100644 --- a/src/broker/Manager.cc +++ b/src/broker/Manager.cc @@ -84,17 +84,17 @@ struct scoped_reporter_location { #ifdef DEBUG static std::string RenderMessage(std::string topic, const broker::data& x) { - return fmt("%s -> %s", broker::to_string(x).c_str(), topic.c_str()); + return zeek::util::fmt("%s -> %s", broker::to_string(x).c_str(), topic.c_str()); } static std::string RenderEvent(std::string topic, std::string name, const broker::data& args) { - return fmt("%s(%s) -> %s", name.c_str(), broker::to_string(args).c_str(), topic.c_str()); + return zeek::util::fmt("%s(%s) -> %s", name.c_str(), broker::to_string(args).c_str(), topic.c_str()); } static std::string RenderMessage(const broker::store::response& x) { - return fmt("%s [id %" PRIu64 "]", (x.answer ? broker::to_string(*x.answer).c_str() : ""), x.id); + return zeek::util::fmt("%s [id %" PRIu64 "]", (x.answer ? broker::to_string(*x.answer).c_str() : ""), x.id); } static std::string RenderMessage(const broker::vector* xs) @@ -119,7 +119,7 @@ static std::string RenderMessage(const broker::status& s) static std::string RenderMessage(const broker::error& e) { - return fmt("%s (%s)", broker::to_string(e.code()).c_str(), + return zeek::util::fmt("%s (%s)", broker::to_string(e.code()).c_str(), caf::to_string(e.context()).c_str()); } @@ -174,14 +174,14 @@ void Manager::InitPostScript() auto scheduler_policy = get_option("Broker::scheduler_policy")->AsString()->CheckString(); - if ( streq(scheduler_policy, "sharing") ) + if ( zeek::util::streq(scheduler_policy, "sharing") ) config.set("scheduler.policy", caf::atom("sharing")); - else if ( streq(scheduler_policy, "stealing") ) + else if ( zeek::util::streq(scheduler_policy, "stealing") ) config.set("scheduler.policy", caf::atom("stealing")); else zeek::reporter->FatalError("Invalid Broker::scheduler_policy: %s", scheduler_policy); - auto max_threads_env = zeekenv("ZEEK_BROKER_MAX_THREADS"); + auto max_threads_env = zeek::util::zeekenv("ZEEK_BROKER_MAX_THREADS"); if ( max_threads_env ) config.set("scheduler.max-threads", atoi(max_threads_env)); @@ -369,7 +369,7 @@ void Manager::Peer(const string& addr, uint16_t port, double retry) DBG_LOG(zeek::DBG_BROKER, "Starting to peer with %s:%" PRIu16, addr.c_str(), port); - auto e = zeekenv("ZEEK_DEFAULT_CONNECT_RETRY"); + auto e = zeek::util::zeekenv("ZEEK_DEFAULT_CONNECT_RETRY"); if ( e ) retry = atoi(e); @@ -394,7 +394,7 @@ void Manager::Unpeer(const string& addr, uint16_t port) return; DBG_LOG(zeek::DBG_BROKER, "Stopping to peer with %s:%" PRIu16, - addr.c_str(), port); + addr.c_str(), port); FlushLogBuffers(); bstate->endpoint.unpeer_nosync(addr, port); @@ -679,7 +679,7 @@ void Manager::Error(const char* format, ...) { va_list args; va_start(args, format); - auto msg = vfmt(format, args); + auto msg = zeek::util::vfmt(format, args); va_end(args); if ( script_scope ) @@ -923,7 +923,7 @@ void Manager::Process() // Ensure that time gets update before processing broker messages, or events // based on them might get scheduled wrong. if ( use_real_time ) - zeek::net::detail::net_update_time(current_time()); + zeek::net::detail::net_update_time(zeek::util::current_time()); bool had_input = false; @@ -999,7 +999,7 @@ void Manager::Process() // If we're getting Broker messages, but still haven't initialized // zeek::net::network_time, may as well do so now because otherwise the // broker/cluster logs will end up using timestamp 0. - zeek::net::detail::net_update_time(current_time()); + zeek::net::detail::net_update_time(zeek::util::current_time()); } } @@ -1216,7 +1216,7 @@ void Manager::ProcessEvent(const broker::topic& topic, broker::zeek::Event ev) } if ( vl.size() == args.size() ) - zeek::event_mgr.Enqueue(handler, std::move(vl), SOURCE_BROKER); + zeek::event_mgr.Enqueue(handler, std::move(vl), zeek::util::SOURCE_BROKER); } bool Manager::ProcessLogCreate(broker::zeek::LogCreate lc) @@ -1499,7 +1499,7 @@ void Manager::ProcessError(broker::error err) else { ec = BifEnum::Broker::ErrorCode::CAF_ERROR; - msg = fmt("[%s] %s", caf::to_string(err.category()).c_str(), caf::to_string(err.context()).c_str()); + msg = zeek::util::fmt("[%s] %s", caf::to_string(err.category()).c_str(), caf::to_string(err.context()).c_str()); } zeek::event_mgr.Enqueue(::Broker::error, diff --git a/src/broker/store.bif b/src/broker/store.bif index a404db83b2..fceb43e68b 100644 --- a/src/broker/store.bif +++ b/src/broker/store.bif @@ -41,7 +41,7 @@ function Broker::__create_master%(id: string, b: BackendType, if ( ! store ) { - zeek::emit_builtin_error(fmt("Could not create Broker master store '%s'", name)); + zeek::emit_builtin_error(zeek::util::fmt("Could not create Broker master store '%s'", name)); return nullptr; } @@ -66,7 +66,7 @@ function Broker::__create_clone%(id: string, resync_interval: interval, if ( ! store ) { - zeek::emit_builtin_error(fmt("Could not create clone of Broker store '%s'", name)); + zeek::emit_builtin_error(zeek::util::fmt("Could not create clone of Broker store '%s'", name)); return nullptr; } diff --git a/src/file_analysis/File.cc b/src/file_analysis/File.cc index 6e96122e80..61092c6796 100644 --- a/src/file_analysis/File.cc +++ b/src/file_analysis/File.cc @@ -390,7 +390,7 @@ void File::DeliverStream(const u_char* data, uint64_t len) "[%s] %" PRIu64 " stream bytes in at offset %" PRIu64 "; %s [%s%s]", id.c_str(), len, stream_offset, IsComplete() ? "complete" : "incomplete", - fmt_bytes((const char*) data, std::min((uint64_t)40, len)), + zeek::util::fmt_bytes((const char*) data, std::min((uint64_t)40, len)), len > 40 ? "..." : ""); file_analysis::Analyzer* a = nullptr; @@ -494,7 +494,7 @@ void File::DeliverChunk(const u_char* data, uint64_t len, uint64_t offset) "[%s] %" PRIu64 " chunk bytes in at offset %" PRIu64 "; %s [%s%s]", id.c_str(), len, offset, IsComplete() ? "complete" : "incomplete", - fmt_bytes((const char*) data, std::min((uint64_t)40, len)), + zeek::util::fmt_bytes((const char*) data, std::min((uint64_t)40, len)), len > 40 ? "..." : ""); file_analysis::Analyzer* a = nullptr; diff --git a/src/file_analysis/analyzer/extract/Extract.cc b/src/file_analysis/analyzer/extract/Extract.cc index 6d9f4de30c..5df33a6141 100644 --- a/src/file_analysis/analyzer/extract/Extract.cc +++ b/src/file_analysis/analyzer/extract/Extract.cc @@ -22,7 +22,7 @@ Extract::Extract(zeek::RecordValPtr args, zeek::file_analysis::File* file, { fd = 0; char buf[128]; - bro_strerror_r(errno, buf, sizeof(buf)); + zeek::util::zeek_strerror_r(errno, buf, sizeof(buf)); zeek::reporter->Error("cannot open %s: %s", filename.c_str(), buf); } } @@ -30,7 +30,7 @@ Extract::Extract(zeek::RecordValPtr args, zeek::file_analysis::File* file, Extract::~Extract() { if ( fd ) - safe_close(fd); + zeek::util::safe_close(fd); } static const zeek::ValPtr& get_extract_field_val(const zeek::RecordValPtr& args, @@ -107,7 +107,7 @@ bool Extract::DeliverStream(const u_char* data, uint64_t len) if ( towrite > 0 ) { - safe_write(fd, reinterpret_cast(data), towrite); + zeek::util::safe_write(fd, reinterpret_cast(data), towrite); depth += towrite; } @@ -119,7 +119,7 @@ bool Extract::Undelivered(uint64_t offset, uint64_t len) if ( depth == offset ) { char* tmp = new char[len](); - safe_write(fd, tmp, len); + zeek::util::safe_write(fd, tmp, len); delete [] tmp; depth += len; } diff --git a/src/file_analysis/analyzer/hash/Hash.cc b/src/file_analysis/analyzer/hash/Hash.cc index 97f7008047..087d5554ce 100644 --- a/src/file_analysis/analyzer/hash/Hash.cc +++ b/src/file_analysis/analyzer/hash/Hash.cc @@ -11,7 +11,7 @@ namespace zeek::file_analysis::detail { Hash::Hash(zeek::RecordValPtr args, zeek::file_analysis::File* file, zeek::HashVal* hv, const char* arg_kind) - : zeek::file_analysis::Analyzer(zeek::file_mgr->GetComponentTag(to_upper(arg_kind).c_str()), + : zeek::file_analysis::Analyzer(zeek::file_mgr->GetComponentTag(zeek::util::to_upper(arg_kind).c_str()), std::move(args), file), hash(hv), fed(false), kind(arg_kind) { diff --git a/src/file_analysis/analyzer/x509/X509.cc b/src/file_analysis/analyzer/x509/X509.cc index 398eef65f8..25e289f953 100644 --- a/src/file_analysis/analyzer/x509/X509.cc +++ b/src/file_analysis/analyzer/x509/X509.cc @@ -261,7 +261,7 @@ X509_STORE* X509::GetRootStore(zeek::TableVal* root_certs) ::X509* x = d2i_X509(NULL, &data, sv->Len()); if ( ! x ) { - zeek::emit_builtin_error(fmt("Root CA error: %s", ERR_error_string(ERR_get_error(), NULL))); + zeek::emit_builtin_error(zeek::util::fmt("Root CA error: %s", ERR_error_string(ERR_get_error(), NULL))); return nullptr; } @@ -408,7 +408,7 @@ void X509::ParseSAN(X509_EXTENSION* ext) else { - zeek::reporter->Weird(GetFile(), "x509_san_ip_length", fmt("%d", gen->d.ip->length)); + zeek::reporter->Weird(GetFile(), "x509_san_ip_length", zeek::util::fmt("%d", gen->d.ip->length)); continue; } } diff --git a/src/file_analysis/analyzer/x509/functions.bif b/src/file_analysis/analyzer/x509/functions.bif index 9e6687b256..b6cdfab0b8 100644 --- a/src/file_analysis/analyzer/x509/functions.bif +++ b/src/file_analysis/analyzer/x509/functions.bif @@ -29,7 +29,7 @@ STACK_OF(X509)* x509_get_untrusted_stack(zeek::VectorVal* certs_vec) STACK_OF(X509)* untrusted_certs = sk_X509_new_null(); if ( ! untrusted_certs ) { - zeek::emit_builtin_error(fmt("Untrusted certificate stack initialization error: %s", + zeek::emit_builtin_error(zeek::util::fmt("Untrusted certificate stack initialization error: %s", ERR_error_string(ERR_get_error(),NULL))); return 0; } @@ -46,7 +46,7 @@ STACK_OF(X509)* x509_get_untrusted_stack(zeek::VectorVal* certs_vec) if ( ! x ) { sk_X509_free(untrusted_certs); - zeek::emit_builtin_error(fmt("No certificate in opaque in stack")); + zeek::emit_builtin_error(zeek::util::fmt("No certificate in opaque in stack")); return 0; } @@ -243,7 +243,7 @@ function x509_ocsp_verify%(certs: x509_opaque_vector, ocsp_reply: string, root_c X509* cert = cert_handle->GetCertificate(); if ( ! cert ) { - zeek::emit_builtin_error(fmt("No certificate in opaque")); + zeek::emit_builtin_error(zeek::util::fmt("No certificate in opaque")); return x509_result_record(-1, "No certificate in opaque"); } @@ -528,7 +528,7 @@ function x509_verify%(certs: x509_opaque_vector, root_certs: table_string_of_str X509* cert = cert_handle->GetCertificate(); if ( ! cert ) { - zeek::emit_builtin_error(fmt("No certificate in opaque")); + zeek::emit_builtin_error(zeek::util::fmt("No certificate in opaque")); return x509_result_record(-1, "No certificate in opaque"); } diff --git a/src/fuzzers/fuzzer-setup.h b/src/fuzzers/fuzzer-setup.h index be0b983a87..de8f2275b5 100644 --- a/src/fuzzers/fuzzer-setup.h +++ b/src/fuzzers/fuzzer-setup.h @@ -20,9 +20,9 @@ extern "C" int LLVMFuzzerInitialize(int* argc, char*** argv) auto constexpr oss_fuzz_scripts = "oss-fuzz-zeek-scripts"; auto fuzzer_path = get_exe_path(*argv[0]); auto fuzzer_dir = SafeDirname(fuzzer_path).result; - std::string fs = fmt("%s/%s", fuzzer_dir.data(), oss_fuzz_scripts); + std::string fs = zeek::util::fmt("%s/%s", fuzzer_dir.data(), oss_fuzz_scripts); auto p = fs.data(); - auto oss_fuzz_zeekpath = fmt(".:%s:%s/policy:%s/site", p, p, p); + auto oss_fuzz_zeekpath = zeek::util::fmt(".:%s:%s/policy:%s/site", p, p, p); if ( setenv("ZEEKPATH", oss_fuzz_zeekpath, true) == -1 ) abort(); diff --git a/src/input/Manager.cc b/src/input/Manager.cc index 7e13d9e5c6..e1421332db 100644 --- a/src/input/Manager.cc +++ b/src/input/Manager.cc @@ -244,8 +244,8 @@ bool Manager::CreateStream(Stream* info, zeek::RecordVal* description) string source((const char*) bsource->Bytes(), bsource->Len()); ReaderBackend::ReaderInfo rinfo; - rinfo.source = copy_string(source.c_str()); - rinfo.name = copy_string(name.c_str()); + rinfo.source = zeek::util::copy_string(source.c_str()); + rinfo.name = zeek::util::copy_string(name.c_str()); auto mode_val = description->GetFieldOrDefault("mode"); auto mode = mode_val->AsEnumVal(); @@ -282,7 +282,7 @@ bool Manager::CreateStream(Stream* info, zeek::RecordVal* description) auto index = info->config->RecreateIndex(*k); string key = index->Idx(0)->AsString()->CheckString(); string value = v->GetVal()->AsString()->CheckString(); - rinfo.config.insert(std::make_pair(copy_string(key.c_str()), copy_string(value.c_str()))); + rinfo.config.insert(std::make_pair(zeek::util::copy_string(key.c_str()), zeek::util::copy_string(value.c_str()))); delete k; } } @@ -1828,7 +1828,7 @@ void Manager::SendEvent(zeek::EventHandlerPtr ev, const int numvals, ...) const va_end(lP); if ( ev ) - zeek::event_mgr.Enqueue(ev, std::move(vl), SOURCE_LOCAL); + zeek::event_mgr.Enqueue(ev, std::move(vl), zeek::util::SOURCE_LOCAL); } void Manager::SendEvent(zeek::EventHandlerPtr ev, list events) const @@ -1845,7 +1845,7 @@ void Manager::SendEvent(zeek::EventHandlerPtr ev, list events) const vl.emplace_back(zeek::AdoptRef{}, *i); if ( ev ) - zeek::event_mgr.Enqueue(ev, std::move(vl), SOURCE_LOCAL); + zeek::event_mgr.Enqueue(ev, std::move(vl), zeek::util::SOURCE_LOCAL); } // Convert a bro list value to a bro record value. diff --git a/src/input/ReaderBackend.cc b/src/input/ReaderBackend.cc index ec7e46dc80..14dfa4262e 100644 --- a/src/input/ReaderBackend.cc +++ b/src/input/ReaderBackend.cc @@ -63,7 +63,7 @@ public: ReaderErrorMessage(ReaderFrontend* reader, Type arg_type, const char* arg_msg) : threading::OutputMessage("ReaderErrorMessage", reader) - { type = arg_type; msg = copy_string(arg_msg); } + { type = arg_type; msg = zeek::util::copy_string(arg_msg); } ~ReaderErrorMessage() override { delete [] msg; } diff --git a/src/input/ReaderBackend.h b/src/input/ReaderBackend.h index 6356112e8d..88cc3e2f46 100644 --- a/src/input/ReaderBackend.h +++ b/src/input/ReaderBackend.h @@ -75,7 +75,7 @@ public: struct ReaderInfo { // Structure takes ownership of the strings. - typedef std::map config_map; + typedef std::map config_map; /** * A string left to the interpretation of the reader @@ -111,12 +111,12 @@ public: ReaderInfo(const ReaderInfo& other) { - source = other.source ? copy_string(other.source) : nullptr; - name = other.name ? copy_string(other.name) : nullptr; + source = other.source ? zeek::util::copy_string(other.source) : nullptr; + name = other.name ? zeek::util::copy_string(other.name) : nullptr; mode = other.mode; for ( config_map::const_iterator i = other.config.begin(); i != other.config.end(); i++ ) - config.insert(std::make_pair(copy_string(i->first), copy_string(i->second))); + config.insert(std::make_pair(zeek::util::copy_string(i->first), zeek::util::copy_string(i->second))); } ~ReaderInfo() diff --git a/src/input/ReaderFrontend.cc b/src/input/ReaderFrontend.cc index ab6c6cc4f0..cd1367dc6d 100644 --- a/src/input/ReaderFrontend.cc +++ b/src/input/ReaderFrontend.cc @@ -40,7 +40,7 @@ ReaderFrontend::ReaderFrontend(const ReaderBackend::ReaderInfo& arg_info, zeek:: info = new ReaderBackend::ReaderInfo(arg_info); const char* t = type->GetType()->AsEnumType()->Lookup(type->InternalInt()); - name = copy_string(fmt("%s/%s", arg_info.source, t)); + name = zeek::util::copy_string(zeek::util::fmt("%s/%s", arg_info.source, t)); backend = input_mgr->CreateBackend(this, type); assert(backend); diff --git a/src/input/readers/benchmark/Benchmark.cc b/src/input/readers/benchmark/Benchmark.cc index 783e43b479..6b25c9c350 100644 --- a/src/input/readers/benchmark/Benchmark.cc +++ b/src/input/readers/benchmark/Benchmark.cc @@ -137,7 +137,7 @@ zeek::threading::Value* Benchmark::EntryToVal(zeek::TypeTag type, zeek::TypeTag case zeek::TYPE_STRING: { std::string rnd = RandomString(10); - val->val.string_val.data = copy_string(rnd.c_str()); + val->val.string_val.data = zeek::util::copy_string(rnd.c_str()); val->val.string_val.length = rnd.size(); break; } diff --git a/src/input/readers/config/Config.cc b/src/input/readers/config/Config.cc index 10c6621995..de926a23c0 100644 --- a/src/input/readers/config/Config.cc +++ b/src/input/readers/config/Config.cc @@ -248,11 +248,11 @@ bool Config::DoUpdate() Value** fields = new Value*[2]; Value* keyval = new threading::Value(zeek::TYPE_STRING, true); keyval->val.string_val.length = key.size(); - keyval->val.string_val.data = copy_string(key.c_str()); + keyval->val.string_val.data = zeek::util::copy_string(key.c_str()); fields[0] = keyval; Value* val = new threading::Value(zeek::TYPE_STRING, true); val->val.string_val.length = value.size(); - val->val.string_val.data = copy_string(value.c_str()); + val->val.string_val.data = zeek::util::copy_string(value.c_str()); fields[1] = val; if ( Info().mode == zeek::input::MODE_STREAM ) @@ -264,13 +264,13 @@ bool Config::DoUpdate() { Value** vals = new Value*[4]; vals[0] = new Value(zeek::TYPE_STRING, true); - vals[0]->val.string_val.data = copy_string(Info().name); + vals[0]->val.string_val.data = zeek::util::copy_string(Info().name); vals[0]->val.string_val.length = strlen(Info().name); vals[1] = new Value(zeek::TYPE_STRING, true); - vals[1]->val.string_val.data = copy_string(Info().source); + vals[1]->val.string_val.data = zeek::util::copy_string(Info().source); vals[1]->val.string_val.length = strlen(Info().source); vals[2] = new Value(zeek::TYPE_STRING, true); - vals[2]->val.string_val.data = copy_string(key.c_str()); + vals[2]->val.string_val.data = zeek::util::copy_string(key.c_str()); vals[2]->val.string_val.length = key.size(); vals[3] = eventval; diff --git a/src/input/readers/raw/Raw.cc b/src/input/readers/raw/Raw.cc index 9628429ffc..d57e231229 100644 --- a/src/input/readers/raw/Raw.cc +++ b/src/input/readers/raw/Raw.cc @@ -82,7 +82,7 @@ void Raw::ClosePipeEnd(int i) if ( pipes[i] == -1 ) return; - safe_close(pipes[i]); + zeek::util::safe_close(pipes[i]); pipes[i] = -1; } @@ -92,7 +92,7 @@ bool Raw::SetFDFlags(int fd, int cmd, int flags) return true; char buf[256]; - bro_strerror_r(errno, buf, sizeof(buf)); + zeek::util::zeek_strerror_r(errno, buf, sizeof(buf)); Error(Fmt("failed to set fd flags: %s", buf)); return false; } @@ -199,7 +199,7 @@ bool Raw::Execute() else { char buf[256]; - bro_strerror_r(errno, buf, sizeof(buf)); + zeek::util::zeek_strerror_r(errno, buf, sizeof(buf)); Warning(Fmt("Could not set child process group: %s", buf)); } } @@ -295,7 +295,7 @@ bool Raw::OpenInput() if ( fseek(file.get(), pos, whence) < 0 ) { char buf[256]; - bro_strerror_r(errno, buf, sizeof(buf)); + zeek::util::zeek_strerror_r(errno, buf, sizeof(buf)); Error(Fmt("Seek failed in init: %s", buf)); } } @@ -459,7 +459,8 @@ int64_t Raw::GetLine(FILE* arg_file) // researching everything each time is a bit... cpu-intensive. But otherwhise we have // to deal with situations where the separator is multi-character and split over multiple // reads... - int found = strstr_n(pos, (unsigned char*) buf.get(), separator.size(), (unsigned char*) separator.c_str()); + int found = zeek::util::strstr_n(pos, (unsigned char*) buf.get(), + separator.size(), (unsigned char*) separator.c_str()); if ( found == -1 ) { @@ -678,10 +679,10 @@ bool Raw::DoUpdate() Value** vals = new Value*[4]; vals[0] = new Value(zeek::TYPE_STRING, true); - vals[0]->val.string_val.data = copy_string(Info().name); + vals[0]->val.string_val.data = zeek::util::copy_string(Info().name); vals[0]->val.string_val.length = strlen(Info().name); vals[1] = new Value(zeek::TYPE_STRING, true); - vals[1]->val.string_val.data = copy_string(Info().source); + vals[1]->val.string_val.data = zeek::util::copy_string(Info().source); vals[1]->val.string_val.length = strlen(Info().source); vals[2] = new Value(zeek::TYPE_COUNT, true); vals[2]->val.int_val = code; diff --git a/src/iosource/Component.cc b/src/iosource/Component.cc index c7a1af6917..8a2b6abe74 100644 --- a/src/iosource/Component.cc +++ b/src/iosource/Component.cc @@ -24,7 +24,7 @@ Component::~Component() PktSrcComponent::PktSrcComponent(const std::string& arg_name, const std::string& arg_prefix, InputType arg_type, factory_callback arg_factory) : iosource::Component(zeek::plugin::component::PKTSRC, arg_name) { - tokenize_string(arg_prefix, ":", &prefixes); + zeek::util::tokenize_string(arg_prefix, ":", &prefixes); type = arg_type; factory = arg_factory; } @@ -110,7 +110,7 @@ void PktSrcComponent::DoDescribe(zeek::ODesc* d) const PktDumperComponent::PktDumperComponent(const std::string& name, const std::string& arg_prefix, factory_callback arg_factory) : zeek::plugin::Component(zeek::plugin::component::PKTDUMPER, name) { - tokenize_string(arg_prefix, ":", &prefixes); + zeek::util::tokenize_string(arg_prefix, ":", &prefixes); factory = arg_factory; } diff --git a/src/iosource/PktSrc.cc b/src/iosource/PktSrc.cc index ea8be1d2ee..3289d02b2a 100644 --- a/src/iosource/PktSrc.cc +++ b/src/iosource/PktSrc.cc @@ -83,7 +83,7 @@ double PktSrc::CurrentPacketWallClock() { // We stop time when we are suspended. if ( zeek::net::net_is_processing_suspended() ) - current_wallclock = current_time(true); + current_wallclock = zeek::util::current_time(true); return current_wallclock; } @@ -112,7 +112,7 @@ void PktSrc::Opened(const Properties& arg_props) if ( props.is_live ) { - Info(fmt("listening on %s\n", props.path.c_str())); + Info(zeek::util::fmt("listening on %s\n", props.path.c_str())); // We only register the file descriptor if we're in live // mode because libpcap's file descriptor for trace files @@ -163,7 +163,7 @@ void PktSrc::InternalError(const std::string& msg) void PktSrc::ContinueAfterSuspend() { - current_wallclock = current_time(true); + current_wallclock = zeek::util::current_time(true); } double PktSrc::CheckPseudoTime() @@ -175,7 +175,7 @@ double PktSrc::CheckPseudoTime() return 0; double pseudo_time = current_packet.time - first_timestamp; - double ct = (current_time(true) - first_wallclock) * zeek::net::pseudo_realtime; + double ct = (zeek::util::current_time(true) - first_wallclock) * zeek::net::pseudo_realtime; return pseudo_time <= ct ? zeek::net::zeek_start_time + pseudo_time : 0; } @@ -206,7 +206,7 @@ void PktSrc::Process() current_pseudo = CheckPseudoTime(); zeek::net::detail::net_packet_dispatch(current_pseudo, ¤t_packet, this); if ( ! first_wallclock ) - first_wallclock = current_time(true); + first_wallclock = zeek::util::current_time(true); } else @@ -235,7 +235,7 @@ bool PktSrc::ExtractNextPacketInternal() return false; if ( zeek::net::pseudo_realtime ) - current_wallclock = current_time(true); + current_wallclock = zeek::util::current_time(true); if ( ExtractNextPacket(¤t_packet) ) { @@ -273,7 +273,7 @@ bool PktSrc::PrecompileBPFFilter(int index, const std::string& filter) if ( ! code->Compile(zeek::BifConst::Pcap::snaplen, LinkType(), filter.c_str(), Netmask(), errbuf, sizeof(errbuf)) ) { - std::string msg = fmt("cannot compile BPF filter \"%s\"", filter.c_str()); + std::string msg = zeek::util::fmt("cannot compile BPF filter \"%s\"", filter.c_str()); if ( *errbuf ) msg += ": " + std::string(errbuf); @@ -310,7 +310,7 @@ bool PktSrc::ApplyBPFFilter(int index, const struct pcap_pkthdr *hdr, const u_ch if ( ! code ) { - Error(fmt("BPF filter %d not compiled", index)); + Error(zeek::util::fmt("BPF filter %d not compiled", index)); Close(); return false; } @@ -353,7 +353,7 @@ double PktSrc::GetNextTimeout() ExtractNextPacketInternal(); double pseudo_time = current_packet.time - first_timestamp; - double ct = (current_time(true) - first_wallclock) * zeek::net::pseudo_realtime; + double ct = (zeek::util::current_time(true) - first_wallclock) * zeek::net::pseudo_realtime; return std::max(0.0, pseudo_time - ct); } diff --git a/src/iosource/pcap/Dumper.cc b/src/iosource/pcap/Dumper.cc index fe9a1ac3f0..6bfd62c068 100644 --- a/src/iosource/pcap/Dumper.cc +++ b/src/iosource/pcap/Dumper.cc @@ -51,7 +51,7 @@ void PcapDumper::Open() if ( exists < 0 && errno != ENOENT ) { - Error(fmt("can't stat file %s: %s", props.path.c_str(), strerror(errno))); + Error(zeek::util::fmt("can't stat file %s: %s", props.path.c_str(), strerror(errno))); return; } } @@ -76,7 +76,7 @@ void PcapDumper::Open() dumper = (pcap_dumper_t*) fopen(props.path.c_str(), "a"); if ( ! dumper ) { - Error(fmt("can't open dump %s: %s", props.path.c_str(), strerror(errno))); + Error(zeek::util::fmt("can't open dump %s: %s", props.path.c_str(), strerror(errno))); return; } } diff --git a/src/iosource/pcap/Source.cc b/src/iosource/pcap/Source.cc index 4bda7476a0..2aa522e751 100644 --- a/src/iosource/pcap/Source.cc +++ b/src/iosource/pcap/Source.cc @@ -61,7 +61,7 @@ void PcapSource::OpenLive() if ( pcap_findalldevs(&devs, errbuf) < 0 ) { - Error(fmt("pcap_findalldevs: %s", errbuf)); + Error(zeek::util::fmt("pcap_findalldevs: %s", errbuf)); return; } @@ -157,7 +157,7 @@ void PcapSource::OpenLive() #endif #ifdef HAVE_PCAP_INT_H - Info(fmt("pcap bufsize = %d\n", ((struct pcap *) pd)->bufsize)); + Info(zeek::util::fmt("pcap bufsize = %d\n", ((struct pcap *) pd)->bufsize)); #endif props.selectable_fd = pcap_get_selectable_fd(pd); @@ -328,12 +328,12 @@ void PcapSource::PcapError(const char* where) std::string location; if ( where ) - location = fmt(" (%s)", where); + location = zeek::util::fmt(" (%s)", where); if ( pd ) - Error(fmt("pcap_error: %s%s", pcap_geterr(pd), location.c_str())); + Error(zeek::util::fmt("pcap_error: %s%s", pcap_geterr(pd), location.c_str())); else - Error(fmt("pcap_error: not open%s", location.c_str())); + Error(zeek::util::fmt("pcap_error: not open%s", location.c_str())); Close(); } diff --git a/src/iosource/pcap/pcap.bif b/src/iosource/pcap/pcap.bif index 8058e6743e..5655a8fac9 100644 --- a/src/iosource/pcap/pcap.bif +++ b/src/iosource/pcap/pcap.bif @@ -33,7 +33,8 @@ function precompile_pcap_filter%(id: PcapFilterID, s: string%): bool // We use a vector as underlying data structure for fast // lookups and limit the ID space so that that doesn't grow too // large. - zeek::emit_builtin_error(fmt("PCAP filter ids must remain below 100 (is %" PRId64 ")", id->AsInt())); + zeek::emit_builtin_error( + zeek::util::fmt("PCAP filter ids must remain below 100 (is %" PRId64 ")", id->AsInt())); return zeek::val_mgr->False(); } diff --git a/src/logging/Manager.cc b/src/logging/Manager.cc index 5971d1bcbf..f2463860b2 100644 --- a/src/logging/Manager.cc +++ b/src/logging/Manager.cc @@ -855,14 +855,14 @@ bool Manager::Write(zeek::EnumVal* id, zeek::RecordVal* columns_arg) if ( const auto& val = filter->field_name_map->Find(fn) ) { delete [] filter->fields[j]->name; - filter->fields[j]->name = copy_string(val->AsStringVal()->CheckString()); + filter->fields[j]->name = zeek::util::copy_string(val->AsStringVal()->CheckString()); } } arg_fields[j] = new threading::Field(*filter->fields[j]); } info = new WriterBackend::WriterInfo; - info->path = copy_string(path.c_str()); + info->path = zeek::util::copy_string(path.c_str()); info->network_time = zeek::net::network_time; zeek::detail::HashKey* k; @@ -874,7 +874,7 @@ bool Manager::Write(zeek::EnumVal* id, zeek::RecordVal* columns_arg) auto index = filter->config->RecreateIndex(*k); string key = index->Idx(0)->AsString()->CheckString(); string value = v->GetVal()->AsString()->CheckString(); - info->config.insert(std::make_pair(copy_string(key.c_str()), copy_string(value.c_str()))); + info->config.insert(std::make_pair(zeek::util::copy_string(key.c_str()), zeek::util::copy_string(value.c_str()))); delete k; } @@ -944,14 +944,14 @@ threading::Value* Manager::ValToLogVal(zeek::Val* val, zeek::Type* ty) if ( s ) { - lval->val.string_val.data = copy_string(s); + lval->val.string_val.data = zeek::util::copy_string(s); lval->val.string_val.length = strlen(s); } else { val->GetType()->Error("enum type does not contain value", val); - lval->val.string_val.data = copy_string(""); + lval->val.string_val.data = zeek::util::copy_string(""); lval->val.string_val.length = 0; } break; @@ -995,7 +995,7 @@ threading::Value* Manager::ValToLogVal(zeek::Val* val, zeek::Type* ty) { const zeek::File* f = val->AsFile(); string s = f->Name(); - lval->val.string_val.data = copy_string(s.c_str()); + lval->val.string_val.data = zeek::util::copy_string(s.c_str()); lval->val.string_val.length = s.size(); break; } @@ -1006,7 +1006,7 @@ threading::Value* Manager::ValToLogVal(zeek::Val* val, zeek::Type* ty) const zeek::Func* f = val->AsFunc(); f->Describe(&d); const char* s = d.Description(); - lval->val.string_val.data = copy_string(s); + lval->val.string_val.data = zeek::util::copy_string(s); lval->val.string_val.length = strlen(s); break; } @@ -1179,7 +1179,7 @@ WriterFrontend* Manager::CreateWriter(zeek::EnumVal* id, zeek::EnumVal* writer, if ( f->postprocessor ) { delete [] winfo->info->post_proc_func; - winfo->info->post_proc_func = copy_string(f->postprocessor->Name()); + winfo->info->post_proc_func = zeek::util::copy_string(f->postprocessor->Name()); } break; @@ -1215,7 +1215,7 @@ WriterFrontend* Manager::CreateWriter(zeek::EnumVal* id, zeek::EnumVal* writer, static auto base_time = log_rotate_base_time->AsString()->CheckString(); winfo->info->rotation_interval = winfo->interval; - winfo->info->rotation_base = parse_rotate_base_time(base_time); + winfo->info->rotation_base = zeek::util::parse_rotate_base_time(base_time); winfo->writer = new WriterFrontend(*winfo->info, id, writer, local, remote); winfo->writer->Init(num_fields, fields); @@ -1474,9 +1474,9 @@ void Manager::InstallRotationTimer(WriterInfo* winfo) static auto log_rotate_base_time = zeek::id::find_val("log_rotate_base_time"); static auto base_time = log_rotate_base_time->AsString()->CheckString(); - double base = parse_rotate_base_time(base_time); + double base = zeek::util::parse_rotate_base_time(base_time); double delta_t = - calc_next_rotate(zeek::net::network_time, rotation_interval, base); + zeek::util::calc_next_rotate(zeek::net::network_time, rotation_interval, base); winfo->rotation_timer = new RotationTimer(zeek::net::network_time + delta_t, winfo, true); @@ -1522,7 +1522,7 @@ std::string Manager::FormatRotationPath(zeek::EnumValPtr writer, auto prefix = rp_val->GetField(1)->AsString()->CheckString(); auto dir = dir_val->AsString()->CheckString(); - if ( ! streq(dir, "") && ! ensure_intermediate_dirs(dir) ) + if ( ! zeek::util::streq(dir, "") && ! zeek::util::ensure_intermediate_dirs(dir) ) { zeek::reporter->Error("Failed to create dir '%s' returned by " "Log::rotation_format_func for path %.*s: %s", @@ -1531,17 +1531,17 @@ std::string Manager::FormatRotationPath(zeek::EnumValPtr writer, dir = ""; } - if ( streq(dir, "") ) + if ( zeek::util::streq(dir, "") ) rval = prefix; else - rval = fmt("%s/%s", dir, prefix); + rval = zeek::util::fmt("%s/%s", dir, prefix); } catch ( zeek::InterpreterException& e ) { auto rot_str = format_rotation_time_fallback((time_t)open); - rval = fmt("%.*s-%s", static_cast(path.size()), path.data(), - rot_str.data()); + rval = zeek::util::fmt("%.*s-%s", static_cast(path.size()), path.data(), + rot_str.data()); zeek::reporter->Error("Failed to call Log::rotation_format_func for path %.*s " "continuing with rotation to: ./%s", static_cast(path.size()), path.data(), rval.data()); diff --git a/src/logging/WriterBackend.cc b/src/logging/WriterBackend.cc index d006b9fcfd..6658f880c6 100644 --- a/src/logging/WriterBackend.cc +++ b/src/logging/WriterBackend.cc @@ -22,7 +22,7 @@ public: RotationFinishedMessage(WriterFrontend* writer, const char* new_name, const char* old_name, double open, double close, bool success, bool terminating) : threading::OutputMessage("RotationFinished", writer), - new_name(copy_string(new_name)), old_name(copy_string(old_name)), open(open), + new_name(zeek::util::copy_string(new_name)), old_name(zeek::util::copy_string(old_name)), open(open), close(close), success(success), terminating(terminating) { } ~RotationFinishedMessage() override @@ -97,8 +97,8 @@ bool WriterBackend::WriterInfo::FromBroker(broker::data d) if ( ! (bpath && brotation_base && brotation_interval && bnetwork_time && bconfig && bppf) ) return false; - path = copy_string(bpath->c_str()); - post_proc_func = copy_string(bppf->c_str()); + path = zeek::util::copy_string(bpath->c_str()); + post_proc_func = zeek::util::copy_string(bppf->c_str()); rotation_base = *brotation_base; rotation_interval = *brotation_interval; network_time = *bnetwork_time; @@ -111,7 +111,7 @@ bool WriterBackend::WriterInfo::FromBroker(broker::data d) if ( ! (k && v) ) return false; - auto p = std::make_pair(copy_string(k->c_str()), copy_string(v->c_str())); + auto p = std::make_pair(zeek::util::copy_string(k->c_str()), zeek::util::copy_string(v->c_str())); config.insert(p); } diff --git a/src/logging/WriterBackend.h b/src/logging/WriterBackend.h index 899c25e2e2..a0f2362e87 100644 --- a/src/logging/WriterBackend.h +++ b/src/logging/WriterBackend.h @@ -50,7 +50,7 @@ public: struct WriterInfo { // Structure takes ownership of these strings. - typedef std::map config_map; + typedef std::map config_map; /** * A string left to the interpretation of the writer @@ -98,14 +98,15 @@ public: WriterInfo(const WriterInfo& other) { - path = other.path ? copy_string(other.path) : nullptr; - post_proc_func = other.post_proc_func ? copy_string(other.post_proc_func) : nullptr; + path = other.path ? zeek::util::copy_string(other.path) : nullptr; + post_proc_func = other.post_proc_func ? zeek::util::copy_string(other.post_proc_func) : nullptr; rotation_interval = other.rotation_interval; rotation_base = other.rotation_base; network_time = other.network_time; for ( config_map::const_iterator i = other.config.begin(); i != other.config.end(); i++ ) - config.insert(std::make_pair(copy_string(i->first), copy_string(i->second))); + config.insert(std::make_pair(zeek::util::copy_string(i->first), + zeek::util::copy_string(i->second))); } ~WriterInfo() diff --git a/src/logging/WriterFrontend.cc b/src/logging/WriterFrontend.cc index c0127ff391..14c03a3835 100644 --- a/src/logging/WriterFrontend.cc +++ b/src/logging/WriterFrontend.cc @@ -36,7 +36,7 @@ public: const double close, const bool terminating) : zeek::threading::InputMessage("Rotate", backend), frontend(frontend), - rotated_path(copy_string(rotated_path)), open(open), + rotated_path(zeek::util::copy_string(rotated_path)), open(open), close(close), terminating(terminating) { } virtual ~RotateMessage() { delete [] rotated_path; } @@ -113,7 +113,7 @@ WriterFrontend::WriterFrontend(const WriterBackend::WriterInfo& arg_info, zeek:: fields = nullptr; const char* w = arg_writer->GetType()->AsEnumType()->Lookup(arg_writer->InternalInt()); - name = copy_string(fmt("%s/%s", arg_info.path, w)); + name = zeek::util::copy_string(zeek::util::fmt("%s/%s", arg_info.path, w)); if ( local ) { diff --git a/src/logging/writers/ascii/Ascii.cc b/src/logging/writers/ascii/Ascii.cc index 21b046d0cd..fc9f5d6913 100644 --- a/src/logging/writers/ascii/Ascii.cc +++ b/src/logging/writers/ascii/Ascii.cc @@ -106,7 +106,7 @@ static std::optional parse_shadow_log(const std::string& fname) if ( ! sf_stream ) { - rval.error = fmt("Failed to open %s: %s", + rval.error = zeek::util::fmt("Failed to open %s: %s", rval.shadow_filename.data(), strerror(errno)); return rval; } @@ -115,7 +115,7 @@ static std::optional parse_shadow_log(const std::string& fname) if ( res == -1 ) { - rval.error = fmt("Failed to fseek(SEEK_END) on %s: %s", + rval.error = zeek::util::fmt("Failed to fseek(SEEK_END) on %s: %s", rval.shadow_filename.data(), strerror(errno)); fclose(sf_stream); return rval; @@ -125,7 +125,7 @@ static std::optional parse_shadow_log(const std::string& fname) if ( sf_len == -1 ) { - rval.error = fmt("Failed to ftell() on %s: %s", + rval.error = zeek::util::fmt("Failed to ftell() on %s: %s", rval.shadow_filename.data(), strerror(errno)); fclose(sf_stream); return rval; @@ -135,7 +135,7 @@ static std::optional parse_shadow_log(const std::string& fname) if ( res == -1 ) { - rval.error = fmt("Failed to fseek(SEEK_SET) on %s: %s", + rval.error = zeek::util::fmt("Failed to fseek(SEEK_SET) on %s: %s", rval.shadow_filename.data(), strerror(errno)); fclose(sf_stream); return rval; @@ -152,11 +152,11 @@ static std::optional parse_shadow_log(const std::string& fname) } std::string_view sf_view(sf_content.get(), sf_len); - auto sf_lines = tokenize_string(sf_view, '\n'); + auto sf_lines = zeek::util::tokenize_string(sf_view, '\n'); if ( sf_lines.size() < 2 ) { - rval.error = fmt("Found leftover log, '%s', but the associated shadow " + rval.error = zeek::util::fmt("Found leftover log, '%s', but the associated shadow " " file, '%s', required to process it is invalid", rval.filename.data(), rval.shadow_filename.data()); return rval; @@ -170,7 +170,7 @@ static std::optional parse_shadow_log(const std::string& fname) // Use shadow file's modification time as creation time. if ( stat(rval.shadow_filename.data(), &st) != 0 ) { - rval.error = fmt("Failed to stat %s: %s", + rval.error = zeek::util::fmt("Failed to stat %s: %s", rval.shadow_filename.data(), strerror(errno)); return rval; } @@ -180,7 +180,7 @@ static std::optional parse_shadow_log(const std::string& fname) // Use log file's modification time for closing time. if ( stat(rval.filename.data(), &st) != 0 ) { - rval.error = fmt("Failed to stat %s: %s", + rval.error = zeek::util::fmt("Failed to stat %s: %s", rval.filename.data(), strerror(errno)); return rval; } @@ -462,17 +462,17 @@ bool Ascii::DoInit(const WriterInfo& info, int num_fields, const zeek::threading return false; } - safe_write(sfd, ext.data(), ext.size()); - safe_write(sfd, "\n", 1); + zeek::util::safe_write(sfd, ext.data(), ext.size()); + zeek::util::safe_write(sfd, "\n", 1); auto ppf = info.post_proc_func; if ( ppf ) - safe_write(sfd, ppf, strlen(ppf)); + zeek::util::safe_write(sfd, ppf, strlen(ppf)); - safe_write(sfd, "\n", 1); + zeek::util::safe_write(sfd, "\n", 1); - safe_close(sfd); + zeek::util::safe_close(sfd); } } @@ -552,16 +552,16 @@ bool Ascii::WriteHeader(const string& path) string str = meta_prefix + "separator " // Always use space as separator here. - + get_escaped_string(separator, false) + + zeek::util::get_escaped_string(separator, false) + "\n"; if ( ! InternalWrite(fd, str.c_str(), str.length()) ) return false; - if ( ! (WriteHeaderField("set_separator", get_escaped_string(set_separator, false)) && - WriteHeaderField("empty_field", get_escaped_string(empty_field, false)) && - WriteHeaderField("unset_field", get_escaped_string(unset_field, false)) && - WriteHeaderField("path", get_escaped_string(path, false)) && + if ( ! (WriteHeaderField("set_separator", zeek::util::get_escaped_string(set_separator, false)) && + WriteHeaderField("empty_field", zeek::util::get_escaped_string(empty_field, false)) && + WriteHeaderField("unset_field", zeek::util::get_escaped_string(unset_field, false)) && + WriteHeaderField("path", zeek::util::get_escaped_string(path, false)) && WriteHeaderField("open", Timestamp(0))) ) return false; @@ -615,7 +615,7 @@ bool Ascii::DoWrite(int num_fields, const zeek::threading::Field* const * fields { // It would so escape the first character. char hex[4] = {'\\', 'x', '0', '0'}; - bytetohex(bytes[0], hex + 2); + zeek::util::bytetohex(bytes[0], hex + 2); if ( ! InternalWrite(fd, hex, 4) ) goto write_error; @@ -659,7 +659,7 @@ bool Ascii::DoRotate(const char* rotated_path, double open, double close, bool t if ( rename(fname.c_str(), nname.c_str()) != 0 ) { char buf[256]; - bro_strerror_r(errno, buf, sizeof(buf)); + zeek::util::zeek_strerror_r(errno, buf, sizeof(buf)); Error(Fmt("failed to rename %s to %s: %s", fname.c_str(), nname.c_str(), buf)); FinishedRotation(); @@ -717,7 +717,7 @@ static std::vector find_leftover_logs() std::string log_name = dp->d_name + prefix_len; - if ( is_file(log_name) ) + if ( zeek::util::is_file(log_name) ) { if ( auto ll = parse_shadow_log(log_name) ) { @@ -822,7 +822,7 @@ void Ascii::RotateLeftoverLogs() string Ascii::LogExt() { - const char* ext = zeekenv("ZEEK_LOG_SUFFIX"); + const char* ext = zeek::util::zeekenv("ZEEK_LOG_SUFFIX"); if ( ! ext ) ext = "log"; @@ -857,7 +857,7 @@ string Ascii::Timestamp(double t) bool Ascii::InternalWrite(int fd, const char* data, int len) { if ( ! gzfile ) - return safe_write(fd, data, len); + return zeek::util::safe_write(fd, data, len); while ( len > 0 ) { @@ -881,7 +881,7 @@ bool Ascii::InternalClose(int fd) { if ( ! gzfile ) { - safe_close(fd); + zeek::util::safe_close(fd); return true; } diff --git a/src/main.cc b/src/main.cc index 620802c69d..bb0d4a2f60 100644 --- a/src/main.cc +++ b/src/main.cc @@ -9,7 +9,7 @@ int main(int argc, char** argv) { - auto time_start = current_time(true); + auto time_start = zeek::util::current_time(true); auto setup_result = zeek::detail::setup(argc, argv); if ( setup_result.code ) @@ -40,41 +40,41 @@ int main(int argc, char** argv) if ( zeek::Supervisor::ThisNode() ) zeek::detail::timer_mgr->Add(new zeek::detail::ParentProcessCheckTimer(1, 1)); - double time_net_start = current_time(true);; + double time_net_start = zeek::util::current_time(true);; uint64_t mem_net_start_total; uint64_t mem_net_start_malloced; if ( options.print_execution_time ) { - get_memory_usage(&mem_net_start_total, &mem_net_start_malloced); + zeek::util::get_memory_usage(&mem_net_start_total, &mem_net_start_malloced); fprintf(stderr, "# initialization %.6f\n", time_net_start - time_start); fprintf(stderr, "# initialization %" PRIu64 "M/%" PRIu64 "M\n", - mem_net_start_total / 1024 / 1024, - mem_net_start_malloced / 1024 / 1024); + mem_net_start_total / 1024 / 1024, + mem_net_start_malloced / 1024 / 1024); } zeek::net::detail::net_run(); - double time_net_done = current_time(true);; + double time_net_done = zeek::util::current_time(true); uint64_t mem_net_done_total; uint64_t mem_net_done_malloced; if ( options.print_execution_time ) { - get_memory_usage(&mem_net_done_total, &mem_net_done_malloced); + zeek::util::get_memory_usage(&mem_net_done_total, &mem_net_done_malloced); fprintf(stderr, "# total time %.6f, processing %.6f\n", - time_net_done - time_start, time_net_done - time_net_start); + time_net_done - time_start, time_net_done - time_net_start); fprintf(stderr, "# total mem %" PRId64 "M/%" PRId64 "M, processing %" PRId64 "M/%" PRId64 "M\n", - mem_net_done_total / 1024 / 1024, - mem_net_done_malloced / 1024 / 1024, - (mem_net_done_total - mem_net_start_total) / 1024 / 1024, - (mem_net_done_malloced - mem_net_start_malloced) / 1024 / 1024); + mem_net_done_total / 1024 / 1024, + mem_net_done_malloced / 1024 / 1024, + (mem_net_done_total - mem_net_start_total) / 1024 / 1024, + (mem_net_done_malloced - mem_net_start_malloced) / 1024 / 1024); } } diff --git a/src/option.bif b/src/option.bif index f0afeb9ae8..e9de84be63 100644 --- a/src/option.bif +++ b/src/option.bif @@ -61,20 +61,20 @@ function Option::set%(ID: string, val: any, location: string &default=""%): bool const auto& i = zeek::detail::global_scope()->Find(ID->CheckString()); if ( ! i ) { - zeek::emit_builtin_error(fmt("Could not find ID named '%s'", ID->CheckString())); + zeek::emit_builtin_error(zeek::util::fmt("Could not find ID named '%s'", ID->CheckString())); return zeek::val_mgr->False(); } if ( ! i->HasVal() ) { // should be impossible because initialization is enforced - zeek::emit_builtin_error(fmt("ID '%s' has no value", ID->CheckString())); + zeek::emit_builtin_error(zeek::util::fmt("ID '%s' has no value", ID->CheckString())); return zeek::val_mgr->False(); } if ( ! i->IsOption() ) { - zeek::emit_builtin_error(fmt("ID '%s' is not an option", ID->CheckString())); + zeek::emit_builtin_error(zeek::util::fmt("ID '%s' is not an option", ID->CheckString())); return zeek::val_mgr->False(); } @@ -85,7 +85,7 @@ function Option::set%(ID: string, val: any, location: string &default=""%): bool if ( ! val_from_data ) { - zeek::emit_builtin_error(fmt("Incompatible type for set of ID '%s': got broker data '%s', need '%s'", + zeek::emit_builtin_error(zeek::util::fmt("Incompatible type for set of ID '%s': got broker data '%s', need '%s'", ID->CheckString(), dv->data.get_type_name(), type_name(i->GetType()->Tag()))); return zeek::val_mgr->False(); @@ -109,7 +109,7 @@ function Option::set%(ID: string, val: any, location: string &default=""%): bool return zeek::val_mgr->Bool(rval); } - zeek::emit_builtin_error(fmt("Incompatible type for set of ID '%s': got '%s', need '%s'", + zeek::emit_builtin_error(zeek::util::fmt("Incompatible type for set of ID '%s': got '%s', need '%s'", ID->CheckString(), type_name(val->GetType()->Tag()), type_name(i->GetType()->Tag()))); return zeek::val_mgr->False(); @@ -148,19 +148,19 @@ function Option::set_change_handler%(ID: string, on_change: any, priority: int & const auto& i = zeek::detail::global_scope()->Find(ID->CheckString()); if ( ! i ) { - zeek::emit_builtin_error(fmt("Could not find ID named '%s'", ID->CheckString())); + zeek::emit_builtin_error(zeek::util::fmt("Could not find ID named '%s'", ID->CheckString())); return zeek::val_mgr->False(); } if ( ! i->IsOption() ) { - zeek::emit_builtin_error(fmt("ID '%s' is not an option", ID->CheckString())); + zeek::emit_builtin_error(zeek::util::fmt("ID '%s' is not an option", ID->CheckString())); return zeek::val_mgr->False(); } if ( on_change->GetType()->Tag() != TYPE_FUNC ) { - zeek::emit_builtin_error(fmt("Option::on_change needs function argument; got '%s' for ID '%s'", + zeek::emit_builtin_error(zeek::util::fmt("Option::on_change needs function argument; got '%s' for ID '%s'", type_name(on_change->GetType()->Tag()), ID->CheckString())); return zeek::val_mgr->False(); } @@ -174,21 +174,21 @@ function Option::set_change_handler%(ID: string, on_change: any, priority: int & const auto& args = on_change->GetType()->AsFuncType()->ParamList()->GetTypes(); if ( args.size() < 2 || args.size() > 3 ) { - zeek::emit_builtin_error(fmt("Wrong number of arguments for passed function in Option::on_change for ID '%s'; expected 2 or 3, got %zu", + zeek::emit_builtin_error(zeek::util::fmt("Wrong number of arguments for passed function in Option::on_change for ID '%s'; expected 2 or 3, got %zu", ID->CheckString(), args.size())); return zeek::val_mgr->False(); } if ( args[0]->Tag() != TYPE_STRING ) { - zeek::emit_builtin_error(fmt("First argument of passed function has to be string in Option::on_change for ID '%s'; got '%s'", + zeek::emit_builtin_error(zeek::util::fmt("First argument of passed function has to be string in Option::on_change for ID '%s'; got '%s'", ID->CheckString(), type_name(args[0]->Tag()))); return zeek::val_mgr->False(); } if ( ! same_type(args[1], i->GetType()) ) { - zeek::emit_builtin_error(fmt("Second argument of passed function has to be %s in Option::on_change for ID '%s'; got '%s'", + zeek::emit_builtin_error(zeek::util::fmt("Second argument of passed function has to be %s in Option::on_change for ID '%s'; got '%s'", type_name(i->GetType()->Tag()), ID->CheckString(), type_name(args[1]->Tag()))); return zeek::val_mgr->False(); @@ -196,14 +196,14 @@ function Option::set_change_handler%(ID: string, on_change: any, priority: int & if ( args.size() == 3 && args[2]->Tag() != TYPE_STRING ) { - zeek::emit_builtin_error(fmt("Third argument of passed function has to be string in Option::on_change for ID '%s'; got '%s'", + zeek::emit_builtin_error(zeek::util::fmt("Third argument of passed function has to be string in Option::on_change for ID '%s'; got '%s'", ID->CheckString(), type_name(args[2]->Tag()))); return zeek::val_mgr->False(); } if ( ! same_type(on_change->GetType()->AsFuncType()->Yield(), i->GetType()) ) { - zeek::emit_builtin_error(fmt("Passed function needs to return type '%s' for ID '%s'; got '%s'", + zeek::emit_builtin_error(zeek::util::fmt("Passed function needs to return type '%s' for ID '%s'; got '%s'", type_name(i->GetType()->Tag()), ID->CheckString(), type_name(on_change->GetType()->AsFuncType()->Yield()->Tag()))); return zeek::val_mgr->False(); diff --git a/src/parse.y b/src/parse.y index fd195ad768..fe73b08839 100644 --- a/src/parse.y +++ b/src/parse.y @@ -669,12 +669,12 @@ expr: false, is_export); */ - yyerror(fmt("unknown identifier %s", $1)); + yyerror(zeek::util::fmt("unknown identifier %s", $1)); YYERROR; } else { - yyerror(fmt("unknown identifier %s", $1)); + yyerror(zeek::util::fmt("unknown identifier %s", $1)); YYERROR; } } @@ -1182,7 +1182,7 @@ func_hdr: | TOK_EVENT event_id func_params opt_attr { const char* name = $2->Name(); - if ( streq("bro_init", name) || streq("bro_done", name) || streq("bro_script_loaded", name) ) + if ( zeek::util::streq("bro_init", name) || zeek::util::streq("bro_done", name) || zeek::util::streq("bro_script_loaded", name) ) { auto base = std::string(name).substr(4); zeek::reporter->Error("event %s() is no longer available, use zeek_%s() instead", name, base.c_str()); @@ -1618,7 +1618,7 @@ event: { if ( ! id->IsGlobal() ) { - yyerror(fmt("local identifier \"%s\" cannot be used to reference an event", $1)); + yyerror(zeek::util::fmt("local identifier \"%s\" cannot be used to reference an event", $1)); YYERROR; } @@ -1905,7 +1905,7 @@ opt_deprecated: int yyerror(const char msg[]) { if ( in_debug ) - g_curr_debug_error = copy_string(msg); + g_curr_debug_error = zeek::util::copy_string(msg); if ( last_tok[0] == '\n' ) zeek::reporter->Error("%s, on previous line", msg); @@ -1919,7 +1919,7 @@ int yyerror(const char msg[]) else { if ( last_last_tok_filename && last_tok_filename && - ! streq(last_last_tok_filename, last_tok_filename) ) + ! zeek::util::streq(last_last_tok_filename, last_tok_filename) ) zeek::reporter->Error("%s, at or near \"%s\" or end of file %s", msg, last_tok, last_last_tok_filename); else diff --git a/src/plugin/Component.cc b/src/plugin/Component.cc index 7a7ef38f5e..bd51703214 100644 --- a/src/plugin/Component.cc +++ b/src/plugin/Component.cc @@ -11,7 +11,7 @@ Component::Component(component::Type arg_type, const std::string& arg_name) { type = arg_type; name = arg_name; - canon_name = canonify_name(name); + canon_name = zeek::util::canonify_name(name); } Component::~Component() diff --git a/src/plugin/ComponentManager.h b/src/plugin/ComponentManager.h index ecfef4c06d..690053dd5c 100644 --- a/src/plugin/ComponentManager.h +++ b/src/plugin/ComponentManager.h @@ -221,7 +221,7 @@ template C* ComponentManager::Lookup(const std::string& name) const { typename std::map::const_iterator i = - components_by_name.find(to_upper(name)); + components_by_name.find(zeek::util::to_upper(name)); return i != components_by_name.end() ? i->second : 0; } @@ -259,7 +259,7 @@ void ComponentManager::RegisterComponent(C* component, component->Tag().AsVal()->InternalInt(), component)); // Install an identfier for enum value - std::string id = fmt("%s%s", prefix.c_str(), cname.c_str()); + std::string id = zeek::util::fmt("%s%s", prefix.c_str(), cname.c_str()); tag_enum_type->AddName(module, id.c_str(), component->Tag().AsVal()->InternalInt(), true, nullptr); diff --git a/src/plugin/Manager.cc b/src/plugin/Manager.cc index 34a795b970..3bdb5ed7f3 100644 --- a/src/plugin/Manager.cc +++ b/src/plugin/Manager.cc @@ -63,7 +63,7 @@ void Manager::SearchDynamicPlugins(const std::string& dir) return; } - if ( ! is_dir(dir) ) + if ( ! zeek::util::is_dir(dir) ) { DBG_LOG(zeek::DBG_PLUGINS, "Not a valid plugin directory: %s", dir.c_str()); return; @@ -73,7 +73,7 @@ void Manager::SearchDynamicPlugins(const std::string& dir) const std::string magic = dir + "/__bro_plugin__"; - if ( is_file(magic) ) + if ( zeek::util::is_file(magic) ) { // It's a plugin, get it's name. std::ifstream in(magic.c_str()); @@ -83,8 +83,8 @@ void Manager::SearchDynamicPlugins(const std::string& dir) std::string name; std::getline(in, name); - strstrip(name); - string lower_name = strtolower(name); + zeek::util::strstrip(name); + string lower_name = zeek::util::strtolower(name); if ( name.empty() ) reporter->FatalError("empty plugin magic file %s", magic.c_str()); @@ -141,7 +141,7 @@ void Manager::SearchDynamicPlugins(const std::string& dir) bool Manager::ActivateDynamicPluginInternal(const std::string& name, bool ok_if_not_found) { - dynamic_plugin_map::iterator m = dynamic_plugins.find(strtolower(name)); + dynamic_plugin_map::iterator m = dynamic_plugins.find(zeek::util::strtolower(name)); if ( m == dynamic_plugins.end() ) { @@ -177,50 +177,50 @@ bool Manager::ActivateDynamicPluginInternal(const std::string& name, bool ok_if_ // Add the "scripts" and "bif" directories to ZEEKPATH. std::string scripts = dir + "scripts"; - if ( is_dir(scripts) ) + if ( zeek::util::is_dir(scripts) ) { DBG_LOG(zeek::DBG_PLUGINS, " Adding %s to ZEEKPATH", scripts.c_str()); - add_to_bro_path(scripts); + zeek::util::add_to_zeek_path(scripts); } string init; // First load {scripts}/__preload__.zeek automatically. - for (const string& ext : script_extensions) + for (const string& ext : zeek::util::script_extensions) { init = dir + "scripts/__preload__" + ext; - if ( is_file(init) ) + if ( zeek::util::is_file(init) ) { DBG_LOG(zeek::DBG_PLUGINS, " Loading %s", init.c_str()); - warn_if_legacy_script(init); + zeek::util::warn_if_legacy_script(init); scripts_to_load.push_back(init); break; } } // Load {bif,scripts}/__load__.zeek automatically. - for (const string& ext : script_extensions) + for (const string& ext : zeek::util::script_extensions) { init = dir + "lib/bif/__load__" + ext; - if ( is_file(init) ) + if ( zeek::util::is_file(init) ) { DBG_LOG(zeek::DBG_PLUGINS, " Loading %s", init.c_str()); - warn_if_legacy_script(init); + zeek::util::warn_if_legacy_script(init); scripts_to_load.push_back(init); break; } } - for (const string& ext : script_extensions) + for (const string& ext : zeek::util::script_extensions) { init = dir + "scripts/__load__" + ext; - if ( is_file(init) ) + if ( zeek::util::is_file(init) ) { DBG_LOG(zeek::DBG_PLUGINS, " Loading %s", init.c_str()); - warn_if_legacy_script(init); + zeek::util::warn_if_legacy_script(init); scripts_to_load.push_back(init); break; } @@ -259,7 +259,7 @@ bool Manager::ActivateDynamicPluginInternal(const std::string& name, bool ok_if_ DBG_LOG(zeek::DBG_PLUGINS, " InitialzingComponents"); current_plugin->InitializeComponents(); - plugins_by_path.insert(std::make_pair(normalize_path(dir), current_plugin)); + plugins_by_path.insert(std::make_pair(zeek::util::normalize_path(dir), current_plugin)); // We execute the pre-script initialization here; this in // fact could be *during* script initialization if we got @@ -268,7 +268,7 @@ bool Manager::ActivateDynamicPluginInternal(const std::string& name, bool ok_if_ // Make sure the name the plugin reports is consistent with // what we expect from its magic file. - if ( strtolower(current_plugin->Name()) != strtolower(name) ) + if ( zeek::util::strtolower(current_plugin->Name()) != zeek::util::strtolower(name) ) reporter->FatalError("inconsistent plugin name: %s vs %s", current_plugin->Name().c_str(), name.c_str()); @@ -306,7 +306,7 @@ bool Manager::ActivateDynamicPlugins(bool all) { // Activate plugins that our environment tells us to. vector p; - tokenize_string(bro_plugin_activate(), ",", &p); + zeek::util::tokenize_string(zeek::util::zeek_plugin_activate(), ",", &p); for ( size_t n = 0; n < p.size(); ++n ) ActivateDynamicPluginInternal(p[n], true); @@ -337,7 +337,7 @@ void Manager::UpdateInputFiles() static bool plugin_cmp(const Plugin* a, const Plugin* b) { - return strtolower(a->Name()) < strtolower(b->Name()); + return zeek::util::strtolower(a->Name()) < zeek::util::strtolower(b->Name()); } void Manager::RegisterPlugin(Plugin *plugin) @@ -346,7 +346,7 @@ void Manager::RegisterPlugin(Plugin *plugin) if ( current_dir && current_sopath ) // A dynamic plugin, record its location. - plugin->SetPluginLocation(normalize_path(current_dir), current_sopath); + plugin->SetPluginLocation(zeek::util::normalize_path(current_dir), current_sopath); current_plugin = plugin; } @@ -355,7 +355,7 @@ void Manager::RegisterBifFile(const char* plugin, bif_init_func c) { bif_init_func_map* bifs = BifFilesInternal(); - std::string lower_plugin = strtolower(plugin); + std::string lower_plugin = zeek::util::strtolower(plugin); bif_init_func_map::iterator i = bifs->find(lower_plugin); if ( i == bifs->end() ) @@ -398,7 +398,7 @@ void Manager::InitBifs() for ( plugin_list::iterator i = Manager::ActivePluginsInternal()->begin(); i != Manager::ActivePluginsInternal()->end(); i++ ) { - bif_init_func_map::const_iterator b = bifs->find(strtolower((*i)->Name())); + bif_init_func_map::const_iterator b = bifs->find(zeek::util::strtolower((*i)->Name())); if ( b != bifs->end() ) { @@ -447,7 +447,7 @@ Manager::inactive_plugin_list Manager::InactivePlugins() const for ( plugin_list::const_iterator j = all->begin(); j != all->end(); j++ ) { - if ( (*i).first == strtolower((*j)->Name()) ) + if ( (*i).first == zeek::util::strtolower((*j)->Name()) ) { found = true; break; @@ -483,10 +483,10 @@ Manager::bif_init_func_map* Manager::BifFilesInternal() Plugin* Manager::LookupPluginByPath(std::string_view _path) { - auto path = normalize_path(_path); + auto path = zeek::util::normalize_path(_path); - if ( is_file(path) ) - path = SafeDirname(path).result; + if ( zeek::util::is_file(path) ) + path = zeek::util::SafeDirname(path).result; while ( path.size() ) { @@ -509,7 +509,7 @@ Plugin* Manager::LookupPluginByPath(std::string_view _path) static bool hook_cmp(std::pair a, std::pair b) { if ( a.first == b.first ) - return strtolower(a.second->Name()) < strtolower(a.second->Name()); + return zeek::util::strtolower(a.second->Name()) < zeek::util::strtolower(a.second->Name()); // Reverse sort. return a.first > b.first; diff --git a/src/probabilistic/BloomFilter.cc b/src/probabilistic/BloomFilter.cc index 0d6fdb4cd7..3ef3ee06e2 100644 --- a/src/probabilistic/BloomFilter.cc +++ b/src/probabilistic/BloomFilter.cc @@ -137,7 +137,7 @@ BasicBloomFilter* BasicBloomFilter::Clone() const std::string BasicBloomFilter::InternalState() const { - return fmt("%" PRIu64, bits->Hash()); + return zeek::util::fmt("%" PRIu64, bits->Hash()); } BasicBloomFilter::BasicBloomFilter() @@ -256,7 +256,7 @@ CountingBloomFilter* CountingBloomFilter::Clone() const std::string CountingBloomFilter::InternalState() const { - return fmt("%" PRIu64, cells->Hash()); + return zeek::util::fmt("%" PRIu64, cells->Hash()); } // TODO: Use partitioning in add/count to allow for reusing CMS bounds. diff --git a/src/probabilistic/Hasher.cc b/src/probabilistic/Hasher.cc index 58ad36944e..e3dd574912 100644 --- a/src/probabilistic/Hasher.cc +++ b/src/probabilistic/Hasher.cc @@ -33,7 +33,7 @@ Hasher::seed_t Hasher::MakeSeed(const void* data, size_t size) else { - unsigned int first_seed = initial_seed(); + unsigned int first_seed = zeek::util::initial_seed(); zeek::detail::hash_update(ctx, &first_seed, sizeof(first_seed)); } @@ -119,7 +119,7 @@ DefaultHasher::DefaultHasher(size_t k, Hasher::seed_t seed) for ( size_t i = 1; i <= k; ++i ) { seed_t s = Seed(); - s.h[0] += zeek::prng(i); + s.h[0] += zeek::util::prng(i); hash_functions.push_back(UHF(s)); } } @@ -149,7 +149,7 @@ bool DefaultHasher::Equals(const Hasher* other) const } DoubleHasher::DoubleHasher(size_t k, seed_t seed) - : Hasher(k, seed), h1(seed + zeek::prng(1)), h2(seed + zeek::prng(2)) + : Hasher(k, seed), h1(seed + zeek::util::prng(1)), h2(seed + zeek::util::prng(2)) { } diff --git a/src/re-scan.l b/src/re-scan.l index 333f670b15..9becd2fab0 100644 --- a/src/re-scan.l +++ b/src/re-scan.l @@ -84,7 +84,7 @@ CCL_EXPR ("[:"[[:alpha:]]+":]") } "{"{NAME}"}" { - char* nmstr = copy_string(yytext+1); + char* nmstr = zeek::util::copy_string(yytext+1); nmstr[yyleng - 2] = '\0'; // chop trailing brace std::string namedef = zeek::detail::rem->LookupDef(nmstr); @@ -212,7 +212,7 @@ CCL_EXPR ("[:"[[:alpha:]]+":]") {ESCSEQ} { const char* esc_text = yytext + 1; - yylval.int_val = expand_escape(esc_text); + yylval.int_val = zeek::util::expand_escape(esc_text); if ( YY_START == SC_FIRST_CCL ) BEGIN(SC_CCL); diff --git a/src/rule-scan.l b/src/rule-scan.l index 53efdd19ec..6b61844079 100644 --- a/src/rule-scan.l +++ b/src/rule-scan.l @@ -43,13 +43,13 @@ PID {PIDCOMPONENT}(::{PIDCOMPONENT})* } {IP6} { - rules_lval.prefixval = new zeek::IPPrefix(zeek::IPAddr(extract_ip(yytext)), 128, true); + rules_lval.prefixval = new zeek::IPPrefix(zeek::IPAddr(zeek::util::extract_ip(yytext)), 128, true); return TOK_IP6; } {IP6}{OWS}"/"{OWS}{D} { int len = 0; - std::string ip = extract_ip_and_len(yytext, &len); + std::string ip = zeek::util::extract_ip_and_len(yytext, &len); rules_lval.prefixval = new zeek::IPPrefix(zeek::IPAddr(ip), len, true); return TOK_IP6; } diff --git a/src/scan.l b/src/scan.l index 521928aeab..8243d87b1a 100644 --- a/src/scan.l +++ b/src/scan.l @@ -81,9 +81,9 @@ static std::string find_relative_file(const std::string& filename, const std::st return std::string(); if ( filename[0] == '.' ) - return find_file(filename, SafeDirname(::filename).result, ext); + return zeek::util::find_file(filename, zeek::util::SafeDirname(::filename).result, ext); else - return find_file(filename, bro_path(), ext); + return zeek::util::find_file(filename, zeek::util::zeek_path(), ext); } static std::string find_relative_script_file(const std::string& filename) @@ -92,9 +92,9 @@ static std::string find_relative_script_file(const std::string& filename) return std::string(); if ( filename[0] == '.' ) - return find_script_file(filename, SafeDirname(::filename).result); + return zeek::util::find_script_file(filename, zeek::util::SafeDirname(::filename).result); else - return find_script_file(filename, bro_path()); + return zeek::util::find_script_file(filename, zeek::util::zeek_path()); } class FileInfo { @@ -175,12 +175,12 @@ ESCSEQ (\\([^\n]|[0-7]+|x[[:xdigit:]]+)) /* IPv6 literal constant patterns */ {IP6} { - RET_CONST(new zeek::AddrVal(extract_ip(yytext))) + RET_CONST(new zeek::AddrVal(zeek::util::extract_ip(yytext))) } {IP6}{OWS}"/"{OWS}{D} { int len = 0; - std::string ip = extract_ip_and_len(yytext, &len); + std::string ip = zeek::util::extract_ip_and_len(yytext, &len); RET_CONST(new zeek::SubNetVal(zeek::IPPrefix(zeek::IPAddr(ip), len, true))) } @@ -189,7 +189,7 @@ ESCSEQ (\\([^\n]|[0-7]+|x[[:xdigit:]]+)) ({D}"."){3}{D}{OWS}"/"{OWS}{D} { int len = 0; - std::string ip = extract_ip_and_len(yytext, &len); + std::string ip = zeek::util::extract_ip_and_len(yytext, &len); RET_CONST(new zeek::SubNetVal(zeek::IPPrefix(zeek::IPAddr(ip), len))) } @@ -289,7 +289,7 @@ when return TOK_WHEN; @deprecated.* { auto num_files = file_stack.length(); - auto comment = skip_whitespace(yytext + 11); + auto comment = zeek::util::skip_whitespace(yytext + 11); if ( num_files > 0 ) { @@ -308,7 +308,7 @@ when return TOK_WHEN; @DEBUG return TOK_DEBUG; // marks input for debugger @DIR { - std::string rval = SafeDirname(::filename).result; + std::string rval = zeek::util::SafeDirname(::filename).result; if ( ! rval.empty() && rval[0] == '.' ) { @@ -324,11 +324,11 @@ when return TOK_WHEN; } @FILENAME { - RET_CONST(new zeek::StringVal(SafeBasename(::filename).result)); + RET_CONST(new zeek::StringVal(zeek::util::SafeBasename(::filename).result)); } @load{WS}{FILE} { - const char* new_file = skip_whitespace(yytext + 5); // Skip "@load". + const char* new_file = zeek::util::skip_whitespace(yytext + 5); // Skip "@load". std::string loader = ::filename; // load_files may change ::filename, save copy std::string loading = find_relative_script_file(new_file); (void) load_files(new_file); @@ -336,7 +336,7 @@ when return TOK_WHEN; } @load-sigs{WS}{FILE} { - const char* file = skip_whitespace(yytext + 10); + const char* file = zeek::util::skip_whitespace(yytext + 10); std::string path = find_relative_file(file, ".sig"); int rc = PLUGIN_HOOK_WITH_RESULT(HOOK_LOAD_FILE, HookLoadFile(zeek::plugin::Plugin::SIGNATURES, file, path), -1); @@ -347,7 +347,7 @@ when return TOK_WHEN; zeek::reporter->Error("failed to find file associated with @load-sigs %s", file); else - zeek::net::detail::sig_files.push_back(copy_string(path.c_str())); + zeek::net::detail::sig_files.push_back(zeek::util::copy_string(path.c_str())); break; case 0: @@ -368,7 +368,7 @@ when return TOK_WHEN; } @load-plugin{WS}{ID} { - const char* plugin = skip_whitespace(yytext + 12); + const char* plugin = zeek::util::skip_whitespace(yytext + 12); int rc = PLUGIN_HOOK_WITH_RESULT(HOOK_LOAD_FILE, HookLoadFile(zeek::plugin::Plugin::PLUGIN, plugin, ""), -1); switch ( rc ) { @@ -396,7 +396,7 @@ when return TOK_WHEN; @unload{WS}{FILE} { // Skip "@unload". - const char* file = skip_whitespace(yytext + 7); + const char* file = zeek::util::skip_whitespace(yytext + 7); std::string path = find_relative_script_file(file); if ( path.empty() ) @@ -410,7 +410,7 @@ when return TOK_WHEN; } @prefixes{WS}("+"?)={WS}{PREFIX} { - char* pref = skip_whitespace(yytext + 9); // Skip "@prefixes". + char* pref = zeek::util::skip_whitespace(yytext + 9); // Skip "@prefixes". int append = 0; if ( *pref == '+' ) @@ -419,12 +419,12 @@ when return TOK_WHEN; ++pref; } - pref = skip_whitespace(pref + 1); // Skip over '='. + pref = zeek::util::skip_whitespace(pref + 1); // Skip over '='. if ( ! append ) zeek_script_prefixes = { "" }; // don't delete the "" prefix - tokenize_string(pref, ":", &zeek_script_prefixes); + zeek::util::tokenize_string(pref, ":", &zeek_script_prefixes); } @if return TOK_ATIF; @@ -445,7 +445,7 @@ T RET_CONST(zeek::val_mgr->True()->Ref()) F RET_CONST(zeek::val_mgr->False()->Ref()) {ID} { - yylval.str = copy_string(yytext); + yylval.str = zeek::util::copy_string(yytext); last_id_tok = yylval.str; return TOK_ID; } @@ -516,7 +516,7 @@ F RET_CONST(zeek::val_mgr->False()->Ref()) if ( *text == '\\' ) { ++text; // skip '\' - s[i++] = expand_escape(text); + s[i++] = zeek::util::expand_escape(text); --text; // point to end of sequence } else @@ -537,7 +537,7 @@ F RET_CONST(zeek::val_mgr->False()->Ref()) } ([^/\\\n]|{ESCSEQ})+ { - yylval.str = copy_string(yytext); + yylval.str = zeek::util::copy_string(yytext); return TOK_PATTERN_TEXT; } @@ -596,7 +596,7 @@ static int load_files(const char* orig_file) FILE* f = nullptr; - if ( streq(orig_file, "-") ) + if ( zeek::util::streq(orig_file, "-") ) { f = stdin; file_path = canonical_stdin_path; @@ -613,10 +613,10 @@ static int load_files(const char* orig_file) if ( file_path.empty() ) zeek::reporter->FatalError("can't find %s", orig_file); - if ( is_dir(file_path.c_str()) ) - f = open_package(file_path); + if ( zeek::util::is_dir(file_path.c_str()) ) + f = zeek::util::open_package(file_path); else - f = open_file(file_path); + f = zeek::util::open_file(file_path); if ( ! f ) zeek::reporter->FatalError("can't open %s", file_path.c_str()); @@ -659,7 +659,7 @@ static int load_files(const char* orig_file) // Don't delete the old filename - it's pointed to by // every Obj created when parsing it. - yylloc.filename = filename = copy_string(file_path.c_str()); + yylloc.filename = filename = zeek::util::copy_string(file_path.c_str()); return 1; } @@ -794,7 +794,7 @@ void add_essential_input_file(const char* file) if ( ! filename ) (void) load_files(file); else - essential_input_files.push_back(copy_string(file)); + essential_input_files.push_back(zeek::util::copy_string(file)); } void add_input_file(const char* file) @@ -805,7 +805,7 @@ void add_input_file(const char* file) if ( ! filename ) (void) load_files(file); else - input_files.push_back(copy_string(file)); + input_files.push_back(zeek::util::copy_string(file)); } void add_input_file_at_front(const char* file) @@ -816,7 +816,7 @@ void add_input_file_at_front(const char* file) if ( ! filename ) (void) load_files(file); else - input_files.push_front(copy_string(file)); + input_files.push_front(zeek::util::copy_string(file)); } void add_to_name_list(char* s, char delim, zeek::name_list& nl) @@ -827,7 +827,7 @@ void add_to_name_list(char* s, char delim, zeek::name_list& nl) if ( s_delim ) *s_delim = 0; - nl.push_back(copy_string(s)); + nl.push_back(zeek::util::copy_string(s)); if ( s_delim ) s = s_delim + 1; @@ -903,8 +903,8 @@ int yywrap() if ( ! zeek_script_prefixes[i][0] ) continue; - std::string canon = without_bropath_component(it->name); - std::string flat = flatten_script_name(canon, zeek_script_prefixes[i]); + std::string canon = zeek::util::without_zeekpath_component(it->name); + std::string flat = zeek::util::flatten_script_name(canon, zeek_script_prefixes[i]); std::string path = find_relative_script_file(flat); if ( ! path.empty() ) @@ -973,7 +973,7 @@ int yywrap() auto fmt_str = use_quotes ? "redef %s %s= \"%s\";" : "redef %s %s= %s;"; - policy += fmt(fmt_str, id_str.data(), op.data(), val_str.data()); + policy += zeek::util::fmt(fmt_str, id_str.data(), op.data(), val_str.data()); } params.clear(); diff --git a/src/stats.bif b/src/stats.bif index 9d619c451a..2ebef38774 100644 --- a/src/stats.bif +++ b/src/stats.bif @@ -140,7 +140,7 @@ function get_proc_stats%(%): ProcStats auto r = zeek::make_intrusive(ProcStats); int n = 0; - double elapsed_time = current_time() - zeek::net::zeek_start_time; + double elapsed_time = zeek::util::current_time() - zeek::net::zeek_start_time; double user_time = double(ru.ru_utime.tv_sec) + double(ru.ru_utime.tv_usec) / 1e6; double system_time = @@ -159,7 +159,7 @@ function get_proc_stats%(%): ProcStats r->Assign(n++, zeek::make_intrusive(system_time, Seconds)); uint64_t total_mem; - get_memory_usage(&total_mem, NULL); + zeek::util::get_memory_usage(&total_mem, NULL); r->Assign(n++, zeek::val_mgr->Count(unsigned(total_mem))); r->Assign(n++, zeek::val_mgr->Count(unsigned(ru.ru_minflt))); diff --git a/src/strings.bif b/src/strings.bif index 534ba2a419..95f29113ad 100644 --- a/src/strings.bif +++ b/src/strings.bif @@ -487,7 +487,7 @@ function subst_string%(s: string, from: string, to: string%): string while ( big_len >= little_len ) { - int j = strstr_n(big_len, big, little_len, from->Bytes()); + int j = zeek::util::strstr_n(big_len, big, little_len, from->Bytes()); if ( j < 0 ) break; @@ -688,7 +688,7 @@ function str_smith_waterman%(s1: string, s2: string, params: sw_params%) : sw_su auto* subseq = zeek::detail::smith_waterman(s1->AsString(), s2->AsString(), sw_params); auto result = zeek::VectorValPtr{zeek::AdoptRef{}, zeek::detail::Substring::VecToPolicy(subseq)}; - delete_each(subseq); + zeek::util::delete_each(subseq); delete subseq; return result; diff --git a/src/supervisor/Supervisor.cc b/src/supervisor/Supervisor.cc index efb4abbe6f..4fa08dbd31 100644 --- a/src/supervisor/Supervisor.cc +++ b/src/supervisor/Supervisor.cc @@ -180,7 +180,7 @@ read_msgs(int fd, std::string* buffer, char delim) static std::string make_create_message(const Supervisor::NodeConfig& node) { auto json_str = node.ToJSON(); - return fmt("create %s %s", node.name.data(), json_str.data()); + return zeek::util::fmt("create %s %s", node.name.data(), json_str.data()); } zeek::detail::ParentProcessCheckTimer::ParentProcessCheckTimer(double t, @@ -265,7 +265,7 @@ Supervisor::~Supervisor() if ( kill_res == -1 ) { char tmp[256]; - bro_strerror_r(errno, tmp, sizeof(tmp)); + zeek::util::zeek_strerror_r(errno, tmp, sizeof(tmp)); reporter->Error("Failed to send SIGTERM to stem process: %s", tmp); } else @@ -276,7 +276,7 @@ Supervisor::~Supervisor() if ( wait_res == -1 ) { char tmp[256]; - bro_strerror_r(errno, tmp, sizeof(tmp)); + zeek::util::zeek_strerror_r(errno, tmp, sizeof(tmp)); reporter->Error("Failed to wait for stem process to exit: %s", tmp); } } @@ -308,7 +308,7 @@ void Supervisor::ReapStem() if ( res == -1 ) { char tmp[256]; - bro_strerror_r(errno, tmp, sizeof(tmp)); + zeek::util::zeek_strerror_r(errno, tmp, sizeof(tmp)); reporter->Error("Supervisor failed to get exit status" " of stem process: %s", tmp); return; @@ -410,7 +410,7 @@ void Supervisor::HandleChildSignal() { stem_pid = 0; char tmp[256]; - bro_strerror_r(errno, tmp, sizeof(tmp)); + zeek::util::zeek_strerror_r(errno, tmp, sizeof(tmp)); reporter->Error("failed to fork Zeek supervisor stem process: %s\n", tmp); signal_flare.Fire(); // Sleep to avoid spinning too fast in a revival-fail loop. @@ -421,9 +421,9 @@ void Supervisor::HandleChildSignal() if ( stem_pid == 0 ) { // Child stem process needs to exec() - auto stem_env = fmt("%d,%d,%d,%d,%d", stem_ppid, - stem_pipe->In().ReadFD(), stem_pipe->In().WriteFD(), - stem_pipe->Out().ReadFD(), stem_pipe->Out().WriteFD()); + auto stem_env = zeek::util::fmt("%d,%d,%d,%d,%d", stem_ppid, + stem_pipe->In().ReadFD(), stem_pipe->In().WriteFD(), + stem_pipe->Out().ReadFD(), stem_pipe->Out().WriteFD()); if ( setenv("ZEEK_STEM", stem_env, true) == -1 ) { @@ -485,7 +485,7 @@ void Supervisor::HandleChildSignal() { const auto& node = n.second; auto msg = make_create_message(node.config); - safe_write(stem_pipe->OutFD(), msg.data(), msg.size() + 1); + zeek::util::safe_write(stem_pipe->OutFD(), msg.data(), msg.size() + 1); } } @@ -593,7 +593,7 @@ size_t Supervisor::ProcessMessages() { DBG_LOG(zeek::DBG_SUPERVISOR, "read msg from Stem: %s", msg.data()); std::vector msg_tokens; - tokenize_string(msg, " ", &msg_tokens); + zeek::util::tokenize_string(msg, " ", &msg_tokens); const auto& type = msg_tokens[0]; if ( type == "status" ) @@ -611,7 +611,7 @@ size_t Supervisor::ProcessMessages() else if ( type == "error" ) { msg_tokens.erase(msg_tokens.begin()); - auto err_msg = implode_string_vector(msg_tokens, " "); + auto err_msg = zeek::util::implode_string_vector(msg_tokens, " "); reporter->Error("%s", err_msg.data()); } else @@ -624,7 +624,7 @@ size_t Supervisor::ProcessMessages() Stem::Stem(State ss) : parent_pid(ss.parent_pid), signal_flare(new zeek::detail::Flare()), pipe(std::move(ss.pipe)) { - zeek::set_thread_name("zeek.stem"); + zeek::util::set_thread_name("zeek.stem"); pipe->Swap(); stem = this; setsignal(SIGCHLD, stem_signal_handler); @@ -826,7 +826,7 @@ std::optional Stem::Revive() std::variant Stem::Spawn(SupervisorNode* node) { auto ppid = getpid(); - auto fork_res = fork_with_stdio_redirect(fmt("node %s", node->Name().data())); + auto fork_res = fork_with_stdio_redirect(zeek::util::fmt("node %s", node->Name().data())); auto node_pid = fork_res.pid; if ( node_pid == -1 ) @@ -840,7 +840,7 @@ std::variant Stem::Spawn(SupervisorNode* node) { setsignal(SIGCHLD, SIG_DFL); setsignal(SIGTERM, SIG_DFL); - zeek::set_thread_name(fmt("zeek.%s", node->Name().data())); + zeek::util::set_thread_name(zeek::util::fmt("zeek.%s", node->Name().data())); SupervisedNode rval; rval.config = node->config; rval.parent_pid = ppid; @@ -848,7 +848,7 @@ std::variant Stem::Spawn(SupervisorNode* node) } node->pid = node_pid; - auto prefix = fmt("[%s] ", node->Name().data()); + auto prefix = zeek::util::fmt("[%s] ", node->Name().data()); node->stdout_pipe.pipe = std::move(fork_res.stdout_pipe); node->stdout_pipe.prefix = prefix; node->stdout_pipe.stream = stdout; @@ -926,13 +926,13 @@ void Stem::Shutdown(int exit_code) void Stem::ReportStatus(const SupervisorNode& node) const { - std::string msg = fmt("status %s %d", node.Name().data(), node.pid); - safe_write(pipe->OutFD(), msg.data(), msg.size() + 1); + std::string msg = zeek::util::fmt("status %s %d", node.Name().data(), node.pid); + zeek::util::safe_write(pipe->OutFD(), msg.data(), msg.size() + 1); } void Stem::Log(std::string_view type, const char* format, va_list args) const { - auto raw_msg = vfmt(format, args); + auto raw_msg = zeek::util::vfmt(format, args); if ( getenv("ZEEK_DEBUG_STEM_STDERR") ) { @@ -944,7 +944,7 @@ void Stem::Log(std::string_view type, const char* format, va_list args) const std::string msg{type.data(), type.size()}; msg += " "; msg += raw_msg; - safe_write(pipe->OutFD(), msg.data(), msg.size() + 1); + zeek::util::safe_write(pipe->OutFD(), msg.data(), msg.size() + 1); } void Stem::LogDebug(const char* format, ...) const @@ -1090,7 +1090,7 @@ std::optional Stem::Poll() for ( auto& msg : msgs ) { std::vector msg_tokens; - tokenize_string(std::move(msg), " ", &msg_tokens, 2); + zeek::util::tokenize_string(std::move(msg), " ", &msg_tokens, 2); const auto& cmd = msg_tokens[0]; const auto& node_name = msg_tokens[1]; @@ -1153,7 +1153,7 @@ std::optional Supervisor::CreateStem(bool supervisor_mode) setlinebuf(stdout); setlinebuf(stderr); std::vector zeek_stem_nums; - tokenize_string(zeek_stem_env, ",", &zeek_stem_nums); + zeek::util::tokenize_string(zeek_stem_env, ",", &zeek_stem_nums); if ( zeek_stem_nums.size() != 5 ) { @@ -1507,7 +1507,7 @@ void SupervisedNode::Init(zeek::Options* options) const exit(1); } - safe_close(fd); + zeek::util::safe_close(fd); } if ( config.stdout_file ) @@ -1524,7 +1524,7 @@ void SupervisedNode::Init(zeek::Options* options) const exit(1); } - safe_close(fd); + zeek::util::safe_close(fd); } if ( config.cpu_affinity ) @@ -1602,23 +1602,23 @@ std::string Supervisor::Create(const Supervisor::NodeConfig& node) return "node names must not be an empty string"; if ( node.name.find(' ') != std::string::npos ) - return fmt("node names must not contain spaces: '%s'", + return zeek::util::fmt("node names must not contain spaces: '%s'", node.name.data()); if ( nodes.find(node.name) != nodes.end() ) - return fmt("node with name '%s' already exists", node.name.data()); + return zeek::util::fmt("node with name '%s' already exists", node.name.data()); if ( node.directory ) { - auto res = ensure_intermediate_dirs(node.directory->data()); + auto res = zeek::util::ensure_intermediate_dirs(node.directory->data()); if ( ! res ) - return fmt("failed to create working directory %s\n", - node.directory->data()); + return zeek::util::fmt("failed to create working directory %s\n", + node.directory->data()); } auto msg = make_create_message(node); - safe_write(stem_pipe->OutFD(), msg.data(), msg.size() + 1); + zeek::util::safe_write(stem_pipe->OutFD(), msg.data(), msg.size() + 1); nodes.emplace(node.name, node); return ""; } @@ -1630,7 +1630,7 @@ bool Supervisor::Destroy(std::string_view node_name) std::stringstream ss; ss << "destroy " << name; std::string msg = ss.str(); - safe_write(stem_pipe->OutFD(), msg.data(), msg.size() + 1); + zeek::util::safe_write(stem_pipe->OutFD(), msg.data(), msg.size() + 1); }; if ( node_name.empty() ) @@ -1659,7 +1659,7 @@ bool Supervisor::Restart(std::string_view node_name) std::stringstream ss; ss << "restart " << name; std::string msg = ss.str(); - safe_write(stem_pipe->OutFD(), msg.data(), msg.size() + 1); + zeek::util::safe_write(stem_pipe->OutFD(), msg.data(), msg.size() + 1); }; if ( node_name.empty() ) diff --git a/src/threading/BasicThread.cc b/src/threading/BasicThread.cc index 9228603c66..45b8120ad4 100644 --- a/src/threading/BasicThread.cc +++ b/src/threading/BasicThread.cc @@ -20,11 +20,11 @@ BasicThread::BasicThread() killed = false; buf_len = STD_FMT_BUF_LEN; - buf = (char*) safe_malloc(buf_len); + buf = (char*) zeek::util::safe_malloc(buf_len); strerr_buffer = nullptr; - name = copy_string(fmt("thread-%" PRIu64, ++thread_counter)); + name = zeek::util::copy_string(zeek::util::fmt("thread-%" PRIu64, ++thread_counter)); thread_mgr->AddThread(this); } @@ -41,13 +41,13 @@ BasicThread::~BasicThread() void BasicThread::SetName(const char* arg_name) { delete [] name; - name = copy_string(arg_name); + name = zeek::util::copy_string(arg_name); } void BasicThread::SetOSName(const char* arg_name) { static_assert(std::is_same::value, "libstdc++ doesn't use pthread_t"); - zeek::set_thread_name(arg_name, thread.native_handle()); + zeek::util::set_thread_name(arg_name, thread.native_handle()); } const char* BasicThread::Fmt(const char* format, ...) @@ -55,7 +55,7 @@ const char* BasicThread::Fmt(const char* format, ...) if ( buf_len > 10 * STD_FMT_BUF_LEN ) { // Shrink back to normal. - buf = (char*) safe_realloc(buf, STD_FMT_BUF_LEN); + buf = (char*) zeek::util::safe_realloc(buf, STD_FMT_BUF_LEN); buf_len = STD_FMT_BUF_LEN; } @@ -67,7 +67,7 @@ const char* BasicThread::Fmt(const char* format, ...) if ( (unsigned int) n >= buf_len ) { // Not enough room, grow the buffer. buf_len = n + 32; - buf = (char*) safe_realloc(buf, buf_len); + buf = (char*) zeek::util::safe_realloc(buf, buf_len); // Is it portable to restart? va_start(al, format); @@ -83,7 +83,7 @@ const char* BasicThread::Strerror(int err) if ( ! strerr_buffer ) strerr_buffer = new char[256]; - bro_strerror_r(err, strerr_buffer, 256); + zeek::util::zeek_strerror_r(err, strerr_buffer, 256); return strerr_buffer; } diff --git a/src/threading/BasicThread.h b/src/threading/BasicThread.h index 04dc05e621..3f7d067fce 100644 --- a/src/threading/BasicThread.h +++ b/src/threading/BasicThread.h @@ -113,7 +113,7 @@ public: bool Killed() const { return killed; } /** - * A version of fmt() that the thread can safely use. + * A version of zeek::util::fmt() that the thread can safely use. * * This is safe to call from Run() but must not be used from any * other thread than the current one. diff --git a/src/threading/Manager.cc b/src/threading/Manager.cc index 9b2e312d7b..e0e325cb1d 100644 --- a/src/threading/Manager.cc +++ b/src/threading/Manager.cc @@ -182,7 +182,7 @@ bool Manager::SendEvent(MsgThread* thread, const std::string& name, const int nu if ( convert_error ) return false; else if ( handler ) - zeek::event_mgr.Enqueue(handler, std::move(vl), SOURCE_LOCAL); + zeek::event_mgr.Enqueue(handler, std::move(vl), zeek::util::SOURCE_LOCAL); return true; } diff --git a/src/threading/MsgThread.cc b/src/threading/MsgThread.cc index 9417a58892..9bd96d87ba 100644 --- a/src/threading/MsgThread.cc +++ b/src/threading/MsgThread.cc @@ -78,7 +78,7 @@ public: ReporterMessage(Type arg_type, MsgThread* thread, const char* arg_msg) : OutputMessage("ReporterMessage", thread) - { type = arg_type; msg = copy_string(arg_msg); } + { type = arg_type; msg = zeek::util::copy_string(arg_msg); } ~ReporterMessage() override { delete [] msg; } @@ -112,7 +112,7 @@ class DebugMessage final : public OutputMessage public: DebugMessage(zeek::DebugStream arg_stream, MsgThread* thread, const char* arg_msg) : OutputMessage("DebugMessage", thread) - { stream = arg_stream; msg = copy_string(arg_msg); } + { stream = arg_stream; msg = zeek::util::copy_string(arg_msg); } ~DebugMessage() override { delete [] msg; } @@ -132,7 +132,7 @@ class SendEventMessage final : public OutputMessage { public: SendEventMessage(MsgThread* thread, const char* name, const int num_vals, Value* *val) : OutputMessage("SendEvent", thread), - name(copy_string(name)), num_vals(num_vals), val(val) {} + name(zeek::util::copy_string(name)), num_vals(num_vals), val(val) {} ~SendEventMessage() override { delete [] name; } @@ -303,7 +303,7 @@ void MsgThread::Heartbeat() if ( child_sent_finish ) return; - SendIn(new detail::HeartbeatMessage(this, zeek::net::network_time, current_time())); + SendIn(new detail::HeartbeatMessage(this, zeek::net::network_time, zeek::util::current_time())); } void MsgThread::Finished() diff --git a/src/threading/MsgThread.h b/src/threading/MsgThread.h index 6c2505986a..88af9ffdd4 100644 --- a/src/threading/MsgThread.h +++ b/src/threading/MsgThread.h @@ -386,7 +386,7 @@ protected: * mainly for debugging purposes. */ explicit Message(const char* arg_name) - { name = copy_string(arg_name); } + { name = zeek::util::copy_string(arg_name); } private: const char* name; diff --git a/src/threading/SerialTypes.cc b/src/threading/SerialTypes.cc index 633ecf5007..b5de44650b 100644 --- a/src/threading/SerialTypes.cc +++ b/src/threading/SerialTypes.cc @@ -32,7 +32,7 @@ bool Field::Read(zeek::detail::SerializationFormat* fmt) if ( ! fmt->Read(&tmp_secondary_name, "secondary_name") ) return false; - secondary_name = copy_string(tmp_secondary_name.c_str()); + secondary_name = zeek::util::copy_string(tmp_secondary_name.c_str()); } else secondary_name = nullptr; @@ -45,7 +45,7 @@ bool Field::Read(zeek::detail::SerializationFormat* fmt) if ( ! success ) return false; - name = copy_string(tmp_name.c_str()); + name = zeek::util::copy_string(tmp_name.c_str()); type = static_cast(t); subtype = static_cast(st); diff --git a/src/threading/SerialTypes.h b/src/threading/SerialTypes.h index 641513e341..ea010bb892 100644 --- a/src/threading/SerialTypes.h +++ b/src/threading/SerialTypes.h @@ -29,16 +29,16 @@ struct Field { * Constructor. */ Field(const char* name, const char* secondary_name, zeek::TypeTag type, zeek::TypeTag subtype, bool optional) - : name(name ? copy_string(name) : nullptr), - secondary_name(secondary_name ? copy_string(secondary_name) : nullptr), + : name(name ? zeek::util::copy_string(name) : nullptr), + secondary_name(secondary_name ? zeek::util::copy_string(secondary_name) : nullptr), type(type), subtype(subtype), optional(optional) { } /** * Copy constructor. */ Field(const Field& other) - : name(other.name ? copy_string(other.name) : nullptr), - secondary_name(other.secondary_name ? copy_string(other.secondary_name) : nullptr), + : name(other.name ? zeek::util::copy_string(other.name) : nullptr), + secondary_name(other.secondary_name ? zeek::util::copy_string(other.secondary_name) : nullptr), type(other.type), subtype(other.subtype), optional(other.optional) { } ~Field() diff --git a/src/threading/formatters/Ascii.cc b/src/threading/formatters/Ascii.cc index 73a292c6f1..113ddf7fa7 100644 --- a/src/threading/formatters/Ascii.cc +++ b/src/threading/formatters/Ascii.cc @@ -22,7 +22,7 @@ static inline bool escapeReservedContent(zeek::ODesc* desc, const string& reserv return false; char hex[4] = {'\\', 'x', '0', '0'}; - bytetohex(*data, hex + 2); + zeek::util::bytetohex(*data, hex + 2); desc->AddRaw(hex, 4); desc->AddN(data + 1, size - 1); return true; @@ -223,15 +223,15 @@ zeek::threading::Value* Ascii::ParseValue(const string& s, const string& name, z case zeek::TYPE_ENUM: case zeek::TYPE_STRING: { - string unescaped = get_unescaped_string(s); + string unescaped = zeek::util::get_unescaped_string(s); val->val.string_val.length = unescaped.size(); - val->val.string_val.data = copy_string(unescaped.c_str()); + val->val.string_val.data = zeek::util::copy_string(unescaped.c_str()); break; } case zeek::TYPE_BOOL: { - auto stripped = strstrip(s); + auto stripped = zeek::util::strstrip(s); if ( stripped == "T" || stripped == "1" ) val->val.int_val = 1; else if ( stripped == "F" || stripped == "0" ) @@ -267,20 +267,20 @@ zeek::threading::Value* Ascii::ParseValue(const string& s, const string& name, z case zeek::TYPE_PORT: { - auto stripped = strstrip(s); + auto stripped = zeek::util::strstrip(s); val->val.port_val.proto = TRANSPORT_UNKNOWN; pos = stripped.find('/'); string numberpart; if ( pos != std::string::npos && stripped.length() > pos + 1 ) { auto proto = stripped.substr(pos+1); - if ( strtolower(proto) == "tcp" ) + if ( zeek::util::strtolower(proto) == "tcp" ) val->val.port_val.proto = TRANSPORT_TCP; - else if ( strtolower(proto) == "udp" ) + else if ( zeek::util::strtolower(proto) == "udp" ) val->val.port_val.proto = TRANSPORT_UDP; - else if ( strtolower(proto) == "icmp" ) + else if ( zeek::util::strtolower(proto) == "icmp" ) val->val.port_val.proto = TRANSPORT_ICMP; - else if ( strtolower(proto) == "unknown" ) + else if ( zeek::util::strtolower(proto) == "unknown" ) val->val.port_val.proto = TRANSPORT_UNKNOWN; else GetThread()->Warning(GetThread()->Fmt("Port '%s' contained unknown protocol '%s'", s.c_str(), proto.c_str())); @@ -299,7 +299,7 @@ zeek::threading::Value* Ascii::ParseValue(const string& s, const string& name, z case zeek::TYPE_SUBNET: { - string unescaped = strstrip(get_unescaped_string(s)); + string unescaped = zeek::util::strstrip(zeek::util::get_unescaped_string(s)); size_t pos = unescaped.find('/'); if ( pos == unescaped.npos ) { @@ -322,14 +322,14 @@ zeek::threading::Value* Ascii::ParseValue(const string& s, const string& name, z case zeek::TYPE_ADDR: { - string unescaped = strstrip(get_unescaped_string(s)); + string unescaped = zeek::util::strstrip(zeek::util::get_unescaped_string(s)); val->val.addr_val = ParseAddr(unescaped); break; } case zeek::TYPE_PATTERN: { - string candidate = get_unescaped_string(s); + string candidate = zeek::util::get_unescaped_string(s); // A string is a candidate pattern iff it begins and ends with // a '/'. Rather or not the rest of the string is legal will // be determined later when it is given to the RE engine. @@ -341,7 +341,7 @@ zeek::threading::Value* Ascii::ParseValue(const string& s, const string& name, z // Remove the '/'s candidate.erase(0, 1); candidate.erase(candidate.size() - 1); - val->val.pattern_text_val = copy_string(candidate.c_str()); + val->val.pattern_text_val = zeek::util::copy_string(candidate.c_str()); break; } } diff --git a/src/threading/formatters/JSON.cc b/src/threading/formatters/JSON.cc index bea46700ba..eb41ca1e55 100644 --- a/src/threading/formatters/JSON.cc +++ b/src/threading/formatters/JSON.cc @@ -174,7 +174,8 @@ void JSON::BuildJSON(NullDoubleWriter& writer, zeek::threading::Value* val, cons case zeek::TYPE_FILE: case zeek::TYPE_FUNC: { - writer.String(json_escape_utf8(std::string(val->val.string_val.data, val->val.string_val.length))); + writer.String(zeek::util::json_escape_utf8( + std::string(val->val.string_val.data, val->val.string_val.length))); break; } diff --git a/src/util.cc b/src/util.cc index 91ed616e4b..d29c6fb10b 100644 --- a/src/util.cc +++ b/src/util.cc @@ -70,6 +70,10 @@ using namespace std; +extern const char* proc_status_file; + +namespace zeek::util { + static bool starts_with(std::string_view s, std::string_view beginning) { if ( beginning.size() > s.size() ) @@ -1065,32 +1069,27 @@ static bool write_random_seeds(const char* write_file, uint32_t seed, return true; } -static bool bro_rand_determistic = false; -static long int bro_rand_state = 0; +static bool zeek_rand_determistic = false; +static long int zeek_rand_state = 0; static bool first_seed_saved = false; static unsigned int first_seed = 0; -static void bro_srandom(unsigned int seed, bool deterministic) +static void zeek_srandom(unsigned int seed, bool deterministic) { - bro_rand_state = seed == 0 ? 1 : seed; - bro_rand_determistic = deterministic; + zeek_rand_state = seed == 0 ? 1 : seed; + zeek_rand_determistic = deterministic; srandom(seed); } -void zeek::seed_random(unsigned int seed) +void seed_random(unsigned int seed) { - if ( bro_rand_determistic ) - bro_rand_state = seed == 0 ? 1 : seed; + if ( zeek_rand_determistic ) + zeek_rand_state = seed == 0 ? 1 : seed; else srandom(seed); } -void bro_srandom(unsigned int seed) - { - zeek::seed_random(seed); - } - void init_random_seed(const char* read_file, const char* write_file, bool use_empty_seeds) { @@ -1163,7 +1162,7 @@ void init_random_seed(const char* read_file, const char* write_file, seeds_done = true; } - bro_srandom(seed, seeds_done); + zeek_srandom(seed, seeds_done); if ( ! first_seed_saved ) { @@ -1186,18 +1185,18 @@ unsigned int initial_seed() bool have_random_seed() { - return bro_rand_determistic; + return zeek_rand_determistic; } constexpr uint32_t zeek_prng_mod = 2147483647; constexpr uint32_t zeek_prng_max = zeek_prng_mod - 1; -long int zeek::max_random() +long int max_random() { - return bro_rand_determistic ? zeek_prng_max : RAND_MAX; + return zeek_rand_determistic ? zeek_prng_max : RAND_MAX; } -long int zeek::prng(long int state) +long int prng(long int state) { // Use our own simple linear congruence PRNG to make sure we are // predictable across platforms. (Lehmer RNG, Schrage's method) @@ -1220,24 +1219,14 @@ long int zeek::prng(long int state) return res; } -unsigned int bro_prng(unsigned int state) +long int random_number() { - return zeek::prng(state); - } - -long int zeek::random_number() - { - if ( ! bro_rand_determistic ) + if ( ! zeek_rand_determistic ) return random(); // Use system PRNG. - bro_rand_state = zeek::prng(bro_rand_state); + zeek_rand_state = zeek::util::prng(zeek_rand_state); - return bro_rand_state; - } - -long int bro_random() - { - return zeek::random_number(); + return zeek_rand_state; } // Returns a 64-bit random string. @@ -1247,7 +1236,7 @@ uint64_t rand64bit() int i; for ( i = 1; i <= 4; ++i ) - base = (base<<16) | zeek::random_number(); + base = (base<<16) | zeek::util::random_number(); return base; } @@ -1264,32 +1253,32 @@ int int_list_cmp(const void* v1, const void* v2) return 1; } -static string bro_path_value; +static string zeek_path_value; -const std::string& bro_path() +const std::string& zeek_path() { - if ( bro_path_value.empty() ) + if ( zeek_path_value.empty() ) { const char* path = zeekenv("ZEEKPATH"); if ( ! path ) path = DEFAULT_ZEEKPATH; - bro_path_value = path; + zeek_path_value = path; } - return bro_path_value; + return zeek_path_value; } -extern void add_to_bro_path(const string& dir) +extern void add_to_zeek_path(const string& dir) { // Make sure path is initialized. - bro_path(); + zeek_path(); - bro_path_value += string(":") + dir; + zeek_path_value += string(":") + dir; } -const char* bro_plugin_path() +const char* zeek_plugin_path() { const char* path = zeekenv("ZEEK_PLUGIN_PATH"); @@ -1299,7 +1288,7 @@ const char* bro_plugin_path() return path; } -const char* bro_plugin_activate() +const char* zeek_plugin_activate() { const char* names = zeekenv("ZEEK_PLUGIN_ACTIVATE"); @@ -1309,7 +1298,7 @@ const char* bro_plugin_activate() return names; } -string bro_prefixes() +string zeek_prefixes() { string rval; @@ -1366,7 +1355,7 @@ FILE* open_file(const string& path, const string& mode) if ( ! rval ) { char buf[256]; - bro_strerror_r(errno, buf, sizeof(buf)); + zeek_strerror_r(errno, buf, sizeof(buf)); zeek::reporter->Error("Failed to open file %s: %s", filename, buf); } @@ -1459,7 +1448,7 @@ SafeDirname::SafeDirname(const string& path, bool error_aborts) void SafeDirname::DoFunc(const string& path, bool error_aborts) { - char* tmp = copy_string(path.c_str()); + char* tmp = zeek::util::copy_string(path.c_str()); CheckValid(dirname(tmp), tmp, error_aborts); delete [] tmp; } @@ -1478,7 +1467,7 @@ SafeBasename::SafeBasename(const string& path, bool error_aborts) void SafeBasename::DoFunc(const string& path, bool error_aborts) { - char* tmp = copy_string(path.c_str()); + char* tmp = zeek::util::copy_string(path.c_str()); CheckValid(basename(tmp), tmp, error_aborts); delete [] tmp; } @@ -1697,11 +1686,11 @@ string normalize_path(std::string_view path) return new_path; } -string without_bropath_component(std::string_view path) +string without_zeekpath_component(std::string_view path) { string rval = normalize_path(path); - const auto paths = tokenize_string(bro_path(), ':'); + const auto paths = tokenize_string(zeek_path(), ':'); for ( size_t i = 0; i < paths.size(); ++i ) { @@ -1963,7 +1952,6 @@ void terminate_processing() raise(SIGTERM); } -extern const char* proc_status_file; void set_processing_status(const char* status, const char* reason) { if ( ! proc_status_file ) @@ -1980,7 +1968,7 @@ void set_processing_status(const char* status, const char* reason) if ( fd < 0 ) { char buf[256]; - bro_strerror_r(errno, buf, sizeof(buf)); + zeek_strerror_r(errno, buf, sizeof(buf)); if ( zeek::reporter ) zeek::reporter->Error("Failed to open process status file '%s': %s", proc_status_file, buf); @@ -2117,7 +2105,7 @@ uint64_t calculate_unique_id(size_t pool) gettimeofday(&unique.time, 0); unique.pool = (uint64_t) pool; unique.pid = getpid(); - unique.rnd = static_cast(zeek::random_number()); + unique.rnd = static_cast(zeek::util::random_number()); uid_instance = zeek::detail::HashKey::HashBytes(&unique, sizeof(unique)); ++uid_instance; // Now it's larger than zero. @@ -2205,23 +2193,12 @@ void safe_close(int fd) if ( close(fd) < 0 && errno != EINTR ) { char buf[128]; - bro_strerror_r(errno, buf, sizeof(buf)); + zeek_strerror_r(errno, buf, sizeof(buf)); fprintf(stderr, "safe_close error %d: %s\n", errno, buf); abort(); } } -extern "C" void out_of_memory(const char* where) - { - fprintf(stderr, "out of memory in %s.\n", where); - - if ( zeek::reporter ) - // Guess that might fail here if memory is really tight ... - zeek::reporter->FatalError("out of memory in %s.\n", where); - - abort(); - } - void get_memory_usage(uint64_t* total, uint64_t* malloced) { uint64_t ret_total; @@ -2358,9 +2335,9 @@ static void strerror_r_helper(char* result, char* buf, size_t buflen) static void strerror_r_helper(int result, char* buf, size_t buflen) { /* XSI flavor of strerror_r, no-op. */ } -void bro_strerror_r(int bro_errno, char* buf, size_t buflen) +void zeek_strerror_r(int zeek_errno, char* buf, size_t buflen) { - auto res = strerror_r(bro_errno, buf, buflen); + auto res = strerror_r(zeek_errno, buf, buflen); // GNU vs. XSI flavors make it harder to use strerror_r. strerror_r_helper(res, buf, buflen); } @@ -2532,7 +2509,7 @@ string json_escape_utf8(const string& val) return result; } -void zeek::set_thread_name(const char* name, pthread_t tid) +void set_thread_name(const char* name, pthread_t tid) { #ifdef HAVE_LINUX prctl(PR_SET_NAME, name, 0, 0, 0); @@ -2547,5 +2524,96 @@ void zeek::set_thread_name(const char* name, pthread_t tid) #endif } +} // namespace zeek::util + // Remove in v4.1. double& network_time = zeek::net::network_time; + +unsigned int bro_prng(unsigned int state) + { return zeek::util::prng(state); } + +long int bro_random() + { return zeek::util::random_number(); } + +void bro_srandom(unsigned int seed) + { zeek::util::seed_random(seed); } + +zeek::ODesc* get_escaped_string(zeek::ODesc* d, const char* str, size_t len, bool escape_all) + { return zeek::util::get_escaped_string(d, str, len, escape_all); } +std::string get_escaped_string(const char* str, size_t len, bool escape_all) + { return zeek::util::get_escaped_string(str, len, escape_all); } +std::string get_escaped_string(const std::string& str, bool escape_all) + { return zeek::util::get_escaped_string(str, escape_all); } + +std::vector* tokenize_string(std::string_view input, + std::string_view delim, + std::vector* rval, int limit) + { return zeek::util::tokenize_string(input, delim, rval, limit); } +std::vector tokenize_string(std::string_view input, const char delim) noexcept + { return zeek::util::tokenize_string(input, delim); } + +char* skip_whitespace(char* s) + { return zeek::util::skip_whitespace(s); } +const char* skip_whitespace(const char* s) + { return zeek::util::skip_whitespace(s); } +char* skip_whitespace(char* s, char* end_of_s) + { return zeek::util::skip_whitespace(s, end_of_s); } +const char* skip_whitespace(const char* s, const char* end_of_s) + { return zeek::util::skip_whitespace(s, end_of_s); } + +char* get_word(char*& s) + { return zeek::util::get_word(s); } +void get_word(int length, const char* s, int& pwlen, const char*& pw) + { zeek::util::get_word(length, s, pwlen, pw); } +void to_upper(char* s) + { zeek::util::to_upper(s); } +std::string to_upper(const std::string& s) + { return zeek::util::to_upper(s); } + +char* uitoa_n(uint64_t value, char* str, int n, int base, const char* prefix) + { return zeek::util::uitoa_n(value, str, n, base, prefix); } +int fputs(int len, const char* s, FILE* fp) + { return zeek::util::fputs(len, s, fp); } + +std::string implode_string_vector(const std::vector& v, + const std::string& delim) + { return zeek::util::implode_string_vector(v, delim); } +std::string flatten_script_name(const std::string& name, + const std::string& prefix) + { return zeek::util::flatten_script_name(name, prefix); } + +std::string find_file(const std::string& filename, const std::string& path_set, + const std::string& opt_ext) + { return zeek::util::find_file(filename, path_set, opt_ext); } +FILE* open_file(const std::string& path, const std::string& mode) + { return zeek::util::open_file(path, mode); } +FILE* open_package(std::string& path, const std::string& mode) + { return zeek::util::open_package(path, mode); } + +double current_time(bool real) + { return zeek::util::current_time(real); } + +uint64_t calculate_unique_id() + { return zeek::util::calculate_unique_id(); } +uint64_t calculate_unique_id(const size_t pool) + { return zeek::util::calculate_unique_id(pool); } + +const array& script_extensions = zeek::util::script_extensions; + +namespace zeek { + +void set_thread_name(const char* name, pthread_t tid) + { zeek::util::set_thread_name(name, tid); } + +} // namespace zeek + +extern "C" void out_of_memory(const char* where) + { + fprintf(stderr, "out of memory in %s.\n", where); + + if ( zeek::reporter ) + // Guess that might fail here if memory is really tight ... + zeek::reporter->FatalError("out of memory in %s.\n", where); + + abort(); + } diff --git a/src/util.h b/src/util.h index 2c91bb9742..c49961680c 100644 --- a/src/util.h +++ b/src/util.h @@ -79,9 +79,6 @@ typedef int16_t int16; [[deprecated("Remove in v4.1. Use int8_t instead.")]] typedef int8_t int8; -typedef int64_t bro_int_t; -typedef uint64_t bro_uint_t; - // "ptr_compat_uint" and "ptr_compat_int" are (un)signed integers of // pointer size. They can be cast safely to a pointer, e.g. in Lists, // which represent their entities as void* pointers. @@ -103,6 +100,47 @@ extern "C" #include "modp_numtoa.h" } +using bro_int_t = int64_t; +using bro_uint_t = uint64_t; + +ZEEK_FORWARD_DECLARE_NAMESPACED(ODesc, zeek); +ZEEK_FORWARD_DECLARE_NAMESPACED(RecordVal, zeek); + +#ifndef HAVE_STRCASESTR +extern char* strcasestr(const char* s, const char* find); +#endif + +// Current timestamp, from a networking perspective, not a wall-clock +// perspective. In particular, if we're reading from a savefile this +// is the time of the most recent packet, not the time returned by +// gettimeofday(). +extern double& network_time [[deprecated("Remove in v4.1. Use zeek::net::network_time.")]]; + +[[deprecated("Remove in v4.1: Use system snprintf instead")]] +inline int safe_snprintf(char* str, size_t size, const char* format, ...) + { + va_list al; + va_start(al, format); + int result = vsnprintf(str, size, format, al); + va_end(al); + str[size-1] = '\0'; + + return result; + } + +[[deprecated("Remove in v4.1: Use system vsnprintf instead")]] +inline int safe_vsnprintf(char* str, size_t size, const char* format, va_list al) + { + int result = vsnprintf(str, size, format, al); + str[size-1] = '\0'; + return result; + } + +// This is used by the patricia code and so it remains outside of hte namespace. +extern "C" void out_of_memory(const char* where); + +namespace zeek::util { + template void delete_each(T* t) { @@ -123,8 +161,6 @@ inline void bytetohex(unsigned char byte, char* hex_out) std::string get_unescaped_string(const std::string& str); -ZEEK_FORWARD_DECLARE_NAMESPACED(ODesc, zeek); - zeek::ODesc* get_escaped_string(zeek::ODesc* d, const char* str, size_t len, bool escape_all); std::string get_escaped_string(const char* str, size_t len, bool escape_all); @@ -159,9 +195,6 @@ extern void to_upper(char* s); extern std::string to_upper(const std::string& s); extern int decode_hex(char ch); extern unsigned char encode_hex(int h); -#ifndef HAVE_STRCASESTR -extern char* strcasestr(const char* s, const char* find); -#endif extern const char* strpbrk_n(size_t len, const char* s, const char* charset); template int atoi_n(int len, const char* s, const char** end, int base, T& result); extern char* uitoa_n(uint64_t value, char* str, int n, int base, const char* prefix=nullptr); @@ -216,21 +249,6 @@ unsigned int initial_seed(); // Returns true if the user explicitly set a seed via init_random_seed(); extern bool have_random_seed(); -// A simple linear congruence PRNG. It takes its state as argument and -// returns a new random value, which can serve as state for subsequent calls. -[[deprecated("Remove in v4.1. Use zeek::prng()")]] -unsigned int bro_prng(unsigned int state); - -// Replacement for the system random(), to which is normally falls back -// except when a seed has been given. In that case, the function bro_prng. -[[deprecated("Remove in v4.1. Use zeek::random_number()")]] -long int bro_random(); - -// Calls the system srandom() function with the given seed if not running -// in deterministic mode, else it updates the state of the deterministic PRNG. -[[deprecated("Remove in v4.1. Use zeek::seed_random()")]] -void bro_srandom(unsigned int seed); - extern uint64_t rand64bit(); // Each event source that may generate events gets an internally unique ID. @@ -255,11 +273,11 @@ static const SourceID SOURCE_BROKER = 0xffffffff; extern void pinpoint(); extern int int_list_cmp(const void* v1, const void* v2); -extern const std::string& bro_path(); -extern const char* bro_magic_path(); -extern const char* bro_plugin_path(); -extern const char* bro_plugin_activate(); -extern std::string bro_prefixes(); +extern const std::string& zeek_path(); +extern const char* zeek_magic_path(); +extern const char* zeek_plugin_path(); +extern const char* zeek_plugin_activate(); +extern std::string zeek_prefixes(); extern const std::array script_extensions; @@ -268,7 +286,7 @@ void warn_if_legacy_script(std::string_view filename); bool is_package_loader(const std::string& path); -extern void add_to_bro_path(const std::string& dir); +extern void add_to_zeek_path(const std::string& dir); /** @@ -318,7 +336,7 @@ std::string implode_string_vector(const std::vector& v, /** * Flatten a script name by replacing '/' path separators with '.'. - * @param file A path to a Bro script. If it is a __load__.zeek, that part + * @param file A path to a Zeek script. If it is a __load__.zeek, that part * is discarded when constructing the flattened the name. * @param prefix A string to prepend to the flattened script name. * @return The flattened script name. @@ -339,7 +357,7 @@ std::string normalize_path(std::string_view path); * @param path A file/directory path that may be within a ZEEKPATH component. * @return *path* minus the common ZEEKPATH component (if any) removed. */ -std::string without_bropath_component(std::string_view path); +std::string without_zeekpath_component(std::string_view path); /** * Gets the full path used to invoke some executable. @@ -370,8 +388,8 @@ std::string find_script_file(const std::string& filename, const std::string& pat // Wrapper around fopen(3). Emits an error when failing to open. FILE* open_file(const std::string& path, const std::string& mode = "r"); -/** Opens a Bro script package. - * @param path Location of a Bro script package (a directory). Will be changed +/** Opens a Zeek script package. + * @param path Location of a Zeek script package (a directory). Will be changed * to the path of the package's loader script. * @param mode An fopen(3) mode. * @return The return value of fopen(3) on the loader script or null if one @@ -382,7 +400,6 @@ FILE* open_package(std::string& path, const std::string& mode = "r"); // Renames the given file to a new temporary name, and opens a new file with // the original name. Returns new file or NULL on error. Inits rotate_info if // given (open time is set network time). -ZEEK_FORWARD_DECLARE_NAMESPACED(RecordVal, zeek); extern FILE* rotate_file(const char* name, zeek::RecordVal* rotate_info); // This mimics the script-level function with the same name. @@ -408,20 +425,14 @@ double calc_next_rotate(double current, double rotate_interval, double base); // Terminates processing gracefully, similar to pressing CTRL-C. void terminate_processing(); -// Sets the current status of the Bro process to the given string. +// Sets the current status of the Zeek process to the given string. // If the option --status-file has been set, this is written into // the the corresponding file. Otherwise, the function is a no-op. void set_processing_status(const char* status, const char* reason); -// Current timestamp, from a networking perspective, not a wall-clock -// perspective. In particular, if we're reading from a savefile this -// is the time of the most recent packet, not the time returned by -// gettimeofday(). -extern double& network_time [[deprecated("Remove in v4.1. Use zeek::net::network_time.")]]; - // Returns the current time. // (In pseudo-realtime mode this is faked to be the start time of the -// trace plus the time interval Bro has been running. To avoid this, +// trace plus the time interval Zeek has been running. To avoid this, // call with real=true). extern double current_time(bool real=false); @@ -431,7 +442,7 @@ extern struct timeval double_to_timeval(double t); // Return > 0 if tv_a > tv_b, 0 if equal, < 0 if tv_a < tv_b. extern int time_compare(struct timeval* tv_a, struct timeval* tv_b); -// Returns an integer that's very likely to be unique, even across Bro +// Returns an integer that's very likely to be unique, even across Zeek // instances. The integer can be drawn from different pools, which is helpful // when the random number generator is seeded to be deterministic. In that // case, the same sequence of integers is generated per pool. @@ -476,7 +487,7 @@ inline size_t pad_size(size_t size) return ((size+3) / pad + 1) * pad; } -#define padded_sizeof(x) (pad_size(sizeof(x))) +#define padded_sizeof(x) (zeek::util::pad_size(sizeof(x))) // Like write() but handles interrupted system calls by restarting. Returns // true if the write was successful, otherwise sets errno. This function is @@ -490,7 +501,7 @@ extern bool safe_pwrite(int fd, const unsigned char* data, size_t len, // Wraps close(2) to emit error messages and abort on unrecoverable errors. extern void safe_close(int fd); -extern "C" void out_of_memory(const char* where); +// Versions of realloc/malloc which abort() on out of memory inline void* safe_realloc(void* ptr, size_t size) { @@ -517,26 +528,6 @@ inline char* safe_strncpy(char* dest, const char* src, size_t n) return result; } -[[deprecated("Remove in v4.1: Use system snprintf instead")]] -inline int safe_snprintf(char* str, size_t size, const char* format, ...) - { - va_list al; - va_start(al, format); - int result = vsnprintf(str, size, format, al); - va_end(al); - str[size-1] = '\0'; - - return result; - } - -[[deprecated("Remove in v4.1: Use system vsnprintf instead")]] -inline int safe_vsnprintf(char* str, size_t size, const char* format, va_list al) - { - int result = vsnprintf(str, size, format, al); - str[size-1] = '\0'; - return result; - } - // Returns total memory allocations and (if available) amount actually // handed out by malloc. extern void get_memory_usage(uint64_t* total, uint64_t* malloced); @@ -564,7 +555,7 @@ std::string canonify_name(const std::string& name); * Reentrant version of strerror(). Takes care of the difference between the * XSI-compliant and the GNU-specific version of strerror_r(). */ -void bro_strerror_r(int bro_errno, char* buf, size_t buflen); +void zeek_strerror_r(int zeek_errno, char* buf, size_t buflen); /** * A wrapper function for getenv(). Helps check for existence of @@ -580,7 +571,6 @@ char* zeekenv(const char* name); */ std::string json_escape_utf8(const std::string& val); -namespace zeek { /** * Set the process/thread name. May not be supported on all OSs. * @param name new name for the process/thread. OS limitations typically @@ -621,4 +611,183 @@ long int max_random(); */ void seed_random(unsigned int seed); -} // namespace zeek +} // namespace zeek::util + +// A simple linear congruence PRNG. It takes its state as argument and +// returns a new random value, which can serve as state for subsequent calls. +[[deprecated("Remove in v4.1. Use zeek::util::prng()")]] +unsigned int bro_prng(unsigned int state); + +// Replacement for the system random(), to which is normally falls back +// except when a seed has been given. In that case, the function bro_prng. +[[deprecated("Remove in v4.1. Use zeek::util::random_number()")]] +long int bro_random(); + +// Calls the system srandom() function with the given seed if not running +// in deterministic mode, else it updates the state of the deterministic PRNG. +[[deprecated("Remove in v4.1. Use zeek::util::seed_random()")]] +void bro_srandom(unsigned int seed); + +template +[[ deprecated("Remove in v4.1. Use zeek::util::delete_each.")]] +void delete_each(T* t) { zeek::util::delete_each(t); } + +constexpr auto extract_ip [[deprecated("Remove in v4.1. Use zeek::util::extract_ip.")]] = zeek::util::extract_ip; +constexpr auto extract_ip_and_len [[deprecated("Remove in v4.1. Use zeek::util::extract_ip_and_len.")]] = zeek::util::extract_ip_and_len; +constexpr auto bytetohex [[deprecated("Remove in v4.1. Use zeek::util::bytetohex.")]] = zeek::util::bytetohex; +constexpr auto get_unescaped_string [[deprecated("Remove in v4.1. Use zeek::util::get_unescaped_string.")]] = zeek::util::get_unescaped_string; + +[[deprecated("Remove in v4.1. Use zeek::util::get_escaped_string.")]] +extern zeek::ODesc* get_escaped_string(zeek::ODesc* d, const char* str, size_t len, bool escape_all); +[[deprecated("Remove in v4.1. Use zeek::util::get_escaped_string.")]] +extern std::string get_escaped_string(const char* str, size_t len, bool escape_all); +[[deprecated("Remove in v4.1. Use zeek::util::get_escaped_string.")]] +extern std::string get_escaped_string(const std::string& str, bool escape_all); +[[deprecated("Remove in v4.1. Use zeek::util::tokenize_string.")]] +extern std::vector* tokenize_string(std::string_view input, + std::string_view delim, + std::vector* rval = nullptr, int limit = 0); +[[deprecated("Remove in v4.1. Use zeek::util::tokenize_string.")]] +std::vector tokenize_string(std::string_view input, const char delim) noexcept; + +constexpr auto copy_string [[deprecated("Remove in v4.1. Use zeek::util::copy_string.")]] = zeek::util::copy_string; +constexpr auto streq [[deprecated("Remove in v4.1. Use zeek::util::streq.")]] = zeek::util::streq; +constexpr auto expand_escape [[deprecated("Remove in v4.1. Use zeek::util::expand_escape.")]] = zeek::util::expand_escape; +constexpr auto skip_digits [[deprecated("Remove in v4.1. Use zeek::util::skip_digits.")]] = zeek::util::skip_digits; + +[[deprecated("Remove in v4.1. Use zeek::util::skip_whitespace.")]] +extern char* skip_whitespace(char* s); +[[deprecated("Remove in v4.1. Use zeek::util::skip_whitespace.")]] +extern const char* skip_whitespace(const char* s); +[[deprecated("Remove in v4.1. Use zeek::util::skip_whitespace.")]] +extern char* skip_whitespace(char* s, char* end_of_s); +[[deprecated("Remove in v4.1. Use zeek::util::skip_whitespace.")]] +extern const char* skip_whitespace(const char* s, const char* end_of_s); + +[[deprecated("Remove in v4.1. Use zeek::util::get_word.")]] +extern char* get_word(char*& s); +[[deprecated("Remove in v4.1. Use zeek::util::get_word.")]] +extern void get_word(int length, const char* s, int& pwlen, const char*& pw); +[[deprecated("Remove in v4.1. Use zeek::util::to_upper.")]] +extern void to_upper(char* s); +[[deprecated("Remove in v4.1. Use zeek::util::to_upper.")]] +extern std::string to_upper(const std::string& s); + +constexpr auto decode_hex [[deprecated("Remove in v4.1. Use zeek::util::decode_hex.")]] = zeek::util::decode_hex; +constexpr auto encode_hex [[deprecated("Remove in v4.1. Use zeek::util::encode_hex.")]] = zeek::util::encode_hex; +constexpr auto strpbrk_n [[deprecated("Remove in v4.1. Use zeek::util::strpbrk_n.")]] = zeek::util::strpbrk_n; +constexpr auto strstr_n [[deprecated("Remove in v4.1. Use zeek::util::strstr_n.")]] = zeek::util::strstr_n; + +template +[[deprecated("Remove in v4.1. Use zeek::util::atoi_n.")]] +int atoi_n(int len, const char* s, const char** end, int base, T& result) + { return zeek::util::atoi_n(len, s, end, base, result); } + +[[deprecated("Remove in v4.1. Use zeek::util::uitoa_n.")]] +extern char* uitoa_n(uint64_t value, char* str, int n, int base, const char* prefix=nullptr); + +[[deprecated("Remove in v4.1. Use zeek::util::fputs.")]] +extern int fputs(int len, const char* s, FILE* fp); + +constexpr auto is_printable [[deprecated("Remove in v4.1. Use zeek::util::is_printable.")]] = zeek::util::is_printable; +constexpr auto strtolower [[deprecated("Remove in v4.1. Use zeek::util::strtolower.")]] = zeek::util::strtolower; +constexpr auto fmt_bytes [[deprecated("Remove in v4.1. Use zeek::util::fmt_bytes.")]] = zeek::util::fmt_bytes; +constexpr auto vfmt [[deprecated("Remove in v4.1. Use zeek::util::vfmt.")]] = zeek::util::vfmt; +constexpr auto fmt [[deprecated("Remove in v4.1. Use zeek::util::fmt.")]] = zeek::util::fmt; +constexpr auto fmt_access_time [[deprecated("Remove in v4.1. Use zeek::util::fmt_access_time.")]] = zeek::util::fmt_access_time; +constexpr auto ensure_intermediate_dirs [[deprecated("Remove in v4.1. Use zeek::util::ensure_intermediate_dirs.")]] = zeek::util::ensure_intermediate_dirs; +constexpr auto ensure_dir [[deprecated("Remove in v4.1. Use zeek::util::ensure_dir.")]] = zeek::util::ensure_dir; +constexpr auto is_dir [[deprecated("Remove in v4.1. Use zeek::util::is_dir.")]] = zeek::util::is_dir; +constexpr auto is_file [[deprecated("Remove in v4.1. Use zeek::util::is_file.")]] = zeek::util::is_file; +constexpr auto strreplace [[deprecated("Remove in v4.1. Use zeek::util::strreplace.")]] = zeek::util::strreplace; +constexpr auto strstrip [[deprecated("Remove in v4.1. Use zeek::util::strstrip.")]] = zeek::util::strstrip; +constexpr auto hmac_md5 [[deprecated("Remove in v4.1. Use zeek::util::hmac_md5.")]] = zeek::util::hmac_md5; +constexpr auto init_random_seed [[deprecated("Remove in v4.1. Use zeek::util::init_random_seed.")]] = zeek::util::init_random_seed; +constexpr auto initial_seed [[deprecated("Remove in v4.1. Use zeek::util::initial_seed.")]] = zeek::util::initial_seed; +constexpr auto have_random_seed [[deprecated("Remove in v4.1. Use zeek::util::have_random_seed.")]] = zeek::util::have_random_seed; +constexpr auto rand64bit [[deprecated("Remove in v4.1. Use zeek::util::rand64bit.")]] = zeek::util::rand64bit; + +using SourceID [[deprecated("Remove in v4.1. Use zeek::util::SourceID.")]] = zeek::util::SourceID; +static const zeek::util::SourceID SOURCE_LOCAL [[deprecated("Remove in v4.1. Use zeek::util::SOURCE_LOCAL.")]] = zeek::util::SOURCE_LOCAL; +static const zeek::util::SourceID SOURCE_BROKER [[deprecated("Remove in v4.1. Use zeek::util::SOURCE_BROKER.")]] = zeek::util::SOURCE_BROKER; + +constexpr auto pinpoint [[deprecated("Remove in v4.1. Use zeek::util::pinpoint.")]] = zeek::util::pinpoint; +constexpr auto int_list_cmp [[deprecated("Remove in v4.1. Use zeek::util::int_list_cmp.")]] = zeek::util::int_list_cmp; +constexpr auto bro_path [[deprecated("Remove in v4.1. Use zeek::util::zeek_path.")]] = zeek::util::zeek_path; +constexpr auto bro_magic_path [[deprecated("Remove in v4.1. Use zeek::util::zeek_magic_path.")]] = zeek::util::zeek_magic_path; +constexpr auto bro_plugin_path [[deprecated("Remove in v4.1. Use zeek::util::zeek_plugin_path.")]] = zeek::util::zeek_plugin_path; +constexpr auto bro_plugin_activate [[deprecated("Remove in v4.1. Use zeek::util::zeek_plugin_activate.")]] = zeek::util::zeek_plugin_activate; +constexpr auto bro_prefixes [[deprecated("Remove in v4.1. Use zeek::util::zeek_prefixes.")]] = zeek::util::zeek_prefixes; + +extern const std::array& script_extensions [[deprecated("Remove in v4.1. Use zeek::util::script_extensions.")]]; + +constexpr auto warn_if_legacy_script [[deprecated("Remove in v4.1. Use zeek::util::warn_if_legacy_script.")]] = zeek::util::warn_if_legacy_script; +constexpr auto is_package_loader [[deprecated("Remove in v4.1. Use zeek::util::is_package_loader.")]] = zeek::util::is_package_loader; +constexpr auto add_to_bro_path [[deprecated("Remove in v4.1. Use zeek::util::add_to_zeek_path.")]] = zeek::util::add_to_zeek_path; + +using SafePathOp [[deprecated("Remove in v4.1. Use zeek::util::SafePathOp.")]] = zeek::util::SafePathOp; +using SafeDirname [[deprecated("Remove in v4.1. Use zeek::util::SafeDirname.")]] = zeek::util::SafeDirname; +using SafeBasename [[deprecated("Remove in v4.1. Use zeek::util::SafeBasename.")]] = zeek::util::SafeBasename; + +[[deprecated("Remove in v4.1. Use zeek::util::implode_string_vector.")]] +std::string implode_string_vector(const std::vector& v, + const std::string& delim = "\n"); +[[deprecated("Remove in v4.1. Use zeek::util::flatten_script_name.")]] +std::string flatten_script_name(const std::string& name, + const std::string& prefix = ""); + +constexpr auto normalize_path [[deprecated("Remove in v4.1. Use zeek::util::normalize_path.")]] = zeek::util::normalize_path; +constexpr auto without_bropath_component [[deprecated("Remove in v4.1. Use zeek::util::without_zeekpath_component.")]] = zeek::util::without_zeekpath_component; +constexpr auto get_exe_path [[deprecated("Remove in v4.1. Use zeek::util::get_exe_path.")]] = zeek::util::get_exe_path; +constexpr auto find_script_file [[deprecated("Remove in v4.1. Use zeek::util::find_script_file.")]] = zeek::util::find_script_file; + +[[deprecated("Remove in v4.1. Use zeek::util::find_file.")]] +std::string find_file(const std::string& filename, const std::string& path_set, + const std::string& opt_ext = ""); +[[deprecated("Remove in v4.1. Use zeek::util::open_file.")]] +FILE* open_file(const std::string& path, const std::string& mode = "r"); +[[deprecated("Remove in v4.1. Use zeek::util::open_package.")]] +FILE* open_package(std::string& path, const std::string& mode = "r"); + +constexpr auto rotate_file [[deprecated("Remove in v4.1. Use zeek::util::rotate_file.")]] = zeek::util::rotate_file; +constexpr auto log_file_name [[deprecated("Remove in v4.1. Use zeek::util::log_file_name.")]] = zeek::util::log_file_name; +constexpr auto parse_rotate_base_time [[deprecated("Remove in v4.1. Use zeek::util::parse_rotate_base_time.")]] = zeek::util::parse_rotate_base_time; +constexpr auto calc_next_rotate [[deprecated("Remove in v4.1. Use zeek::util::calc_next_rotate.")]] = zeek::util::calc_next_rotate; +constexpr auto terminate_processing [[deprecated("Remove in v4.1. Use zeek::util::terminate_processing.")]] = zeek::util::terminate_processing; +constexpr auto set_processing_status [[deprecated("Remove in v4.1. Use zeek::util::set_processing_status.")]] = zeek::util::set_processing_status; + +[[deprecated("Remove in v4.1. Use zeek::util::current_time.")]] +extern double current_time(bool real=false); + +constexpr auto double_to_timeval [[deprecated("Remove in v4.1. Use zeek::util::double_to_timeval.")]] = zeek::util::double_to_timeval; +constexpr auto time_compare [[deprecated("Remove in v4.1. Use zeek::util::time_compare.")]] = zeek::util::time_compare; + +[[deprecated("Remove in v4.1. Use zeek::util::calculate_unique_id.")]] +extern uint64_t calculate_unique_id(); +[[deprecated("Remove in v4.1. Use zeek::util::calculate_unique_id.")]] +extern uint64_t calculate_unique_id(const size_t pool); + +using ltstr [[deprecated("Remove in v4.1. Use zeek::util::ltstr.")]] = zeek::util::ltstr; +constexpr auto pad_size [[deprecated("Remove in v4.1. Use zeek::util::pad_size.")]] = zeek::util::pad_size; +constexpr auto safe_write [[deprecated("Remove in v4.1. Use zeek::util::safe_write.")]] = zeek::util::safe_write; +constexpr auto safe_pwrite [[deprecated("Remove in v4.1. Use zeek::util::safe_pwrite.")]] = zeek::util::safe_pwrite; +constexpr auto safe_close [[deprecated("Remove in v4.1. Use zeek::util::safe_close.")]] = zeek::util::safe_close; +constexpr auto safe_realloc [[deprecated("Remove in v4.1. Use zeek::util::safe_realloc.")]] = zeek::util::safe_realloc; +constexpr auto safe_malloc [[deprecated("Remove in v4.1. Use zeek::util::safe_malloc.")]] = zeek::util::safe_malloc; +constexpr auto safe_strncpy [[deprecated("Remove in v4.1. Use zeek::util::safe_strncpy.")]] = zeek::util::safe_strncpy; +constexpr auto get_memory_usage [[deprecated("Remove in v4.1. Use zeek::util::get_memory_usage.")]] = zeek::util::get_memory_usage; +using CompareString [[deprecated("Remove in v4.1. Use zeek::util::CompareString.")]] = zeek::util::CompareString; +constexpr auto canonify_name [[deprecated("Remove in v4.1. Use zeek::util::canonify_name.")]] = zeek::util::canonify_name; +constexpr auto bro_strerror_r [[deprecated("Remove in v4.1. Use zeek::util::zeek_strerror_r.")]] = zeek::util::zeek_strerror_r; +constexpr auto zeekenv [[deprecated("Remove in v4.1. Use zeek::util::zeekenv.")]] = zeek::util::zeekenv; +constexpr auto json_escape_utf8 [[deprecated("Remove in v4.1. Use zeek::util::json_escape_utf8.")]] = zeek::util::json_escape_utf8; + +namespace zeek { + [[deprecated("Remove in v4.1. Use zeek::util::set_thread_name.")]] + void set_thread_name(const char* name, pthread_t tid = pthread_self()); + + constexpr auto prng [[deprecated("Remove in v4.1. Use zeek::util::prng.")]] = zeek::util::prng; + constexpr auto random_number [[deprecated("Remove in v4.1. Use zeek::util::random_number.")]] = zeek::util::random_number; + constexpr auto max_random [[deprecated("Remove in v4.1. Use zeek::util::max_random.")]] = zeek::util::max_random; + constexpr auto seed_random [[deprecated("Remove in v4.1. Use zeek::util::seed_random.")]] = zeek::util::seed_random; +} diff --git a/src/zeek-setup.cc b/src/zeek-setup.cc index d984a06c82..43d58b524b 100644 --- a/src/zeek-setup.cc +++ b/src/zeek-setup.cc @@ -232,7 +232,7 @@ bool show_plugins(int level) void done_with_network() { - set_processing_status("TERMINATING", "done_with_network"); + zeek::util::set_processing_status("TERMINATING", "done_with_network"); // Cancel any pending alarms (watchdog, in particular). (void) alarm(0); @@ -279,7 +279,7 @@ void done_with_network() void terminate_bro() { - set_processing_status("TERMINATING", "terminate_bro"); + zeek::util::set_processing_status("TERMINATING", "terminate_bro"); zeek::net::terminating = true; @@ -341,7 +341,7 @@ namespace zeek::net::detail { void zeek_terminate_loop(const char* reason) { - set_processing_status("TERMINATING", reason); + zeek::util::set_processing_status("TERMINATING", reason); zeek::reporter->Info("%s", reason); net_get_final_stats(); @@ -363,7 +363,7 @@ void zeek_terminate_loop(const char* reason) RETSIGTYPE sig_handler(int signo) { - set_processing_status("TERMINATING", "sig_handler"); + zeek::util::set_processing_status("TERMINATING", "sig_handler"); signal_val = signo; if ( ! zeek::net::terminating ) @@ -374,7 +374,7 @@ RETSIGTYPE sig_handler(int signo) static void atexit_handler() { - set_processing_status("TERMINATED", "atexit"); + zeek::util::set_processing_status("TERMINATED", "atexit"); } static void bro_new_handler() @@ -388,7 +388,7 @@ static std::vector get_script_signature_files() // Parse rule files defined on the script level. char* script_signature_files = - copy_string(zeek::id::find_val("signature_files")->AsString()->CheckString()); + zeek::util::copy_string(zeek::id::find_val("signature_files")->AsString()->CheckString()); char* tmp = script_signature_files; char* s; @@ -406,7 +406,7 @@ zeek::detail::SetupResult zeek::detail::setup(int argc, char** argv, ZEEK_LSAN_DISABLE(); std::set_new_handler(bro_new_handler); - auto zeek_exe_path = get_exe_path(argv[0]); + auto zeek_exe_path = zeek::util::get_exe_path(argv[0]); if ( zeek_exe_path.empty() ) { @@ -418,7 +418,7 @@ zeek::detail::SetupResult zeek::detail::setup(int argc, char** argv, bro_argv = new char* [argc]; for ( int i = 0; i < argc; i++ ) - bro_argv[i] = copy_string(argv[i]); + bro_argv[i] = zeek::util::copy_string(argv[i]); auto options = zopts ? *zopts : zeek::parse_cmdline(argc, argv); @@ -455,10 +455,10 @@ zeek::detail::SetupResult zeek::detail::setup(int argc, char** argv, RETSIGTYPE (*oldhandler)(int); zeek_script_prefixes = options.script_prefixes; - auto zeek_prefixes = zeekenv("ZEEK_PREFIXES"); + auto zeek_prefixes = zeek::util::zeekenv("ZEEK_PREFIXES"); if ( zeek_prefixes ) - tokenize_string(zeek_prefixes, ":", &zeek_script_prefixes); + zeek::util::tokenize_string(zeek_prefixes, ":", &zeek_script_prefixes); zeek::net::pseudo_realtime = options.pseudo_realtime; @@ -483,12 +483,12 @@ zeek::detail::SetupResult zeek::detail::setup(int argc, char** argv, } if ( options.process_status_file ) - proc_status_file = copy_string(options.process_status_file->data()); + proc_status_file = zeek::util::copy_string(options.process_status_file->data()); atexit(atexit_handler); - set_processing_status("INITIALIZING", "main"); + zeek::util::set_processing_status("INITIALIZING", "main"); - zeek::net::zeek_start_time = current_time(true); + zeek::net::zeek_start_time = zeek::util::current_time(true); zeek::val_mgr = new ValManager(); reporter = new Reporter(options.abort_on_scripting_errors); @@ -515,14 +515,14 @@ zeek::detail::SetupResult zeek::detail::setup(int argc, char** argv, zeek::supervisor_mgr = new zeek::Supervisor(std::move(cfg), std::move(*stem)); } - const char* seed_load_file = zeekenv("ZEEK_SEED_FILE"); + const char* seed_load_file = zeek::util::zeekenv("ZEEK_SEED_FILE"); if ( options.random_seed_input_file ) seed_load_file = options.random_seed_input_file->data(); - init_random_seed((seed_load_file && *seed_load_file ? seed_load_file : nullptr), - options.random_seed_output_file ? options.random_seed_output_file->data() : nullptr, - options.deterministic_mode); + zeek::util::init_random_seed((seed_load_file && *seed_load_file ? seed_load_file : nullptr), + options.random_seed_output_file ? options.random_seed_output_file->data() : nullptr, + options.deterministic_mode); // DEBUG_MSG("HMAC key: %s\n", md5_digest_print(shared_hmac_md5_key)); init_hash_function(); @@ -559,7 +559,7 @@ zeek::detail::SetupResult zeek::detail::setup(int argc, char** argv, if ( ! options.bare_mode ) add_input_file("base/init-default.zeek"); - zeek::plugin_mgr->SearchDynamicPlugins(bro_plugin_path()); + zeek::plugin_mgr->SearchDynamicPlugins(zeek::util::zeek_plugin_path()); if ( options.plugins_to_load.empty() && options.scripts_to_load.empty() && options.script_options_to_set.empty() && @@ -818,7 +818,7 @@ zeek::detail::SetupResult zeek::detail::setup(int argc, char** argv, if ( ! zeek::net::reading_live && ! zeek::net::reading_traces ) // Set up network_time to track real-time, since // we don't have any other source for it. - zeek::net::detail::net_update_time(current_time()); + zeek::net::detail::net_update_time(zeek::util::current_time()); if ( zeek_init ) zeek::event_mgr.Enqueue(zeek_init, zeek::Args{}); @@ -879,7 +879,7 @@ zeek::detail::SetupResult zeek::detail::setup(int argc, char** argv, // Drain the event queue here to support the protocols framework configuring DPM zeek::event_mgr.Drain(); - if ( zeek::reporter->Errors() > 0 && ! zeekenv("ZEEK_ALLOW_INIT_ERRORS") ) + if ( zeek::reporter->Errors() > 0 && ! zeek::util::zeekenv("ZEEK_ALLOW_INIT_ERRORS") ) zeek::reporter->FatalError("errors occurred while initializing"); zeek::broker_mgr->ZeekInitDone(); diff --git a/src/zeek.bif b/src/zeek.bif index d164998a45..6d9cc79a22 100644 --- a/src/zeek.bif +++ b/src/zeek.bif @@ -319,7 +319,7 @@ static int next_fmt(const char*& fmt, const zeek::Args* args, zeek::ODesc* d, in ## .. zeek:see:: network_time function current_time%(%): time %{ - return zeek::make_intrusive(current_time()); + return zeek::make_intrusive(zeek::util::current_time()); %} ## Returns the timestamp of the last packet processed. This function returns @@ -344,7 +344,7 @@ function network_time%(%): time ## .. zeek:see:: setenv function getenv%(var: string%): string %{ - const char* env_val = zeekenv(var->CheckString()); + const char* env_val = zeek::util::zeekenv(var->CheckString()); if ( ! env_val ) env_val = ""; // ### return zeek::make_intrusive(env_val); @@ -391,7 +391,7 @@ function terminate%(%): bool if ( zeek::net::terminating ) return zeek::val_mgr->False(); - terminate_processing(); + zeek::util::terminate_processing(); return zeek::val_mgr->True(); %} @@ -415,10 +415,10 @@ static bool prepare_environment(zeek::TableVal* tbl, bool set) return false; } - char* tmp = copy_string(key->AsString()->CheckString()); - to_upper(tmp); - std::string var1 = fmt("ZEEK_ARG_%s", tmp); - std::string var2 = fmt("BRO_ARG_%s", tmp); // legacy support + char* tmp = zeek::util::copy_string(key->AsString()->CheckString()); + zeek::util::to_upper(tmp); + std::string var1 = zeek::util::fmt("ZEEK_ARG_%s", tmp); + std::string var2 = zeek::util::fmt("BRO_ARG_%s", tmp); // legacy support delete [] tmp; if ( set ) @@ -930,7 +930,7 @@ function hrw_weight%(key_digest: count, site_id: count%): count ## provided by the OS. function rand%(max: count%): count %{ - auto result = bro_uint_t(double(max) * double(zeek::random_number()) / (zeek::max_random() + 1.0)); + auto result = bro_uint_t(double(max) * double(zeek::util::random_number()) / (zeek::util::max_random() + 1.0)); return zeek::val_mgr->Count(result); %} @@ -946,7 +946,7 @@ function rand%(max: count%): count ## provided by the OS. function srand%(seed: count%): any %{ - zeek::seed_random(seed); + zeek::util::seed_random(seed); return nullptr; %} @@ -1123,8 +1123,9 @@ function entropy_test_finish%(handle: opaque of entropy%): entropy_test_result function unique_id%(prefix: string%) : string %{ char tmp[20]; - uint64_t uid = calculate_unique_id(UID_POOL_DEFAULT_SCRIPT); - return zeek::make_intrusive(uitoa_n(uid, tmp, sizeof(tmp), 62, prefix->CheckString())); + uint64_t uid = zeek::util::calculate_unique_id(UID_POOL_DEFAULT_SCRIPT); + return zeek::make_intrusive( + zeek::util::uitoa_n(uid, tmp, sizeof(tmp), 62, prefix->CheckString())); %} ## Creates an identifier that is unique with high probability. @@ -1141,8 +1142,9 @@ function unique_id_from%(pool: int, prefix: string%) : string pool += UID_POOL_CUSTOM_SCRIPT; // Make sure we don't conflict with internal pool. char tmp[20]; - uint64_t uid = calculate_unique_id(pool); - return zeek::make_intrusive(uitoa_n(uid, tmp, sizeof(tmp), 62, prefix->CheckString())); + uint64_t uid = zeek::util::calculate_unique_id(pool); + return zeek::make_intrusive( + zeek::util::uitoa_n(uid, tmp, sizeof(tmp), 62, prefix->CheckString())); %} # =========================================================================== @@ -2653,11 +2655,11 @@ function to_port%(s: string%): port if ( ! errno ) { ++slash; - if ( streq(slash, "tcp") ) + if ( zeek::util::streq(slash, "tcp") ) return zeek::val_mgr->Port(port, TRANSPORT_TCP); - else if ( streq(slash, "udp") ) + else if ( zeek::util::streq(slash, "udp") ) return zeek::val_mgr->Port(port, TRANSPORT_UDP); - else if ( streq(slash, "icmp") ) + else if ( zeek::util::streq(slash, "icmp") ) return zeek::val_mgr->Port(port, TRANSPORT_ICMP); } } @@ -3380,8 +3382,8 @@ const char* conn_id_string(zeek::Val* c) const zeek::IPAddr& resp_h = (*vl)[2]->AsAddr(); uint32_t resp_p = (*vl)[3]->AsPortVal()->Port(); - return fmt("%s/%u -> %s/%u\n", orig_h.AsString().c_str(), orig_p, - resp_h.AsString().c_str(), resp_p); + return zeek::util::fmt("%s/%u -> %s/%u\n", orig_h.AsString().c_str(), orig_p, + resp_h.AsString().c_str(), resp_p); } %%} @@ -3697,7 +3699,7 @@ static void report_mmdb_msg(const char* format, ...) va_list al; va_start(al, format); - std::string msg = fmt(format, al); + std::string msg = zeek::util::fmt(format, al); va_end(al); zeek::reporter->Info("%s", msg.data()); @@ -4437,7 +4439,7 @@ function open%(f: string%): file %{ const char* file = f->CheckString(); - if ( streq(file, "-") ) + if ( zeek::util::streq(file, "-") ) return zeek::make_intrusive(zeek::make_intrusive(stdout, "-", "w")); else return zeek::make_intrusive(zeek::make_intrusive(file, "w")); @@ -4544,8 +4546,8 @@ function mkdir%(f: string%): bool && S_ISDIR(filestat.st_mode) ) return zeek::val_mgr->True(); - zeek::emit_builtin_error(fmt("cannot create directory '%s': %s", filename, - strerror(error))); + zeek::emit_builtin_error(zeek::util::fmt("cannot create directory '%s': %s", filename, + strerror(error))); return zeek::val_mgr->False(); } else @@ -4569,8 +4571,8 @@ function rmdir%(d: string%): bool if ( rmdir(dirname) < 0 ) { - zeek::emit_builtin_error(fmt("cannot remove directory '%s': %s", dirname, - strerror(errno))); + zeek::emit_builtin_error(zeek::util::fmt("cannot remove directory '%s': %s", dirname, + strerror(errno))); return zeek::val_mgr->False(); } else @@ -4593,8 +4595,8 @@ function unlink%(f: string%): bool if ( unlink(filename) < 0 ) { - zeek::emit_builtin_error(fmt("cannot unlink file '%s': %s", filename, - strerror(errno))); + zeek::emit_builtin_error(zeek::util::fmt("cannot unlink file '%s': %s", filename, + strerror(errno))); return zeek::val_mgr->False(); } else @@ -4619,8 +4621,8 @@ function rename%(src_f: string, dst_f: string%): bool if ( rename(src_filename, dst_filename) < 0 ) { - zeek::emit_builtin_error(fmt("cannot rename file '%s' to '%s': %s", src_filename, - dst_filename, strerror(errno))); + zeek::emit_builtin_error(zeek::util::fmt("cannot rename file '%s' to '%s': %s", src_filename, + dst_filename, strerror(errno))); return zeek::val_mgr->False(); } else @@ -4697,20 +4699,20 @@ function rotate_file_by_name%(f: string%): rotate_info bool is_addl_pkt_dumper = false; // Special case: one of current dump files. - if ( zeek::net::detail::pkt_dumper && streq(zeek::net::detail::pkt_dumper->Path().c_str(), f->CheckString()) ) + if ( zeek::net::detail::pkt_dumper && zeek::util::streq(zeek::net::detail::pkt_dumper->Path().c_str(), f->CheckString()) ) { is_pkt_dumper = true; zeek::net::detail::pkt_dumper->Close(); } if ( addl_pkt_dumper && - streq(addl_pkt_dumper->Path().c_str(), f->CheckString()) ) + zeek::util::streq(addl_pkt_dumper->Path().c_str(), f->CheckString()) ) { is_addl_pkt_dumper = true; addl_pkt_dumper->Close(); } - FILE* file = rotate_file(f->CheckString(), info.get()); + FILE* file = zeek::util::rotate_file(f->CheckString(), info.get()); if ( ! file ) { // Record indicating error. @@ -4748,8 +4750,8 @@ function calc_next_rotate%(i: interval%) : interval static auto log_rotate_base_time = zeek::id::find_val("log_rotate_base_time"); static auto base_time = log_rotate_base_time->AsString()->CheckString(); - double base = parse_rotate_base_time(base_time); - return zeek::make_intrusive(calc_next_rotate(zeek::net::network_time, i, base)); + double base = zeek::util::parse_rotate_base_time(base_time); + return zeek::make_intrusive(zeek::util::calc_next_rotate(zeek::net::network_time, i, base)); %} ## Returns the size of a given file. @@ -4997,7 +4999,7 @@ function uninstall_dst_net_filter%(snet: subnet%) : bool ## Returns: True if the last raised event came from a remote peer. function is_remote_event%(%) : bool %{ - return zeek::val_mgr->Bool(zeek::event_mgr.CurrentSource() != SOURCE_LOCAL); + return zeek::val_mgr->Bool(zeek::event_mgr.CurrentSource() != zeek::util::SOURCE_LOCAL); %} ## Stops Zeek's packet processing. This function is used to synchronize @@ -5167,5 +5169,5 @@ function to_json%(val: any, only_loggable: bool &default=F, field_escape_pattern ## Returns: a compressed version of the input path. function compress_path%(dir: string%): string %{ - return zeek::make_intrusive(normalize_path(dir->ToStdString())); + return zeek::make_intrusive(zeek::util::normalize_path(dir->ToStdString())); %} diff --git a/src/zeekygen/Configuration.cc b/src/zeekygen/Configuration.cc index 7cd885c110..1b0ce2a436 100644 --- a/src/zeekygen/Configuration.cc +++ b/src/zeekygen/Configuration.cc @@ -46,7 +46,7 @@ Config::Config(const string& arg_file, const string& delim) { ++line_number; vector tokens; - tokenize_string(line, delim, &tokens); + zeek::util::tokenize_string(line, delim, &tokens); tokens.erase(remove(tokens.begin(), tokens.end(), ""), tokens.end()); if ( tokens.empty() ) diff --git a/src/zeekygen/Manager.cc b/src/zeekygen/Manager.cc index d8fe9db12a..78e2d9753c 100644 --- a/src/zeekygen/Manager.cc +++ b/src/zeekygen/Manager.cc @@ -33,9 +33,9 @@ static void WarnMissingScript(const char* type, const zeek::detail::ID* id, if ( script == "" ) return; - DbgAndWarn(fmt("Can't generate Zeekygen doumentation for %s %s, " - "lookup of %s failed", - type, id->Name(), script.c_str())); + DbgAndWarn(zeek::util::fmt("Can't generate Zeekygen doumentation for %s %s, " + "lookup of %s failed", + type, id->Name(), script.c_str())); } static string RemoveLeadingSpace(const string& s) @@ -56,12 +56,12 @@ static string NormalizeScriptPath(const string& path) { if ( auto p = zeek::plugin_mgr->LookupPluginByPath(path) ) { - auto rval = normalize_path(path); - auto prefix = SafeBasename(p->PluginDirectory()).result; + auto rval = zeek::util::normalize_path(path); + auto prefix = zeek::util::SafeBasename(p->PluginDirectory()).result; return prefix + "/" + rval.substr(p->PluginDirectory().size() + 1); } - return without_bropath_component(path); + return zeek::util::without_zeekpath_component(path); } Manager::Manager(const string& arg_config, const string& bro_command) @@ -69,7 +69,7 @@ Manager::Manager(const string& arg_config, const string& bro_command) identifiers(), all_info(), last_identifier_seen(), incomplete_type(), enum_mappings(), config(arg_config), bro_mtime() { - if ( zeekenv("ZEEK_DISABLE_ZEEKYGEN") ) + if ( zeek::util::zeekenv("ZEEK_DISABLE_ZEEKYGEN") ) disabled = true; // If running bro without the "-X" option, then we don't need bro_mtime. @@ -81,7 +81,7 @@ Manager::Manager(const string& arg_config, const string& bro_command) // bro_command is a relative path). const char* env_path = getenv("PATH"); string path = env_path ? string(env_path) + ":." : "."; - string path_to_bro = find_file(bro_command, path); + string path_to_bro = zeek::util::find_file(bro_command, path); struct stat s; // One way that find_file() could fail is when bro is located in @@ -137,8 +137,8 @@ void Manager::Script(const string& path) if ( scripts.GetInfo(name) ) { - DbgAndWarn(fmt("Duplicate Zeekygen script documentation: %s", - name.c_str())); + DbgAndWarn(zeek::util::fmt("Duplicate Zeekygen script documentation: %s", + name.c_str())); return; } @@ -150,12 +150,12 @@ void Manager::Script(const string& path) if ( ! info->IsPkgLoader() ) return; - name = SafeDirname(name).result; + name = zeek::util::SafeDirname(name).result; if ( packages.GetInfo(name) ) { - DbgAndWarn(fmt("Duplicate Zeekygen package documentation: %s", - name.c_str())); + DbgAndWarn(zeek::util::fmt("Duplicate Zeekygen package documentation: %s", + name.c_str())); return; } @@ -172,8 +172,8 @@ void Manager::ScriptDependency(const string& path, const string& dep) if ( dep.empty() ) { - DbgAndWarn(fmt("Empty Zeekygen script doc dependency: %s", - path.c_str())); + DbgAndWarn(zeek::util::fmt("Empty Zeekygen script doc dependency: %s", + path.c_str())); return; } @@ -183,8 +183,8 @@ void Manager::ScriptDependency(const string& path, const string& dep) if ( ! script_info ) { - DbgAndWarn(fmt("Failed to add Zeekygen script doc dependency %s " - "for %s", depname.c_str(), name.c_str())); + DbgAndWarn(zeek::util::fmt("Failed to add Zeekygen script doc dependency %s " + "for %s", depname.c_str(), name.c_str())); return; } @@ -193,8 +193,8 @@ void Manager::ScriptDependency(const string& path, const string& dep) depname.c_str(), name.c_str()); for ( size_t i = 0; i < comment_buffer.size(); ++i ) - DbgAndWarn(fmt("Discarded extraneous Zeekygen comment: %s", - comment_buffer[i].c_str())); + DbgAndWarn(zeek::util::fmt("Discarded extraneous Zeekygen comment: %s", + comment_buffer[i].c_str())); } void Manager::ModuleUsage(const string& path, const string& module) @@ -207,8 +207,8 @@ void Manager::ModuleUsage(const string& path, const string& module) if ( ! script_info ) { - DbgAndWarn(fmt("Failed to add Zeekygen module usage %s in %s", - module.c_str(), name.c_str())); + DbgAndWarn(zeek::util::fmt("Failed to add Zeekygen module usage %s in %s", + module.c_str(), name.c_str())); return; } @@ -255,8 +255,8 @@ void Manager::StartType(zeek::detail::IDPtr id) if ( id->GetLocationInfo() == &zeek::detail::no_location ) { - DbgAndWarn(fmt("Can't generate zeekygen doumentation for %s, " - "no location available", id->Name())); + DbgAndWarn(zeek::util::fmt("Can't generate zeekygen doumentation for %s, " + "no location available", id->Name())); return; } @@ -310,7 +310,7 @@ void Manager::Identifier(zeek::detail::IDPtr id) return; } - DbgAndWarn(fmt("Duplicate identifier documentation: %s", id->Name())); + DbgAndWarn(zeek::util::fmt("Duplicate identifier documentation: %s", id->Name())); return; } @@ -348,9 +348,9 @@ void Manager::RecordField(const zeek::detail::ID* id, const zeek::TypeDecl* fiel if ( ! idd ) { - DbgAndWarn(fmt("Can't generate zeekygen doumentation for " - "record field %s, unknown record: %s", - field->id, id->Name())); + DbgAndWarn(zeek::util::fmt("Can't generate zeekygen doumentation for " + "record field %s, unknown record: %s", + field->id, id->Name())); return; } @@ -376,9 +376,9 @@ void Manager::Redef(const zeek::detail::ID* id, const string& path, if ( ! id_info ) { - DbgAndWarn(fmt("Can't generate zeekygen doumentation for " - "redef of %s, identifier lookup failed", - id->Name())); + DbgAndWarn(zeek::util::fmt("Can't generate zeekygen doumentation for " + "redef of %s, identifier lookup failed", + id->Name())); return; } @@ -416,8 +416,8 @@ void Manager::SummaryComment(const string& script, const string& comment) if ( info ) info->AddComment(RemoveLeadingSpace(comment)); else - DbgAndWarn(fmt("Lookup of script %s failed for summary comment %s", - name.c_str(), comment.c_str())); + DbgAndWarn(zeek::util::fmt("Lookup of script %s failed for summary comment %s", + name.c_str(), comment.c_str())); } void Manager::PreComment(const string& comment) @@ -438,8 +438,8 @@ void Manager::PostComment(const string& comment, const string& id_hint) if ( last_identifier_seen ) last_identifier_seen->AddComment(RemoveLeadingSpace(comment)); else - DbgAndWarn(fmt("Discarded unassociated Zeekygen comment %s", - comment.c_str())); + DbgAndWarn(zeek::util::fmt("Discarded unassociated Zeekygen comment %s", + comment.c_str())); return; } diff --git a/src/zeekygen/PackageInfo.cc b/src/zeekygen/PackageInfo.cc index c995c8e758..2a212789ad 100644 --- a/src/zeekygen/PackageInfo.cc +++ b/src/zeekygen/PackageInfo.cc @@ -15,7 +15,7 @@ PackageInfo::PackageInfo(const string& arg_name) : Info(), pkg_name(arg_name), readme() { - string readme_file = find_file(pkg_name + "/README", bro_path()); + string readme_file = zeek::util::find_file(pkg_name + "/README", zeek::util::zeek_path()); if ( readme_file.empty() ) return; @@ -38,8 +38,8 @@ PackageInfo::PackageInfo(const string& arg_name) string PackageInfo::DoReStructuredText(bool roles_only) const { - string rval = fmt(":doc:`%s `\n\n", pkg_name.c_str(), - pkg_name.c_str()); + string rval = zeek::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"; @@ -49,7 +49,7 @@ string PackageInfo::DoReStructuredText(bool roles_only) const time_t PackageInfo::DoGetModificationTime() const { - string readme_file = find_file(pkg_name + "/README", bro_path()); + string readme_file = zeek::util::find_file(pkg_name + "/README", zeek::util::zeek_path()); if ( readme_file.empty() ) return 0; diff --git a/src/zeekygen/ScriptInfo.cc b/src/zeekygen/ScriptInfo.cc index b12f5b769a..3754ab3b09 100644 --- a/src/zeekygen/ScriptInfo.cc +++ b/src/zeekygen/ScriptInfo.cc @@ -161,7 +161,7 @@ static string make_redef_details(const string& heading, char underline, ScriptInfo::ScriptInfo(const string& arg_name, const string& arg_path) : Info(), name(arg_name), path(arg_path), - is_pkg_loader(is_package_loader(name)), + is_pkg_loader(zeek::util::is_package_loader(name)), dependencies(), module_usages(), comments(), id_info(), redef_options(), constants(), state_vars(), types(), events(), hooks(), functions(), redefs() @@ -317,20 +317,20 @@ string ScriptInfo::DoReStructuredText(bool roles_only) const if ( it != dependencies.begin() ) rval += ", "; - string path = find_script_file(*it, bro_path()); + string path = zeek::util::find_script_file(*it, zeek::util::zeek_path()); string doc = *it; - if ( ! path.empty() && is_dir(path.c_str()) ) + if ( ! path.empty() && zeek::util::is_dir(path.c_str()) ) // Reference the package. doc += "/index"; - rval += fmt(":doc:`%s `", it->c_str(), doc.c_str()); + rval += zeek::util::fmt(":doc:`%s `", it->c_str(), doc.c_str()); } rval += "\n"; } - //rval += fmt(":Source File: :download:`/scripts/%s`\n", name.c_str()); + //rval += zeek::util::fmt(":Source File: :download:`/scripts/%s`\n", name.c_str()); rval += "\n"; rval += zeekygen::make_heading("Summary", '~'); rval += make_summary("Runtime Options", '#', '=', options); @@ -368,7 +368,7 @@ time_t ScriptInfo::DoGetModificationTime() const if ( ! info ) { - for (const string& ext : script_extensions) + for (const string& ext : zeek::util::script_extensions) { string pkg_name = *it + "/__load__" + ext; info = zeekygen_mgr->GetScriptInfo(pkg_name); diff --git a/src/zeekygen/Target.cc b/src/zeekygen/Target.cc index 282007bc1c..ff74f6bf96 100644 --- a/src/zeekygen/Target.cc +++ b/src/zeekygen/Target.cc @@ -36,7 +36,7 @@ static void write_plugin_section_heading(FILE* f, const zeek::plugin::Plugin* p) static void write_analyzer_component(FILE* f, const zeek::analyzer::Component* c) { const auto& atag = zeek::analyzer_mgr->GetTagType(); - string tag = fmt("ANALYZER_%s", c->CanonicalName().c_str()); + string tag = zeek::util::fmt("ANALYZER_%s", c->CanonicalName().c_str()); if ( atag->Lookup("Analyzer", tag.c_str()) < 0 ) zeek::reporter->InternalError("missing analyzer tag for %s", tag.c_str()); @@ -47,7 +47,7 @@ static void write_analyzer_component(FILE* f, const zeek::analyzer::Component* c static void write_analyzer_component(FILE* f, const zeek::file_analysis::Component* c) { const auto& atag = zeek::file_mgr->GetTagType(); - string tag = fmt("ANALYZER_%s", c->CanonicalName().c_str()); + string tag = zeek::util::fmt("ANALYZER_%s", c->CanonicalName().c_str()); if ( atag->Lookup("Files", tag.c_str()) < 0 ) zeek::reporter->InternalError("missing analyzer tag for %s", tag.c_str()); @@ -193,9 +193,9 @@ TargetFile::TargetFile(const string& arg_name) { if ( name.find('/') != string::npos ) { - string dir = SafeDirname(name).result; + string dir = zeek::util::SafeDirname(name).result; - if ( ! ensure_intermediate_dirs(dir.c_str()) ) + if ( ! zeek::util::ensure_intermediate_dirs(dir.c_str()) ) zeek::reporter->FatalError("Zeekygen failed to make dir %s", dir.c_str()); } @@ -352,7 +352,7 @@ void PackageTarget::DoGenerate() const for ( manifest_t::const_iterator it = pkg_manifest.begin(); it != pkg_manifest.end(); ++it ) { - string header = fmt("Package: %s", it->first->Name().c_str()); + string header = zeek::util::fmt("Package: %s", it->first->Name().c_str()); header += "\n" + string(header.size(), '='); fprintf(file.f, "%s\n\n", header.c_str()); @@ -412,9 +412,9 @@ void ScriptTarget::DoFindDependencies(const vector& infos) for ( size_t i = 0; i < script_deps.size(); ++i ) { - if ( is_package_loader(script_deps[i]->Name()) ) + if ( zeek::util::is_package_loader(script_deps[i]->Name()) ) { - string pkg_dir = SafeDirname(script_deps[i]->Name()).result; + string pkg_dir = zeek::util::SafeDirname(script_deps[i]->Name()).result; string target_file = Name() + pkg_dir + "/index.rst"; Target* t = new PackageTarget(target_file, pkg_dir); t->FindDependencies(infos); @@ -434,7 +434,7 @@ vector dir_contents_recursive(string dir) while ( dir[dir.size() - 1] == '/' ) dir.erase(dir.size() - 1, 1); - char* dir_copy = copy_string(dir.c_str()); + char* dir_copy = zeek::util::copy_string(dir.c_str()); char** scan_path = new char*[2]; scan_path[0] = dir_copy; scan_path[1] = NULL; diff --git a/src/zeekygen/utils.cc b/src/zeekygen/utils.cc index 88a6385f36..a97b6343be 100644 --- a/src/zeekygen/utils.cc +++ b/src/zeekygen/utils.cc @@ -132,6 +132,6 @@ bool zeekygen::is_all_whitespace(const string& s) string zeekygen::redef_indication(const string& from_script) { - return fmt("(present if :doc:`/scripts/%s` is loaded)", - from_script.c_str()); + return zeek::util::fmt("(present if :doc:`/scripts/%s` is loaded)", + from_script.c_str()); } diff --git a/src/zeekygen/zeekygen.bif b/src/zeekygen/zeekygen.bif index 1287905418..33ccf80e90 100644 --- a/src/zeekygen/zeekygen.bif +++ b/src/zeekygen/zeekygen.bif @@ -11,7 +11,7 @@ static zeek::StringValPtr comments_to_val(const vector& comments) { - return zeek::make_intrusive(implode_string_vector(comments)); + return zeek::make_intrusive(zeek::util::implode_string_vector(comments)); } %%}