Move a few of the zeek::util methods and variables to zeek::util::detail

This commit is contained in:
Tim Wojtulewicz 2020-08-06 15:45:42 -07:00
parent 5a2ac84eee
commit ddf48d7529
35 changed files with 1221 additions and 1226 deletions

@ -1 +1 @@
Subproject commit 2affd6a4fd7b2543a533c481334828d3a47890d6 Subproject commit 1607cc50ddde62ac13c0f1d6539a96bb7182ca4e

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::util::random_number() & 0xffff) << 16) | (zeek::util::random_number() & 0xffff); return ((zeek::util::detail::random_number() & 0xffff) << 16) | (zeek::util::detail::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;
zeek::util::hmac_md5(sizeof(input), (u_char*)(&input), digest); zeek::util::detail::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})).
zeek::util::hmac_md5(sizeof(prefix), (u_char*) &prefix, digest); zeek::util::detail::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

@ -512,13 +512,13 @@ void Connection::ConnectionEvent(zeek::EventHandlerPtr f, zeek::analyzer::Analyz
return; return;
// "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::detail::SOURCE_LOCAL, a ? a->GetID() : 0, this);
} }
void Connection::ConnectionEventFast(zeek::EventHandlerPtr f, zeek::analyzer::Analyzer* a, val_list vl) void Connection::ConnectionEventFast(zeek::EventHandlerPtr f, zeek::analyzer::Analyzer* a, val_list vl)
{ {
// "this" is passed as a cookie for the event // "this" is passed as a cookie for the event
zeek::event_mgr.Enqueue(f, zeek::val_list_to_args(vl), SOURCE_LOCAL, zeek::event_mgr.Enqueue(f, zeek::val_list_to_args(vl), zeek::util::detail::SOURCE_LOCAL,
a ? a->GetID() : 0, this); a ? a->GetID() : 0, this);
} }
@ -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), zeek::util::SOURCE_LOCAL, a ? a->GetID() : 0, this); zeek::event_mgr.Enqueue(f, std::move(args), zeek::util::detail::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

@ -49,7 +49,7 @@ void DebugLogger::OpenDebugLog(const char* filename)
{ {
if ( filename ) if ( filename )
{ {
filename = zeek::util::log_file_name(filename); filename = zeek::util::detail::log_file_name(filename);
file = fopen(filename, "w"); file = fopen(filename, "w");
if ( ! file ) if ( ! file )

View file

@ -410,14 +410,14 @@ size_t Dictionary::MemoryAllocation() const
size_t size = padded_sizeof(*this); size_t size = padded_sizeof(*this);
if ( table ) if ( table )
{ {
size += pad_size(Capacity() * sizeof(detail::DictEntry)); size += zeek::util::pad_size(Capacity() * sizeof(detail::DictEntry));
for ( int i = Capacity()-1; i>=0; i-- ) for ( int i = Capacity()-1; i>=0; i-- )
if ( ! table[i].Empty() && table[i].key_size > 8 ) if ( ! table[i].Empty() && table[i].key_size > 8 )
size += pad_size(table[i].key_size); size += zeek::util::pad_size(table[i].key_size);
} }
if ( order ) if ( order )
size += padded_sizeof(std::vector<detail::DictEntry>) + pad_size(sizeof(detail::DictEntry) * order->capacity()); size += padded_sizeof(std::vector<detail::DictEntry>) + zeek::util::pad_size(sizeof(detail::DictEntry) * order->capacity());
return size; return size;
} }
@ -497,7 +497,7 @@ void Dictionary::Dump(int level) const
{ {
if ( table[i].Empty() ) if ( table[i].Empty() )
continue; continue;
key_size += pad_size(table[i].key_size); key_size += zeek::util::pad_size(table[i].key_size);
if ( ! table[i].value ) if ( ! table[i].value )
continue; continue;
} }

View file

@ -19,7 +19,8 @@ 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,
zeek::util::SourceID arg_src, zeek::analyzer::ID arg_aid, Obj* arg_obj) zeek::util::detail::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 +49,7 @@ void Event::Describe(ODesc* d) const
void Event::Dispatch(bool no_remote) void Event::Dispatch(bool no_remote)
{ {
if ( src == zeek::util::SOURCE_BROKER ) if ( src == zeek::util::detail::SOURCE_BROKER )
no_remote = true; no_remote = true;
if ( handler->ErrorHandler() ) if ( handler->ErrorHandler() )
@ -75,7 +76,7 @@ void Event::Dispatch(bool no_remote)
EventMgr::EventMgr() EventMgr::EventMgr()
{ {
head = tail = nullptr; head = tail = nullptr;
current_src = zeek::util::SOURCE_LOCAL; current_src = zeek::util::detail::SOURCE_LOCAL;
current_aid = 0; current_aid = 0;
src_val = nullptr; src_val = nullptr;
draining = false; draining = false;
@ -94,14 +95,14 @@ EventMgr::~EventMgr()
} }
void EventMgr::QueueEventFast(const EventHandlerPtr &h, val_list vl, void EventMgr::QueueEventFast(const EventHandlerPtr &h, val_list vl,
SourceID src, analyzer::ID aid, zeek::detail::TimerMgr* mgr, zeek::util::detail::SourceID src, analyzer::ID aid, zeek::detail::TimerMgr* mgr,
Obj* obj) Obj* obj)
{ {
QueueEvent(new Event(h, zeek::val_list_to_args(vl), src, aid, obj)); QueueEvent(new Event(h, zeek::val_list_to_args(vl), src, aid, obj));
} }
void EventMgr::QueueEvent(const EventHandlerPtr &h, val_list vl, void EventMgr::QueueEvent(const EventHandlerPtr &h, val_list vl,
SourceID src, analyzer::ID aid, zeek::util::detail::SourceID src, analyzer::ID aid,
zeek::detail::TimerMgr* mgr, Obj* obj) zeek::detail::TimerMgr* mgr, Obj* obj)
{ {
auto args = zeek::val_list_to_args(vl); auto args = zeek::val_list_to_args(vl);
@ -111,7 +112,7 @@ void EventMgr::QueueEvent(const EventHandlerPtr &h, val_list vl,
} }
void EventMgr::QueueEvent(const EventHandlerPtr &h, val_list* vl, void EventMgr::QueueEvent(const EventHandlerPtr &h, val_list* vl,
SourceID src, analyzer::ID aid, zeek::util::detail::SourceID src, analyzer::ID aid,
zeek::detail::TimerMgr* mgr, Obj* obj) zeek::detail::TimerMgr* mgr, Obj* obj)
{ {
auto args = zeek::val_list_to_args(*vl); auto args = zeek::val_list_to_args(*vl);
@ -122,7 +123,8 @@ 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,
zeek::util::SourceID src, zeek::analyzer::ID aid, Obj* obj) zeek::util::detail::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));
} }

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,
zeek::util::SourceID src = zeek::util::SOURCE_LOCAL, zeek::analyzer::ID aid = 0, zeek::util::detail::SourceID src = zeek::util::detail::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; }
zeek::util::SourceID Source() const { return src; } zeek::util::detail::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;
zeek::util::SourceID src; zeek::util::detail::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,
zeek::util::SourceID src = zeek::util::SOURCE_LOCAL, zeek::analyzer::ID aid = 0, zeek::util::detail::SourceID src = zeek::util::detail::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,
zeek::util::SourceID src = zeek::util::SOURCE_LOCAL, zeek::analyzer::ID aid = 0, zeek::util::detail::SourceID src = zeek::util::detail::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,
zeek::util::SourceID src = zeek::util::SOURCE_LOCAL, zeek::analyzer::ID aid = 0, zeek::util::detail::SourceID src = zeek::util::detail::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,
zeek::util::SourceID src = zeek::util::SOURCE_LOCAL, zeek::analyzer::ID aid = 0, zeek::util::detail::SourceID src = zeek::util::detail::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.
zeek::util::SourceID CurrentSource() const { return current_src; } zeek::util::detail::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;
zeek::util::SourceID current_src; zeek::util::detail::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

@ -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 = zeek::util::rotate_file(name, info); FILE* newf = zeek::util::detail::rotate_file(name, info);
if ( ! newf ) if ( ! newf )
{ {

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 zeek::util::hmac_md5(size_t size, const unsigned char* bytes, unsigned char digest[16]); friend void zeek::util::detail::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*);
}; };

View file

@ -222,8 +222,8 @@ void ID::SetVal(ExprPtr ev, InitClass c)
if ( ! val ) if ( ! val )
{ {
Error(fmt("%s initializer applied to ID without value", Error(zeek::util::fmt("%s initializer applied to ID without value",
c == INIT_EXTRA ? "+=" : "-="), this); c == INIT_EXTRA ? "+=" : "-="), this);
return; return;
} }

View file

@ -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::util::random_number() & 0xffffffff) < load_freq ) if ( uint32_t(zeek::util::detail::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()
{ {
zeek::util::set_processing_status("RUNNING", "net_run"); zeek::util::detail::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());
@ -364,7 +364,7 @@ void net_get_final_stats()
void net_finish(int drain_events) void net_finish(int drain_events)
{ {
zeek::util::set_processing_status("TERMINATING", "net_finish"); zeek::util::detail::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()
{ {
zeek::util::set_processing_status("TERMINATING", "net_delete"); zeek::util::detail::set_processing_status("TERMINATING", "net_delete");
delete zeek::sessions; delete zeek::sessions;

View file

@ -431,7 +431,7 @@ zeek::Options zeek::parse_cmdline(int argc, char** argv)
if ( path->empty() ) if ( path->empty() )
return; return;
*path = zeek::util::normalize_path(*path); *path = zeek::util::detail::normalize_path(*path);
if ( (*path)[0] == '/' || (*path)[0] == '~' ) if ( (*path)[0] == '/' || (*path)[0] == '~' )
// Absolute path // Absolute path

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::util::max_random()); f->probability = probability * static_cast<double>(zeek::util::detail::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::util::max_random()); f->probability = probability * static_cast<double>(zeek::util::detail::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::util::max_random()); f->probability = probability * static_cast<double>(zeek::util::detail::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::util::max_random()); f->probability = probability * static_cast<double>(zeek::util::detail::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::util::random_number() < f.probability; return zeek::util::detail::random_number() < f.probability;
} }
} // namespace zeek::detail } // namespace zeek::detail

View file

@ -126,7 +126,7 @@ void Reporter::FatalError(const char* fmt, ...)
va_end(ap); va_end(ap);
zeek::util::set_processing_status("TERMINATED", "fatal_error"); zeek::util::detail::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);
zeek::util::set_processing_status("TERMINATED", "fatal_error"); zeek::util::detail::set_processing_status("TERMINATED", "fatal_error");
abort(); abort();
} }
@ -195,7 +195,7 @@ void Reporter::InternalError(const char* fmt, ...)
va_end(ap); va_end(ap);
zeek::util::set_processing_status("TERMINATED", "internal_error"); zeek::util::detail::set_processing_status("TERMINATED", "internal_error");
abort(); abort();
} }

