Move everything in util.h to zeek::util namespace.

This commit includes renaming a number of methods prefixed with bro_ to be prefixed with zeek_.
This commit is contained in:
Tim Wojtulewicz 2020-08-06 10:40:24 -07:00
parent 8862b585fa
commit 8d2d867a65
179 changed files with 1277 additions and 1033 deletions

View file

@ -20,7 +20,7 @@ AnonymizeIPAddr* zeek::detail::ip_anonymizer[NUM_ADDR_ANONYMIZATION_METHODS] = {
static uint32_t rand32() 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. // From tcpdpriv.
@ -104,7 +104,7 @@ ipaddr32_t AnonymizeIPAddr_RandomMD5::anonymize(ipaddr32_t input)
uint8_t digest[16]; uint8_t digest[16];
ipaddr32_t output = 0; 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 ) for ( int i = 0; i < 4; ++i )
output = (output << 8) | digest[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))); prefix.prefix = htonl((input & ~(prefix_mask>>i)) | (1<<(31-i)));
// HK(PAD(x_0 ... x_{i-1})). // 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}))). // f_{i-1} = LSB(HK(PAD(x_0 ... x_{i-1}))).
ipaddr32_t bit_mask = (digest[0] & 1) << (31-i); ipaddr32_t bit_mask = (digest[0] & 1) << (31-i);

View file

@ -193,7 +193,7 @@ int Base64Converter::Decode(int len, const char* data, int* pblen, char** pbuf)
else else
{ {
if ( ++errored == 1 ) 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; ++dlen;
@ -210,7 +210,8 @@ int Base64Converter::Done(int* pblen, char** pbuf)
if ( base64_group_next != 0 ) if ( base64_group_next != 0 )
{ {
if ( base64_group_next < 4 ) 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); Decode(4 - base64_group_next, padding, pblen, pbuf);
return -1; return -1;
} }

View file

@ -48,7 +48,7 @@ void CCL::Sort()
unsigned int CCL::MemoryAllocation() const 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 } // namespace zeek::detail

View file

@ -36,7 +36,7 @@ public:
zeek::ListValPtr RecoverVals(const zeek::detail::HashKey* k) const zeek::ListValPtr RecoverVals(const zeek::detail::HashKey* k) const
{ return RecoverVals(*k); } { 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: protected:
std::unique_ptr<zeek::detail::HashKey> ComputeSingletonHash(const zeek::Val* v, bool type_check) const; std::unique_ptr<zeek::detail::HashKey> ComputeSingletonHash(const zeek::Val* v, bool type_check) const;

View file

@ -439,7 +439,7 @@ void Connection::AppendAddl(const char* str)
const char* old = cv->GetField(6)->AsString()->CheckString(); const char* old = cv->GetField(6)->AsString()->CheckString();
const char* format = *old ? "%s %s" : "%s%s"; const char* format = *old ? "%s %s" : "%s%s";
cv->Assign(6, zeek::make_intrusive<zeek::StringVal>(fmt(format, old, str))); cv->Assign(6, zeek::make_intrusive<zeek::StringVal>(zeek::util::fmt(format, old, str)));
} }
// Returns true if the character at s separates a version number. // 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) zeek::Args args)
{ {
// "this" is passed as a cookie for the event // "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) void Connection::Weird(const char* name, const char* addl)

View file

@ -284,9 +284,9 @@ void DFA_State::Stats(unsigned int* computed, unsigned int* uncomputed)
unsigned int DFA_State::Size() unsigned int DFA_State::Size()
{ {
return sizeof(*this) return sizeof(*this)
+ pad_size(sizeof(DFA_State*) * num_sym) + zeek::util::pad_size(sizeof(DFA_State*) * num_sym)
+ (accept ? pad_size(sizeof(int) * accept->size()) : 0) + (accept ? zeek::util::pad_size(sizeof(int) * accept->size()) : 0)
+ (nfa_states ? pad_size(sizeof(NFA_State*) * nfa_states->length()) : 0) + (nfa_states ? zeek::util::pad_size(sizeof(NFA_State*) * nfa_states->length()) : 0)
+ (meta_ec ? meta_ec->Size() : 0); + (meta_ec ? meta_ec->Size() : 0);
} }
@ -373,7 +373,7 @@ void DFA_State_Cache::GetStats(Stats* s)
++s->dfa_states; ++s->dfa_states;
s->nfa_states += e->NFAStateNum(); s->nfa_states += e->NFAStateNum();
e->Stats(&s->computed, &s->uncomputed); 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);
} }
} }

View file

@ -58,7 +58,7 @@ namespace zeek::detail {
class DNS_Mgr_Request { class DNS_Mgr_Request {
public: public:
DNS_Mgr_Request(const char* h, int af, bool is_txt) 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() request_pending()
{ } { }
@ -140,7 +140,7 @@ public:
if ( req_host && num_addrs == 0) if ( req_host && num_addrs == 0)
return false; // nothing to expire 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; } 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) DNS_Mapping::DNS_Mapping(const char* host, struct hostent* h, uint32_t ttl)
{ {
Init(h); Init(h);
req_host = copy_string(host); req_host = zeek::util::copy_string(host);
req_ttl = ttl; req_ttl = ttl;
if ( names && ! names[0] ) 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) 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<bool>(failed_local); failed = static_cast<bool>(failed_local);
if ( is_req_host ) if ( is_req_host )
req_host = copy_string(req_buf); req_host = zeek::util::copy_string(req_buf);
else else
req_addr = zeek::IPAddr(req_buf); req_addr = zeek::IPAddr(req_buf);
num_names = 1; num_names = 1;
names = new char*[num_names]; names = new char*[num_names];
names[0] = copy_string(name_buf); names[0] = zeek::util::copy_string(name_buf);
if ( num_addrs > 0 ) if ( num_addrs > 0 )
{ {
@ -318,7 +318,7 @@ void DNS_Mapping::Init(struct hostent* h)
{ {
no_mapping = false; no_mapping = false;
init_failed = false; init_failed = false;
creation_time = current_time(); creation_time = zeek::util::current_time();
host_val = nullptr; host_val = nullptr;
addrs_val = nullptr; addrs_val = nullptr;
@ -331,7 +331,7 @@ void DNS_Mapping::Init(struct hostent* h)
map_type = h->h_addrtype; map_type = h->h_addrtype;
num_names = 1; // for now, just use official name num_names = 1; // for now, just use official name
names = new char*[num_names]; 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 ) 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 // 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 // configured to the user's desired address at the time when we need to to
// the lookup. // 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(); auto dns_resolver_addr = dns_resolver ? zeek::IPAddr(dns_resolver) : zeek::IPAddr();
char err[NB_DNS_ERRSIZE]; char err[NB_DNS_ERRSIZE];
@ -1204,7 +1204,7 @@ void DNS_Mgr::IssueAsyncRequests()
continue; continue;
} }
req->time = current_time(); req->time = zeek::util::current_time();
asyncs_timeouts.push(req); asyncs_timeouts.push(req);
++asyncs_pending; ++asyncs_pending;
@ -1350,7 +1350,7 @@ void DNS_Mgr::Process()
{ {
AsyncRequest* req = asyncs_timeouts.top(); 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; break;
if ( ! req->processed ) if ( ! req->processed )

View file

@ -62,7 +62,7 @@ public:
zeek::ValPtr LookupAddr(const zeek::IPAddr& addr); zeek::ValPtr LookupAddr(const zeek::IPAddr& addr);
// Define the directory where to store the data. // 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 Verify();
void Resolve(); void Resolve();

View file

@ -119,7 +119,7 @@ FILE* TraceState::SetTraceFile(const char* filename)
{ {
FILE* newfile; FILE* newfile;
if ( streq(filename, "-") ) if ( zeek::util::streq(filename, "-") )
newfile = stderr; newfile = stderr;
else else
newfile = fopen(filename, "w"); newfile = fopen(filename, "w");
@ -179,7 +179,7 @@ int TraceState::LogTrace(const char* fmt, ...)
if ( ! loc.filename ) if ( ! loc.filename )
{ {
loc.filename = copy_string("<no filename>"); loc.filename = zeek::util::copy_string("<no filename>");
loc.last_line = 0; loc.last_line = 0;
} }
@ -377,7 +377,7 @@ vector<ParseLocationRec> parse_location_string(const string& s)
if ( ! sscanf(line_string.c_str(), "%d", &plr.line) ) if ( ! sscanf(line_string.c_str(), "%d", &plr.line) )
plr.type = PLR_UNKNOWN; 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() ) if ( path.empty() )
{ {
@ -555,7 +555,7 @@ int dbg_execute_command(const char* cmd)
if ( ! cmd ) if ( ! cmd )
return 0; return 0;
if ( streq(cmd, "") ) // do the GDB command completion if ( zeek::util::streq(cmd, "") ) // do the GDB command completion
{ {
#ifdef HAVE_READLINE #ifdef HAVE_READLINE
int i; int i;
@ -581,7 +581,7 @@ int dbg_execute_command(const char* cmd)
return 0; return 0;
} }
char* localcmd = copy_string(cmd); char* localcmd = zeek::util::copy_string(cmd);
string opstring; string opstring;
vector<string> arguments; vector<string> arguments;
@ -768,7 +768,7 @@ string get_context_description(const zeek::detail::Stmt* stmt, const zeek::detai
loc = *stmt->GetLocationInfo(); loc = *stmt->GetLocationInfo();
else else
{ {
loc.filename = copy_string("<no filename>"); loc.filename = zeek::util::copy_string("<no filename>");
loc.last_line = 0; loc.last_line = 0;
} }
@ -831,7 +831,7 @@ int dbg_handle_debug_input()
// readline uses malloc, and we want to be consistent // readline uses malloc, and we want to be consistent
// with it. // with it.
input_line = (char*) safe_malloc(1024); input_line = (char*) zeek::util::safe_malloc(1024);
input_line[1023] = 0; input_line[1023] = 0;
// ### Maybe it's not always stdin. // ### Maybe it's not always stdin.
input_line = fgets(input_line, 1023, stdin); input_line = fgets(input_line, 1023, stdin);

View file

@ -37,7 +37,7 @@ static bool string_is_regex(const string& s)
static void lookup_global_symbols_regex(const string& orig_regex, vector<zeek::detail::ID*>& matches, static void lookup_global_symbols_regex(const string& orig_regex, vector<zeek::detail::ID*>& matches,
bool func_only = false) bool func_only = false)
{ {
if ( streq(orig_regex.c_str(), "") ) if ( zeek::util::streq(orig_regex.c_str(), "") )
return; return;
string regex = "^"; string regex = "^";

View file

@ -49,7 +49,7 @@ void DebugLogger::OpenDebugLog(const char* filename)
{ {
if ( filename ) if ( filename )
{ {
filename = log_file_name(filename); filename = zeek::util::log_file_name(filename);
file = fopen(filename, "w"); file = fopen(filename, "w");
if ( ! file ) if ( ! file )
@ -93,7 +93,7 @@ void DebugLogger::ShowStreamsHelp()
void DebugLogger::EnableStreams(const char* s) void DebugLogger::EnableStreams(const char* s)
{ {
char* brkt; char* brkt;
char* tmp = copy_string(s); char* tmp = zeek::util::copy_string(s);
char* tok = strtok(tmp, ","); char* tok = strtok(tmp, ",");
while ( tok ) while ( tok )
@ -159,7 +159,7 @@ void DebugLogger::Log(DebugStream stream, const char* fmt, ...)
return; return;
fprintf(file, "%17.06f/%17.06f [%s] ", 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 ) for ( int i = g->indent; i > 0; --i )
fputs(" ", file); 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, ...) void DebugLogger::Log(const zeek::plugin::Plugin& plugin, const char* fmt, ...)
{ {
std::string tok = std::string("plugin-") + plugin.Name(); std::string tok = std::string("plugin-") + plugin.Name();
tok = strreplace(tok, "::", "-"); tok = zeek::util::strreplace(tok, "::", "-");
if ( enabled_streams.find(tok) == enabled_streams.end() ) if ( enabled_streams.find(tok) == enabled_streams.end() )
return; return;
fprintf(file, "%17.06f/%17.06f [plugin %s] ", 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_list ap;
va_start(ap, fmt); va_start(ap, fmt);

View file

@ -27,7 +27,7 @@ ODesc::ODesc(desc_type t, zeek::File* arg_f)
if ( f == nullptr ) if ( f == nullptr )
{ {
size = DEFAULT_SIZE; size = DEFAULT_SIZE;
base = safe_malloc(size); base = zeek::util::safe_malloc(size);
((char*) base)[0] = '\0'; ((char*) base)[0] = '\0';
offset = 0; offset = 0;
} }
@ -335,7 +335,7 @@ void ODesc::AddBytes(const void* bytes, unsigned int n)
if ( p.first ) if ( p.first )
{ {
AddBytesRaw(s, p.first - s); 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; s = p.first + p.second;
} }
else else
@ -388,7 +388,7 @@ void ODesc::Grow(unsigned int n)
while ( offset + n + SLOP >= size ) while ( offset + n + SLOP >= size )
size *= 2; size *= 2;
base = safe_realloc(base, size); base = zeek::util::safe_realloc(base, size);
} }
void ODesc::Clear() void ODesc::Clear()
@ -400,7 +400,7 @@ void ODesc::Clear()
{ {
free(base); free(base);
size = DEFAULT_SIZE; size = DEFAULT_SIZE;
base = safe_malloc(size); base = zeek::util::safe_malloc(size);
((char*) base)[0] = '\0'; ((char*) base)[0] = '\0';
} }
} }

View file

@ -189,7 +189,7 @@ void EquivClass::Dump(FILE* f)
int EquivClass::Size() const 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 } // namespace zeek::detail

View file

@ -19,7 +19,7 @@ zeek::EventMgr& mgr = zeek::event_mgr;
namespace zeek { namespace zeek {
Event::Event(EventHandlerPtr arg_handler, zeek::Args arg_args, 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), : handler(arg_handler),
args(std::move(arg_args)), args(std::move(arg_args)),
src(arg_src), src(arg_src),
@ -48,7 +48,7 @@ void Event::Describe(ODesc* d) const
void Event::Dispatch(bool no_remote) void Event::Dispatch(bool no_remote)
{ {
if ( src == SOURCE_BROKER ) if ( src == zeek::util::SOURCE_BROKER )
no_remote = true; no_remote = true;
if ( handler->ErrorHandler() ) if ( handler->ErrorHandler() )
@ -75,7 +75,7 @@ void Event::Dispatch(bool no_remote)
EventMgr::EventMgr() EventMgr::EventMgr()
{ {
head = tail = nullptr; head = tail = nullptr;
current_src = SOURCE_LOCAL; current_src = zeek::util::SOURCE_LOCAL;
current_aid = 0; current_aid = 0;
src_val = nullptr; src_val = nullptr;
draining = false; draining = false;
@ -122,7 +122,7 @@ void EventMgr::QueueEvent(const EventHandlerPtr &h, val_list* vl,
} }
void EventMgr::Enqueue(const EventHandlerPtr& h, zeek::Args 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)); 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. // here to the current time since otherwise it won't move forward.
zeek::iosource::PktSrc* pkt_src = zeek::iosource_mgr->GetPktSrc(); zeek::iosource::PktSrc* pkt_src = zeek::iosource_mgr->GetPktSrc();
if ( ! pkt_src || ! pkt_src->IsOpen() || zeek::net::reading_live ) 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(); queue_flare.Extinguish();

View file

@ -19,13 +19,13 @@ namespace zeek {
class Event final : public zeek::Obj { class Event final : public zeek::Obj {
public: public:
Event(EventHandlerPtr handler, zeek::Args args, 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); zeek::Obj* obj = nullptr);
void SetNext(Event* n) { next_event = n; } void SetNext(Event* n) { next_event = n; }
Event* NextEvent() const { return next_event; } 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; } zeek::analyzer::ID Analyzer() const { return aid; }
EventHandlerPtr Handler() const { return handler; } EventHandlerPtr Handler() const { return handler; }
const zeek::Args& Args() const { return args; } const zeek::Args& Args() const { return args; }
@ -41,7 +41,7 @@ protected:
EventHandlerPtr handler; EventHandlerPtr handler;
zeek::Args args; zeek::Args args;
SourceID src; zeek::util::SourceID src;
zeek::analyzer::ID aid; zeek::analyzer::ID aid;
zeek::Obj* obj; zeek::Obj* obj;
Event* next_event; Event* next_event;
@ -62,7 +62,7 @@ public:
// arguments when there's no handlers to consume them). // arguments when there's no handlers to consume them).
[[deprecated("Remove in v4.1. Use Enqueue() instead.")]] [[deprecated("Remove in v4.1. Use Enqueue() instead.")]]
void QueueEventFast(const EventHandlerPtr &h, val_list vl, 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); zeek::detail::TimerMgr* mgr = nullptr, zeek::Obj* obj = nullptr);
// Queues an event if there's an event handler (or remote consumer). This // Queues an event if there's an event handler (or remote consumer). This
@ -73,7 +73,7 @@ public:
// existence check. // existence check.
[[deprecated("Remove in v4.1. Use Enqueue() instead.")]] [[deprecated("Remove in v4.1. Use Enqueue() instead.")]]
void QueueEvent(const EventHandlerPtr &h, val_list vl, 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); zeek::detail::TimerMgr* mgr = nullptr, zeek::Obj* obj = nullptr);
// Same as QueueEvent, except taking the event's argument list via a // Same as QueueEvent, except taking the event's argument list via a
@ -82,7 +82,7 @@ public:
// each of its elements. // each of its elements.
[[deprecated("Remove in v4.1. Use Enqueue() instead.")]] [[deprecated("Remove in v4.1. Use Enqueue() instead.")]]
void QueueEvent(const EventHandlerPtr &h, val_list* vl, 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); zeek::detail::TimerMgr* mgr = nullptr, zeek::Obj* obj = nullptr);
/** /**
@ -98,7 +98,7 @@ public:
* reference to until dispatching the event. * reference to until dispatching the event.
*/ */
void Enqueue(const EventHandlerPtr& h, zeek::Args vl, 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); zeek::Obj* obj = nullptr);
/** /**
@ -119,7 +119,7 @@ public:
bool HasEvents() const { return head != nullptr; } bool HasEvents() const { return head != nullptr; }
// Returns the source ID of last raised event. // 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 // Returns the ID of the analyzer which raised the last event, or 0 if
// non-analyzer event. // non-analyzer event.
@ -143,7 +143,7 @@ protected:
Event* head; Event* head;
Event* tail; Event* tail;
SourceID current_src; zeek::util::SourceID current_src;
zeek::analyzer::ID current_aid; zeek::analyzer::ID current_aid;
zeek::RecordVal* src_val; zeek::RecordVal* src_val;
bool draining; bool draining;

View file

@ -1265,7 +1265,7 @@ AddToExpr::AddToExpr(ExprPtr arg_op1, ExprPtr arg_op2)
} }
else if ( bt1 != bt2 && bt1 != zeek::TYPE_ANY ) else if ( bt1 != bt2 && bt1 != zeek::TYPE_ANY )
ExprError(fmt("incompatible vector append: %s and %s", ExprError(zeek::util::fmt("incompatible vector append: %s and %s",
type_name(bt1), type_name(bt2))); type_name(bt1), type_name(bt2)));
else else
@ -1487,12 +1487,12 @@ ValPtr DivideExpr::AddrFold(Val* v1, Val* v2) const
if ( a.GetFamily() == IPv4 ) if ( a.GetFamily() == IPv4 )
{ {
if ( mask > 32 ) if ( mask > 32 )
RuntimeError(fmt("bad IPv4 subnet prefix length: %" PRIu32, mask)); RuntimeError(zeek::util::fmt("bad IPv4 subnet prefix length: %" PRIu32, mask));
} }
else else
{ {
if ( mask > 128 ) 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<zeek::SubNetVal>(a, mask); return zeek::make_intrusive<zeek::SubNetVal>(a, mask);
@ -2249,7 +2249,7 @@ bool AssignExpr::TypeCheckArithmetics(TypeTag bt1, TypeTag bt2)
{ {
if ( ! IsArithmetic(bt2) ) if ( ! IsArithmetic(bt2) )
{ {
ExprError(fmt("assignment of non-arithmetic value to arithmetic (%s/%s)", ExprError(zeek::util::fmt("assignment of non-arithmetic value to arithmetic (%s/%s)",
type_name(bt1), type_name(bt2))); type_name(bt1), type_name(bt2)));
return false; return false;
} }
@ -2459,7 +2459,7 @@ bool AssignExpr::IsRecordElement(TypeDecl* td) const
{ {
const NameExpr* n = (const NameExpr*) op1.get(); const NameExpr* n = (const NameExpr*) op1.get();
td->type = op2->GetType(); td->type = op2->GetType();
td->id = copy_string(n->Id()->Name()); td->id = zeek::util::copy_string(n->Id()->Name());
} }
return true; return true;
@ -2519,7 +2519,7 @@ IndexExpr::IndexExpr(ExprPtr arg_op1, ListExprPtr arg_op2, bool arg_is_slice)
if ( match_type == DOES_NOT_MATCH_INDEX ) if ( match_type == DOES_NOT_MATCH_INDEX )
{ {
std::string error_msg = std::string error_msg =
fmt("expression with type '%s' is not a type that can be indexed", zeek::util::fmt("expression with type '%s' is not a type that can be indexed",
type_name(op1->GetType()->Tag())); type_name(op1->GetType()->Tag()));
SetError(error_msg.data()); SetError(error_msg.data());
} }
@ -2806,7 +2806,7 @@ void IndexExpr::Assign(Frame* f, ValPtr v)
const auto& vt = v->GetType(); const auto& vt = v->GetType();
auto vtt = vt->Tag(); auto vtt = vt->Tag();
std::string tn = vtt == zeek::TYPE_RECORD ? vt->GetName() : type_name(vtt); 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", "vector index assignment failed for invalid type '%s', value: %s",
tn.data(), d.Description())); tn.data(), d.Description()));
} }
@ -2828,7 +2828,7 @@ void IndexExpr::Assign(Frame* f, ValPtr v)
const auto& vt = v->GetType(); const auto& vt = v->GetType();
auto vtt = vt->Tag(); auto vtt = vt->Tag();
std::string tn = vtt == zeek::TYPE_RECORD ? vt->GetName() : type_name(vtt); 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", "table index assignment failed for invalid type '%s', value: %s",
tn.data(), d.Description())); tn.data(), d.Description()));
} }
@ -2875,7 +2875,7 @@ TraversalCode IndexExpr::Traverse(TraversalCallback* cb) const
FieldExpr::FieldExpr(ExprPtr arg_op, const char* arg_field_name) FieldExpr::FieldExpr(ExprPtr arg_op, const char* arg_field_name)
: UnaryExpr(EXPR_FIELD, std::move(arg_op)), : 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() ) if ( IsError() )
return; return;
@ -3036,7 +3036,7 @@ RecordConstructorExpr::RecordConstructorExpr(ListExprPtr constructor_list)
FieldAssignExpr* field = (FieldAssignExpr*) e; FieldAssignExpr* field = (FieldAssignExpr*) e;
const auto& field_type = field->GetType(); 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)); 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) ) 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; return nullptr;
} }
} }
@ -3387,7 +3387,7 @@ ValPtr VectorConstructorExpr::Eval(Frame* f) const
if ( ! vec->Assign(i, e->Eval(f)) ) 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; return nullptr;
} }
} }
@ -3413,7 +3413,7 @@ ValPtr VectorConstructorExpr::InitVal(const zeek::Type* t, ValPtr aggr) const
if ( ! v || ! vec->Assign(i, std::move(v)) ) 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; return nullptr;
} }
} }
@ -3460,7 +3460,7 @@ bool FieldAssignExpr::IsRecordElement(TypeDecl* td) const
if ( td ) if ( td )
{ {
td->type = op->GetType(); td->type = op->GetType();
td->id = copy_string(field_name.c_str()); td->id = zeek::util::copy_string(field_name.c_str());
} }
return true; return true;
@ -3584,7 +3584,7 @@ RecordCoerceExpr::RecordCoerceExpr(ExprPtr arg_op, zeek::RecordTypePtr r)
int t_i = t_r->FieldOffset(sub_r->FieldName(i)); int t_i = t_r->FieldOffset(sub_r->FieldName(i));
if ( t_i < 0 ) if ( t_i < 0 )
{ {
ExprError(fmt("orphaned field \"%s\" in record coercion", ExprError(zeek::util::fmt("orphaned field \"%s\" in record coercion",
sub_r->FieldName(i))); sub_r->FieldName(i)));
break; 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()) && if ( ! is_arithmetic_promotable(sup_t_i.get(), sub_t_i.get()) &&
! is_record_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)); "type clash for field \"%s\"", sub_r->FieldName(i));
Error(error_msg.c_str(), sub_t_i.get()); Error(error_msg.c_str(), sub_t_i.get());
SetError(); SetError();
@ -3646,7 +3646,7 @@ RecordCoerceExpr::RecordCoerceExpr(ExprPtr arg_op, zeek::RecordTypePtr r)
{ {
if ( ! t_r->FieldDecl(i)->GetAttr(ATTR_OPTIONAL) ) 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)); "non-optional field \"%s\" missing", t_r->FieldName(i));
Error(error_msg.c_str()); Error(error_msg.c_str());
SetError(); SetError();
@ -4010,7 +4010,7 @@ ValPtr InExpr::Fold(Val* v1, Val* v2) const
// Could do better here e.g. Boyer-Moore if done repeatedly. // Could do better here e.g. Boyer-Moore if done repeatedly.
auto s = reinterpret_cast<const unsigned char*>(s1->CheckString()); auto s = reinterpret_cast<const unsigned char*>(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); 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 // run-time errors when we apply this analysis during
// parsing. Really we should instead do it after we've // parsing. Really we should instead do it after we've
// parsed the entire set of scripts. // 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 // The following is needed because fmt might not yet
// be bound as a name. // be bound as a name.
did_builtin_init && did_builtin_init &&
@ -4594,7 +4594,7 @@ ValPtr ListExpr::InitVal(const zeek::Type* t, ValPtr aggr) const
if ( ! vec->Assign(i, e->Eval(nullptr)) ) 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; return nullptr;
} }
} }

View file

@ -68,8 +68,8 @@ File::File(FILE* arg_f, const char* arg_name, const char* arg_access)
{ {
Init(); Init();
f = arg_f; f = arg_f;
name = copy_string(arg_name); name = zeek::util::copy_string(arg_name);
access = copy_string(arg_access); access = zeek::util::copy_string(arg_access);
t = zeek::base_type(zeek::TYPE_STRING); t = zeek::base_type(zeek::TYPE_STRING);
is_open = (f != nullptr); is_open = (f != nullptr);
} }
@ -78,15 +78,15 @@ File::File(const char* arg_name, const char* arg_access)
{ {
Init(); Init();
f = nullptr; f = nullptr;
name = copy_string(arg_name); name = zeek::util::copy_string(arg_name);
access = copy_string(arg_access); access = zeek::util::copy_string(arg_access);
t = zeek::base_type(zeek::TYPE_STRING); t = zeek::base_type(zeek::TYPE_STRING);
if ( streq(name, "/dev/stdin") ) if ( zeek::util::streq(name, "/dev/stdin") )
f = stdin; f = stdin;
else if ( streq(name, "/dev/stdout") ) else if ( zeek::util::streq(name, "/dev/stdout") )
f = stdout; f = stdout;
else if ( streq(name, "/dev/stderr") ) else if ( zeek::util::streq(name, "/dev/stderr") )
f = stderr; f = stderr;
if ( f ) if ( f )
@ -119,7 +119,7 @@ const char* File::Name() const
bool File::Open(FILE* file, const char* mode) bool File::Open(FILE* file, const char* mode)
{ {
static bool fds_maximized = false; 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 ) if ( ! fds_maximized )
{ {
@ -282,7 +282,7 @@ zeek::RecordVal* File::Rotate()
static auto rotate_info = zeek::id::find_type<zeek::RecordType>("rotate_info"); static auto rotate_info = zeek::id::find_type<zeek::RecordType>("rotate_info");
auto* info = new zeek::RecordVal(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 ) if ( ! newf )
{ {

View file

@ -19,7 +19,7 @@ Flare::Flare()
abort(); abort();
char buf[256]; char buf[256];
bro_strerror_r(errno, buf, sizeof(buf)); zeek::util::zeek_strerror_r(errno, buf, sizeof(buf));
if ( zeek::reporter ) if ( zeek::reporter )
zeek::reporter->FatalErrorWithCore("unexpected pipe %s failure: %s", which, buf); zeek::reporter->FatalErrorWithCore("unexpected pipe %s failure: %s", which, buf);

View file

@ -108,12 +108,12 @@ std::string render_call_stack()
arg_desc += d.Description(); 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 ) if ( ci.call )
{ {
auto loc = ci.call->GetLocationInfo(); 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; ++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]; const zeek::detail::Expr* fmt_str_arg = args[0];
if ( fmt_str_arg->GetType()->Tag() != zeek::TYPE_STRING ) 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; return false;
} }
@ -729,7 +729,7 @@ bool check_built_in_call(BuiltinFunc* f, zeek::detail::CallExpr* call)
if ( args.length() != num_fmt + 1 ) 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; return false;
} }
} }

View file

@ -199,7 +199,7 @@ private:
inline static uint8_t shared_hmac_md5_key[16]; inline static uint8_t shared_hmac_md5_key[16];
inline static bool seeds_initialized = false; 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*); friend BifReturnVal zeek::BifFunc::md5_hmac_bif(zeek::detail::Frame* frame, const zeek::Args*);
}; };
@ -258,7 +258,7 @@ public:
int Size() const { return size; } int Size() const { return size; }
hash_t Hash() const { return hash; } 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); static hash_t HashBytes(const void* bytes, int size);
protected: protected:

View file

@ -107,7 +107,7 @@ namespace zeek::detail {
ID::ID(const char* arg_name, IDScope arg_scope, bool arg_is_export) 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; scope = arg_scope;
is_export = arg_is_export; is_export = arg_is_export;
is_option = false; is_option = false;
@ -309,9 +309,9 @@ std::string ID::GetDeprecationWarning() const
result = depr_attr->DeprecationMessage(); result = depr_attr->DeprecationMessage();
if ( result.empty() ) if ( result.empty() )
return fmt("deprecated (%s)", Name()); return zeek::util::fmt("deprecated (%s)", Name());
else 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) void ID::AddAttrs(AttributesPtr a)
@ -614,10 +614,10 @@ void ID::DescribeReST(ODesc* d, bool roles_only) const
ODesc expr_desc; ODesc expr_desc;
ir->init_expr->Describe(&expr_desc); ir->init_expr->Describe(&expr_desc);
redef_str = expr_desc.Description(); redef_str = expr_desc.Description();
redef_str = strreplace(redef_str, "\n", " "); redef_str = zeek::util::strreplace(redef_str, "\n", " ");
d->Add(":Redefinition: "); 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->NL();
d->PushIndent(); d->PushIndent();

View file

@ -284,7 +284,7 @@ zeek::RecordValPtr IPv6_Hdr::ToVal(zeek::VectorValPtr chain) const
} }
default: 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; break;
} }
@ -632,7 +632,7 @@ void IPv6_Hdr_Chain::ProcessRoutingHeader(const struct ip6_rthdr* r, uint16_t le
default: default:
zeek::reporter->Weird(SrcAddr(), DstAddr(), "unknown_routing_type", zeek::reporter->Weird(SrcAddr(), DstAddr(), "unknown_routing_type",
fmt("%d", r->ip6r_type)); zeek::util::fmt("%d", r->ip6r_type));
break; break;
} }
} }

View file

@ -51,7 +51,7 @@ public:
max_entries = size; 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) List(const List& b)
@ -60,7 +60,7 @@ public:
num_entries = b.num_entries; num_entries = b.num_entries;
if ( max_entries ) if ( max_entries )
entries = (T*) safe_malloc(max_entries * sizeof(T)); entries = (T*) zeek::util::safe_malloc(max_entries * sizeof(T));
else else
entries = nullptr; entries = nullptr;
@ -81,7 +81,7 @@ public:
List(const T* arr, int n) List(const T* arr, int n)
{ {
num_entries = max_entries = 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)); memcpy(entries, arr, n * sizeof(T));
} }
@ -98,7 +98,7 @@ public:
num_entries = b.num_entries; num_entries = b.num_entries;
if ( max_entries ) if ( max_entries )
entries = (T *) safe_malloc(max_entries * sizeof(T)); entries = (T *) zeek::util::safe_malloc(max_entries * sizeof(T));
else else
entries = nullptr; entries = nullptr;
@ -148,7 +148,7 @@ public:
if ( new_size != max_entries ) 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 ) if ( entries )
max_entries = new_size; max_entries = new_size;
else else
@ -159,7 +159,7 @@ public:
} }
int MemoryAllocation() const 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) void push_front(const T& a)
{ {

View file

@ -80,7 +80,7 @@ RETSIGTYPE watchdog(int /* signo */)
// handler and the allocation routines are not // handler and the allocation routines are not
// reentrant. // reentrant.
double ct = current_time(); double ct = zeek::util::current_time();
int int_ct = int(ct); int int_ct = int(ct);
int frac_ct = int((ct - int_ct) * 1e6); 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 ) if ( load_freq == 0 )
load_freq = uint32_t(0xffffffff) / uint32_t(load_sample_freq); 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 // Drain the queued timer events so they're not
// charged against this sample. // charged against this sample.
@ -263,7 +263,7 @@ void net_packet_dispatch(double t, const zeek::Packet* pkt, zeek::iosource::PktS
void net_run() void net_run()
{ {
set_processing_status("RUNNING", "net_run"); zeek::util::set_processing_status("RUNNING", "net_run");
std::vector<zeek::iosource::IOSource*> ready; std::vector<zeek::iosource::IOSource*> ready;
ready.reserve(zeek::iosource_mgr->TotalSize()); ready.reserve(zeek::iosource_mgr->TotalSize());
@ -281,7 +281,7 @@ void net_run()
if ( ! ready.empty() || loop_counter++ % 100 == 0 ) if ( ! ready.empty() || loop_counter++ % 100 == 0 )
{ {
DBG_LOG(zeek::DBG_MAINLOOP, "realtime=%.6f ready_count=%zu", DBG_LOG(zeek::DBG_MAINLOOP, "realtime=%.6f ready_count=%zu",
current_time(), ready.size()); zeek::util::current_time(), ready.size());
if ( ! ready.empty() ) if ( ! ready.empty() )
loop_counter = 0; loop_counter = 0;
@ -307,7 +307,7 @@ void net_run()
// date on timers and events. Because we only // date on timers and events. Because we only
// have timers as sources, going to sleep here // have timers as sources, going to sleep here
// doesn't risk blocking on other inputs. // doesn't risk blocking on other inputs.
net_update_time(current_time()); net_update_time(zeek::util::current_time());
expire_timers(); expire_timers();
} }
@ -364,7 +364,7 @@ void net_get_final_stats()
void net_finish(int drain_events) void net_finish(int drain_events)
{ {
set_processing_status("TERMINATING", "net_finish"); zeek::util::set_processing_status("TERMINATING", "net_finish");
if ( drain_events ) if ( drain_events )
{ {
@ -389,7 +389,7 @@ void net_finish(int drain_events)
void net_delete() void net_delete()
{ {
set_processing_status("TERMINATING", "net_delete"); zeek::util::set_processing_status("TERMINATING", "net_delete");
delete zeek::sessions; delete zeek::sessions;

View file

@ -45,7 +45,7 @@ void Location::Describe(zeek::ODesc* d) const
bool Location::operator==(const Location& l) const bool Location::operator==(const Location& l) const
{ {
if ( filename == l.filename || 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; return first_line == l.first_line && last_line == l.last_line;
else else
return false; return false;
@ -137,7 +137,7 @@ bool Obj::SetLocationInfo(const detail::Location* start, const detail::Location*
if ( ! start || ! end ) if ( ! start || ! end )
return false; return false;
if ( end->filename && ! streq(start->filename, end->filename) ) if ( end->filename && ! zeek::util::streq(start->filename, end->filename) )
return false; return false;
if ( location && (start == &zeek::detail::no_location || end == &zeek::detail::no_location) ) if ( location && (start == &zeek::detail::no_location || end == &zeek::detail::no_location) )

View file

@ -66,7 +66,7 @@ void zeek::Options::filter_supervised_node_options()
bool zeek::fake_dns() bool zeek::fake_dns()
{ {
return zeekenv("ZEEK_DNS_FAKE"); return zeek::util::zeekenv("ZEEK_DNS_FAKE");
} }
extern const char* zeek_version(); extern const char* zeek_version();
@ -121,16 +121,16 @@ void zeek::usage(const char* prog, int code)
#endif #endif
fprintf(stderr, " --test | run unit tests ('--test -h' for help, only when compiling with ENABLE_ZEEK_UNIT_TESTS)\n"); 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, " $ZEEKPATH | file search path (%s)\n", zeek::util::zeek_path().c_str());
fprintf(stderr, " $ZEEK_PLUGIN_PATH | plugin search path (%s)\n", bro_plugin_path()); 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", bro_plugin_activate()); fprintf(stderr, " $ZEEK_PLUGIN_ACTIVATE | plugins to always activate (%s)\n", zeek::util::zeek_plugin_activate());
fprintf(stderr, " $ZEEK_PREFIXES | prefix list (%s)\n", bro_prefixes().c_str()); 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_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_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_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_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_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", zeekenv("ZEEK_DNS_RESOLVER") ? zeekenv("ZEEK_DNS_RESOLVER") : "not set, will use first IPv4 address from /etc/resolv.conf"); 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, " $ZEEK_DEBUG_LOG_STDERR | Use stderr for debug logs generated via the -B flag");
fprintf(stderr, "\n"); fprintf(stderr, "\n");
@ -236,7 +236,7 @@ zeek::Options zeek::parse_cmdline(int argc, char** argv)
}; };
char opts[256]; char opts[256];
safe_strncpy(opts, "B:e:f:G:H:I:i:j::n:p:r:s:T:t:U:w:X:CDFNPQSWabdhv", 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)); sizeof(opts));
#ifdef USE_PERFTOOLS_DEBUG #ifdef USE_PERFTOOLS_DEBUG
@ -431,7 +431,7 @@ zeek::Options zeek::parse_cmdline(int argc, char** argv)
if ( path->empty() ) if ( path->empty() )
return; return;
*path = normalize_path(*path); *path = zeek::util::normalize_path(*path);
if ( (*path)[0] == '/' || (*path)[0] == '~' ) if ( (*path)[0] == '/' || (*path)[0] == '~' )
// Absolute path // Absolute path
@ -440,7 +440,7 @@ zeek::Options zeek::parse_cmdline(int argc, char** argv)
if ( (*path)[0] != '.' ) if ( (*path)[0] != '.' )
{ {
// Look up file in ZEEKPATH // 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() ) if ( res.empty() )
{ {

View file

@ -33,7 +33,7 @@ void PacketDumper::DumpPacket(const struct pcap_pkthdr* hdr,
void PacketDumper::SortTimeStamp(struct timeval* timestamp) 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; *timestamp = last_timestamp;
else else
last_timestamp = *timestamp; last_timestamp = *timestamp;

View file

@ -20,7 +20,7 @@ void PacketFilter::AddSrc(const zeek::IPAddr& src, uint32_t tcp_flags, double pr
{ {
Filter* f = new Filter; Filter* f = new Filter;
f->tcp_flags = tcp_flags; f->tcp_flags = tcp_flags;
f->probability = probability * static_cast<double>(zeek::max_random()); f->probability = probability * static_cast<double>(zeek::util::max_random());
auto prev = static_cast<Filter*>(src_filter.Insert(src, 128, f)); auto prev = static_cast<Filter*>(src_filter.Insert(src, 128, f));
delete prev; delete prev;
} }
@ -29,7 +29,7 @@ void PacketFilter::AddSrc(zeek::Val* src, uint32_t tcp_flags, double probability
{ {
Filter* f = new Filter; Filter* f = new Filter;
f->tcp_flags = tcp_flags; f->tcp_flags = tcp_flags;
f->probability = probability * static_cast<double>(zeek::max_random()); f->probability = probability * static_cast<double>(zeek::util::max_random());
auto prev = static_cast<Filter*>(src_filter.Insert(src, f)); auto prev = static_cast<Filter*>(src_filter.Insert(src, f));
delete prev; delete prev;
} }
@ -38,7 +38,7 @@ void PacketFilter::AddDst(const zeek::IPAddr& dst, uint32_t tcp_flags, double pr
{ {
Filter* f = new Filter; Filter* f = new Filter;
f->tcp_flags = tcp_flags; f->tcp_flags = tcp_flags;
f->probability = probability * static_cast<double>(zeek::max_random()); f->probability = probability * static_cast<double>(zeek::util::max_random());
auto prev = static_cast<Filter*>(dst_filter.Insert(dst, 128, f)); auto prev = static_cast<Filter*>(dst_filter.Insert(dst, 128, f));
delete prev; delete prev;
} }
@ -47,7 +47,7 @@ void PacketFilter::AddDst(zeek::Val* dst, uint32_t tcp_flags, double probability
{ {
Filter* f = new Filter; Filter* f = new Filter;
f->tcp_flags = tcp_flags; f->tcp_flags = tcp_flags;
f->probability = probability * static_cast<double>(zeek::max_random()); f->probability = probability * static_cast<double>(zeek::util::max_random());
auto prev = static_cast<Filter*>(dst_filter.Insert(dst, f)); auto prev = static_cast<Filter*>(dst_filter.Insert(dst, f));
delete prev; delete prev;
} }
@ -115,7 +115,7 @@ bool PacketFilter::MatchFilter(const Filter& f, const zeek::IP_Hdr& ip,
return false; return false;
} }
return zeek::random_number() < f.probability; return zeek::util::random_number() < f.probability;
} }
} // namespace zeek::detail } // namespace zeek::detail

View file

@ -12,7 +12,7 @@ using namespace zeek::detail;
static void pipe_fail(int eno) static void pipe_fail(int eno)
{ {
char tmp[256]; char tmp[256];
bro_strerror_r(eno, tmp, sizeof(tmp)); zeek::util::zeek_strerror_r(eno, tmp, sizeof(tmp));
if ( zeek::reporter ) if ( zeek::reporter )
zeek::reporter->FatalError("Pipe failure: %s", tmp); zeek::reporter->FatalError("Pipe failure: %s", tmp);

View file

@ -84,7 +84,7 @@ bool LoadPolicyFileText(const char* policy_filename)
if ( fstat(fileno(f), &st) != 0 ) if ( fstat(fileno(f), &st) != 0 )
{ {
char buf[256]; 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); zeek::reporter->Error("fstat failed on %s: %s", policy_filename, buf);
fclose(f); fclose(f);
return false; return false;

View file

@ -6,7 +6,7 @@ namespace zeek::detail {
prefix_t* PrefixTable::MakePrefix(const zeek::IPAddr& addr, int width) 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); addr.CopyIPv6(&prefix->add.sin6);
prefix->family = AF_INET6; prefix->family = AF_INET6;

View file

@ -423,21 +423,21 @@ unsigned int Specific_RE_Matcher::MemoryAllocation() const
for ( int i = 0; i < ccl_list.length(); ++i ) for ( int i = 0; i < ccl_list.length(); ++i )
size += ccl_list[i]->MemoryAllocation(); 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 ) 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(); size += entry.second->MemoryAllocation();
} }
for ( const auto& entry : defs ) 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) + zeek::util::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.second.size());
} }
return size + padded_sizeof(*this) 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) + ccl_list.MemoryAllocation() - padded_sizeof(ccl_list)
+ equiv_class.Size() - padded_sizeof(EquivClass) + equiv_class.Size() - padded_sizeof(EquivClass)
+ (dfa ? dfa->MemoryAllocation() : 0) // this is ref counted; consider the bytes here? + (dfa ? dfa->MemoryAllocation() : 0) // this is ref counted; consider the bytes here?

View file

@ -59,7 +59,7 @@ public:
void MakeCaseInsensitive(); 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); bool Compile(bool lazy = false);

View file

@ -126,7 +126,7 @@ void Reporter::FatalError(const char* fmt, ...)
va_end(ap); va_end(ap);
set_processing_status("TERMINATED", "fatal_error"); zeek::util::set_processing_status("TERMINATED", "fatal_error");
fflush(stderr); fflush(stderr);
fflush(stdout); fflush(stdout);
_exit(1); _exit(1);
@ -142,7 +142,7 @@ void Reporter::FatalErrorWithCore(const char* fmt, ...)
va_end(ap); va_end(ap);
set_processing_status("TERMINATED", "fatal_error"); zeek::util::set_processing_status("TERMINATED", "fatal_error");
abort(); abort();
} }
@ -195,7 +195,7 @@ void Reporter::InternalError(const char* fmt, ...)
va_end(ap); va_end(ap);
set_processing_status("TERMINATED", "internal_error"); zeek::util::set_processing_status("TERMINATED", "internal_error");
abort(); abort();
} }
@ -562,7 +562,8 @@ void Reporter::DoLog(const char* prefix, EventHandlerPtr event, FILE* out,
vl.reserve(vl_size); vl.reserve(vl_size);
if ( time ) if ( time )
vl.emplace_back(zeek::make_intrusive<zeek::TimeVal>(zeek::net::network_time ? zeek::net::network_time : current_time())); vl.emplace_back(zeek::make_intrusive<zeek::TimeVal>(
zeek::net::network_time ? zeek::net::network_time : zeek::util::current_time()));
vl.emplace_back(zeek::make_intrusive<zeek::StringVal>(buffer)); vl.emplace_back(zeek::make_intrusive<zeek::StringVal>(buffer));

View file

@ -75,7 +75,7 @@ void Rule::AddPattern(const char* str, Rule::PatternType type,
uint32_t offset, uint32_t depth) uint32_t offset, uint32_t depth)
{ {
Pattern* p = new Pattern; Pattern* p = new Pattern;
p->pattern = copy_string(str); p->pattern = zeek::util::copy_string(str);
p->type = type; p->type = type;
p->id = ++pattern_counter; p->id = ++pattern_counter;
p->offset = offset; 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) void Rule::AddRequires(const char* id, bool opposite_direction, bool negate)
{ {
Precond* p = new Precond; Precond* p = new Precond;
p->id = copy_string(id); p->id = zeek::util::copy_string(id);
p->rule = nullptr; p->rule = nullptr;
p->opposite_dir = opposite_direction; p->opposite_dir = opposite_direction;
p->negate = negate; p->negate = negate;

View file

@ -24,7 +24,7 @@ class Rule {
public: public:
Rule(const char* arg_id, const zeek::detail::Location& arg_location) 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++; idx = rule_counter++;
location = arg_location; location = arg_location;
active = true; active = true;

View file

@ -16,7 +16,7 @@ namespace zeek::detail {
RuleActionEvent::RuleActionEvent(const char* arg_msg) 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, void RuleActionEvent::DoAction(const Rule* parent, RuleEndpointState* state,
@ -38,7 +38,7 @@ void RuleActionEvent::PrintDebug()
RuleActionMIME::RuleActionMIME(const char* arg_mime, int arg_strength) RuleActionMIME::RuleActionMIME(const char* arg_mime, int arg_strength)
{ {
mime = copy_string(arg_mime); mime = zeek::util::copy_string(arg_mime);
strength = arg_strength; strength = arg_strength;
} }

View file

@ -113,7 +113,7 @@ RuleHdrTest::RuleHdrTest(RuleHdrTest& h)
copied_set->re = nullptr; copied_set->re = nullptr;
copied_set->ids = orig_set->ids; copied_set->ids = orig_set->ids;
for ( const auto& pattern : orig_set->patterns ) 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; delete copied_set;
// TODO: Why do we create copied_set only to then // TODO: Why do we create copied_set only to then
// never use it? // never use it?
@ -261,7 +261,7 @@ bool RuleMatcher::ReadFiles(const std::vector<std::string>& files)
for ( const auto& f : 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 ) if ( ! rules_in )
{ {
@ -673,7 +673,7 @@ RuleMatcher::MIME_Matches* RuleMatcher::Match(RuleFileMagicState* state,
#ifdef DEBUG #ifdef DEBUG
if ( debug_logger.IsEnabled(zeek::DBG_RULES) ) if ( debug_logger.IsEnabled(zeek::DBG_RULES) )
{ {
const char* s = fmt_bytes(reinterpret_cast<const char*>(data), const char* s = zeek::util::fmt_bytes(reinterpret_cast<const char*>(data),
min(40, static_cast<int>(len))); min(40, static_cast<int>(len)));
DBG_LOG(zeek::DBG_RULES, "Matching %s rules on |%s%s|", DBG_LOG(zeek::DBG_RULES, "Matching %s rules on |%s%s|",
Rule::TypeToString(Rule::FILE_MAGIC), s, Rule::TypeToString(Rule::FILE_MAGIC), s,
@ -871,7 +871,7 @@ void RuleMatcher::Match(RuleEndpointState* state, Rule::PatternType type,
if ( debug_logger.IsEnabled(zeek::DBG_RULES) ) if ( debug_logger.IsEnabled(zeek::DBG_RULES) )
{ {
const char* s = 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|", DBG_LOG(zeek::DBG_RULES, "Matching %s rules [%d,%d] on |%s%s|",
Rule::TypeToString(type), bol, eol, s, Rule::TypeToString(type), bol, eol, s,
@ -1234,11 +1234,11 @@ void RuleMatcher::DumpStats(zeek::File* f)
Stats stats; Stats stats;
GetStats(&stats); GetStats(&stats);
f->Write(fmt("%.6f computed dfa states = %d; classes = ??; " f->Write(zeek::util::fmt("%.6f computed dfa states = %d; classes = ??; "
"computed trans. = %d; matchers = %d; mem = %d\n", "computed trans. = %d; matchers = %d; mem = %d\n",
zeek::net::network_time, stats.dfa_states, stats.computed, zeek::net::network_time, stats.dfa_states, stats.computed,
stats.matchers, stats.mem)); stats.matchers, stats.mem));
f->Write(fmt("%.6f DFA cache hits = %d; misses = %d\n", zeek::net::network_time, f->Write(zeek::util::fmt("%.6f DFA cache hits = %d; misses = %d\n", zeek::net::network_time,
stats.hits, stats.misses)); stats.hits, stats.misses));
DumpStateStats(f, root); DumpStateStats(f, root);
@ -1256,14 +1256,14 @@ void RuleMatcher::DumpStateStats(zeek::File* f, RuleHdrTest* hdr_test)
RuleHdrTest::PatternSet* set = hdr_test->psets[i][j]; RuleHdrTest::PatternSet* set = hdr_test->psets[i][j];
assert(set->re); assert(set->re);
f->Write(fmt("%.6f %d DFA states in %s group %d from sigs ", zeek::net::network_time, f->Write(zeek::util::fmt("%.6f %d DFA states in %s group %d from sigs ", zeek::net::network_time,
set->re->DFA()->NumStates(), set->re->DFA()->NumStates(),
Rule::TypeToString((Rule::PatternType)i), j)); Rule::TypeToString((Rule::PatternType)i), j));
for ( const auto& id : set->ids ) for ( const auto& id : set->ids )
{ {
Rule* r = Rule::rule_table[id - 1]; Rule* r = Rule::rule_table[id - 1];
f->Write(fmt("%s ", r->ID())); f->Write(zeek::util::fmt("%s ", r->ID()));
} }
f->Write("\n"); f->Write("\n");
@ -1399,7 +1399,7 @@ char* id_to_str(const char* id)
return dst; return dst;
error: error:
char* dummy = copy_string("<error>"); char* dummy = zeek::util::copy_string("<error>");
return dummy; return dummy;
} }

View file

@ -39,7 +39,7 @@ void ScriptCoverageManager::AddStmt(zeek::detail::Stmt* s)
bool ScriptCoverageManager::ReadStats() bool ScriptCoverageManager::ReadStats()
{ {
char* bf = zeekenv("ZEEK_PROFILER_FILE"); char* bf = zeek::util::zeekenv("ZEEK_PROFILER_FILE");
if ( ! bf ) if ( ! bf )
return false; return false;
@ -56,7 +56,7 @@ bool ScriptCoverageManager::ReadStats()
ss.clear(); ss.clear();
std::vector<std::string> lines; std::vector<std::string> lines;
tokenize_string(file_contents, "\n", &lines); zeek::util::tokenize_string(file_contents, "\n", &lines);
string delimiter; string delimiter;
delimiter = delim; delimiter = delim;
@ -66,7 +66,7 @@ bool ScriptCoverageManager::ReadStats()
continue; continue;
std::vector<std::string> line_components; std::vector<std::string> line_components;
tokenize_string(line, delimiter, &line_components); zeek::util::tokenize_string(line, delimiter, &line_components);
if ( line_components.size() != 3 ) if ( line_components.size() != 3 )
{ {
@ -80,7 +80,7 @@ bool ScriptCoverageManager::ReadStats()
pair<string, string> location_desc(std::move(location), std::move(desc)); pair<string, string> location_desc(std::move(location), std::move(desc));
uint64_t count; 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); usage_map.emplace(std::move(location_desc), count);
} }
@ -89,14 +89,14 @@ bool ScriptCoverageManager::ReadStats()
bool ScriptCoverageManager::WriteStats() bool ScriptCoverageManager::WriteStats()
{ {
char* bf = zeekenv("ZEEK_PROFILER_FILE"); char* bf = zeek::util::zeekenv("ZEEK_PROFILER_FILE");
if ( ! bf ) if ( ! bf )
return false; 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); zeek::reporter->Error("Failed to open ZEEK_PROFILER_FILE destination '%s' for writing", bf);
return false; return false;

View file

@ -45,7 +45,7 @@ void SerializationFormat::StartWrite()
if ( ! output ) if ( ! output )
{ {
output = (char*)safe_malloc(INITIAL_SIZE); output = (char*)zeek::util::safe_malloc(INITIAL_SIZE);
output_size = 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 ) while ( output_pos + count > output_size )
output_size *= GROWTH_FACTOR; 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); memcpy(output + output_pos, b, count);
output_pos += 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 BinarySerializationFormat::Read(char* v, const char* tag)
{ {
bool ret = ReadData(v, 1); 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; return ret;
} }
@ -218,7 +218,7 @@ bool BinarySerializationFormat::Read(char** str, int* len, const char* tag)
*str = s; *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; return true;
} }
@ -303,7 +303,7 @@ bool BinarySerializationFormat::Read(struct in6_addr* addr, const char* tag)
bool BinarySerializationFormat::Write(char v, 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); return WriteData(&v, 1);
} }
@ -434,7 +434,7 @@ bool BinarySerializationFormat::WriteSeparator()
bool BinarySerializationFormat::Write(const char* buf, int len, const char* tag) 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); uint32_t l = htonl(len);
return WriteData(&l, sizeof(l)) && WriteData(buf, len); return WriteData(&l, sizeof(l)) && WriteData(buf, len);
} }

View file

@ -450,7 +450,7 @@ void NetSessions::DoNextPacket(double t, const zeek::Packet* pkt, const zeek::IP
if ( gre_version != 0 && gre_version != 1 ) if ( gre_version != 0 && gre_version != 1 )
{ {
Weird("unknown_gre_version", ip_hdr, encapsulation, Weird("unknown_gre_version", ip_hdr, encapsulation,
fmt("%d", gre_version)); zeek::util::fmt("%d", gre_version));
return; return;
} }
@ -528,7 +528,7 @@ void NetSessions::DoNextPacket(double t, const zeek::Packet* pkt, const zeek::IP
{ {
// Enhanced GRE payload must be PPP. // Enhanced GRE payload must be PPP.
Weird("egre_protocol_type", ip_hdr, encapsulation, Weird("egre_protocol_type", ip_hdr, encapsulation,
fmt("%d", proto_typ)); zeek::util::fmt("%d", proto_typ));
return; return;
} }
} }
@ -661,7 +661,7 @@ void NetSessions::DoNextPacket(double t, const zeek::Packet* pkt, const zeek::IP
} }
default: default:
Weird("unknown_protocol", pkt, encapsulation, fmt("%d", proto)); Weird("unknown_protocol", pkt, encapsulation, zeek::util::fmt("%d", proto));
return; return;
} }
@ -1331,7 +1331,7 @@ void NetSessions::Weird(const char* name, const zeek::Packet* pkt,
dump_this_packet = true; dump_this_packet = true;
if ( encap && encap->LastType() != BifEnum::Tunnel::NONE ) 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 else
zeek::reporter->Weird(name, addl); 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 ) if ( encap && encap->LastType() != BifEnum::Tunnel::NONE )
zeek::reporter->Weird(ip->SrcAddr(), ip->DstAddr(), zeek::reporter->Weird(ip->SrcAddr(), ip->DstAddr(),
fmt("%s_in_tunnel", name), addl); zeek::util::fmt("%s_in_tunnel", name), addl);
else else
zeek::reporter->Weird(ip->SrcAddr(), ip->DstAddr(), name, addl); zeek::reporter->Weird(ip->SrcAddr(), ip->DstAddr(), name, addl);
} }

View file

@ -359,7 +359,7 @@ static void sw_collect_multiple(Substring::Vec* result,
{ {
if ( (*it2)->DoesCover(*it3) ) if ( (*it2)->DoesCover(*it3) )
{ {
delete_each(new_al); zeek::util::delete_each(new_al);
delete new_al; delete new_al;
new_al = nullptr; new_al = nullptr;
goto end_loop; goto end_loop;
@ -367,7 +367,7 @@ static void sw_collect_multiple(Substring::Vec* result,
if ( (*it3)->DoesCover(*it2) ) if ( (*it3)->DoesCover(*it2) )
{ {
delete_each(old_al); zeek::util::delete_each(old_al);
delete old_al; delete old_al;
*it = 0; *it = 0;
goto end_loop; goto end_loop;

View file

@ -75,7 +75,7 @@ void ProfileLogger::Log()
// Connections have been flushed already. // Connections have been flushed already.
return; 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. // Do expensive profiling only occasionally.
bool expensive = false; bool expensive = false;
@ -90,14 +90,14 @@ void ProfileLogger::Log()
struct timeval tv_stime = r.ru_stime; struct timeval tv_stime = r.ru_stime;
uint64_t total, malloced; uint64_t total, malloced;
get_memory_usage(&total, &malloced); zeek::util::get_memory_usage(&total, &malloced);
static unsigned int first_total = 0; static unsigned int first_total = 0;
static double first_rtime = 0; static double first_rtime = 0;
static double first_utime = 0; static double first_utime = 0;
static double first_stime = 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 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; double stime = double(tv_stime.tv_sec) + double(tv_stime.tv_usec) / 1e6;
@ -108,26 +108,26 @@ void ProfileLogger::Log()
first_utime = utime; first_utime = utime;
first_stime = stime; 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++ ) for ( int i = 0; i < bro_argc; i++ )
{ {
file->Write(bro_argv[i]); file->Write(bro_argv[i]);
file->Write(" "); 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, zeek::net::network_time, total / 1024, (total - first_total) / 1024,
malloced / 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), zeek::net::network_time, (utime + stime) - (first_utime + first_stime),
utime - first_utime, stime - first_stime, rtime - first_rtime)); utime - first_utime, stime - first_stime, rtime - first_rtime));
int conn_mem_use = expensive ? sessions->ConnectionMemoryUsage() : 0; 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, zeek::net::network_time,
Connection::TotalConnections(), Connection::TotalConnections(),
Connection::CurrentConnections(), Connection::CurrentConnections(),
@ -141,7 +141,7 @@ void ProfileLogger::Log()
SessionStats s; SessionStats s;
sessions->GetStats(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, zeek::net::network_time,
s.num_TCP_conns, s.max_TCP_conns, s.num_TCP_conns, s.max_TCP_conns,
s.num_UDP_conns, s.max_UDP_conns, s.num_UDP_conns, s.max_UDP_conns,
@ -149,11 +149,11 @@ void ProfileLogger::Log()
)); ));
sessions->tcp_stats.PrintStats(file, 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... // 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, zeek::net::network_time,
sessions->tcp_stats.StateInactive(), sessions->tcp_stats.StateInactive(),
sessions->tcp_stats.StateRequest(), 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)); 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)); Reassembler::TotalMemoryAllocation() / 1024));
// Signature engine. // Signature engine.
@ -179,12 +179,12 @@ void ProfileLogger::Log()
zeek::detail::RuleMatcher::Stats stats; zeek::detail::RuleMatcher::Stats stats;
zeek::detail::rule_matcher->GetStats(&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, "ncomputed=%d mem=%dK\n", zeek::net::network_time, stats.matchers,
stats.nfa_states, stats.dfa_states, stats.computed, stats.mem / 1024)); 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::net::network_time,
zeek::detail::timer_mgr->Size(), zeek::detail::timer_mgr->PeakSize(), zeek::detail::timer_mgr->Size(), zeek::detail::timer_mgr->PeakSize(),
zeek::net::network_time - zeek::detail::timer_mgr->LastTimestamp())); 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::Stats dstats;
zeek::detail::dns_mgr->GetStats(&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, zeek::net::network_time,
dstats.requests, dstats.successful, dstats.failed, dstats.pending, dstats.requests, dstats.successful, dstats.failed, dstats.pending,
dstats.cached_hosts, dstats.cached_addresses)); dstats.cached_hosts, dstats.cached_addresses));
@ -200,25 +200,25 @@ void ProfileLogger::Log()
zeek::detail::trigger::Manager::Stats tstats; zeek::detail::trigger::Manager::Stats tstats;
zeek::detail::trigger_mgr->GetStats(&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(); unsigned int* current_timers = zeek::detail::TimerMgr::CurrentTimers();
for ( int i = 0; i < zeek::detail::NUM_TIMER_TYPES; ++i ) for ( int i = 0; i < zeek::detail::NUM_TIMER_TYPES; ++i )
{ {
if ( current_timers[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<zeek::detail::TimerType>(i)), zeek::detail::timer_type_to_string(static_cast<zeek::detail::TimerType>(i)),
current_timers[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(); const threading::Manager::msg_stats_list& thread_stats = zeek::thread_mgr->GetMsgThreadStats();
for ( threading::Manager::msg_stats_list::const_iterator i = thread_stats.begin(); for ( threading::Manager::msg_stats_list::const_iterator i = thread_stats.begin();
i != thread_stats.end(); ++i ) i != thread_stats.end(); ++i )
{ {
threading::MsgThread::Stats s = i->second; 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 ")" " (#queue r/w: in=%" PRIu64 "/%" PRIu64 " out=%" PRIu64 "/%" PRIu64 ")"
"\n", "\n",
zeek::net::network_time, zeek::net::network_time,
@ -232,7 +232,7 @@ void ProfileLogger::Log()
auto cs = broker_mgr->GetStatistics(); 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 " "pending_queries=%zu "
"events_in=%zu events_out=%zu " "events_in=%zu events_out=%zu "
"logs_in=%zu logs_out=%zu " "logs_in=%zu logs_out=%zu "
@ -253,7 +253,7 @@ void ProfileLogger::Log()
int total_table_entries = 0; int total_table_entries = 0;
int total_table_rentries = 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)); zeek::net::network_time, mem / 1024));
for ( const auto& global : globals ) for ( const auto& global : globals )
@ -294,12 +294,12 @@ void ProfileLogger::Log()
if ( print ) if ( print )
{ {
file->Write(fmt("%.06f %s = %dK", file->Write(zeek::util::fmt("%.06f %s = %dK",
zeek::net::network_time, id->Name(), zeek::net::network_time, id->Name(),
size / 1024)); size / 1024));
if ( entries >= 0 ) if ( entries >= 0 )
file->Write(fmt(" (%d/%d entries)\n", file->Write(zeek::util::fmt(" (%d/%d entries)\n",
entries, rentries)); entries, rentries));
else else
file->Write("\n"); 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)); 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, zeek::net::network_time,
total_table_entries, total_table_rentries)); total_table_entries, total_table_rentries));
} }
@ -329,16 +329,16 @@ void ProfileLogger::SegmentProfile(const char* name, const zeek::detail::Locatio
double dtime, int dmem) double dtime, int dmem)
{ {
if ( name ) 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)); zeek::net::network_time, name, dtime, dmem));
else if ( loc ) 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, zeek::net::network_time,
loc->filename ? loc->filename : "nofile", loc->filename ? loc->filename : "nofile",
loc->first_line, loc->first_line,
dtime, dmem)); dtime, dmem));
else 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)); zeek::net::network_time, dtime, dmem));
} }
@ -442,7 +442,7 @@ void PacketProfiler::ProfilePkt(double t, unsigned int bytes)
getrusage(RUSAGE_SELF, &res); getrusage(RUSAGE_SELF, &res);
gettimeofday(&ptimestamp, 0); 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_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_Stime = res.ru_stime.tv_sec + res.ru_stime.tv_usec / 1e6;
last_Rtime = ptimestamp.tv_sec + ptimestamp.tv_usec / 1e6; last_Rtime = ptimestamp.tv_sec + ptimestamp.tv_usec / 1e6;
@ -466,9 +466,9 @@ void PacketProfiler::ProfilePkt(double t, unsigned int bytes)
ptimestamp.tv_sec + ptimestamp.tv_usec / 1e6; ptimestamp.tv_sec + ptimestamp.tv_usec / 1e6;
uint64_t curr_mem; 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", file->Write(zeek::util::fmt("%.06f %.03f %" PRIu64 " %" PRIu64 " %.03f %.03f %.03f %" PRIu64 "\n",
t, time-last_timestamp, pkt_cnt, byte_cnt, t, time-last_timestamp, pkt_cnt, byte_cnt,
curr_Rtime - last_Rtime, curr_Rtime - last_Rtime,
curr_Utime - last_Utime, curr_Utime - last_Utime,