View file

@ -96,7 +96,7 @@ bool ScriptCoverageManager::WriteStats()
zeek::util::SafeDirname dirname{bf}; zeek::util::SafeDirname dirname{bf};
if ( ! zeek::util::ensure_intermediate_dirs(dirname.result.data()) ) if ( ! zeek::util::detail::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

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

View file

@ -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(zeek::util::fmt_access_time(v->ExpireAccessTime())); d->Add(zeek::util::detail::fmt_access_time(v->ExpireAccessTime()));
} }
} }

View file

@ -1216,7 +1216,7 @@ void Manager::ProcessEvent(const broker::topic& topic, broker::zeek::Event ev)
} }
if ( vl.size() == args.size() ) if ( vl.size() == args.size() )
zeek::event_mgr.Enqueue(handler, std::move(vl), zeek::util::SOURCE_BROKER); zeek::event_mgr.Enqueue(handler, std::move(vl), zeek::util::detail::SOURCE_BROKER);
} }
bool Manager::ProcessLogCreate(broker::zeek::LogCreate lc) bool Manager::ProcessLogCreate(broker::zeek::LogCreate lc)

View file

@ -1828,7 +1828,7 @@ void Manager::SendEvent(zeek::EventHandlerPtr ev, const int numvals, ...) const
va_end(lP); va_end(lP);
if ( ev ) if ( ev )
zeek::event_mgr.Enqueue(ev, std::move(vl), zeek::util::SOURCE_LOCAL); zeek::event_mgr.Enqueue(ev, std::move(vl), zeek::util::detail::SOURCE_LOCAL);
} }
void Manager::SendEvent(zeek::EventHandlerPtr ev, list<zeek::Val*> events) const void Manager::SendEvent(zeek::EventHandlerPtr ev, list<zeek::Val*> events) const
@ -1845,7 +1845,7 @@ void Manager::SendEvent(zeek::EventHandlerPtr ev, list<zeek::Val*> events) const
vl.emplace_back(zeek::AdoptRef{}, *i); vl.emplace_back(zeek::AdoptRef{}, *i);
if ( ev ) if ( ev )
zeek::event_mgr.Enqueue(ev, std::move(vl), zeek::util::SOURCE_LOCAL); zeek::event_mgr.Enqueue(ev, std::move(vl), zeek::util::detail::SOURCE_LOCAL);
} }
// Convert a bro list value to a bro record value. // Convert a bro list value to a bro record value.

View file