View file

@ -143,7 +143,7 @@ void Stmt::AccessStats(ODesc* d) const
if ( d->IncludeStats() ) if ( d->IncludeStats() )
{ {
d->Add("(@"); d->Add("(@");
d->Add(last_access ? fmt_access_time(last_access) : "<never>"); d->Add(last_access ? zeek::util::fmt_access_time(last_access) : "<never>");
d->Add(" #"); d->Add(" #");
d->Add(access_count); d->Add(access_count);
d->Add(")"); d->Add(")");

View file

@ -92,7 +92,7 @@ zeek::EnumVal* Tag::AsEnumVal(zeek::EnumType* etype) const
std::string Tag::AsString() const std::string Tag::AsString() const
{ {
return fmt("%" PRIu32 "/%" PRIu32, type, subtype); return zeek::util::fmt("%" PRIu32 "/%" PRIu32, type, subtype);
} }
} // namespace zeek } // namespace zeek

View file

@ -97,7 +97,7 @@ void TimerMgr::Process()
// move forward and the timers won't fire correctly. // move forward and the timers won't fire correctly.
iosource::PktSrc* pkt_src = zeek::iosource_mgr->GetPktSrc(); iosource::PktSrc* pkt_src = zeek::iosource_mgr->GetPktSrc();
if ( ! pkt_src || ! pkt_src->IsOpen() || zeek::net::reading_live || zeek::net::net_is_processing_suspended() ) 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 // 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. // change the time, but will dispatch any timers that need dispatching.

View file

@ -313,7 +313,7 @@ bool Trigger::Eval()
assert(trigger->attached == this); assert(trigger->attached == this);
#ifdef DEBUG #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); DBG_LOG(zeek::DBG_NOTIFIERS, "%s: trigger has parent %s, caching result", Name(), pname);
delete [] pname; delete [] pname;
#endif #endif
@ -366,7 +366,7 @@ void Trigger::Timeout()
assert(trigger->attached == this); assert(trigger->attached == this);
#ifdef DEBUG #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); DBG_LOG(zeek::DBG_NOTIFIERS, "%s: trigger has parent %s, caching timeout result", Name(), pname);
delete [] pname; delete [] pname;
#endif #endif
@ -426,7 +426,7 @@ void Trigger::Attach(Trigger *trigger)
assert(! trigger->delayed); assert(! trigger->delayed);
#ifdef DEBUG #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); DBG_LOG(zeek::DBG_NOTIFIERS, "%s: attaching to %s", Name(), pname);
delete [] pname; delete [] pname;
#endif #endif
@ -486,7 +486,7 @@ void Trigger::Modified(zeek::notifier::detail::Modifiable* m)
const char* Trigger::Name() const const char* Trigger::Name() const
{ {
assert(location); assert(location);
return fmt("%s:%d-%d", location->filename, return zeek::util::fmt("%s:%d-%d", location->filename,
location->first_line, location->last_line); location->first_line, location->last_line);
} }

View file

@ -266,7 +266,7 @@ void Type::Describe(ODesc* d) const
void Type::DescribeReST(ODesc* d, bool roles_only) 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() void Type::SetError()
@ -339,7 +339,7 @@ unsigned int TypeList::MemoryAllocation() const
for ( const auto& t : types ) for ( const auto& t : types )
size += t->MemoryAllocation(); 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() return Type::MemoryAllocation()
+ padded_sizeof(*this) - padded_sizeof(Type) + padded_sizeof(*this) - padded_sizeof(Type)
@ -553,7 +553,7 @@ FuncType::FuncType(RecordTypePtr arg_args,
else if ( has_default_arg ) else if ( has_default_arg )
{ {
const char* err_str = fmt("required parameter '%s' must precede " const char* err_str = zeek::util::fmt("required parameter '%s' must precede "
"default parameters", td->id); "default parameters", td->id);
args->Error(err_str); args->Error(err_str);
} }
@ -621,7 +621,7 @@ bool FuncType::CheckArgs(const std::vector<TypePtr>& args,
if ( my_args.size() != args.size() ) if ( my_args.size() != args.size() )
{ {
Warn(fmt("Wrong number of arguments for function. Expected %zu, got %zu.", Warn(zeek::util::fmt("Wrong number of arguments for function. Expected %zu, got %zu.",
args.size(), my_args.size())); args.size(), my_args.size()));
return false; return false;
} }
@ -631,7 +631,7 @@ bool FuncType::CheckArgs(const std::vector<TypePtr>& args,
for ( size_t i = 0; i < my_args.size(); ++i ) for ( size_t i = 0; i < my_args.size(); ++i )
if ( ! same_type(args[i], my_args[i], is_init) ) if ( ! same_type(args[i], my_args[i], is_init) )
{ {
Warn(fmt("Type mismatch in function argument #%zu. Expected %s, got %s.", 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()))); i, type_name(args[i]->Tag()), type_name(my_args[i]->Tag())));
success = false; success = false;
} }
@ -719,7 +719,7 @@ std::optional<FuncType::Prototype> FuncType::FindPrototype(const RecordType& arg
const auto& desired_type = args.GetFieldType(i); const auto& desired_type = args.GetFieldType(i);
if ( ! same_type(ptype, desired_type) || 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; matched = false;
break; break;
@ -744,7 +744,7 @@ TypeDecl::TypeDecl(const TypeDecl& other)
type = other.type; type = other.type;
attrs = other.attrs; attrs = other.attrs;
id = copy_string(other.id); id = zeek::util::copy_string(other.id);
} }
TypeDecl::~TypeDecl() TypeDecl::~TypeDecl()
@ -821,7 +821,7 @@ int RecordType::FieldOffset(const char* field) const
loop_over_list(*types, i) loop_over_list(*types, i)
{ {
TypeDecl* td = (*types)[i]; TypeDecl* td = (*types)[i];
if ( streq(td->id, field) ) if ( zeek::util::streq(td->id, field) )
return i; return i;
} }
@ -1045,7 +1045,7 @@ void RecordType::DescribeFieldsReST(ODesc* d, bool func_args) const
d->Add("<recursion>"); d->Add("<recursion>");
else 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 ) td->type->Tag() == TYPE_ANY )
// This was a BIF using variable argument list // This was a BIF using variable argument list
d->Add("..."); d->Add("...");
@ -1122,10 +1122,10 @@ string RecordType::GetFieldDeprecationWarning(int field, bool has_check) const
result = deprecation->DeprecationMessage(); result = deprecation->DeprecationMessage();
if ( result.empty() ) if ( result.empty() )
return fmt("deprecated (%s%s$%s)", GetName().c_str(), has_check ? "?" : "", return zeek::util::fmt("deprecated (%s%s$%s)", GetName().c_str(), has_check ? "?" : "",
FieldName(field)); FieldName(field));
else else
return fmt("deprecated (%s%s$%s): %s", GetName().c_str(), has_check ? "?" : "", return zeek::util::fmt("deprecated (%s%s$%s): %s", GetName().c_str(), has_check ? "?" : "",
FieldName(field), result.c_str()); FieldName(field), result.c_str());
} }
@ -1182,7 +1182,7 @@ void OpaqueType::Describe(ODesc* d) const
void OpaqueType::DescribeReST(ODesc* d, bool roles_only) 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) EnumType::EnumType(const string& name)
@ -1373,9 +1373,9 @@ void EnumType::DescribeReST(ODesc* d, bool roles_only) const
d->PushIndent(); d->PushIndent();
if ( roles_only ) 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 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; using zeekygen::IdentifierInfo;
IdentifierInfo* doc = zeekygen_mgr->GetIdentifierInfo(it->second); 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 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() ) if ( yield_type->GetName().empty() )
yield_type->DescribeReST(d, roles_only); yield_type->DescribeReST(d, roles_only);
else 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 // 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* td1 = rt1->FieldDecl(i);
const TypeDecl* td2 = rt2->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) ) ! same_type(td1->type, td2->type, is_init, match_record_field_names) )
return false; return false;
} }
@ -1856,7 +1856,7 @@ TypePtr merge_types(const TypePtr& arg_t1,
// there creating clones of the type, so safer to compare name. // there creating clones of the type, so safer to compare name.
if ( t1->GetName() != t2->GetName() ) if ( t1->GetName() != t2->GetName() )
{ {
std::string msg = fmt("incompatible enum types: '%s' and '%s'", std::string msg = zeek::util::fmt("incompatible enum types: '%s' and '%s'",
t1->GetName().data(), t2->GetName().data()); t1->GetName().data(), t2->GetName().data());
t1->Error(msg.data(), t2); t1->Error(msg.data(), t2);
@ -1875,7 +1875,7 @@ TypePtr merge_types(const TypePtr& arg_t1,
// actually see those changes from the redef. // actually see those changes from the redef.
return id->GetType(); return id->GetType();
std::string msg = fmt("incompatible enum types: '%s' and '%s'" std::string msg = zeek::util::fmt("incompatible enum types: '%s' and '%s'"
" ('%s' enum type ID is invalid)", " ('%s' enum type ID is invalid)",
t1->GetName().data(), t2->GetName().data(), t1->GetName().data(), t2->GetName().data(),
t1->GetName().data()); t1->GetName().data());
@ -1967,14 +1967,14 @@ TypePtr merge_types(const TypePtr& arg_t1,
const TypeDecl* td2 = rt2->FieldDecl(i); const TypeDecl* td2 = rt2->FieldDecl(i);
auto tdl3_i = merge_types(td1->type, td2->type); 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); t1->Error("incompatible record fields", t2);
delete tdl3; delete tdl3;
return nullptr; 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<RecordType>(tdl3); return zeek::make_intrusive<RecordType>(tdl3);

View file

@ -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; size_t size = res.rem ? res.quot + 1 : res.quot;
for ( size_t i = 0; i < size; ++i ) 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 ) if ( res.rem )
uid[0] >>= 64 - 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 char tmp[sizeof(uid) * 8 + 1]; // enough for even binary representation
for ( size_t i = 0; i < BRO_UID_LEN; ++i ) 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; return prefix;
} }

View file

@ -421,7 +421,7 @@ detail::ID* Val::GetID() const
void Val::SetID(detail::ID* id) void Val::SetID(detail::ID* id)
{ {
delete [] bound_id; delete [] bound_id;
bound_id = id ? copy_string(id->Name()) : nullptr; bound_id = id ? zeek::util::copy_string(id->Name()) : nullptr;
} }
#endif #endif
@ -558,7 +558,7 @@ static void BuildJSON(zeek::threading::formatter::JSON::NullDoubleWriter& writer
ODesc d; ODesc d;
d.SetStyle(RAW_STYLE); d.SetStyle(RAW_STYLE);
val->Describe(&d); val->Describe(&d);
writer.String(json_escape_utf8(string(reinterpret_cast<const char*>(d.Bytes()), d.Len()))); writer.String(zeek::util::json_escape_utf8(std::string(reinterpret_cast<const char*>(d.Bytes()), d.Len())));
break; break;
} }
@ -1331,7 +1331,7 @@ unsigned int ListVal::MemoryAllocation() const
for ( const auto& val : vals ) for ( const auto& val : vals )
size += val->MemoryAllocation(); 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(); return size + padded_sizeof(*this) + type->MemoryAllocation();
} }
@ -2445,7 +2445,7 @@ void TableVal::Describe(ODesc* d) const
if ( d->IsReadable() && ! d->IsShort() && d->IncludeStats() ) if ( d->IsReadable() && ! d->IsShort() && d->IncludeStats() )
{ {
d->Add(" @"); 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 += v->MemoryAllocation();
} }
size += pad_size(vl.capacity() * sizeof(ValPtr)); size += zeek::util::pad_size(vl.capacity() * sizeof(ValPtr));
size += padded_sizeof(vl); size += padded_sizeof(vl);
return size + padded_sizeof(*this); return size + padded_sizeof(*this);
} }

View file

@ -84,7 +84,7 @@ static bool add_prototype(const zeek::detail::IDPtr& id, zeek::Type* t,
if ( alt_args->FieldDecl(i)->attrs ) 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; return false;
} }
@ -92,7 +92,7 @@ static bool add_prototype(const zeek::detail::IDPtr& id, zeek::Type* t,
if ( o < 0 ) 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; return false;
} }
@ -469,11 +469,11 @@ static std::optional<zeek::FuncType::Prototype> func_type_check(const zeek::Func
auto msg = ad->DeprecationMessage(); auto msg = ad->DeprecationMessage();
if ( msg.empty() ) if ( msg.empty() )
impl->Warn(fmt("use of deprecated parameter '%s'", impl->Warn(zeek::util::fmt("use of deprecated parameter '%s'",
rval->args->FieldName(i)), rval->args->FieldName(i)),
decl, true); decl, true);
else else
impl->Warn(fmt("use of deprecated parameter '%s': %s", impl->Warn(zeek::util::fmt("use of deprecated parameter '%s': %s",
rval->args->FieldName(i), msg.data()), rval->args->FieldName(i), msg.data()),
decl, true); decl, true);
} }
@ -553,10 +553,10 @@ void begin_func(zeek::detail::IDPtr id, const char* module_name,
if ( prototype->deprecated ) if ( prototype->deprecated )
{ {
if ( prototype->deprecation_msg.empty() ) 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); prototype->args.get(), true);
else else
t->Warn(fmt("use of deprecated '%s' prototype: %s", t->Warn(zeek::util::fmt("use of deprecated '%s' prototype: %s",
id->Name(), prototype->deprecation_msg.data()), id->Name(), prototype->deprecation_msg.data()),
prototype->args.get(), true); prototype->args.get(), true);
} }
@ -648,7 +648,7 @@ void begin_func(zeek::detail::IDPtr id, const char* module_name,
if ( hide ) if ( hide )
// Note the illegal '-' in hidden name implies we haven't // Note the illegal '-' in hidden name implies we haven't
// clobbered any local variable names. // 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 = zeek::detail::install_ID(local_name, module_name, false, false);
arg_id->SetType(arg_i->type); arg_id->SetType(arg_i->type);

View file

@ -279,7 +279,7 @@ void String::ToUpper()
unsigned int String::MemoryAllocation() const 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 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 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 String::Vec* String::Split(const String::IdxVec& indices) const

View file

@ -232,7 +232,7 @@ void Analyzer::NextPacket(int len, const u_char* data, bool is_orig, uint64_t se
} }
catch ( binpac::Exception const &e ) 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 ) 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 ) 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]", 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_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) void Analyzer::DeliverStream(int len, const u_char* data, bool is_orig)
{ {
DBG_LOG(zeek::DBG_ANALYZER, "%s DeliverStream(%d, %s) [%s%s]", DBG_LOG(zeek::DBG_ANALYZER, "%s DeliverStream(%d, %s) [%s%s]",
fmt_analyzer(this).c_str(), len, is_orig ? "T" : "F", 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) void Analyzer::Undelivered(uint64_t seq, int len, bool is_orig)
@ -714,9 +714,9 @@ void Analyzer::ProtocolViolation(const char* reason, const char* data, int len)
if ( data && len ) if ( data && len )
{ {
const char *tmp = copy_string(reason); const char *tmp = zeek::util::copy_string(reason);
r = zeek::make_intrusive<zeek::StringVal>(fmt("%s [%s%s]", tmp, r = zeek::make_intrusive<zeek::StringVal>(zeek::util::fmt("%s [%s%s]", tmp,
fmt_bytes(data, min(40, len)), zeek::util::fmt_bytes(data, min(40, len)),
len > 40 ? "..." : "")); len > 40 ? "..." : ""));
delete [] tmp; delete [] tmp;
} }

View file

@ -637,7 +637,7 @@ protected:
* and ID. * and ID.
*/ */
static std::string fmt_analyzer(const Analyzer* a) 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 * Associates a connection with this analyzer. Must be called if

View file

@ -31,7 +31,7 @@ void AYIYA_Analyzer::DeliverPacket(int len, const u_char* data, bool orig, uint6
} }
catch ( const binpac::Exception& e ) catch ( const binpac::Exception& e )
{ {
ProtocolViolation(fmt("Binpac exception: %s", e.c_msg())); ProtocolViolation(zeek::util::fmt("Binpac exception: %s", e.c_msg()));
} }
} }