@ -1215,7 +1215,7 @@ WriterFrontend* Manager::CreateWriter(zeek::EnumVal* id, zeek::EnumVal* writer,
static auto base_time = log_rotate_base_time->AsString()->CheckString(); static auto base_time = log_rotate_base_time->AsString()->CheckString();
winfo->info->rotation_interval = winfo->interval; winfo->info->rotation_interval = winfo->interval;
winfo->info->rotation_base = zeek::util::parse_rotate_base_time(base_time); winfo->info->rotation_base = zeek::util::detail::parse_rotate_base_time(base_time);
winfo->writer = new WriterFrontend(*winfo->info, id, writer, local, remote); winfo->writer = new WriterFrontend(*winfo->info, id, writer, local, remote);
winfo->writer->Init(num_fields, fields); winfo->writer->Init(num_fields, fields);
@ -1474,9 +1474,9 @@ void Manager::InstallRotationTimer(WriterInfo* winfo)
static auto log_rotate_base_time = zeek::id::find_val<zeek::StringVal>("log_rotate_base_time"); static auto log_rotate_base_time = zeek::id::find_val<zeek::StringVal>("log_rotate_base_time");
static auto base_time = log_rotate_base_time->AsString()->CheckString(); static auto base_time = log_rotate_base_time->AsString()->CheckString();
double base = zeek::util::parse_rotate_base_time(base_time); double base = zeek::util::detail::parse_rotate_base_time(base_time);
double delta_t = double delta_t =
zeek::util::calc_next_rotate(zeek::net::network_time, rotation_interval, base); zeek::util::detail::calc_next_rotate(zeek::net::network_time, rotation_interval, base);
winfo->rotation_timer = winfo->rotation_timer =
new RotationTimer(zeek::net::network_time + delta_t, winfo, true); new RotationTimer(zeek::net::network_time + delta_t, winfo, true);
@ -1522,7 +1522,7 @@ std::string Manager::FormatRotationPath(zeek::EnumValPtr writer,
auto prefix = rp_val->GetField(1)->AsString()->CheckString(); auto prefix = rp_val->GetField(1)->AsString()->CheckString();
auto dir = dir_val->AsString()->CheckString(); auto dir = dir_val->AsString()->CheckString();
if ( ! zeek::util::streq(dir, "") && ! zeek::util::ensure_intermediate_dirs(dir) ) if ( ! zeek::util::streq(dir, "") && ! zeek::util::detail::ensure_intermediate_dirs(dir) )
{ {
zeek::reporter->Error("Failed to create dir '%s' returned by " zeek::reporter->Error("Failed to create dir '%s' returned by "
"Log::rotation_format_func for path %.*s: %s", "Log::rotation_format_func for path %.*s: %s",

View file

@ -180,47 +180,47 @@ bool Manager::ActivateDynamicPluginInternal(const std::string& name, bool ok_if_
if ( zeek::util::is_dir(scripts) ) if ( zeek::util::is_dir(scripts) )
{ {
DBG_LOG(zeek::DBG_PLUGINS, " Adding %s to ZEEKPATH", scripts.c_str()); DBG_LOG(zeek::DBG_PLUGINS, " Adding %s to ZEEKPATH", scripts.c_str());
zeek::util::add_to_zeek_path(scripts); zeek::util::detail::add_to_zeek_path(scripts);
} }
string init; string init;
// First load {scripts}/__preload__.zeek automatically. // First load {scripts}/__preload__.zeek automatically.
for (const string& ext : zeek::util::script_extensions) for (const string& ext : zeek::util::detail::script_extensions)
{ {
init = dir + "scripts/__preload__" + ext; init = dir + "scripts/__preload__" + ext;
if ( zeek::util::is_file(init) ) if ( zeek::util::is_file(init) )
{ {
DBG_LOG(zeek::DBG_PLUGINS, " Loading %s", init.c_str()); DBG_LOG(zeek::DBG_PLUGINS, " Loading %s", init.c_str());
zeek::util::warn_if_legacy_script(init); zeek::util::detail::warn_if_legacy_script(init);
scripts_to_load.push_back(init); scripts_to_load.push_back(init);
break; break;
} }
} }
// Load {bif,scripts}/__load__.zeek automatically. // Load {bif,scripts}/__load__.zeek automatically.
for (const string& ext : zeek::util::script_extensions) for (const string& ext : zeek::util::detail::script_extensions)
{ {
init = dir + "lib/bif/__load__" + ext; init = dir + "lib/bif/__load__" + ext;
if ( zeek::util::is_file(init) ) if ( zeek::util::is_file(init) )
{ {
DBG_LOG(zeek::DBG_PLUGINS, " Loading %s", init.c_str()); DBG_LOG(zeek::DBG_PLUGINS, " Loading %s", init.c_str());
zeek::util::warn_if_legacy_script(init); zeek::util::detail::warn_if_legacy_script(init);
scripts_to_load.push_back(init); scripts_to_load.push_back(init);
break; break;
} }
} }
for (const string& ext : zeek::util::script_extensions) for (const string& ext : zeek::util::detail::script_extensions)
{ {
init = dir + "scripts/__load__" + ext; init = dir + "scripts/__load__" + ext;
if ( zeek::util::is_file(init) ) if ( zeek::util::is_file(init) )
{ {
DBG_LOG(zeek::DBG_PLUGINS, " Loading %s", init.c_str()); DBG_LOG(zeek::DBG_PLUGINS, " Loading %s", init.c_str());
zeek::util::warn_if_legacy_script(init); zeek::util::detail::warn_if_legacy_script(init);
scripts_to_load.push_back(init); scripts_to_load.push_back(init);
break; break;
} }
@ -259,7 +259,7 @@ bool Manager::ActivateDynamicPluginInternal(const std::string& name, bool ok_if_
DBG_LOG(zeek::DBG_PLUGINS, " InitialzingComponents"); DBG_LOG(zeek::DBG_PLUGINS, " InitialzingComponents");
current_plugin->InitializeComponents(); current_plugin->InitializeComponents();
plugins_by_path.insert(std::make_pair(zeek::util::normalize_path(dir), current_plugin)); plugins_by_path.insert(std::make_pair(zeek::util::detail::normalize_path(dir), current_plugin));
// We execute the pre-script initialization here; this in // We execute the pre-script initialization here; this in
// fact could be *during* script initialization if we got // fact could be *during* script initialization if we got
@ -346,7 +346,7 @@ void Manager::RegisterPlugin(Plugin *plugin)
if ( current_dir && current_sopath ) if ( current_dir && current_sopath )
// A dynamic plugin, record its location. // A dynamic plugin, record its location.
plugin->SetPluginLocation(zeek::util::normalize_path(current_dir), current_sopath); plugin->SetPluginLocation(zeek::util::detail::normalize_path(current_dir), current_sopath);
current_plugin = plugin; current_plugin = plugin;
} }
@ -483,7 +483,7 @@ Manager::bif_init_func_map* Manager::BifFilesInternal()
Plugin* Manager::LookupPluginByPath(std::string_view _path) Plugin* Manager::LookupPluginByPath(std::string_view _path)
{ {
auto path = zeek::util::normalize_path(_path); auto path = zeek::util::detail::normalize_path(_path);
if ( zeek::util::is_file(path) ) if ( zeek::util::is_file(path) )
path = zeek::util::SafeDirname(path).result; path = zeek::util::SafeDirname(path).result;

View file

@ -33,7 +33,7 @@ Hasher::seed_t Hasher::MakeSeed(const void* data, size_t size)
else else
{ {
unsigned int first_seed = zeek::util::initial_seed(); unsigned int first_seed = zeek::util::detail::initial_seed();
zeek::detail::hash_update(ctx, &first_seed, sizeof(first_seed)); zeek::detail::hash_update(ctx, &first_seed, sizeof(first_seed));
} }
@ -119,7 +119,7 @@ DefaultHasher::DefaultHasher(size_t k, Hasher::seed_t seed)
for ( size_t i = 1; i <= k; ++i ) for ( size_t i = 1; i <= k; ++i )
{ {
seed_t s = Seed(); seed_t s = Seed();
s.h[0] += zeek::util::prng(i); s.h[0] += zeek::util::detail::prng(i);
hash_functions.push_back(UHF(s)); hash_functions.push_back(UHF(s));
} }
} }
@ -149,7 +149,7 @@ bool DefaultHasher::Equals(const Hasher* other) const
} }
DoubleHasher::DoubleHasher(size_t k, seed_t seed) DoubleHasher::DoubleHasher(size_t k, seed_t seed)
: Hasher(k, seed), h1(seed + zeek::util::prng(1)), h2(seed + zeek::util::prng(2)) : Hasher(k, seed), h1(seed + zeek::util::detail::prng(1)), h2(seed + zeek::util::detail::prng(2))
{ {
} }

View file

@ -212,7 +212,7 @@ CCL_EXPR ("[:"[[:alpha:]]+":]")
<INITIAL,SC_QUOTE,SC_FIRST_CCL,SC_CCL>{ESCSEQ} { <INITIAL,SC_QUOTE,SC_FIRST_CCL,SC_CCL>{ESCSEQ} {
const char* esc_text = yytext + 1; const char* esc_text = yytext + 1;
yylval.int_val = zeek::util::expand_escape(esc_text); yylval.int_val = zeek::util::detail::expand_escape(esc_text);
if ( YY_START == SC_FIRST_CCL ) if ( YY_START == SC_FIRST_CCL )
BEGIN(SC_CCL); BEGIN(SC_CCL);

View file

@ -43,13 +43,13 @@ PID {PIDCOMPONENT}(::{PIDCOMPONENT})*
} }
{IP6} { {IP6} {
rules_lval.prefixval = new zeek::IPPrefix(zeek::IPAddr(zeek::util::extract_ip(yytext)), 128, true); rules_lval.prefixval = new zeek::IPPrefix(zeek::IPAddr(zeek::util::detail::extract_ip(yytext)), 128, true);
return TOK_IP6; return TOK_IP6;
} }
{IP6}{OWS}"/"{OWS}{D} { {IP6}{OWS}"/"{OWS}{D} {
int len = 0; int len = 0;
std::string ip = zeek::util::extract_ip_and_len(yytext, &len); std::string ip = zeek::util::detail::extract_ip_and_len(yytext, &len);
rules_lval.prefixval = new zeek::IPPrefix(zeek::IPAddr(ip), len, true); rules_lval.prefixval = new zeek::IPPrefix(zeek::IPAddr(ip), len, true);
return TOK_IP6; return TOK_IP6;
} }

View file

@ -175,12 +175,12 @@ ESCSEQ (\\([^\n]|[0-7]+|x[[:xdigit:]]+))
/* IPv6 literal constant patterns */ /* IPv6 literal constant patterns */
{IP6} { {IP6} {
RET_CONST(new zeek::AddrVal(zeek::util::extract_ip(yytext))) RET_CONST(new zeek::AddrVal(zeek::util::detail::extract_ip(yytext)))
} }
{IP6}{OWS}"/"{OWS}{D} { {IP6}{OWS}"/"{OWS}{D} {
int len = 0; int len = 0;
std::string ip = zeek::util::extract_ip_and_len(yytext, &len); std::string ip = zeek::util::detail::extract_ip_and_len(yytext, &len);
RET_CONST(new zeek::SubNetVal(zeek::IPPrefix(zeek::IPAddr(ip), len, true))) RET_CONST(new zeek::SubNetVal(zeek::IPPrefix(zeek::IPAddr(ip), len, true)))
} }
@ -189,7 +189,7 @@ ESCSEQ (\\([^\n]|[0-7]+|x[[:xdigit:]]+))
({D}"."){3}{D}{OWS}"/"{OWS}{D} { ({D}"."){3}{D}{OWS}"/"{OWS}{D} {
int len = 0; int len = 0;
std::string ip = zeek::util::extract_ip_and_len(yytext, &len); std::string ip = zeek::util::detail::extract_ip_and_len(yytext, &len);
RET_CONST(new zeek::SubNetVal(zeek::IPPrefix(zeek::IPAddr(ip), len))) RET_CONST(new zeek::SubNetVal(zeek::IPPrefix(zeek::IPAddr(ip), len)))
} }
@ -516,7 +516,7 @@ F RET_CONST(zeek::val_mgr->False()->Ref())
if ( *text == '\\' ) if ( *text == '\\' )
{ {
++text; // skip '\' ++text; // skip '\'
s[i++] = zeek::util::expand_escape(text); s[i++] = zeek::util::detail::expand_escape(text);
--text; // point to end of sequence --text; // point to end of sequence
} }
else else
@ -614,7 +614,7 @@ static int load_files(const char* orig_file)
zeek::reporter->FatalError("can't find %s", orig_file); zeek::reporter->FatalError("can't find %s", orig_file);
if ( zeek::util::is_dir(file_path.c_str()) ) if ( zeek::util::is_dir(file_path.c_str()) )
f = zeek::util::open_package(file_path); f = zeek::util::detail::open_package(file_path);
else else
f = zeek::util::open_file(file_path); f = zeek::util::open_file(file_path);
@ -903,8 +903,8 @@ int yywrap()
if ( ! zeek_script_prefixes[i][0] ) if ( ! zeek_script_prefixes[i][0] )
continue; continue;
std::string canon = zeek::util::without_zeekpath_component(it->name); std::string canon = zeek::util::detail::without_zeekpath_component(it->name);
std::string flat = zeek::util::flatten_script_name(canon, zeek_script_prefixes[i]); std::string flat = zeek::util::detail::flatten_script_name(canon, zeek_script_prefixes[i]);
std::string path = find_relative_script_file(flat); std::string path = find_relative_script_file(flat);
if ( ! path.empty() ) if ( ! path.empty() )

View file

@ -624,7 +624,7 @@ size_t Supervisor::ProcessMessages()
Stem::Stem(State ss) Stem::Stem(State ss)
: parent_pid(ss.parent_pid), signal_flare(new zeek::detail::Flare()), pipe(std::move(ss.pipe)) : parent_pid(ss.parent_pid), signal_flare(new zeek::detail::Flare()), pipe(std::move(ss.pipe))
{ {
zeek::util::set_thread_name("zeek.stem"); zeek::util::detail::set_thread_name("zeek.stem");
pipe->Swap(); pipe->Swap();
stem = this; stem = this;
setsignal(SIGCHLD, stem_signal_handler); setsignal(SIGCHLD, stem_signal_handler);
@ -840,7 +840,7 @@ std::variant<bool, SupervisedNode> Stem::Spawn(SupervisorNode* node)
{ {
setsignal(SIGCHLD, SIG_DFL); setsignal(SIGCHLD, SIG_DFL);
setsignal(SIGTERM, SIG_DFL); setsignal(SIGTERM, SIG_DFL);
zeek::util::set_thread_name(zeek::util::fmt("zeek.%s", node->Name().data())); zeek::util::detail::set_thread_name(zeek::util::fmt("zeek.%s", node->Name().data()));
SupervisedNode rval; SupervisedNode rval;
rval.config = node->config; rval.config = node->config;
rval.parent_pid = ppid; rval.parent_pid = ppid;
@ -1610,7 +1610,7 @@ std::string Supervisor::Create(const Supervisor::NodeConfig& node)
if ( node.directory ) if ( node.directory )
{ {
auto res = zeek::util::ensure_intermediate_dirs(node.directory->data()); auto res = zeek::util::detail::ensure_intermediate_dirs(node.directory->data());
if ( ! res ) if ( ! res )
return zeek::util::fmt("failed to create working directory %s\n", return zeek::util::fmt("failed to create working directory %s\n",

View file

@ -47,7 +47,7 @@ void BasicThread::SetName(const char* arg_name)
void BasicThread::SetOSName(const char* arg_name) void BasicThread::SetOSName(const char* arg_name)
{ {
static_assert(std::is_same<std::thread::native_handle_type, pthread_t>::value, "libstdc++ doesn't use pthread_t"); static_assert(std::is_same<std::thread::native_handle_type, pthread_t>::value, "libstdc++ doesn't use pthread_t");
zeek::util::set_thread_name(arg_name, thread.native_handle()); zeek::util::detail::set_thread_name(arg_name, thread.native_handle());
} }
const char* BasicThread::Fmt(const char* format, ...) const char* BasicThread::Fmt(const char* format, ...)

View file

@ -182,7 +182,7 @@ bool Manager::SendEvent(MsgThread* thread, const std::string& name, const int nu
if ( convert_error ) if ( convert_error )
return false; return false;
else if ( handler ) else if ( handler )
zeek::event_mgr.Enqueue(handler, std::move(vl), zeek::util::SOURCE_LOCAL); zeek::event_mgr.Enqueue(handler, std::move(vl), zeek::util::detail::SOURCE_LOCAL);
return true; return true;
} }

File diff suppressed because it is too large Load diff

View file

@ -50,7 +50,6 @@
extern HeapLeakChecker* heap_checker; extern HeapLeakChecker* heap_checker;
#endif #endif
#include <stdint.h>
#include <pthread.h> #include <pthread.h>
#ifdef HAVE_LINUX #ifdef HAVE_LINUX
@ -140,96 +139,21 @@ inline int safe_vsnprintf(char* str, size_t size, const char* format, va_list al
extern "C" void out_of_memory(const char* where); extern "C" void out_of_memory(const char* where);
namespace zeek::util { namespace zeek::util {
namespace detail {
template <class T>
void delete_each(T* t)
{
typedef typename T::iterator iterator;
for ( iterator it = t->begin(); it != t->end(); ++it )
delete *it;
}
std::string extract_ip(const std::string& i); std::string extract_ip(const std::string& i);
std::string extract_ip_and_len(const std::string& i, int* len); std::string extract_ip_and_len(const std::string& i, int* len);
inline void bytetohex(unsigned char byte, char* hex_out)
{
static constexpr char hex_chars[] = "0123456789abcdef";
hex_out[0] = hex_chars[(byte & 0xf0) >> 4];
hex_out[1] = hex_chars[byte & 0x0f];
}
std::string get_unescaped_string(const std::string& str);
zeek::ODesc* get_escaped_string(zeek::ODesc* d, const char* str, size_t len,
bool escape_all);
std::string get_escaped_string(const char* str, size_t len, bool escape_all);
inline std::string get_escaped_string(const std::string& str, bool escape_all)
{
return get_escaped_string(str.data(), str.length(), escape_all);
}
std::vector<std::string>* tokenize_string(std::string_view input,
std::string_view delim,
std::vector<std::string>* rval = nullptr, int limit = 0);
std::vector<std::string_view> tokenize_string(std::string_view input, const char delim) noexcept;
extern char* copy_string(const char* s);
extern int streq(const char* s1, const char* s2);
// Returns the character corresponding to the given escape sequence (s points // Returns the character corresponding to the given escape sequence (s points
// just past the '\'), and updates s to point just beyond the last character // just past the '\'), and updates s to point just beyond the last character
// of the sequence. // of the sequence.
extern int expand_escape(const char*& s); extern int expand_escape(const char*& s);
extern char* skip_whitespace(char* s);
extern const char* skip_whitespace(const char* s);
extern char* skip_whitespace(char* s, char* end_of_s);
extern const char* skip_whitespace(const char* s, const char* end_of_s);
extern char* skip_digits(char* s);
extern char* get_word(char*& s);
extern void get_word(int length, const char* s, int& pwlen, const char*& pw);
extern void to_upper(char* s);
extern std::string to_upper(const std::string& s);
extern int decode_hex(char ch);
extern unsigned char encode_hex(int h);
extern const char* strpbrk_n(size_t len, const char* s, const char* charset);
template<class T> int atoi_n(int len, const char* s, const char** end, int base, T& result);
extern char* uitoa_n(uint64_t value, char* str, int n, int base, const char* prefix=nullptr);
int strstr_n(const int big_len, const unsigned char* big,
const int little_len, const unsigned char* little);
extern int fputs(int len, const char* s, FILE* fp);
extern bool is_printable(const char* s, int len);
// Return a lower-cased version of the string.
extern std::string strtolower(const std::string& s);
extern const char* fmt_bytes(const char* data, int len);
// Note: returns a pointer into a shared buffer.
extern const char* vfmt(const char* format, va_list args);
// Note: returns a pointer into a shared buffer.
extern const char* fmt(const char* format, ...)
__attribute__((format (printf, 1, 2)));
extern const char* fmt_access_time(double time); extern const char* fmt_access_time(double time);
extern bool ensure_intermediate_dirs(const char* dirname); extern bool ensure_intermediate_dirs(const char* dirname);
extern bool ensure_dir(const char *dirname); extern bool ensure_dir(const char *dirname);
// Returns true if path exists and is a directory.
bool is_dir(const std::string& path);
// Returns true if path exists and is a file.
bool is_file(const std::string& path);
// Replaces all occurences of *o* in *s* with *n*.
extern std::string strreplace(const std::string& s, const std::string& o, const std::string& n);
// Remove all leading and trailing white space from string.
extern std::string strstrip(std::string s);
extern void hmac_md5(size_t size, const unsigned char* bytes, extern void hmac_md5(size_t size, const unsigned char* bytes,
unsigned char digest[16]); unsigned char digest[16]);
@ -251,6 +175,46 @@ extern bool have_random_seed();
extern uint64_t rand64bit(); extern uint64_t rand64bit();
/**
* A platform-independent PRNG implementation. Note that this is not
* necessarily a "statistically sound" implementation as the main purpose is
* not for production use, but rather for regression testing.
* @param state The value used to generate the next random number.
* @return A new random value generated from *state* and that can passed
* back into subsequent calls to generate further random numbers.
*/
long int prng(long int state);
/**
* Wrapper for system random() in the default case, but when running in
* deterministic mode, uses the platform-independent zeek::prng()
* to obtain consistent results since implementations of rand() may vary.
* @return A value in the range [0, zeek::max_random()].
*/
long int random_number();
/**
* @return The maximum value that can be returned from zeek::random_number().
* When not using deterministic-mode, this is always equivalent to RAND_MAX.
*/
long int max_random();
/**
* Wrapper for system srandom() in the default case, but when running in
* deterministic mode, updates the state used for calling zeek::prng()
* inside of zeek::random_number().
* @param seed Value to use for initializing the PRNG.
*/
void seed_random(unsigned int seed);
/**
* Set the process/thread name. May not be supported on all OSs.
* @param name new name for the process/thread. OS limitations typically
* truncate the name to 15 bytes maximum.
* @param tid handle of thread whose name shall change
*/
void set_thread_name(const char* name, pthread_t tid = pthread_self());
// Each event source that may generate events gets an internally unique ID. // Each event source that may generate events gets an internally unique ID.
// This is always LOCAL for a local Bro. For remote event sources, it gets // This is always LOCAL for a local Bro. For remote event sources, it gets
// assigned by the RemoteSerializer. // assigned by the RemoteSerializer.
@ -261,23 +225,14 @@ extern uint64_t rand64bit();
using SourceID = std::uintptr_t; using SourceID = std::uintptr_t;
#define PRI_SOURCE_ID PRI_PTR_COMPAT_UINT #define PRI_SOURCE_ID PRI_PTR_COMPAT_UINT
static const SourceID SOURCE_LOCAL = 0; constexpr SourceID SOURCE_LOCAL = 0;
// TODO: This is a temporary marker to flag events coming in via Broker. // TODO: This is a temporary marker to flag events coming in via Broker.
// Those are remote events but we don't have any further peer informationa // Those are remote events but we don't have any further peer informationa
// available for them (as the old communication code would have). Once we // available for them (as the old communication code would have). Once we
// remove RemoteSerializer, we can turn the SourceID into a simple boolean // remove RemoteSerializer, we can turn the SourceID into a simple boolean
// indicating whether it's a local or remote event. // indicating whether it's a local or remote event.
static const SourceID SOURCE_BROKER = 0xffffffff; constexpr SourceID SOURCE_BROKER = 0xffffffff;
extern void pinpoint();
extern int int_list_cmp(const void* v1, const void* v2);
extern const std::string& zeek_path();
extern const char* zeek_magic_path();
extern const char* zeek_plugin_path();
extern const char* zeek_plugin_activate();
extern std::string zeek_prefixes();
extern const std::array<std::string, 2> script_extensions; extern const std::array<std::string, 2> script_extensions;
@ -288,7 +243,6 @@ bool is_package_loader(const std::string& path);
extern void add_to_zeek_path(const std::string& dir); extern void add_to_zeek_path(const std::string& dir);
/** /**
* Wrapper class for functions like dirname(3) or basename(3) that won't * Wrapper class for functions like dirname(3) or basename(3) that won't
* modify the path argument and may optionally abort execution on error. * modify the path argument and may optionally abort execution on error.
@ -309,31 +263,6 @@ protected:
}; };
class SafeDirname : public SafePathOp {
public:
explicit SafeDirname(const char* path, bool error_aborts = true);
explicit SafeDirname(const std::string& path, bool error_aborts = true);
private:
void DoFunc(const std::string& path, bool error_aborts = true);
};
class SafeBasename : public SafePathOp {
public:
explicit SafeBasename(const char* path, bool error_aborts = true);
explicit SafeBasename(const std::string& path, bool error_aborts = true);
private:
void DoFunc(const std::string& path, bool error_aborts = true);
};
std::string implode_string_vector(const std::vector<std::string>& v,
const std::string& delim = "\n");
/** /**
* Flatten a script name by replacing '/' path separators with '.'. * Flatten a script name by replacing '/' path separators with '.'.
* @param file A path to a Zeek script. If it is a __load__.zeek, that part * @param file A path to a Zeek script. If it is a __load__.zeek, that part
@ -367,6 +296,161 @@ std::string without_zeekpath_component(std::string_view path);
*/ */
std::string get_exe_path(const std::string& invocation); std::string get_exe_path(const std::string& invocation);
/** Opens a Zeek script package.
* @param path Location of a Zeek script package (a directory). Will be changed
* to the path of the package's loader script.
* @param mode An fopen(3) mode.
* @return The return value of fopen(3) on the loader script or null if one
* doesn't exist.
*/
FILE* open_package(std::string& path, const std::string& mode = "r");
// This mimics the script-level function with the same name.
const char* log_file_name(const char* tag);
// Terminates processing gracefully, similar to pressing CTRL-C.
void terminate_processing();
// Sets the current status of the Zeek process to the given string.
// If the option --status-file has been set, this is written into
// the the corresponding file. Otherwise, the function is a no-op.
void set_processing_status(const char* status, const char* reason);
// Renames the given file to a new temporary name, and opens a new file with
// the original name. Returns new file or NULL on error. Inits rotate_info if
// given (open time is set network time).
extern FILE* rotate_file(const char* name, zeek::RecordVal* rotate_info);
// Parse a time string of the form "HH:MM" (as used for the rotation base
// time) into a double representing the number of seconds. Returns -1 if the
// string cannot be parsed. The function's result is intended to be used with
// calc_next_rotate().
//
// This function is not thread-safe.
double parse_rotate_base_time(const char* rotate_base_time);
// Calculate the duration until the next time a file is to be rotated, based
// on the given rotate_interval and rotate_base_time. 'current' the the
// current time to be used as base, 'rotate_interval' the rotation interval,
// and 'base' the value returned by parse_rotate_base_time(). For the latter,
// if the function returned -1, that's fine, calc_next_rotate() handles that.
//
// This function is thread-safe.
double calc_next_rotate(double current, double rotate_interval, double base);
} // namespace detail
template <class T>
void delete_each(T* t)
{
typedef typename T::iterator iterator;
for ( iterator it = t->begin(); it != t->end(); ++it )
delete *it;
}
inline void bytetohex(unsigned char byte, char* hex_out)
{
static constexpr char hex_chars[] = "0123456789abcdef";
hex_out[0] = hex_chars[(byte & 0xf0) >> 4];
hex_out[1] = hex_chars[byte & 0x0f];
}
std::string get_unescaped_string(const std::string& str);
zeek::ODesc* get_escaped_string(zeek::ODesc* d, const char* str, size_t len,
bool escape_all);
std::string get_escaped_string(const char* str, size_t len, bool escape_all);
inline std::string get_escaped_string(const std::string& str, bool escape_all)
{
return get_escaped_string(str.data(), str.length(), escape_all);
}
std::vector<std::string>* tokenize_string(std::string_view input,
std::string_view delim,
std::vector<std::string>* rval = nullptr, int limit = 0);
std::vector<std::string_view> tokenize_string(std::string_view input, const char delim) noexcept;
extern char* copy_string(const char* s);
extern int streq(const char* s1, const char* s2);
extern char* skip_whitespace(char* s);
extern const char* skip_whitespace(const char* s);
extern char* skip_whitespace(char* s, char* end_of_s);
extern const char* skip_whitespace(const char* s, const char* end_of_s);
extern char* skip_digits(char* s);
extern char* get_word(char*& s);
extern void get_word(int length, const char* s, int& pwlen, const char*& pw);
extern void to_upper(char* s);
extern std::string to_upper(const std::string& s);
extern int decode_hex(char ch);
extern unsigned char encode_hex(int h);
template<class T> int atoi_n(int len, const char* s, const char** end, int base, T& result);
extern char* uitoa_n(uint64_t value, char* str, int n, int base, const char* prefix=nullptr);
extern const char* strpbrk_n(size_t len, const char* s, const char* charset);
int strstr_n(const int big_len, const unsigned char* big,
const int little_len, const unsigned char* little);
// Replaces all occurences of *o* in *s* with *n*.
extern std::string strreplace(const std::string& s, const std::string& o, const std::string& n);
// Remove all leading and trailing white space from string.
extern std::string strstrip(std::string s);
// Return a lower-cased version of the string.
extern std::string strtolower(const std::string& s);
extern int fputs(int len, const char* s, FILE* fp);
extern bool is_printable(const char* s, int len);
extern const char* fmt_bytes(const char* data, int len);
// Note: returns a pointer into a shared buffer.
extern const char* vfmt(const char* format, va_list args);
// Note: returns a pointer into a shared buffer.
extern const char* fmt(const char* format, ...)
__attribute__((format (printf, 1, 2)));
// Returns true if path exists and is a directory.
bool is_dir(const std::string& path);
// Returns true if path exists and is a file.
bool is_file(const std::string& path);
extern int int_list_cmp(const void* v1, const void* v2);
extern const std::string& zeek_path();
extern const char* zeek_magic_path();
extern const char* zeek_plugin_path();
extern const char* zeek_plugin_activate();
extern std::string zeek_prefixes();
class SafeDirname : public detail::SafePathOp {
public:
explicit SafeDirname(const char* path, bool error_aborts = true);
explicit SafeDirname(const std::string& path, bool error_aborts = true);
private:
void DoFunc(const std::string& path, bool error_aborts = true);
};
class SafeBasename : public detail::SafePathOp {
public:
explicit SafeBasename(const char* path, bool error_aborts = true);
explicit SafeBasename(const std::string& path, bool error_aborts = true);
private:
void DoFunc(const std::string& path, bool error_aborts = true);
};
std::string implode_string_vector(const std::vector<std::string>& v,
const std::string& delim = "\n");
/** /**
* Locate a file within a given search path. * Locate a file within a given search path.
* @param filename Name of a file to find. * @param filename Name of a file to find.
@ -388,48 +472,6 @@ std::string find_script_file(const std::string& filename, const std::string& pat
// Wrapper around fopen(3). Emits an error when failing to open. // Wrapper around fopen(3). Emits an error when failing to open.
FILE* open_file(const std::string& path, const std::string& mode = "r"); FILE* open_file(const std::string& path, const std::string& mode = "r");
/** Opens a Zeek script package.
* @param path Location of a Zeek script package (a directory). Will be changed
* to the path of the package's loader script.
* @param mode An fopen(3) mode.
* @return The return value of fopen(3) on the loader script or null if one
* doesn't exist.
*/
FILE* open_package(std::string& path, const std::string& mode = "r");
// Renames the given file to a new temporary name, and opens a new file with
// the original name. Returns new file or NULL on error. Inits rotate_info if
// given (open time is set network time).
extern FILE* rotate_file(const char* name, zeek::RecordVal* rotate_info);
// This mimics the script-level function with the same name.
const char* log_file_name(const char* tag);
// Parse a time string of the form "HH:MM" (as used for the rotation base
// time) into a double representing the number of seconds. Returns -1 if the
// string cannot be parsed. The function's result is intended to be used with
// calc_next_rotate().
//
// This function is not thread-safe.
double parse_rotate_base_time(const char* rotate_base_time);
// Calculate the duration until the next time a file is to be rotated, based
// on the given rotate_interval and rotate_base_time. 'current' the the
// current time to be used as base, 'rotate_interval' the rotation interval,
// and 'base' the value returned by parse_rotate_base_time(). For the latter,
// if the function returned -1, that's fine, calc_next_rotate() handles that.
//
// This function is thread-safe.
double calc_next_rotate(double current, double rotate_interval, double base);
// Terminates processing gracefully, similar to pressing CTRL-C.
void terminate_processing();
// Sets the current status of the Zeek process to the given string.
// If the option --status-file has been set, this is written into
// the the corresponding file. Otherwise, the function is a no-op.
void set_processing_status(const char* status, const char* reason);
// Returns the current time. // Returns the current time.
// (In pseudo-realtime mode this is faked to be the start time of the // (In pseudo-realtime mode this is faked to be the start time of the
// trace plus the time interval Zeek has been running. To avoid this, // trace plus the time interval Zeek has been running. To avoid this,
@ -452,17 +494,6 @@ extern int time_compare(struct timeval* tv_a, struct timeval* tv_b);
extern uint64_t calculate_unique_id(); extern uint64_t calculate_unique_id();
extern uint64_t calculate_unique_id(const size_t pool); extern uint64_t calculate_unique_id(const size_t pool);
// For now, don't use hash_maps - they're not fully portable.
#if 0
// Use for hash_map's string keys.
struct eqstr {
bool operator()(const char* s1, const char* s2) const
{
return strcmp(s1, s2) == 0;
}
};
#endif
// Use for map's string keys. // Use for map's string keys.
struct ltstr { struct ltstr {
bool operator()(const char* s1, const char* s2) const bool operator()(const char* s1, const char* s2) const
@ -471,8 +502,6 @@ struct ltstr {
} }
}; };
// Versions of realloc/malloc which abort() on out of memory
constexpr size_t pad_size(size_t size) constexpr size_t pad_size(size_t size)
{ {
// We emulate glibc here (values measured on Linux i386). // We emulate glibc here (values measured on Linux i386).
@ -503,6 +532,8 @@ extern void safe_close(int fd);
// Versions of realloc/malloc which abort() on out of memory // Versions of realloc/malloc which abort() on out of memory
// Versions of realloc/malloc which abort() on out of memory
inline void* safe_realloc(void* ptr, size_t size) inline void* safe_realloc(void* ptr, size_t size)
{ {
ptr = realloc(ptr, size); ptr = realloc(ptr, size);
@ -571,46 +602,6 @@ char* zeekenv(const char* name);
*/ */
std::string json_escape_utf8(const std::string& val); std::string json_escape_utf8(const std::string& val);
/**
* Set the process/thread name. May not be supported on all OSs.
* @param name new name for the process/thread. OS limitations typically
* truncate the name to 15 bytes maximum.
* @param tid handle of thread whose name shall change
*/
void set_thread_name(const char* name, pthread_t tid = pthread_self());
/**
* A platform-independent PRNG implementation. Note that this is not
* necessarily a "statistically sound" implementation as the main purpose is
* not for production use, but rather for regression testing.
* @param state The value used to generate the next random number.
* @return A new random value generated from *state* and that can passed
* back into subsequent calls to generate further random numbers.
*/
long int prng(long int state);
/**
* Wrapper for system random() in the default case, but when running in
* deterministic mode, uses the platform-independent zeek::prng()
* to obtain consistent results since implementations of rand() may vary.
* @return A value in the range [0, zeek::max_random()].
*/
long int random_number();
/**
* @return The maximum value that can be returned from zeek::random_number().
* When not using deterministic-mode, this is always equivalent to RAND_MAX.
*/
long int max_random();
/**
* Wrapper for system srandom() in the default case, but when running in
* deterministic mode, updates the state used for calling zeek::prng()
* inside of zeek::random_number().
* @param seed Value to use for initializing the PRNG.
*/
void seed_random(unsigned int seed);
} // namespace zeek::util } // namespace zeek::util
// A simple linear congruence PRNG. It takes its state as argument and // A simple linear congruence PRNG. It takes its state as argument and
@ -632,8 +623,8 @@ template<class T>
[[ deprecated("Remove in v4.1. Use zeek::util::delete_each.")]] [[ deprecated("Remove in v4.1. Use zeek::util::delete_each.")]]
void delete_each(T* t) { zeek::util::delete_each<T>(t); } void delete_each(T* t) { zeek::util::delete_each<T>(t); }
constexpr auto extract_ip [[deprecated("Remove in v4.1. Use zeek::util::extract_ip.")]] = zeek::util::extract_ip; constexpr auto extract_ip [[deprecated("Remove in v4.1. Use zeek::util::detail::extract_ip.")]] = zeek::util::detail::extract_ip;
constexpr auto extract_ip_and_len [[deprecated("Remove in v4.1. Use zeek::util::extract_ip_and_len.")]] = zeek::util::extract_ip_and_len; constexpr auto extract_ip_and_len [[deprecated("Remove in v4.1. Use zeek::util::detail::extract_ip_and_len.")]] = zeek::util::detail::extract_ip_and_len;
constexpr auto bytetohex [[deprecated("Remove in v4.1. Use zeek::util::bytetohex.")]] = zeek::util::bytetohex; constexpr auto bytetohex [[deprecated("Remove in v4.1. Use zeek::util::bytetohex.")]] = zeek::util::bytetohex;
constexpr auto get_unescaped_string [[deprecated("Remove in v4.1. Use zeek::util::get_unescaped_string.")]] = zeek::util::get_unescaped_string; constexpr auto get_unescaped_string [[deprecated("Remove in v4.1. Use zeek::util::get_unescaped_string.")]] = zeek::util::get_unescaped_string;
@ -652,7 +643,7 @@ std::vector<std::string_view> tokenize_string(std::string_view input, const char
constexpr auto copy_string [[deprecated("Remove in v4.1. Use zeek::util::copy_string.")]] = zeek::util::copy_string; constexpr auto copy_string [[deprecated("Remove in v4.1. Use zeek::util::copy_string.")]] = zeek::util::copy_string;
constexpr auto streq [[deprecated("Remove in v4.1. Use zeek::util::streq.")]] = zeek::util::streq; constexpr auto streq [[deprecated("Remove in v4.1. Use zeek::util::streq.")]] = zeek::util::streq;
constexpr auto expand_escape [[deprecated("Remove in v4.1. Use zeek::util::expand_escape.")]] = zeek::util::expand_escape; constexpr auto expand_escape [[deprecated("Remove in v4.1. Use zeek::util::detail::expand_escape.")]] = zeek::util::detail::expand_escape;
constexpr auto skip_digits [[deprecated("Remove in v4.1. Use zeek::util::skip_digits.")]] = zeek::util::skip_digits; constexpr auto skip_digits [[deprecated("Remove in v4.1. Use zeek::util::skip_digits.")]] = zeek::util::skip_digits;
[[deprecated("Remove in v4.1. Use zeek::util::skip_whitespace.")]] [[deprecated("Remove in v4.1. Use zeek::util::skip_whitespace.")]]
@ -677,6 +668,8 @@ constexpr auto decode_hex [[deprecated("Remove in v4.1. Use zeek::util::decode_h
constexpr auto encode_hex [[deprecated("Remove in v4.1. Use zeek::util::encode_hex.")]] = zeek::util::encode_hex; constexpr auto encode_hex [[deprecated("Remove in v4.1. Use zeek::util::encode_hex.")]] = zeek::util::encode_hex;
constexpr auto strpbrk_n [[deprecated("Remove in v4.1. Use zeek::util::strpbrk_n.")]] = zeek::util::strpbrk_n; constexpr auto strpbrk_n [[deprecated("Remove in v4.1. Use zeek::util::strpbrk_n.")]] = zeek::util::strpbrk_n;
constexpr auto strstr_n [[deprecated("Remove in v4.1. Use zeek::util::strstr_n.")]] = zeek::util::strstr_n; constexpr auto strstr_n [[deprecated("Remove in v4.1. Use zeek::util::strstr_n.")]] = zeek::util::strstr_n;
constexpr auto strreplace [[deprecated("Remove in v4.1. Use zeek::util::strreplace.")]] = zeek::util::strreplace;
constexpr auto strstrip [[deprecated("Remove in v4.1. Use zeek::util::strstrip.")]] = zeek::util::strstrip;
template<class T> template<class T>
[[deprecated("Remove in v4.1. Use zeek::util::atoi_n.")]] [[deprecated("Remove in v4.1. Use zeek::util::atoi_n.")]]
@ -694,24 +687,21 @@ constexpr auto strtolower [[deprecated("Remove in v4.1. Use zeek::util::strtolow
constexpr auto fmt_bytes [[deprecated("Remove in v4.1. Use zeek::util::fmt_bytes.")]] = zeek::util::fmt_bytes; constexpr auto fmt_bytes [[deprecated("Remove in v4.1. Use zeek::util::fmt_bytes.")]] = zeek::util::fmt_bytes;
constexpr auto vfmt [[deprecated("Remove in v4.1. Use zeek::util::vfmt.")]] = zeek::util::vfmt; constexpr auto vfmt [[deprecated("Remove in v4.1. Use zeek::util::vfmt.")]] = zeek::util::vfmt;
constexpr auto fmt [[deprecated("Remove in v4.1. Use zeek::util::fmt.")]] = zeek::util::fmt; constexpr auto fmt [[deprecated("Remove in v4.1. Use zeek::util::fmt.")]] = zeek::util::fmt;
constexpr auto fmt_access_time [[deprecated("Remove in v4.1. Use zeek::util::fmt_access_time.")]] = zeek::util::fmt_access_time; constexpr auto fmt_access_time [[deprecated("Remove in v4.1. Use zeek::util::detail::fmt_access_time.")]] = zeek::util::detail::fmt_access_time;
constexpr auto ensure_intermediate_dirs [[deprecated("Remove in v4.1. Use zeek::util::ensure_intermediate_dirs.")]] = zeek::util::ensure_intermediate_dirs; constexpr auto ensure_intermediate_dirs [[deprecated("Remove in v4.1. Use zeek::util::detail::ensure_intermediate_dirs.")]] = zeek::util::detail::ensure_intermediate_dirs;
constexpr auto ensure_dir [[deprecated("Remove in v4.1. Use zeek::util::ensure_dir.")]] = zeek::util::ensure_dir; constexpr auto ensure_dir [[deprecated("Remove in v4.1. Use zeek::util::detail::ensure_dir.")]] = zeek::util::detail::ensure_dir;
constexpr auto is_dir [[deprecated("Remove in v4.1. Use zeek::util::is_dir.")]] = zeek::util::is_dir; constexpr auto is_dir [[deprecated("Remove in v4.1. Use zeek::util::is_dir.")]] = zeek::util::is_dir;
constexpr auto is_file [[deprecated("Remove in v4.1. Use zeek::util::is_file.")]] = zeek::util::is_file; constexpr auto is_file [[deprecated("Remove in v4.1. Use zeek::util::is_file.")]] = zeek::util::is_file;
constexpr auto strreplace [[deprecated("Remove in v4.1. Use zeek::util::strreplace.")]] = zeek::util::strreplace; constexpr auto hmac_md5 [[deprecated("Remove in v4.1. Use zeek::util::detail::hmac_md5.")]] = zeek::util::detail::hmac_md5;
constexpr auto strstrip [[deprecated("Remove in v4.1. Use zeek::util::strstrip.")]] = zeek::util::strstrip; constexpr auto init_random_seed [[deprecated("Remove in v4.1. Use zeek::util::detail::init_random_seed.")]] = zeek::util::detail::init_random_seed;
constexpr auto hmac_md5 [[deprecated("Remove in v4.1. Use zeek::util::hmac_md5.")]] = zeek::util::hmac_md5; constexpr auto initial_seed [[deprecated("Remove in v4.1. Use zeek::util::detail::initial_seed.")]] = zeek::util::detail::initial_seed;
constexpr auto init_random_seed [[deprecated("Remove in v4.1. Use zeek::util::init_random_seed.")]] = zeek::util::init_random_seed; constexpr auto have_random_seed [[deprecated("Remove in v4.1. Use zeek::util::detail::have_random_seed.")]] = zeek::util::detail::have_random_seed;
constexpr auto initial_seed [[deprecated("Remove in v4.1. Use zeek::util::initial_seed.")]] = zeek::util::initial_seed; constexpr auto rand64bit [[deprecated("Remove in v4.1. Use zeek::util::detail::rand64bit.")]] = zeek::util::detail::rand64bit;
constexpr auto have_random_seed [[deprecated("Remove in v4.1. Use zeek::util::have_random_seed.")]] = zeek::util::have_random_seed;
constexpr auto rand64bit [[deprecated("Remove in v4.1. Use zeek::util::rand64bit.")]] = zeek::util::rand64bit;
using SourceID [[deprecated("Remove in v4.1. Use zeek::util::SourceID.")]] = zeek::util::SourceID; using SourceID [[deprecated("Remove in v4.1. Use zeek::util::detail::SourceID.")]] = zeek::util::detail::SourceID;
static const zeek::util::SourceID SOURCE_LOCAL [[deprecated("Remove in v4.1. Use zeek::util::SOURCE_LOCAL.")]] = zeek::util::SOURCE_LOCAL; static const zeek::util::detail::SourceID SOURCE_LOCAL [[deprecated("Remove in v4.1. Use zeek::util::detail::SOURCE_LOCAL.")]] = zeek::util::detail::SOURCE_LOCAL;
static const zeek::util::SourceID SOURCE_BROKER [[deprecated("Remove in v4.1. Use zeek::util::SOURCE_BROKER.")]] = zeek::util::SOURCE_BROKER; static const zeek::util::detail::SourceID SOURCE_BROKER [[deprecated("Remove in v4.1. Use zeek::util::detail::SOURCE_BROKER.")]] = zeek::util::detail::SOURCE_BROKER;
constexpr auto pinpoint [[deprecated("Remove in v4.1. Use zeek::util::pinpoint.")]] = zeek::util::pinpoint;
constexpr auto int_list_cmp [[deprecated("Remove in v4.1. Use zeek::util::int_list_cmp.")]] = zeek::util::int_list_cmp; constexpr auto int_list_cmp [[deprecated("Remove in v4.1. Use zeek::util::int_list_cmp.")]] = zeek::util::int_list_cmp;
constexpr auto bro_path [[deprecated("Remove in v4.1. Use zeek::util::zeek_path.")]] = zeek::util::zeek_path; constexpr auto bro_path [[deprecated("Remove in v4.1. Use zeek::util::zeek_path.")]] = zeek::util::zeek_path;
constexpr auto bro_magic_path [[deprecated("Remove in v4.1. Use zeek::util::zeek_magic_path.")]] = zeek::util::zeek_magic_path; constexpr auto bro_magic_path [[deprecated("Remove in v4.1. Use zeek::util::zeek_magic_path.")]] = zeek::util::zeek_magic_path;
@ -719,13 +709,13 @@ constexpr auto bro_plugin_path [[deprecated("Remove in v4.1. Use zeek::util::zee
constexpr auto bro_plugin_activate [[deprecated("Remove in v4.1. Use zeek::util::zeek_plugin_activate.")]] = zeek::util::zeek_plugin_activate; constexpr auto bro_plugin_activate [[deprecated("Remove in v4.1. Use zeek::util::zeek_plugin_activate.")]] = zeek::util::zeek_plugin_activate;
constexpr auto bro_prefixes [[deprecated("Remove in v4.1. Use zeek::util::zeek_prefixes.")]] = zeek::util::zeek_prefixes; constexpr auto bro_prefixes [[deprecated("Remove in v4.1. Use zeek::util::zeek_prefixes.")]] = zeek::util::zeek_prefixes;
extern const std::array<std::string, 2>& script_extensions [[deprecated("Remove in v4.1. Use zeek::util::script_extensions.")]]; extern const std::array<std::string, 2>& script_extensions [[deprecated("Remove in v4.1. Use zeek::util::detail::script_extensions.")]];
constexpr auto warn_if_legacy_script [[deprecated("Remove in v4.1. Use zeek::util::warn_if_legacy_script.")]] = zeek::util::warn_if_legacy_script; constexpr auto warn_if_legacy_script [[deprecated("Remove in v4.1. Use zeek::util::detail::warn_if_legacy_script.")]] = zeek::util::detail::warn_if_legacy_script;
constexpr auto is_package_loader [[deprecated("Remove in v4.1. Use zeek::util::is_package_loader.")]] = zeek::util::is_package_loader; constexpr auto is_package_loader [[deprecated("Remove in v4.1. Use zeek::util::detail::is_package_loader.")]] = zeek::util::detail::is_package_loader;
constexpr auto add_to_bro_path [[deprecated("Remove in v4.1. Use zeek::util::add_to_zeek_path.")]] = zeek::util::add_to_zeek_path; constexpr auto add_to_bro_path [[deprecated("Remove in v4.1. Use zeek::util::detail::add_to_zeek_path.")]] = zeek::util::detail::add_to_zeek_path;
using SafePathOp [[deprecated("Remove in v4.1. Use zeek::util::SafePathOp.")]] = zeek::util::SafePathOp; using SafePathOp [[deprecated("Remove in v4.1. Use zeek::util::detail::SafePathOp.")]] = zeek::util::detail::SafePathOp;
using SafeDirname [[deprecated("Remove in v4.1. Use zeek::util::SafeDirname.")]] = zeek::util::SafeDirname; using SafeDirname [[deprecated("Remove in v4.1. Use zeek::util::SafeDirname.")]] = zeek::util::SafeDirname;
using SafeBasename [[deprecated("Remove in v4.1. Use zeek::util::SafeBasename.")]] = zeek::util::SafeBasename; using SafeBasename [[deprecated("Remove in v4.1. Use zeek::util::SafeBasename.")]] = zeek::util::SafeBasename;
@ -736,9 +726,9 @@ std::string implode_string_vector(const std::vector<std::string>& v,
std::string flatten_script_name(const std::string& name, std::string flatten_script_name(const std::string& name,
const std::string& prefix = ""); const std::string& prefix = "");
constexpr auto normalize_path [[deprecated("Remove in v4.1. Use zeek::util::normalize_path.")]] = zeek::util::normalize_path; constexpr auto normalize_path [[deprecated("Remove in v4.1. Use zeek::util::detail::normalize_path.")]] = zeek::util::detail::normalize_path;
constexpr auto without_bropath_component [[deprecated("Remove in v4.1. Use zeek::util::without_zeekpath_component.")]] = zeek::util::without_zeekpath_component; constexpr auto without_bropath_component [[deprecated("Remove in v4.1. Use zeek::util::detail::without_zeekpath_component.")]] = zeek::util::detail::without_zeekpath_component;
constexpr auto get_exe_path [[deprecated("Remove in v4.1. Use zeek::util::get_exe_path.")]] = zeek::util::get_exe_path; constexpr auto get_exe_path [[deprecated("Remove in v4.1. Use zeek::util::detail::get_exe_path.")]] = zeek::util::detail::get_exe_path;
constexpr auto find_script_file [[deprecated("Remove in v4.1. Use zeek::util::find_script_file.")]] = zeek::util::find_script_file; constexpr auto find_script_file [[deprecated("Remove in v4.1. Use zeek::util::find_script_file.")]] = zeek::util::find_script_file;
[[deprecated("Remove in v4.1. Use zeek::util::find_file.")]] [[deprecated("Remove in v4.1. Use zeek::util::find_file.")]]
@ -749,12 +739,12 @@ FILE* open_file(const std::string& path, const std::string& mode = "r");
[[deprecated("Remove in v4.1. Use zeek::util::open_package.")]] [[deprecated("Remove in v4.1. Use zeek::util::open_package.")]]
FILE* open_package(std::string& path, const std::string& mode = "r"); FILE* open_package(std::string& path, const std::string& mode = "r");
constexpr auto rotate_file [[deprecated("Remove in v4.1. Use zeek::util::rotate_file.")]] = zeek::util::rotate_file; constexpr auto rotate_file [[deprecated("Remove in v4.1. Use zeek::util::detail::rotate_file.")]] = zeek::util::detail::rotate_file;
constexpr auto log_file_name [[deprecated("Remove in v4.1. Use zeek::util::log_file_name.")]] = zeek::util::log_file_name; constexpr auto log_file_name [[deprecated("Remove in v4.1. Use zeek::util::detail::log_file_name.")]] = zeek::util::detail::log_file_name;
constexpr auto parse_rotate_base_time [[deprecated("Remove in v4.1. Use zeek::util::parse_rotate_base_time.")]] = zeek::util::parse_rotate_base_time; constexpr auto parse_rotate_base_time [[deprecated("Remove in v4.1. Use zeek::util::detail::parse_rotate_base_time.")]] = zeek::util::detail::parse_rotate_base_time;
constexpr auto calc_next_rotate [[deprecated("Remove in v4.1. Use zeek::util::calc_next_rotate.")]] = zeek::util::calc_next_rotate; constexpr auto calc_next_rotate [[deprecated("Remove in v4.1. Use zeek::util::detail::calc_next_rotate.")]] = zeek::util::detail::calc_next_rotate;
constexpr auto terminate_processing [[deprecated("Remove in v4.1. Use zeek::util::terminate_processing.")]] = zeek::util::terminate_processing; constexpr auto terminate_processing [[deprecated("Remove in v4.1. Use zeek::util::detail::terminate_processing.")]] = zeek::util::detail::terminate_processing;
constexpr auto set_processing_status [[deprecated("Remove in v4.1. Use zeek::util::set_processing_status.")]] = zeek::util::set_processing_status; constexpr auto set_processing_status [[deprecated("Remove in v4.1. Use zeek::util::detail::set_processing_status.")]] = zeek::util::detail::set_processing_status;
[[deprecated("Remove in v4.1. Use zeek::util::current_time.")]] [[deprecated("Remove in v4.1. Use zeek::util::current_time.")]]
extern double current_time(bool real=false); extern double current_time(bool real=false);
@ -786,8 +776,8 @@ namespace zeek {
[[deprecated("Remove in v4.1. Use zeek::util::set_thread_name.")]] [[deprecated("Remove in v4.1. Use zeek::util::set_thread_name.")]]
void set_thread_name(const char* name, pthread_t tid = pthread_self()); void set_thread_name(const char* name, pthread_t tid = pthread_self());
constexpr auto prng [[deprecated("Remove in v4.1. Use zeek::util::prng.")]] = zeek::util::prng; constexpr auto prng [[deprecated("Remove in v4.1. Use zeek::util::detail::prng.")]] = zeek::util::detail::prng;
constexpr auto random_number [[deprecated("Remove in v4.1. Use zeek::util::random_number.")]] = zeek::util::random_number; constexpr auto random_number [[deprecated("Remove in v4.1. Use zeek::util::detail::random_number.")]] = zeek::util::detail::random_number;
constexpr auto max_random [[deprecated("Remove in v4.1. Use zeek::util::max_random.")]] = zeek::util::max_random; constexpr auto max_random [[deprecated("Remove in v4.1. Use zeek::util::detail::max_random.")]] = zeek::util::detail::max_random;
constexpr auto seed_random [[deprecated("Remove in v4.1. Use zeek::util::seed_random.")]] = zeek::util::seed_random; constexpr auto seed_random [[deprecated("Remove in v4.1. Use zeek::util::detail::seed_random.")]] = zeek::util::detail::seed_random;
} }

View file

@ -233,7 +233,7 @@ bool show_plugins(int level)
void done_with_network() void done_with_network()
{ {
zeek::util::set_processing_status("TERMINATING", "done_with_network"); zeek::util::detail::set_processing_status("TERMINATING", "done_with_network");
// Cancel any pending alarms (watchdog, in particular). // Cancel any pending alarms (watchdog, in particular).
(void) alarm(0); (void) alarm(0);
@ -280,7 +280,7 @@ void done_with_network()
void terminate_bro() void terminate_bro()
{ {
zeek::util::set_processing_status("TERMINATING", "terminate_bro"); zeek::util::detail::set_processing_status("TERMINATING", "terminate_bro");
zeek::net::terminating = true; zeek::net::terminating = true;
@ -342,7 +342,7 @@ namespace zeek::net::detail {
void zeek_terminate_loop(const char* reason) void zeek_terminate_loop(const char* reason)
{ {
zeek::util::set_processing_status("TERMINATING", reason); zeek::util::detail::set_processing_status("TERMINATING", reason);
zeek::reporter->Info("%s", reason); zeek::reporter->Info("%s", reason);
net_get_final_stats(); net_get_final_stats();
@ -364,7 +364,7 @@ void zeek_terminate_loop(const char* reason)
RETSIGTYPE sig_handler(int signo) RETSIGTYPE sig_handler(int signo)
{ {
zeek::util::set_processing_status("TERMINATING", "sig_handler"); zeek::util::detail::set_processing_status("TERMINATING", "sig_handler");
signal_val = signo; signal_val = signo;
if ( ! zeek::net::terminating ) if ( ! zeek::net::terminating )
@ -375,7 +375,7 @@ RETSIGTYPE sig_handler(int signo)
static void atexit_handler() static void atexit_handler()
{ {
zeek::util::set_processing_status("TERMINATED", "atexit"); zeek::util::detail::set_processing_status("TERMINATED", "atexit");
} }
static void bro_new_handler() static void bro_new_handler()
@ -407,7 +407,7 @@ zeek::detail::SetupResult zeek::detail::setup(int argc, char** argv,
ZEEK_LSAN_DISABLE(); ZEEK_LSAN_DISABLE();
std::set_new_handler(bro_new_handler); std::set_new_handler(bro_new_handler);
auto zeek_exe_path = zeek::util::get_exe_path(argv[0]); auto zeek_exe_path = zeek::util::detail::get_exe_path(argv[0]);
if ( zeek_exe_path.empty() ) if ( zeek_exe_path.empty() )
{ {
@ -487,7 +487,7 @@ zeek::detail::SetupResult zeek::detail::setup(int argc, char** argv,
proc_status_file = zeek::util::copy_string(options.process_status_file->data()); proc_status_file = zeek::util::copy_string(options.process_status_file->data());
atexit(atexit_handler); atexit(atexit_handler);
zeek::util::set_processing_status("INITIALIZING", "main"); zeek::util::detail::set_processing_status("INITIALIZING", "main");
zeek::net::zeek_start_time = zeek::util::current_time(true); zeek::net::zeek_start_time = zeek::util::current_time(true);
@ -521,9 +521,9 @@ zeek::detail::SetupResult zeek::detail::setup(int argc, char** argv,
if ( options.random_seed_input_file ) if ( options.random_seed_input_file )
seed_load_file = options.random_seed_input_file->data(); seed_load_file = options.random_seed_input_file->data();
zeek::util::init_random_seed((seed_load_file && *seed_load_file ? seed_load_file : nullptr), zeek::util::detail::init_random_seed((seed_load_file && *seed_load_file ? seed_load_file : nullptr),
options.random_seed_output_file ? options.random_seed_output_file->data() : nullptr, options.random_seed_output_file ? options.random_seed_output_file->data() : nullptr,
options.deterministic_mode); options.deterministic_mode);
// DEBUG_MSG("HMAC key: %s\n", md5_digest_print(shared_hmac_md5_key)); // DEBUG_MSG("HMAC key: %s\n", md5_digest_print(shared_hmac_md5_key));
init_hash_function(); init_hash_function();

View file

@ -391,7 +391,7 @@ function terminate%(%): bool
if ( zeek::net::terminating ) if ( zeek::net::terminating )
return zeek::val_mgr->False(); return zeek::val_mgr->False();
zeek::util::terminate_processing(); zeek::util::detail::terminate_processing();
return zeek::val_mgr->True(); return zeek::val_mgr->True();
%} %}
@ -930,7 +930,7 @@ function hrw_weight%(key_digest: count, site_id: count%): count
## provided by the OS. ## provided by the OS.
function rand%(max: count%): count function rand%(max: count%): count
%{ %{
auto result = bro_uint_t(double(max) * double(zeek::util::random_number()) / (zeek::util::max_random() + 1.0)); auto result = bro_uint_t(double(max) * double(zeek::util::detail::random_number()) / (zeek::util::detail::max_random() + 1.0));
return zeek::val_mgr->Count(result); return zeek::val_mgr->Count(result);
%} %}
@ -946,7 +946,7 @@ function rand%(max: count%): count
## provided by the OS. ## provided by the OS.
function srand%(seed: count%): any function srand%(seed: count%): any
%{ %{
zeek::util::seed_random(seed); zeek::util::detail::seed_random(seed);
return nullptr; return nullptr;
%} %}
@ -4712,7 +4712,7 @@ function rotate_file_by_name%(f: string%): rotate_info
addl_pkt_dumper->Close(); addl_pkt_dumper->Close();
} }
FILE* file = zeek::util::rotate_file(f->CheckString(), info.get()); FILE* file = zeek::util::detail::rotate_file(f->CheckString(), info.get());
if ( ! file ) if ( ! file )
{ {
// Record indicating error. // Record indicating error.
@ -4750,8 +4750,8 @@ function calc_next_rotate%(i: interval%) : interval
static auto log_rotate_base_time = zeek::id::find_val<zeek::StringVal>("log_rotate_base_time"); static auto log_rotate_base_time = zeek::id::find_val<zeek::StringVal>("log_rotate_base_time");
static auto base_time = log_rotate_base_time->AsString()->CheckString(); static auto base_time = log_rotate_base_time->AsString()->CheckString();
double base = zeek::util::parse_rotate_base_time(base_time); double base = zeek::util::detail::parse_rotate_base_time(base_time);
return zeek::make_intrusive<zeek::IntervalVal>(zeek::util::calc_next_rotate(zeek::net::network_time, i, base)); return zeek::make_intrusive<zeek::IntervalVal>(zeek::util::detail::calc_next_rotate(zeek::net::network_time, i, base));
%} %}
## Returns the size of a given file. ## Returns the size of a given file.
@ -4999,7 +4999,7 @@ function uninstall_dst_net_filter%(snet: subnet%) : bool
## Returns: True if the last raised event came from a remote peer. ## Returns: True if the last raised event came from a remote peer.
function is_remote_event%(%) : bool function is_remote_event%(%) : bool
%{ %{
return zeek::val_mgr->Bool(zeek::event_mgr.CurrentSource() != zeek::util::SOURCE_LOCAL); return zeek::val_mgr->Bool(zeek::event_mgr.CurrentSource() != zeek::util::detail::SOURCE_LOCAL);
%} %}
## Stops Zeek's packet processing. This function is used to synchronize ## Stops Zeek's packet processing. This function is used to synchronize
@ -5169,5 +5169,5 @@ function to_json%(val: any, only_loggable: bool &default=F, field_escape_pattern
## Returns: a compressed version of the input path. ## Returns: a compressed version of the input path.
function compress_path%(dir: string%): string function compress_path%(dir: string%): string
%{ %{
return zeek::make_intrusive<zeek::StringVal>(zeek::util::normalize_path(dir->ToStdString())); return zeek::make_intrusive<zeek::StringVal>(zeek::util::detail::normalize_path(dir->ToStdString()));
%} %}

View file

@ -58,12 +58,12 @@ static string NormalizeScriptPath(const string& path)
{ {
if ( auto p = zeek::plugin_mgr->LookupPluginByPath(path) ) if ( auto p = zeek::plugin_mgr->LookupPluginByPath(path) )
{ {
auto rval = zeek::util::normalize_path(path); auto rval = zeek::util::detail::normalize_path(path);
auto prefix = zeek::util::SafeBasename(p->PluginDirectory()).result; auto prefix = zeek::util::SafeBasename(p->PluginDirectory()).result;
return prefix + "/" + rval.substr(p->PluginDirectory().size() + 1); return prefix + "/" + rval.substr(p->PluginDirectory().size() + 1);
} }
return zeek::util::without_zeekpath_component(path); return zeek::util::detail::without_zeekpath_component(path);
} }
Manager::Manager(const string& arg_config, const string& bro_command) Manager::Manager(const string& arg_config, const string& bro_command)

View file

@ -162,7 +162,7 @@ static string make_redef_details(const string& heading, char underline,
ScriptInfo::ScriptInfo(const string& arg_name, const string& arg_path) ScriptInfo::ScriptInfo(const string& arg_name, const string& arg_path)
: Info(), : Info(),
name(arg_name), path(arg_path), name(arg_name), path(arg_path),
is_pkg_loader(zeek::util::is_package_loader(name)), is_pkg_loader(zeek::util::detail::is_package_loader(name)),
dependencies(), module_usages(), comments(), id_info(), dependencies(), module_usages(), comments(), id_info(),
redef_options(), constants(), state_vars(), types(), events(), hooks(), redef_options(), constants(), state_vars(), types(), events(), hooks(),
functions(), redefs() functions(), redefs()
@ -369,7 +369,7 @@ time_t ScriptInfo::DoGetModificationTime() const
if ( ! info ) if ( ! info )
{ {
for (const string& ext : zeek::util::script_extensions) for (const string& ext : zeek::util::detail::script_extensions)
{ {
string pkg_name = *it + "/__load__" + ext; string pkg_name = *it + "/__load__" + ext;
info = zeek::detail::zeekygen_mgr->GetScriptInfo(pkg_name); info = zeek::detail::zeekygen_mgr->GetScriptInfo(pkg_name);

View file

@ -196,7 +196,7 @@ TargetFile::TargetFile(const string& arg_name)
{ {
string dir = zeek::util::SafeDirname(name).result; string dir = zeek::util::SafeDirname(name).result;
if ( ! zeek::util::ensure_intermediate_dirs(dir.c_str()) ) if ( ! zeek::util::detail::ensure_intermediate_dirs(dir.c_str()) )
zeek::reporter->FatalError("Zeekygen failed to make dir %s", zeek::reporter->FatalError("Zeekygen failed to make dir %s",
dir.c_str()); dir.c_str());
} }
@ -413,7 +413,7 @@ void ScriptTarget::DoFindDependencies(const vector<Info*>& infos)
for ( size_t i = 0; i < script_deps.size(); ++i ) for ( size_t i = 0; i < script_deps.size(); ++i )
{ {
if ( zeek::util::is_package_loader(script_deps[i]->Name()) ) if ( zeek::util::detail::is_package_loader(script_deps[i]->Name()) )
{ {
string pkg_dir = zeek::util::SafeDirname(script_deps[i]->Name()).result; string pkg_dir = zeek::util::SafeDirname(script_deps[i]->Name()).result;
string target_file = Name() + pkg_dir + "/index.rst"; string target_file = Name() + pkg_dir + "/index.rst";