View file

@ -59,7 +59,7 @@ void BitTorrent_Analyzer::DeliverStream(int len, const u_char* data, bool orig)
Parent()->RemoveChildAnalyzer(this); Parent()->RemoveChildAnalyzer(this);
else else
{ {
DeliverWeird(fmt("Stopping BitTorrent analysis: protocol violation (%s)", DeliverWeird(zeek::util::fmt("Stopping BitTorrent analysis: protocol violation (%s)",
e.c_msg()), orig); e.c_msg()), orig);
this_stop = true; this_stop = true;
if ( stop_orig && stop_resp ) if ( stop_orig && stop_resp )

View file

@ -322,7 +322,7 @@ bool BitTorrentTracker_Analyzer::ParseRequest(char* line)
case detail::BTT_REQ_DONE: case detail::BTT_REQ_DONE:
if ( *line ) 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); Weird("bittorrent_tracker_data_post_request", msg);
DeliverWeird(msg, true); DeliverWeird(msg, true);
} }

View file

@ -49,7 +49,7 @@ flow BitTorrent_Flow(is_orig: bool) {
function validate_message_length(len: uint32): bool function validate_message_length(len: uint32): bool
%{ %{
if ( len > MSGLEN_LIMIT ) 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)); len, MSGLEN_LIMIT));
return true; return true;
%} %}

View file

@ -61,7 +61,7 @@ void DCE_RPC_Analyzer::DeliverStream(int len, const u_char* data, bool orig)
} }
catch ( const binpac::Exception& e ) catch ( const binpac::Exception& e )
{ {
ProtocolViolation(fmt("Binpac exception: %s", e.c_msg())); ProtocolViolation(zeek::util::fmt("Binpac exception: %s", e.c_msg()));
} }
} }

View file

@ -43,7 +43,7 @@ refine connection DCE_RPC_Conn += {
ntlm->DeliverStream(${auth.blob}.length(), ${auth.blob}.begin(), is_orig); ntlm->DeliverStream(${auth.blob}.length(), ${auth.blob}.begin(), is_orig);
break; break;
default: 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; break;
} }

View file

@ -32,7 +32,7 @@ void DHCP_Analyzer::DeliverPacket(int len, const u_char* data,
} }
catch ( const binpac::Exception& e ) catch ( const binpac::Exception& e )
{ {
ProtocolViolation(fmt("Binpac exception: %s", e.c_msg())); ProtocolViolation(zeek::util::fmt("Binpac exception: %s", e.c_msg()));
} }
} }

View file

@ -44,7 +44,7 @@ refine flow DHCP_Flow += {
// the message options. // the message options.
if ( ${msg.cookie} != 0x63825363 ) 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; return false;
} }

View file

@ -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 ) if ( crc16[0] == (crc & 0xff) && crc16[1] == (crc & 0xff00) >> 8 )
return true; return true;
analyzer->Weird(fmt("dnp3_corrupt_%s_checksum", where)); analyzer->Weird(zeek::util::fmt("dnp3_corrupt_%s_checksum", where));
return false; return false;
} }

View file

@ -352,7 +352,7 @@ bool DNS_Interpreter::ParseAnswer(detail::DNS_MsgInfo* msg,
msg->BuildAnswerVal() 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; data += rdlength;
len -= rdlength; len -= rdlength;
status = true; status = true;
@ -980,7 +980,7 @@ bool DNS_Interpreter::ParseRR_RRSIG(detail::DNS_MsgInfo* msg,
switch ( dsa ) { switch ( dsa ) {
case detail::RSA_MD5: 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; break;
case detail::Diffie_Hellman: case detail::Diffie_Hellman:
break; break;
@ -1005,16 +1005,16 @@ bool DNS_Interpreter::ParseRR_RRSIG(detail::DNS_MsgInfo* msg,
case detail::ECDSA_curveP384withSHA384: case detail::ECDSA_curveP384withSHA384:
break; break;
case detail::Indirect: case detail::Indirect:
analyzer->Weird("DNSSEC_RRSIG_Indirect_ZoneSignAlgo", fmt("%d", algo)); analyzer->Weird("DNSSEC_RRSIG_Indirect_ZoneSignAlgo", zeek::util::fmt("%d", algo));
break; break;
case detail::PrivateDNS: case detail::PrivateDNS:
analyzer->Weird("DNSSEC_RRSIG_PrivateDNS_ZoneSignAlgo", fmt("%d", algo)); analyzer->Weird("DNSSEC_RRSIG_PrivateDNS_ZoneSignAlgo", zeek::util::fmt("%d", algo));
break; break;
case detail::PrivateOID: case detail::PrivateOID:
analyzer->Weird("DNSSEC_RRSIG_PrivateOID_ZoneSignAlgo", fmt("%d", algo)); analyzer->Weird("DNSSEC_RRSIG_PrivateOID_ZoneSignAlgo", zeek::util::fmt("%d", algo));
break; break;
default: default:
analyzer->Weird("DNSSEC_RRSIG_unknown_ZoneSignAlgo", fmt("%d", algo)); analyzer->Weird("DNSSEC_RRSIG_unknown_ZoneSignAlgo", zeek::util::fmt("%d", algo));
break; break;
} }
@ -1069,18 +1069,18 @@ bool DNS_Interpreter::ParseRR_DNSKEY(detail::DNS_MsgInfo* msg,
// flags bit 8: revoked // flags bit 8: revoked
// flags bit 15: Secure Entry Point, key signing key // flags bit 15: Secure Entry Point, key signing key
if ( (dflags & 0xfe7e) != 0 ) 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 // flags bit 7, 8, and 15 all set
if ( (dflags & 0x0181) == 0x0181 ) 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 ) 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 ) { switch ( dsa ) {
case detail::RSA_MD5: 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; break;
case detail::Diffie_Hellman: case detail::Diffie_Hellman:
break; break;
@ -1105,16 +1105,16 @@ bool DNS_Interpreter::ParseRR_DNSKEY(detail::DNS_MsgInfo* msg,
case detail::ECDSA_curveP384withSHA384: case detail::ECDSA_curveP384withSHA384:
break; break;
case detail::Indirect: case detail::Indirect:
analyzer->Weird("DNSSEC_DNSKEY_Indirect_ZoneSignAlgo", fmt("%d", dalgorithm)); analyzer->Weird("DNSSEC_DNSKEY_Indirect_ZoneSignAlgo", zeek::util::fmt("%d", dalgorithm));
break; break;
case detail::PrivateDNS: case detail::PrivateDNS:
analyzer->Weird("DNSSEC_DNSKEY_PrivateDNS_ZoneSignAlgo", fmt("%d", dalgorithm)); analyzer->Weird("DNSSEC_DNSKEY_PrivateDNS_ZoneSignAlgo", zeek::util::fmt("%d", dalgorithm));
break; break;
case detail::PrivateOID: case detail::PrivateOID:
analyzer->Weird("DNSSEC_DNSKEY_PrivateOID_ZoneSignAlgo", fmt("%d", dalgorithm)); analyzer->Weird("DNSSEC_DNSKEY_PrivateOID_ZoneSignAlgo", zeek::util::fmt("%d", dalgorithm));
break; break;
default: default:
analyzer->Weird("DNSSEC_DNSKEY_unknown_ZoneSignAlgo", fmt("%d", dalgorithm)); analyzer->Weird("DNSSEC_DNSKEY_unknown_ZoneSignAlgo", zeek::util::fmt("%d", dalgorithm));
break; break;
} }
@ -1168,7 +1168,7 @@ bool DNS_Interpreter::ParseRR_NSEC(detail::DNS_MsgInfo* msg,
if ( bmlen == 0 ) if ( bmlen == 0 )
{ {
analyzer->Weird("DNSSEC_NSEC_bitmapLen0", fmt("%d", win_blck)); analyzer->Weird("DNSSEC_NSEC_bitmapLen0", zeek::util::fmt("%d", win_blck));
break; break;
} }
@ -1243,7 +1243,7 @@ bool DNS_Interpreter::ParseRR_NSEC3(detail::DNS_MsgInfo* msg,
if ( bmlen == 0 ) if ( bmlen == 0 )
{ {
analyzer->Weird("DNSSEC_NSEC3_bitmapLen0", fmt("%d", win_blck)); analyzer->Weird("DNSSEC_NSEC3_bitmapLen0", zeek::util::fmt("%d", win_blck));
break; break;
} }
@ -1307,10 +1307,10 @@ bool DNS_Interpreter::ParseRR_DS(detail::DNS_MsgInfo* msg,
case detail::SHA384: case detail::SHA384:
break; break;
case detail::reserved: case detail::reserved:
analyzer->Weird("DNSSEC_DS_ResrevedDigestType", fmt("%d", ds_dtype)); analyzer->Weird("DNSSEC_DS_ResrevedDigestType", zeek::util::fmt("%d", ds_dtype));
break; break;
default: default:
analyzer->Weird("DNSSEC_DS_unknown_DigestType", fmt("%d", ds_dtype)); analyzer->Weird("DNSSEC_DS_unknown_DigestType", zeek::util::fmt("%d", ds_dtype));
break; break;
} }
@ -1856,13 +1856,13 @@ void Contents_DNS::ProcessChunk(int& len, const u_char*& data, bool orig)
if ( buf_len < msg_size ) if ( buf_len < msg_size )
{ {
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 else
{ {
buf_len = msg_size; buf_len = msg_size;
msg_buf = (u_char*) safe_malloc(buf_len); msg_buf = (u_char*) zeek::util::safe_malloc(buf_len);
} }
++data; ++data;

View file

@ -50,12 +50,12 @@ void Finger_Analyzer::DeliverStream(int length, const u_char* data, bool is_orig
if ( ! finger_request ) if ( ! finger_request )
return; return;
line = skip_whitespace(line, end_of_line); line = zeek::util::skip_whitespace(line, end_of_line);
// Check for /W. // Check for /W.
int long_cnt = (line + 2 <= end_of_line && line[0] == '/' && toupper(line[1]) == 'W'); int long_cnt = (line + 2 <= end_of_line && line[0] == '/' && toupper(line[1]) == 'W');
if ( long_cnt ) 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); 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. size_t n = end_of_line >= line ? end_of_line - line : 0; // just to be sure if assertions aren't on.

View file

@ -84,9 +84,9 @@ void FTP_Analyzer::DeliverStream(int length, const u_char* data, bool orig)
const char* cmd; const char* cmd;
zeek::StringVal* cmd_str; zeek::StringVal* cmd_str;
line = skip_whitespace(line, end_of_line); line = zeek::util::skip_whitespace(line, end_of_line);
get_word(end_of_line - line, line, cmd_len, cmd); zeek::util::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 + cmd_len, end_of_line);
if ( cmd_len == 0 ) if ( cmd_len == 0 )
{ {
@ -125,7 +125,7 @@ void FTP_Analyzer::DeliverStream(int length, const u_char* data, bool orig)
length > 3 && line[3] == ' ' ) length > 3 && line[3] == ' ' )
{ {
// This is the end of the reply. // 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; pending_reply = 0;
cont_resp = 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] == '-' ) if ( reply_code > 0 && length > 3 && line[3] == '-' )
{ // a continued reply { // a continued reply
pending_reply = reply_code; 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; cont_resp = 1;
} }
else else
@ -152,7 +152,7 @@ void FTP_Analyzer::DeliverStream(int length, const u_char* data, bool orig)
(const char*) data, length); (const char*) data, length);
if ( line < end_of_line ) if ( line < end_of_line )
line = skip_whitespace(line, end_of_line); line = zeek::util::skip_whitespace(line, end_of_line);
else else
line = end_of_line; line = end_of_line;
@ -210,12 +210,12 @@ void FTP_ADAT_Analyzer::DeliverStream(int len, const u_char* data, bool orig)
{ {
int cmd_len; int cmd_len;
const char* cmd; const char* cmd;
line = skip_whitespace(line, end_of_line); line = zeek::util::skip_whitespace(line, end_of_line);
get_word(len, line, cmd_len, cmd); zeek::util::get_word(len, line, cmd_len, cmd);
if ( strncmp(cmd, "ADAT", cmd_len) == 0 ) 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); zeek::StringVal encoded(end_of_line - line, line);
decoded_adat = zeek::detail::decode_base64(encoded.AsString(), nullptr, Conn()); 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] == '-' ) if ( len > 3 && line[0] == '-' )
line++; 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 ) if ( end_of_line - line >= 5 && strncmp(line, "ADAT=", 5) == 0 )
{ {

View file

@ -206,7 +206,7 @@ function fmt_ftp_port%(a: addr, p: port%): string
{ {
uint32_t a = ntohl(addr[0]); uint32_t a = ntohl(addr[0]);
uint32_t pn = p->Port(); uint32_t pn = p->Port();
return zeek::make_intrusive<zeek::StringVal>(fmt("%d,%d,%d,%d,%d,%d", return zeek::make_intrusive<zeek::StringVal>(zeek::util::fmt("%d,%d,%d,%d,%d,%d",
a >> 24, (a >> 16) & 0xff, a >> 24, (a >> 16) & 0xff,
(a >> 8) & 0xff, a & 0xff, (a >> 8) & 0xff, a & 0xff,
pn >> 8, pn & 0xff)); pn >> 8, pn & 0xff));

View file

@ -45,7 +45,7 @@ void GSSAPI_Analyzer::DeliverStream(int len, const u_char* data, bool orig)
} }
catch ( const binpac::Exception& e ) catch ( const binpac::Exception& e )
{ {
ProtocolViolation(fmt("Binpac exception: %s", e.c_msg())); ProtocolViolation(zeek::util::fmt("Binpac exception: %s", e.c_msg()));
} }
} }

View file

@ -32,7 +32,7 @@ void GTPv1_Analyzer::DeliverPacket(int len, const u_char* data, bool orig, uint6
} }
catch ( const binpac::Exception& e ) catch ( const binpac::Exception& e )
{ {
ProtocolViolation(fmt("Binpac exception: %s", e.c_msg())); ProtocolViolation(zeek::util::fmt("Binpac exception: %s", e.c_msg()));
} }
} }

View file

@ -323,7 +323,7 @@ void CreatePDP_Request(const BroAnalyzer& a, const GTPv1_Header* pdu)
rv->Assign(21, BuildPrivateExt(ie)); rv->Assign(21, BuildPrivateExt(ie));
break; break;
default: 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; break;
} }
} }
@ -392,7 +392,7 @@ void CreatePDP_Response(const BroAnalyzer& a, const GTPv1_Header* pdu)
rv->Assign(12, BuildPrivateExt(ie)); rv->Assign(12, BuildPrivateExt(ie));
break; break;
default: 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; break;
} }
} }
@ -470,7 +470,7 @@ void UpdatePDP_Request(const BroAnalyzer& a, const GTPv1_Header* pdu)
rv->Assign(15, BuildEndUserAddr(ie)); rv->Assign(15, BuildEndUserAddr(ie));
break; break;
default: 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; break;
} }
} }
@ -530,7 +530,7 @@ void UpdatePDP_Response(const BroAnalyzer& a, const GTPv1_Header* pdu)
rv->Assign(9, BuildPrivateExt(ie)); rv->Assign(9, BuildPrivateExt(ie));
break; break;
default: 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; break;
} }
} }
@ -564,7 +564,7 @@ void DeletePDP_Request(const BroAnalyzer& a, const GTPv1_Header* pdu)
rv->Assign(2, BuildPrivateExt(ie)); rv->Assign(2, BuildPrivateExt(ie));
break; break;
default: 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; break;
} }
} }
@ -595,7 +595,7 @@ void DeletePDP_Response(const BroAnalyzer& a, const GTPv1_Header* pdu)
rv->Assign(1, BuildPrivateExt(ie)); rv->Assign(1, BuildPrivateExt(ie));
break; break;
default: 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; break;
} }
} }

View file

@ -115,7 +115,7 @@ void HTTP_Entity::Deliver(int len, const char* data, bool trailing_CRLF)
switch ( chunked_transfer_state ) { switch ( chunked_transfer_state ) {
case EXPECT_CHUNK_SIZE: case EXPECT_CHUNK_SIZE:
ASSERT(trailing_CRLF); 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"); http_message->Weird("HTTP_bad_chunk_size");
expect_data_length = 0; 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) ) if ( ! zeek::analyzer::mime::is_null_data_chunk(vt) )
{ {
int64_t n; 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; content_length = n;
@ -435,8 +435,8 @@ void HTTP_Entity::SubmitHeader(zeek::analyzer::mime::MIME_Header* h)
instance_length_str.c_str()); instance_length_str.c_str());
int64_t f, l; int64_t f, l;
atoi_n(first_byte_pos.size(), first_byte_pos.c_str(), nullptr, 10, f); zeek::util::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(last_byte_pos.size(), last_byte_pos.c_str(), nullptr, 10, l);
int64_t len = l - f + 1; int64_t len = l - f + 1;
if ( DEBUG_http ) if ( DEBUG_http )
@ -446,7 +446,7 @@ void HTTP_Entity::SubmitHeader(zeek::analyzer::mime::MIME_Header* h)
{ {
if ( instance_length_str != "*" ) if ( instance_length_str != "*" )
{ {
if ( ! atoi_n(instance_length_str.size(), if ( ! zeek::util::atoi_n(instance_length_str.size(),
instance_length_str.c_str(), nullptr, 10, instance_length_str.c_str(), nullptr, 10,
instance_length) ) instance_length) )
instance_length = 0; instance_length = 0;
@ -1095,7 +1095,7 @@ void HTTP_Analyzer::Undelivered(uint64_t seq, int len, bool is_orig)
{ {
if ( msg ) if ( msg )
msg->SubmitEvent(zeek::analyzer::mime::MIME_EVENT_CONTENT_GAP, 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 // 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; return nullptr;
const char* orig_line = line; 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 ) if ( line == orig_line )
// Word didn't end at prefix. // 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; 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 ) if ( rest == end_of_method )
goto error; 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 ) for ( version_start = end_of_uri; version_start < end_of_line; ++version_start )
{ {
end_of_uri = 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/") ) if ( PrefixMatch(version_start, end_of_line, "HTTP/") )
break; break;
} }
@ -1313,7 +1313,7 @@ bool HTTP_Analyzer::ParseRequest(const char* line, const char* end_of_line)
version_start)); version_start));
version_end = version_start + 3; 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", HTTP_Event("crud after HTTP version is ignored",
zeek::analyzer::mime::to_string_val(line, end_of_line)); zeek::analyzer::mime::to_string_val(line, end_of_line));
} }
@ -1409,7 +1409,7 @@ void HTTP_Analyzer::HTTP_Request()
request_method, request_method,
TruncateURI(request_URI), TruncateURI(request_URI),
TruncateURI(unescaped_URI), TruncateURI(unescaped_URI),
zeek::make_intrusive<zeek::StringVal>(fmt("%.1f", request_version.ToDouble())) zeek::make_intrusive<zeek::StringVal>(zeek::util::fmt("%.1f", request_version.ToDouble()))
); );
} }
@ -1418,7 +1418,7 @@ void HTTP_Analyzer::HTTP_Reply()
if ( http_reply ) if ( http_reply )
EnqueueConnEvent(http_reply, EnqueueConnEvent(http_reply,
ConnVal(), ConnVal(),
zeek::make_intrusive<zeek::StringVal>(fmt("%.1f", reply_version.ToDouble())), zeek::make_intrusive<zeek::StringVal>(zeek::util::fmt("%.1f", reply_version.ToDouble())),
zeek::val_mgr->Count(reply_code), zeek::val_mgr->Count(reply_code),
reply_reason_phrase ? reply_reason_phrase ?
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; return 0;
} }
rest = skip_whitespace(rest, end_of_line); rest = zeek::util::skip_whitespace(rest, end_of_line);
if ( rest + 3 > 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; return 1;
} }
rest = skip_whitespace(rest, end_of_line); rest = zeek::util::skip_whitespace(rest, end_of_line);
reply_reason_phrase = reply_reason_phrase =
zeek::make_intrusive<zeek::StringVal>(end_of_line - rest, (const char *) rest); zeek::make_intrusive<zeek::StringVal>(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) void escape_URI_char(unsigned char ch, unsigned char*& p)
{ {
*p++ = '%'; *p++ = '%';
*p++ = encode_hex((ch >> 4) & 0xf); *p++ = zeek::util::encode_hex((ch >> 4) & 0xf);
*p++ = encode_hex(ch & 0xf); *p++ = zeek::util::encode_hex(ch & 0xf);
} }
zeek::String* unescape_URI(const u_char* line, const u_char* line_end, 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]) ) else if ( isxdigit(line[0]) && isxdigit(line[1]) )
{ {
*URI_p++ = (decode_hex(line[0]) << 4) + *URI_p++ = (zeek::util::decode_hex(line[0]) << 4) +
decode_hex(line[1]); zeek::util::decode_hex(line[1]);
++line; // place line at the last hex digit ++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 // It could just be ASCII encoded into this
// unicode escaping structure. // unicode escaping structure.
if ( ! (line[1] == '0' && line[2] == '0' ) ) if ( ! (line[1] == '0' && line[2] == '0' ) )
*URI_p++ = (decode_hex(line[1]) << 4) + *URI_p++ = (zeek::util::decode_hex(line[1]) << 4) +
decode_hex(line[2]); zeek::util::decode_hex(line[2]);
*URI_p++ = (decode_hex(line[3]) << 4) + *URI_p++ = (zeek::util::decode_hex(line[3]) << 4) +
decode_hex(line[4]); zeek::util::decode_hex(line[4]);
line += 4; line += 4;
} }

View file

@ -112,7 +112,7 @@ void Ident_Analyzer::DeliverStream(int length, const u_char* data, bool is_orig)
return; 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 restlen = end_of_line - line;
int is_error; int is_error;
@ -132,7 +132,7 @@ void Ident_Analyzer::DeliverStream(int length, const u_char* data, bool is_orig)
return; return;
} }
line = skip_whitespace(line, end_of_line); line = zeek::util::skip_whitespace(line, end_of_line);
if ( line >= end_of_line || line[0] != ':' ) 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; return;
} }
line = skip_whitespace(line + 1, end_of_line); line = zeek::util::skip_whitespace(line + 1, end_of_line);
if ( is_error ) 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, new zeek::String((const u_char*) sys_type,
sys_end - sys_type + 1, true); 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, EnqueueConnEvent(ident_reply,
ConnVal(), ConnVal(),
@ -214,7 +214,7 @@ const char* Ident_Analyzer::ParsePort(const char* line, const char* end_of_line,
{ {
int n = 0; 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) ) if ( line >= end_of_line || ! isdigit(*line) )
return nullptr; 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) ); 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 ) if ( n < 0 || n > 65535 )
{ {

View file

@ -61,7 +61,7 @@ void IMAP_Analyzer::DeliverStream(int len, const u_char* data, bool orig)
} }
catch ( const binpac::Exception& e ) catch ( const binpac::Exception& e )
{ {
ProtocolViolation(fmt("Binpac exception: %s", e.c_msg())); ProtocolViolation(zeek::util::fmt("Binpac exception: %s", e.c_msg()));
} }
} }

View file

@ -83,7 +83,7 @@ void KRB_Analyzer::DeliverPacket(int len, const u_char* data, bool orig,
} }
catch ( const binpac::Exception& e ) 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; return nullptr;
} }
auto tkt = static_cast<krb5_ticket*>(safe_malloc(sizeof(krb5_ticket))); auto tkt = static_cast<krb5_ticket*>(zeek::util::safe_malloc(sizeof(krb5_ticket)));
memset(tkt, 0, sizeof(krb5_ticket)); memset(tkt, 0, sizeof(krb5_ticket));
tkt->server = sprinc; tkt->server = sprinc;
tkt->enc_part.enctype = enctype; tkt->enc_part.enctype = enctype;
auto ctd = static_cast<char*>(safe_malloc(ciphertext->Len())); auto ctd = static_cast<char*>(zeek::util::safe_malloc(ciphertext->Len()));
memcpy(ctd, ciphertext->Bytes(), ciphertext->Len()); memcpy(ctd, ciphertext->Bytes(), ciphertext->Len());
tkt->enc_part.ciphertext.data = ctd; tkt->enc_part.ciphertext.data = ctd;
tkt->enc_part.ciphertext.length = ciphertext->Len(); tkt->enc_part.ciphertext.length = ciphertext->Len();

View file

@ -53,7 +53,7 @@ void KRB_Analyzer::DeliverStream(int len, const u_char* data, bool orig)
} }
catch ( const binpac::Exception& e ) catch ( const binpac::Exception& e )
{ {
ProtocolViolation(fmt("Binpac exception: %s", e.c_msg())); ProtocolViolation(zeek::util::fmt("Binpac exception: %s", e.c_msg()));
} }
} }

View file

@ -18,9 +18,9 @@ zeek::ValPtr GetStringFromPrincipalName(const KRB_Principal_Name* pname)
if ( pname->data()->size() == 1 ) if ( pname->data()->size() == 1 )
return to_stringval(pname->data()[0][0]->encoding()->content()); return to_stringval(pname->data()[0][0]->encoding()->content());
if ( pname->data()->size() == 2 ) if ( pname->data()->size() == 2 )
return zeek::make_intrusive<zeek::StringVal>(fmt("%s/%s", (char *) pname->data()[0][0]->encoding()->content().begin(), (char *)pname->data()[0][1]->encoding()->content().begin())); return zeek::make_intrusive<zeek::StringVal>(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 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<zeek::StringVal>(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::StringVal>(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<zeek::StringVal>("unknown"); return zeek::make_intrusive<zeek::StringVal>("unknown");
} }

View file

@ -323,14 +323,14 @@ void Login_Analyzer::SetEnv(bool orig, char* name, char* val)
else else
{ {
if ( streq(name, "USER") ) if ( zeek::util::streq(name, "USER") )
{ {
if ( username ) if ( username )
{ {
const zeek::String* u = username->AsString(); const zeek::String* u = username->AsString();
const zeek::byte_vec ub = u->Bytes(); const zeek::byte_vec ub = u->Bytes();
const char* us = (const char*) ub; const char* us = (const char*) ub;
if ( ! streq(val, us) ) if ( ! zeek::util::streq(val, us) )
Confused("multiple_USERs", val); Confused("multiple_USERs", val);
Unref(username); Unref(username);
} }
@ -339,19 +339,19 @@ void Login_Analyzer::SetEnv(bool orig, char* name, char* val)
username = new zeek::StringVal(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, EnqueueConnEvent(login_terminal,
ConnVal(), ConnVal(),
zeek::make_intrusive<zeek::StringVal>(val) zeek::make_intrusive<zeek::StringVal>(val)
); );
else if ( login_display && streq(name, "DISPLAY") ) else if ( login_display && zeek::util::streq(name, "DISPLAY") )
EnqueueConnEvent(login_display, EnqueueConnEvent(login_display,
ConnVal(), ConnVal(),
zeek::make_intrusive<zeek::StringVal>(val) zeek::make_intrusive<zeek::StringVal>(val)
); );
else if ( login_prompt && streq(name, "TTYPROMPT") ) else if ( login_prompt && zeek::util::streq(name, "TTYPROMPT") )
EnqueueConnEvent(login_prompt, EnqueueConnEvent(login_prompt,
ConnVal(), ConnVal(),
zeek::make_intrusive<zeek::StringVal>(val) zeek::make_intrusive<zeek::StringVal>(val)
@ -562,7 +562,7 @@ void Login_Analyzer::AddUserText(const char* line)
if ( ++user_text_last == MAX_USER_TEXT ) if ( ++user_text_last == MAX_USER_TEXT )
user_text_last = 0; 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; ++num_user_text;
} }
@ -612,7 +612,7 @@ bool Login_Analyzer::MatchesTypeahead(const char* line) const
if ( i == MAX_USER_TEXT ) if ( i == MAX_USER_TEXT )
i = 0; i = 0;
if ( streq(user_text[i], line) ) if ( zeek::util::streq(user_text[i], line) )
return true; return true;
} }

View file

@ -251,7 +251,7 @@ void TelnetAuthenticateOption::RecvSubOption(u_char* data, int len)
case AUTHENTICATION_NAME: case AUTHENTICATION_NAME:
{ {
char* auth_name = new char[len]; 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); endp->SetAuthName(auth_name);
} }
break; break;

View file

@ -171,7 +171,7 @@ void Rsh_Analyzer::DeliverStream(int len, const u_char* data, bool orig)
zeek::Args vl; zeek::Args vl;
vl.reserve(4 + orig); vl.reserve(4 + orig);
const char* line = (const char*) data; const char* line = (const char*) data;
line = skip_whitespace(line); line = zeek::util::skip_whitespace(line);
vl.emplace_back(ConnVal()); vl.emplace_back(ConnVal());
if ( client_name ) if ( client_name )

View file

@ -1083,8 +1083,8 @@ void MIME_Entity::DecodeQuotedPrintable(int len, const char* data)
if ( i + 2 < len ) if ( i + 2 < len )
{ {
int a, b; int a, b;
a = decode_hex(data[i+1]); a = zeek::util::decode_hex(data[i+1]);
b = decode_hex(data[i+2]); b = zeek::util::decode_hex(data[i+2]);
if ( a >= 0 && b >= 0 ) if ( a >= 0 && b >= 0 )
{ {
@ -1114,7 +1114,7 @@ void MIME_Entity::DecodeQuotedPrintable(int len, const char* data)
else 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]); DataOctet(data[i]);
} }
} }

View file

@ -203,7 +203,7 @@ refine flow ModbusTCP_Flow += {
if ( ${message.byte_count} % 2 != 0 ) if ( ${message.byte_count} % 2 != 0 )
{ {
connection()->bro_analyzer()->ProtocolViolation( 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; return false;
} }
@ -247,7 +247,7 @@ refine flow ModbusTCP_Flow += {
if ( ${message.byte_count} % 2 != 0 ) if ( ${message.byte_count} % 2 != 0 )
{ {
connection()->bro_analyzer()->ProtocolViolation( 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; return false;
} }
@ -283,7 +283,7 @@ refine flow ModbusTCP_Flow += {
val = 1; val = 1;
else 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})); ${message.value}));
return false; return false;
} }
@ -310,7 +310,7 @@ refine flow ModbusTCP_Flow += {
val = 1; val = 1;
else 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})); ${message.value}));
return false; return false;
} }
@ -391,7 +391,7 @@ refine flow ModbusTCP_Flow += {
if ( ${message.byte_count} % 2 != 0 ) if ( ${message.byte_count} % 2 != 0 )
{ {
connection()->bro_analyzer()->ProtocolViolation( 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; return false;
} }
@ -576,7 +576,7 @@ refine flow ModbusTCP_Flow += {
if ( ${message.write_byte_count} % 2 != 0 ) if ( ${message.write_byte_count} % 2 != 0 )
{ {
connection()->bro_analyzer()->ProtocolViolation( 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; return false;
} }
@ -608,7 +608,7 @@ refine flow ModbusTCP_Flow += {
if ( ${message.byte_count} % 2 != 0 ) if ( ${message.byte_count} % 2 != 0 )
{ {
connection()->bro_analyzer()->ProtocolViolation( 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; return false;
} }
@ -652,7 +652,7 @@ refine flow ModbusTCP_Flow += {
if ( ${message.byte_count} % 2 != 0 ) if ( ${message.byte_count} % 2 != 0 )
{ {
connection()->bro_analyzer()->ProtocolViolation( 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; return false;
} }

View file

@ -46,7 +46,7 @@ void MQTT_Analyzer::DeliverStream(int len, const u_char* data, bool orig)
} }
catch ( const binpac::Exception& e ) catch ( const binpac::Exception& e )
{ {
ProtocolViolation(fmt("Binpac exception: %s", e.c_msg())); ProtocolViolation(zeek::util::fmt("Binpac exception: %s", e.c_msg()));
} }
} }

View file

@ -53,7 +53,7 @@ void MySQL_Analyzer::DeliverStream(int len, const u_char* data, bool orig)
} }
catch ( const binpac::Exception& e ) catch ( const binpac::Exception& e )
{ {
ProtocolViolation(fmt("Binpac exception: %s", e.c_msg())); ProtocolViolation(zeek::util::fmt("Binpac exception: %s", e.c_msg()));
} }
} }

View file

@ -43,7 +43,7 @@ void NCP_Session::Deliver(bool is_orig, int len, const u_char* data)
} }
catch ( const binpac::Exception& e ) 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()));
} }
} }

View file

@ -105,7 +105,7 @@ void NetbiosSSN_Interpreter::ParseMessage(unsigned int type, unsigned int flags,
break; break;
default: default:
analyzer->Weird("unknown_netbios_type", fmt("0x%x", type)); analyzer->Weird("unknown_netbios_type", zeek::util::fmt("0x%x", type));
break; break;
} }
} }
@ -146,7 +146,7 @@ void NetbiosSSN_Interpreter::ParseMessageTCP(const u_char* data, int len,
NetbiosSSN_RawMsgHdr hdr(data, len); NetbiosSSN_RawMsgHdr hdr(data, len);
if ( hdr.length > unsigned(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)); hdr.length, len));
else if ( hdr.length < unsigned(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); NetbiosDGM_RawMsgHdr hdr(data, len);
if ( unsigned(hdr.length-14) > unsigned(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)); hdr.length, len));
else if ( hdr.length < unsigned(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)); hdr.length, len));
len = hdr.length; len = hdr.length;
} }

View file

@ -45,7 +45,7 @@ void NTLM_Analyzer::DeliverStream(int len, const u_char* data, bool orig)
} }
catch ( const binpac::Exception& e ) catch ( const binpac::Exception& e )
{ {
ProtocolViolation(fmt("Binpac exception: %s", e.c_msg())); ProtocolViolation(zeek::util::fmt("Binpac exception: %s", e.c_msg()));
} }
} }

View file

@ -34,7 +34,7 @@ void NTP_Analyzer::DeliverPacket(int len, const u_char* data, bool orig,
} }
catch ( const binpac::Exception& e ) catch ( const binpac::Exception& e )
{ {
ProtocolViolation(fmt("Binpac exception: %s", e.c_msg())); ProtocolViolation(zeek::util::fmt("Binpac exception: %s", e.c_msg()));
} }
} }

View file

@ -91,7 +91,7 @@ static std::string trim_whitespace(const char* in)
char* out = new char[n + 1]; char* out = new char[n + 1];
char* out_p = out; char* out_p = out;
in = skip_whitespace(in); in = zeek::util::skip_whitespace(in);
while ( *in ) while ( *in )
{ {
@ -245,7 +245,7 @@ static std::string commands[] = {
void POP3_Analyzer::NotAllowed(const char* cmd, const char* state) void POP3_Analyzer::NotAllowed(const char* cmd, const char* state)
{ {
POP3Event(pop3_unexpected, true, cmd, 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() void POP3_Analyzer::ProcessClientCmd()
@ -320,7 +320,7 @@ void POP3_Analyzer::ProcessClientCmd()
state = detail::APOP; state = detail::APOP;
subState = detail::POP3_WOK; subState = detail::POP3_WOK;
char* arg1 = copy_string(message); char* arg1 = zeek::util::copy_string(message);
char* e; char* e;
for ( e = arg1; *e && *e != ' ' && *e != '\t'; ++e ) for ( e = arg1; *e && *e != ' ' && *e != '\t'; ++e )
; ;
@ -354,7 +354,7 @@ void POP3_Analyzer::ProcessClientCmd()
{ {
state = detail::AUTH; state = detail::AUTH;
POP3Event(pop3_unexpected, true, cmd, POP3Event(pop3_unexpected, true, cmd,
fmt("unknown AUTH method %s", message)); zeek::util::fmt("unknown AUTH method %s", message));
} }
subState = detail::POP3_WOK; subState = detail::POP3_WOK;
@ -634,7 +634,7 @@ void POP3_Analyzer::ProcessReply(int length, const char* line)
{ {
if ( ! waitingForAuthentication ) if ( ! waitingForAuthentication )
{ {
ProtocolViolation(fmt("unknown server command (%s)", ProtocolViolation(zeek::util::fmt("unknown server command (%s)",
(tokens.size() > 0 ? (tokens.size() > 0 ?
tokens[0].c_str() : tokens[0].c_str() :
"???")), "???")),

View file

@ -35,7 +35,7 @@ void RADIUS_Analyzer::DeliverPacket(int len, const u_char* data,
} }
catch ( const binpac::Exception& e ) catch ( const binpac::Exception& e )
{ {
ProtocolViolation(fmt("Binpac exception: %s", e.c_msg())); ProtocolViolation(zeek::util::fmt("Binpac exception: %s", e.c_msg()));
} }
} }

View file

@ -88,7 +88,7 @@ void RDP_Analyzer::DeliverStream(int len, const u_char* data, bool orig)
} }
catch ( const binpac::Exception& e ) catch ( const binpac::Exception& e )
{ {
ProtocolViolation(fmt("Binpac exception: %s", e.c_msg())); ProtocolViolation(zeek::util::fmt("Binpac exception: %s", e.c_msg()));
} }
} }
} }

View file

@ -32,7 +32,7 @@ void RDP_Analyzer::DeliverPacket(int len, const u_char* data, bool orig,
} }
catch ( const binpac::Exception& e ) catch ( const binpac::Exception& e )
{ {
ProtocolViolation(fmt("Binpac exception: %s", e.c_msg())); ProtocolViolation(zeek::util::fmt("Binpac exception: %s", e.c_msg()));
} }
} }

View file

@ -63,7 +63,7 @@ void RFB_Analyzer::DeliverStream(int len, const u_char* data, bool orig)
} }
catch ( const binpac::Exception& e ) 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; invalid = true;
} }
} }

View file

@ -181,7 +181,7 @@ refine connection RFB_Conn += {
else else
{ {
// Shouldn't be a possible. // 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; return true;
@ -235,7 +235,7 @@ refine connection RFB_Conn += {
} }
else 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; return true;
@ -277,7 +277,7 @@ refine connection RFB_Conn += {
// Failed // Failed
server_state = SERVER_AUTH_FAILURE; server_state = SERVER_AUTH_FAILURE;
else 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; return true;
%} %}
@ -309,7 +309,7 @@ refine connection RFB_Conn += {
function handle_invalid_data(client: bool) : bool 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; return true;
%} %}

View file

@ -19,7 +19,7 @@ namespace detail {
bool MOUNT_Interp::RPC_BuildCall(RPC_CallInfo* c, const u_char*& buf, int& n) bool MOUNT_Interp::RPC_BuildCall(RPC_CallInfo* c, const u_char*& buf, int& n)
{ {
if ( c->Program() != 100005 ) 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(); uint32_t proc = c->Proc();
// The call arguments, depends on the call type obviously ... // 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; n = 0;
} }
else 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 // Return 1 so that replies to unprocessed calls will still
// be processed, and the return status extracted. // be processed, and the return status extracted.

View file

@ -19,7 +19,7 @@ namespace detail {
bool NFS_Interp::RPC_BuildCall(RPC_CallInfo* c, const u_char*& buf, int& n) bool NFS_Interp::RPC_BuildCall(RPC_CallInfo* c, const u_char*& buf, int& n)
{ {
if ( c->Program() != 100003 ) 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(); uint32_t proc = c->Proc();
// The call arguments, depends on the call type obviously ... // 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; n = 0;
} }
else 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 // Return 1 so that replies to unprocessed calls will still
// be processed, and the return status extracted. // be processed, and the return status extracted.

View file

@ -535,7 +535,7 @@ bool Contents_RPC::CheckResync(int& len, const u_char*& data, bool orig)
DEBUG_MSG("%.6f RPC resync: " DEBUG_MSG("%.6f RPC resync: "
"discard small pieces: %d\n", "discard small pieces: %d\n",
zeek::net::network_time, len); 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(); 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); // zeek::net::network_time, IsOrig(), marker, last_frag, msg_buf.GetExpected(), msg_buf.GetProcessed(), len);
if ( ! msg_buf.AddToExpected(marker) ) 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 ) if ( last_frag )
state = WAIT_FOR_LAST_DATA; state = WAIT_FOR_LAST_DATA;

View file

@ -39,7 +39,7 @@ void SIP_Analyzer::DeliverPacket(int len, const u_char* data, bool orig,
} }
catch ( const binpac::Exception& e ) catch ( const binpac::Exception& e )
{ {
ProtocolViolation(fmt("Binpac exception: %s", e.c_msg())); ProtocolViolation(zeek::util::fmt("Binpac exception: %s", e.c_msg()));
} }
} }

View file

@ -55,7 +55,7 @@ void SIP_Analyzer::DeliverStream(int len, const u_char* data, bool orig)
} }
catch ( const binpac::Exception& e ) catch ( const binpac::Exception& e )
{ {
ProtocolViolation(fmt("Binpac exception: %s", e.c_msg())); ProtocolViolation(zeek::util::fmt("Binpac exception: %s", e.c_msg()));
} }
} }

View file

@ -81,7 +81,7 @@ void SMB_Analyzer::DeliverStream(int len, const u_char* data, bool orig)
} }
catch ( const binpac::Exception& e ) catch ( const binpac::Exception& e )
{ {
ProtocolViolation(fmt("Binpac exception: %s", e.c_msg())); ProtocolViolation(zeek::util::fmt("Binpac exception: %s", e.c_msg()));
NeedResync(); NeedResync();
} }
} }

View file

@ -85,7 +85,7 @@ void SMTP_Analyzer::Undelivered(uint64_t seq, int len, bool is_orig)
if ( len <= 0 ) if ( len <= 0 )
return; 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); int buf_len = strlen(buf);
Unexpected(is_orig, "content gap", buf_len, 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_sender = false;
expect_recver = true; expect_recver = true;
get_word(length, line, cmd_len, cmd); zeek::util::get_word(length, line, cmd_len, cmd);
line = skip_whitespace(line + cmd_len, end_of_line); line = zeek::util::skip_whitespace(line + cmd_len, end_of_line);
cmd_code = ParseCmd(cmd_len, cmd); cmd_code = ParseCmd(cmd_len, cmd);
if ( cmd_code == -1 ) if ( cmd_code == -1 )
@ -299,7 +299,7 @@ void SMTP_Analyzer::ProcessLine(int length, const char* line, bool orig)
{ {
reply_code = -1; reply_code = -1;
Unexpected(is_sender, "reply code out of range", length, line); Unexpected(is_sender, "reply code out of range", length, line);
ProtocolViolation(fmt("reply code %d out of range", ProtocolViolation(zeek::util::fmt("reply code %d out of range",
reply_code), line, length); reply_code), line, length);
} }
@ -319,12 +319,12 @@ void SMTP_Analyzer::ProcessLine(int length, const char* line, bool orig)
if ( reply_code >= 0 && length > 3 && line[3] == '-' ) if ( reply_code >= 0 && length > 3 && line[3] == '-' )
{ // A continued reply. { // A continued reply.
pending_reply = reply_code; pending_reply = reply_code;
line = skip_whitespace(line+4, end_of_line); line = zeek::util::skip_whitespace(line+4, end_of_line);
} }
else else
{ // This is the end of the reply. { // 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; pending_reply = 0;
expect_sender = true; expect_sender = true;
@ -366,7 +366,7 @@ void SMTP_Analyzer::ProcessLine(int length, const char* line, bool orig)
const char* ext; const char* ext;
int ext_len; 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); ProcessExtension(ext_len, ext);
} }
} }

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