Merge remote-tracking branch 'origin/topic/timw/266-namespaces-part5'

- Did a few whitespace re-adjustments during merge

* origin/topic/timw/266-namespaces-part5:
  Update plugin btests for namespace changes
  Plugins: Clean up explicit uses of namespaces in places where they're not necessary.
  Base: Clean up explicit uses of namespaces in places where they're not necessary.
This commit is contained in:
Jon Siwek 2020-08-25 19:47:02 -07:00
commit 427a7de411
454 changed files with 10363 additions and 10255 deletions

View file

@ -1,4 +1,10 @@
3.3.0-dev.200 | 2020-08-25 19:47:02 -0700
* Update plugin btests for namespace changes (Tim Wojtulewicz, Corelight)
* Remove namespace qualifications where unnecessary. (Tim Wojtulewicz, Corelight)
3.3.0-dev.196 | 2020-08-25 17:04:12 -0700 3.3.0-dev.196 | 2020-08-25 17:04:12 -0700
* Fix closing timestamp of rotated log files in supervised-cluster mode (Jon Siwek, Corelight) * Fix closing timestamp of rotated log files in supervised-cluster mode (Jon Siwek, Corelight)

View file

@ -1 +1 @@
3.3.0-dev.196 3.3.0-dev.200

View file

@ -13,14 +13,15 @@
#include "Scope.h" #include "Scope.h"
#include "ID.h" #include "ID.h"
#include "IPAddr.h" #include "IPAddr.h"
#include "Event.h"
using namespace zeek::detail; namespace zeek::detail {
AnonymizeIPAddr* zeek::detail::ip_anonymizer[NUM_ADDR_ANONYMIZATION_METHODS] = {nullptr}; AnonymizeIPAddr* ip_anonymizer[NUM_ADDR_ANONYMIZATION_METHODS] = {nullptr};
static uint32_t rand32() static uint32_t rand32()
{ {
return ((zeek::util::detail::random_number() & 0xffff) << 16) | (zeek::util::detail::random_number() & 0xffff); return ((util::detail::random_number() & 0xffff) << 16) | (util::detail::random_number() & 0xffff);
} }
// From tcpdpriv. // From tcpdpriv.
@ -75,7 +76,7 @@ ipaddr32_t AnonymizeIPAddr::Anonymize(ipaddr32_t addr)
// Keep the specified prefix unchanged. // Keep the specified prefix unchanged.
bool AnonymizeIPAddr::PreservePrefix(ipaddr32_t /* input */, int /* num_bits */) bool AnonymizeIPAddr::PreservePrefix(ipaddr32_t /* input */, int /* num_bits */)
{ {
zeek::reporter->InternalError("prefix preserving is not supported for the anonymizer"); reporter->InternalError("prefix preserving is not supported for the anonymizer");
return false; return false;
} }
@ -104,7 +105,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::detail::hmac_md5(sizeof(input), (u_char*)(&input), digest); 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 +133,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::detail::hmac_md5(sizeof(prefix), (u_char*) &prefix, digest); 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);
@ -172,7 +173,7 @@ bool AnonymizeIPAddr_A50::PreservePrefix(ipaddr32_t input, int num_bits)
if ( ! before_anonymization ) if ( ! before_anonymization )
{ {
zeek::reporter->Error("prefix perservation specified after anonymization begun"); reporter->Error("prefix perservation specified after anonymization begun");
return false; return false;
} }
@ -219,7 +220,7 @@ AnonymizeIPAddr_A50::Node* AnonymizeIPAddr_A50::new_node_block()
int block_size = 1024; int block_size = 1024;
Node* block = new Node[block_size]; Node* block = new Node[block_size];
if ( ! block ) if ( ! block )
zeek::reporter->InternalError("out of memory!"); reporter->InternalError("out of memory!");
blocks.push_back(block); blocks.push_back(block);
@ -271,7 +272,7 @@ ipaddr32_t AnonymizeIPAddr_A50::make_output(ipaddr32_t old_output, int swivel) c
AnonymizeIPAddr_A50::Node* AnonymizeIPAddr_A50::make_peer(ipaddr32_t a, Node* n) AnonymizeIPAddr_A50::Node* AnonymizeIPAddr_A50::make_peer(ipaddr32_t a, Node* n)
{ {
if ( a == 0 || a == 0xFFFFFFFFU ) if ( a == 0 || a == 0xFFFFFFFFU )
zeek::reporter->InternalError("0.0.0.0 and 255.255.255.255 should never get into the tree"); reporter->InternalError("0.0.0.0 and 255.255.255.255 should never get into the tree");
// Become a peer. // Become a peer.
// Algorithm: create two nodes, the two peers. Leave orig node as // Algorithm: create two nodes, the two peers. Leave orig node as
@ -354,15 +355,15 @@ AnonymizeIPAddr_A50::Node* AnonymizeIPAddr_A50::find_node(ipaddr32_t a)
} }
} }
zeek::reporter->InternalError("out of memory!"); reporter->InternalError("out of memory!");
return nullptr; return nullptr;
} }
static zeek::TableValPtr anon_preserve_orig_addr; static TableValPtr anon_preserve_orig_addr;
static zeek::TableValPtr anon_preserve_resp_addr; static TableValPtr anon_preserve_resp_addr;
static zeek::TableValPtr anon_preserve_other_addr; static TableValPtr anon_preserve_other_addr;
void zeek::detail::init_ip_addr_anonymizers() void init_ip_addr_anonymizers()
{ {
ip_anonymizer[KEEP_ORIG_ADDR] = nullptr; ip_anonymizer[KEEP_ORIG_ADDR] = nullptr;
ip_anonymizer[SEQUENTIALLY_NUMBERED] = new AnonymizeIPAddr_Seq(); ip_anonymizer[SEQUENTIALLY_NUMBERED] = new AnonymizeIPAddr_Seq();
@ -373,23 +374,23 @@ void zeek::detail::init_ip_addr_anonymizers()
auto id = global_scope()->Find("preserve_orig_addr"); auto id = global_scope()->Find("preserve_orig_addr");
if ( id ) if ( id )
anon_preserve_orig_addr = zeek::cast_intrusive<zeek::TableVal>(id->GetVal()); anon_preserve_orig_addr = cast_intrusive<TableVal>(id->GetVal());
id = global_scope()->Find("preserve_resp_addr"); id = global_scope()->Find("preserve_resp_addr");
if ( id ) if ( id )
anon_preserve_resp_addr = zeek::cast_intrusive<zeek::TableVal>(id->GetVal()); anon_preserve_resp_addr = cast_intrusive<TableVal>(id->GetVal());
id = global_scope()->Find("preserve_other_addr"); id = global_scope()->Find("preserve_other_addr");
if ( id ) if ( id )
anon_preserve_other_addr = zeek::cast_intrusive<zeek::TableVal>(id->GetVal()); anon_preserve_other_addr = cast_intrusive<TableVal>(id->GetVal());
} }
ipaddr32_t zeek::detail::anonymize_ip(ipaddr32_t ip, enum ip_addr_anonymization_class_t cl) ipaddr32_t anonymize_ip(ipaddr32_t ip, enum ip_addr_anonymization_class_t cl)
{ {
TableVal* preserve_addr = nullptr; TableVal* preserve_addr = nullptr;
auto addr = zeek::make_intrusive<zeek::AddrVal>(ip); auto addr = make_intrusive<AddrVal>(ip);
int method = -1; int method = -1;
@ -421,14 +422,14 @@ ipaddr32_t zeek::detail::anonymize_ip(ipaddr32_t ip, enum ip_addr_anonymization_
new_ip = ip; new_ip = ip;
else if ( ! ip_anonymizer[method] ) else if ( ! ip_anonymizer[method] )
zeek::reporter->InternalError("IP anonymizer not initialized"); reporter->InternalError("IP anonymizer not initialized");
else else
new_ip = ip_anonymizer[method]->Anonymize(ip); new_ip = ip_anonymizer[method]->Anonymize(ip);
} }
else else
zeek::reporter->InternalError("invalid IP anonymization method"); reporter->InternalError("invalid IP anonymization method");
#ifdef LOG_ANONYMIZATION_MAPPING #ifdef LOG_ANONYMIZATION_MAPPING
log_anonymization_mapping(ip, new_ip); log_anonymization_mapping(ip, new_ip);
@ -438,16 +439,15 @@ ipaddr32_t zeek::detail::anonymize_ip(ipaddr32_t ip, enum ip_addr_anonymization_
#ifdef LOG_ANONYMIZATION_MAPPING #ifdef LOG_ANONYMIZATION_MAPPING
#include "NetVar.h" void log_anonymization_mapping(ipaddr32_t input, ipaddr32_t output)
#include "Event.h"
void zeek::detail::log_anonymization_mapping(ipaddr32_t input, ipaddr32_t output)
{ {
if ( anonymization_mapping ) if ( anonymization_mapping )
zeek::event_mgr.Enqueue(anonymization_mapping, event_mgr.Enqueue(anonymization_mapping,
zeek::make_intrusive<zeek::AddrVal>(input), make_intrusive<AddrVal>(input),
zeek::make_intrusive<AddrVal>(output) make_intrusive<AddrVal>(output)
); );
} }
#endif #endif
} // namespace zeek::detail

View file

@ -50,7 +50,7 @@ std::string Attr::DeprecationMessage() const
if ( ! expr ) if ( ! expr )
return ""; return "";
auto ce = static_cast<zeek::detail::ConstExpr*>(expr.get()); auto ce = static_cast<ConstExpr*>(expr.get());
return ce->Value()->AsStringVal()->CheckString(); return ce->Value()->AsStringVal()->CheckString();
} }
@ -164,7 +164,7 @@ Attributes::Attributes(AttrPList* a, TypePtr t, bool arg_in_record, bool is_glob
// the necessary checking gets done. // the necessary checking gets done.
for ( const auto& attr : *a ) for ( const auto& attr : *a )
AddAttr({zeek::NewRef{}, attr}); AddAttr({NewRef{}, attr});
delete a; delete a;
} }
@ -209,7 +209,7 @@ void Attributes::AddAttr(AttrPtr attr)
if ( (attr->Tag() == ATTR_ADD_FUNC || attr->Tag() == ATTR_DEL_FUNC) && if ( (attr->Tag() == ATTR_ADD_FUNC || attr->Tag() == ATTR_DEL_FUNC) &&
! Find(ATTR_REDEF) ) ! Find(ATTR_REDEF) )
{ {
auto a = zeek::make_intrusive<Attr>(ATTR_REDEF); auto a = make_intrusive<Attr>(ATTR_REDEF);
attrs_list.push_back(a.get()); attrs_list.push_back(a.get());
attrs.emplace_back(std::move(a)); attrs.emplace_back(std::move(a));
} }
@ -218,7 +218,7 @@ void Attributes::AddAttr(AttrPtr attr)
if ( ! global_var && attr->Tag() == ATTR_DEFAULT && if ( ! global_var && attr->Tag() == ATTR_DEFAULT &&
! Find(ATTR_OPTIONAL) ) ! Find(ATTR_OPTIONAL) )
{ {
auto a = zeek::make_intrusive<Attr>(ATTR_OPTIONAL); auto a = make_intrusive<Attr>(ATTR_OPTIONAL);
attrs_list.push_back(a.get()); attrs_list.push_back(a.get());
attrs.emplace_back(std::move(a)); attrs.emplace_back(std::move(a));
} }

View file

@ -22,7 +22,7 @@ using TypePtr = IntrusivePtr<Type>;
namespace detail { namespace detail {
using ExprPtr = zeek::IntrusivePtr<zeek::detail::Expr>; using ExprPtr = IntrusivePtr<Expr>;
enum AttrTag { enum AttrTag {
ATTR_OPTIONAL, ATTR_OPTIONAL,
@ -50,9 +50,9 @@ enum AttrTag {
}; };
class Attr; class Attr;
using AttrPtr = zeek::IntrusivePtr<Attr>; using AttrPtr = IntrusivePtr<Attr>;
class Attributes; class Attributes;
using AttributesPtr = zeek::IntrusivePtr<Attributes>; using AttributesPtr = IntrusivePtr<Attributes>;
class Attr final : public Obj { class Attr final : public Obj {
public: public:
@ -66,7 +66,7 @@ public:
AttrTag Tag() const { return tag; } AttrTag Tag() const { return tag; }
[[deprecated("Remove in v4.1. Use GetExpr().")]] [[deprecated("Remove in v4.1. Use GetExpr().")]]
zeek::detail::Expr* AttrExpr() const { return expr.get(); } Expr* AttrExpr() const { return expr.get(); }
const ExprPtr& GetExpr() const const ExprPtr& GetExpr() const
{ return expr; } { return expr; }
@ -107,9 +107,9 @@ protected:
class Attributes final : public Obj { class Attributes final : public Obj {
public: public:
[[deprecated("Remove in v4.1. Construct using IntrusivePtrs instead.")]] [[deprecated("Remove in v4.1. Construct using IntrusivePtrs instead.")]]
Attributes(AttrPList* a, zeek::TypePtr t, bool in_record, bool is_global); Attributes(AttrPList* a, TypePtr t, bool in_record, bool is_global);
Attributes(std::vector<AttrPtr> a, zeek::TypePtr t, Attributes(std::vector<AttrPtr> a, TypePtr t,
bool in_record, bool is_global); bool in_record, bool is_global);
Attributes(TypePtr t, bool in_record, bool is_global); Attributes(TypePtr t, bool in_record, bool is_global);

View file

@ -17,10 +17,10 @@ void Base64Converter::Encode(int len, const unsigned char* data, int* pblen, cha
char *buf; char *buf;
if ( ! pbuf ) if ( ! pbuf )
zeek::reporter->InternalError("nil pointer to encoding result buffer"); reporter->InternalError("nil pointer to encoding result buffer");
if ( *pbuf && (*pblen % 4 != 0) ) if ( *pbuf && (*pblen % 4 != 0) )
zeek::reporter->InternalError("Base64 encode buffer not a multiple of 4"); reporter->InternalError("Base64 encode buffer not a multiple of 4");
if ( *pbuf ) if ( *pbuf )
{ {
@ -88,7 +88,7 @@ int* Base64Converter::InitBase64Table(const std::string& alphabet)
return base64_table; return base64_table;
} }
Base64Converter::Base64Converter(zeek::Connection* arg_conn, const std::string& arg_alphabet) Base64Converter::Base64Converter(Connection* arg_conn, const std::string& arg_alphabet)
{ {
if ( arg_alphabet.size() > 0 ) if ( arg_alphabet.size() > 0 )
{ {
@ -123,7 +123,7 @@ int Base64Converter::Decode(int len, const char* data, int* pblen, char** pbuf)
base64_table = InitBase64Table(alphabet); base64_table = InitBase64Table(alphabet);
if ( ! pbuf ) if ( ! pbuf )
zeek::reporter->InternalError("nil pointer to decoding result buffer"); reporter->InternalError("nil pointer to decoding result buffer");
if ( *pbuf ) if ( *pbuf )
{ {
@ -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(zeek::util::fmt("character %d ignored by Base64 decoding", (int) (data[dlen]))); IllegalEncoding(util::fmt("character %d ignored by Base64 decoding", (int) (data[dlen])));
} }
++dlen; ++dlen;
@ -210,8 +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(zeek::util::fmt("incomplete base64 group, padding with %d bits of 0", IllegalEncoding(util::fmt("incomplete base64 group, padding with %d bits of 0",
(4-base64_group_next) * 6)); (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;
} }
@ -228,15 +228,15 @@ void Base64Converter::IllegalEncoding(const char* msg)
if ( conn ) if ( conn )
conn->Weird("base64_illegal_encoding", msg); conn->Weird("base64_illegal_encoding", msg);
else else
zeek::reporter->Error("%s", msg); reporter->Error("%s", msg);
} }
zeek::String* decode_base64(const zeek::String* s, const zeek::String* a, zeek::Connection* conn) String* decode_base64(const String* s, const String* a, Connection* conn)
{ {
if ( a && a->Len() != 0 && a->Len() != 64 ) if ( a && a->Len() != 0 && a->Len() != 64 )
{ {
zeek::reporter->Error("base64 decoding alphabet is not 64 characters: %s", reporter->Error("base64 decoding alphabet is not 64 characters: %s",
a->CheckString()); a->CheckString());
return nullptr; return nullptr;
} }
@ -258,18 +258,18 @@ zeek::String* decode_base64(const zeek::String* s, const zeek::String* a, zeek::
rlen += rlen2; rlen += rlen2;
rbuf[rlen] = '\0'; rbuf[rlen] = '\0';
return new zeek::String(true, (u_char*) rbuf, rlen); return new String(true, (u_char*) rbuf, rlen);
err: err:
delete [] rbuf; delete [] rbuf;
return nullptr; return nullptr;
} }
zeek::String* encode_base64(const zeek::String* s, const zeek::String* a, zeek::Connection* conn) String* encode_base64(const String* s, const String* a, Connection* conn)
{ {
if ( a && a->Len() != 0 && a->Len() != 64 ) if ( a && a->Len() != 0 && a->Len() != 64 )
{ {
zeek::reporter->Error("base64 alphabet is not 64 characters: %s", reporter->Error("base64 alphabet is not 64 characters: %s",
a->CheckString()); a->CheckString());
return nullptr; return nullptr;
} }
@ -279,7 +279,7 @@ zeek::String* encode_base64(const zeek::String* s, const zeek::String* a, zeek::
Base64Converter enc(conn, a ? a->CheckString() : ""); Base64Converter enc(conn, a ? a->CheckString() : "");
enc.Encode(s->Len(), (const unsigned char*) s->Bytes(), &outlen, &outbuf); enc.Encode(s->Len(), (const unsigned char*) s->Bytes(), &outlen, &outbuf);
return new zeek::String(true, (u_char*)outbuf, outlen); return new String(true, (u_char*)outbuf, outlen);
} }
} // namespace zeek::detail } // namespace zeek::detail

View file

@ -62,8 +62,8 @@ protected:
}; };
zeek::String* decode_base64(const zeek::String* s, const zeek::String* a = nullptr, zeek::Connection* conn = nullptr); String* decode_base64(const String* s, const String* a = nullptr, Connection* conn = nullptr);
zeek::String* encode_base64(const zeek::String* s, const zeek::String* a = nullptr, zeek::Connection* conn = nullptr); String* encode_base64(const String* s, const String* a = nullptr, Connection* conn = nullptr);
} // namespace zeek::detail } // namespace zeek::detail

View file

@ -8,8 +8,8 @@ namespace zeek::detail {
BifReturnVal::BifReturnVal(std::nullptr_t) noexcept BifReturnVal::BifReturnVal(std::nullptr_t) noexcept
{} {}
BifReturnVal::BifReturnVal(zeek::Val* v) noexcept BifReturnVal::BifReturnVal(Val* v) noexcept
: rval(zeek::AdoptRef{}, v) : rval(AdoptRef{}, v)
{} {}
} // namespace zeek::detail } // namespace zeek::detail

View file

@ -7,7 +7,7 @@
ZEEK_FORWARD_DECLARE_NAMESPACED(Val, zeek); ZEEK_FORWARD_DECLARE_NAMESPACED(Val, zeek);
namespace zeek { namespace zeek {
using ValPtr = zeek::IntrusivePtr<zeek::Val>; using ValPtr = IntrusivePtr<Val>;
} }
namespace zeek::detail { namespace zeek::detail {
@ -21,16 +21,16 @@ class BifReturnVal {
public: public:
template <typename T> template <typename T>
BifReturnVal(zeek::IntrusivePtr<T> v) noexcept BifReturnVal(IntrusivePtr<T> v) noexcept
: rval(zeek::AdoptRef{}, v.release()) : rval(AdoptRef{}, v.release())
{ } { }
BifReturnVal(std::nullptr_t) noexcept; BifReturnVal(std::nullptr_t) noexcept;
[[deprecated("Remove in v4.1. Return an IntrusivePtr instead.")]] [[deprecated("Remove in v4.1. Return an IntrusivePtr instead.")]]
BifReturnVal(zeek::Val* v) noexcept; BifReturnVal(Val* v) noexcept;
zeek::ValPtr rval; ValPtr rval;
}; };
} // namespace zeek::detail } // namespace zeek::detail

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) + zeek::util::pad_size(syms->size() * sizeof(int_list::value_type)); return padded_sizeof(*this) + padded_sizeof(*syms) + util::pad_size(syms->size() * sizeof(int_list::value_type));
} }
} // namespace zeek::detail } // namespace zeek::detail

View file

@ -17,17 +17,17 @@
namespace zeek::detail { namespace zeek::detail {
CompositeHash::CompositeHash(zeek::TypeListPtr composite_type) CompositeHash::CompositeHash(TypeListPtr composite_type)
: type(std::move(composite_type)) : type(std::move(composite_type))
{ {
singleton_tag = zeek::TYPE_INTERNAL_ERROR; singleton_tag = TYPE_INTERNAL_ERROR;
// If the only element is a record, don't treat it as a // If the only element is a record, don't treat it as a
// singleton, since it needs to be evaluated specially. // singleton, since it needs to be evaluated specially.
if ( type->GetTypes().size() == 1 ) if ( type->GetTypes().size() == 1 )
{ {
if ( type->GetTypes()[0]->Tag() == zeek::TYPE_RECORD ) if ( type->GetTypes()[0]->Tag() == TYPE_RECORD )
{ {
is_complex_type = true; is_complex_type = true;
is_singleton = false; is_singleton = false;
@ -74,10 +74,10 @@ CompositeHash::~CompositeHash()
// Computes the piece of the hash for Val*, returning the new kp. // Computes the piece of the hash for Val*, returning the new kp.
char* CompositeHash::SingleValHash(bool type_check, char* kp0, char* CompositeHash::SingleValHash(bool type_check, char* kp0,
zeek::Type* bt, zeek::Val* v, bool optional) const Type* bt, Val* v, bool optional) const
{ {
char* kp1 = nullptr; char* kp1 = nullptr;
zeek::InternalTypeTag t = bt->InternalType(); InternalTypeTag t = bt->InternalType();
if ( optional ) if ( optional )
{ {
@ -92,13 +92,13 @@ char* CompositeHash::SingleValHash(bool type_check, char* kp0,
if ( type_check ) if ( type_check )
{ {
zeek::InternalTypeTag vt = v->GetType()->InternalType(); InternalTypeTag vt = v->GetType()->InternalType();
if ( vt != t ) if ( vt != t )
return nullptr; return nullptr;
} }
switch ( t ) { switch ( t ) {
case zeek::TYPE_INTERNAL_INT: case TYPE_INTERNAL_INT:
{ {
bro_int_t* kp = AlignAndPadType<bro_int_t>(kp0); bro_int_t* kp = AlignAndPadType<bro_int_t>(kp0);
*kp = v->ForceAsInt(); *kp = v->ForceAsInt();
@ -106,7 +106,7 @@ char* CompositeHash::SingleValHash(bool type_check, char* kp0,
} }
break; break;
case zeek::TYPE_INTERNAL_UNSIGNED: case TYPE_INTERNAL_UNSIGNED:
{ {
bro_uint_t* kp = AlignAndPadType<bro_uint_t>(kp0); bro_uint_t* kp = AlignAndPadType<bro_uint_t>(kp0);
*kp = v->ForceAsUInt(); *kp = v->ForceAsUInt();
@ -114,7 +114,7 @@ char* CompositeHash::SingleValHash(bool type_check, char* kp0,
} }
break; break;
case zeek::TYPE_INTERNAL_ADDR: case TYPE_INTERNAL_ADDR:
{ {
uint32_t* kp = AlignAndPadType<uint32_t>(kp0); uint32_t* kp = AlignAndPadType<uint32_t>(kp0);
v->AsAddr().CopyIPv6(kp); v->AsAddr().CopyIPv6(kp);
@ -122,7 +122,7 @@ char* CompositeHash::SingleValHash(bool type_check, char* kp0,
} }
break; break;
case zeek::TYPE_INTERNAL_SUBNET: case TYPE_INTERNAL_SUBNET:
{ {
uint32_t* kp = AlignAndPadType<uint32_t>(kp0); uint32_t* kp = AlignAndPadType<uint32_t>(kp0);
v->AsSubNet().Prefix().CopyIPv6(kp); v->AsSubNet().Prefix().CopyIPv6(kp);
@ -131,7 +131,7 @@ char* CompositeHash::SingleValHash(bool type_check, char* kp0,
} }
break; break;
case zeek::TYPE_INTERNAL_DOUBLE: case TYPE_INTERNAL_DOUBLE:
{ {
double* kp = AlignAndPadType<double>(kp0); double* kp = AlignAndPadType<double>(kp0);
*kp = v->InternalDouble(); *kp = v->InternalDouble();
@ -139,11 +139,11 @@ char* CompositeHash::SingleValHash(bool type_check, char* kp0,
} }
break; break;
case zeek::TYPE_INTERNAL_VOID: case TYPE_INTERNAL_VOID:
case zeek::TYPE_INTERNAL_OTHER: case TYPE_INTERNAL_OTHER:
{ {
switch ( v->GetType()->Tag() ) { switch ( v->GetType()->Tag() ) {
case zeek::TYPE_FUNC: case TYPE_FUNC:
{ {
uint32_t* kp = AlignAndPadType<uint32_t>(kp0); uint32_t* kp = AlignAndPadType<uint32_t>(kp0);
*kp = v->AsFunc()->GetUniqueFuncID(); *kp = v->AsFunc()->GetUniqueFuncID();
@ -151,7 +151,7 @@ char* CompositeHash::SingleValHash(bool type_check, char* kp0,
break; break;
} }
case zeek::TYPE_PATTERN: case TYPE_PATTERN:
{ {
const char* texts[2] = { const char* texts[2] = {
v->AsPattern()->PatternText(), v->AsPattern()->PatternText(),
@ -175,19 +175,19 @@ char* CompositeHash::SingleValHash(bool type_check, char* kp0,
break; break;
} }
case zeek::TYPE_RECORD: case TYPE_RECORD:
{ {
char* kp = kp0; char* kp = kp0;
zeek::RecordVal* rv = v->AsRecordVal(); RecordVal* rv = v->AsRecordVal();
zeek::RecordType* rt = bt->AsRecordType(); RecordType* rt = bt->AsRecordType();
int num_fields = rt->NumFields(); int num_fields = rt->NumFields();
for ( int i = 0; i < num_fields; ++i ) for ( int i = 0; i < num_fields; ++i )
{ {
auto rv_i = rv->GetField(i).get(); auto rv_i = rv->GetField(i).get();
zeek::detail::Attributes* a = rt->FieldDecl(i)->attrs.get(); Attributes* a = rt->FieldDecl(i)->attrs.get();
bool optional = (a && a->Find(zeek::detail::ATTR_OPTIONAL)); bool optional = (a && a->Find(ATTR_OPTIONAL));
if ( ! (rv_i || optional) ) if ( ! (rv_i || optional) )
return nullptr; return nullptr;
@ -202,19 +202,19 @@ char* CompositeHash::SingleValHash(bool type_check, char* kp0,
break; break;
} }
case zeek::TYPE_TABLE: case TYPE_TABLE:
{ {
int* kp = AlignAndPadType<int>(kp0); int* kp = AlignAndPadType<int>(kp0);
zeek::TableVal* tv = v->AsTableVal(); TableVal* tv = v->AsTableVal();
*kp = tv->Size(); *kp = tv->Size();
kp1 = reinterpret_cast<char*>(kp+1); kp1 = reinterpret_cast<char*>(kp+1);
auto tbl = tv->AsTable(); auto tbl = tv->AsTable();
auto it = tbl->InitForIteration(); auto it = tbl->InitForIteration();
auto lv = zeek::make_intrusive<zeek::ListVal>(zeek::TYPE_ANY); auto lv = make_intrusive<ListVal>(TYPE_ANY);
struct HashKeyComparer { struct HashKeyComparer {
bool operator()(const zeek::detail::HashKey* a, const zeek::detail::HashKey* b) const bool operator()(const HashKey* a, const HashKey* b) const
{ {
if ( a->Hash() != b->Hash() ) if ( a->Hash() != b->Hash() )
return a->Hash() < b->Hash(); return a->Hash() < b->Hash();
@ -226,8 +226,8 @@ char* CompositeHash::SingleValHash(bool type_check, char* kp0,
} }
}; };
std::map<zeek::detail::HashKey*, int, HashKeyComparer> hashkeys; std::map<HashKey*, int, HashKeyComparer> hashkeys;
zeek::detail::HashKey* k; HashKey* k;
auto idx = 0; auto idx = 0;
while ( tbl->NextEntry(k, it) ) while ( tbl->NextEntry(k, it) )
@ -261,11 +261,11 @@ char* CompositeHash::SingleValHash(bool type_check, char* kp0,
} }
break; break;
case zeek::TYPE_VECTOR: case TYPE_VECTOR:
{ {
unsigned int* kp = AlignAndPadType<unsigned int>(kp0); unsigned int* kp = AlignAndPadType<unsigned int>(kp0);
zeek::VectorVal* vv = v->AsVectorVal(); VectorVal* vv = v->AsVectorVal();
zeek::VectorType* vt = v->GetType()->AsVectorType(); VectorType* vt = v->GetType()->AsVectorType();
*kp = vv->Size(); *kp = vv->Size();
kp1 = reinterpret_cast<char*>(kp+1); kp1 = reinterpret_cast<char*>(kp+1);
for ( unsigned int i = 0; i < vv->Size(); ++i ) for ( unsigned int i = 0; i < vv->Size(); ++i )
@ -289,15 +289,15 @@ char* CompositeHash::SingleValHash(bool type_check, char* kp0,
} }
break; break;
case zeek::TYPE_LIST: case TYPE_LIST:
{ {
int* kp = AlignAndPadType<int>(kp0); int* kp = AlignAndPadType<int>(kp0);
zeek::ListVal* lv = v->AsListVal(); ListVal* lv = v->AsListVal();
*kp = lv->Length(); *kp = lv->Length();
kp1 = reinterpret_cast<char*>(kp+1); kp1 = reinterpret_cast<char*>(kp+1);
for ( int i = 0; i < lv->Length(); ++i ) for ( int i = 0; i < lv->Length(); ++i )
{ {
zeek::Val* v = lv->Idx(i).get(); Val* v = lv->Idx(i).get();
if ( ! (kp1 = SingleValHash(type_check, kp1, v->GetType().get(), v, if ( ! (kp1 = SingleValHash(type_check, kp1, v->GetType().get(), v,
false)) ) false)) )
return nullptr; return nullptr;
@ -307,19 +307,19 @@ char* CompositeHash::SingleValHash(bool type_check, char* kp0,
default: default:
{ {
zeek::reporter->InternalError("bad index type in CompositeHash::SingleValHash"); reporter->InternalError("bad index type in CompositeHash::SingleValHash");
return nullptr; return nullptr;
} }
} }
break; // case zeek::TYPE_INTERNAL_VOID/OTHER break; // case TYPE_INTERNAL_VOID/OTHER
} }
case zeek::TYPE_INTERNAL_STRING: case TYPE_INTERNAL_STRING:
{ {
// Align to int for the length field. // Align to int for the length field.
int* kp = AlignAndPadType<int>(kp0); int* kp = AlignAndPadType<int>(kp0);
const zeek::String* sval = v->AsString(); const String* sval = v->AsString();
*kp = sval->Len(); // so we can recover the value *kp = sval->Len(); // so we can recover the value
@ -330,7 +330,7 @@ char* CompositeHash::SingleValHash(bool type_check, char* kp0,
} }
break; break;
case zeek::TYPE_INTERNAL_ERROR: case TYPE_INTERNAL_ERROR:
return nullptr; return nullptr;
} }
@ -338,22 +338,22 @@ char* CompositeHash::SingleValHash(bool type_check, char* kp0,
} }
std::unique_ptr<zeek::detail::HashKey> CompositeHash::MakeHashKey(const zeek::Val& argv, bool type_check) const std::unique_ptr<HashKey> CompositeHash::MakeHashKey(const Val& argv, bool type_check) const
{ {
auto v = &argv; auto v = &argv;
if ( is_singleton ) if ( is_singleton )
return ComputeSingletonHash(v, type_check); return ComputeSingletonHash(v, type_check);
if ( is_complex_type && v->GetType()->Tag() != zeek::TYPE_LIST ) if ( is_complex_type && v->GetType()->Tag() != TYPE_LIST )
{ {
zeek::ListVal lv(zeek::TYPE_ANY); ListVal lv(TYPE_ANY);
// Cast away const to use ListVal - but since we // Cast away const to use ListVal - but since we
// re-introduce const on the recursive call, it should // re-introduce const on the recursive call, it should
// be okay; the only thing is that the ListVal unref's it. // be okay; the only thing is that the ListVal unref's it.
zeek::Val* ncv = (zeek::Val*) v; Val* ncv = (Val*) v;
lv.Append({zeek::NewRef{}, ncv}); lv.Append({NewRef{}, ncv});
return MakeHashKey(lv, type_check); return MakeHashKey(lv, type_check);
} }
@ -371,7 +371,7 @@ std::unique_ptr<zeek::detail::HashKey> CompositeHash::MakeHashKey(const zeek::Va
const auto& tl = type->GetTypes(); const auto& tl = type->GetTypes();
if ( type_check && v->GetType()->Tag() != zeek::TYPE_LIST ) if ( type_check && v->GetType()->Tag() != TYPE_LIST )
return nullptr; return nullptr;
auto lv = v->AsListVal(); auto lv = v->AsListVal();
@ -387,12 +387,12 @@ std::unique_ptr<zeek::detail::HashKey> CompositeHash::MakeHashKey(const zeek::Va
return nullptr; return nullptr;
} }
return std::make_unique<zeek::detail::HashKey>((k == key), (void*) k, kp - k); return std::make_unique<HashKey>((k == key), (void*) k, kp - k);
} }
std::unique_ptr<zeek::detail::HashKey> CompositeHash::ComputeSingletonHash(const zeek::Val* v, bool type_check) const std::unique_ptr<HashKey> CompositeHash::ComputeSingletonHash(const Val* v, bool type_check) const
{ {
if ( v->GetType()->Tag() == zeek::TYPE_LIST ) if ( v->GetType()->Tag() == TYPE_LIST )
{ {
auto lv = v->AsListVal(); auto lv = v->AsListVal();
@ -406,25 +406,25 @@ std::unique_ptr<zeek::detail::HashKey> CompositeHash::ComputeSingletonHash(const
return nullptr; return nullptr;
switch ( singleton_tag ) { switch ( singleton_tag ) {
case zeek::TYPE_INTERNAL_INT: case TYPE_INTERNAL_INT:
case zeek::TYPE_INTERNAL_UNSIGNED: case TYPE_INTERNAL_UNSIGNED:
return std::make_unique<zeek::detail::HashKey>(v->ForceAsInt()); return std::make_unique<HashKey>(v->ForceAsInt());
case zeek::TYPE_INTERNAL_ADDR: case TYPE_INTERNAL_ADDR:
return v->AsAddr().MakeHashKey(); return v->AsAddr().MakeHashKey();
case zeek::TYPE_INTERNAL_SUBNET: case TYPE_INTERNAL_SUBNET:
return v->AsSubNet().MakeHashKey(); return v->AsSubNet().MakeHashKey();
case zeek::TYPE_INTERNAL_DOUBLE: case TYPE_INTERNAL_DOUBLE:
return std::make_unique<zeek::detail::HashKey>(v->InternalDouble()); return std::make_unique<HashKey>(v->InternalDouble());
case zeek::TYPE_INTERNAL_VOID: case TYPE_INTERNAL_VOID:
case zeek::TYPE_INTERNAL_OTHER: case TYPE_INTERNAL_OTHER:
if ( v->GetType()->Tag() == zeek::TYPE_FUNC ) if ( v->GetType()->Tag() == TYPE_FUNC )
return std::make_unique<zeek::detail::HashKey>(v->AsFunc()->GetUniqueFuncID()); return std::make_unique<HashKey>(v->AsFunc()->GetUniqueFuncID());
if ( v->GetType()->Tag() == zeek::TYPE_PATTERN ) if ( v->GetType()->Tag() == TYPE_PATTERN )
{ {
const char* texts[2] = { const char* texts[2] = {
v->AsPattern()->PatternText(), v->AsPattern()->PatternText(),
@ -434,71 +434,71 @@ std::unique_ptr<zeek::detail::HashKey> CompositeHash::ComputeSingletonHash(const
char* key = new char[n]; char* key = new char[n];
std::memcpy(key, texts[0], strlen(texts[0]) + 1); std::memcpy(key, texts[0], strlen(texts[0]) + 1);
std::memcpy(key + strlen(texts[0]) + 1, texts[1], strlen(texts[1]) + 1); std::memcpy(key + strlen(texts[0]) + 1, texts[1], strlen(texts[1]) + 1);
return std::make_unique<zeek::detail::HashKey>(false, key, n); return std::make_unique<HashKey>(false, key, n);
} }
zeek::reporter->InternalError("bad index type in CompositeHash::ComputeSingletonHash"); reporter->InternalError("bad index type in CompositeHash::ComputeSingletonHash");
return nullptr; return nullptr;
case zeek::TYPE_INTERNAL_STRING: case TYPE_INTERNAL_STRING:
return std::make_unique<zeek::detail::HashKey>(v->AsString()); return std::make_unique<HashKey>(v->AsString());
case zeek::TYPE_INTERNAL_ERROR: case TYPE_INTERNAL_ERROR:
return nullptr; return nullptr;
default: default:
zeek::reporter->InternalError("bad internal type in CompositeHash::ComputeSingletonHash"); reporter->InternalError("bad internal type in CompositeHash::ComputeSingletonHash");
return nullptr; return nullptr;
} }
} }
int CompositeHash::SingleTypeKeySize(zeek::Type* bt, const zeek::Val* v, int CompositeHash::SingleTypeKeySize(Type* bt, const Val* v,
bool type_check, int sz, bool optional, bool type_check, int sz, bool optional,
bool calc_static_size) const bool calc_static_size) const
{ {
zeek::InternalTypeTag t = bt->InternalType(); InternalTypeTag t = bt->InternalType();
if ( optional ) if ( optional )
sz = SizeAlign(sz, sizeof(char)); sz = SizeAlign(sz, sizeof(char));
if ( type_check && v ) if ( type_check && v )
{ {
zeek::InternalTypeTag vt = v->GetType()->InternalType(); InternalTypeTag vt = v->GetType()->InternalType();
if ( vt != t ) if ( vt != t )
return 0; return 0;
} }
switch ( t ) { switch ( t ) {
case zeek::TYPE_INTERNAL_INT: case TYPE_INTERNAL_INT:
case zeek::TYPE_INTERNAL_UNSIGNED: case TYPE_INTERNAL_UNSIGNED:
sz = SizeAlign(sz, sizeof(bro_int_t)); sz = SizeAlign(sz, sizeof(bro_int_t));
break; break;
case zeek::TYPE_INTERNAL_ADDR: case TYPE_INTERNAL_ADDR:
sz = SizeAlign(sz, sizeof(uint32_t)); sz = SizeAlign(sz, sizeof(uint32_t));
sz += sizeof(uint32_t) * 3; // to make a total of 4 words sz += sizeof(uint32_t) * 3; // to make a total of 4 words
break; break;
case zeek::TYPE_INTERNAL_SUBNET: case TYPE_INTERNAL_SUBNET:
sz = SizeAlign(sz, sizeof(uint32_t)); sz = SizeAlign(sz, sizeof(uint32_t));
sz += sizeof(uint32_t) * 4; // to make a total of 5 words sz += sizeof(uint32_t) * 4; // to make a total of 5 words
break; break;
case zeek::TYPE_INTERNAL_DOUBLE: case TYPE_INTERNAL_DOUBLE:
sz = SizeAlign(sz, sizeof(double)); sz = SizeAlign(sz, sizeof(double));
break; break;
case zeek::TYPE_INTERNAL_VOID: case TYPE_INTERNAL_VOID:
case zeek::TYPE_INTERNAL_OTHER: case TYPE_INTERNAL_OTHER:
{ {
switch ( bt->Tag() ) { switch ( bt->Tag() ) {
case zeek::TYPE_FUNC: case TYPE_FUNC:
{ {
sz = SizeAlign(sz, sizeof(uint32_t)); sz = SizeAlign(sz, sizeof(uint32_t));
break; break;
} }
case zeek::TYPE_PATTERN: case TYPE_PATTERN:
{ {
if ( ! v ) if ( ! v )
return (optional && ! calc_static_size) ? sz : 0; return (optional && ! calc_static_size) ? sz : 0;
@ -509,16 +509,16 @@ int CompositeHash::SingleTypeKeySize(zeek::Type* bt, const zeek::Val* v,
break; break;
} }
case zeek::TYPE_RECORD: case TYPE_RECORD:
{ {
const zeek::RecordVal* rv = v ? v->AsRecordVal() : nullptr; const RecordVal* rv = v ? v->AsRecordVal() : nullptr;
zeek::RecordType* rt = bt->AsRecordType(); RecordType* rt = bt->AsRecordType();
int num_fields = rt->NumFields(); int num_fields = rt->NumFields();
for ( int i = 0; i < num_fields; ++i ) for ( int i = 0; i < num_fields; ++i )
{ {
zeek::detail::Attributes* a = rt->FieldDecl(i)->attrs.get(); Attributes* a = rt->FieldDecl(i)->attrs.get();
bool optional = (a && a->Find(zeek::detail::ATTR_OPTIONAL)); bool optional = (a && a->Find(ATTR_OPTIONAL));
sz = SingleTypeKeySize(rt->GetFieldType(i).get(), sz = SingleTypeKeySize(rt->GetFieldType(i).get(),
rv ? rv->GetField(i).get() : nullptr, rv ? rv->GetField(i).get() : nullptr,
@ -531,13 +531,13 @@ int CompositeHash::SingleTypeKeySize(zeek::Type* bt, const zeek::Val* v,
break; break;
} }
case zeek::TYPE_TABLE: case TYPE_TABLE:
{ {
if ( ! v ) if ( ! v )
return (optional && ! calc_static_size) ? sz : 0; return (optional && ! calc_static_size) ? sz : 0;
sz = SizeAlign(sz, sizeof(int)); sz = SizeAlign(sz, sizeof(int));
zeek::TableVal* tv = const_cast<zeek::TableVal*>(v->AsTableVal()); TableVal* tv = const_cast<TableVal*>(v->AsTableVal());
auto lv = tv->ToListVal(); auto lv = tv->ToListVal();
for ( int i = 0; i < tv->Size(); ++i ) for ( int i = 0; i < tv->Size(); ++i )
{ {
@ -560,13 +560,13 @@ int CompositeHash::SingleTypeKeySize(zeek::Type* bt, const zeek::Val* v,
break; break;
} }
case zeek::TYPE_VECTOR: case TYPE_VECTOR:
{ {
if ( ! v ) if ( ! v )
return (optional && ! calc_static_size) ? sz : 0; return (optional && ! calc_static_size) ? sz : 0;
sz = SizeAlign(sz, sizeof(unsigned int)); sz = SizeAlign(sz, sizeof(unsigned int));
zeek::VectorVal* vv = const_cast<zeek::VectorVal*>(v->AsVectorVal()); VectorVal* vv = const_cast<VectorVal*>(v->AsVectorVal());
for ( unsigned int i = 0; i < vv->Size(); ++i ) for ( unsigned int i = 0; i < vv->Size(); ++i )
{ {
const auto& val = vv->At(i); const auto& val = vv->At(i);
@ -582,13 +582,13 @@ int CompositeHash::SingleTypeKeySize(zeek::Type* bt, const zeek::Val* v,
break; break;
} }
case zeek::TYPE_LIST: case TYPE_LIST:
{ {
if ( ! v ) if ( ! v )
return (optional && ! calc_static_size) ? sz : 0; return (optional && ! calc_static_size) ? sz : 0;
sz = SizeAlign(sz, sizeof(int)); sz = SizeAlign(sz, sizeof(int));
zeek::ListVal* lv = const_cast<zeek::ListVal*>(v->AsListVal()); ListVal* lv = const_cast<ListVal*>(v->AsListVal());
for ( int i = 0; i < lv->Length(); ++i ) for ( int i = 0; i < lv->Length(); ++i )
{ {
sz = SingleTypeKeySize(lv->Idx(i)->GetType().get(), lv->Idx(i).get(), sz = SingleTypeKeySize(lv->Idx(i)->GetType().get(), lv->Idx(i).get(),
@ -601,15 +601,15 @@ int CompositeHash::SingleTypeKeySize(zeek::Type* bt, const zeek::Val* v,
default: default:
{ {
zeek::reporter->InternalError("bad index type in CompositeHash::CompositeHash"); reporter->InternalError("bad index type in CompositeHash::CompositeHash");
return 0; return 0;
} }
} }
break; // case zeek::TYPE_INTERNAL_VOID/OTHER break; // case TYPE_INTERNAL_VOID/OTHER
} }
case zeek::TYPE_INTERNAL_STRING: case TYPE_INTERNAL_STRING:
if ( ! v ) if ( ! v )
return (optional && ! calc_static_size) ? sz : 0; return (optional && ! calc_static_size) ? sz : 0;
@ -618,20 +618,20 @@ int CompositeHash::SingleTypeKeySize(zeek::Type* bt, const zeek::Val* v,
sz += v->AsString()->Len(); sz += v->AsString()->Len();
break; break;
case zeek::TYPE_INTERNAL_ERROR: case TYPE_INTERNAL_ERROR:
return 0; return 0;
} }
return sz; return sz;
} }
int CompositeHash::ComputeKeySize(const zeek::Val* v, bool type_check, bool calc_static_size) const int CompositeHash::ComputeKeySize(const Val* v, bool type_check, bool calc_static_size) const
{ {
const auto& tl = type->GetTypes(); const auto& tl = type->GetTypes();
if ( v ) if ( v )
{ {
if ( type_check && v->GetType()->Tag() != zeek::TYPE_LIST ) if ( type_check && v->GetType()->Tag() != TYPE_LIST )
return 0; return 0;
auto lv = v->AsListVal(); auto lv = v->AsListVal();
@ -711,38 +711,38 @@ int CompositeHash::SizeAlign(int offset, unsigned int size) const
return offset; return offset;
} }
zeek::ListValPtr CompositeHash::RecoverVals(const zeek::detail::HashKey& k) const ListValPtr CompositeHash::RecoverVals(const HashKey& k) const
{ {
auto l = zeek::make_intrusive<zeek::ListVal>(zeek::TYPE_ANY); auto l = make_intrusive<ListVal>(TYPE_ANY);
const auto& tl = type->GetTypes(); const auto& tl = type->GetTypes();
const char* kp = (const char*) k.Key(); const char* kp = (const char*) k.Key();
const char* const k_end = kp + k.Size(); const char* const k_end = kp + k.Size();
for ( const auto& type : tl ) for ( const auto& type : tl )
{ {
zeek::ValPtr v; ValPtr v;
kp = RecoverOneVal(k, kp, k_end, type.get(), &v, false); kp = RecoverOneVal(k, kp, k_end, type.get(), &v, false);
ASSERT(v); ASSERT(v);
l->Append(std::move(v)); l->Append(std::move(v));
} }
if ( kp != k_end ) if ( kp != k_end )
zeek::reporter->InternalError("under-ran key in CompositeHash::DescribeKey %zd", k_end - kp); reporter->InternalError("under-ran key in CompositeHash::DescribeKey %zd", k_end - kp);
return l; return l;
} }
const char* CompositeHash::RecoverOneVal( const char* CompositeHash::RecoverOneVal(
const zeek::detail::HashKey& k, const char* kp0, const HashKey& k, const char* kp0,
const char* const k_end, zeek::Type* t, const char* const k_end, Type* t,
zeek::ValPtr* pval, bool optional) const ValPtr* pval, bool optional) const
{ {
// k->Size() == 0 for a single empty string. // k->Size() == 0 for a single empty string.
if ( kp0 >= k_end && k.Size() > 0 ) if ( kp0 >= k_end && k.Size() > 0 )
zeek::reporter->InternalError("over-ran key in CompositeHash::RecoverVals"); reporter->InternalError("over-ran key in CompositeHash::RecoverVals");
zeek::TypeTag tag = t->Tag(); TypeTag tag = t->Tag();
zeek::InternalTypeTag it = t->InternalType(); InternalTypeTag it = t->InternalType();
const char* kp1 = nullptr; const char* kp1 = nullptr;
if ( optional ) if ( optional )
@ -758,128 +758,128 @@ const char* CompositeHash::RecoverOneVal(
} }
switch ( it ) { switch ( it ) {
case zeek::TYPE_INTERNAL_INT: case TYPE_INTERNAL_INT:
{ {
const bro_int_t* const kp = AlignType<bro_int_t>(kp0); const bro_int_t* const kp = AlignType<bro_int_t>(kp0);
kp1 = reinterpret_cast<const char*>(kp+1); kp1 = reinterpret_cast<const char*>(kp+1);
if ( tag == zeek::TYPE_ENUM ) if ( tag == TYPE_ENUM )
*pval = t->AsEnumType()->GetEnumVal(*kp); *pval = t->AsEnumType()->GetEnumVal(*kp);
else if ( tag == zeek::TYPE_BOOL ) else if ( tag == TYPE_BOOL )
*pval = zeek::val_mgr->Bool(*kp); *pval = val_mgr->Bool(*kp);
else if ( tag == zeek::TYPE_INT ) else if ( tag == TYPE_INT )
*pval = zeek::val_mgr->Int(*kp); *pval = val_mgr->Int(*kp);
else else
{ {
zeek::reporter->InternalError("bad internal unsigned int in CompositeHash::RecoverOneVal()"); reporter->InternalError("bad internal unsigned int in CompositeHash::RecoverOneVal()");
*pval = nullptr; *pval = nullptr;
} }
} }
break; break;
case zeek::TYPE_INTERNAL_UNSIGNED: case TYPE_INTERNAL_UNSIGNED:
{ {
const bro_uint_t* const kp = AlignType<bro_uint_t>(kp0); const bro_uint_t* const kp = AlignType<bro_uint_t>(kp0);
kp1 = reinterpret_cast<const char*>(kp+1); kp1 = reinterpret_cast<const char*>(kp+1);
switch ( tag ) { switch ( tag ) {
case zeek::TYPE_COUNT: case TYPE_COUNT:
*pval = zeek::val_mgr->Count(*kp); *pval = val_mgr->Count(*kp);
break; break;
case zeek::TYPE_PORT: case TYPE_PORT:
*pval = zeek::val_mgr->Port(*kp); *pval = val_mgr->Port(*kp);
break; break;
default: default:
zeek::reporter->InternalError("bad internal unsigned int in CompositeHash::RecoverOneVal()"); reporter->InternalError("bad internal unsigned int in CompositeHash::RecoverOneVal()");
*pval = nullptr; *pval = nullptr;
break; break;
} }
} }
break; break;
case zeek::TYPE_INTERNAL_DOUBLE: case TYPE_INTERNAL_DOUBLE:
{ {
const double* const kp = AlignType<double>(kp0); const double* const kp = AlignType<double>(kp0);
kp1 = reinterpret_cast<const char*>(kp+1); kp1 = reinterpret_cast<const char*>(kp+1);
if ( tag == zeek::TYPE_INTERVAL ) if ( tag == TYPE_INTERVAL )
*pval = zeek::make_intrusive<zeek::IntervalVal>(*kp, 1.0); *pval = make_intrusive<IntervalVal>(*kp, 1.0);
else if ( tag == zeek::TYPE_TIME ) else if ( tag == TYPE_TIME )
*pval = zeek::make_intrusive<zeek::TimeVal>(*kp); *pval = make_intrusive<TimeVal>(*kp);
else else
*pval = zeek::make_intrusive<zeek::DoubleVal>(*kp); *pval = make_intrusive<DoubleVal>(*kp);
} }
break; break;
case zeek::TYPE_INTERNAL_ADDR: case TYPE_INTERNAL_ADDR:
{ {
const uint32_t* const kp = AlignType<uint32_t>(kp0); const uint32_t* const kp = AlignType<uint32_t>(kp0);
kp1 = reinterpret_cast<const char*>(kp+4); kp1 = reinterpret_cast<const char*>(kp+4);
zeek::IPAddr addr(IPv6, kp, zeek::IPAddr::Network); IPAddr addr(IPv6, kp, IPAddr::Network);
switch ( tag ) { switch ( tag ) {
case zeek::TYPE_ADDR: case TYPE_ADDR:
*pval = zeek::make_intrusive<zeek::AddrVal>(addr); *pval = make_intrusive<AddrVal>(addr);
break; break;
default: default:
zeek::reporter->InternalError("bad internal address in CompositeHash::RecoverOneVal()"); reporter->InternalError("bad internal address in CompositeHash::RecoverOneVal()");
*pval = nullptr; *pval = nullptr;
break; break;
} }
} }
break; break;
case zeek::TYPE_INTERNAL_SUBNET: case TYPE_INTERNAL_SUBNET:
{ {
const uint32_t* const kp = AlignType<uint32_t>(kp0); const uint32_t* const kp = AlignType<uint32_t>(kp0);
kp1 = reinterpret_cast<const char*>(kp+5); kp1 = reinterpret_cast<const char*>(kp+5);
*pval = zeek::make_intrusive<zeek::SubNetVal>(kp, kp[4]); *pval = make_intrusive<SubNetVal>(kp, kp[4]);
} }
break; break;
case zeek::TYPE_INTERNAL_VOID: case TYPE_INTERNAL_VOID:
case zeek::TYPE_INTERNAL_OTHER: case TYPE_INTERNAL_OTHER:
{ {
switch ( t->Tag() ) { switch ( t->Tag() ) {
case zeek::TYPE_FUNC: case TYPE_FUNC:
{ {
const uint32_t* const kp = AlignType<uint32_t>(kp0); const uint32_t* const kp = AlignType<uint32_t>(kp0);
kp1 = reinterpret_cast<const char*>(kp+1); kp1 = reinterpret_cast<const char*>(kp+1);
const auto& f = zeek::Func::GetFuncPtrByID(*kp); const auto& f = Func::GetFuncPtrByID(*kp);
if ( ! f ) if ( ! f )
zeek::reporter->InternalError("failed to look up unique function id %" PRIu32 " in CompositeHash::RecoverOneVal()", *kp); reporter->InternalError("failed to look up unique function id %" PRIu32 " in CompositeHash::RecoverOneVal()", *kp);
*pval = zeek::make_intrusive<zeek::Val>(f); *pval = make_intrusive<Val>(f);
const auto& pvt = (*pval)->GetType(); const auto& pvt = (*pval)->GetType();
if ( ! pvt ) if ( ! pvt )
zeek::reporter->InternalError("bad aggregate Val in CompositeHash::RecoverOneVal()"); reporter->InternalError("bad aggregate Val in CompositeHash::RecoverOneVal()");
else if ( t->Tag() != zeek::TYPE_FUNC && ! same_type(pvt, t) ) else if ( t->Tag() != TYPE_FUNC && ! same_type(pvt, t) )
// ### Maybe fix later, but may be fundamentally // ### Maybe fix later, but may be fundamentally
// un-checkable --US // un-checkable --US
zeek::reporter->InternalError("inconsistent aggregate Val in CompositeHash::RecoverOneVal()"); reporter->InternalError("inconsistent aggregate Val in CompositeHash::RecoverOneVal()");
// ### A crude approximation for now. // ### A crude approximation for now.
else if ( t->Tag() == zeek::TYPE_FUNC && pvt->Tag() != zeek::TYPE_FUNC ) else if ( t->Tag() == TYPE_FUNC && pvt->Tag() != TYPE_FUNC )
zeek::reporter->InternalError("inconsistent aggregate Val in CompositeHash::RecoverOneVal()"); reporter->InternalError("inconsistent aggregate Val in CompositeHash::RecoverOneVal()");
} }
break; break;
case zeek::TYPE_PATTERN: case TYPE_PATTERN:
{ {
zeek::RE_Matcher* re = nullptr; RE_Matcher* re = nullptr;
if ( is_singleton ) if ( is_singleton )
{ {
kp1 = kp0; kp1 = kp0;
int divider = strlen(kp0) + 1; int divider = strlen(kp0) + 1;
re = new zeek::RE_Matcher(kp1, kp1 + divider); re = new RE_Matcher(kp1, kp1 + divider);
kp1 += k.Size(); kp1 += k.Size();
} }
else else
@ -887,32 +887,32 @@ const char* CompositeHash::RecoverOneVal(
const uint64_t* const len = AlignType<uint64_t>(kp0); const uint64_t* const len = AlignType<uint64_t>(kp0);
kp1 = reinterpret_cast<const char*>(len+2); kp1 = reinterpret_cast<const char*>(len+2);
re = new zeek::RE_Matcher(kp1, kp1 + len[0]); re = new RE_Matcher(kp1, kp1 + len[0]);
kp1 += len[0] + len[1]; kp1 += len[0] + len[1];
} }
if ( ! re->Compile() ) if ( ! re->Compile() )
zeek::reporter->InternalError("failed compiling table/set key pattern: %s", reporter->InternalError("failed compiling table/set key pattern: %s",
re->PatternText()); re->PatternText());
*pval = zeek::make_intrusive<zeek::PatternVal>(re); *pval = make_intrusive<PatternVal>(re);
} }
break; break;
case zeek::TYPE_RECORD: case TYPE_RECORD:
{ {
const char* kp = kp0; const char* kp = kp0;
zeek::RecordType* rt = t->AsRecordType(); RecordType* rt = t->AsRecordType();
int num_fields = rt->NumFields(); int num_fields = rt->NumFields();
std::vector<zeek::ValPtr> values; std::vector<ValPtr> values;
int i; int i;
for ( i = 0; i < num_fields; ++i ) for ( i = 0; i < num_fields; ++i )
{ {
zeek::ValPtr v; ValPtr v;
zeek::detail::Attributes* a = rt->FieldDecl(i)->attrs.get(); Attributes* a = rt->FieldDecl(i)->attrs.get();
bool optional = (a && a->Find(zeek::detail::ATTR_OPTIONAL)); bool optional = (a && a->Find(ATTR_OPTIONAL));
kp = RecoverOneVal(k, kp, k_end, kp = RecoverOneVal(k, kp, k_end,
rt->GetFieldType(i).get(), &v, optional); rt->GetFieldType(i).get(), &v, optional);
@ -922,7 +922,7 @@ const char* CompositeHash::RecoverOneVal(
// NOLINTNEXTLINE(clang-analyzer-core.uninitialized.Branch) // NOLINTNEXTLINE(clang-analyzer-core.uninitialized.Branch)
if ( ! (v || optional) ) if ( ! (v || optional) )
{ {
zeek::reporter->InternalError("didn't recover expected number of fields from HashKey"); reporter->InternalError("didn't recover expected number of fields from HashKey");
pval = nullptr; pval = nullptr;
break; break;
} }
@ -932,7 +932,7 @@ const char* CompositeHash::RecoverOneVal(
ASSERT(int(values.size()) == num_fields); ASSERT(int(values.size()) == num_fields);
auto rv = zeek::make_intrusive<zeek::RecordVal>(zeek::IntrusivePtr{zeek::NewRef{}, rt}); auto rv = make_intrusive<RecordVal>(IntrusivePtr{NewRef{}, rt});
for ( int i = 0; i < num_fields; ++i ) for ( int i = 0; i < num_fields; ++i )
rv->Assign(i, std::move(values[i])); rv->Assign(i, std::move(values[i]));
@ -942,25 +942,25 @@ const char* CompositeHash::RecoverOneVal(
} }
break; break;
case zeek::TYPE_TABLE: case TYPE_TABLE:
{ {
int n; int n;
const int* const kp = AlignType<int>(kp0); const int* const kp = AlignType<int>(kp0);
n = *kp; n = *kp;
kp1 = reinterpret_cast<const char*>(kp+1); kp1 = reinterpret_cast<const char*>(kp+1);
zeek::TableType* tt = t->AsTableType(); TableType* tt = t->AsTableType();
auto tv = zeek::make_intrusive<zeek::TableVal>(zeek::IntrusivePtr{zeek::NewRef{}, tt}); auto tv = make_intrusive<TableVal>(IntrusivePtr{NewRef{}, tt});
for ( int i = 0; i < n; ++i ) for ( int i = 0; i < n; ++i )
{ {
zeek::ValPtr key; ValPtr key;
kp1 = RecoverOneVal(k, kp1, k_end, tt->GetIndices().get(), &key, false); kp1 = RecoverOneVal(k, kp1, k_end, tt->GetIndices().get(), &key, false);
if ( t->IsSet() ) if ( t->IsSet() )
tv->Assign(std::move(key), nullptr); tv->Assign(std::move(key), nullptr);
else else
{ {
zeek::ValPtr value; ValPtr value;
kp1 = RecoverOneVal(k, kp1, k_end, tt->Yield().get(), &value, kp1 = RecoverOneVal(k, kp1, k_end, tt->Yield().get(), &value,
false); false);
tv->Assign(std::move(key), std::move(value)); tv->Assign(std::move(key), std::move(value));
@ -971,14 +971,14 @@ const char* CompositeHash::RecoverOneVal(
} }
break; break;
case zeek::TYPE_VECTOR: case TYPE_VECTOR:
{ {
unsigned int n; unsigned int n;
const unsigned int* kp = AlignType<unsigned int>(kp0); const unsigned int* kp = AlignType<unsigned int>(kp0);
n = *kp; n = *kp;
kp1 = reinterpret_cast<const char*>(kp+1); kp1 = reinterpret_cast<const char*>(kp+1);
zeek::VectorType* vt = t->AsVectorType(); VectorType* vt = t->AsVectorType();
auto vv = zeek::make_intrusive<zeek::VectorVal>(zeek::IntrusivePtr{zeek::NewRef{}, vt}); auto vv = make_intrusive<VectorVal>(IntrusivePtr{NewRef{}, vt});
for ( unsigned int i = 0; i < n; ++i ) for ( unsigned int i = 0; i < n; ++i )
{ {
@ -988,7 +988,7 @@ const char* CompositeHash::RecoverOneVal(
kp = AlignType<unsigned int>(kp1); kp = AlignType<unsigned int>(kp1);
unsigned int have_val = *kp; unsigned int have_val = *kp;
kp1 = reinterpret_cast<const char*>(kp+1); kp1 = reinterpret_cast<const char*>(kp+1);
zeek::ValPtr value; ValPtr value;
if ( have_val ) if ( have_val )
kp1 = RecoverOneVal(k, kp1, k_end, vt->Yield().get(), &value, kp1 = RecoverOneVal(k, kp1, k_end, vt->Yield().get(), &value,
@ -1001,19 +1001,19 @@ const char* CompositeHash::RecoverOneVal(
} }
break; break;
case zeek::TYPE_LIST: case TYPE_LIST:
{ {
int n; int n;
const int* const kp = AlignType<int>(kp0); const int* const kp = AlignType<int>(kp0);
n = *kp; n = *kp;
kp1 = reinterpret_cast<const char*>(kp+1); kp1 = reinterpret_cast<const char*>(kp+1);
zeek::TypeList* tl = t->AsTypeList(); TypeList* tl = t->AsTypeList();
auto lv = zeek::make_intrusive<zeek::ListVal>(zeek::TYPE_ANY); auto lv = make_intrusive<ListVal>(TYPE_ANY);
for ( int i = 0; i < n; ++i ) for ( int i = 0; i < n; ++i )
{ {
zeek::ValPtr v; ValPtr v;
zeek::Type* it = tl->GetTypes()[i].get(); Type* it = tl->GetTypes()[i].get();
kp1 = RecoverOneVal(k, kp1, k_end, it, &v, false); kp1 = RecoverOneVal(k, kp1, k_end, it, &v, false);
lv->Append(std::move(v)); lv->Append(std::move(v));
} }
@ -1024,13 +1024,13 @@ const char* CompositeHash::RecoverOneVal(
default: default:
{ {
zeek::reporter->InternalError("bad index type in CompositeHash::DescribeKey"); reporter->InternalError("bad index type in CompositeHash::DescribeKey");
} }
} }
} }
break; break;
case zeek::TYPE_INTERNAL_STRING: case TYPE_INTERNAL_STRING:
{ {
// There is a minor issue here -- the pointer does not have to // There is a minor issue here -- the pointer does not have to
// be aligned by int in the singleton case. // be aligned by int in the singleton case.
@ -1048,12 +1048,12 @@ const char* CompositeHash::RecoverOneVal(
kp1 = reinterpret_cast<const char*>(kp+1); kp1 = reinterpret_cast<const char*>(kp+1);
} }
*pval = zeek::make_intrusive<zeek::StringVal>(new zeek::String((const zeek::byte_vec) kp1, n, true)); *pval = make_intrusive<StringVal>(new String((const byte_vec) kp1, n, true));
kp1 += n; kp1 += n;
} }
break; break;
case zeek::TYPE_INTERNAL_ERROR: case TYPE_INTERNAL_ERROR:
break; break;
} }

View file

@ -18,32 +18,32 @@ namespace zeek::detail {
class CompositeHash { class CompositeHash {
public: public:
explicit CompositeHash(zeek::TypeListPtr composite_type); explicit CompositeHash(TypeListPtr composite_type);
~CompositeHash(); ~CompositeHash();
// Compute the hash corresponding to the given index val, // Compute the hash corresponding to the given index val,
// or nullptr if it fails to typecheck. // or nullptr if it fails to typecheck.
std::unique_ptr<zeek::detail::HashKey> MakeHashKey(const zeek::Val& v, bool type_check) const; std::unique_ptr<HashKey> MakeHashKey(const Val& v, bool type_check) const;
[[deprecated("Remove in v4.1. Use MakeHashKey().")]] [[deprecated("Remove in v4.1. Use MakeHashKey().")]]
zeek::detail::HashKey* ComputeHash(const zeek::Val* v, bool type_check) const HashKey* ComputeHash(const Val* v, bool type_check) const
{ return MakeHashKey(*v, type_check).release(); } { return MakeHashKey(*v, type_check).release(); }
// Given a hash key, recover the values used to create it. // Given a hash key, recover the values used to create it.
zeek::ListValPtr RecoverVals(const zeek::detail::HashKey& k) const; ListValPtr RecoverVals(const HashKey& k) const;
[[deprecated("Remove in v4.1. Pass in zeek::detail::HashKey& instead.")]] [[deprecated("Remove in v4.1. Pass in HashKey& instead.")]]
zeek::ListValPtr RecoverVals(const zeek::detail::HashKey* k) const ListValPtr RecoverVals(const HashKey* k) const
{ return RecoverVals(*k); } { return RecoverVals(*k); }
unsigned int MemoryAllocation() const { return padded_sizeof(*this) + zeek::util::pad_size(size); } unsigned int MemoryAllocation() const { return padded_sizeof(*this) + util::pad_size(size); }
protected: protected:
std::unique_ptr<zeek::detail::HashKey> ComputeSingletonHash(const zeek::Val* v, bool type_check) const; std::unique_ptr<HashKey> ComputeSingletonHash(const Val* v, bool type_check) const;
// Computes the piece of the hash for Val*, returning the new kp. // Computes the piece of the hash for Val*, returning the new kp.
// Used as a helper for ComputeHash in the non-singleton case. // Used as a helper for ComputeHash in the non-singleton case.
char* SingleValHash(bool type_check, char* kp, zeek::Type* bt, zeek::Val* v, char* SingleValHash(bool type_check, char* kp, Type* bt, Val* v,
bool optional) const; bool optional) const;
// Recovers just one Val of possibly many; called from RecoverVals. // Recovers just one Val of possibly many; called from RecoverVals.
@ -51,8 +51,8 @@ protected:
// Returns and updated kp for the next Val. Calls reporter->InternalError() // Returns and updated kp for the next Val. Calls reporter->InternalError()
// upon errors, so there is no return value for invalid input. // upon errors, so there is no return value for invalid input.
const char* RecoverOneVal( const char* RecoverOneVal(
const zeek::detail::HashKey& k, const char* kp, const char* const k_end, const HashKey& k, const char* kp, const char* const k_end,
zeek::Type* t, zeek::ValPtr* pval, bool optional) const; Type* t, ValPtr* pval, bool optional) const;
// Rounds the given pointer up to the nearest multiple of the // Rounds the given pointer up to the nearest multiple of the
// given size, if not already a multiple. // given size, if not already a multiple.
@ -88,14 +88,14 @@ protected:
// the value is computed for the particular list of values. // the value is computed for the particular list of values.
// Returns 0 if the key has an indeterminant size (if v not given), // Returns 0 if the key has an indeterminant size (if v not given),
// or if v doesn't match the index type (if given). // or if v doesn't match the index type (if given).
int ComputeKeySize(const zeek::Val* v, bool type_check, int ComputeKeySize(const Val* v, bool type_check,
bool calc_static_size) const; bool calc_static_size) const;
int SingleTypeKeySize(zeek::Type*, const zeek::Val*, int SingleTypeKeySize(Type*, const Val*,
bool type_check, int sz, bool optional, bool type_check, int sz, bool optional,
bool calc_static_size) const; bool calc_static_size) const;
zeek::TypeListPtr type; TypeListPtr type;
char* key; // space for composite key char* key; // space for composite key
int size; int size;
bool is_singleton; // if just one type in index bool is_singleton; // if just one type in index
@ -103,7 +103,7 @@ protected:
// If one type, but not normal "singleton", e.g. record. // If one type, but not normal "singleton", e.g. record.
bool is_complex_type; bool is_complex_type;
zeek::InternalTypeTag singleton_tag; InternalTypeTag singleton_tag;
}; };
} // namespace zeek::detail } // namespace zeek::detail

View file

@ -25,7 +25,7 @@ namespace zeek {
namespace detail { namespace detail {
void ConnectionTimer::Init(Connection* arg_conn, timer_func arg_timer, void ConnectionTimer::Init(Connection* arg_conn, timer_func arg_timer,
bool arg_do_expire) bool arg_do_expire)
{ {
conn = arg_conn; conn = arg_conn;
timer = arg_timer; timer = arg_timer;
@ -36,7 +36,7 @@ void ConnectionTimer::Init(Connection* arg_conn, timer_func arg_timer,
ConnectionTimer::~ConnectionTimer() ConnectionTimer::~ConnectionTimer()
{ {
if ( conn->RefCnt() < 1 ) if ( conn->RefCnt() < 1 )
zeek::reporter->InternalError("reference count inconsistency in ~ConnectionTimer"); reporter->InternalError("reference count inconsistency in ~ConnectionTimer");
conn->RemoveTimer(this); conn->RemoveTimer(this);
Unref(conn); Unref(conn);
@ -54,7 +54,7 @@ void ConnectionTimer::Dispatch(double t, bool is_expire)
(conn->*timer)(t); (conn->*timer)(t);
if ( conn->RefCnt() < 1 ) if ( conn->RefCnt() < 1 )
zeek::reporter->InternalError("reference count inconsistency in ConnectionTimer::Dispatch"); reporter->InternalError("reference count inconsistency in ConnectionTimer::Dispatch");
} }
} // namespace detail } // namespace detail
@ -62,9 +62,9 @@ void ConnectionTimer::Dispatch(double t, bool is_expire)
uint64_t Connection::total_connections = 0; uint64_t Connection::total_connections = 0;
uint64_t Connection::current_connections = 0; uint64_t Connection::current_connections = 0;
Connection::Connection(zeek::NetSessions* s, const zeek::detail::ConnIDKey& k, double t, Connection::Connection(NetSessions* s, const detail::ConnIDKey& k, double t,
const ConnID* id, uint32_t flow, const zeek::Packet* pkt, const ConnID* id, uint32_t flow, const Packet* pkt,
const zeek::EncapsulationStack* arg_encap) const EncapsulationStack* arg_encap)
{ {
sessions = s; sessions = s;
key = k; key = k;
@ -122,7 +122,7 @@ Connection::Connection(zeek::NetSessions* s, const zeek::detail::ConnIDKey& k, d
++total_connections; ++total_connections;
if ( arg_encap ) if ( arg_encap )
encapsulation = new zeek::EncapsulationStack(*arg_encap); encapsulation = new EncapsulationStack(*arg_encap);
else else
encapsulation = nullptr; encapsulation = nullptr;
} }
@ -130,7 +130,7 @@ Connection::Connection(zeek::NetSessions* s, const zeek::detail::ConnIDKey& k, d
Connection::~Connection() Connection::~Connection()
{ {
if ( ! finished ) if ( ! finished )
zeek::reporter->InternalError("Done() not called before destruction of Connection"); reporter->InternalError("Done() not called before destruction of Connection");
CancelTimers(); CancelTimers();
@ -143,7 +143,7 @@ Connection::~Connection()
--current_connections; --current_connections;
} }
void Connection::CheckEncapsulation(const zeek::EncapsulationStack* arg_encap) void Connection::CheckEncapsulation(const EncapsulationStack* arg_encap)
{ {
if ( encapsulation && arg_encap ) if ( encapsulation && arg_encap )
{ {
@ -154,7 +154,7 @@ void Connection::CheckEncapsulation(const zeek::EncapsulationStack* arg_encap)
arg_encap->ToVal()); arg_encap->ToVal());
delete encapsulation; delete encapsulation;
encapsulation = new zeek::EncapsulationStack(*arg_encap); encapsulation = new EncapsulationStack(*arg_encap);
} }
} }
@ -162,7 +162,7 @@ void Connection::CheckEncapsulation(const zeek::EncapsulationStack* arg_encap)
{ {
if ( tunnel_changed ) if ( tunnel_changed )
{ {
zeek::EncapsulationStack empty; EncapsulationStack empty;
EnqueueEvent(tunnel_changed, nullptr, ConnVal(), empty.ToVal()); EnqueueEvent(tunnel_changed, nullptr, ConnVal(), empty.ToVal());
} }
@ -175,7 +175,7 @@ void Connection::CheckEncapsulation(const zeek::EncapsulationStack* arg_encap)
if ( tunnel_changed ) if ( tunnel_changed )
EnqueueEvent(tunnel_changed, nullptr, ConnVal(), arg_encap->ToVal()); EnqueueEvent(tunnel_changed, nullptr, ConnVal(), arg_encap->ToVal());
encapsulation = new zeek::EncapsulationStack(*arg_encap); encapsulation = new EncapsulationStack(*arg_encap);
} }
} }
@ -188,14 +188,14 @@ void Connection::Done()
} }
void Connection::NextPacket(double t, bool is_orig, void Connection::NextPacket(double t, bool is_orig,
const zeek::IP_Hdr* ip, int len, int caplen, const IP_Hdr* ip, int len, int caplen,
const u_char*& data, const u_char*& data,
int& record_packet, int& record_content, int& record_packet, int& record_content,
// arguments for reproducing packets // arguments for reproducing packets
const zeek::Packet *pkt) const Packet *pkt)
{ {
zeek::run_state::current_timestamp = t; run_state::current_timestamp = t;
zeek::run_state::current_pkt = pkt; run_state::current_pkt = pkt;
if ( Skipping() ) if ( Skipping() )
return; return;
@ -218,14 +218,14 @@ void Connection::NextPacket(double t, bool is_orig,
else else
last_time = t; last_time = t;
zeek::run_state::current_timestamp = 0; run_state::current_timestamp = 0;
zeek::run_state::current_pkt = nullptr; run_state::current_pkt = nullptr;
} }
void Connection::SetLifetime(double lifetime) void Connection::SetLifetime(double lifetime)
{ {
ADD_TIMER(&Connection::DeleteTimer, zeek::run_state::network_time + lifetime, 0, ADD_TIMER(&Connection::DeleteTimer, run_state::network_time + lifetime, 0,
zeek::detail::TIMER_CONN_DELETE); detail::TIMER_CONN_DELETE);
} }
bool Connection::IsReuse(double t, const u_char* pkt) bool Connection::IsReuse(double t, const u_char* pkt)
@ -258,7 +258,7 @@ bool Connection::ScaledHistoryEntry(char code, uint32_t& counter,
return false; return false;
} }
void Connection::HistoryThresholdEvent(zeek::EventHandlerPtr e, bool is_orig, void Connection::HistoryThresholdEvent(EventHandlerPtr e, bool is_orig,
uint32_t threshold) uint32_t threshold)
{ {
if ( ! e ) if ( ! e )
@ -271,8 +271,8 @@ void Connection::HistoryThresholdEvent(zeek::EventHandlerPtr e, bool is_orig,
EnqueueEvent(e, nullptr, EnqueueEvent(e, nullptr,
ConnVal(), ConnVal(),
zeek::val_mgr->Bool(is_orig), val_mgr->Bool(is_orig),
zeek::val_mgr->Count(threshold) val_mgr->Count(threshold)
); );
} }
@ -290,12 +290,12 @@ void Connection::InactivityTimer(double t)
{ {
Event(connection_timeout, nullptr); Event(connection_timeout, nullptr);
sessions->Remove(this); sessions->Remove(this);
++zeek::detail::killed_by_inactivity; ++detail::killed_by_inactivity;
} }
else else
ADD_TIMER(&Connection::InactivityTimer, ADD_TIMER(&Connection::InactivityTimer,
last_time + inactivity_timeout, 0, last_time + inactivity_timeout, 0,
zeek::detail::TIMER_CONN_INACTIVITY); detail::TIMER_CONN_INACTIVITY);
} }
void Connection::RemoveConnectionTimer(double t) void Connection::RemoveConnectionTimer(double t)
@ -311,15 +311,15 @@ void Connection::SetInactivityTimeout(double timeout)
// First cancel and remove any existing inactivity timer. // First cancel and remove any existing inactivity timer.
for ( const auto& timer : timers ) for ( const auto& timer : timers )
if ( timer->Type() == zeek::detail::TIMER_CONN_INACTIVITY ) if ( timer->Type() == detail::TIMER_CONN_INACTIVITY )
{ {
zeek::detail::timer_mgr->Cancel(timer); detail::timer_mgr->Cancel(timer);
break; break;
} }
if ( timeout ) if ( timeout )
ADD_TIMER(&Connection::InactivityTimer, ADD_TIMER(&Connection::InactivityTimer,
last_time + timeout, 0, zeek::detail::TIMER_CONN_INACTIVITY); last_time + timeout, 0, detail::TIMER_CONN_INACTIVITY);
inactivity_timeout = timeout; inactivity_timeout = timeout;
} }
@ -329,8 +329,8 @@ void Connection::EnableStatusUpdateTimer()
if ( connection_status_update && zeek::detail::connection_status_update_interval ) if ( connection_status_update && zeek::detail::connection_status_update_interval )
{ {
ADD_TIMER(&Connection::StatusUpdateTimer, ADD_TIMER(&Connection::StatusUpdateTimer,
zeek::run_state::network_time + zeek::detail::connection_status_update_interval, 0, run_state::network_time + detail::connection_status_update_interval, 0,
zeek::detail::TIMER_CONN_STATUS_UPDATE); detail::TIMER_CONN_STATUS_UPDATE);
installed_status_timer = 1; installed_status_timer = 1;
} }
} }
@ -339,95 +339,95 @@ void Connection::StatusUpdateTimer(double t)
{ {
EnqueueEvent(connection_status_update, nullptr, ConnVal()); EnqueueEvent(connection_status_update, nullptr, ConnVal());
ADD_TIMER(&Connection::StatusUpdateTimer, ADD_TIMER(&Connection::StatusUpdateTimer,
zeek::run_state::network_time + zeek::detail::connection_status_update_interval, 0, run_state::network_time + detail::connection_status_update_interval, 0,
zeek::detail::TIMER_CONN_STATUS_UPDATE); detail::TIMER_CONN_STATUS_UPDATE);
} }
zeek::RecordVal* Connection::BuildConnVal() RecordVal* Connection::BuildConnVal()
{ {
return ConnVal()->Ref()->AsRecordVal(); return ConnVal()->Ref()->AsRecordVal();
} }
const zeek::RecordValPtr& Connection::ConnVal() const RecordValPtr& Connection::ConnVal()
{ {
if ( ! conn_val ) if ( ! conn_val )
{ {
conn_val = zeek::make_intrusive<zeek::RecordVal>(zeek::id::connection); conn_val = make_intrusive<RecordVal>(id::connection);
TransportProto prot_type = ConnTransport(); TransportProto prot_type = ConnTransport();
auto id_val = zeek::make_intrusive<zeek::RecordVal>(zeek::id::conn_id); auto id_val = make_intrusive<RecordVal>(id::conn_id);
id_val->Assign(0, zeek::make_intrusive<zeek::AddrVal>(orig_addr)); id_val->Assign(0, make_intrusive<AddrVal>(orig_addr));
id_val->Assign(1, zeek::val_mgr->Port(ntohs(orig_port), prot_type)); id_val->Assign(1, val_mgr->Port(ntohs(orig_port), prot_type));
id_val->Assign(2, zeek::make_intrusive<zeek::AddrVal>(resp_addr)); id_val->Assign(2, make_intrusive<AddrVal>(resp_addr));
id_val->Assign(3, zeek::val_mgr->Port(ntohs(resp_port), prot_type)); id_val->Assign(3, val_mgr->Port(ntohs(resp_port), prot_type));
auto orig_endp = zeek::make_intrusive<zeek::RecordVal>(zeek::id::endpoint); auto orig_endp = make_intrusive<RecordVal>(id::endpoint);
orig_endp->Assign(0, zeek::val_mgr->Count(0)); orig_endp->Assign(0, val_mgr->Count(0));
orig_endp->Assign(1, zeek::val_mgr->Count(0)); orig_endp->Assign(1, val_mgr->Count(0));
orig_endp->Assign(4, zeek::val_mgr->Count(orig_flow_label)); orig_endp->Assign(4, val_mgr->Count(orig_flow_label));
const int l2_len = sizeof(orig_l2_addr); const int l2_len = sizeof(orig_l2_addr);
char null[l2_len]{}; char null[l2_len]{};
if ( memcmp(&orig_l2_addr, &null, l2_len) != 0 ) if ( memcmp(&orig_l2_addr, &null, l2_len) != 0 )
orig_endp->Assign(5, zeek::make_intrusive<zeek::StringVal>(fmt_mac(orig_l2_addr, l2_len))); orig_endp->Assign(5, make_intrusive<StringVal>(fmt_mac(orig_l2_addr, l2_len)));
auto resp_endp = zeek::make_intrusive<zeek::RecordVal>(zeek::id::endpoint); auto resp_endp = make_intrusive<RecordVal>(id::endpoint);
resp_endp->Assign(0, zeek::val_mgr->Count(0)); resp_endp->Assign(0, val_mgr->Count(0));
resp_endp->Assign(1, zeek::val_mgr->Count(0)); resp_endp->Assign(1, val_mgr->Count(0));
resp_endp->Assign(4, zeek::val_mgr->Count(resp_flow_label)); resp_endp->Assign(4, val_mgr->Count(resp_flow_label));
if ( memcmp(&resp_l2_addr, &null, l2_len) != 0 ) if ( memcmp(&resp_l2_addr, &null, l2_len) != 0 )
resp_endp->Assign(5, zeek::make_intrusive<zeek::StringVal>(fmt_mac(resp_l2_addr, l2_len))); resp_endp->Assign(5, make_intrusive<StringVal>(fmt_mac(resp_l2_addr, l2_len)));
conn_val->Assign(0, std::move(id_val)); conn_val->Assign(0, std::move(id_val));
conn_val->Assign(1, std::move(orig_endp)); conn_val->Assign(1, std::move(orig_endp));
conn_val->Assign(2, std::move(resp_endp)); conn_val->Assign(2, std::move(resp_endp));
// 3 and 4 are set below. // 3 and 4 are set below.
conn_val->Assign(5, zeek::make_intrusive<zeek::TableVal>(zeek::id::string_set)); // service conn_val->Assign(5, make_intrusive<TableVal>(id::string_set)); // service
conn_val->Assign(6, zeek::val_mgr->EmptyString()); // history conn_val->Assign(6, val_mgr->EmptyString()); // history
if ( ! uid ) if ( ! uid )
uid.Set(zeek::detail::bits_per_uid); uid.Set(zeek::detail::bits_per_uid);
conn_val->Assign(7, zeek::make_intrusive<zeek::StringVal>(uid.Base62("C").c_str())); conn_val->Assign(7, make_intrusive<StringVal>(uid.Base62("C").c_str()));
if ( encapsulation && encapsulation->Depth() > 0 ) if ( encapsulation && encapsulation->Depth() > 0 )
conn_val->Assign(8, encapsulation->ToVal()); conn_val->Assign(8, encapsulation->ToVal());
if ( vlan != 0 ) if ( vlan != 0 )
conn_val->Assign(9, zeek::val_mgr->Int(vlan)); conn_val->Assign(9, val_mgr->Int(vlan));
if ( inner_vlan != 0 ) if ( inner_vlan != 0 )
conn_val->Assign(10, zeek::val_mgr->Int(inner_vlan)); conn_val->Assign(10, val_mgr->Int(inner_vlan));
} }
if ( root_analyzer ) if ( root_analyzer )
root_analyzer->UpdateConnVal(conn_val.get()); root_analyzer->UpdateConnVal(conn_val.get());
conn_val->Assign(3, zeek::make_intrusive<zeek::TimeVal>(start_time)); // ### conn_val->Assign(3, make_intrusive<TimeVal>(start_time)); // ###
conn_val->Assign(4, zeek::make_intrusive<zeek::IntervalVal>(last_time - start_time)); conn_val->Assign(4, make_intrusive<IntervalVal>(last_time - start_time));
conn_val->Assign(6, zeek::make_intrusive<zeek::StringVal>(history.c_str())); conn_val->Assign(6, make_intrusive<StringVal>(history.c_str()));
conn_val->Assign(11, zeek::val_mgr->Bool(is_successful)); conn_val->Assign(11, val_mgr->Bool(is_successful));
conn_val->SetOrigin(this); conn_val->SetOrigin(this);
return conn_val; return conn_val;
} }
zeek::analyzer::Analyzer* Connection::FindAnalyzer(zeek::analyzer::ID id) analyzer::Analyzer* Connection::FindAnalyzer(analyzer::ID id)
{ {
return root_analyzer ? root_analyzer->FindChild(id) : nullptr; return root_analyzer ? root_analyzer->FindChild(id) : nullptr;
} }
zeek::analyzer::Analyzer* Connection::FindAnalyzer(const zeek::analyzer::Tag& tag) analyzer::Analyzer* Connection::FindAnalyzer(const analyzer::Tag& tag)
{ {
return root_analyzer ? root_analyzer->FindChild(tag) : nullptr; return root_analyzer ? root_analyzer->FindChild(tag) : nullptr;
} }
zeek::analyzer::Analyzer* Connection::FindAnalyzer(const char* name) analyzer::Analyzer* Connection::FindAnalyzer(const char* name)
{ {
return root_analyzer->FindChild(name); return root_analyzer->FindChild(name);
} }
@ -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>(zeek::util::fmt(format, old, str))); cv->Assign(6, make_intrusive<StringVal>(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.
@ -455,7 +455,7 @@ static inline bool is_version_sep(const char* s, const char* end)
isspace(s[0]); isspace(s[0]);
} }
void Connection::Match(zeek::detail::Rule::PatternType type, const u_char* data, int len, void Connection::Match(detail::Rule::PatternType type, const u_char* data, int len,
bool is_orig, bool bol, bool eol, bool clear_state) bool is_orig, bool bol, bool eol, bool clear_state)
{ {
if ( primary_PIA ) if ( primary_PIA )
@ -471,18 +471,18 @@ void Connection::RemovalEvent()
EnqueueEvent(successful_connection_remove, nullptr, ConnVal()); EnqueueEvent(successful_connection_remove, nullptr, ConnVal());
} }
void Connection::Event(zeek::EventHandlerPtr f, zeek::analyzer::Analyzer* analyzer, const char* name) void Connection::Event(EventHandlerPtr f, analyzer::Analyzer* analyzer, const char* name)
{ {
if ( ! f ) if ( ! f )
return; return;
if ( name ) if ( name )
EnqueueEvent(f, analyzer, zeek::make_intrusive<zeek::StringVal>(name), ConnVal()); EnqueueEvent(f, analyzer, make_intrusive<StringVal>(name), ConnVal());
else else
EnqueueEvent(f, analyzer, ConnVal()); EnqueueEvent(f, analyzer, ConnVal());
} }
void Connection::Event(zeek::EventHandlerPtr f, zeek::analyzer::Analyzer* analyzer, zeek::Val* v1, zeek::Val* v2) void Connection::Event(EventHandlerPtr f, analyzer::Analyzer* analyzer, Val* v1, Val* v2)
{ {
if ( ! f ) if ( ! f )
{ {
@ -494,17 +494,17 @@ void Connection::Event(zeek::EventHandlerPtr f, zeek::analyzer::Analyzer* analyz
if ( v2 ) if ( v2 )
EnqueueEvent(f, analyzer, EnqueueEvent(f, analyzer,
ConnVal(), ConnVal(),
zeek::IntrusivePtr{zeek::AdoptRef{}, v1}, IntrusivePtr{AdoptRef{}, v1},
zeek::IntrusivePtr{zeek::AdoptRef{}, v2}); IntrusivePtr{AdoptRef{}, v2});
else else
EnqueueEvent(f, analyzer, EnqueueEvent(f, analyzer,
ConnVal(), ConnVal(),
zeek::IntrusivePtr{zeek::AdoptRef{}, v1}); IntrusivePtr{AdoptRef{}, v1});
} }
void Connection::ConnectionEvent(zeek::EventHandlerPtr f, zeek::analyzer::Analyzer* a, ValPList vl) void Connection::ConnectionEvent(EventHandlerPtr f, analyzer::Analyzer* a, ValPList vl)
{ {
auto args = zeek::val_list_to_args(vl); auto args = val_list_to_args(vl);
if ( ! f ) if ( ! f )
// This may actually happen if there is no local handler // This may actually happen if there is no local handler
@ -512,40 +512,40 @@ 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), zeek::util::detail::SOURCE_LOCAL, a ? a->GetID() : 0, this); event_mgr.Enqueue(f, std::move(args), util::detail::SOURCE_LOCAL, a ? a->GetID() : 0, this);
} }
void Connection::ConnectionEventFast(zeek::EventHandlerPtr f, zeek::analyzer::Analyzer* a, ValPList vl) void Connection::ConnectionEventFast(EventHandlerPtr f, analyzer::Analyzer* a, ValPList 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), zeek::util::detail::SOURCE_LOCAL, event_mgr.Enqueue(f, val_list_to_args(vl), util::detail::SOURCE_LOCAL,
a ? a->GetID() : 0, this); a ? a->GetID() : 0, this);
} }
void Connection::ConnectionEvent(zeek::EventHandlerPtr f, zeek::analyzer::Analyzer* a, ValPList* vl) void Connection::ConnectionEvent(EventHandlerPtr f, analyzer::Analyzer* a, ValPList* vl)
{ {
auto args = zeek::val_list_to_args(*vl); auto args = val_list_to_args(*vl);
delete vl; delete vl;
if ( f ) if ( f )
EnqueueEvent(f, a, std::move(args)); EnqueueEvent(f, a, std::move(args));
} }
void Connection::EnqueueEvent(zeek::EventHandlerPtr f, zeek::analyzer::Analyzer* a, void Connection::EnqueueEvent(EventHandlerPtr f, analyzer::Analyzer* a,
zeek::Args args) 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::detail::SOURCE_LOCAL, a ? a->GetID() : 0, this); event_mgr.Enqueue(f, std::move(args), 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)
{ {
weird = 1; weird = 1;
zeek::reporter->Weird(this, name, addl ? addl : ""); reporter->Weird(this, name, addl ? addl : "");
} }
void Connection::AddTimer(timer_func timer, double t, bool do_expire, void Connection::AddTimer(timer_func timer, double t, bool do_expire,
zeek::detail::TimerType type) detail::TimerType type)
{ {
if ( timers_canceled ) if ( timers_canceled )
return; return;
@ -556,12 +556,12 @@ void Connection::AddTimer(timer_func timer, double t, bool do_expire,
if ( ! key_valid ) if ( ! key_valid )
return; return;
zeek::detail::Timer* conn_timer = new detail::ConnectionTimer(this, timer, t, do_expire, type); detail::Timer* conn_timer = new detail::ConnectionTimer(this, timer, t, do_expire, type);
zeek::detail::timer_mgr->Add(conn_timer); detail::timer_mgr->Add(conn_timer);
timers.push_back(conn_timer); timers.push_back(conn_timer);
} }
void Connection::RemoveTimer(zeek::detail::Timer* t) void Connection::RemoveTimer(detail::Timer* t)
{ {
timers.remove(t); timers.remove(t);
} }
@ -576,7 +576,7 @@ void Connection::CancelTimers()
std::copy(timers.begin(), timers.end(), std::back_inserter(tmp)); std::copy(timers.begin(), timers.end(), std::back_inserter(tmp));
for ( const auto& timer : tmp ) for ( const auto& timer : tmp )
zeek::detail::timer_mgr->Cancel(timer); detail::timer_mgr->Cancel(timer);
timers_canceled = 1; timers_canceled = 1;
timers.clear(); timers.clear();
@ -584,7 +584,7 @@ void Connection::CancelTimers()
void Connection::FlipRoles() void Connection::FlipRoles()
{ {
zeek::IPAddr tmp_addr = resp_addr; IPAddr tmp_addr = resp_addr;
resp_addr = orig_addr; resp_addr = orig_addr;
orig_addr = tmp_addr; orig_addr = tmp_addr;
@ -611,7 +611,7 @@ void Connection::FlipRoles()
if ( root_analyzer ) if ( root_analyzer )
root_analyzer->FlipRoles(); root_analyzer->FlipRoles();
zeek::analyzer_mgr->ApplyScheduledAnalyzers(this); analyzer_mgr->ApplyScheduledAnalyzers(this);
AddHistory('^'); AddHistory('^');
} }
@ -632,7 +632,7 @@ unsigned int Connection::MemoryAllocationConnVal() const
return conn_val ? conn_val->MemoryAllocation() : 0; return conn_val ? conn_val->MemoryAllocation() : 0;
} }
void Connection::Describe(zeek::ODesc* d) const void Connection::Describe(ODesc* d) const
{ {
d->Add(start_time); d->Add(start_time);
d->Add("("); d->Add("(");
@ -654,13 +654,13 @@ void Connection::Describe(zeek::ODesc* d) const
case TRANSPORT_UNKNOWN: case TRANSPORT_UNKNOWN:
d->Add("unknown"); d->Add("unknown");
zeek::reporter->InternalWarning( reporter->InternalWarning(
"unknown transport in Connction::Describe()"); "unknown transport in Connction::Describe()");
break; break;
default: default:
zeek::reporter->InternalError( reporter->InternalError(
"unhandled transport type in Connection::Describe"); "unhandled transport type in Connection::Describe");
} }
@ -679,7 +679,7 @@ void Connection::Describe(zeek::ODesc* d) const
d->NL(); d->NL();
} }
void Connection::IDString(zeek::ODesc* d) const void Connection::IDString(ODesc* d) const
{ {
d->Add(orig_addr); d->Add(orig_addr);
d->AddRaw(":", 1); d->AddRaw(":", 1);
@ -690,8 +690,8 @@ void Connection::IDString(zeek::ODesc* d) const
d->Add(ntohs(resp_port)); d->Add(ntohs(resp_port));
} }
void Connection::SetRootAnalyzer(zeek::analyzer::TransportLayerAnalyzer* analyzer, void Connection::SetRootAnalyzer(analyzer::TransportLayerAnalyzer* analyzer,
zeek::analyzer::pia::PIA* pia) analyzer::pia::PIA* pia)
{ {
root_analyzer = analyzer; root_analyzer = analyzer;
primary_PIA = pia; primary_PIA = pia;
@ -705,8 +705,8 @@ void Connection::CheckFlowLabel(bool is_orig, uint32_t flow_label)
{ {
if ( conn_val ) if ( conn_val )
{ {
zeek::RecordVal* endp = conn_val->GetField(is_orig ? 1 : 2)->AsRecordVal(); RecordVal* endp = conn_val->GetField(is_orig ? 1 : 2)->AsRecordVal();
endp->Assign(4, zeek::val_mgr->Count(flow_label)); endp->Assign(4, val_mgr->Count(flow_label));
} }
if ( connection_flow_label_changed && if ( connection_flow_label_changed &&
@ -714,9 +714,9 @@ void Connection::CheckFlowLabel(bool is_orig, uint32_t flow_label)
{ {
EnqueueEvent(connection_flow_label_changed, nullptr, EnqueueEvent(connection_flow_label_changed, nullptr,
ConnVal(), ConnVal(),
zeek::val_mgr->Bool(is_orig), val_mgr->Bool(is_orig),
zeek::val_mgr->Count(my_flow_label), val_mgr->Count(my_flow_label),
zeek::val_mgr->Count(flow_label) val_mgr->Count(flow_label)
); );
} }
@ -732,7 +732,7 @@ void Connection::CheckFlowLabel(bool is_orig, uint32_t flow_label)
bool Connection::PermitWeird(const char* name, uint64_t threshold, uint64_t rate, bool Connection::PermitWeird(const char* name, uint64_t threshold, uint64_t rate,
double duration) double duration)
{ {
return zeek::detail::PermitWeird(weird_state, name, threshold, rate, duration); return detail::PermitWeird(weird_state, name, threshold, rate, duration);
} }
} // namespace zeek } // namespace zeek

View file

@ -36,8 +36,8 @@ ZEEK_FORWARD_DECLARE_NAMESPACED(TransportLayerAnalyzer, zeek, analyzer);
ZEEK_FORWARD_DECLARE_NAMESPACED(Analyzer, zeek, analyzer); ZEEK_FORWARD_DECLARE_NAMESPACED(Analyzer, zeek, analyzer);
namespace zeek { namespace zeek {
using ValPtr = zeek::IntrusivePtr<Val>; using ValPtr = IntrusivePtr<Val>;
using RecordValPtr = zeek::IntrusivePtr<RecordVal>; using RecordValPtr = IntrusivePtr<RecordVal>;
enum ConnEventToFlag { enum ConnEventToFlag {
NUL_IN_LINE, NUL_IN_LINE,
@ -49,23 +49,23 @@ enum ConnEventToFlag {
typedef void (Connection::*timer_func)(double t); typedef void (Connection::*timer_func)(double t);
struct ConnID { struct ConnID {
zeek::IPAddr src_addr; IPAddr src_addr;
zeek::IPAddr dst_addr; IPAddr dst_addr;
uint32_t src_port; uint32_t src_port;
uint32_t dst_port; uint32_t dst_port;
bool is_one_way; // if true, don't canonicalize order bool is_one_way; // if true, don't canonicalize order
}; };
static inline int addr_port_canon_lt(const zeek::IPAddr& addr1, uint32_t p1, static inline int addr_port_canon_lt(const IPAddr& addr1, uint32_t p1,
const zeek::IPAddr& addr2, uint32_t p2) const IPAddr& addr2, uint32_t p2)
{ {
return addr1 < addr2 || (addr1 == addr2 && p1 < p2); return addr1 < addr2 || (addr1 == addr2 && p1 < p2);
} }
class Connection final : public zeek::Obj { class Connection final : public Obj {
public: public:
Connection(zeek::NetSessions* s, const zeek::detail::ConnIDKey& k, double t, const ConnID* id, Connection(NetSessions* s, const detail::ConnIDKey& k, double t, const ConnID* id,
uint32_t flow, const zeek::Packet* pkt, const zeek::EncapsulationStack* arg_encap); uint32_t flow, const Packet* pkt, const EncapsulationStack* arg_encap);
~Connection() override; ~Connection() override;
// Invoked when an encapsulation is discovered. It records the // Invoked when an encapsulation is discovered. It records the
@ -73,7 +73,7 @@ public:
// event if it's different from the previous encapsulation (or the // event if it's different from the previous encapsulation (or the
// first encountered). encap can be null to indicate no // first encountered). encap can be null to indicate no
// encapsulation. // encapsulation.
void CheckEncapsulation(const zeek::EncapsulationStack* encap); void CheckEncapsulation(const EncapsulationStack* encap);
// Invoked when connection is about to be removed. Use Ref(this) // Invoked when connection is about to be removed. Use Ref(this)
// inside Done to keep the connection object around (though it'll // inside Done to keep the connection object around (though it'll
@ -91,16 +91,16 @@ public:
// be recorded, otherwise just up through the transport header. // be recorded, otherwise just up through the transport header.
// Both are assumed set to true when called. // Both are assumed set to true when called.
void NextPacket(double t, bool is_orig, void NextPacket(double t, bool is_orig,
const zeek::IP_Hdr* ip, int len, int caplen, const IP_Hdr* ip, int len, int caplen,
const u_char*& data, const u_char*& data,
int& record_packet, int& record_content, int& record_packet, int& record_content,
// arguments for reproducing packets // arguments for reproducing packets
const zeek::Packet *pkt); const Packet *pkt);
// Keys are only considered valid for a connection when a // Keys are only considered valid for a connection when a
// connection is in the session map. If it is removed, the key // connection is in the session map. If it is removed, the key
// should be marked invalid. // should be marked invalid.
const zeek::detail::ConnIDKey& Key() const { return key; } const detail::ConnIDKey& Key() const { return key; }
void ClearKey() { key_valid = false; } void ClearKey() { key_valid = false; }
bool IsKeyValid() const { return key_valid; } bool IsKeyValid() const { return key_valid; }
@ -109,17 +109,17 @@ public:
double LastTime() const { return last_time; } double LastTime() const { return last_time; }
void SetLastTime(double t) { last_time = t; } void SetLastTime(double t) { last_time = t; }
const zeek::IPAddr& OrigAddr() const { return orig_addr; } const IPAddr& OrigAddr() const { return orig_addr; }
const zeek::IPAddr& RespAddr() const { return resp_addr; } const IPAddr& RespAddr() const { return resp_addr; }
uint32_t OrigPort() const { return orig_port; } uint32_t OrigPort() const { return orig_port; }
uint32_t RespPort() const { return resp_port; } uint32_t RespPort() const { return resp_port; }
void FlipRoles(); void FlipRoles();
zeek::analyzer::Analyzer* FindAnalyzer(zeek::analyzer::ID id); analyzer::Analyzer* FindAnalyzer(analyzer::ID id);
zeek::analyzer::Analyzer* FindAnalyzer(const zeek::analyzer::Tag& tag); // find first in tree. analyzer::Analyzer* FindAnalyzer(const analyzer::Tag& tag); // find first in tree.
zeek::analyzer::Analyzer* FindAnalyzer(const char* name); // find first in tree. analyzer::Analyzer* FindAnalyzer(const char* name); // find first in tree.
TransportProto ConnTransport() const { return proto; } TransportProto ConnTransport() const { return proto; }
@ -167,18 +167,18 @@ public:
void EnableStatusUpdateTimer(); void EnableStatusUpdateTimer();
[[deprecated("Remove in v4.1. Use ConnVal() instead.")]] [[deprecated("Remove in v4.1. Use ConnVal() instead.")]]
zeek::RecordVal* BuildConnVal(); RecordVal* BuildConnVal();
/** /**
* Returns the associated "connection" record. * Returns the associated "connection" record.
*/ */
const zeek::RecordValPtr& ConnVal(); const RecordValPtr& ConnVal();
void AppendAddl(const char* str); void AppendAddl(const char* str);
LoginConn* AsLoginConn() { return login_conn; } LoginConn* AsLoginConn() { return login_conn; }
void Match(zeek::detail::Rule::PatternType type, const u_char* data, int len, void Match(detail::Rule::PatternType type, const u_char* data, int len,
bool is_orig, bool bol, bool eol, bool clear_state); bool is_orig, bool bol, bool eol, bool clear_state);
/** /**
@ -190,29 +190,27 @@ public:
// given that event's first argument will be it, and it's second will be // given that event's first argument will be it, and it's second will be
// the connection value. If 'name' is null, then the event's first // the connection value. If 'name' is null, then the event's first
// argument is the connection value. // argument is the connection value.
void Event(zeek::EventHandlerPtr f, zeek::analyzer::Analyzer* analyzer, const char* name = nullptr); void Event(EventHandlerPtr f, analyzer::Analyzer* analyzer, const char* name = nullptr);
// If a handler exists for 'f', an event will be generated. In any case, // If a handler exists for 'f', an event will be generated. In any case,
// 'v1' and 'v2' reference counts get decremented. The event's first // 'v1' and 'v2' reference counts get decremented. The event's first
// argument is the connection value, second argument is 'v1', and if 'v2' // argument is the connection value, second argument is 'v1', and if 'v2'
// is given that will be it's third argument. // is given that will be it's third argument.
[[deprecated("Remove in v4.1. Use EnqueueEvent() instead (note it doesn't automatically add the connection argument).")]] [[deprecated("Remove in v4.1. Use EnqueueEvent() instead (note it doesn't automatically add the connection argument).")]]
void Event(zeek::EventHandlerPtr f, zeek::analyzer::Analyzer* analyzer, zeek::Val* v1, zeek::Val* v2 = nullptr); void Event(EventHandlerPtr f, analyzer::Analyzer* analyzer, Val* v1, Val* v2 = nullptr);
// If a handler exists for 'f', an event will be generated. In any case, // If a handler exists for 'f', an event will be generated. In any case,
// reference count for each element in the 'vl' list are decremented. The // reference count for each element in the 'vl' list are decremented. The
// arguments used for the event are whatevever is provided in 'vl'. // arguments used for the event are whatevever is provided in 'vl'.
[[deprecated("Remove in v4.1. Use EnqueueEvent() instead.")]] [[deprecated("Remove in v4.1. Use EnqueueEvent() instead.")]]
void ConnectionEvent(zeek::EventHandlerPtr f, zeek::analyzer::Analyzer* analyzer, void ConnectionEvent(EventHandlerPtr f, analyzer::Analyzer* analyzer, ValPList vl);
ValPList vl);
// Same as ConnectionEvent, except taking the event's argument list via a // Same as ConnectionEvent, except taking the event's argument list via a
// pointer instead of by value. This function takes ownership of the // pointer instead of by value. This function takes ownership of the
// memory pointed to by 'vl' and also for decrementing the reference count // memory pointed to by 'vl' and also for decrementing the reference count
// of each of its elements. // of each of its elements.
[[deprecated("Remove in v4.1. Use EnqueueEvent() instead.")]] [[deprecated("Remove in v4.1. Use EnqueueEvent() instead.")]]
void ConnectionEvent(zeek::EventHandlerPtr f, zeek::analyzer::Analyzer* analyzer, void ConnectionEvent(EventHandlerPtr f, analyzer::Analyzer* analyzer, ValPList* vl);
ValPList* vl);
// Queues an event without first checking if there's any available event // Queues an event without first checking if there's any available event
// handlers (or remote consumes). If it turns out there's actually nothing // handlers (or remote consumes). If it turns out there's actually nothing
@ -229,8 +227,8 @@ public:
/** /**
* Enqueues an event associated with this connection and given analyzer. * Enqueues an event associated with this connection and given analyzer.
*/ */
void EnqueueEvent(zeek::EventHandlerPtr f, zeek::analyzer::Analyzer* analyzer, void EnqueueEvent(EventHandlerPtr f, analyzer::Analyzer* analyzer,
zeek::Args args); Args args);
/** /**
* A version of EnqueueEvent() taking a variable number of arguments. * A version of EnqueueEvent() taking a variable number of arguments.
@ -238,8 +236,8 @@ public:
template <class... Args> template <class... Args>
std::enable_if_t< std::enable_if_t<
std::is_convertible_v< std::is_convertible_v<
std::tuple_element_t<0, std::tuple<Args...>>, zeek::ValPtr>> std::tuple_element_t<0, std::tuple<Args...>>, ValPtr>>
EnqueueEvent(zeek::EventHandlerPtr h, zeek::analyzer::Analyzer* analyzer, Args&&... args) EnqueueEvent(EventHandlerPtr h, analyzer::Analyzer* analyzer, Args&&... args)
{ return EnqueueEvent(h, analyzer, zeek::Args{std::forward<Args>(args)...}); } { return EnqueueEvent(h, analyzer, zeek::Args{std::forward<Args>(args)...}); }
void Weird(const char* name, const char* addl = ""); void Weird(const char* name, const char* addl = "");
@ -260,8 +258,8 @@ public:
return true; return true;
} }
void Describe(zeek::ODesc* d) const override; void Describe(ODesc* d) const override;
void IDString(zeek::ODesc* d) const; void IDString(ODesc* d) const;
// Statistics. // Statistics.
@ -295,7 +293,7 @@ public:
uint32_t& scaling_threshold, uint32_t& scaling_threshold,
uint32_t scaling_base = 10); uint32_t scaling_base = 10);
void HistoryThresholdEvent(zeek::EventHandlerPtr e, bool is_orig, void HistoryThresholdEvent(EventHandlerPtr e, bool is_orig,
uint32_t threshold); uint32_t threshold);
void AddHistory(char code) { history += code; } void AddHistory(char code) { history += code; }
@ -303,18 +301,18 @@ public:
void DeleteTimer(double t); void DeleteTimer(double t);
// Sets the root of the analyzer tree as well as the primary PIA. // Sets the root of the analyzer tree as well as the primary PIA.
void SetRootAnalyzer(zeek::analyzer::TransportLayerAnalyzer* analyzer, zeek::analyzer::pia::PIA* pia); void SetRootAnalyzer(analyzer::TransportLayerAnalyzer* analyzer, analyzer::pia::PIA* pia);
zeek::analyzer::TransportLayerAnalyzer* GetRootAnalyzer() { return root_analyzer; } analyzer::TransportLayerAnalyzer* GetRootAnalyzer() { return root_analyzer; }
zeek::analyzer::pia::PIA* GetPrimaryPIA() { return primary_PIA; } analyzer::pia::PIA* GetPrimaryPIA() { return primary_PIA; }
// Sets the transport protocol in use. // Sets the transport protocol in use.
void SetTransport(TransportProto arg_proto) { proto = arg_proto; } void SetTransport(TransportProto arg_proto) { proto = arg_proto; }
void SetUID(const zeek::UID &arg_uid) { uid = arg_uid; } void SetUID(const UID &arg_uid) { uid = arg_uid; }
zeek::UID GetUID() const { return uid; } UID GetUID() const { return uid; }
const zeek::EncapsulationStack* GetEncapsulation() const const EncapsulationStack* GetEncapsulation() const
{ return encapsulation; } { return encapsulation; }
void CheckFlowLabel(bool is_orig, uint32_t flow_label); void CheckFlowLabel(bool is_orig, uint32_t flow_label);
@ -331,9 +329,9 @@ protected:
// is true, then the timer is also evaluated when Bro terminates, // is true, then the timer is also evaluated when Bro terminates,
// otherwise not. // otherwise not.
void AddTimer(timer_func timer, double t, bool do_expire, void AddTimer(timer_func timer, double t, bool do_expire,
zeek::detail::TimerType type); detail::TimerType type);
void RemoveTimer(zeek::detail::Timer* t); void RemoveTimer(detail::Timer* t);
// Allow other classes to access pointers to these: // Allow other classes to access pointers to these:
friend class detail::ConnectionTimer; friend class detail::ConnectionTimer;
@ -342,25 +340,25 @@ protected:
void StatusUpdateTimer(double t); void StatusUpdateTimer(double t);
void RemoveConnectionTimer(double t); void RemoveConnectionTimer(double t);
zeek::NetSessions* sessions; NetSessions* sessions;
zeek::detail::ConnIDKey key; detail::ConnIDKey key;
bool key_valid; bool key_valid;
TimerPList timers; TimerPList timers;
zeek::IPAddr orig_addr; IPAddr orig_addr;
zeek::IPAddr resp_addr; IPAddr resp_addr;
uint32_t orig_port, resp_port; // in network order uint32_t orig_port, resp_port; // in network order
TransportProto proto; TransportProto proto;
uint32_t orig_flow_label, resp_flow_label; // most recent IPv6 flow labels uint32_t orig_flow_label, resp_flow_label; // most recent IPv6 flow labels
uint32_t vlan, inner_vlan; // VLAN this connection traverses, if available uint32_t vlan, inner_vlan; // VLAN this connection traverses, if available
u_char orig_l2_addr[zeek::Packet::l2_addr_len]; // Link-layer originator address, if available u_char orig_l2_addr[Packet::l2_addr_len]; // Link-layer originator address, if available
u_char resp_l2_addr[zeek::Packet::l2_addr_len]; // Link-layer responder address, if available u_char resp_l2_addr[Packet::l2_addr_len]; // Link-layer responder address, if available
double start_time, last_time; double start_time, last_time;
double inactivity_timeout; double inactivity_timeout;
zeek::RecordValPtr conn_val; RecordValPtr conn_val;
LoginConn* login_conn; // either nil, or this LoginConn* login_conn; // either nil, or this
const zeek::EncapsulationStack* encapsulation; // tunnels const EncapsulationStack* encapsulation; // tunnels
int suppress_event; // suppress certain events to once per conn. int suppress_event; // suppress certain events to once per conn.
unsigned int installed_status_timer:1; unsigned int installed_status_timer:1;
@ -381,20 +379,20 @@ protected:
std::string history; std::string history;
uint32_t hist_seen; uint32_t hist_seen;
zeek::analyzer::TransportLayerAnalyzer* root_analyzer; analyzer::TransportLayerAnalyzer* root_analyzer;
zeek::analyzer::pia::PIA* primary_PIA; analyzer::pia::PIA* primary_PIA;
zeek::UID uid; // Globally unique connection ID. UID uid; // Globally unique connection ID.
zeek::detail::WeirdStateMap weird_state; detail::WeirdStateMap weird_state;
}; };
namespace detail { namespace detail {
class ConnectionTimer final : public zeek::detail::Timer { class ConnectionTimer final : public Timer {
public: public:
ConnectionTimer(Connection* arg_conn, timer_func arg_timer, ConnectionTimer(Connection* arg_conn, timer_func arg_timer,
double arg_t, bool arg_do_expire, zeek::detail::TimerType arg_type) double arg_t, bool arg_do_expire, TimerType arg_type)
: zeek::detail::Timer(arg_t, arg_type) : Timer(arg_t, arg_type)
{ Init(arg_conn, arg_timer, arg_do_expire); } { Init(arg_conn, arg_timer, arg_do_expire); }
~ConnectionTimer() override; ~ConnectionTimer() override;

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)
+ zeek::util::pad_size(sizeof(DFA_State*) * num_sym) + util::pad_size(sizeof(DFA_State*) * num_sym)
+ (accept ? zeek::util::pad_size(sizeof(int) * accept->size()) : 0) + (accept ? util::pad_size(sizeof(int) * accept->size()) : 0)
+ (nfa_states ? zeek::util::pad_size(sizeof(NFA_State*) * nfa_states->length()) : 0) + (nfa_states ? 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 += zeek::util::pad_size(e->Size()) + padded_sizeof(*e); s->mem += util::pad_size(e->Size()) + padded_sizeof(*e);
} }
} }

View file

@ -23,7 +23,7 @@ class DFA_Machine;
#define DFA_UNCOMPUTED_STATE -2 #define DFA_UNCOMPUTED_STATE -2
#define DFA_UNCOMPUTED_STATE_PTR ((DFA_State*) DFA_UNCOMPUTED_STATE) #define DFA_UNCOMPUTED_STATE_PTR ((DFA_State*) DFA_UNCOMPUTED_STATE)
class DFA_State : public zeek::Obj { class DFA_State : public Obj {
public: public:
DFA_State(int state_num, const EquivClass* ec, DFA_State(int state_num, const EquivClass* ec,
NFA_state_list* nfa_states, AcceptingSet* accept); NFA_state_list* nfa_states, AcceptingSet* accept);
@ -108,7 +108,7 @@ private:
std::map<DigestStr, DFA_State*> states; std::map<DigestStr, DFA_State*> states;
}; };
class DFA_Machine : public zeek::Obj { class DFA_Machine : public Obj {
public: public:
DFA_Machine(NFA_Machine* n, EquivClass* ec); DFA_Machine(NFA_Machine* n, EquivClass* ec);
~DFA_Machine() override; ~DFA_Machine() override;

View file

@ -58,11 +58,11 @@ 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(zeek::util::copy_string(h)), fam(af), qtype(is_txt ? 16 : 0), addr(), : host(util::copy_string(h)), fam(af), qtype(is_txt ? 16 : 0), addr(),
request_pending() request_pending()
{ } { }
DNS_Mgr_Request(const zeek::IPAddr& a) DNS_Mgr_Request(const IPAddr& a)
: host(), fam(), qtype(), addr(a), request_pending() : host(), fam(), qtype(), addr(a), request_pending()
{ } { }
@ -70,7 +70,7 @@ public:
// Returns nil if this was an address request. // Returns nil if this was an address request.
const char* ReqHost() const { return host; } const char* ReqHost() const { return host; }
const zeek::IPAddr& ReqAddr() const { return addr; } const IPAddr& ReqAddr() const { return addr; }
bool ReqIsTxt() const { return qtype == 16; } bool ReqIsTxt() const { return qtype == 16; }
int MakeRequest(nb_dns_info* nb_dns); int MakeRequest(nb_dns_info* nb_dns);
@ -82,7 +82,7 @@ protected:
char* host; // if non-nil, this is a host request char* host; // if non-nil, this is a host request
int fam; // address family query type for host requests int fam; // address family query type for host requests
int qtype; // Query type int qtype; // Query type
zeek::IPAddr addr; IPAddr addr;
int request_pending; int request_pending;
}; };
@ -108,7 +108,7 @@ int DNS_Mgr_Request::MakeRequest(nb_dns_info* nb_dns)
class DNS_Mapping { class DNS_Mapping {
public: public:
DNS_Mapping(const char* host, struct hostent* h, uint32_t ttl); DNS_Mapping(const char* host, struct hostent* h, uint32_t ttl);
DNS_Mapping(const zeek::IPAddr& addr, struct hostent* h, uint32_t ttl); DNS_Mapping(const IPAddr& addr, struct hostent* h, uint32_t ttl);
DNS_Mapping(FILE* f); DNS_Mapping(FILE* f);
bool NoMapping() const { return no_mapping; } bool NoMapping() const { return no_mapping; }
@ -118,15 +118,15 @@ public:
// Returns nil if this was an address request. // Returns nil if this was an address request.
const char* ReqHost() const { return req_host; } const char* ReqHost() const { return req_host; }
zeek::IPAddr ReqAddr() const { return req_addr; } IPAddr ReqAddr() const { return req_addr; }
string ReqStr() const string ReqStr() const
{ {
return req_host ? req_host : req_addr.AsString(); return req_host ? req_host : req_addr.AsString();
} }
zeek::ListValPtr Addrs(); ListValPtr Addrs();
zeek::TableValPtr AddrsSet(); // addresses returned as a set TableValPtr AddrsSet(); // addresses returned as a set
zeek::StringValPtr Host(); StringValPtr Host();
double CreationTime() const { return creation_time; } double CreationTime() const { return creation_time; }
@ -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 zeek::util::current_time() > (creation_time + req_ttl); return util::current_time() > (creation_time + req_ttl);
} }
int Type() const { return map_type; } int Type() const { return map_type; }
@ -152,16 +152,16 @@ protected:
void Clear(); void Clear();
char* req_host; char* req_host;
zeek::IPAddr req_addr; IPAddr req_addr;
uint32_t req_ttl; uint32_t req_ttl;
int num_names; int num_names;
char** names; char** names;
zeek::StringValPtr host_val; StringValPtr host_val;
int num_addrs; int num_addrs;
zeek::IPAddr* addrs; IPAddr* addrs;
zeek::ListValPtr addrs_val; ListValPtr addrs_val;
double creation_time; double creation_time;
int map_type; int map_type;
@ -175,26 +175,26 @@ void DNS_Mgr_mapping_delete_func(void* v)
delete (DNS_Mapping*) v; delete (DNS_Mapping*) v;
} }
static zeek::TableValPtr empty_addr_set() static TableValPtr empty_addr_set()
{ {
auto addr_t = zeek::base_type(zeek::TYPE_ADDR); auto addr_t = base_type(TYPE_ADDR);
auto set_index = zeek::make_intrusive<zeek::TypeList>(addr_t); auto set_index = make_intrusive<TypeList>(addr_t);
set_index->Append(std::move(addr_t)); set_index->Append(std::move(addr_t));
auto s = zeek::make_intrusive<zeek::SetType>(std::move(set_index), nullptr); auto s = make_intrusive<SetType>(std::move(set_index), nullptr);
return zeek::make_intrusive<zeek::TableVal>(std::move(s)); return make_intrusive<TableVal>(std::move(s));
} }
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 = zeek::util::copy_string(host); req_host = util::copy_string(host);
req_ttl = ttl; req_ttl = ttl;
if ( names && ! names[0] ) if ( names && ! names[0] )
names[0] = zeek::util::copy_string(host); names[0] = util::copy_string(host);
} }
DNS_Mapping::DNS_Mapping(const zeek::IPAddr& addr, struct hostent* h, uint32_t ttl) DNS_Mapping::DNS_Mapping(const IPAddr& addr, struct hostent* h, uint32_t ttl)
{ {
Init(h); Init(h);
req_addr = addr; req_addr = addr;
@ -231,17 +231,17 @@ 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 = zeek::util::copy_string(req_buf); req_host = util::copy_string(req_buf);
else else
req_addr = zeek::IPAddr(req_buf); req_addr = IPAddr(req_buf);
num_names = 1; num_names = 1;
names = new char*[num_names]; names = new char*[num_names];
names[0] = zeek::util::copy_string(name_buf); names[0] = util::copy_string(name_buf);
if ( num_addrs > 0 ) if ( num_addrs > 0 )
{ {
addrs = new zeek::IPAddr[num_addrs]; addrs = new IPAddr[num_addrs];
for ( int i = 0; i < num_addrs; ++i ) for ( int i = 0; i < num_addrs; ++i )
{ {
@ -255,7 +255,7 @@ DNS_Mapping::DNS_Mapping(FILE* f)
if ( newline ) if ( newline )
*newline = '\0'; *newline = '\0';
addrs[i] = zeek::IPAddr(buf); addrs[i] = IPAddr(buf);
} }
} }
else else
@ -278,23 +278,23 @@ DNS_Mapping::~DNS_Mapping()
delete [] addrs; delete [] addrs;
} }
zeek::ListValPtr DNS_Mapping::Addrs() ListValPtr DNS_Mapping::Addrs()
{ {
if ( failed ) if ( failed )
return nullptr; return nullptr;
if ( ! addrs_val ) if ( ! addrs_val )
{ {
addrs_val = zeek::make_intrusive<zeek::ListVal>(zeek::TYPE_ADDR); addrs_val = make_intrusive<ListVal>(TYPE_ADDR);
for ( int i = 0; i < num_addrs; ++i ) for ( int i = 0; i < num_addrs; ++i )
addrs_val->Append(zeek::make_intrusive<zeek::AddrVal>(addrs[i])); addrs_val->Append(make_intrusive<AddrVal>(addrs[i]));
} }
return addrs_val; return addrs_val;
} }
zeek::TableValPtr DNS_Mapping::AddrsSet() { TableValPtr DNS_Mapping::AddrsSet() {
auto l = Addrs(); auto l = Addrs();
if ( ! l ) if ( ! l )
@ -303,13 +303,13 @@ zeek::TableValPtr DNS_Mapping::AddrsSet() {
return l->ToSetVal(); return l->ToSetVal();
} }
zeek::StringValPtr DNS_Mapping::Host() StringValPtr DNS_Mapping::Host()
{ {
if ( failed || num_names == 0 || ! names[0] ) if ( failed || num_names == 0 || ! names[0] )
return nullptr; return nullptr;
if ( ! host_val ) if ( ! host_val )
host_val = zeek::make_intrusive<zeek::StringVal>(names[0]); host_val = make_intrusive<StringVal>(names[0]);
return host_val; return host_val;
} }
@ -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 = zeek::util::current_time(); creation_time = util::current_time();
host_val = nullptr; host_val = nullptr;
addrs_val = nullptr; addrs_val = nullptr;
@ -331,21 +331,21 @@ 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 ? zeek::util::copy_string(h->h_name) : nullptr; names[0] = h->h_name ? 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 )
; ;
if ( num_addrs > 0 ) if ( num_addrs > 0 )
{ {
addrs = new zeek::IPAddr[num_addrs]; addrs = new IPAddr[num_addrs];
for ( int i = 0; i < num_addrs; ++i ) for ( int i = 0; i < num_addrs; ++i )
if ( h->h_addrtype == AF_INET ) if ( h->h_addrtype == AF_INET )
addrs[i] = zeek::IPAddr(IPv4, (uint32_t*)h->h_addr_list[i], addrs[i] = IPAddr(IPv4, (uint32_t*)h->h_addr_list[i],
zeek::IPAddr::Network); IPAddr::Network);
else if ( h->h_addrtype == AF_INET6 ) else if ( h->h_addrtype == AF_INET6 )
addrs[i] = zeek::IPAddr(IPv6, (uint32_t*)h->h_addr_list[i], addrs[i] = IPAddr(IPv6, (uint32_t*)h->h_addr_list[i],
zeek::IPAddr::Network); IPAddr::Network);
} }
else else
addrs = nullptr; addrs = nullptr;
@ -411,11 +411,11 @@ 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 = zeek::util::zeekenv("ZEEK_DNS_RESOLVER"); auto dns_resolver = util::zeekenv("ZEEK_DNS_RESOLVER");
auto dns_resolver_addr = dns_resolver ? zeek::IPAddr(dns_resolver) : zeek::IPAddr(); auto dns_resolver_addr = dns_resolver ? IPAddr(dns_resolver) : IPAddr();
char err[NB_DNS_ERRSIZE]; char err[NB_DNS_ERRSIZE];
if ( dns_resolver_addr == zeek::IPAddr() ) if ( dns_resolver_addr == IPAddr() )
nb_dns = nb_dns_init(err); nb_dns = nb_dns_init(err);
else else
{ {
@ -439,12 +439,12 @@ void DNS_Mgr::InitSource()
if ( nb_dns ) if ( nb_dns )
{ {
if ( ! zeek::iosource_mgr->RegisterFd(nb_dns_fd(nb_dns), this) ) if ( ! iosource_mgr->RegisterFd(nb_dns_fd(nb_dns), this) )
zeek::reporter->FatalError("Failed to register nb_dns file descriptor with iosource_mgr"); reporter->FatalError("Failed to register nb_dns file descriptor with iosource_mgr");
} }
else else
{ {
zeek::reporter->Warning("problem initializing NB-DNS: %s", err); reporter->Warning("problem initializing NB-DNS: %s", err);
} }
did_init = true; did_init = true;
@ -452,10 +452,10 @@ void DNS_Mgr::InitSource()
void DNS_Mgr::InitPostScript() void DNS_Mgr::InitPostScript()
{ {
dm_rec = zeek::id::find_type<zeek::RecordType>("dns_mapping"); dm_rec = id::find_type<RecordType>("dns_mapping");
// Registering will call Init() // Registering will call Init()
zeek::iosource_mgr->Register(this, true); iosource_mgr->Register(this, true);
const char* cache_dir = dir ? dir : "."; const char* cache_dir = dir ? dir : ".";
cache_name = new char[strlen(cache_dir) + 64]; cache_name = new char[strlen(cache_dir) + 64];
@ -463,12 +463,12 @@ void DNS_Mgr::InitPostScript()
LoadCache(fopen(cache_name, "r")); LoadCache(fopen(cache_name, "r"));
} }
static zeek::TableValPtr fake_name_lookup_result(const char* name) static TableValPtr fake_name_lookup_result(const char* name)
{ {
hash128_t hash; hash128_t hash;
KeyedHash::StaticHash128(name, strlen(name), &hash); KeyedHash::StaticHash128(name, strlen(name), &hash);
auto hv = zeek::make_intrusive<zeek::ListVal>(zeek::TYPE_ADDR); auto hv = make_intrusive<ListVal>(TYPE_ADDR);
hv->Append(zeek::make_intrusive<zeek::AddrVal>(reinterpret_cast<const uint32_t*>(&hash))); hv->Append(make_intrusive<AddrVal>(reinterpret_cast<const uint32_t*>(&hash)));
return hv->ToSetVal(); return hv->ToSetVal();
} }
@ -479,7 +479,7 @@ static const char* fake_text_lookup_result(const char* name)
return tmp; return tmp;
} }
static const char* fake_addr_lookup_result(const zeek::IPAddr& addr) static const char* fake_addr_lookup_result(const IPAddr& addr)
{ {
static char tmp[128]; static char tmp[128];
snprintf(tmp, sizeof(tmp), "fake_addr_lookup_result_%s", snprintf(tmp, sizeof(tmp), "fake_addr_lookup_result_%s",
@ -487,7 +487,7 @@ static const char* fake_addr_lookup_result(const zeek::IPAddr& addr)
return tmp; return tmp;
} }
zeek::TableValPtr DNS_Mgr::LookupHost(const char* name) TableValPtr DNS_Mgr::LookupHost(const char* name)
{ {
if ( mode == DNS_FAKE ) if ( mode == DNS_FAKE )
return fake_name_lookup_result(name); return fake_name_lookup_result(name);
@ -508,7 +508,7 @@ zeek::TableValPtr DNS_Mgr::LookupHost(const char* name)
if ( (d4 && d4->Failed()) || (d6 && d6->Failed()) ) if ( (d4 && d4->Failed()) || (d6 && d6->Failed()) )
{ {
zeek::reporter->Warning("no such host: %s", name); reporter->Warning("no such host: %s", name);
return empty_addr_set(); return empty_addr_set();
} }
else if ( d4 && d6 ) else if ( d4 && d6 )
@ -529,7 +529,7 @@ zeek::TableValPtr DNS_Mgr::LookupHost(const char* name)
return empty_addr_set(); return empty_addr_set();
case DNS_FORCE: case DNS_FORCE:
zeek::reporter->FatalError("can't find DNS entry for %s in cache", name); reporter->FatalError("can't find DNS entry for %s in cache", name);
return nullptr; return nullptr;
case DNS_DEFAULT: case DNS_DEFAULT:
@ -539,12 +539,12 @@ zeek::TableValPtr DNS_Mgr::LookupHost(const char* name)
return LookupHost(name); return LookupHost(name);
default: default:
zeek::reporter->InternalError("bad mode in DNS_Mgr::LookupHost"); reporter->InternalError("bad mode in DNS_Mgr::LookupHost");
return nullptr; return nullptr;
} }
} }
zeek::ValPtr DNS_Mgr::LookupAddr(const zeek::IPAddr& addr) ValPtr DNS_Mgr::LookupAddr(const IPAddr& addr)
{ {
InitSource(); InitSource();
@ -560,8 +560,8 @@ zeek::ValPtr DNS_Mgr::LookupAddr(const zeek::IPAddr& addr)
else else
{ {
string s(addr); string s(addr);
zeek::reporter->Warning("can't resolve IP address: %s", s.c_str()); reporter->Warning("can't resolve IP address: %s", s.c_str());
return zeek::make_intrusive<zeek::StringVal>(s.c_str()); return make_intrusive<StringVal>(s.c_str());
} }
} }
} }
@ -570,10 +570,10 @@ zeek::ValPtr DNS_Mgr::LookupAddr(const zeek::IPAddr& addr)
switch ( mode ) { switch ( mode ) {
case DNS_PRIME: case DNS_PRIME:
requests.push_back(new DNS_Mgr_Request(addr)); requests.push_back(new DNS_Mgr_Request(addr));
return zeek::make_intrusive<zeek::StringVal>("<none>"); return make_intrusive<StringVal>("<none>");
case DNS_FORCE: case DNS_FORCE:
zeek::reporter->FatalError("can't find DNS entry for %s in cache", reporter->FatalError("can't find DNS entry for %s in cache",
addr.AsString().c_str()); addr.AsString().c_str());
return nullptr; return nullptr;
@ -583,7 +583,7 @@ zeek::ValPtr DNS_Mgr::LookupAddr(const zeek::IPAddr& addr)
return LookupAddr(addr); return LookupAddr(addr);
default: default:
zeek::reporter->InternalError("bad mode in DNS_Mgr::LookupAddr"); reporter->InternalError("bad mode in DNS_Mgr::LookupAddr");
return nullptr; return nullptr;
} }
} }
@ -644,7 +644,7 @@ void DNS_Mgr::Resolve()
struct nb_dns_result r; struct nb_dns_result r;
status = nb_dns_activity(nb_dns, &r, err); status = nb_dns_activity(nb_dns, &r, err);
if ( status < 0 ) if ( status < 0 )
zeek::reporter->Warning( reporter->Warning(
"NB-DNS error in DNS_Mgr::WaitForReplies (%s)", "NB-DNS error in DNS_Mgr::WaitForReplies (%s)",
err); err);
else if ( status > 0 ) else if ( status > 0 )
@ -696,16 +696,16 @@ void DNS_Mgr::Event(EventHandlerPtr e, DNS_Mapping* dm)
if ( ! e ) if ( ! e )
return; return;
zeek::event_mgr.Enqueue(e, BuildMappingVal(dm)); event_mgr.Enqueue(e, BuildMappingVal(dm));
} }
void DNS_Mgr::Event(EventHandlerPtr e, DNS_Mapping* dm, void DNS_Mgr::Event(EventHandlerPtr e, DNS_Mapping* dm,
zeek::ListValPtr l1, zeek::ListValPtr l2) ListValPtr l1, ListValPtr l2)
{ {
if ( ! e ) if ( ! e )
return; return;
zeek::event_mgr.Enqueue(e, BuildMappingVal(dm), l1->ToSetVal(), l2->ToSetVal()); event_mgr.Enqueue(e, BuildMappingVal(dm), l1->ToSetVal(), l2->ToSetVal());
} }
void DNS_Mgr::Event(EventHandlerPtr e, DNS_Mapping* old_dm, DNS_Mapping* new_dm) void DNS_Mgr::Event(EventHandlerPtr e, DNS_Mapping* old_dm, DNS_Mapping* new_dm)
@ -713,20 +713,20 @@ void DNS_Mgr::Event(EventHandlerPtr e, DNS_Mapping* old_dm, DNS_Mapping* new_dm)
if ( ! e ) if ( ! e )
return; return;
zeek::event_mgr.Enqueue(e, BuildMappingVal(old_dm), BuildMappingVal(new_dm)); event_mgr.Enqueue(e, BuildMappingVal(old_dm), BuildMappingVal(new_dm));
} }
zeek::ValPtr DNS_Mgr::BuildMappingVal(DNS_Mapping* dm) ValPtr DNS_Mgr::BuildMappingVal(DNS_Mapping* dm)
{ {
auto r = zeek::make_intrusive<zeek::RecordVal>(dm_rec); auto r = make_intrusive<RecordVal>(dm_rec);
r->Assign(0, zeek::make_intrusive<zeek::TimeVal>(dm->CreationTime())); r->Assign(0, make_intrusive<TimeVal>(dm->CreationTime()));
r->Assign(1, zeek::make_intrusive<zeek::StringVal>(dm->ReqHost() ? dm->ReqHost() : "")); r->Assign(1, make_intrusive<StringVal>(dm->ReqHost() ? dm->ReqHost() : ""));
r->Assign(2, zeek::make_intrusive<zeek::AddrVal>(dm->ReqAddr())); r->Assign(2, make_intrusive<AddrVal>(dm->ReqAddr()));
r->Assign(3, zeek::val_mgr->Bool(dm->Valid())); r->Assign(3, val_mgr->Bool(dm->Valid()));
auto h = dm->Host(); auto h = dm->Host();
r->Assign(4, h ? std::move(h) : zeek::make_intrusive<zeek::StringVal>("<none>")); r->Assign(4, h ? std::move(h) : make_intrusive<StringVal>("<none>"));
r->Assign(5, dm->AddrsSet()); r->Assign(5, dm->AddrsSet());
return r; return r;
@ -861,7 +861,7 @@ void DNS_Mgr::CompareMappings(DNS_Mapping* prev_dm, DNS_Mapping* new_dm)
if ( ! prev_a || ! new_a ) if ( ! prev_a || ! new_a )
{ {
zeek::reporter->InternalWarning("confused in DNS_Mgr::CompareMappings"); reporter->InternalWarning("confused in DNS_Mgr::CompareMappings");
return; return;
} }
@ -872,18 +872,18 @@ void DNS_Mgr::CompareMappings(DNS_Mapping* prev_dm, DNS_Mapping* new_dm)
Event(dns_mapping_altered, new_dm, std::move(prev_delta), std::move(new_delta)); Event(dns_mapping_altered, new_dm, std::move(prev_delta), std::move(new_delta));
} }
zeek::ListValPtr DNS_Mgr::AddrListDelta(zeek::ListVal* al1, zeek::ListVal* al2) ListValPtr DNS_Mgr::AddrListDelta(ListVal* al1, ListVal* al2)
{ {
auto delta = zeek::make_intrusive<zeek::ListVal>(zeek::TYPE_ADDR); auto delta = make_intrusive<ListVal>(TYPE_ADDR);
for ( int i = 0; i < al1->Length(); ++i ) for ( int i = 0; i < al1->Length(); ++i )
{ {
const zeek::IPAddr& al1_i = al1->Idx(i)->AsAddr(); const IPAddr& al1_i = al1->Idx(i)->AsAddr();
int j; int j;
for ( j = 0; j < al2->Length(); ++j ) for ( j = 0; j < al2->Length(); ++j )
{ {
const zeek::IPAddr& al2_j = al2->Idx(j)->AsAddr(); const IPAddr& al2_j = al2->Idx(j)->AsAddr();
if ( al1_i == al2_j ) if ( al1_i == al2_j )
break; break;
} }
@ -896,11 +896,11 @@ zeek::ListValPtr DNS_Mgr::AddrListDelta(zeek::ListVal* al1, zeek::ListVal* al2)
return delta; return delta;
} }
void DNS_Mgr::DumpAddrList(FILE* f, zeek::ListVal* al) void DNS_Mgr::DumpAddrList(FILE* f, ListVal* al)
{ {
for ( int i = 0; i < al->Length(); ++i ) for ( int i = 0; i < al->Length(); ++i )
{ {
const zeek::IPAddr& al_i = al->Idx(i)->AsAddr(); const IPAddr& al_i = al->Idx(i)->AsAddr();
fprintf(f, "%s%s", i > 0 ? "," : "", al_i.AsString().c_str()); fprintf(f, "%s%s", i > 0 ? "," : "", al_i.AsString().c_str());
} }
} }
@ -932,7 +932,7 @@ void DNS_Mgr::LoadCache(FILE* f)
} }
if ( ! m->NoMapping() ) if ( ! m->NoMapping() )
zeek::reporter->FatalError("DNS cache corrupted"); reporter->FatalError("DNS cache corrupted");
delete m; delete m;
fclose(f); fclose(f);
@ -961,7 +961,7 @@ void DNS_Mgr::Save(FILE* f, const HostMap& m)
} }
} }
const char* DNS_Mgr::LookupAddrInCache(const zeek::IPAddr& addr) const char* DNS_Mgr::LookupAddrInCache(const IPAddr& addr)
{ {
AddrMap::iterator it = addr_mappings.find(addr); AddrMap::iterator it = addr_mappings.find(addr);
@ -982,7 +982,7 @@ const char* DNS_Mgr::LookupAddrInCache(const zeek::IPAddr& addr)
return d->names ? d->names[0] : "<\?\?\?>"; return d->names ? d->names[0] : "<\?\?\?>";
} }
zeek::TableValPtr DNS_Mgr::LookupNameInCache(const string& name) TableValPtr DNS_Mgr::LookupNameInCache(const string& name)
{ {
HostMap::iterator it = host_mappings.find(name); HostMap::iterator it = host_mappings.find(name);
if ( it == host_mappings.end() ) if ( it == host_mappings.end() )
@ -1032,7 +1032,7 @@ const char* DNS_Mgr::LookupTextInCache(const string& name)
} }
static void resolve_lookup_cb(DNS_Mgr::LookupCallback* callback, static void resolve_lookup_cb(DNS_Mgr::LookupCallback* callback,
zeek::TableValPtr result) TableValPtr result)
{ {
callback->Resolved(result.get()); callback->Resolved(result.get());
delete callback; delete callback;
@ -1045,7 +1045,7 @@ static void resolve_lookup_cb(DNS_Mgr::LookupCallback* callback,
delete callback; delete callback;
} }
void DNS_Mgr::AsyncLookupAddr(const zeek::IPAddr& host, LookupCallback* callback) void DNS_Mgr::AsyncLookupAddr(const IPAddr& host, LookupCallback* callback)
{ {
InitSource(); InitSource();
@ -1167,7 +1167,7 @@ static bool DoRequest(nb_dns_info* nb_dns, DNS_Mgr_Request* dr)
// dr stored in nb_dns cookie and deleted later when results available. // dr stored in nb_dns cookie and deleted later when results available.
return true; return true;
zeek::reporter->Warning("can't issue DNS request"); reporter->Warning("can't issue DNS request");
delete dr; delete dr;
return false; return false;
} }
@ -1204,14 +1204,14 @@ void DNS_Mgr::IssueAsyncRequests()
continue; continue;
} }
req->time = zeek::util::current_time(); req->time = util::current_time();
asyncs_timeouts.push(req); asyncs_timeouts.push(req);
++asyncs_pending; ++asyncs_pending;
} }
} }
void DNS_Mgr::CheckAsyncAddrRequest(const zeek::IPAddr& addr, bool timeout) void DNS_Mgr::CheckAsyncAddrRequest(const IPAddr& addr, bool timeout)
{ {
// Note that this code is a mirror of that for CheckAsyncHostRequest. // Note that this code is a mirror of that for CheckAsyncHostRequest.
@ -1338,7 +1338,7 @@ double DNS_Mgr::GetNextTimeout()
if ( asyncs_timeouts.empty() ) if ( asyncs_timeouts.empty() )
return -1; return -1;
return zeek::run_state::network_time + DNS_TIMEOUT; return run_state::network_time + DNS_TIMEOUT;
} }
void DNS_Mgr::Process() void DNS_Mgr::Process()
@ -1350,7 +1350,7 @@ void DNS_Mgr::Process()
{ {
AsyncRequest* req = asyncs_timeouts.top(); AsyncRequest* req = asyncs_timeouts.top();
if ( req->time + DNS_TIMEOUT > zeek::util::current_time() && ! zeek::run_state::terminating ) if ( req->time + DNS_TIMEOUT > util::current_time() && ! run_state::terminating )
break; break;
if ( ! req->processed ) if ( ! req->processed )
@ -1376,7 +1376,7 @@ void DNS_Mgr::Process()
int status = nb_dns_activity(nb_dns, &r, err); int status = nb_dns_activity(nb_dns, &r, err);
if ( status < 0 ) if ( status < 0 )
zeek::reporter->Warning("NB-DNS error in DNS_Mgr::Process (%s)", err); reporter->Warning("NB-DNS error in DNS_Mgr::Process (%s)", err);
else if ( status > 0 ) else if ( status > 0 )
{ {
@ -1416,7 +1416,7 @@ int DNS_Mgr::AnswerAvailable(int timeout)
int fd = nb_dns_fd(nb_dns); int fd = nb_dns_fd(nb_dns);
if ( fd < 0 ) if ( fd < 0 )
{ {
zeek::reporter->Warning("nb_dns_fd() failed in DNS_Mgr::WaitForReplies"); reporter->Warning("nb_dns_fd() failed in DNS_Mgr::WaitForReplies");
return -1; return -1;
} }
@ -1434,14 +1434,14 @@ int DNS_Mgr::AnswerAvailable(int timeout)
if ( status < 0 ) if ( status < 0 )
{ {
if ( errno != EINTR ) if ( errno != EINTR )
zeek::reporter->Warning("problem with DNS select"); reporter->Warning("problem with DNS select");
return -1; return -1;
} }
if ( status > 1 ) if ( status > 1 )
{ {
zeek::reporter->Warning("strange return from DNS select"); reporter->Warning("strange return from DNS select");
return -1; return -1;
} }
@ -1462,7 +1462,7 @@ void DNS_Mgr::GetStats(Stats* stats)
void DNS_Mgr::Terminate() void DNS_Mgr::Terminate()
{ {
if ( nb_dns ) if ( nb_dns )
zeek::iosource_mgr->UnregisterFd(nb_dns_fd(nb_dns), this); iosource_mgr->UnregisterFd(nb_dns_fd(nb_dns), this);
} }
} // namespace zeek::detail } // namespace zeek::detail

View file

@ -22,9 +22,9 @@ ZEEK_FORWARD_DECLARE_NAMESPACED(TableVal, zeek);
namespace zeek { namespace zeek {
template <class T> class IntrusivePtr; template <class T> class IntrusivePtr;
using ValPtr = zeek::IntrusivePtr<Val>; using ValPtr = IntrusivePtr<Val>;
using ListValPtr = zeek::IntrusivePtr<ListVal>; using ListValPtr = IntrusivePtr<ListVal>;
using TableValPtr = zeek::IntrusivePtr<TableVal>; using TableValPtr = IntrusivePtr<TableVal>;
} }
// Defined in nb_dns.h // Defined in nb_dns.h
@ -33,7 +33,7 @@ struct nb_dns_result;
namespace zeek::detail { namespace zeek::detail {
using DNS_mgr_request_list = zeek::PList<DNS_Mgr_Request>; using DNS_mgr_request_list = PList<DNS_Mgr_Request>;
class DNS_Mapping; class DNS_Mapping;
@ -47,7 +47,7 @@ enum DNS_MgrMode {
// Number of seconds we'll wait for a reply. // Number of seconds we'll wait for a reply.
#define DNS_TIMEOUT 5 #define DNS_TIMEOUT 5
class DNS_Mgr final : public zeek::iosource::IOSource { class DNS_Mgr final : public iosource::IOSource {
public: public:
explicit DNS_Mgr(DNS_MgrMode mode); explicit DNS_Mgr(DNS_MgrMode mode);
~DNS_Mgr() override; ~DNS_Mgr() override;
@ -57,19 +57,19 @@ public:
// Looks up the address or addresses of the given host, and returns // Looks up the address or addresses of the given host, and returns
// a set of addr. // a set of addr.
zeek::TableValPtr LookupHost(const char* host); TableValPtr LookupHost(const char* host);
zeek::ValPtr LookupAddr(const zeek::IPAddr& addr); ValPtr LookupAddr(const 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 = zeek::util::copy_string(arg_dir); } void SetDir(const char* arg_dir) { dir = util::copy_string(arg_dir); }
void Verify(); void Verify();
void Resolve(); void Resolve();
bool Save(); bool Save();
const char* LookupAddrInCache(const zeek::IPAddr& addr); const char* LookupAddrInCache(const IPAddr& addr);
zeek::TableValPtr LookupNameInCache(const std::string& name); TableValPtr LookupNameInCache(const std::string& name);
const char* LookupTextInCache(const std::string& name); const char* LookupTextInCache(const std::string& name);
// Support for async lookups. // Support for async lookups.
@ -79,11 +79,11 @@ public:
virtual ~LookupCallback() { } virtual ~LookupCallback() { }
virtual void Resolved(const char* name) { }; virtual void Resolved(const char* name) { };
virtual void Resolved(zeek::TableVal* addrs) { }; virtual void Resolved(TableVal* addrs) { };
virtual void Timeout() = 0; virtual void Timeout() = 0;
}; };
void AsyncLookupAddr(const zeek::IPAddr& host, LookupCallback* callback); void AsyncLookupAddr(const IPAddr& host, LookupCallback* callback);
void AsyncLookupName(const std::string& name, LookupCallback* callback); void AsyncLookupName(const std::string& name, LookupCallback* callback);
void AsyncLookupNameText(const std::string& name, LookupCallback* callback); void AsyncLookupNameText(const std::string& name, LookupCallback* callback);
@ -105,20 +105,20 @@ protected:
friend class LookupCallback; friend class LookupCallback;
friend class DNS_Mgr_Request; friend class DNS_Mgr_Request;
void Event(zeek::EventHandlerPtr e, DNS_Mapping* dm); void Event(EventHandlerPtr e, DNS_Mapping* dm);
void Event(zeek::EventHandlerPtr e, DNS_Mapping* dm, void Event(EventHandlerPtr e, DNS_Mapping* dm,
zeek::ListValPtr l1, zeek::ListValPtr l2); ListValPtr l1, ListValPtr l2);
void Event(zeek::EventHandlerPtr e, DNS_Mapping* old_dm, DNS_Mapping* new_dm); void Event(EventHandlerPtr e, DNS_Mapping* old_dm, DNS_Mapping* new_dm);
zeek::ValPtr BuildMappingVal(DNS_Mapping* dm); ValPtr BuildMappingVal(DNS_Mapping* dm);
void AddResult(DNS_Mgr_Request* dr, struct nb_dns_result* r); void AddResult(DNS_Mgr_Request* dr, struct nb_dns_result* r);
void CompareMappings(DNS_Mapping* prev_dm, DNS_Mapping* new_dm); void CompareMappings(DNS_Mapping* prev_dm, DNS_Mapping* new_dm);
zeek::ListValPtr AddrListDelta(zeek::ListVal* al1, zeek::ListVal* al2); ListValPtr AddrListDelta(ListVal* al1, ListVal* al2);
void DumpAddrList(FILE* f, zeek::ListVal* al); void DumpAddrList(FILE* f, ListVal* al);
typedef std::map<std::string, std::pair<DNS_Mapping*, DNS_Mapping*> > HostMap; typedef std::map<std::string, std::pair<DNS_Mapping*, DNS_Mapping*> > HostMap;
typedef std::map<zeek::IPAddr, DNS_Mapping*> AddrMap; typedef std::map<IPAddr, DNS_Mapping*> AddrMap;
typedef std::map<std::string, DNS_Mapping*> TextMap; typedef std::map<std::string, DNS_Mapping*> TextMap;
void LoadCache(FILE* f); void LoadCache(FILE* f);
void Save(FILE* f, const AddrMap& m); void Save(FILE* f, const AddrMap& m);
@ -134,7 +134,7 @@ protected:
// Finish the request if we have a result. If not, time it out if // Finish the request if we have a result. If not, time it out if
// requested. // requested.
void CheckAsyncAddrRequest(const zeek::IPAddr& addr, bool timeout); void CheckAsyncAddrRequest(const IPAddr& addr, bool timeout);
void CheckAsyncHostRequest(const char* host, bool timeout); void CheckAsyncHostRequest(const char* host, bool timeout);
void CheckAsyncTextRequest(const char* host, bool timeout); void CheckAsyncTextRequest(const char* host, bool timeout);
@ -158,13 +158,13 @@ protected:
bool did_init; bool did_init;
zeek::RecordTypePtr dm_rec; RecordTypePtr dm_rec;
typedef std::list<LookupCallback*> CallbackList; typedef std::list<LookupCallback*> CallbackList;
struct AsyncRequest { struct AsyncRequest {
double time; double time;
zeek::IPAddr host; IPAddr host;
std::string name; std::string name;
CallbackList callbacks; CallbackList callbacks;
bool is_txt; bool is_txt;
@ -186,7 +186,7 @@ protected:
processed = true; processed = true;
} }
void Resolved(zeek::TableVal* addrs) void Resolved(TableVal* addrs)
{ {
for ( CallbackList::iterator i = callbacks.begin(); for ( CallbackList::iterator i = callbacks.begin();
i != callbacks.end(); ++i ) i != callbacks.end(); ++i )
@ -212,7 +212,7 @@ protected:
}; };
typedef std::map<zeek::IPAddr, AsyncRequest*> AsyncRequestAddrMap; typedef std::map<IPAddr, AsyncRequest*> AsyncRequestAddrMap;
AsyncRequestAddrMap asyncs_addrs; AsyncRequestAddrMap asyncs_addrs;
typedef std::map<std::string, AsyncRequest*> AsyncRequestNameMap; typedef std::map<std::string, AsyncRequest*> AsyncRequestNameMap;

View file

@ -152,10 +152,10 @@ bool DbgBreakpoint::SetLocation(ParseLocationRec plr, std::string_view loc_str)
{ {
std::string loc_s(loc_str); std::string loc_s(loc_str);
kind = BP_FUNC; kind = BP_FUNC;
function_name = make_full_var_name(zeek::detail::current_module.c_str(), function_name = make_full_var_name(current_module.c_str(),
loc_s.c_str()); loc_s.c_str());
at_stmt = plr.stmt; at_stmt = plr.stmt;
const zeek::detail::Location* loc = at_stmt->GetLocationInfo(); const Location* loc = at_stmt->GetLocationInfo();
snprintf(description, sizeof(description), "%s at %s:%d", snprintf(description, sizeof(description), "%s at %s:%d",
function_name.c_str(), loc->filename, loc->last_line); function_name.c_str(), loc->filename, loc->last_line);
@ -167,7 +167,7 @@ bool DbgBreakpoint::SetLocation(ParseLocationRec plr, std::string_view loc_str)
return true; return true;
} }
bool DbgBreakpoint::SetLocation(zeek::detail::Stmt* stmt) bool DbgBreakpoint::SetLocation(Stmt* stmt)
{ {
if ( ! stmt ) if ( ! stmt )
return false; return false;
@ -178,7 +178,7 @@ bool DbgBreakpoint::SetLocation(zeek::detail::Stmt* stmt)
SetEnable(true); SetEnable(true);
AddToGlobalMap(); AddToGlobalMap();
const zeek::detail::Location* loc = stmt->GetLocationInfo(); const Location* loc = stmt->GetLocationInfo();
snprintf(description, sizeof(description), "%s:%d", snprintf(description, sizeof(description), "%s:%d",
loc->filename, loc->last_line); loc->filename, loc->last_line);
@ -219,7 +219,7 @@ bool DbgBreakpoint::Reset()
break; break;
} }
zeek::reporter->InternalError("DbgBreakpoint::Reset function incomplete."); reporter->InternalError("DbgBreakpoint::Reset function incomplete.");
// Cannot be reached. // Cannot be reached.
return false; return false;
@ -259,8 +259,8 @@ BreakCode DbgBreakpoint::HasHit()
return BC_HIT; return BC_HIT;
} }
if ( ! zeek::IsIntegral(yes->GetType()->Tag()) && if ( ! IsIntegral(yes->GetType()->Tag()) &&
! zeek::IsBool(yes->GetType()->Tag()) ) ! IsBool(yes->GetType()->Tag()) )
{ {
PrintHitMsg(); PrintHitMsg();
debug_msg("Breakpoint condition should return an integral type"); debug_msg("Breakpoint condition should return an integral type");
@ -291,7 +291,7 @@ BreakCode DbgBreakpoint::HasHit()
return BC_HIT; return BC_HIT;
} }
BreakCode DbgBreakpoint::ShouldBreak(zeek::detail::Stmt* s) BreakCode DbgBreakpoint::ShouldBreak(Stmt* s)
{ {
if ( ! IsEnabled() ) if ( ! IsEnabled() )
return BC_NO_HIT; return BC_NO_HIT;
@ -312,7 +312,7 @@ BreakCode DbgBreakpoint::ShouldBreak(zeek::detail::Stmt* s)
assert(false); assert(false);
default: default:
zeek::reporter->InternalError("Invalid breakpoint type in DbgBreakpoint::ShouldBreak"); reporter->InternalError("Invalid breakpoint type in DbgBreakpoint::ShouldBreak");
} }
// If we got here, that means that the breakpoint could hit, // If we got here, that means that the breakpoint could hit,
@ -329,7 +329,7 @@ BreakCode DbgBreakpoint::ShouldBreak(zeek::detail::Stmt* s)
BreakCode DbgBreakpoint::ShouldBreak(double t) BreakCode DbgBreakpoint::ShouldBreak(double t)
{ {
if ( kind != BP_TIME ) if ( kind != BP_TIME )
zeek::reporter->InternalError("Calling ShouldBreak(time) on a non-time breakpoint"); reporter->InternalError("Calling ShouldBreak(time) on a non-time breakpoint");
if ( t < at_time ) if ( t < at_time )
return BC_NO_HIT; return BC_NO_HIT;
@ -352,13 +352,13 @@ void DbgBreakpoint::PrintHitMsg()
case BP_LINE: case BP_LINE:
{ {
ODesc d; ODesc d;
zeek::detail::Frame* f = g_frame_stack.back(); Frame* f = g_frame_stack.back();
const zeek::detail::ScriptFunc* func = f->GetFunction(); const ScriptFunc* func = f->GetFunction();
if ( func ) if ( func )
func->DescribeDebug (&d, f->GetFuncArgs()); func->DescribeDebug (&d, f->GetFuncArgs());
const zeek::detail::Location* loc = at_stmt->GetLocationInfo(); const Location* loc = at_stmt->GetLocationInfo();
debug_msg("Breakpoint %d, %s at %s:%d\n", debug_msg("Breakpoint %d, %s at %s:%d\n",
GetID(), d.Description(), GetID(), d.Description(),
@ -370,7 +370,7 @@ void DbgBreakpoint::PrintHitMsg()
assert(false); assert(false);
default: default:
zeek::reporter->InternalError("Missed a case in DbgBreakpoint::PrintHitMsg\n"); reporter->InternalError("Missed a case in DbgBreakpoint::PrintHitMsg\n");
} }
} }

View file

@ -23,7 +23,7 @@ public:
// True if breakpoint could be set; false otherwise // True if breakpoint could be set; false otherwise
bool SetLocation(ParseLocationRec plr, std::string_view loc_str); bool SetLocation(ParseLocationRec plr, std::string_view loc_str);
bool SetLocation(zeek::detail::Stmt* stmt); bool SetLocation(Stmt* stmt);
bool SetLocation(double time); bool SetLocation(double time);
bool Reset(); // cancel and re-apply bpt when restarting execution bool Reset(); // cancel and re-apply bpt when restarting execution
@ -38,7 +38,7 @@ public:
// //
// NOTE: If it returns a hit, the DbgBreakpoint object will take // NOTE: If it returns a hit, the DbgBreakpoint object will take
// appropriate action (e.g., resetting counters). // appropriate action (e.g., resetting counters).
BreakCode ShouldBreak(zeek::detail::Stmt* s); BreakCode ShouldBreak(Stmt* s);
BreakCode ShouldBreak(double t); BreakCode ShouldBreak(double t);
const std::string& GetCondition() const { return condition; } const std::string& GetCondition() const { return condition; }
@ -73,7 +73,7 @@ protected:
bool enabled; // ### comment this and next bool enabled; // ### comment this and next
bool temporary; bool temporary;
zeek::detail::Stmt* at_stmt; Stmt* at_stmt;
double at_time; // break when the virtual time is this double at_time; // break when the virtual time is this
// Support for conditional and N'th time breakpoints. // Support for conditional and N'th time breakpoints.

View file

@ -6,13 +6,17 @@
#include "DbgWatch.h" #include "DbgWatch.h"
#include "Reporter.h" #include "Reporter.h"
namespace zeek::detail {
// Support classes // Support classes
zeek::detail::DbgWatch::DbgWatch(zeek::Obj* var_to_watch) DbgWatch::DbgWatch(zeek::Obj* var_to_watch)
{ {
zeek::reporter->InternalError("DbgWatch unimplemented"); reporter->InternalError("DbgWatch unimplemented");
} }
zeek::detail::DbgWatch::DbgWatch(zeek::detail::Expr* expr_to_watch) DbgWatch::DbgWatch(Expr* expr_to_watch)
{ {
zeek::reporter->InternalError("DbgWatch unimplemented"); reporter->InternalError("DbgWatch unimplemented");
} }
} // namespace zeek::detail

View file

@ -12,13 +12,13 @@ namespace zeek::detail {
class DbgWatch { class DbgWatch {
public: public:
explicit DbgWatch(zeek::Obj* var_to_watch); explicit DbgWatch(Obj* var_to_watch);
explicit DbgWatch(zeek::detail::Expr* expr_to_watch); explicit DbgWatch(Expr* expr_to_watch);
~DbgWatch() = default; ~DbgWatch() = default;
protected: protected:
zeek::Obj* var; Obj* var;
zeek::detail::Expr* expr; Expr* expr;
}; };
} // namespace zeek::detail } // namespace zeek::detail

View file

@ -80,7 +80,7 @@ DebuggerState::DebuggerState()
BreakFromSignal(false); BreakFromSignal(false);
// ### Don't choose this arbitrary size! Extend Frame. // ### Don't choose this arbitrary size! Extend Frame.
dbg_locals = new zeek::detail::Frame(1024, /* func = */ nullptr, /* fn_args = */ nullptr); dbg_locals = new Frame(1024, /* func = */ nullptr, /* fn_args = */ nullptr);
} }
DebuggerState::~DebuggerState() DebuggerState::~DebuggerState()
@ -91,7 +91,7 @@ DebuggerState::~DebuggerState()
bool StmtLocMapping::StartsAfter(const StmtLocMapping* m2) bool StmtLocMapping::StartsAfter(const StmtLocMapping* m2)
{ {
if ( ! m2 ) if ( ! m2 )
zeek::reporter->InternalError("Assertion failed: m2 != 0"); reporter->InternalError("Assertion failed: m2 != 0");
return loc.first_line > m2->loc.first_line || return loc.first_line > m2->loc.first_line ||
(loc.first_line == m2->loc.first_line && (loc.first_line == m2->loc.first_line &&
@ -119,7 +119,7 @@ FILE* TraceState::SetTraceFile(const char* filename)
{ {
FILE* newfile; FILE* newfile;
if ( zeek::util::streq(filename, "-") ) if ( util::streq(filename, "-") )
newfile = stderr; newfile = stderr;
else else
newfile = fopen(filename, "w"); newfile = fopen(filename, "w");
@ -158,10 +158,10 @@ int TraceState::LogTrace(const char* fmt, ...)
va_start(args, fmt); va_start(args, fmt);
// Prefix includes timestamp and file/line info. // Prefix includes timestamp and file/line info.
fprintf(trace_file, "%.6f ", zeek::run_state::network_time); fprintf(trace_file, "%.6f ", run_state::network_time);
const zeek::detail::Stmt* stmt; const Stmt* stmt;
zeek::detail::Location loc; Location loc;
loc.filename = nullptr; loc.filename = nullptr;
if ( g_frame_stack.size() > 0 && g_frame_stack.back() ) if ( g_frame_stack.size() > 0 && g_frame_stack.back() )
@ -171,7 +171,7 @@ int TraceState::LogTrace(const char* fmt, ...)
loc = *stmt->GetLocationInfo(); loc = *stmt->GetLocationInfo();
else else
{ {
const zeek::detail::ScriptFunc* f = g_frame_stack.back()->GetFunction(); const ScriptFunc* f = g_frame_stack.back()->GetFunction();
if ( f ) if ( f )
loc = *f->GetLocationInfo(); loc = *f->GetLocationInfo();
} }
@ -179,7 +179,7 @@ int TraceState::LogTrace(const char* fmt, ...)
if ( ! loc.filename ) if ( ! loc.filename )
{ {
loc.filename = zeek::util::copy_string("<no filename>"); loc.filename = util::copy_string("<no filename>");
loc.last_line = 0; loc.last_line = 0;
} }
@ -199,7 +199,7 @@ int TraceState::LogTrace(const char* fmt, ...)
// Helper functions. // Helper functions.
void get_first_statement(zeek::detail::Stmt* list, zeek::detail::Stmt*& first, zeek::detail::Location& loc) void get_first_statement(Stmt* list, Stmt*& first, Location& loc)
{ {
if ( ! list ) if ( ! list )
{ {
@ -222,11 +222,11 @@ void get_first_statement(zeek::detail::Stmt* list, zeek::detail::Stmt*& first, z
static void parse_function_name(vector<ParseLocationRec>& result, static void parse_function_name(vector<ParseLocationRec>& result,
ParseLocationRec& plr, const string& s) ParseLocationRec& plr, const string& s)
{ // function name { // function name
const auto& id = zeek::detail::lookup_ID(s.c_str(), zeek::detail::current_module.c_str()); const auto& id = lookup_ID(s.c_str(), current_module.c_str());
if ( ! id ) if ( ! id )
{ {
string fullname = make_full_var_name(zeek::detail::current_module.c_str(), s.c_str()); string fullname = make_full_var_name(current_module.c_str(), s.c_str());
debug_msg("Function %s not defined.\n", fullname.c_str()); debug_msg("Function %s not defined.\n", fullname.c_str());
plr.type = PLR_UNKNOWN; plr.type = PLR_UNKNOWN;
return; return;
@ -246,8 +246,8 @@ static void parse_function_name(vector<ParseLocationRec>& result,
return; return;
} }
const zeek::Func* func = id->GetVal()->AsFunc(); const Func* func = id->GetVal()->AsFunc();
const vector<zeek::Func::Body>& bodies = func->GetBodies(); const vector<Func::Body>& bodies = func->GetBodies();
if ( bodies.size() == 0 ) if ( bodies.size() == 0 )
{ {
@ -256,7 +256,7 @@ static void parse_function_name(vector<ParseLocationRec>& result,
return; return;
} }
zeek::detail::Stmt* body = nullptr; // the particular body we care about; 0 = all Stmt* body = nullptr; // the particular body we care about; 0 = all
if ( bodies.size() == 1 ) if ( bodies.size() == 1 )
body = bodies[0].stmts.get(); body = bodies[0].stmts.get();
@ -268,8 +268,8 @@ static void parse_function_name(vector<ParseLocationRec>& result,
"Please choose one of the following options:\n"); "Please choose one of the following options:\n");
for ( unsigned int i = 0; i < bodies.size(); ++i ) for ( unsigned int i = 0; i < bodies.size(); ++i )
{ {
zeek::detail::Stmt* first; Stmt* first;
zeek::detail::Location stmt_loc; Location stmt_loc;
get_first_statement(bodies[i].stmts.get(), first, stmt_loc); get_first_statement(bodies[i].stmts.get(), first, stmt_loc);
debug_msg("[%d] %s:%d\n", i+1, stmt_loc.filename, stmt_loc.first_line); debug_msg("[%d] %s:%d\n", i+1, stmt_loc.filename, stmt_loc.first_line);
} }
@ -311,8 +311,8 @@ static void parse_function_name(vector<ParseLocationRec>& result,
plr.type = PLR_FUNCTION; plr.type = PLR_FUNCTION;
// Find first atomic (non-STMT_LIST) statement // Find first atomic (non-STMT_LIST) statement
zeek::detail::Stmt* first; Stmt* first;
zeek::detail::Location stmt_loc; Location stmt_loc;
if ( body ) if ( body )
{ {
@ -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(zeek::util::find_script_file(filename, zeek::util::zeek_path())); string path(util::find_script_file(filename, util::zeek_path()));
if ( path.empty() ) if ( path.empty() )
{ {
@ -395,7 +395,7 @@ vector<ParseLocationRec> parse_location_string(const string& s)
{ {
auto iter = g_dbgfilemaps.find(loc_filename); auto iter = g_dbgfilemaps.find(loc_filename);
if ( iter == g_dbgfilemaps.end() ) if ( iter == g_dbgfilemaps.end() )
zeek::reporter->InternalError("Policy file %s should have been loaded\n", reporter->InternalError("Policy file %s should have been loaded\n",
loc_filename.data()); loc_filename.data());
if ( plr.line > how_many_lines_in(loc_filename.data()) ) if ( plr.line > how_many_lines_in(loc_filename.data()) )
@ -555,7 +555,7 @@ int dbg_execute_command(const char* cmd)
if ( ! cmd ) if ( ! cmd )
return 0; return 0;
if ( zeek::util::streq(cmd, "") ) // do the GDB command completion if ( 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 = zeek::util::copy_string(cmd); char* localcmd = util::copy_string(cmd);
string opstring; string opstring;
vector<string> arguments; vector<string> arguments;
@ -637,7 +637,7 @@ int dbg_execute_command(const char* cmd)
#endif #endif
if ( int(cmd_code) >= num_debug_cmds() ) if ( int(cmd_code) >= num_debug_cmds() )
zeek::reporter->InternalError("Assertion failed: int(cmd_code) < num_debug_cmds()"); reporter->InternalError("Assertion failed: int(cmd_code) < num_debug_cmds()");
// Dispatch to the op-specific handler (with args). // Dispatch to the op-specific handler (with args).
int retcode = dbg_dispatch_cmd(cmd_code, arguments); int retcode = dbg_dispatch_cmd(cmd_code, arguments);
@ -646,7 +646,7 @@ int dbg_execute_command(const char* cmd)
const DebugCmdInfo* info = get_debug_cmd_info(cmd_code); const DebugCmdInfo* info = get_debug_cmd_info(cmd_code);
if ( ! info ) if ( ! info )
zeek::reporter->InternalError("Assertion failed: info"); reporter->InternalError("Assertion failed: info");
if ( ! info ) if ( ! info )
return -2; // ### yuck, why -2? return -2; // ### yuck, why -2?
@ -659,7 +659,7 @@ static int dbg_dispatch_cmd(DebugCmd cmd_code, const vector<string>& args)
{ {
switch ( cmd_code ) { switch ( cmd_code ) {
case dcHelp: case dcHelp:
zeek::detail::dbg_cmd_help(cmd_code, args); dbg_cmd_help(cmd_code, args);
break; break;
case dcQuit: case dcQuit:
@ -689,11 +689,11 @@ static int dbg_dispatch_cmd(DebugCmd cmd_code, const vector<string>& args)
break; break;
case dcBreak: case dcBreak:
zeek::detail::dbg_cmd_break(cmd_code, args); dbg_cmd_break(cmd_code, args);
break; break;
case dcBreakCondition: case dcBreakCondition:
zeek::detail::dbg_cmd_break_condition(cmd_code, args); dbg_cmd_break_condition(cmd_code, args);
break; break;
case dcDeleteBreak: case dcDeleteBreak:
@ -701,26 +701,26 @@ static int dbg_dispatch_cmd(DebugCmd cmd_code, const vector<string>& args)
case dcDisableBreak: case dcDisableBreak:
case dcEnableBreak: case dcEnableBreak:
case dcIgnoreBreak: case dcIgnoreBreak:
zeek::detail::dbg_cmd_break_set_state(cmd_code, args); dbg_cmd_break_set_state(cmd_code, args);
break; break;
case dcPrint: case dcPrint:
zeek::detail::dbg_cmd_print(cmd_code, args); dbg_cmd_print(cmd_code, args);
break; break;
case dcBacktrace: case dcBacktrace:
return zeek::detail::dbg_cmd_backtrace(cmd_code, args); return dbg_cmd_backtrace(cmd_code, args);
case dcFrame: case dcFrame:
case dcUp: case dcUp:
case dcDown: case dcDown:
return zeek::detail::dbg_cmd_frame(cmd_code, args); return dbg_cmd_frame(cmd_code, args);
case dcInfo: case dcInfo:
return zeek::detail::dbg_cmd_info(cmd_code, args); return dbg_cmd_info(cmd_code, args);
case dcList: case dcList:
return zeek::detail::dbg_cmd_list(cmd_code, args); return dbg_cmd_list(cmd_code, args);
case dcDisplay: case dcDisplay:
case dcUndisplay: case dcUndisplay:
@ -728,7 +728,7 @@ static int dbg_dispatch_cmd(DebugCmd cmd_code, const vector<string>& args)
break; break;
case dcTrace: case dcTrace:
return zeek::detail::dbg_cmd_trace(cmd_code, args); return dbg_cmd_trace(cmd_code, args);
default: default:
debug_msg("INTERNAL ERROR: " debug_msg("INTERNAL ERROR: "
@ -753,22 +753,22 @@ static char* get_prompt(bool reset_counter = false)
return prompt; return prompt;
} }
string get_context_description(const zeek::detail::Stmt* stmt, const zeek::detail::Frame* frame) string get_context_description(const Stmt* stmt, const Frame* frame)
{ {
ODesc d; ODesc d;
const zeek::detail::ScriptFunc* func = frame ? frame->GetFunction() : nullptr; const ScriptFunc* func = frame ? frame->GetFunction() : nullptr;
if ( func ) if ( func )
func->DescribeDebug(&d, frame->GetFuncArgs()); func->DescribeDebug(&d, frame->GetFuncArgs());
else else
d.Add("<unknown function>", 0); d.Add("<unknown function>", 0);
zeek::detail::Location loc; Location loc;
if ( stmt ) if ( stmt )
loc = *stmt->GetLocationInfo(); loc = *stmt->GetLocationInfo();
else else
{ {
loc.filename = zeek::util::copy_string("<no filename>"); loc.filename = util::copy_string("<no filename>");
loc.last_line = 0; loc.last_line = 0;
} }
@ -794,18 +794,18 @@ int dbg_handle_debug_input()
g_debugger_state.BreakFromSignal(false); g_debugger_state.BreakFromSignal(false);
} }
zeek::detail::Frame* curr_frame = g_frame_stack.back(); Frame* curr_frame = g_frame_stack.back();
const zeek::detail::ScriptFunc* func = curr_frame->GetFunction(); const ScriptFunc* func = curr_frame->GetFunction();
if ( func ) if ( func )
zeek::detail::current_module = extract_module_name(func->Name()); current_module = extract_module_name(func->Name());
else else
zeek::detail::current_module = GLOBAL_MODULE_NAME; current_module = GLOBAL_MODULE_NAME;
const zeek::detail::Stmt* stmt = curr_frame->GetNextStmt(); const Stmt* stmt = curr_frame->GetNextStmt();
if ( ! stmt ) if ( ! stmt )
zeek::reporter->InternalError("Assertion failed: stmt != 0"); reporter->InternalError("Assertion failed: stmt != 0");
const zeek::detail::Location loc = *stmt->GetLocationInfo(); const Location loc = *stmt->GetLocationInfo();
if ( ! step_or_next_pending || g_frame_stack.back() != last_frame ) if ( ! step_or_next_pending || g_frame_stack.back() != last_frame )
{ {
@ -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*) zeek::util::safe_malloc(1024); input_line = (char*) 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);
@ -865,7 +865,7 @@ int dbg_handle_debug_input()
// Return true to continue execution, false to abort. // Return true to continue execution, false to abort.
bool pre_execute_stmt(zeek::detail::Stmt* stmt, zeek::detail::Frame* f) bool pre_execute_stmt(Stmt* stmt, Frame* f)
{ {
if ( ! g_policy_debug || if ( ! g_policy_debug ||
stmt->Tag() == STMT_LIST || stmt->Tag() == STMT_NULL ) stmt->Tag() == STMT_LIST || stmt->Tag() == STMT_NULL )
@ -909,7 +909,7 @@ bool pre_execute_stmt(zeek::detail::Stmt* stmt, zeek::detail::Frame* f)
p = g_debugger_state.breakpoint_map.equal_range(stmt); p = g_debugger_state.breakpoint_map.equal_range(stmt);
if ( p.first == p.second ) if ( p.first == p.second )
zeek::reporter->InternalError("Breakpoint count nonzero, but no matching breakpoints"); reporter->InternalError("Breakpoint count nonzero, but no matching breakpoints");
for ( BPMapType::iterator i = p.first; i != p.second; ++i ) for ( BPMapType::iterator i = p.first; i != p.second; ++i )
{ {
@ -930,7 +930,7 @@ bool pre_execute_stmt(zeek::detail::Stmt* stmt, zeek::detail::Frame* f)
return true; return true;
} }
bool post_execute_stmt(zeek::detail::Stmt* stmt, zeek::detail::Frame* f, zeek::Val* result, zeek::detail::StmtFlowType* flow) bool post_execute_stmt(Stmt* stmt, Frame* f, Val* result, StmtFlowType* flow)
{ {
// Handle the case where someone issues a "next" debugger command, // Handle the case where someone issues a "next" debugger command,
// but we're at a return statement, so the next statement is in // but we're at a return statement, so the next statement is in
@ -957,7 +957,7 @@ bool post_execute_stmt(zeek::detail::Stmt* stmt, zeek::detail::Frame* f, zeek::V
return true; return true;
} }
zeek::ValPtr dbg_eval_expr(const char* expr) ValPtr dbg_eval_expr(const char* expr)
{ {
// Push the current frame's associated scope. // Push the current frame's associated scope.
// Note: g_debugger_state.curr_frame_idx is the user-visible number, // Note: g_debugger_state.curr_frame_idx is the user-visible number,
@ -966,17 +966,17 @@ zeek::ValPtr dbg_eval_expr(const char* expr)
(g_frame_stack.size() - 1) - g_debugger_state.curr_frame_idx; (g_frame_stack.size() - 1) - g_debugger_state.curr_frame_idx;
if ( ! (frame_idx >= 0 && (unsigned) frame_idx < g_frame_stack.size()) ) if ( ! (frame_idx >= 0 && (unsigned) frame_idx < g_frame_stack.size()) )
zeek::reporter->InternalError("Assertion failed: frame_idx >= 0 && (unsigned) frame_idx < g_frame_stack.size()"); reporter->InternalError("Assertion failed: frame_idx >= 0 && (unsigned) frame_idx < g_frame_stack.size()");
zeek::detail::Frame* frame = g_frame_stack[frame_idx]; Frame* frame = g_frame_stack[frame_idx];
if ( ! (frame) ) if ( ! (frame) )
zeek::reporter->InternalError("Assertion failed: frame"); reporter->InternalError("Assertion failed: frame");
const zeek::detail::ScriptFunc* func = frame->GetFunction(); const ScriptFunc* func = frame->GetFunction();
if ( func ) if ( func )
{ {
Ref(func->GetScope()); Ref(func->GetScope());
zeek::detail::push_existing_scope(func->GetScope()); push_existing_scope(func->GetScope());
} }
// ### Possibly push a debugger-local scope? // ### Possibly push a debugger-local scope?
@ -992,7 +992,7 @@ zeek::ValPtr dbg_eval_expr(const char* expr)
yylloc.first_line = yylloc.last_line = line_number = 1; yylloc.first_line = yylloc.last_line = line_number = 1;
// Parse the thing into an expr. // Parse the thing into an expr.
zeek::ValPtr result; ValPtr result;
if ( yyparse() ) if ( yyparse() )
{ {
if ( g_curr_debug_error ) if ( g_curr_debug_error )
@ -1010,7 +1010,7 @@ zeek::ValPtr dbg_eval_expr(const char* expr)
result = g_curr_debug_expr->Eval(frame); result = g_curr_debug_expr->Eval(frame);
if ( func ) if ( func )
zeek::detail::pop_scope(); pop_scope();
delete g_curr_debug_expr; delete g_curr_debug_expr;
g_curr_debug_expr = nullptr; g_curr_debug_expr = nullptr;

View file

@ -32,15 +32,15 @@ class ParseLocationRec {
public: public:
ParseLocationRecType type; ParseLocationRecType type;
int32_t line; int32_t line;
zeek::detail::Stmt* stmt; Stmt* stmt;
const char* filename; const char* filename;
}; };
class StmtLocMapping; class StmtLocMapping;
using Filemap = zeek::PQueue<StmtLocMapping>; // mapping for a single file using Filemap = PQueue<StmtLocMapping>; // mapping for a single file
using BPIDMapType = std::map<int, zeek::detail::DbgBreakpoint*>; using BPIDMapType = std::map<int, DbgBreakpoint*>;
using BPMapType = std::multimap<const zeek::detail::Stmt*, zeek::detail::DbgBreakpoint*>; using BPMapType = std::multimap<const Stmt*, DbgBreakpoint*>;
class TraceState { class TraceState {
public: public:
@ -87,11 +87,11 @@ public:
bool already_did_list; // did we already do a 'list' command? bool already_did_list; // did we already do a 'list' command?
zeek::detail::Location last_loc; // used by 'list'; the last location listed Location last_loc; // used by 'list'; the last location listed
BPIDMapType breakpoints; // BPID -> Breakpoint BPIDMapType breakpoints; // BPID -> Breakpoint
std::vector<zeek::detail::DbgWatch*> watches; std::vector<DbgWatch*> watches;
std::vector<zeek::detail::DbgDisplay*> displays; std::vector<DbgDisplay*> displays;
BPMapType breakpoint_map; // maps Stmt -> Breakpoints on it BPMapType breakpoint_map; // maps Stmt -> Breakpoints on it
protected: protected:
@ -101,7 +101,7 @@ protected:
int next_bp_id, next_watch_id, next_display_id; int next_bp_id, next_watch_id, next_display_id;
private: private:
zeek::detail::Frame* dbg_locals; // unused Frame* dbg_locals; // unused
}; };
// Source line -> statement mapping. // Source line -> statement mapping.
@ -109,15 +109,15 @@ private:
class StmtLocMapping { class StmtLocMapping {
public: public:
StmtLocMapping() { } StmtLocMapping() { }
StmtLocMapping(const zeek::detail::Location* l, zeek::detail::Stmt* s) { loc = *l; stmt = s; } StmtLocMapping(const Location* l, Stmt* s) { loc = *l; stmt = s; }
bool StartsAfter(const StmtLocMapping* m2); bool StartsAfter(const StmtLocMapping* m2);
const zeek::detail::Location& Loc() const { return loc; } const Location& Loc() const { return loc; }
zeek::detail::Stmt* Statement() const { return stmt; } Stmt* Statement() const { return stmt; }
protected: protected:
zeek::detail::Location loc; Location loc;
zeek::detail::Stmt* stmt; Stmt* stmt;
}; };
extern bool g_policy_debug; // enable debugging facility extern bool g_policy_debug; // enable debugging facility
@ -147,8 +147,8 @@ std::vector<ParseLocationRec> parse_location_string(const std::string& s);
// Debugging hooks. // Debugging hooks.
// Return true to continue execution, false to abort. // Return true to continue execution, false to abort.
bool pre_execute_stmt(zeek::detail::Stmt* stmt, zeek::detail::Frame* f); bool pre_execute_stmt(Stmt* stmt, Frame* f);
bool post_execute_stmt(zeek::detail::Stmt* stmt, zeek::detail::Frame* f, zeek::Val* result, StmtFlowType* flow); bool post_execute_stmt(Stmt* stmt, Frame* f, Val* result, StmtFlowType* flow);
// Returns 1 if successful, 0 otherwise. // Returns 1 if successful, 0 otherwise.
// If cmdfile is non-nil, it contains the location of a file of commands // If cmdfile is non-nil, it contains the location of a file of commands
@ -164,19 +164,19 @@ int dbg_handle_debug_input(); // read a line and then have it executed
int dbg_execute_command(const char* cmd); int dbg_execute_command(const char* cmd);
// Interactive expression evaluation. // Interactive expression evaluation.
zeek::ValPtr dbg_eval_expr(const char* expr); ValPtr dbg_eval_expr(const char* expr);
// Get line that looks like "In FnFoo(arg = val) at File:Line". // Get line that looks like "In FnFoo(arg = val) at File:Line".
std::string get_context_description(const zeek::detail::Stmt* stmt, const zeek::detail::Frame* frame); std::string get_context_description(const Stmt* stmt, const Frame* frame);
extern zeek::detail::Frame* g_dbg_locals; // variables created within debugger context extern Frame* g_dbg_locals; // variables created within debugger context
extern std::map<std::string, Filemap*> g_dbgfilemaps; // filename => filemap extern std::map<std::string, Filemap*> g_dbgfilemaps; // filename => filemap
// Perhaps add a code/priority argument to do selective output. // Perhaps add a code/priority argument to do selective output.
int debug_msg(const char* fmt, ...) __attribute__ ((format (printf, 1, 2))); int debug_msg(const char* fmt, ...) __attribute__ ((format (printf, 1, 2)));
} // namespace zeek::detail } // namespace detail
} // namespace zeek } // namespace zeek
constexpr auto plrUnknown [[deprecated("Remove in v4.1. Use zeek::detail::PLR_UNKNOWN.")]] = zeek::detail::PLR_UNKNOWN; constexpr auto plrUnknown [[deprecated("Remove in v4.1. Use zeek::detail::PLR_UNKNOWN.")]] = zeek::detail::PLR_UNKNOWN;

View file

@ -5,278 +5,282 @@
// //
#include "util.h" #include "util.h"
void zeek::detail::init_global_dbg_constants () { namespace zeek::detail {
void init_global_dbg_constants () {
{ {
zeek::detail::DebugCmdInfo* info; DebugCmdInfo* info;
const char * const names[] = { }; const char * const names[] = { };
info = new zeek::detail::DebugCmdInfo(dcInvalid, names, 0, false, "This function should not be called", info = new DebugCmdInfo(dcInvalid, names, 0, false, "This function should not be called",
false); false);
zeek::detail::g_DebugCmdInfos.push_back(info); g_DebugCmdInfos.push_back(info);
} }
{ {
zeek::detail::DebugCmdInfo* info; DebugCmdInfo* info;
const char * const names[] = { const char * const names[] = {
"help" "help"
}; };
info = new zeek::detail::DebugCmdInfo(dcHelp, names, 1, false, "Get help with debugger commands", info = new DebugCmdInfo(dcHelp, names, 1, false, "Get help with debugger commands",
false); false);
zeek::detail::g_DebugCmdInfos.push_back(info); g_DebugCmdInfos.push_back(info);
} }
{ {
zeek::detail::DebugCmdInfo* info; DebugCmdInfo* info;
const char * const names[] = { const char * const names[] = {
"quit" "quit"
}; };
info = new zeek::detail::DebugCmdInfo(dcQuit, names, 1, false, "Exit Zeek", info = new DebugCmdInfo(dcQuit, names, 1, false, "Exit Zeek",
false); false);
zeek::detail::g_DebugCmdInfos.push_back(info); g_DebugCmdInfos.push_back(info);
} }
{ {
zeek::detail::DebugCmdInfo* info; DebugCmdInfo* info;
const char * const names[] = { const char * const names[] = {
"next" "next"
}; };
info = new zeek::detail::DebugCmdInfo(dcNext, names, 1, true, "Step to the following statement, skipping function calls", info = new DebugCmdInfo(dcNext, names, 1, true, "Step to the following statement, skipping function calls",
true); true);
zeek::detail::g_DebugCmdInfos.push_back(info); g_DebugCmdInfos.push_back(info);
} }
{ {
zeek::detail::DebugCmdInfo* info; DebugCmdInfo* info;
const char * const names[] = { const char * const names[] = {
"step", "step",
"s" "s"
}; };
info = new zeek::detail::DebugCmdInfo(dcStep, names, 2, true, "Step to following statements, stepping in to function calls", info = new DebugCmdInfo(dcStep, names, 2, true, "Step to following statements, stepping in to function calls",
true); true);
zeek::detail::g_DebugCmdInfos.push_back(info); g_DebugCmdInfos.push_back(info);
} }
{ {
zeek::detail::DebugCmdInfo* info; DebugCmdInfo* info;
const char * const names[] = { const char * const names[] = {
"continue", "continue",
"c" "c"
}; };
info = new zeek::detail::DebugCmdInfo(dcContinue, names, 2, true, "Resume execution of the policy script", info = new DebugCmdInfo(dcContinue, names, 2, true, "Resume execution of the policy script",
true); true);
zeek::detail::g_DebugCmdInfos.push_back(info); g_DebugCmdInfos.push_back(info);
} }
{ {
zeek::detail::DebugCmdInfo* info; DebugCmdInfo* info;
const char * const names[] = { const char * const names[] = {
"finish" "finish"
}; };
info = new zeek::detail::DebugCmdInfo(dcFinish, names, 1, true, "Run until the currently-executing function completes", info = new DebugCmdInfo(dcFinish, names, 1, true, "Run until the currently-executing function completes",
true); true);
zeek::detail::g_DebugCmdInfos.push_back(info); g_DebugCmdInfos.push_back(info);
} }
{ {
zeek::detail::DebugCmdInfo* info; DebugCmdInfo* info;
const char * const names[] = { const char * const names[] = {
"break", "break",
"b" "b"
}; };
info = new zeek::detail::DebugCmdInfo(dcBreak, names, 2, false, "Set a breakpoint", info = new DebugCmdInfo(dcBreak, names, 2, false, "Set a breakpoint",
false); false);
zeek::detail::g_DebugCmdInfos.push_back(info); g_DebugCmdInfos.push_back(info);
} }
{ {
zeek::detail::DebugCmdInfo* info; DebugCmdInfo* info;
const char * const names[] = { const char * const names[] = {
"cond" "cond"
}; };
info = new zeek::detail::DebugCmdInfo(dcBreakCondition, names, 1, false, "", info = new DebugCmdInfo(dcBreakCondition, names, 1, false, "",
false); false);
zeek::detail::g_DebugCmdInfos.push_back(info); g_DebugCmdInfos.push_back(info);
} }
{ {
zeek::detail::DebugCmdInfo* info; DebugCmdInfo* info;
const char * const names[] = { const char * const names[] = {
"delete", "delete",
"d" "d"
}; };
info = new zeek::detail::DebugCmdInfo(dcDeleteBreak, names, 2, false, "Delete the specified breakpoints; delete all if no arguments", info = new DebugCmdInfo(dcDeleteBreak, names, 2, false, "Delete the specified breakpoints; delete all if no arguments",
false); false);
zeek::detail::g_DebugCmdInfos.push_back(info); g_DebugCmdInfos.push_back(info);
} }
{ {
zeek::detail::DebugCmdInfo* info; DebugCmdInfo* info;
const char * const names[] = { const char * const names[] = {
"clear" "clear"
}; };
info = new zeek::detail::DebugCmdInfo(dcClearBreak, names, 1, false, "", info = new DebugCmdInfo(dcClearBreak, names, 1, false, "",
false); false);
zeek::detail::g_DebugCmdInfos.push_back(info); g_DebugCmdInfos.push_back(info);
} }
{ {
zeek::detail::DebugCmdInfo* info; DebugCmdInfo* info;
const char * const names[] = { const char * const names[] = {
"disable", "disable",
"dis" "dis"
}; };
info = new zeek::detail::DebugCmdInfo(dcDisableBreak, names, 2, false, "", info = new DebugCmdInfo(dcDisableBreak, names, 2, false, "",
false); false);
zeek::detail::g_DebugCmdInfos.push_back(info); g_DebugCmdInfos.push_back(info);
} }
{ {
zeek::detail::DebugCmdInfo* info; DebugCmdInfo* info;
const char * const names[] = { const char * const names[] = {
"enable" "enable"
}; };
info = new zeek::detail::DebugCmdInfo(dcEnableBreak, names, 1, false, "", info = new DebugCmdInfo(dcEnableBreak, names, 1, false, "",
false); false);
zeek::detail::g_DebugCmdInfos.push_back(info); g_DebugCmdInfos.push_back(info);
} }
{ {
zeek::detail::DebugCmdInfo* info; DebugCmdInfo* info;
const char * const names[] = { const char * const names[] = {
"ignore" "ignore"
}; };
info = new zeek::detail::DebugCmdInfo(dcIgnoreBreak, names, 1, false, "", info = new DebugCmdInfo(dcIgnoreBreak, names, 1, false, "",
false); false);
zeek::detail::g_DebugCmdInfos.push_back(info); g_DebugCmdInfos.push_back(info);
} }
{ {
zeek::detail::DebugCmdInfo* info; DebugCmdInfo* info;
const char * const names[] = { const char * const names[] = {
"print", "print",
"p", "p",
"set" "set"
}; };
info = new zeek::detail::DebugCmdInfo(dcPrint, names, 3, false, "Evaluate an expression and print the result (also aliased as 'set')", info = new DebugCmdInfo(dcPrint, names, 3, false, "Evaluate an expression and print the result (also aliased as 'set')",
true); true);
zeek::detail::g_DebugCmdInfos.push_back(info); g_DebugCmdInfos.push_back(info);
} }
{ {
zeek::detail::DebugCmdInfo* info; DebugCmdInfo* info;
const char * const names[] = { const char * const names[] = {
"backtrace", "backtrace",
"bt", "bt",
"where" "where"
}; };
info = new zeek::detail::DebugCmdInfo(dcBacktrace, names, 3, false, "Print a stack trace (with +- N argument, inner/outer N frames only)", info = new DebugCmdInfo(dcBacktrace, names, 3, false, "Print a stack trace (with +- N argument, inner/outer N frames only)",
false); false);
zeek::detail::g_DebugCmdInfos.push_back(info); g_DebugCmdInfos.push_back(info);
} }
{ {
zeek::detail::DebugCmdInfo* info; DebugCmdInfo* info;
const char * const names[] = { const char * const names[] = {
"frame" "frame"
}; };
info = new zeek::detail::DebugCmdInfo(dcFrame, names, 1, false, "Select frame number N", info = new DebugCmdInfo(dcFrame, names, 1, false, "Select frame number N",
false); false);
zeek::detail::g_DebugCmdInfos.push_back(info); g_DebugCmdInfos.push_back(info);
} }
{ {
zeek::detail::DebugCmdInfo* info; DebugCmdInfo* info;
const char * const names[] = { const char * const names[] = {
"up" "up"
}; };
info = new zeek::detail::DebugCmdInfo(dcUp, names, 1, false, "Select the stack frame one level up", info = new DebugCmdInfo(dcUp, names, 1, false, "Select the stack frame one level up",
false); false);
zeek::detail::g_DebugCmdInfos.push_back(info); g_DebugCmdInfos.push_back(info);
} }
{ {
zeek::detail::DebugCmdInfo* info; DebugCmdInfo* info;
const char * const names[] = { const char * const names[] = {
"down" "down"
}; };
info = new zeek::detail::DebugCmdInfo(dcDown, names, 1, false, "Select the stack frame one level down", info = new DebugCmdInfo(dcDown, names, 1, false, "Select the stack frame one level down",
false); false);
zeek::detail::g_DebugCmdInfos.push_back(info); g_DebugCmdInfos.push_back(info);
} }
{ {
zeek::detail::DebugCmdInfo* info; DebugCmdInfo* info;
const char * const names[] = { const char * const names[] = {
"info" "info"
}; };
info = new zeek::detail::DebugCmdInfo(dcInfo, names, 1, false, "Get information about the debugging environment", info = new DebugCmdInfo(dcInfo, names, 1, false, "Get information about the debugging environment",
false); false);
zeek::detail::g_DebugCmdInfos.push_back(info); g_DebugCmdInfos.push_back(info);
} }
{ {
zeek::detail::DebugCmdInfo* info; DebugCmdInfo* info;
const char * const names[] = { const char * const names[] = {
"list", "list",
"l" "l"
}; };
info = new zeek::detail::DebugCmdInfo(dcList, names, 2, false, "Print source lines surrounding specified context", info = new DebugCmdInfo(dcList, names, 2, false, "Print source lines surrounding specified context",
true); true);
zeek::detail::g_DebugCmdInfos.push_back(info); g_DebugCmdInfos.push_back(info);
} }
{ {
zeek::detail::DebugCmdInfo* info; DebugCmdInfo* info;
const char * const names[] = { const char * const names[] = {
"display" "display"
}; };
info = new zeek::detail::DebugCmdInfo(dcDisplay, names, 1, false, "", info = new DebugCmdInfo(dcDisplay, names, 1, false, "",
false); false);
zeek::detail::g_DebugCmdInfos.push_back(info); g_DebugCmdInfos.push_back(info);
} }
{ {
zeek::detail::DebugCmdInfo* info; DebugCmdInfo* info;
const char * const names[] = { const char * const names[] = {
"undisplay" "undisplay"
}; };
info = new zeek::detail::DebugCmdInfo(dcUndisplay, names, 1, false, "", info = new DebugCmdInfo(dcUndisplay, names, 1, false, "",
false); false);
zeek::detail::g_DebugCmdInfos.push_back(info); g_DebugCmdInfos.push_back(info);
} }
{ {
zeek::detail::DebugCmdInfo* info; DebugCmdInfo* info;
const char * const names[] = { const char * const names[] = {
"trace" "trace"
}; };
info = new zeek::detail::DebugCmdInfo(dcTrace, names, 1, false, "Turn on or off execution tracing (with no arguments, prints current state.)", info = new DebugCmdInfo(dcTrace, names, 1, false, "Turn on or off execution tracing (with no arguments, prints current state.)",
false); false);
zeek::detail::g_DebugCmdInfos.push_back(info); g_DebugCmdInfos.push_back(info);
} }
} }
} // namespace zeek::detail

View file

@ -26,6 +26,11 @@
using namespace std; using namespace std;
zeek::PQueue<zeek::detail::DebugCmdInfo> zeek::detail::g_DebugCmdInfos;
zeek::PQueue<zeek::detail::DebugCmdInfo>& g_DebugCmdInfos = zeek::detail::g_DebugCmdInfos;
namespace zeek::detail {
// //
// Helper routines // Helper routines
// //
@ -34,10 +39,10 @@ static bool string_is_regex(const string& s)
return strpbrk(s.data(), "?*\\+"); return strpbrk(s.data(), "?*\\+");
} }
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<ID*>& matches,
bool func_only = false) bool func_only = false)
{ {
if ( zeek::util::streq(orig_regex.c_str(), "") ) if ( util::streq(orig_regex.c_str(), "") )
return; return;
string regex = "^"; string regex = "^";
@ -53,24 +58,24 @@ static void lookup_global_symbols_regex(const string& orig_regex, vector<zeek::d
regex_t re; regex_t re;
if ( regcomp(&re, regex.c_str(), REG_EXTENDED|REG_NOSUB) ) if ( regcomp(&re, regex.c_str(), REG_EXTENDED|REG_NOSUB) )
{ {
zeek::detail::debug_msg("Invalid regular expression: %s\n", regex.c_str()); debug_msg("Invalid regular expression: %s\n", regex.c_str());
return; return;
} }
zeek::detail::Scope* global = zeek::detail::global_scope(); Scope* global = global_scope();
const auto& syms = global->Vars(); const auto& syms = global->Vars();
zeek::detail::ID* nextid; ID* nextid;
for ( const auto& sym : syms ) for ( const auto& sym : syms )
{ {
zeek::detail::ID* nextid = sym.second.get(); ID* nextid = sym.second.get();
if ( ! func_only || nextid->GetType()->Tag() == zeek::TYPE_FUNC ) if ( ! func_only || nextid->GetType()->Tag() == TYPE_FUNC )
if ( ! regexec (&re, nextid->Name(), 0, 0, 0) ) if ( ! regexec (&re, nextid->Name(), 0, 0, 0) )
matches.push_back(nextid); matches.push_back(nextid);
} }
} }
static void choose_global_symbols_regex(const string& regex, vector<zeek::detail::ID*>& choices, static void choose_global_symbols_regex(const string& regex, vector<ID*>& choices,
bool func_only = false) bool func_only = false)
{ {
lookup_global_symbols_regex(regex, choices, func_only); lookup_global_symbols_regex(regex, choices, func_only);
@ -80,14 +85,14 @@ static void choose_global_symbols_regex(const string& regex, vector<zeek::detail
while ( true ) while ( true )
{ {
zeek::detail::debug_msg("There were multiple matches, please choose:\n"); debug_msg("There were multiple matches, please choose:\n");
for ( size_t i = 0; i < choices.size(); i++ ) for ( size_t i = 0; i < choices.size(); i++ )
zeek::detail::debug_msg("[%zu] %s\n", i+1, choices[i]->Name()); debug_msg("[%zu] %s\n", i+1, choices[i]->Name());
zeek::detail::debug_msg("[a] All of the above\n"); debug_msg("[a] All of the above\n");
zeek::detail::debug_msg("[n] None of the above\n"); debug_msg("[n] None of the above\n");
zeek::detail::debug_msg("Enter your choice: "); debug_msg("Enter your choice: ");
char charinput[256]; char charinput[256];
if ( ! fgets(charinput, sizeof(charinput) - 1, stdin) ) if ( ! fgets(charinput, sizeof(charinput) - 1, stdin) )
@ -110,7 +115,7 @@ static void choose_global_symbols_regex(const string& regex, vector<zeek::detail
int option = atoi(input.c_str()); int option = atoi(input.c_str());
if ( option > 0 && option <= (int) choices.size() ) if ( option > 0 && option <= (int) choices.size() )
{ {
zeek::detail::ID* choice = choices[option - 1]; ID* choice = choices[option - 1];
choices.clear(); choices.clear();
choices.push_back(choice); choices.push_back(choice);
return; return;
@ -123,11 +128,6 @@ static void choose_global_symbols_regex(const string& regex, vector<zeek::detail
// DebugCmdInfo implementation // DebugCmdInfo implementation
// //
zeek::PQueue<zeek::detail::DebugCmdInfo> zeek::detail::g_DebugCmdInfos;
zeek::PQueue<zeek::detail::DebugCmdInfo>& g_DebugCmdInfos = zeek::detail::g_DebugCmdInfos;
namespace zeek::detail {
DebugCmdInfo::DebugCmdInfo(const DebugCmdInfo& info) DebugCmdInfo::DebugCmdInfo(const DebugCmdInfo& info)
: cmd(info.cmd), helpstring(nullptr) : cmd(info.cmd), helpstring(nullptr)
{ {
@ -206,7 +206,7 @@ static int dbg_backtrace_internal(int start, int end)
if ( start < 0 || end < 0 || if ( start < 0 || end < 0 ||
(unsigned) start >= g_frame_stack.size() || (unsigned) start >= g_frame_stack.size() ||
(unsigned) end >= g_frame_stack.size() ) (unsigned) end >= g_frame_stack.size() )
zeek::reporter->InternalError("Invalid stack frame index in DbgBacktraceInternal\n"); reporter->InternalError("Invalid stack frame index in DbgBacktraceInternal\n");
if ( start < end ) if ( start < end )
{ {
@ -217,8 +217,8 @@ static int dbg_backtrace_internal(int start, int end)
for ( int i = start; i >= end; --i ) for ( int i = start; i >= end; --i )
{ {
const zeek::detail::Frame* f = g_frame_stack[i]; const Frame* f = g_frame_stack[i];
const zeek::detail::Stmt* stmt = f ? f->GetNextStmt() : nullptr; const Stmt* stmt = f ? f->GetNextStmt() : nullptr;
string context = get_context_description(stmt, f); string context = get_context_description(stmt, f);
debug_msg("#%d %s\n", debug_msg("#%d %s\n",
@ -335,11 +335,11 @@ int dbg_cmd_frame(DebugCmd cmd, const vector<string>& args)
// Set the current location to the new frame being looked at // Set the current location to the new frame being looked at
// for 'list', 'break', etc. // for 'list', 'break', etc.
const zeek::detail::Stmt* stmt = g_frame_stack[user_frame_number]->GetNextStmt(); const Stmt* stmt = g_frame_stack[user_frame_number]->GetNextStmt();
if ( ! stmt ) if ( ! stmt )
zeek::reporter->InternalError("Assertion failed: %s", "stmt != 0"); reporter->InternalError("Assertion failed: %s", "stmt != 0");
const zeek::detail::Location loc = *stmt->GetLocationInfo(); const Location loc = *stmt->GetLocationInfo();
g_debugger_state.last_loc = loc; g_debugger_state.last_loc = loc;
g_debugger_state.already_did_list = false; g_debugger_state.already_did_list = false;
@ -375,9 +375,9 @@ int dbg_cmd_break(DebugCmd cmd, const vector<string>& args)
g_frame_stack.size() - 1 - g_frame_stack.size() - 1 -
g_debugger_state.curr_frame_idx; g_debugger_state.curr_frame_idx;
zeek::detail::Stmt* stmt = g_frame_stack[user_frame_number]->GetNextStmt(); Stmt* stmt = g_frame_stack[user_frame_number]->GetNextStmt();
if ( ! stmt ) if ( ! stmt )
zeek::reporter->InternalError("Assertion failed: %s", "stmt != 0"); reporter->InternalError("Assertion failed: %s", "stmt != 0");
DbgBreakpoint* bp = new DbgBreakpoint(); DbgBreakpoint* bp = new DbgBreakpoint();
bp->SetID(g_debugger_state.NextBPID()); bp->SetID(g_debugger_state.NextBPID());
@ -400,7 +400,7 @@ int dbg_cmd_break(DebugCmd cmd, const vector<string>& args)
vector<string> locstrings; vector<string> locstrings;
if ( string_is_regex(args[0]) ) if ( string_is_regex(args[0]) )
{ {
vector<zeek::detail::ID*> choices; vector<ID*> choices;
choose_global_symbols_regex(args[0], choices, true); choose_global_symbols_regex(args[0], choices, true);
for ( unsigned int i = 0; i < choices.size(); ++i ) for ( unsigned int i = 0; i < choices.size(); ++i )
locstrings.push_back(choices[i]->Name()); locstrings.push_back(choices[i]->Name());
@ -540,7 +540,7 @@ int dbg_cmd_break_set_state(DebugCmd cmd, const vector<string>& args)
break; break;
default: default:
zeek::reporter->InternalError("Invalid command in DbgCmdBreakSetState\n"); reporter->InternalError("Invalid command in DbgCmdBreakSetState\n");
} }
} }

View file

@ -43,7 +43,7 @@ protected:
bool repeatable; bool repeatable;
}; };
extern zeek::PQueue<DebugCmdInfo> g_DebugCmdInfos; extern PQueue<DebugCmdInfo> g_DebugCmdInfos;
void init_global_dbg_constants (); void init_global_dbg_constants ();

View file

@ -49,14 +49,14 @@ void DebugLogger::OpenDebugLog(const char* filename)
{ {
if ( filename ) if ( filename )
{ {
filename = zeek::util::detail::log_file_name(filename); filename = util::detail::log_file_name(filename);
file = fopen(filename, "w"); file = fopen(filename, "w");
if ( ! file ) if ( ! file )
{ {
// The reporter may not be initialized here yet. // The reporter may not be initialized here yet.
if ( zeek::reporter ) if ( reporter )
zeek::reporter->FatalError("can't open '%s' for debugging output", filename); reporter->FatalError("can't open '%s' for debugging output", filename);
else else
{ {
fprintf(stderr, "can't open '%s' for debugging output\n", filename); fprintf(stderr, "can't open '%s' for debugging output\n", filename);
@ -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 = zeek::util::copy_string(s); char* tmp = util::copy_string(s);
char* tok = strtok(tmp, ","); char* tok = strtok(tmp, ",");
while ( tok ) while ( tok )
@ -142,7 +142,7 @@ void DebugLogger::EnableStreams(const char* s)
} }
} }
zeek::reporter->FatalError("unknown debug stream '%s', try -B help.\n", tok); reporter->FatalError("unknown debug stream '%s', try -B help.\n", tok);
next: next:
tok = strtok(0, ","); tok = strtok(0, ",");
@ -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::run_state::network_time, zeek::util::current_time(true), g->prefix); run_state::network_time, 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);
@ -173,16 +173,16 @@ void DebugLogger::Log(DebugStream stream, const char* fmt, ...)
fflush(file); fflush(file);
} }
void DebugLogger::Log(const zeek::plugin::Plugin& plugin, const char* fmt, ...) void DebugLogger::Log(const plugin::Plugin& plugin, const char* fmt, ...)
{ {
std::string tok = std::string("plugin-") + plugin.Name(); std::string tok = std::string("plugin-") + plugin.Name();
tok = zeek::util::strreplace(tok, "::", "-"); tok = 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::run_state::network_time, zeek::util::current_time(true), plugin.Name().c_str()); run_state::network_time, util::current_time(true), plugin.Name().c_str());
va_list ap; va_list ap;
va_start(ap, fmt); va_start(ap, fmt);

View file

@ -62,7 +62,7 @@ public:
void OpenDebugLog(const char* filename = 0); void OpenDebugLog(const char* filename = 0);
void Log(DebugStream stream, const char* fmt, ...) __attribute__((format(printf, 3, 4))); void Log(DebugStream stream, const char* fmt, ...) __attribute__((format(printf, 3, 4)));
void Log(const zeek::plugin::Plugin& plugin, const char* fmt, ...) __attribute__((format(printf, 3, 4))); void Log(const plugin::Plugin& plugin, const char* fmt, ...) __attribute__((format(printf, 3, 4)));
void PushIndent(DebugStream stream) void PushIndent(DebugStream stream)
{ ++streams[int(stream)].indent; } { ++streams[int(stream)].indent; }

View file

@ -18,7 +18,7 @@
namespace zeek { namespace zeek {
ODesc::ODesc(desc_type t, zeek::File* arg_f) ODesc::ODesc(DescType t, File* arg_f)
{ {
type = t; type = t;
style = STANDARD_STYLE; style = STANDARD_STYLE;
@ -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 = zeek::util::safe_malloc(size); base = util::safe_malloc(size);
((char*) base)[0] = '\0'; ((char*) base)[0] = '\0';
offset = 0; offset = 0;
} }
@ -77,7 +77,7 @@ void ODesc::PushIndent()
void ODesc::PopIndent() void ODesc::PopIndent()
{ {
if ( --indent_level < 0 ) if ( --indent_level < 0 )
zeek::reporter->InternalError("ODesc::PopIndent underflow"); reporter->InternalError("ODesc::PopIndent underflow");
NL(); NL();
} }
@ -85,7 +85,7 @@ void ODesc::PopIndent()
void ODesc::PopIndentNoNL() void ODesc::PopIndentNoNL()
{ {
if ( --indent_level < 0 ) if ( --indent_level < 0 )
zeek::reporter->InternalError("ODesc::PopIndent underflow"); reporter->InternalError("ODesc::PopIndent underflow");
} }
void ODesc::Add(const char* s, int do_indent) void ODesc::Add(const char* s, int do_indent)
@ -180,12 +180,12 @@ void ODesc::Add(double d, bool no_exp)
} }
} }
void ODesc::Add(const zeek::IPAddr& addr) void ODesc::Add(const IPAddr& addr)
{ {
Add(addr.AsString()); Add(addr.AsString());
} }
void ODesc::Add(const zeek::IPPrefix& prefix) void ODesc::Add(const IPPrefix& prefix)
{ {
Add(prefix.AsString()); Add(prefix.AsString());
} }
@ -199,7 +199,7 @@ void ODesc::AddCS(const char* s)
Add(s); Add(s);
} }
void ODesc::AddBytes(const zeek::String* s) void ODesc::AddBytes(const String* s)
{ {
if ( IsReadable() ) if ( IsReadable() )
{ {
@ -207,7 +207,7 @@ void ODesc::AddBytes(const zeek::String* s)
AddBytes(reinterpret_cast<const char*>(s->Bytes()), s->Len()); AddBytes(reinterpret_cast<const char*>(s->Bytes()), s->Len());
else else
{ {
const char* str = s->Render(zeek::String::EXPANDED_STRING); const char* str = s->Render(String::EXPANDED_STRING);
Add(str); Add(str);
delete [] str; delete [] str;
} }
@ -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);
zeek::util::get_escaped_string(this, p.first, p.second, true); util::get_escaped_string(this, p.first, p.second, true);
s = p.first + p.second; s = p.first + p.second;
} }
else else
@ -360,7 +360,7 @@ void ODesc::AddBytesRaw(const void* bytes, unsigned int n)
if ( ! write_failed ) if ( ! write_failed )
// Most likely it's a "disk full" so report // Most likely it's a "disk full" so report
// subsequent failures only once. // subsequent failures only once.
zeek::reporter->Error("error writing to %s: %s", f->Name(), strerror(errno)); reporter->Error("error writing to %s: %s", f->Name(), strerror(errno));
write_failed = true; write_failed = true;
return; return;
@ -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 = zeek::util::safe_realloc(base, size); base = util::safe_realloc(base, size);
} }
void ODesc::Clear() void ODesc::Clear()
@ -400,24 +400,24 @@ void ODesc::Clear()
{ {
free(base); free(base);
size = DEFAULT_SIZE; size = DEFAULT_SIZE;
base = zeek::util::safe_malloc(size); base = util::safe_malloc(size);
((char*) base)[0] = '\0'; ((char*) base)[0] = '\0';
} }
} }
bool ODesc::PushType(const zeek::Type* type) bool ODesc::PushType(const Type* type)
{ {
auto res = encountered_types.insert(type); auto res = encountered_types.insert(type);
return std::get<1>(res); return std::get<1>(res);
} }
bool ODesc::PopType(const zeek::Type* type) bool ODesc::PopType(const Type* type)
{ {
size_t res = encountered_types.erase(type); size_t res = encountered_types.erase(type);
return (res == 1); return (res == 1);
} }
bool ODesc::FindType(const zeek::Type* type) bool ODesc::FindType(const Type* type)
{ {
auto res = encountered_types.find(type); auto res = encountered_types.find(type);

View file

@ -11,31 +11,28 @@
#include <sys/types.h> // for u_char #include <sys/types.h> // for u_char
namespace zeek { class File; }
using BroFile [[deprecated("Remove in v4.1. Use zeek::File.")]] = zeek::File;
ZEEK_FORWARD_DECLARE_NAMESPACED(IPAddr, zeek); ZEEK_FORWARD_DECLARE_NAMESPACED(IPAddr, zeek);
ZEEK_FORWARD_DECLARE_NAMESPACED(IPPrefix, zeek); ZEEK_FORWARD_DECLARE_NAMESPACED(IPPrefix, zeek);
namespace zeek { class Type; }
using BroType [[deprecated("Remove in v4.1. Use zeek::Type instead.")]] = zeek::Type;
namespace zeek { namespace zeek {
enum desc_type { class File;
class Type;
enum DescType {
DESC_READABLE, DESC_READABLE,
DESC_PORTABLE, DESC_PORTABLE,
DESC_BINARY, DESC_BINARY,
}; };
enum desc_style { enum DescStyle {
STANDARD_STYLE, STANDARD_STYLE,
RAW_STYLE, RAW_STYLE,
}; };
class ODesc { class ODesc {
public: public:
explicit ODesc(desc_type t=DESC_READABLE, zeek::File* f=nullptr); explicit ODesc(DescType t=DESC_READABLE, File* f=nullptr);
~ODesc(); ~ODesc();
@ -56,8 +53,8 @@ public:
bool IncludeStats() const { return include_stats; } bool IncludeStats() const { return include_stats; }
void SetIncludeStats(bool s) { include_stats = s; } void SetIncludeStats(bool s) { include_stats = s; }
desc_style Style() const { return style; } DescStyle Style() const { return style; }
void SetStyle(desc_style s) { style = s; } void SetStyle(DescStyle s) { style = s; }
void SetFlush(bool arg_do_flush) { do_flush = arg_do_flush; } void SetFlush(bool arg_do_flush) { do_flush = arg_do_flush; }
@ -91,13 +88,13 @@ public:
void Add(int64_t i); void Add(int64_t i);
void Add(uint64_t u); void Add(uint64_t u);
void Add(double d, bool no_exp=false); void Add(double d, bool no_exp=false);
void Add(const zeek::IPAddr& addr); void Add(const IPAddr& addr);
void Add(const zeek::IPPrefix& prefix); void Add(const IPPrefix& prefix);
// Add s as a counted string. // Add s as a counted string.
void AddCS(const char* s); void AddCS(const char* s);
void AddBytes(const zeek::String* s); void AddBytes(const String* s);
void Add(const char* s1, const char* s2) void Add(const char* s1, const char* s2)
{ Add(s1); Add(s2); } { Add(s1); Add(s2); }
@ -134,7 +131,7 @@ public:
const char* Description() const { return (const char*) base; } const char* Description() const { return (const char*) base; }
const u_char* Bytes() const { return (const u_char *) base; } const u_char* Bytes() const { return (const u_char *) base; }
zeek::byte_vec TakeBytes() byte_vec TakeBytes()
{ {
const void* t = base; const void* t = base;
base = nullptr; base = nullptr;
@ -143,7 +140,7 @@ public:
// Don't clear offset, as we want to still support // Don't clear offset, as we want to still support
// subsequent calls to Len(). // subsequent calls to Len().
return zeek::byte_vec(t); return byte_vec(t);
} }
int Len() const { return offset; } int Len() const { return offset; }
@ -152,9 +149,9 @@ public:
// Used to determine recursive types. Records push their types on here; // Used to determine recursive types. Records push their types on here;
// if the same type (by address) is re-encountered, processing aborts. // if the same type (by address) is re-encountered, processing aborts.
bool PushType(const zeek::Type* type); bool PushType(const Type* type);
bool PopType(const zeek::Type* type); bool PopType(const Type* type);
bool FindType(const zeek::Type* type); bool FindType(const Type* type);
protected: protected:
void Indent(); void Indent();
@ -187,8 +184,8 @@ protected:
*/ */
size_t StartsWithEscapeSequence(const char* start, const char* end); size_t StartsWithEscapeSequence(const char* start, const char* end);
desc_type type; DescType type;
desc_style style; DescStyle style;
void* base; // beginning of buffer void* base; // beginning of buffer
unsigned int offset; // where we are in the buffer unsigned int offset; // where we are in the buffer
@ -204,23 +201,26 @@ protected:
using escape_set = std::set<std::string>; using escape_set = std::set<std::string>;
escape_set escape_sequences; // additional sequences of chars to escape escape_set escape_sequences; // additional sequences of chars to escape
zeek::File* f; // or the file we're using. File* f; // or the file we're using.
int indent_level; int indent_level;
bool do_flush; bool do_flush;
bool include_stats; bool include_stats;
std::set<const zeek::Type*> encountered_types; std::set<const Type*> encountered_types;
}; };
} // namespace zeek } // namespace zeek
using BroFile [[deprecated("Remove in v4.1. Use zeek::File.")]] = zeek::File;
using BroType [[deprecated("Remove in v4.1. Use zeek::Type instead.")]] = zeek::Type;
using ODesc [[deprecated("Remove in v4.1. Use zeek::ODesc.")]] = zeek::ODesc; using ODesc [[deprecated("Remove in v4.1. Use zeek::ODesc.")]] = zeek::ODesc;
using desc_type [[deprecated("Remove in v4.1. Use zeek::desc_type.")]] = zeek::desc_type; using desc_type [[deprecated("Remove in v4.1. Use zeek::DescType.")]] = zeek::DescType;
constexpr auto DESC_READABLE [[deprecated("Remove in v4.1. Use zeek::DESC_READABLE.")]] = zeek::DESC_READABLE; constexpr auto DESC_READABLE [[deprecated("Remove in v4.1. Use zeek::DESC_READABLE.")]] = zeek::DESC_READABLE;
constexpr auto DESC_PORTABLE [[deprecated("Remove in v4.1. Use zeek::DESC_PORTABLE.")]] = zeek::DESC_PORTABLE; constexpr auto DESC_PORTABLE [[deprecated("Remove in v4.1. Use zeek::DESC_PORTABLE.")]] = zeek::DESC_PORTABLE;
constexpr auto DESC_BINARY [[deprecated("Remove in v4.1. Use zeek::DESC_BINARY.")]] = zeek::DESC_BINARY; constexpr auto DESC_BINARY [[deprecated("Remove in v4.1. Use zeek::DESC_BINARY.")]] = zeek::DESC_BINARY;
using desc_style [[deprecated("Remove in v4.1. Use zeek::desc_style.")]] = zeek::desc_style; using desc_style [[deprecated("Remove in v4.1. Use zeek::DescStyle.")]] = zeek::DescStyle;
constexpr auto STANDARD_STYLE [[deprecated("Remove in v4.1. Use zeek::STANDARD_STYLE.")]] = zeek::STANDARD_STYLE; constexpr auto STANDARD_STYLE [[deprecated("Remove in v4.1. Use zeek::STANDARD_STYLE.")]] = zeek::STANDARD_STYLE;
constexpr auto RAW_STYLE [[deprecated("Remove in v4.1. Use zeek::RAW_STYLE.")]] = zeek::RAW_STYLE; constexpr auto RAW_STYLE [[deprecated("Remove in v4.1. Use zeek::RAW_STYLE.")]] = zeek::RAW_STYLE;

View file

@ -95,11 +95,11 @@ TEST_CASE("dict operation")
uint32_t val = 10; uint32_t val = 10;
uint32_t key_val = 5; uint32_t key_val = 5;
zeek::detail::HashKey* key = new zeek::detail::HashKey(key_val); detail::HashKey* key = new detail::HashKey(key_val);
dict.Insert(key, &val); dict.Insert(key, &val);
CHECK(dict.Length() == 1); CHECK(dict.Length() == 1);
zeek::detail::HashKey* key2 = new zeek::detail::HashKey(key_val); detail::HashKey* key2 = new detail::HashKey(key_val);
uint32_t* lookup = dict.Lookup(key2); uint32_t* lookup = dict.Lookup(key2);
CHECK(*lookup == val); CHECK(*lookup == val);
@ -120,7 +120,7 @@ TEST_CASE("dict operation")
uint32_t val2 = 15; uint32_t val2 = 15;
uint32_t key_val2 = 25; uint32_t key_val2 = 25;
key2 = new zeek::detail::HashKey(key_val2); key2 = new detail::HashKey(key_val2);
dict.Insert(key, &val); dict.Insert(key, &val);
dict.Insert(key2, &val2); dict.Insert(key2, &val2);
@ -141,13 +141,13 @@ TEST_CASE("dict nthentry")
uint32_t val = 15; uint32_t val = 15;
uint32_t key_val = 5; uint32_t key_val = 5;
zeek::detail::HashKey* okey = new zeek::detail::HashKey(key_val); detail::HashKey* okey = new detail::HashKey(key_val);
zeek::detail::HashKey* ukey = new zeek::detail::HashKey(key_val); detail::HashKey* ukey = new detail::HashKey(key_val);
uint32_t val2 = 10; uint32_t val2 = 10;
uint32_t key_val2 = 25; uint32_t key_val2 = 25;
zeek::detail::HashKey* okey2 = new zeek::detail::HashKey(key_val2); detail::HashKey* okey2 = new detail::HashKey(key_val2);
zeek::detail::HashKey* ukey2 = new zeek::detail::HashKey(key_val2); detail::HashKey* ukey2 = new detail::HashKey(key_val2);
unordered.Insert(ukey, &val); unordered.Insert(ukey, &val);
unordered.Insert(ukey2, &val2); unordered.Insert(ukey2, &val2);
@ -176,16 +176,16 @@ TEST_CASE("dict iteration")
uint32_t val = 15; uint32_t val = 15;
uint32_t key_val = 5; uint32_t key_val = 5;
zeek::detail::HashKey* key = new zeek::detail::HashKey(key_val); detail::HashKey* key = new detail::HashKey(key_val);
uint32_t val2 = 10; uint32_t val2 = 10;
uint32_t key_val2 = 25; uint32_t key_val2 = 25;
zeek::detail::HashKey* key2 = new zeek::detail::HashKey(key_val2); detail::HashKey* key2 = new detail::HashKey(key_val2);
dict.Insert(key, &val); dict.Insert(key, &val);
dict.Insert(key2, &val2); dict.Insert(key2, &val2);
zeek::detail::HashKey* it_key; detail::HashKey* it_key;
IterCookie* it = dict.InitForIteration(); IterCookie* it = dict.InitForIteration();
CHECK(it != nullptr); CHECK(it != nullptr);
int count = 0; int count = 0;
@ -258,7 +258,7 @@ int Dictionary::ThresholdEntries() const
return capacity - ( capacity >> detail::DICT_LOAD_FACTOR_BITS ); return capacity - ( capacity >> detail::DICT_LOAD_FACTOR_BITS );
} }
zeek::detail::hash_t Dictionary::FibHash(zeek::detail::hash_t h) const detail::hash_t Dictionary::FibHash(detail::hash_t h) const
{ {
//GoldenRatio phi = (sqrt(5)+1)/2 = 1.6180339887... //GoldenRatio phi = (sqrt(5)+1)/2 = 1.6180339887...
//1/phi = phi - 1 //1/phi = phi - 1
@ -268,16 +268,16 @@ zeek::detail::hash_t Dictionary::FibHash(zeek::detail::hash_t h) const
} }
// return position in dict with 2^bit size. // return position in dict with 2^bit size.
int Dictionary::BucketByHash(zeek::detail::hash_t h, int log2_table_size) const //map h to n-bit int Dictionary::BucketByHash(detail::hash_t h, int log2_table_size) const //map h to n-bit
{ {
ASSERT(log2_table_size>=0); ASSERT(log2_table_size>=0);
if ( ! log2_table_size ) if ( ! log2_table_size )
return 0; //<< >> breaks on 64. return 0; //<< >> breaks on 64.
#ifdef DICT_NO_FIB_HASH #ifdef DICT_NO_FIB_HASH
zeek::detail::hash_t hash = h; detail::hash_t hash = h;
#else #else
zeek::detail::hash_t hash = FibHash(h); detail::hash_t hash = FibHash(h);
#endif #endif
int m = 64 - log2_table_size; int m = 64 - log2_table_size;
@ -619,12 +619,12 @@ void generic_delete_func(void* v)
// Look up now also possibly modifies the entry. Why? if the entry is found but not positioned // Look up now also possibly modifies the entry. Why? if the entry is found but not positioned
// according to the current dict (so it's before SizeUp), it will be moved to the right // according to the current dict (so it's before SizeUp), it will be moved to the right
// position so next lookup is fast. // position so next lookup is fast.
void* Dictionary::Lookup(const zeek::detail::HashKey* key) const void* Dictionary::Lookup(const detail::HashKey* key) const
{ {
return Lookup(key->Key(), key->Size(), key->Hash()); return Lookup(key->Key(), key->Size(), key->Hash());
} }
void* Dictionary::Lookup(const void* key, int key_size, zeek::detail::hash_t h) const void* Dictionary::Lookup(const void* key, int key_size, detail::hash_t h) const
{ {
Dictionary* d = const_cast<Dictionary*>(this); Dictionary* d = const_cast<Dictionary*>(this);
int position = d->LookupIndex(key, key_size, h); int position = d->LookupIndex(key, key_size, h);
@ -632,7 +632,7 @@ void* Dictionary::Lookup(const void* key, int key_size, zeek::detail::hash_t h)
} }
//for verification purposes //for verification purposes
int Dictionary::LinearLookupIndex(const void* key, int key_size, zeek::detail::hash_t hash) const int Dictionary::LinearLookupIndex(const void* key, int key_size, detail::hash_t hash) const
{ {
for ( int i = 0; i < Capacity(); i++ ) for ( int i = 0; i < Capacity(); i++ )
if ( ! table[i].Empty() && table[i].Equal((const char*)key, key_size, hash) ) if ( ! table[i].Empty() && table[i].Equal((const char*)key, key_size, hash) )
@ -642,7 +642,7 @@ int Dictionary::LinearLookupIndex(const void* key, int key_size, zeek::detail::h
// Lookup position for all possible table_sizes caused by remapping. Remap it immediately // Lookup position for all possible table_sizes caused by remapping. Remap it immediately
// if not in the middle of iteration. // if not in the middle of iteration.
int Dictionary::LookupIndex(const void* key, int key_size, zeek::detail::hash_t hash, int* insert_position, int* insert_distance) int Dictionary::LookupIndex(const void* key, int key_size, detail::hash_t hash, int* insert_position, int* insert_distance)
{ {
ASSERT_VALID(this); ASSERT_VALID(this);
if ( ! table ) if ( ! table )
@ -696,7 +696,7 @@ int Dictionary::LookupIndex(const void* key, int key_size, zeek::detail::hash_t
// position/distance if required. The starting point for the search may not be the bucket // position/distance if required. The starting point for the search may not be the bucket
// for the current table size since this method is also used to search for an item in the // for the current table size since this method is also used to search for an item in the
// previous table size. // previous table size.
int Dictionary::LookupIndex(const void* key, int key_size, zeek::detail::hash_t hash, int bucket, int end, int Dictionary::LookupIndex(const void* key, int key_size, detail::hash_t hash, int bucket, int end,
int* insert_position/*output*/, int* insert_distance/*output*/) int* insert_position/*output*/, int* insert_distance/*output*/)
{ {
ASSERT(bucket>=0 && bucket < Buckets()); ASSERT(bucket>=0 && bucket < Buckets());
@ -719,7 +719,7 @@ int Dictionary::LookupIndex(const void* key, int key_size, zeek::detail::hash_t
// Insert // Insert
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void* Dictionary::Insert(void* key, int key_size, zeek::detail::hash_t hash, void* val, bool copy_key) void* Dictionary::Insert(void* key, int key_size, detail::hash_t hash, void* val, bool copy_key)
{ {
ASSERT_VALID(this); ASSERT_VALID(this);
@ -880,7 +880,7 @@ void Dictionary::SizeUp()
// Remove // Remove
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void* Dictionary::Remove(const void* key, int key_size, zeek::detail::hash_t hash, bool dont_delete) void* Dictionary::Remove(const void* key, int key_size, detail::hash_t hash, bool dont_delete)
{//cookie adjustment: maintain inserts here. maintain next in lower level version. {//cookie adjustment: maintain inserts here. maintain next in lower level version.
ASSERT_VALID(this); ASSERT_VALID(this);
ASSERT(num_iterators == 0 || (cookies && cookies->size() == num_iterators)); //only robust iterators exist. ASSERT(num_iterators == 0 || (cookies && cookies->size() == num_iterators)); //only robust iterators exist.
@ -1050,7 +1050,7 @@ void Dictionary::StopIterationNonConst(IterCookie* cookie) //const
delete cookie; delete cookie;
} }
void* Dictionary::NextEntryNonConst(zeek::detail::HashKey*& h, IterCookie*& c, bool return_hash) //const void* Dictionary::NextEntryNonConst(detail::HashKey*& h, IterCookie*& c, bool return_hash) //const
{ {
// If there are any inserted entries, return them first. // If there are any inserted entries, return them first.
// That keeps the list small and helps avoiding searching // That keeps the list small and helps avoiding searching
@ -1072,7 +1072,7 @@ void* Dictionary::NextEntryNonConst(zeek::detail::HashKey*& h, IterCookie*& c, b
// and removing from the tail is cheaper. // and removing from the tail is cheaper.
detail::DictEntry e = c->inserted->back(); detail::DictEntry e = c->inserted->back();
if ( return_hash ) if ( return_hash )
h = new zeek::detail::HashKey(e.GetKey(), e.key_size, e.hash); h = new detail::HashKey(e.GetKey(), e.key_size, e.hash);
void* v = e.value; void* v = e.value;
c->inserted->pop_back(); c->inserted->pop_back();
return v; return v;
@ -1120,7 +1120,7 @@ void* Dictionary::NextEntryNonConst(zeek::detail::HashKey*& h, IterCookie*& c, b
ASSERT(! table[c->next].Empty()); ASSERT(! table[c->next].Empty());
void* v = table[c->next].value; void* v = table[c->next].value;
if ( return_hash ) if ( return_hash )
h = new zeek::detail::HashKey(table[c->next].GetKey(), table[c->next].key_size, table[c->next].hash); h = new detail::HashKey(table[c->next].GetKey(), table[c->next].key_size, table[c->next].hash);
//prepare for next time. //prepare for next time.
c->next = Next(c->next); c->next = Next(c->next);
@ -1134,7 +1134,7 @@ IterCookie* Dictionary::InitForIteration() const
return dp->InitForIterationNonConst(); return dp->InitForIterationNonConst();
} }
void* Dictionary::NextEntry(zeek::detail::HashKey*& h, IterCookie*& cookie, bool return_hash) const void* Dictionary::NextEntry(detail::HashKey*& h, IterCookie*& cookie, bool return_hash) const
{ {
Dictionary* dp = const_cast<Dictionary*>(this); Dictionary* dp = const_cast<Dictionary*>(this);
return dp->NextEntryNonConst(h, cookie, return_hash); return dp->NextEntryNonConst(h, cookie, return_hash);

View file

@ -74,7 +74,7 @@ public:
char* key; char* key;
}; };
DictEntry(void* arg_key, int key_size = 0, zeek::detail::hash_t hash = 0, void* value = nullptr, DictEntry(void* arg_key, int key_size = 0, hash_t hash = 0, void* value = nullptr,
int16_t d = TOO_FAR_TO_REACH, bool copy_key = false) int16_t d = TOO_FAR_TO_REACH, bool copy_key = false)
: distance(d), key_size(key_size), hash((uint32_t)hash), value(value) : distance(d), key_size(key_size), hash((uint32_t)hash), value(value)
{ {
@ -121,7 +121,7 @@ public:
const char* GetKey() const { return key_size <= 8 ? key_here : key; } const char* GetKey() const { return key_size <= 8 ? key_here : key; }
bool Equal(const char* arg_key, int arg_key_size, zeek::detail::hash_t arg_hash) const bool Equal(const char* arg_key, int arg_key_size, hash_t arg_hash) const
{//only 40-bit hash comparison. {//only 40-bit hash comparison.
return ( 0 == ((hash ^ arg_hash) & HASH_MASK) ) return ( 0 == ((hash ^ arg_hash) & HASH_MASK) )
&& key_size == arg_key_size && 0 == memcmp(GetKey(), arg_key, key_size); && key_size == arg_key_size && 0 == memcmp(GetKey(), arg_key, key_size);
@ -160,24 +160,24 @@ public:
// which takes a zeek::detail::HashKey, and the other which takes a raw key, // which takes a zeek::detail::HashKey, and the other which takes a raw key,
// its size, and its (unmodulated) hash. // its size, and its (unmodulated) hash.
//lookup may move the key to right place if in the old zone to speed up the next lookup. //lookup may move the key to right place if in the old zone to speed up the next lookup.
void* Lookup(const zeek::detail::HashKey* key) const; void* Lookup(const detail::HashKey* key) const;
void* Lookup(const void* key, int key_size, zeek::detail::hash_t h) const; void* Lookup(const void* key, int key_size, detail::hash_t h) const;
// Returns previous value, or 0 if none. // Returns previous value, or 0 if none.
void* Insert(zeek::detail::HashKey* key, void* val) void* Insert(detail::HashKey* key, void* val)
{ return Insert(key->TakeKey(), key->Size(), key->Hash(), val, false); } { return Insert(key->TakeKey(), key->Size(), key->Hash(), val, false); }
// If copy_key is true, then the key is copied, otherwise it's assumed // If copy_key is true, then the key is copied, otherwise it's assumed
// that it's a heap pointer that now belongs to the Dictionary to // that it's a heap pointer that now belongs to the Dictionary to
// manage as needed. // manage as needed.
void* Insert(void* key, int key_size, zeek::detail::hash_t hash, void* val, bool copy_key); void* Insert(void* key, int key_size, detail::hash_t hash, void* val, bool copy_key);
// Removes the given element. Returns a pointer to the element in // Removes the given element. Returns a pointer to the element in
// case it needs to be deleted. Returns 0 if no such element exists. // case it needs to be deleted. Returns 0 if no such element exists.
// If dontdelete is true, the key's bytes will not be deleted. // If dontdelete is true, the key's bytes will not be deleted.
void* Remove(const zeek::detail::HashKey* key) void* Remove(const detail::HashKey* key)
{ return Remove(key->Key(), key->Size(), key->Hash()); } { return Remove(key->Key(), key->Size(), key->Hash()); }
void* Remove(const void* key, int key_size, zeek::detail::hash_t hash, bool dont_delete = false); void* Remove(const void* key, int key_size, detail::hash_t hash, bool dont_delete = false);
// Number of entries. // Number of entries.
int Length() const int Length() const
@ -222,7 +222,7 @@ public:
// If return_hash is true, a HashKey for the entry is returned in h, // If return_hash is true, a HashKey for the entry is returned in h,
// which should be delete'd when no longer needed. // which should be delete'd when no longer needed.
IterCookie* InitForIteration() const; IterCookie* InitForIteration() const;
void* NextEntry(zeek::detail::HashKey*& h, IterCookie*& cookie, bool return_hash) const; void* NextEntry(detail::HashKey*& h, IterCookie*& cookie, bool return_hash) const;
void StopIteration(IterCookie* cookie) const; void StopIteration(IterCookie* cookie) const;
void SetDeleteFunc(dict_delete_func f) { delete_func = f; } void SetDeleteFunc(dict_delete_func f) { delete_func = f; }
@ -262,10 +262,10 @@ private:
int ThresholdEntries() const; int ThresholdEntries() const;
// Used to improve the distribution of the original hash. // Used to improve the distribution of the original hash.
zeek::detail::hash_t FibHash(zeek::detail::hash_t h) const; detail::hash_t FibHash(detail::hash_t h) const;
// Maps a hash to the appropriate n-bit table bucket. // Maps a hash to the appropriate n-bit table bucket.
int BucketByHash(zeek::detail::hash_t h, int bit) const; int BucketByHash(detail::hash_t h, int bit) const;
// Given a position of a non-empty item in the table, find the related bucket. // Given a position of a non-empty item in the table, find the related bucket.
int BucketByPosition(int position) const; int BucketByPosition(int position) const;
@ -297,14 +297,14 @@ private:
//Iteration //Iteration
IterCookie* InitForIterationNonConst(); IterCookie* InitForIterationNonConst();
void* NextEntryNonConst(zeek::detail::HashKey*& h, IterCookie*& cookie, bool return_hash); void* NextEntryNonConst(detail::HashKey*& h, IterCookie*& cookie, bool return_hash);
void StopIterationNonConst(IterCookie* cookie); void StopIterationNonConst(IterCookie* cookie);
//Lookup //Lookup
int LinearLookupIndex(const void* key, int key_size, zeek::detail::hash_t hash) const; int LinearLookupIndex(const void* key, int key_size, detail::hash_t hash) const;
int LookupIndex(const void* key, int key_size, zeek::detail::hash_t hash, int* insert_position = nullptr, int LookupIndex(const void* key, int key_size, detail::hash_t hash, int* insert_position = nullptr,
int* insert_distance = nullptr); int* insert_distance = nullptr);
int LookupIndex(const void* key, int key_size, zeek::detail::hash_t hash, int begin, int end, int LookupIndex(const void* key, int key_size, detail::hash_t hash, int begin, int end,
int* insert_position = nullptr, int* insert_distance = nullptr); int* insert_position = nullptr, int* insert_distance = nullptr);
/// Insert entry, Adjust cookies when necessary. /// Insert entry, Adjust cookies when necessary.
@ -375,17 +375,17 @@ public:
Dictionary(ordering, initial_size) {} Dictionary(ordering, initial_size) {}
T* Lookup(const char* key) const T* Lookup(const char* key) const
{ {
zeek::detail::HashKey h(key); detail::HashKey h(key);
return (T*) Dictionary::Lookup(&h); return (T*) Dictionary::Lookup(&h);
} }
T* Lookup(const zeek::detail::HashKey* key) const T* Lookup(const detail::HashKey* key) const
{ return (T*) Dictionary::Lookup(key); } { return (T*) Dictionary::Lookup(key); }
T* Insert(const char* key, T* val) T* Insert(const char* key, T* val)
{ {
zeek::detail::HashKey h(key); detail::HashKey h(key);
return (T*) Dictionary::Insert(&h, (void*) val); return (T*) Dictionary::Insert(&h, (void*) val);
} }
T* Insert(zeek::detail::HashKey* key, T* val) T* Insert(detail::HashKey* key, T* val)
{ return (T*) Dictionary::Insert(key, (void*) val); } { return (T*) Dictionary::Insert(key, (void*) val); }
T* NthEntry(int n) const T* NthEntry(int n) const
{ return (T*) Dictionary::NthEntry(n); } { return (T*) Dictionary::NthEntry(n); }
@ -396,14 +396,14 @@ public:
} }
T* NextEntry(IterCookie*& cookie) const T* NextEntry(IterCookie*& cookie) const
{ {
zeek::detail::HashKey* h; detail::HashKey* h;
return (T*) Dictionary::NextEntry(h, cookie, false); return (T*) Dictionary::NextEntry(h, cookie, false);
} }
T* NextEntry(zeek::detail::HashKey*& h, IterCookie*& cookie) const T* NextEntry(detail::HashKey*& h, IterCookie*& cookie) const
{ return (T*) Dictionary::NextEntry(h, cookie, true); } { return (T*) Dictionary::NextEntry(h, cookie, true); }
T* RemoveEntry(const zeek::detail::HashKey* key) T* RemoveEntry(const detail::HashKey* key)
{ return (T*) Remove(key->Key(), key->Size(), key->Hash()); } { return (T*) Remove(key->Key(), key->Size(), key->Hash()); }
T* RemoveEntry(const zeek::detail::HashKey& key) T* RemoveEntry(const detail::HashKey& key)
{ return (T*) Remove(key.Key(), key.Size(), key.Hash()); } { return (T*) Remove(key.Key(), key.Size(), key.Hash()); }
}; };

View file

@ -18,12 +18,12 @@ namespace zeek::detail {
Discarder::Discarder() Discarder::Discarder()
{ {
check_ip = zeek::id::find_func("discarder_check_ip"); check_ip = id::find_func("discarder_check_ip");
check_tcp = zeek::id::find_func("discarder_check_tcp"); check_tcp = id::find_func("discarder_check_tcp");
check_udp = zeek::id::find_func("discarder_check_udp"); check_udp = id::find_func("discarder_check_udp");
check_icmp = zeek::id::find_func("discarder_check_icmp"); check_icmp = id::find_func("discarder_check_icmp");
discarder_maxlen = static_cast<int>(zeek::id::find_val("discarder_maxlen")->AsCount()); discarder_maxlen = static_cast<int>(id::find_val("discarder_maxlen")->AsCount());
} }
Discarder::~Discarder() Discarder::~Discarder()
@ -35,7 +35,7 @@ bool Discarder::IsActive()
return check_ip || check_tcp || check_udp || check_icmp; return check_ip || check_tcp || check_udp || check_icmp;
} }
bool Discarder::NextPacket(const zeek::IP_Hdr* ip, int len, int caplen) bool Discarder::NextPacket(const IP_Hdr* ip, int len, int caplen)
{ {
bool discard_packet = false; bool discard_packet = false;
@ -48,7 +48,7 @@ bool Discarder::NextPacket(const zeek::IP_Hdr* ip, int len, int caplen)
discard_packet = check_ip->Invoke(&args)->AsBool(); discard_packet = check_ip->Invoke(&args)->AsBool();
} }
catch ( zeek::InterpreterException& e ) catch ( InterpreterException& e )
{ {
discard_packet = false; discard_packet = false;
} }
@ -95,7 +95,7 @@ bool Discarder::NextPacket(const zeek::IP_Hdr* ip, int len, int caplen)
zeek::Args args{ zeek::Args args{
ip->ToPktHdrVal(), ip->ToPktHdrVal(),
{zeek::AdoptRef{}, BuildData(data, th_len, len, caplen)}, {AdoptRef{}, BuildData(data, th_len, len, caplen)},
}; };
try try
@ -103,7 +103,7 @@ bool Discarder::NextPacket(const zeek::IP_Hdr* ip, int len, int caplen)
discard_packet = check_tcp->Invoke(&args)->AsBool(); discard_packet = check_tcp->Invoke(&args)->AsBool();
} }
catch ( zeek::InterpreterException& e ) catch ( InterpreterException& e )
{ {
discard_packet = false; discard_packet = false;
} }
@ -119,7 +119,7 @@ bool Discarder::NextPacket(const zeek::IP_Hdr* ip, int len, int caplen)
zeek::Args args{ zeek::Args args{
ip->ToPktHdrVal(), ip->ToPktHdrVal(),
{zeek::AdoptRef{}, BuildData(data, uh_len, len, caplen)}, {AdoptRef{}, BuildData(data, uh_len, len, caplen)},
}; };
try try
@ -127,7 +127,7 @@ bool Discarder::NextPacket(const zeek::IP_Hdr* ip, int len, int caplen)
discard_packet = check_udp->Invoke(&args)->AsBool(); discard_packet = check_udp->Invoke(&args)->AsBool();
} }
catch ( zeek::InterpreterException& e ) catch ( InterpreterException& e )
{ {
discard_packet = false; discard_packet = false;
} }
@ -147,7 +147,7 @@ bool Discarder::NextPacket(const zeek::IP_Hdr* ip, int len, int caplen)
discard_packet = check_icmp->Invoke(&args)->AsBool(); discard_packet = check_icmp->Invoke(&args)->AsBool();
} }
catch ( zeek::InterpreterException& e ) catch ( InterpreterException& e )
{ {
discard_packet = false; discard_packet = false;
} }
@ -157,7 +157,7 @@ bool Discarder::NextPacket(const zeek::IP_Hdr* ip, int len, int caplen)
return discard_packet; return discard_packet;
} }
zeek::Val* Discarder::BuildData(const u_char* data, int hdrlen, int len, int caplen) Val* Discarder::BuildData(const u_char* data, int hdrlen, int len, int caplen)
{ {
len -= hdrlen; len -= hdrlen;
caplen -= hdrlen; caplen -= hdrlen;
@ -165,7 +165,7 @@ zeek::Val* Discarder::BuildData(const u_char* data, int hdrlen, int len, int cap
len = std::max(std::min(std::min(len, caplen), discarder_maxlen), 0); len = std::max(std::min(std::min(len, caplen), discarder_maxlen), 0);
return new zeek::StringVal(new zeek::String(data, len, true)); return new StringVal(new String(data, len, true));
} }
} // namespace zeek::detail } // namespace zeek::detail

View file

@ -11,7 +11,7 @@ ZEEK_FORWARD_DECLARE_NAMESPACED(Func, zeek);
ZEEK_FORWARD_DECLARE_NAMESPACED(Val, zeek); ZEEK_FORWARD_DECLARE_NAMESPACED(Val, zeek);
namespace zeek { namespace zeek {
using FuncPtr = zeek::IntrusivePtr<Func>; using FuncPtr = IntrusivePtr<Func>;
namespace detail { namespace detail {
@ -22,15 +22,15 @@ public:
bool IsActive(); bool IsActive();
bool NextPacket(const zeek::IP_Hdr* ip, int len, int caplen); bool NextPacket(const IP_Hdr* ip, int len, int caplen);
protected: protected:
zeek::Val* BuildData(const u_char* data, int hdrlen, int len, int caplen); Val* BuildData(const u_char* data, int hdrlen, int len, int caplen);
zeek::FuncPtr check_ip; FuncPtr check_ip;
zeek::FuncPtr check_tcp; FuncPtr check_tcp;
zeek::FuncPtr check_udp; FuncPtr check_udp;
zeek::FuncPtr check_icmp; FuncPtr check_icmp;
// Maximum amount of application data passed to filtering functions. // Maximum amount of application data passed to filtering functions.
int discarder_maxlen; int discarder_maxlen;

View file

@ -189,7 +189,7 @@ void EquivClass::Dump(FILE* f)
int EquivClass::Size() const int EquivClass::Size() const
{ {
return padded_sizeof(*this) + zeek::util::pad_size(sizeof(int) * size * (ccl_flags ? 5 : 4)); return padded_sizeof(*this) + util::pad_size(sizeof(int) * size * (ccl_flags ? 5 : 4));
} }
} // namespace zeek::detail } // namespace zeek::detail

View file

@ -18,8 +18,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::detail::SourceID arg_src, zeek::analyzer::ID arg_aid, util::detail::SourceID arg_src, analyzer::ID arg_aid,
Obj* arg_obj) Obj* arg_obj)
: handler(arg_handler), : handler(arg_handler),
args(std::move(arg_args)), args(std::move(arg_args)),
@ -49,18 +49,18 @@ void Event::Describe(ODesc* d) const
void Event::Dispatch(bool no_remote) void Event::Dispatch(bool no_remote)
{ {
if ( src == zeek::util::detail::SOURCE_BROKER ) if ( src == util::detail::SOURCE_BROKER )
no_remote = true; no_remote = true;
if ( handler->ErrorHandler() ) if ( handler->ErrorHandler() )
zeek::reporter->BeginErrorHandler(); reporter->BeginErrorHandler();
try try
{ {
handler->Call(&args, no_remote); handler->Call(&args, no_remote);
} }
catch ( zeek::InterpreterException& e ) catch ( InterpreterException& e )
{ {
// Already reported. // Already reported.
} }
@ -70,13 +70,13 @@ void Event::Dispatch(bool no_remote)
Unref(obj); Unref(obj);
if ( handler->ErrorHandler() ) if ( handler->ErrorHandler() )
zeek::reporter->EndErrorHandler(); reporter->EndErrorHandler();
} }
EventMgr::EventMgr() EventMgr::EventMgr()
{ {
head = tail = nullptr; head = tail = nullptr;
current_src = zeek::util::detail::SOURCE_LOCAL; current_src = util::detail::SOURCE_LOCAL;
current_aid = 0; current_aid = 0;
src_val = nullptr; src_val = nullptr;
draining = false; draining = false;
@ -95,36 +95,36 @@ EventMgr::~EventMgr()
} }
void EventMgr::QueueEventFast(const EventHandlerPtr &h, ValPList vl, void EventMgr::QueueEventFast(const EventHandlerPtr &h, ValPList vl,
zeek::util::detail::SourceID src, analyzer::ID aid, zeek::detail::TimerMgr* mgr, util::detail::SourceID src, analyzer::ID aid, detail::TimerMgr* mgr,
Obj* obj) Obj* obj)
{ {
QueueEvent(new Event(h, zeek::val_list_to_args(vl), src, aid, obj)); QueueEvent(new Event(h, val_list_to_args(vl), src, aid, obj));
} }
void EventMgr::QueueEvent(const EventHandlerPtr &h, ValPList vl, void EventMgr::QueueEvent(const EventHandlerPtr &h, ValPList vl,
zeek::util::detail::SourceID src, analyzer::ID aid, util::detail::SourceID src, analyzer::ID aid,
zeek::detail::TimerMgr* mgr, Obj* obj) detail::TimerMgr* mgr, Obj* obj)
{ {
auto args = zeek::val_list_to_args(vl); auto args = val_list_to_args(vl);
if ( h ) if ( h )
Enqueue(h, std::move(args), src, aid, obj); Enqueue(h, std::move(args), src, aid, obj);
} }
void EventMgr::QueueEvent(const EventHandlerPtr &h, ValPList* vl, void EventMgr::QueueEvent(const EventHandlerPtr &h, ValPList* vl,
zeek::util::detail::SourceID src, analyzer::ID aid, util::detail::SourceID src, analyzer::ID aid,
zeek::detail::TimerMgr* mgr, Obj* obj) detail::TimerMgr* mgr, Obj* obj)
{ {
auto args = zeek::val_list_to_args(*vl); auto args = val_list_to_args(*vl);
delete vl; delete vl;
if ( h ) if ( h )
Enqueue(h, std::move(args), src, aid, obj); Enqueue(h, std::move(args), src, aid, obj);
} }
void EventMgr::Enqueue(const EventHandlerPtr& h, zeek::Args vl, void EventMgr::Enqueue(const EventHandlerPtr& h, Args vl,
zeek::util::detail::SourceID src, util::detail::SourceID src,
zeek::analyzer::ID aid, Obj* obj) 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));
} }
@ -160,9 +160,9 @@ void EventMgr::Dispatch(Event* event, bool no_remote)
void EventMgr::Drain() void EventMgr::Drain()
{ {
if ( event_queue_flush_point ) if ( event_queue_flush_point )
Enqueue(event_queue_flush_point, zeek::Args{}); Enqueue(event_queue_flush_point, Args{});
zeek::detail::SegmentProfiler prof(zeek::detail::segment_logger, "draining-events"); detail::SegmentProfiler prof(detail::segment_logger, "draining-events");
PLUGIN_HOOK_VOID(HOOK_DRAIN_EVENTS, HookDrainEvents()); PLUGIN_HOOK_VOID(HOOK_DRAIN_EVENTS, HookDrainEvents());
@ -201,7 +201,7 @@ void EventMgr::Drain()
// Make sure all of the triggers get processed every time the events // Make sure all of the triggers get processed every time the events
// drain. // drain.
zeek::detail::trigger_mgr->Process(); detail::trigger_mgr->Process();
} }
void EventMgr::Describe(ODesc* d) const void EventMgr::Describe(ODesc* d) const
@ -225,9 +225,9 @@ void EventMgr::Process()
// If we don't have a source, or the source is closed, or we're // If we don't have a source, or the source is closed, or we're
// reading live (which includes pseudo-realtime), advance the time // reading live (which includes pseudo-realtime), advance the time
// 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(); iosource::PktSrc* pkt_src = iosource_mgr->GetPktSrc();
if ( ! pkt_src || ! pkt_src->IsOpen() || zeek::run_state::reading_live ) if ( ! pkt_src || ! pkt_src->IsOpen() || run_state::reading_live )
zeek::run_state::detail::update_network_time(zeek::util::current_time()); run_state::detail::update_network_time(util::current_time());
queue_flare.Extinguish(); queue_flare.Extinguish();
@ -242,9 +242,9 @@ void EventMgr::Process()
void EventMgr::InitPostScript() void EventMgr::InitPostScript()
{ {
zeek::iosource_mgr->Register(this, true, false); iosource_mgr->Register(this, true, false);
if ( ! zeek::iosource_mgr->RegisterFd(queue_flare.FD(), this) ) if ( ! iosource_mgr->RegisterFd(queue_flare.FD(), this) )
zeek::reporter->FatalError("Failed to register event manager FD with zeek::iosource_mgr"); reporter->FatalError("Failed to register event manager FD with iosource_mgr");
} }
} // namespace zeek } // namespace zeek

View file

@ -16,17 +16,17 @@ ZEEK_FORWARD_DECLARE_NAMESPACED(EventMgr, zeek);
namespace zeek { namespace zeek {
class Event final : public zeek::Obj { class Event final : public Obj {
public: public:
Event(EventHandlerPtr handler, zeek::Args args, Event(EventHandlerPtr handler, zeek::Args args,
zeek::util::detail::SourceID src = zeek::util::detail::SOURCE_LOCAL, zeek::analyzer::ID aid = 0, util::detail::SourceID src = util::detail::SOURCE_LOCAL, analyzer::ID aid = 0,
zeek::Obj* obj = nullptr); 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::detail::SourceID Source() const { return src; } util::detail::SourceID Source() const { return src; }
zeek::analyzer::ID Analyzer() const { return aid; } 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,13 +41,13 @@ protected:
EventHandlerPtr handler; EventHandlerPtr handler;
zeek::Args args; zeek::Args args;
zeek::util::detail::SourceID src; util::detail::SourceID src;
zeek::analyzer::ID aid; analyzer::ID aid;
zeek::Obj* obj; Obj* obj;
Event* next_event; Event* next_event;
}; };
class EventMgr final : public zeek::Obj, public iosource::IOSource { class EventMgr final : public Obj, public iosource::IOSource {
public: public:
EventMgr(); EventMgr();
~EventMgr() override; ~EventMgr() override;
@ -62,8 +62,8 @@ 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, ValPList vl, void QueueEventFast(const EventHandlerPtr &h, ValPList vl,
zeek::util::detail::SourceID src = zeek::util::detail::SOURCE_LOCAL, zeek::analyzer::ID aid = 0, util::detail::SourceID src = util::detail::SOURCE_LOCAL, analyzer::ID aid = 0,
zeek::detail::TimerMgr* mgr = nullptr, zeek::Obj* obj = nullptr); detail::TimerMgr* mgr = nullptr, 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
// function always takes ownership of decrementing the reference count of // function always takes ownership of decrementing the reference count of
@ -73,8 +73,8 @@ 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, ValPList vl, void QueueEvent(const EventHandlerPtr &h, ValPList vl,
zeek::util::detail::SourceID src = zeek::util::detail::SOURCE_LOCAL, zeek::analyzer::ID aid = 0, util::detail::SourceID src = util::detail::SOURCE_LOCAL, analyzer::ID aid = 0,
zeek::detail::TimerMgr* mgr = nullptr, zeek::Obj* obj = nullptr); detail::TimerMgr* mgr = nullptr, 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
// pointer instead of by value. This function takes ownership of the // pointer instead of by value. This function takes ownership of the
@ -82,8 +82,8 @@ 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, ValPList* vl, void QueueEvent(const EventHandlerPtr &h, ValPList* vl,
zeek::util::detail::SourceID src = zeek::util::detail::SOURCE_LOCAL, zeek::analyzer::ID aid = 0, util::detail::SourceID src = util::detail::SOURCE_LOCAL, analyzer::ID aid = 0,
zeek::detail::TimerMgr* mgr = nullptr, zeek::Obj* obj = nullptr); detail::TimerMgr* mgr = nullptr, Obj* obj = nullptr);
/** /**
* Adds an event to the queue. If no handler is found for the event * Adds an event to the queue. If no handler is found for the event
@ -98,8 +98,8 @@ 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::detail::SourceID src = zeek::util::detail::SOURCE_LOCAL, zeek::analyzer::ID aid = 0, util::detail::SourceID src = util::detail::SOURCE_LOCAL, analyzer::ID aid = 0,
zeek::Obj* obj = nullptr); Obj* obj = nullptr);
/** /**
* A version of Enqueue() taking a variable number of arguments. * A version of Enqueue() taking a variable number of arguments.
@ -107,7 +107,7 @@ public:
template <class... Args> template <class... Args>
std::enable_if_t< std::enable_if_t<
std::is_convertible_v< std::is_convertible_v<
std::tuple_element_t<0, std::tuple<Args...>>, zeek::ValPtr>> std::tuple_element_t<0, std::tuple<Args...>>, ValPtr>>
Enqueue(const EventHandlerPtr& h, Args&&... args) Enqueue(const EventHandlerPtr& h, Args&&... args)
{ return Enqueue(h, zeek::Args{std::forward<Args>(args)...}); } { return Enqueue(h, zeek::Args{std::forward<Args>(args)...}); }
@ -119,11 +119,11 @@ 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::detail::SourceID CurrentSource() const { return current_src; } 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.
zeek::analyzer::ID CurrentAnalyzer() const { return current_aid; } analyzer::ID CurrentAnalyzer() const { return current_aid; }
int Size() const int Size() const
{ return num_events_queued - num_events_dispatched; } { return num_events_queued - num_events_dispatched; }
@ -143,11 +143,11 @@ protected:
Event* head; Event* head;
Event* tail; Event* tail;
zeek::util::detail::SourceID current_src; util::detail::SourceID current_src;
zeek::analyzer::ID current_aid; analyzer::ID current_aid;
zeek::RecordVal* src_val; RecordVal* src_val;
bool draining; bool draining;
zeek::detail::Flare queue_flare; detail::Flare queue_flare;
}; };
extern EventMgr event_mgr; extern EventMgr event_mgr;

View file

@ -28,31 +28,31 @@ EventHandler::operator bool() const
|| ! auto_publish.empty()); || ! auto_publish.empty());
} }
const zeek::FuncTypePtr& EventHandler::GetType(bool check_export) const FuncTypePtr& EventHandler::GetType(bool check_export)
{ {
if ( type ) if ( type )
return type; return type;
const auto& id = zeek::detail::lookup_ID(name.data(), zeek::detail::current_module.c_str(), const auto& id = detail::lookup_ID(name.data(), detail::current_module.c_str(),
false, false, check_export); false, false, check_export);
if ( ! id ) if ( ! id )
return zeek::FuncType::nil; return FuncType::nil;
if ( id->GetType()->Tag() != zeek::TYPE_FUNC ) if ( id->GetType()->Tag() != TYPE_FUNC )
return zeek::FuncType::nil; return FuncType::nil;
type = id->GetType<zeek::FuncType>(); type = id->GetType<FuncType>();
return type; return type;
} }
void EventHandler::SetFunc(zeek::FuncPtr f) void EventHandler::SetFunc(FuncPtr f)
{ local = std::move(f); } { local = std::move(f); }
void EventHandler::SetLocalHandler(zeek::Func* f) void EventHandler::SetLocalHandler(Func* f)
{ SetFunc({zeek::NewRef{}, f}); } { SetFunc({NewRef{}, f}); }
void EventHandler::Call(zeek::Args* vl, bool no_remote) void EventHandler::Call(Args* vl, bool no_remote)
{ {
#ifdef PROFILE_BRO_FUNCTIONS #ifdef PROFILE_BRO_FUNCTIONS
DEBUG_MSG("Event: %s\n", Name()); DEBUG_MSG("Event: %s\n", Name());
@ -72,7 +72,7 @@ void EventHandler::Call(zeek::Args* vl, bool no_remote)
for ( auto i = 0u; i < vl->size(); ++i ) for ( auto i = 0u; i < vl->size(); ++i )
{ {
auto opt_data = zeek::Broker::detail::val_to_data((*vl)[i].get()); auto opt_data = Broker::detail::val_to_data((*vl)[i].get());
if ( opt_data ) if ( opt_data )
xs.emplace_back(std::move(*opt_data)); xs.emplace_back(std::move(*opt_data));
@ -80,7 +80,7 @@ void EventHandler::Call(zeek::Args* vl, bool no_remote)
{ {
valid_args = false; valid_args = false;
auto_publish.clear(); auto_publish.clear();
zeek::reporter->Error("failed auto-remote event '%s', disabled", Name()); reporter->Error("failed auto-remote event '%s', disabled", Name());
break; break;
} }
} }
@ -109,7 +109,7 @@ void EventHandler::Call(zeek::Args* vl, bool no_remote)
local->Invoke(vl); local->Invoke(vl);
} }
void EventHandler::NewEvent(zeek::Args* vl) void EventHandler::NewEvent(Args* vl)
{ {
if ( ! new_event ) if ( ! new_event )
return; return;
@ -118,13 +118,13 @@ void EventHandler::NewEvent(zeek::Args* vl)
// new_event() is the one event we don't want to report. // new_event() is the one event we don't want to report.
return; return;
auto vargs = zeek::MakeCallArgumentVector(*vl, GetType()->Params()); auto vargs = MakeCallArgumentVector(*vl, GetType()->Params());
auto ev = new zeek::Event(new_event, { auto ev = new Event(new_event, {
zeek::make_intrusive<zeek::StringVal>(name), make_intrusive<StringVal>(name),
std::move(vargs), std::move(vargs),
}); });
zeek::event_mgr.Dispatch(ev); event_mgr.Dispatch(ev);
} }
} // namespace zeek } // namespace zeek

View file

@ -12,7 +12,7 @@
ZEEK_FORWARD_DECLARE_NAMESPACED(Func, zeek); ZEEK_FORWARD_DECLARE_NAMESPACED(Func, zeek);
namespace zeek { namespace zeek {
using FuncPtr = zeek::IntrusivePtr<zeek::Func>; using FuncPtr = IntrusivePtr<Func>;
class EventHandler { class EventHandler {
public: public:
@ -20,22 +20,22 @@ public:
const char* Name() { return name.data(); } const char* Name() { return name.data(); }
const zeek::FuncPtr& GetFunc() const FuncPtr& GetFunc()
{ return local; } { return local; }
[[deprecated("Remove in v4.1. Use GetFunc().")]] [[deprecated("Remove in v4.1. Use GetFunc().")]]
zeek::Func* LocalHandler() { return local.get(); } Func* LocalHandler() { return local.get(); }
const zeek::FuncTypePtr& GetType(bool check_export = true); const FuncTypePtr& GetType(bool check_export = true);
[[deprecated("Remove in v4.1. Use GetType().")]] [[deprecated("Remove in v4.1. Use GetType().")]]
zeek::FuncType* FType(bool check_export = true) FuncType* FType(bool check_export = true)
{ return GetType().get(); } { return GetType().get(); }
void SetFunc(zeek::FuncPtr f); void SetFunc(FuncPtr f);
[[deprecated("Remove in v4.1. Use SetFunc().")]] [[deprecated("Remove in v4.1. Use SetFunc().")]]
void SetLocalHandler(zeek::Func* f); void SetLocalHandler(Func* f);
void AutoPublish(std::string topic) void AutoPublish(std::string topic)
{ {
@ -71,8 +71,8 @@ private:
void NewEvent(zeek::Args* vl); // Raise new_event() meta event. void NewEvent(zeek::Args* vl); // Raise new_event() meta event.
std::string name; std::string name;
zeek::FuncPtr local; FuncPtr local;
zeek::FuncTypePtr type; FuncTypePtr type;
bool used; // this handler is indeed used somewhere bool used; // this handler is indeed used somewhere
bool enabled; bool enabled;
bool error_handler; // this handler reports error messages. bool error_handler; // this handler reports error messages.

View file

@ -9,11 +9,11 @@ namespace zeek {
EventRegistry::EventRegistry() = default; EventRegistry::EventRegistry() = default;
EventRegistry::~EventRegistry() noexcept = default; EventRegistry::~EventRegistry() noexcept = default;
zeek::EventHandlerPtr EventRegistry::Register(std::string_view name) EventHandlerPtr EventRegistry::Register(std::string_view name)
{ {
// If there already is an entry in the registry, we have a // If there already is an entry in the registry, we have a
// local handler on the script layer. // local handler on the script layer.
zeek::EventHandler* h = event_registry->Lookup(name); EventHandler* h = event_registry->Lookup(name);
if ( h ) if ( h )
{ {
@ -21,7 +21,7 @@ zeek::EventHandlerPtr EventRegistry::Register(std::string_view name)
return h; return h;
} }
h = new zeek::EventHandler(std::string(name)); h = new EventHandler(std::string(name));
event_registry->Register(h); event_registry->Register(h);
h->SetUsed(); h->SetUsed();
@ -29,12 +29,12 @@ zeek::EventHandlerPtr EventRegistry::Register(std::string_view name)
return h; return h;
} }
void EventRegistry::Register(zeek::EventHandlerPtr handler) void EventRegistry::Register(EventHandlerPtr handler)
{ {
handlers[std::string(handler->Name())] = std::unique_ptr<zeek::EventHandler>(handler.Ptr()); handlers[std::string(handler->Name())] = std::unique_ptr<EventHandler>(handler.Ptr());
} }
zeek::EventHandler* EventRegistry::Lookup(std::string_view name) EventHandler* EventRegistry::Lookup(std::string_view name)
{ {
auto it = handlers.find(name); auto it = handlers.find(name);
if ( it != handlers.end() ) if ( it != handlers.end() )
@ -43,13 +43,13 @@ zeek::EventHandler* EventRegistry::Lookup(std::string_view name)
return nullptr; return nullptr;
} }
EventRegistry::string_list EventRegistry::Match(zeek::RE_Matcher* pattern) EventRegistry::string_list EventRegistry::Match(RE_Matcher* pattern)
{ {
string_list names; string_list names;
for ( const auto& entry : handlers ) for ( const auto& entry : handlers )
{ {
zeek::EventHandler* v = entry.second.get(); EventHandler* v = entry.second.get();
if ( v->GetFunc() && pattern->MatchExactly(v->Name()) ) if ( v->GetFunc() && pattern->MatchExactly(v->Name()) )
names.push_back(entry.first); names.push_back(entry.first);
} }
@ -63,7 +63,7 @@ EventRegistry::string_list EventRegistry::UnusedHandlers()
for ( const auto& entry : handlers ) for ( const auto& entry : handlers )
{ {
zeek::EventHandler* v = entry.second.get(); EventHandler* v = entry.second.get();
if ( v->GetFunc() && ! v->Used() ) if ( v->GetFunc() && ! v->Used() )
names.push_back(entry.first); names.push_back(entry.first);
} }
@ -77,7 +77,7 @@ EventRegistry::string_list EventRegistry::UsedHandlers()
for ( const auto& entry : handlers ) for ( const auto& entry : handlers )
{ {
zeek::EventHandler* v = entry.second.get(); EventHandler* v = entry.second.get();
if ( v->GetFunc() && v->Used() ) if ( v->GetFunc() && v->Used() )
names.push_back(entry.first); names.push_back(entry.first);
} }
@ -101,7 +101,7 @@ void EventRegistry::PrintDebug()
{ {
for ( const auto& entry : handlers ) for ( const auto& entry : handlers )
{ {
zeek::EventHandler* v = entry.second.get(); EventHandler* v = entry.second.get();
fprintf(stderr, "Registered event %s (%s handler / %s)\n", v->Name(), fprintf(stderr, "Registered event %s (%s handler / %s)\n", v->Name(),
v->GetFunc() ? "local" : "no", v->GetFunc() ? "local" : "no",
*v ? "active" : "not active" *v ? "active" : "not active"
@ -111,7 +111,7 @@ void EventRegistry::PrintDebug()
void EventRegistry::SetErrorHandler(std::string_view name) void EventRegistry::SetErrorHandler(std::string_view name)
{ {
zeek::EventHandler* eh = Lookup(name); EventHandler* eh = Lookup(name);
if ( eh ) if ( eh )
{ {
@ -119,8 +119,8 @@ void EventRegistry::SetErrorHandler(std::string_view name)
return; return;
} }
zeek::reporter->InternalWarning("unknown event handler '%s' in SetErrorHandler()", reporter->InternalWarning("unknown event handler '%s' in SetErrorHandler()",
std::string(name).c_str()); std::string(name).c_str());
} }
} // namespace zeek } // namespace zeek

View file

@ -28,17 +28,17 @@ public:
* @param name The name of the event handler to lookup/register. * @param name The name of the event handler to lookup/register.
* @return The event handler. * @return The event handler.
*/ */
zeek::EventHandlerPtr Register(std::string_view name); EventHandlerPtr Register(std::string_view name);
void Register(zeek::EventHandlerPtr handler); void Register(EventHandlerPtr handler);
// Return nil if unknown. // Return nil if unknown.
zeek::EventHandler* Lookup(std::string_view name); EventHandler* Lookup(std::string_view name);
// Returns a list of all local handlers that match the given pattern. // Returns a list of all local handlers that match the given pattern.
// Passes ownership of list. // Passes ownership of list.
using string_list = std::vector<std::string>; using string_list = std::vector<std::string>;
string_list Match(zeek::RE_Matcher* pattern); string_list Match(RE_Matcher* pattern);
// Marks a handler as handling errors. Error handler will not be called // Marks a handler as handling errors. Error handler will not be called
// recursively to avoid infinite loops in case they trigger an error // recursively to avoid infinite loops in case they trigger an error
@ -52,7 +52,7 @@ public:
void PrintDebug(); void PrintDebug();
private: private:
std::map<std::string, std::unique_ptr<zeek::EventHandler>, std::less<>> handlers; std::map<std::string, std::unique_ptr<EventHandler>, std::less<>> handlers;
}; };
extern EventRegistry* event_registry; extern EventRegistry* event_registry;

File diff suppressed because it is too large Load diff

View file

@ -28,7 +28,7 @@ template <class T> class IntrusivePtr;
namespace detail { namespace detail {
using IDPtr = zeek::IntrusivePtr<ID>; using IDPtr = IntrusivePtr<ID>;
enum BroExprTag : int { enum BroExprTag : int {
EXPR_ANY = -1, EXPR_ANY = -1,
@ -80,21 +80,21 @@ class EventExpr;
class Stmt; class Stmt;
class Expr; class Expr;
using ExprPtr = zeek::IntrusivePtr<Expr>; using ExprPtr = IntrusivePtr<Expr>;
using EventExprPtr = zeek::IntrusivePtr<EventExpr>; using EventExprPtr = IntrusivePtr<EventExpr>;
using ListExprPtr = zeek::IntrusivePtr<ListExpr>; using ListExprPtr = IntrusivePtr<ListExpr>;
class Expr : public Obj { class Expr : public Obj {
public: public:
[[deprecated("Remove in v4.1. Use GetType().")]] [[deprecated("Remove in v4.1. Use GetType().")]]
zeek::Type* Type() const { return type.get(); } zeek::Type* Type() const { return type.get(); }
const zeek::TypePtr& GetType() const const TypePtr& GetType() const
{ return type; } { return type; }
template <class T> template <class T>
zeek::IntrusivePtr<T> GetType() const IntrusivePtr<T> GetType() const
{ return zeek::cast_intrusive<T>(type); } { return cast_intrusive<T>(type); }
BroExprTag Tag() const { return tag; } BroExprTag Tag() const { return tag; }
@ -115,7 +115,7 @@ public:
// Returns the type corresponding to this expression interpreted // Returns the type corresponding to this expression interpreted
// as an initialization. Returns nil if the initialization is illegal. // as an initialization. Returns nil if the initialization is illegal.
virtual zeek::TypePtr InitType() const; virtual TypePtr InitType() const;
// Returns true if this expression, interpreted as an initialization, // Returns true if this expression, interpreted as an initialization,
// constitutes a record element, false otherwise. If the TypeDecl* // constitutes a record element, false otherwise. If the TypeDecl*
@ -197,7 +197,7 @@ protected:
// Puts the expression in canonical form. // Puts the expression in canonical form.
virtual void Canonicize(); virtual void Canonicize();
void SetType(zeek::TypePtr t); void SetType(TypePtr t);
// Reports the given error and sets the expression's type to // Reports the given error and sets the expression's type to
// TYPE_ERROR. // TYPE_ERROR.
@ -209,13 +209,13 @@ protected:
[[noreturn]] void RuntimeErrorWithCallStack(const std::string& msg) const; [[noreturn]] void RuntimeErrorWithCallStack(const std::string& msg) const;
BroExprTag tag; BroExprTag tag;
zeek::TypePtr type; TypePtr type;
bool paren; bool paren;
}; };
class NameExpr final : public Expr { class NameExpr final : public Expr {
public: public:
explicit NameExpr(zeek::detail::IDPtr id, bool const_init = false); explicit NameExpr(IDPtr id, bool const_init = false);
ID* Id() const { return id.get(); } ID* Id() const { return id.get(); }
@ -229,7 +229,7 @@ public:
protected: protected:
void ExprDescribe(ODesc* d) const override; void ExprDescribe(ODesc* d) const override;
zeek::detail::IDPtr id; IDPtr id;
bool in_const_init; bool in_const_init;
}; };
@ -499,7 +499,7 @@ public:
ValPtr Eval(Frame* f) const override; ValPtr Eval(Frame* f) const override;
void EvalIntoAggregate(const zeek::Type* t, Val* aggr, Frame* f) const override; void EvalIntoAggregate(const zeek::Type* t, Val* aggr, Frame* f) const override;
zeek::TypePtr InitType() const override; TypePtr InitType() const override;
bool IsRecordElement(TypeDecl* td) const override; bool IsRecordElement(TypeDecl* td) const override;
ValPtr InitVal(const zeek::Type* t, ValPtr aggr) const override; ValPtr InitVal(const zeek::Type* t, ValPtr aggr) const override;
bool IsPure() const override; bool IsPure() const override;
@ -608,7 +608,7 @@ class TableConstructorExpr final : public UnaryExpr {
public: public:
TableConstructorExpr(ListExprPtr constructor_list, TableConstructorExpr(ListExprPtr constructor_list,
std::unique_ptr<std::vector<AttrPtr>> attrs, std::unique_ptr<std::vector<AttrPtr>> attrs,
zeek::TypePtr arg_type = nullptr); TypePtr arg_type = nullptr);
[[deprecated("Remove in v4.1. Use GetAttrs().")]] [[deprecated("Remove in v4.1. Use GetAttrs().")]]
Attributes* Attrs() { return attrs.get(); } Attributes* Attrs() { return attrs.get(); }
@ -630,7 +630,7 @@ class SetConstructorExpr final : public UnaryExpr {
public: public:
SetConstructorExpr(ListExprPtr constructor_list, SetConstructorExpr(ListExprPtr constructor_list,
std::unique_ptr<std::vector<AttrPtr>> attrs, std::unique_ptr<std::vector<AttrPtr>> attrs,
zeek::TypePtr arg_type = nullptr); TypePtr arg_type = nullptr);
[[deprecated("Remove in v4.1. Use GetAttrs().")]] [[deprecated("Remove in v4.1. Use GetAttrs().")]]
Attributes* Attrs() { return attrs.get(); } Attributes* Attrs() { return attrs.get(); }
@ -651,7 +651,7 @@ protected:
class VectorConstructorExpr final : public UnaryExpr { class VectorConstructorExpr final : public UnaryExpr {
public: public:
explicit VectorConstructorExpr(ListExprPtr constructor_list, explicit VectorConstructorExpr(ListExprPtr constructor_list,
zeek::TypePtr arg_type = nullptr); TypePtr arg_type = nullptr);
ValPtr Eval(Frame* f) const override; ValPtr Eval(Frame* f) const override;
@ -678,7 +678,7 @@ protected:
class ArithCoerceExpr final : public UnaryExpr { class ArithCoerceExpr final : public UnaryExpr {
public: public:
ArithCoerceExpr(ExprPtr op, zeek::TypeTag t); ArithCoerceExpr(ExprPtr op, TypeTag t);
protected: protected:
ValPtr FoldSingleVal(Val* v, InternalTypeTag t) const; ValPtr FoldSingleVal(Val* v, InternalTypeTag t) const;
@ -842,7 +842,7 @@ public:
ValPtr Eval(Frame* f) const override; ValPtr Eval(Frame* f) const override;
zeek::TypePtr InitType() const override; TypePtr InitType() const override;
ValPtr InitVal(const zeek::Type* t, ValPtr aggr) const override; ValPtr InitVal(const zeek::Type* t, ValPtr aggr) const override;
ExprPtr MakeLvalue() override; ExprPtr MakeLvalue() override;
void Assign(Frame* f, ValPtr v) override; void Assign(Frame* f, ValPtr v) override;
@ -865,7 +865,7 @@ public:
class CastExpr final : public UnaryExpr { class CastExpr final : public UnaryExpr {
public: public:
CastExpr(ExprPtr op, zeek::TypePtr t); CastExpr(ExprPtr op, TypePtr t);
protected: protected:
ValPtr Eval(Frame* f) const override; ValPtr Eval(Frame* f) const override;
@ -874,14 +874,14 @@ protected:
class IsExpr final : public UnaryExpr { class IsExpr final : public UnaryExpr {
public: public:
IsExpr(ExprPtr op, zeek::TypePtr t); IsExpr(ExprPtr op, TypePtr t);
protected: protected:
ValPtr Fold(Val* v) const override; ValPtr Fold(Val* v) const override;
void ExprDescribe(ODesc* d) const override; void ExprDescribe(ODesc* d) const override;
private: private:
zeek::TypePtr t; TypePtr t;
}; };
inline Val* Expr::ExprVal() const inline Val* Expr::ExprVal() const

View file

@ -40,7 +40,7 @@ static void maximize_num_fds()
{ {
struct rlimit rl; struct rlimit rl;
if ( getrlimit(RLIMIT_NOFILE, &rl) < 0 ) if ( getrlimit(RLIMIT_NOFILE, &rl) < 0 )
zeek::reporter->FatalError("maximize_num_fds(): getrlimit failed"); reporter->FatalError("maximize_num_fds(): getrlimit failed");
if ( rl.rlim_max == RLIM_INFINITY ) if ( rl.rlim_max == RLIM_INFINITY )
{ {
@ -52,7 +52,7 @@ static void maximize_num_fds()
rl.rlim_cur = rl.rlim_max; rl.rlim_cur = rl.rlim_max;
if ( setrlimit(RLIMIT_NOFILE, &rl) < 0 ) if ( setrlimit(RLIMIT_NOFILE, &rl) < 0 )
zeek::reporter->FatalError("maximize_num_fds(): setrlimit failed"); reporter->FatalError("maximize_num_fds(): setrlimit failed");
} }
File::File(FILE* arg_f) File::File(FILE* arg_f)
@ -60,7 +60,7 @@ File::File(FILE* arg_f)
Init(); Init();
f = arg_f; f = arg_f;
name = access = nullptr; name = access = nullptr;
t = zeek::base_type(zeek::TYPE_STRING); t = base_type(TYPE_STRING);
is_open = (f != nullptr); is_open = (f != nullptr);
} }
@ -68,9 +68,9 @@ File::File(FILE* arg_f, const char* arg_name, const char* arg_access)
{ {
Init(); Init();
f = arg_f; f = arg_f;
name = zeek::util::copy_string(arg_name); name = util::copy_string(arg_name);
access = zeek::util::copy_string(arg_access); access = util::copy_string(arg_access);
t = zeek::base_type(zeek::TYPE_STRING); t = base_type(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 = zeek::util::copy_string(arg_name); name = util::copy_string(arg_name);
access = zeek::util::copy_string(arg_access); access = util::copy_string(arg_access);
t = zeek::base_type(zeek::TYPE_STRING); t = base_type(TYPE_STRING);
if ( zeek::util::streq(name, "/dev/stdin") ) if ( util::streq(name, "/dev/stdin") )
f = stdin; f = stdin;
else if ( zeek::util::streq(name, "/dev/stdout") ) else if ( util::streq(name, "/dev/stdout") )
f = stdout; f = stdout;
else if ( zeek::util::streq(name, "/dev/stderr") ) else if ( util::streq(name, "/dev/stderr") )
f = stderr; f = stderr;
if ( f ) if ( f )
@ -94,7 +94,7 @@ File::File(const char* arg_name, const char* arg_access)
else if ( ! Open() ) else if ( ! Open() )
{ {
zeek::reporter->Error("cannot open %s: %s", name, strerror(errno)); reporter->Error("cannot open %s: %s", name, strerror(errno));
is_open = false; is_open = false;
} }
} }
@ -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::run_state::network_time ? zeek::run_state::network_time : zeek::util::current_time(); open_time = run_state::network_time ? run_state::network_time : util::current_time();
if ( ! fds_maximized ) if ( ! fds_maximized )
{ {
@ -191,7 +191,7 @@ FILE* File::Seek(long new_position)
return nullptr; return nullptr;
if ( fseek(f, new_position, SEEK_SET) < 0 ) if ( fseek(f, new_position, SEEK_SET) < 0 )
zeek::reporter->Error("seek failed"); reporter->Error("seek failed");
return f; return f;
} }
@ -202,7 +202,7 @@ void File::SetBuf(bool arg_buffered)
return; return;
if ( setvbuf(f, NULL, arg_buffered ? _IOFBF : _IOLBF, 0) != 0 ) if ( setvbuf(f, NULL, arg_buffered ? _IOFBF : _IOLBF, 0) != 0 )
zeek::reporter->Error("setvbuf failed"); reporter->Error("setvbuf failed");
buffered = arg_buffered; buffered = arg_buffered;
} }
@ -259,7 +259,7 @@ void File::Describe(ODesc* d) const
d->Add("(no type)"); d->Add("(no type)");
} }
void File::SetAttrs(zeek::detail::Attributes* arg_attrs) void File::SetAttrs(detail::Attributes* arg_attrs)
{ {
if ( ! arg_attrs ) if ( ! arg_attrs )
return; return;
@ -267,11 +267,11 @@ void File::SetAttrs(zeek::detail::Attributes* arg_attrs)
attrs = arg_attrs; attrs = arg_attrs;
Ref(attrs); Ref(attrs);
if ( attrs->Find(zeek::detail::ATTR_RAW_OUTPUT) ) if ( attrs->Find(detail::ATTR_RAW_OUTPUT) )
EnableRawOutput(); EnableRawOutput();
} }
zeek::RecordVal* File::Rotate() RecordVal* File::Rotate()
{ {
if ( ! is_open ) if ( ! is_open )
return nullptr; return nullptr;
@ -280,9 +280,9 @@ zeek::RecordVal* File::Rotate()
if ( f == stdin || f == stdout || f == stderr ) if ( f == stdin || f == stdout || f == stderr )
return nullptr; return nullptr;
static auto rotate_info = zeek::id::find_type<zeek::RecordType>("rotate_info"); static auto rotate_info = id::find_type<RecordType>("rotate_info");
auto* info = new zeek::RecordVal(rotate_info); auto* info = new RecordVal(rotate_info);
FILE* newf = zeek::util::detail::rotate_file(name, info); FILE* newf = util::detail::rotate_file(name, info);
if ( ! newf ) if ( ! newf )
{ {
@ -290,7 +290,7 @@ zeek::RecordVal* File::Rotate()
return nullptr; return nullptr;
} }
info->Assign<zeek::TimeVal>(2, open_time); info->Assign<TimeVal>(2, open_time);
Unlink(); Unlink();
@ -330,9 +330,9 @@ void File::RaiseOpenEvent()
if ( ! ::file_opened ) if ( ! ::file_opened )
return; return;
FilePtr bf{zeek::NewRef{}, this}; FilePtr bf{NewRef{}, this};
auto* event = new zeek::Event(::file_opened, {zeek::make_intrusive<zeek::Val>(std::move(bf))}); auto* event = new Event(::file_opened, {make_intrusive<Val>(std::move(bf))});
zeek::event_mgr.Dispatch(event, true); event_mgr.Dispatch(event, true);
} }
double File::Size() double File::Size()
@ -341,7 +341,7 @@ double File::Size()
struct stat s; struct stat s;
if ( fstat(fileno(f), &s) < 0 ) if ( fstat(fileno(f), &s) < 0 )
{ {
zeek::reporter->Error("can't stat fd for %s: %s", name, strerror(errno)); reporter->Error("can't stat fd for %s: %s", name, strerror(errno));
return 0; return 0;
} }
@ -352,9 +352,9 @@ FilePtr File::Get(const char* name)
{ {
for ( const auto &el : open_files ) for ( const auto &el : open_files )
if ( el.first == name ) if ( el.first == name )
return {zeek::NewRef{}, el.second}; return {NewRef{}, el.second};
return zeek::make_intrusive<File>(name, "w"); return make_intrusive<File>(name, "w");
} }
} // namespace zeek } // namespace zeek

View file

@ -22,12 +22,12 @@ ZEEK_FORWARD_DECLARE_NAMESPACED(RecordVal, zeek);
namespace zeek { namespace zeek {
class Type; class Type;
using TypePtr = zeek::IntrusivePtr<zeek::Type>; using TypePtr = IntrusivePtr<Type>;
class File; class File;
using FilePtr = zeek::IntrusivePtr<File>; using FilePtr = IntrusivePtr<File>;
class File final : public zeek::Obj { class File final : public Obj {
public: public:
explicit File(FILE* arg_f); explicit File(FILE* arg_f);
File(FILE* arg_f, const char* filename, const char* access); File(FILE* arg_f, const char* filename, const char* access);
@ -46,9 +46,9 @@ public:
void SetBuf(bool buffered); // false=line buffered, true=fully buffered void SetBuf(bool buffered); // false=line buffered, true=fully buffered
[[deprecated("Remove in v4.1. Use GetType().")]] [[deprecated("Remove in v4.1. Use GetType().")]]
zeek::Type* FType() const { return t.get(); } Type* FType() const { return t.get(); }
const zeek::TypePtr& GetType() const const TypePtr& GetType() const
{ return t; } { return t; }
// Whether the file is open in a general sense; it might // Whether the file is open in a general sense; it might
@ -63,10 +63,10 @@ public:
void Describe(ODesc* d) const override; void Describe(ODesc* d) const override;
// Rotates the logfile. Returns rotate_info. // Rotates the logfile. Returns rotate_info.
zeek::RecordVal* Rotate(); RecordVal* Rotate();
// Set &raw_output attribute. // Set &raw_output attribute.
void SetAttrs(zeek::detail::Attributes* attrs); void SetAttrs(detail::Attributes* attrs);
// Returns the current size of the file, after fresh stat'ing. // Returns the current size of the file, after fresh stat'ing.
double Size(); double Size();
@ -85,7 +85,7 @@ public:
protected: protected:
friend class zeek::detail::PrintStmt; friend class detail::PrintStmt;
File() { Init(); } File() { Init(); }
void Init(); void Init();
@ -109,10 +109,10 @@ protected:
void RaiseOpenEvent(); void RaiseOpenEvent();
FILE* f; FILE* f;
zeek::TypePtr t; TypePtr t;
char* name; char* name;
char* access; char* access;
zeek::detail::Attributes* attrs; detail::Attributes* attrs;
double open_time; double open_time;
bool is_open; // whether the file is open in a general sense bool is_open; // whether the file is open in a general sense
bool buffered; bool buffered;

View file

@ -6,7 +6,7 @@
#include <fcntl.h> #include <fcntl.h>
#include <errno.h> #include <errno.h>
using namespace zeek::detail; namespace zeek::detail {
Flare::Flare() Flare::Flare()
: pipe(FD_CLOEXEC, FD_CLOEXEC, O_NONBLOCK, O_NONBLOCK) : pipe(FD_CLOEXEC, FD_CLOEXEC, O_NONBLOCK, O_NONBLOCK)
@ -19,10 +19,10 @@ Flare::Flare()
abort(); abort();
char buf[256]; char buf[256];
zeek::util::zeek_strerror_r(errno, buf, sizeof(buf)); util::zeek_strerror_r(errno, buf, sizeof(buf));
if ( zeek::reporter ) if ( reporter )
zeek::reporter->FatalErrorWithCore("unexpected pipe %s failure: %s", which, buf); reporter->FatalErrorWithCore("unexpected pipe %s failure: %s", which, buf);
else else
{ {
fprintf(stderr, "unexpected pipe %s failure: %s", which, buf); fprintf(stderr, "unexpected pipe %s failure: %s", which, buf);
@ -88,3 +88,5 @@ int Flare::Extinguish(bool signal_safe)
return rval; return rval;
} }
} // namespace zeek::detail

View file

@ -26,11 +26,11 @@ void FragTimer::Dispatch(double t, bool /* is_expire */)
if ( f ) if ( f )
f->Expire(t); f->Expire(t);
else else
zeek::reporter->InternalWarning("fragment timer dispatched w/o reassembler"); reporter->InternalWarning("fragment timer dispatched w/o reassembler");
} }
FragReassembler::FragReassembler(zeek::NetSessions* arg_s, FragReassembler::FragReassembler(NetSessions* arg_s,
const zeek::IP_Hdr* ip, const u_char* pkt, const IP_Hdr* ip, const u_char* pkt,
const FragReassemblerKey& k, double t) const FragReassemblerKey& k, double t)
: Reassembler(0, REASSEM_FRAG) : Reassembler(0, REASSEM_FRAG)
{ {
@ -59,7 +59,7 @@ FragReassembler::FragReassembler(zeek::NetSessions* arg_s,
if ( frag_timeout != 0.0 ) if ( frag_timeout != 0.0 )
{ {
expire_timer = new FragTimer(this, t + frag_timeout); expire_timer = new FragTimer(this, t + frag_timeout);
zeek::detail::timer_mgr->Add(expire_timer); timer_mgr->Add(expire_timer);
} }
else else
expire_timer = nullptr; expire_timer = nullptr;
@ -74,7 +74,7 @@ FragReassembler::~FragReassembler()
delete reassembled_pkt; delete reassembled_pkt;
} }
void FragReassembler::AddFragment(double t, const zeek::IP_Hdr* ip, const u_char* pkt) void FragReassembler::AddFragment(double t, const IP_Hdr* ip, const u_char* pkt)
{ {
const struct ip* ip4 = ip->IP4_Hdr(); const struct ip* ip4 = ip->IP4_Hdr();
@ -155,7 +155,7 @@ void FragReassembler::AddFragment(double t, const zeek::IP_Hdr* ip, const u_char
pkt += hdr_len; pkt += hdr_len;
len -= hdr_len; len -= hdr_len;
NewBlock(zeek::run_state::network_time, offset, len, pkt); NewBlock(run_state::network_time, offset, len, pkt);
} }
void FragReassembler::Weird(const char* name) const void FragReassembler::Weird(const char* name) const
@ -164,20 +164,20 @@ void FragReassembler::Weird(const char* name) const
if ( version == 4 ) if ( version == 4 )
{ {
zeek::IP_Hdr hdr((const ip*)proto_hdr, false); IP_Hdr hdr((const ip*)proto_hdr, false);
s->Weird(name, &hdr); s->Weird(name, &hdr);
} }
else if ( version == 6 ) else if ( version == 6 )
{ {
zeek::IP_Hdr hdr((const ip6_hdr*)proto_hdr, false, proto_hdr_len); IP_Hdr hdr((const ip6_hdr*)proto_hdr, false, proto_hdr_len);
s->Weird(name, &hdr); s->Weird(name, &hdr);
} }
else else
{ {
zeek::reporter->InternalWarning("Unexpected IP version in FragReassembler"); reporter->InternalWarning("Unexpected IP version in FragReassembler");
zeek::reporter->Weird(name); reporter->Weird(name);
} }
} }
@ -277,9 +277,9 @@ void FragReassembler::BlockInserted(DataBlockMap::const_iterator /* it */)
if ( b.upper > n ) if ( b.upper > n )
{ {
zeek::reporter->InternalWarning("bad fragment reassembly"); reporter->InternalWarning("bad fragment reassembly");
DeleteTimer(); DeleteTimer();
Expire(zeek::run_state::network_time); Expire(run_state::network_time);
delete [] pkt_start; delete [] pkt_start;
return; return;
} }
@ -296,7 +296,7 @@ void FragReassembler::BlockInserted(DataBlockMap::const_iterator /* it */)
{ {
struct ip* reassem4 = (struct ip*) pkt_start; struct ip* reassem4 = (struct ip*) pkt_start;
reassem4->ip_len = htons(frag_size + proto_hdr_len); reassem4->ip_len = htons(frag_size + proto_hdr_len);
reassembled_pkt = new zeek::IP_Hdr(reassem4, true); reassembled_pkt = new IP_Hdr(reassem4, true);
DeleteTimer(); DeleteTimer();
} }
@ -304,14 +304,14 @@ void FragReassembler::BlockInserted(DataBlockMap::const_iterator /* it */)
{ {
struct ip6_hdr* reassem6 = (struct ip6_hdr*) pkt_start; struct ip6_hdr* reassem6 = (struct ip6_hdr*) pkt_start;
reassem6->ip6_plen = htons(frag_size + proto_hdr_len - 40); reassem6->ip6_plen = htons(frag_size + proto_hdr_len - 40);
const zeek::IPv6_Hdr_Chain* chain = new zeek::IPv6_Hdr_Chain(reassem6, next_proto, n); const IPv6_Hdr_Chain* chain = new IPv6_Hdr_Chain(reassem6, next_proto, n);
reassembled_pkt = new zeek::IP_Hdr(reassem6, true, n, chain); reassembled_pkt = new IP_Hdr(reassem6, true, n, chain);
DeleteTimer(); DeleteTimer();
} }
else else
{ {
zeek::reporter->InternalWarning("bad IP version in fragment reassembly: %d", reporter->InternalWarning("bad IP version in fragment reassembly: %d",
version); version);
delete [] pkt_start; delete [] pkt_start;
} }
@ -323,7 +323,7 @@ void FragReassembler::Expire(double t)
expire_timer->ClearReassembler(); expire_timer->ClearReassembler();
expire_timer = nullptr; // timer manager will delete it expire_timer = nullptr; // timer manager will delete it
zeek::sessions->Remove(this); sessions->Remove(this);
} }
void FragReassembler::DeleteTimer() void FragReassembler::DeleteTimer()
@ -331,7 +331,7 @@ void FragReassembler::DeleteTimer()
if ( expire_timer ) if ( expire_timer )
{ {
expire_timer->ClearReassembler(); expire_timer->ClearReassembler();
zeek::detail::timer_mgr->Cancel(expire_timer); timer_mgr->Cancel(expire_timer);
expire_timer = nullptr; // timer manager will delete it expire_timer = nullptr; // timer manager will delete it
} }
} }

View file

@ -18,21 +18,21 @@ ZEEK_FORWARD_DECLARE_NAMESPACED(FragTimer, zeek::detail);
namespace zeek::detail { namespace zeek::detail {
using FragReassemblerKey = std::tuple<zeek::IPAddr, zeek::IPAddr, bro_uint_t>; using FragReassemblerKey = std::tuple<IPAddr, IPAddr, bro_uint_t>;
class FragReassembler : public Reassembler { class FragReassembler : public Reassembler {
public: public:
FragReassembler(zeek::NetSessions* s, const zeek::IP_Hdr* ip, const u_char* pkt, FragReassembler(NetSessions* s, const IP_Hdr* ip, const u_char* pkt,
const FragReassemblerKey& k, double t); const FragReassemblerKey& k, double t);
~FragReassembler() override; ~FragReassembler() override;
void AddFragment(double t, const zeek::IP_Hdr* ip, const u_char* pkt); void AddFragment(double t, const IP_Hdr* ip, const u_char* pkt);
void Expire(double t); void Expire(double t);
void DeleteTimer(); void DeleteTimer();
void ClearTimer() { expire_timer = nullptr; } void ClearTimer() { expire_timer = nullptr; }
const zeek::IP_Hdr* ReassembledPkt() { return reassembled_pkt; } const IP_Hdr* ReassembledPkt() { return reassembled_pkt; }
const FragReassemblerKey& Key() const { return key; } const FragReassemblerKey& Key() const { return key; }
protected: protected:
@ -41,8 +41,8 @@ protected:
void Weird(const char* name) const; void Weird(const char* name) const;
u_char* proto_hdr; u_char* proto_hdr;
zeek::IP_Hdr* reassembled_pkt; IP_Hdr* reassembled_pkt;
zeek::NetSessions* s; NetSessions* s;
uint64_t frag_size; // size of fully reassembled fragment uint64_t frag_size; // size of fully reassembled fragment
FragReassemblerKey key; FragReassemblerKey key;
uint16_t next_proto; // first IPv6 fragment header's next proto field uint16_t next_proto; // first IPv6 fragment header's next proto field
@ -51,10 +51,10 @@ protected:
FragTimer* expire_timer; FragTimer* expire_timer;
}; };
class FragTimer final : public zeek::detail::Timer { class FragTimer final : public Timer {
public: public:
FragTimer(FragReassembler* arg_f, double arg_t) FragTimer(FragReassembler* arg_f, double arg_t)
: zeek::detail::Timer(arg_t, zeek::detail::TIMER_FRAG) : Timer(arg_t, TIMER_FRAG)
{ f = arg_f; } { f = arg_f; }
~FragTimer() override; ~FragTimer() override;

View file

@ -55,7 +55,7 @@ Frame::~Frame()
void Frame::AddFunctionWithClosureRef(ScriptFunc* func) void Frame::AddFunctionWithClosureRef(ScriptFunc* func)
{ {
zeek::Ref(func); Ref(func);
if ( ! functions_with_closure_frame_reference ) if ( ! functions_with_closure_frame_reference )
functions_with_closure_frame_reference = std::make_unique<std::vector<ScriptFunc*>>(); functions_with_closure_frame_reference = std::make_unique<std::vector<ScriptFunc*>>();
@ -63,22 +63,22 @@ void Frame::AddFunctionWithClosureRef(ScriptFunc* func)
functions_with_closure_frame_reference->emplace_back(func); functions_with_closure_frame_reference->emplace_back(func);
} }
void Frame::SetElement(int n, zeek::Val* v) void Frame::SetElement(int n, Val* v)
{ SetElement(n, {zeek::AdoptRef{}, v}); } { SetElement(n, {AdoptRef{}, v}); }
void Frame::SetElement(int n, zeek::ValPtr v) void Frame::SetElement(int n, ValPtr v)
{ {
ClearElement(n); ClearElement(n);
frame[n] = {std::move(v), false}; frame[n] = {std::move(v), false};
} }
void Frame::SetElementWeak(int n, zeek::Val* v) void Frame::SetElementWeak(int n, Val* v)
{ {
ClearElement(n); ClearElement(n);
frame[n] = {{zeek::AdoptRef{}, v}, true}; frame[n] = {{AdoptRef{}, v}, true};
} }
void Frame::SetElement(const zeek::detail::ID* id, zeek::ValPtr v) void Frame::SetElement(const ID* id, ValPtr v)
{ {
if ( closure ) if ( closure )
{ {
@ -107,7 +107,7 @@ void Frame::SetElement(const zeek::detail::ID* id, zeek::ValPtr v)
SetElement(id->Offset(), std::move(v)); SetElement(id->Offset(), std::move(v));
} }
const zeek::ValPtr& Frame::GetElementByID(const zeek::detail::ID* id) const const ValPtr& Frame::GetElementByID(const ID* id) const
{ {
if ( closure ) if ( closure )
{ {
@ -188,9 +188,9 @@ Frame* Frame::Clone() const
return other; return other;
} }
static bool val_is_func(const zeek::ValPtr& v, ScriptFunc* func) static bool val_is_func(const ValPtr& v, ScriptFunc* func)
{ {
if ( v->GetType()->Tag() != zeek::TYPE_FUNC ) if ( v->GetType()->Tag() != TYPE_FUNC )
return false; return false;
return v->AsFunc() == func; return v->AsFunc() == func;
@ -245,7 +245,7 @@ Frame* Frame::SelectiveClone(const IDPList& selection, ScriptFunc* func) const
} }
if ( ! frame[id->Offset()].val ) if ( ! frame[id->Offset()].val )
zeek::reporter->InternalError("Attempted to clone an id ('%s') with no associated value.", id->Name()); reporter->InternalError("Attempted to clone an id ('%s') with no associated value.", id->Name());
CloneNonFuncElement(id->Offset(), func, other); CloneNonFuncElement(id->Offset(), func, other);
} }
@ -308,7 +308,7 @@ broker::expected<broker::data> Frame::Serialize(const Frame* target, const IDPLi
if ( them.length() ) if ( them.length() )
{ {
if ( ! target->closure ) if ( ! target->closure )
zeek::reporter->InternalError("Attempting to serialize values from a frame that does not exist."); reporter->InternalError("Attempting to serialize values from a frame that does not exist.");
rval.emplace_back(std::string("ClosureFrame")); rval.emplace_back(std::string("ClosureFrame"));
@ -348,9 +348,9 @@ broker::expected<broker::data> Frame::Serialize(const Frame* target, const IDPLi
const auto& val = target->frame[location].val; const auto& val = target->frame[location].val;
zeek::TypeTag tag = val->GetType()->Tag(); TypeTag tag = val->GetType()->Tag();
auto expected = zeek::Broker::detail::val_to_data(val.get()); auto expected = Broker::detail::val_to_data(val.get());
if ( ! expected ) if ( ! expected )
return broker::ec::invalid_data; return broker::ec::invalid_data;
@ -452,7 +452,7 @@ std::pair<bool, FramePtr> Frame::Unserialize(const broker::vector& data)
int frame_size = body.size(); int frame_size = body.size();
// We'll associate this frame with a function later. // We'll associate this frame with a function later.
auto rf = zeek::make_intrusive<Frame>(frame_size, nullptr, nullptr); auto rf = make_intrusive<Frame>(frame_size, nullptr, nullptr);
rf->offset_map = std::make_unique<OffsetMap>(std::move(offset_map)); rf->offset_map = std::make_unique<OffsetMap>(std::move(offset_map));
// Frame takes ownership of unref'ing elements in outer_ids // Frame takes ownership of unref'ing elements in outer_ids
@ -475,9 +475,9 @@ std::pair<bool, FramePtr> Frame::Unserialize(const broker::vector& data)
return std::make_pair(false, nullptr); return std::make_pair(false, nullptr);
broker::integer g = *has_type; broker::integer g = *has_type;
zeek::Type t( static_cast<zeek::TypeTag>(g) ); Type t( static_cast<TypeTag>(g) );
auto val = zeek::Broker::detail::data_to_val(std::move(val_tuple[0]), &t); auto val = Broker::detail::data_to_val(std::move(val_tuple[0]), &t);
if ( ! val ) if ( ! val )
return std::make_pair(false, nullptr); return std::make_pair(false, nullptr);
@ -493,7 +493,7 @@ void Frame::AddKnownOffsets(const IDPList& ids)
offset_map = std::make_unique<OffsetMap>(); offset_map = std::make_unique<OffsetMap>();
std::transform(ids.begin(), ids.end(), std::inserter(*offset_map, offset_map->end()), std::transform(ids.begin(), ids.end(), std::inserter(*offset_map, offset_map->end()),
[] (const zeek::detail::ID* id) -> std::pair<std::string, int> [] (const ID* id) -> std::pair<std::string, int>
{ {
return std::make_pair(std::string(id->Name()), id->Offset()); return std::make_pair(std::string(id->Name()), id->Offset());
}); });
@ -502,12 +502,12 @@ void Frame::AddKnownOffsets(const IDPList& ids)
void Frame::CaptureClosure(Frame* c, IDPList arg_outer_ids) void Frame::CaptureClosure(Frame* c, IDPList arg_outer_ids)
{ {
if ( closure || outer_ids.length() ) if ( closure || outer_ids.length() )
zeek::reporter->InternalError("Attempted to override a closure."); reporter->InternalError("Attempted to override a closure.");
outer_ids = std::move(arg_outer_ids); outer_ids = std::move(arg_outer_ids);
for ( auto& i : outer_ids ) for ( auto& i : outer_ids )
zeek::Ref(i); Ref(i);
closure = c; closure = c;
if ( closure ) if ( closure )
@ -520,7 +520,7 @@ void Frame::CaptureClosure(Frame* c, IDPList arg_outer_ids)
// if (c) closure = c->SelectiveClone(outer_ids); // if (c) closure = c->SelectiveClone(outer_ids);
} }
void Frame::SetTrigger(zeek::detail::trigger::TriggerPtr arg_trigger) void Frame::SetTrigger(trigger::TriggerPtr arg_trigger)
{ {
trigger = std::move(arg_trigger); trigger = std::move(arg_trigger);
} }
@ -538,10 +538,10 @@ void Frame::ClearElement(int n)
frame[n] = {nullptr, false}; frame[n] = {nullptr, false};
} }
bool Frame::IsOuterID(const zeek::detail::ID* in) const bool Frame::IsOuterID(const ID* in) const
{ {
return std::any_of(outer_ids.begin(), outer_ids.end(), return std::any_of(outer_ids.begin(), outer_ids.end(),
[&in](zeek::detail::ID* id)-> bool { return strcmp(id->Name(), in->Name()) == 0; }); [&in](ID* id)-> bool { return strcmp(id->Name(), in->Name()) == 0; });
} }
broker::expected<broker::data> Frame::SerializeIDList(const IDPList& in) broker::expected<broker::data> Frame::SerializeIDList(const IDPList& in)
@ -603,7 +603,7 @@ Frame::UnserializeIDList(const broker::vector& data)
return std::make_pair(false, std::move(rval)); return std::make_pair(false, std::move(rval));
} }
auto* id = new zeek::detail::ID(has_name->c_str(), zeek::detail::SCOPE_FUNCTION, false); auto* id = new ID(has_name->c_str(), SCOPE_FUNCTION, false);
id->SetOffset(*has_offset); id->SetOffset(*has_offset);
rval.push_back(id); rval.push_back(id);
std::advance(where, 1); std::advance(where, 1);

View file

@ -23,17 +23,17 @@ namespace zeek::detail { class ScriptFunc; }
using BroFunc [[deprecated("Remove in v4.1. Use zeek::detail::ScriptFunc instead.")]] = zeek::detail::ScriptFunc; using BroFunc [[deprecated("Remove in v4.1. Use zeek::detail::ScriptFunc instead.")]] = zeek::detail::ScriptFunc;
namespace zeek { namespace zeek {
using ValPtr = zeek::IntrusivePtr<Val>; using ValPtr = IntrusivePtr<Val>;
namespace detail { namespace detail {
using IDPtr = zeek::IntrusivePtr<ID>; using IDPtr = IntrusivePtr<ID>;
namespace trigger { namespace trigger {
using TriggerPtr = zeek::IntrusivePtr<Trigger>; using TriggerPtr = IntrusivePtr<Trigger>;
} }
class Frame; class Frame;
using FramePtr = zeek::IntrusivePtr<Frame>; using FramePtr = IntrusivePtr<Frame>;
class Frame : public Obj { class Frame : public Obj {
public: public:
@ -57,21 +57,21 @@ public:
* @param n the index to get. * @param n the index to get.
* @return the value at index *n* of the underlying array. * @return the value at index *n* of the underlying array.
*/ */
const zeek::ValPtr& GetElement(int n) const const ValPtr& GetElement(int n) const
{ return frame[n].val; } { return frame[n].val; }
[[deprecated("Remove in v4.1. Use GetElement(int).")]] [[deprecated("Remove in v4.1. Use GetElement(int).")]]
zeek::Val* NthElement(int n) const { return frame[n].val.get(); } Val* NthElement(int n) const { return frame[n].val.get(); }
/** /**
* Sets the element at index *n* of the underlying array to *v*. * Sets the element at index *n* of the underlying array to *v*.
* @param n the index to set * @param n the index to set
* @param v the value to set it to * @param v the value to set it to
*/ */
void SetElement(int n, zeek::ValPtr v); void SetElement(int n, ValPtr v);
[[deprecated("Remove in v4.1. Pass IntrusivePtr instead.")]] [[deprecated("Remove in v4.1. Pass IntrusivePtr instead.")]]
void SetElement(int n, zeek::Val* v); void SetElement(int n, Val* v);
/** /**
* Associates *id* and *v* in the frame. Future lookups of * Associates *id* and *v* in the frame. Future lookups of
@ -80,8 +80,8 @@ public:
* @param id the ID to associate * @param id the ID to associate
* @param v the value to associate it with * @param v the value to associate it with
*/ */
void SetElement(const zeek::detail::ID* id, zeek::ValPtr v); void SetElement(const ID* id, ValPtr v);
void SetElement(const zeek::detail::IDPtr& id, zeek::ValPtr v) void SetElement(const IDPtr& id, ValPtr v)
{ SetElement(id.get(), std::move(v)); } { SetElement(id.get(), std::move(v)); }
/** /**
@ -91,11 +91,11 @@ public:
* @param id the id who's value to retreive * @param id the id who's value to retreive
* @return the value associated with *id* * @return the value associated with *id*
*/ */
const zeek::ValPtr& GetElementByID(const zeek::detail::IDPtr& id) const const ValPtr& GetElementByID(const IDPtr& id) const
{ return GetElementByID(id.get()); } { return GetElementByID(id.get()); }
[[deprecated("Remove in v4.1. Use GetElementByID().")]] [[deprecated("Remove in v4.1. Use GetElementByID().")]]
zeek::Val* GetElement(const zeek::detail::ID* id) const Val* GetElement(const ID* id) const
{ return GetElementByID(id).get(); } { return GetElementByID(id).get(); }
/** /**
@ -119,7 +119,7 @@ public:
* @return the arguments passed to the function that this frame * @return the arguments passed to the function that this frame
* is associated with. * is associated with.
*/ */
const zeek::Args* GetFuncArgs() const { return func_args; } const Args* GetFuncArgs() const { return func_args; }
/** /**
* Change the function that the frame is associated with. * Change the function that the frame is associated with.
@ -133,12 +133,12 @@ public:
* *
* @param stmt the statement to set it to. * @param stmt the statement to set it to.
*/ */
void SetNextStmt(zeek::detail::Stmt* stmt) { next_stmt = stmt; } void SetNextStmt(Stmt* stmt) { next_stmt = stmt; }
/** /**
* @return the next statement to be executed in the context of the frame. * @return the next statement to be executed in the context of the frame.
*/ */
zeek::detail::Stmt* GetNextStmt() const { return next_stmt; } Stmt* GetNextStmt() const { return next_stmt; }
/** Used to implement "next" command in debugger. */ /** Used to implement "next" command in debugger. */
void BreakBeforeNextStmt(bool should_break) void BreakBeforeNextStmt(bool should_break)
@ -230,13 +230,13 @@ public:
// If the frame is run in the context of a trigger condition evaluation, // If the frame is run in the context of a trigger condition evaluation,
// the trigger needs to be registered. // the trigger needs to be registered.
void SetTrigger(zeek::detail::trigger::TriggerPtr arg_trigger); void SetTrigger(trigger::TriggerPtr arg_trigger);
void ClearTrigger(); void ClearTrigger();
zeek::detail::trigger::Trigger* GetTrigger() const { return trigger.get(); } trigger::Trigger* GetTrigger() const { return trigger.get(); }
void SetCall(const zeek::detail::CallExpr* arg_call) { call = arg_call; } void SetCall(const CallExpr* arg_call) { call = arg_call; }
void ClearCall() { call = nullptr; } void ClearCall() { call = nullptr; }
const zeek::detail::CallExpr* GetCall() const { return call; } const CallExpr* GetCall() const { return call; }
void SetDelayed() { delayed = true; } void SetDelayed() { delayed = true; }
bool HasDelayed() const { return delayed; } bool HasDelayed() const { return delayed; }
@ -255,13 +255,13 @@ private:
using OffsetMap = std::unordered_map<std::string, int>; using OffsetMap = std::unordered_map<std::string, int>;
struct Element { struct Element {
zeek::ValPtr val; ValPtr val;
// Weak reference is used to prevent circular reference memory leaks // Weak reference is used to prevent circular reference memory leaks
// in lambdas/closures. // in lambdas/closures.
bool weak_ref; bool weak_ref;
}; };
const zeek::ValPtr& GetElementByID(const zeek::detail::ID* id) const; const ValPtr& GetElementByID(const ID* id) const;
/** /**
* Sets the element at index *n* of the underlying array to *v*, but does * Sets the element at index *n* of the underlying array to *v*, but does
@ -271,7 +271,7 @@ private:
* @param v the value to set it to (caller has not Ref'd and Frame will * @param v the value to set it to (caller has not Ref'd and Frame will
* not Unref it) * not Unref it)
*/ */
void SetElementWeak(int n, zeek::Val* v); void SetElementWeak(int n, Val* v);
/** /**
* Clone an element at an offset into other frame if not equal to a given * Clone an element at an offset into other frame if not equal to a given
@ -287,7 +287,7 @@ private:
void ClearElement(int n); void ClearElement(int n);
/** Have we captured this id? */ /** Have we captured this id? */
bool IsOuterID(const zeek::detail::ID* in) const; bool IsOuterID(const ID* in) const;
/** Serializes an offset_map */ /** Serializes an offset_map */
static broker::expected<broker::data> static broker::expected<broker::data>
@ -334,10 +334,10 @@ private:
const zeek::Args* func_args; const zeek::Args* func_args;
/** The next statement to be evaluted in the context of this frame. */ /** The next statement to be evaluted in the context of this frame. */
zeek::detail::Stmt* next_stmt; Stmt* next_stmt;
zeek::detail::trigger::TriggerPtr trigger; trigger::TriggerPtr trigger;
const zeek::detail::CallExpr* call; const CallExpr* call;
std::unique_ptr<std::vector<ScriptFunc*>> functions_with_closure_frame_reference; std::unique_ptr<std::vector<ScriptFunc*>> functions_with_closure_frame_reference;
}; };

View file

@ -108,12 +108,12 @@ std::string render_call_stack()
arg_desc += d.Description(); arg_desc += d.Description();
} }
rval += zeek::util::fmt("#%d %s(%s)", lvl, name, arg_desc.data()); rval += 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 += zeek::util::fmt(" at %s:%d", loc->filename, loc->first_line); rval += util::fmt(" at %s:%d", loc->filename, loc->first_line);
} }
++lvl; ++lvl;
@ -128,37 +128,37 @@ std::string render_call_stack()
Func::Func() Func::Func()
{ {
unique_id = unique_ids.size(); unique_id = unique_ids.size();
unique_ids.push_back({zeek::NewRef{}, this}); unique_ids.push_back({NewRef{}, this});
} }
Func::Func(Kind arg_kind) : kind(arg_kind) Func::Func(Kind arg_kind) : kind(arg_kind)
{ {
unique_id = unique_ids.size(); unique_id = unique_ids.size();
unique_ids.push_back({zeek::NewRef{}, this}); unique_ids.push_back({NewRef{}, this});
} }
Func::~Func() = default; Func::~Func() = default;
void Func::AddBody(zeek::detail::StmtPtr /* new_body */, void Func::AddBody(detail::StmtPtr /* new_body */,
const std::vector<zeek::detail::IDPtr>& /* new_inits */, const std::vector<detail::IDPtr>& /* new_inits */,
size_t /* new_frame_size */, int /* priority */) size_t /* new_frame_size */, int /* priority */)
{ {
Internal("Func::AddBody called"); Internal("Func::AddBody called");
} }
void Func::SetScope(zeek::detail::ScopePtr newscope) void Func::SetScope(detail::ScopePtr newscope)
{ {
scope = std::move(newscope); scope = std::move(newscope);
} }
zeek::FuncPtr Func::DoClone() FuncPtr Func::DoClone()
{ {
// By default, ok just to return a reference. Func does not have any state // By default, ok just to return a reference. Func does not have any state
// that is different across instances. // that is different across instances.
return {zeek::NewRef{}, this}; return {NewRef{}, this};
} }
void Func::DescribeDebug(ODesc* d, const zeek::Args* args) const void Func::DescribeDebug(ODesc* d, const Args* args) const
{ {
d->Add(Name()); d->Add(Name());
@ -196,7 +196,7 @@ void Func::DescribeDebug(ODesc* d, const zeek::Args* args) const
detail::TraversalCode Func::Traverse(detail::TraversalCallback* cb) const detail::TraversalCode Func::Traverse(detail::TraversalCallback* cb) const
{ {
// FIXME: Make a fake scope for builtins? // FIXME: Make a fake scope for builtins?
zeek::detail::Scope* old_scope = cb->current_scope; detail::Scope* old_scope = cb->current_scope;
cb->current_scope = scope.get(); cb->current_scope = scope.get();
detail::TraversalCode tc = cb->PreFunction(this); detail::TraversalCode tc = cb->PreFunction(this);
@ -233,8 +233,8 @@ void Func::CopyStateInto(Func* other) const
other->unique_id = unique_id; other->unique_id = unique_id;
} }
void Func::CheckPluginResult(bool handled, const zeek::ValPtr& hook_result, void Func::CheckPluginResult(bool handled, const ValPtr& hook_result,
zeek::FunctionFlavor flavor) const FunctionFlavor flavor) const
{ {
// Helper function factoring out this code from ScriptFunc:Call() for // Helper function factoring out this code from ScriptFunc:Call() for
// better readability. // better readability.
@ -242,7 +242,7 @@ void Func::CheckPluginResult(bool handled, const zeek::ValPtr& hook_result,
if ( ! handled ) if ( ! handled )
{ {
if ( hook_result ) if ( hook_result )
zeek::reporter->InternalError("plugin set processed flag to false but actually returned a value"); reporter->InternalError("plugin set processed flag to false but actually returned a value");
// The plugin result hasn't been processed yet (read: fall // The plugin result hasn't been processed yet (read: fall
// into ::Call method). // into ::Call method).
@ -250,34 +250,34 @@ void Func::CheckPluginResult(bool handled, const zeek::ValPtr& hook_result,
} }
switch ( flavor ) { switch ( flavor ) {
case zeek::FUNC_FLAVOR_EVENT: case FUNC_FLAVOR_EVENT:
if ( hook_result ) if ( hook_result )
zeek::reporter->InternalError("plugin returned non-void result for event %s", reporter->InternalError("plugin returned non-void result for event %s",
this->Name()); this->Name());
break; break;
case zeek::FUNC_FLAVOR_HOOK: case FUNC_FLAVOR_HOOK:
if ( hook_result->GetType()->Tag() != zeek::TYPE_BOOL ) if ( hook_result->GetType()->Tag() != TYPE_BOOL )
zeek::reporter->InternalError("plugin returned non-bool for hook %s", reporter->InternalError("plugin returned non-bool for hook %s",
this->Name()); this->Name());
break; break;
case zeek::FUNC_FLAVOR_FUNCTION: case FUNC_FLAVOR_FUNCTION:
{ {
const auto& yt = GetType()->Yield(); const auto& yt = GetType()->Yield();
if ( (! yt) || yt->Tag() == zeek::TYPE_VOID ) if ( (! yt) || yt->Tag() == TYPE_VOID )
{ {
if ( hook_result ) if ( hook_result )
zeek::reporter->InternalError("plugin returned non-void result for void method %s", reporter->InternalError("plugin returned non-void result for void method %s",
this->Name()); this->Name());
} }
else if ( hook_result && hook_result->GetType()->Tag() != yt->Tag() && yt->Tag() != zeek::TYPE_ANY ) else if ( hook_result && hook_result->GetType()->Tag() != yt->Tag() && yt->Tag() != TYPE_ANY )
{ {
zeek::reporter->InternalError("plugin returned wrong type (got %d, expecting %d) for %s", reporter->InternalError("plugin returned wrong type (got %d, expecting %d) for %s",
hook_result->GetType()->Tag(), yt->Tag(), this->Name()); hook_result->GetType()->Tag(), yt->Tag(), this->Name());
} }
@ -286,16 +286,16 @@ void Func::CheckPluginResult(bool handled, const zeek::ValPtr& hook_result,
} }
} }
zeek::Val* Func::Call(ValPList* args, zeek::detail::Frame* parent) const Val* Func::Call(ValPList* args, detail::Frame* parent) const
{ {
auto zargs = zeek::val_list_to_args(*args); auto zargs = val_list_to_args(*args);
return Invoke(&zargs, parent).release(); return Invoke(&zargs, parent).release();
}; };
namespace detail { namespace detail {
ScriptFunc::ScriptFunc(const zeek::detail::IDPtr& arg_id, zeek::detail::StmtPtr arg_body, ScriptFunc::ScriptFunc(const IDPtr& arg_id, StmtPtr arg_body,
const std::vector<zeek::detail::IDPtr>& aggr_inits, const std::vector<IDPtr>& aggr_inits,
size_t arg_frame_size, int priority) size_t arg_frame_size, int priority)
: Func(SCRIPT_FUNC) : Func(SCRIPT_FUNC)
{ {
@ -324,7 +324,7 @@ bool ScriptFunc::IsPure() const
[](const Body& b) { return b.stmts->IsPure(); }); [](const Body& b) { return b.stmts->IsPure(); });
} }
zeek::ValPtr ScriptFunc::Invoke(zeek::Args* args, zeek::detail::Frame* parent) const ValPtr ScriptFunc::Invoke(zeek::Args* args, Frame* parent) const
{ {
#ifdef PROFILE_BRO_FUNCTIONS #ifdef PROFILE_BRO_FUNCTIONS
DEBUG_MSG("Function: %s\n", Name()); DEBUG_MSG("Function: %s\n", Name());
@ -346,11 +346,11 @@ zeek::ValPtr ScriptFunc::Invoke(zeek::Args* args, zeek::detail::Frame* parent) c
if ( bodies.empty() ) if ( bodies.empty() )
{ {
// Can only happen for events and hooks. // Can only happen for events and hooks.
assert(Flavor() == zeek::FUNC_FLAVOR_EVENT || Flavor() == zeek::FUNC_FLAVOR_HOOK); assert(Flavor() == FUNC_FLAVOR_EVENT || Flavor() == FUNC_FLAVOR_HOOK);
return Flavor() == zeek::FUNC_FLAVOR_HOOK ? zeek::val_mgr->True() : nullptr; return Flavor() == FUNC_FLAVOR_HOOK ? val_mgr->True() : nullptr;
} }
auto f = zeek::make_intrusive<zeek::detail::Frame>(frame_size, this, args); auto f = make_intrusive<Frame>(frame_size, this, args);
if ( closure ) if ( closure )
f->CaptureClosure(closure, outer_ids); f->CaptureClosure(closure, outer_ids);
@ -358,12 +358,12 @@ zeek::ValPtr ScriptFunc::Invoke(zeek::Args* args, zeek::detail::Frame* parent) c
// Hand down any trigger. // Hand down any trigger.
if ( parent ) if ( parent )
{ {
f->SetTrigger({zeek::NewRef{}, parent->GetTrigger()}); f->SetTrigger({NewRef{}, parent->GetTrigger()});
f->SetCall(parent->GetCall()); f->SetCall(parent->GetCall());
} }
g_frame_stack.push_back(f.get()); // used for backtracing g_frame_stack.push_back(f.get()); // used for backtracing
const zeek::detail::CallExpr* call_expr = parent ? parent->GetCall() : nullptr; const CallExpr* call_expr = parent ? parent->GetCall() : nullptr;
call_stack.emplace_back(CallInfo{call_expr, this, *args}); call_stack.emplace_back(CallInfo{call_expr, this, *args});
if ( g_trace_state.DoTrace() ) if ( g_trace_state.DoTrace() )
@ -376,7 +376,7 @@ zeek::ValPtr ScriptFunc::Invoke(zeek::Args* args, zeek::detail::Frame* parent) c
} }
StmtFlowType flow = FLOW_NEXT; StmtFlowType flow = FLOW_NEXT;
zeek::ValPtr result; ValPtr result;
for ( const auto& body : bodies ) for ( const auto& body : bodies )
{ {
@ -404,7 +404,7 @@ zeek::ValPtr ScriptFunc::Invoke(zeek::Args* args, zeek::detail::Frame* parent) c
catch ( InterpreterException& e ) catch ( InterpreterException& e )
{ {
// Already reported, but now determine whether to unwind further. // Already reported, but now determine whether to unwind further.
if ( Flavor() == zeek::FUNC_FLAVOR_FUNCTION ) if ( Flavor() == FUNC_FLAVOR_FUNCTION )
{ {
g_frame_stack.pop_back(); g_frame_stack.pop_back();
call_stack.pop_back(); call_stack.pop_back();
@ -424,7 +424,7 @@ zeek::ValPtr ScriptFunc::Invoke(zeek::Args* args, zeek::detail::Frame* parent) c
break; break;
} }
if ( Flavor() == zeek::FUNC_FLAVOR_HOOK ) if ( Flavor() == FUNC_FLAVOR_HOOK )
{ {
// Ignore any return values of hook bodies, final return value // Ignore any return values of hook bodies, final return value
// depends on whether a body returns as a result of break statement. // depends on whether a body returns as a result of break statement.
@ -433,7 +433,7 @@ zeek::ValPtr ScriptFunc::Invoke(zeek::Args* args, zeek::detail::Frame* parent) c
if ( flow == FLOW_BREAK ) if ( flow == FLOW_BREAK )
{ {
// Short-circuit execution of remaining hook handler bodies. // Short-circuit execution of remaining hook handler bodies.
result = zeek::val_mgr->False(); result = val_mgr->False();
break; break;
} }
} }
@ -441,19 +441,19 @@ zeek::ValPtr ScriptFunc::Invoke(zeek::Args* args, zeek::detail::Frame* parent) c
call_stack.pop_back(); call_stack.pop_back();
if ( Flavor() == zeek::FUNC_FLAVOR_HOOK ) if ( Flavor() == FUNC_FLAVOR_HOOK )
{ {
if ( ! result ) if ( ! result )
result = zeek::val_mgr->True(); result = val_mgr->True();
} }
// Warn if the function returns something, but we returned from // Warn if the function returns something, but we returned from
// the function without an explicit return, or without a value. // the function without an explicit return, or without a value.
else if ( GetType()->Yield() && GetType()->Yield()->Tag() != zeek::TYPE_VOID && else if ( GetType()->Yield() && GetType()->Yield()->Tag() != TYPE_VOID &&
(flow != FLOW_RETURN /* we fell off the end */ || (flow != FLOW_RETURN /* we fell off the end */ ||
! result /* explicit return with no result */) && ! result /* explicit return with no result */) &&
! f->HasDelayed() ) ! f->HasDelayed() )
zeek::reporter->Warning("non-void function returning without a value: %s", reporter->Warning("non-void function returning without a value: %s",
Name()); Name());
if ( result && g_trace_state.DoTrace() ) if ( result && g_trace_state.DoTrace() )
@ -469,8 +469,8 @@ zeek::ValPtr ScriptFunc::Invoke(zeek::Args* args, zeek::detail::Frame* parent) c
return result; return result;
} }
void ScriptFunc::AddBody(zeek::detail::StmtPtr new_body, void ScriptFunc::AddBody(StmtPtr new_body,
const std::vector<zeek::detail::IDPtr>& new_inits, const std::vector<IDPtr>& new_inits,
size_t new_frame_size, int priority) size_t new_frame_size, int priority)
{ {
if ( new_frame_size > frame_size ) if ( new_frame_size > frame_size )
@ -483,7 +483,7 @@ void ScriptFunc::AddBody(zeek::detail::StmtPtr new_body,
new_body = AddInits(std::move(new_body), new_inits); new_body = AddInits(std::move(new_body), new_inits);
if ( Flavor() == zeek::FUNC_FLAVOR_FUNCTION ) if ( Flavor() == FUNC_FLAVOR_FUNCTION )
{ {
// For functions, we replace the old body with the new one. // For functions, we replace the old body with the new one.
assert(bodies.size() <= 1); assert(bodies.size() <= 1);
@ -498,7 +498,7 @@ void ScriptFunc::AddBody(zeek::detail::StmtPtr new_body,
sort(bodies.begin(), bodies.end()); sort(bodies.begin(), bodies.end());
} }
void ScriptFunc::AddClosure(IDPList ids, zeek::detail::Frame* f) void ScriptFunc::AddClosure(IDPList ids, Frame* f)
{ {
if ( ! f ) if ( ! f )
return; return;
@ -507,7 +507,7 @@ void ScriptFunc::AddClosure(IDPList ids, zeek::detail::Frame* f)
SetClosureFrame(f); SetClosureFrame(f);
} }
bool ScriptFunc::StrengthenClosureReference(zeek::detail::Frame* f) bool ScriptFunc::StrengthenClosureReference(Frame* f)
{ {
if ( closure != f ) if ( closure != f )
return false; return false;
@ -520,10 +520,10 @@ bool ScriptFunc::StrengthenClosureReference(zeek::detail::Frame* f)
return true; return true;
} }
void ScriptFunc::SetClosureFrame(zeek::detail::Frame* f) void ScriptFunc::SetClosureFrame(Frame* f)
{ {
if ( closure ) if ( closure )
zeek::reporter->InternalError("Tried to override closure for ScriptFunc %s.", reporter->InternalError("Tried to override closure for ScriptFunc %s.",
Name()); Name());
// Have to use weak references initially because otherwise Ref'ing the // Have to use weak references initially because otherwise Ref'ing the
@ -540,7 +540,7 @@ void ScriptFunc::SetClosureFrame(zeek::detail::Frame* f)
bool ScriptFunc::UpdateClosure(const broker::vector& data) bool ScriptFunc::UpdateClosure(const broker::vector& data)
{ {
auto result = zeek::detail::Frame::Unserialize(data); auto result = Frame::Unserialize(data);
if ( ! result.first ) if ( ! result.first )
return false; return false;
@ -560,11 +560,11 @@ bool ScriptFunc::UpdateClosure(const broker::vector& data)
} }
zeek::FuncPtr ScriptFunc::DoClone() FuncPtr ScriptFunc::DoClone()
{ {
// ScriptFunc could hold a closure. In this case a clone of it must // ScriptFunc could hold a closure. In this case a clone of it must
// store a copy of this closure. // store a copy of this closure.
auto other = zeek::IntrusivePtr{zeek::AdoptRef{}, new ScriptFunc()}; auto other = IntrusivePtr{AdoptRef{}, new ScriptFunc()};
CopyStateInto(other.get()); CopyStateInto(other.get());
@ -578,7 +578,7 @@ zeek::FuncPtr ScriptFunc::DoClone()
broker::expected<broker::data> ScriptFunc::SerializeClosure() const broker::expected<broker::data> ScriptFunc::SerializeClosure() const
{ {
return zeek::detail::Frame::Serialize(closure, outer_ids); return Frame::Serialize(closure, outer_ids);
} }
void ScriptFunc::Describe(ODesc* d) const void ScriptFunc::Describe(ODesc* d) const
@ -594,15 +594,15 @@ void ScriptFunc::Describe(ODesc* d) const
} }
} }
zeek::detail::StmtPtr ScriptFunc::AddInits( StmtPtr ScriptFunc::AddInits(
zeek::detail::StmtPtr body, StmtPtr body,
const std::vector<zeek::detail::IDPtr>& inits) const std::vector<IDPtr>& inits)
{ {
if ( inits.empty() ) if ( inits.empty() )
return body; return body;
auto stmt_series = zeek::make_intrusive<zeek::detail::StmtList>(); auto stmt_series = make_intrusive<StmtList>();
stmt_series->Stmts().push_back(new zeek::detail::InitStmt(inits)); stmt_series->Stmts().push_back(new InitStmt(inits));
stmt_series->Stmts().push_back(body.release()); stmt_series->Stmts().push_back(body.release());
return stmt_series; return stmt_series;
@ -616,14 +616,14 @@ BuiltinFunc::BuiltinFunc(built_in_func arg_func, const char* arg_name,
name = make_full_var_name(GLOBAL_MODULE_NAME, arg_name); name = make_full_var_name(GLOBAL_MODULE_NAME, arg_name);
is_pure = arg_is_pure; is_pure = arg_is_pure;
const auto& id = zeek::detail::lookup_ID(Name(), GLOBAL_MODULE_NAME, false); const auto& id = lookup_ID(Name(), GLOBAL_MODULE_NAME, false);
if ( ! id ) if ( ! id )
zeek::reporter->InternalError("built-in function %s missing", Name()); reporter->InternalError("built-in function %s missing", Name());
if ( id->HasVal() ) if ( id->HasVal() )
zeek::reporter->InternalError("built-in function %s multiply defined", Name()); reporter->InternalError("built-in function %s multiply defined", Name());
type = id->GetType<zeek::FuncType>(); type = id->GetType<FuncType>();
id->SetVal(zeek::make_intrusive<zeek::Val>(zeek::IntrusivePtr{zeek::NewRef{}, this})); id->SetVal(make_intrusive<Val>(IntrusivePtr{NewRef{}, this}));
} }
BuiltinFunc::~BuiltinFunc() BuiltinFunc::~BuiltinFunc()
@ -635,7 +635,7 @@ bool BuiltinFunc::IsPure() const
return is_pure; return is_pure;
} }
zeek::ValPtr BuiltinFunc::Invoke(zeek::Args* args, zeek::detail::Frame* parent) const ValPtr BuiltinFunc::Invoke(Args* args, Frame* parent) const
{ {
#ifdef PROFILE_BRO_FUNCTIONS #ifdef PROFILE_BRO_FUNCTIONS
DEBUG_MSG("Function: %s\n", Name()); DEBUG_MSG("Function: %s\n", Name());
@ -649,7 +649,7 @@ zeek::ValPtr BuiltinFunc::Invoke(zeek::Args* args, zeek::detail::Frame* parent)
HookCallFunction(this, parent, args), HookCallFunction(this, parent, args),
empty_hook_result); empty_hook_result);
CheckPluginResult(handled, hook_result, zeek::FUNC_FLAVOR_FUNCTION); CheckPluginResult(handled, hook_result, FUNC_FLAVOR_FUNCTION);
if ( handled ) if ( handled )
return hook_result; return hook_result;
@ -662,7 +662,7 @@ zeek::ValPtr BuiltinFunc::Invoke(zeek::Args* args, zeek::detail::Frame* parent)
g_trace_state.LogTrace("\tBuiltin Function called: %s\n", d.Description()); g_trace_state.LogTrace("\tBuiltin Function called: %s\n", d.Description());
} }
const zeek::detail::CallExpr* call_expr = parent ? parent->GetCall() : nullptr; const CallExpr* call_expr = parent ? parent->GetCall() : nullptr;
call_stack.emplace_back(CallInfo{call_expr, this, *args}); call_stack.emplace_back(CallInfo{call_expr, this, *args});
auto result = std::move(func(parent, args).rval); auto result = std::move(func(parent, args).rval);
call_stack.pop_back(); call_stack.pop_back();
@ -684,9 +684,9 @@ void BuiltinFunc::Describe(ODesc* d) const
d->AddCount(is_pure); d->AddCount(is_pure);
} }
bool check_built_in_call(BuiltinFunc* f, zeek::detail::CallExpr* call) bool check_built_in_call(BuiltinFunc* f, CallExpr* call)
{ {
if ( f->TheFunc() != zeek::BifFunc::fmt_bif) if ( f->TheFunc() != BifFunc::fmt_bif)
return true; return true;
const ExprPList& args = call->Args()->Exprs(); const ExprPList& args = call->Args()->Exprs();
@ -697,10 +697,10 @@ bool check_built_in_call(BuiltinFunc* f, zeek::detail::CallExpr* call)
return true; return true;
} }
const zeek::detail::Expr* fmt_str_arg = args[0]; const Expr* fmt_str_arg = args[0];
if ( fmt_str_arg->GetType()->Tag() != zeek::TYPE_STRING ) if ( fmt_str_arg->GetType()->Tag() != TYPE_STRING )
{ {
call->Error("first argument to zeek::util::fmt() needs to be a format string"); call->Error("first argument to 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 zeek::util::fmt() and number of arguments passed"); call->Error("mismatch between format string to util::fmt() and number of arguments passed");
return false; return false;
} }
} }
@ -739,16 +739,16 @@ bool check_built_in_call(BuiltinFunc* f, zeek::detail::CallExpr* call)
// Gets a function's priority from its Scope's attributes. Errors if it sees any // Gets a function's priority from its Scope's attributes. Errors if it sees any
// problems. // problems.
static int get_func_priority(const std::vector<zeek::detail::AttrPtr>& attrs) static int get_func_priority(const std::vector<AttrPtr>& attrs)
{ {
int priority = 0; int priority = 0;
for ( const auto& a : attrs ) for ( const auto& a : attrs )
{ {
if ( a->Tag() == zeek::detail::ATTR_DEPRECATED ) if ( a->Tag() == ATTR_DEPRECATED )
continue; continue;
if ( a->Tag() != zeek::detail::ATTR_PRIORITY ) if ( a->Tag() != ATTR_PRIORITY )
{ {
a->Error("illegal attribute for function body"); a->Error("illegal attribute for function body");
continue; continue;
@ -762,7 +762,7 @@ static int get_func_priority(const std::vector<zeek::detail::AttrPtr>& attrs)
continue; continue;
} }
if ( ! zeek::IsIntegral(v->GetType()->Tag()) ) if ( ! IsIntegral(v->GetType()->Tag()) )
{ {
a->Error("expression is not of integral type"); a->Error("expression is not of integral type");
continue; continue;
@ -774,7 +774,7 @@ static int get_func_priority(const std::vector<zeek::detail::AttrPtr>& attrs)
return priority; return priority;
} }
function_ingredients::function_ingredients(zeek::detail::ScopePtr scope, zeek::detail::StmtPtr body) function_ingredients::function_ingredients(ScopePtr scope, StmtPtr body)
{ {
frame_size = scope->Length(); frame_size = scope->Length();
inits = scope->GetInits(); inits = scope->GetInits();
@ -790,7 +790,7 @@ function_ingredients::function_ingredients(zeek::detail::ScopePtr scope, zeek::d
static void emit_builtin_error_common(const char* msg, Obj* arg, bool unwind) static void emit_builtin_error_common(const char* msg, Obj* arg, bool unwind)
{ {
auto emit = [=](const zeek::detail::CallExpr* ce) auto emit = [=](const CallExpr* ce)
{ {
if ( ce ) if ( ce )
{ {
@ -800,11 +800,11 @@ static void emit_builtin_error_common(const char* msg, Obj* arg, bool unwind)
{ {
ODesc d; ODesc d;
arg->Describe(&d); arg->Describe(&d);
zeek::reporter->ExprRuntimeError(ce, "%s (%s), during call:", msg, reporter->ExprRuntimeError(ce, "%s (%s), during call:", msg,
d.Description()); d.Description());
} }
else else
zeek::reporter->ExprRuntimeError(ce, "%s", msg); reporter->ExprRuntimeError(ce, "%s", msg);
} }
else else
ce->Error(msg, arg); ce->Error(msg, arg);
@ -814,22 +814,22 @@ static void emit_builtin_error_common(const char* msg, Obj* arg, bool unwind)
if ( arg ) if ( arg )
{ {
if ( unwind ) if ( unwind )
zeek::reporter->RuntimeError(arg->GetLocationInfo(), "%s", msg); reporter->RuntimeError(arg->GetLocationInfo(), "%s", msg);
else else
arg->Error(msg); arg->Error(msg);
} }
else else
{ {
if ( unwind ) if ( unwind )
zeek::reporter->RuntimeError(nullptr, "%s", msg); reporter->RuntimeError(nullptr, "%s", msg);
else else
zeek::reporter->Error("%s", msg); reporter->Error("%s", msg);
} }
} }
}; };
if ( zeek::detail::call_stack.empty() ) if ( call_stack.empty() )
{ {
// Shouldn't happen unless someone (mistakenly) calls builtin_error() // Shouldn't happen unless someone (mistakenly) calls builtin_error()
// from somewhere that's not even evaluating script-code. // from somewhere that's not even evaluating script-code.
@ -837,9 +837,9 @@ static void emit_builtin_error_common(const char* msg, Obj* arg, bool unwind)
return; return;
} }
auto last_call = zeek::detail::call_stack.back(); auto last_call = call_stack.back();
if ( zeek::detail::call_stack.size() < 2 ) if ( call_stack.size() < 2 )
{ {
// Don't need to check for wrapper function like "<module>::__<func>" // Don't need to check for wrapper function like "<module>::__<func>"
emit(last_call.call); emit(last_call.call);
@ -877,7 +877,7 @@ static void emit_builtin_error_common(const char* msg, Obj* arg, bool unwind)
wrapper_func = module_name + "::" + func_name.substr(2); wrapper_func = module_name + "::" + func_name.substr(2);
} }
auto parent_call = zeek::detail::call_stack[zeek::detail::call_stack.size() - 2]; auto parent_call = call_stack[call_stack.size() - 2];
auto parent_func = parent_call.func->Name(); auto parent_func = parent_call.func->Name();
if ( wrapper_func == parent_func ) if ( wrapper_func == parent_func )
@ -891,7 +891,7 @@ void emit_builtin_exception(const char* msg)
emit_builtin_error_common(msg, nullptr, true); emit_builtin_error_common(msg, nullptr, true);
} }
void emit_builtin_exception(const char* msg, const zeek::ValPtr& arg) void emit_builtin_exception(const char* msg, const ValPtr& arg)
{ {
emit_builtin_error_common(msg, arg.get(), true); emit_builtin_error_common(msg, arg.get(), true);
} }

View file

@ -25,12 +25,6 @@ ZEEK_FORWARD_DECLARE_NAMESPACED(ID, zeek::detail);
ZEEK_FORWARD_DECLARE_NAMESPACED(FuncType, zeek); ZEEK_FORWARD_DECLARE_NAMESPACED(FuncType, zeek);
ZEEK_FORWARD_DECLARE_NAMESPACED(Frame, zeek::detail); ZEEK_FORWARD_DECLARE_NAMESPACED(Frame, zeek::detail);
namespace zeek::detail {
using ScopePtr = zeek::IntrusivePtr<detail::Scope>;
using IDPtr = zeek::IntrusivePtr<ID>;
using StmtPtr = zeek::IntrusivePtr<Stmt>;
}
namespace caf { namespace caf {
template <class> class expected; template <class> class expected;
} }
@ -43,8 +37,16 @@ using caf::expected;
namespace zeek { namespace zeek {
namespace detail {
using ScopePtr = IntrusivePtr<Scope>;
using IDPtr = IntrusivePtr<ID>;
using StmtPtr = IntrusivePtr<Stmt>;
} // namespace detail
class Func; class Func;
using FuncPtr = zeek::IntrusivePtr<Func>; using FuncPtr = IntrusivePtr<Func>;
class Func : public Obj { class Func : public Obj {
public: public:
@ -59,10 +61,10 @@ public:
~Func() override; ~Func() override;
virtual bool IsPure() const = 0; virtual bool IsPure() const = 0;
zeek::FunctionFlavor Flavor() const { return GetType()->Flavor(); } FunctionFlavor Flavor() const { return GetType()->Flavor(); }
struct Body { struct Body {
zeek::detail::StmtPtr stmts; detail::StmtPtr stmts;
int priority; int priority;
bool operator<(const Body& other) const bool operator<(const Body& other) const
{ return priority > other.priority; } // reverse sort { return priority > other.priority; } // reverse sort
@ -72,7 +74,7 @@ public:
bool HasBodies() const { return bodies.size(); } bool HasBodies() const { return bodies.size(); }
[[deprecated("Remove in v4.1. Use Invoke() instead.")]] [[deprecated("Remove in v4.1. Use Invoke() instead.")]]
zeek::Val* Call(ValPList* args, zeek::detail::Frame* parent = nullptr) const; Val* Call(ValPList* args, detail::Frame* parent = nullptr) const;
/** /**
* Calls a Zeek function. * Calls a Zeek function.
@ -80,16 +82,16 @@ public:
* @param parent the frame from which the function is being called. * @param parent the frame from which the function is being called.
* @return the return value of the function call. * @return the return value of the function call.
*/ */
virtual zeek::ValPtr Invoke( virtual ValPtr Invoke(
zeek::Args* args, zeek::detail::Frame* parent = nullptr) const = 0; zeek::Args* args, detail::Frame* parent = nullptr) const = 0;
/** /**
* A version of Invoke() taking a variable number of individual arguments. * A version of Invoke() taking a variable number of individual arguments.
*/ */
template <class... Args> template <class... Args>
std::enable_if_t< std::enable_if_t<
std::is_convertible_v<std::tuple_element_t<0, std::tuple<Args...>>, zeek::ValPtr>, std::is_convertible_v<std::tuple_element_t<0, std::tuple<Args...>>, ValPtr>,
zeek::ValPtr> ValPtr>
Invoke(Args&&... args) const Invoke(Args&&... args) const
{ {
auto zargs = zeek::Args{std::forward<Args>(args)...}; auto zargs = zeek::Args{std::forward<Args>(args)...};
@ -97,17 +99,17 @@ public:
} }
// Add a new event handler to an existing function (event). // Add a new event handler to an existing function (event).
virtual void AddBody(zeek::detail::StmtPtr new_body, virtual void AddBody(detail::StmtPtr new_body,
const std::vector<zeek::detail::IDPtr>& new_inits, const std::vector<detail::IDPtr>& new_inits,
size_t new_frame_size, int priority = 0); size_t new_frame_size, int priority = 0);
virtual void SetScope(zeek::detail::ScopePtr newscope); virtual void SetScope(detail::ScopePtr newscope);
virtual zeek::detail::Scope* GetScope() const { return scope.get(); } virtual detail::Scope* GetScope() const { return scope.get(); }
[[deprecated("Remove in v4.1. Use GetType().")]] [[deprecated("Remove in v4.1. Use GetType().")]]
virtual zeek::FuncType* FType() const { return type.get(); } virtual FuncType* FType() const { return type.get(); }
const zeek::FuncTypePtr& GetType() const const FuncTypePtr& GetType() const
{ return type; } { return type; }
Kind GetKind() const { return kind; } Kind GetKind() const { return kind; }
@ -133,30 +135,30 @@ protected:
void CopyStateInto(Func* other) const; void CopyStateInto(Func* other) const;
// Helper function for checking result of plugin hook. // Helper function for checking result of plugin hook.
void CheckPluginResult(bool handled, const zeek::ValPtr& hook_result, void CheckPluginResult(bool handled, const ValPtr& hook_result,
zeek::FunctionFlavor flavor) const; FunctionFlavor flavor) const;
std::vector<Body> bodies; std::vector<Body> bodies;
zeek::detail::ScopePtr scope; detail::ScopePtr scope;
Kind kind; Kind kind;
uint32_t unique_id; uint32_t unique_id;
zeek::FuncTypePtr type; FuncTypePtr type;
std::string name; std::string name;
static inline std::vector<FuncPtr> unique_ids; static inline std::vector<FuncPtr> unique_ids;
}; };
namespace detail { namespace detail {
class ScriptFunc final : public zeek::Func { class ScriptFunc final : public Func {
public: public:
ScriptFunc(const zeek::detail::IDPtr& id, zeek::detail::StmtPtr body, ScriptFunc(const IDPtr& id, StmtPtr body,
const std::vector<zeek::detail::IDPtr>& inits, const std::vector<IDPtr>& inits,
size_t frame_size, int priority); size_t frame_size, int priority);
~ScriptFunc() override; ~ScriptFunc() override;
bool IsPure() const override; bool IsPure() const override;
zeek::ValPtr Invoke(zeek::Args* args, zeek::detail::Frame* parent) const override; ValPtr Invoke(zeek::Args* args, Frame* parent) const override;
/** /**
* Adds adds a closure to the function. Closures are cloned and * Adds adds a closure to the function. Closures are cloned and
@ -165,7 +167,7 @@ public:
* @param ids IDs that are captured by the closure. * @param ids IDs that are captured by the closure.
* @param f the closure to be captured. * @param f the closure to be captured.
*/ */
void AddClosure(IDPList ids, zeek::detail::Frame* f); void AddClosure(IDPList ids, Frame* f);
/** /**
* Replaces the current closure with one built from *data* * Replaces the current closure with one built from *data*
@ -178,7 +180,7 @@ public:
* If the function's closure is a weak reference to the given frame, * If the function's closure is a weak reference to the given frame,
* upgrade to a strong reference of a shallow clone of that frame. * upgrade to a strong reference of a shallow clone of that frame.
*/ */
bool StrengthenClosureReference(zeek::detail::Frame* f); bool StrengthenClosureReference(Frame* f);
/** /**
* Serializes this function's closure. * Serializes this function's closure.
@ -187,8 +189,8 @@ public:
*/ */
broker::expected<broker::data> SerializeClosure() const; broker::expected<broker::data> SerializeClosure() const;
void AddBody(zeek::detail::StmtPtr new_body, void AddBody(StmtPtr new_body,
const std::vector<zeek::detail::IDPtr>& new_inits, const std::vector<IDPtr>& new_inits,
size_t new_frame_size, int priority) override; size_t new_frame_size, int priority) override;
/** Sets this function's outer_id list. */ /** Sets this function's outer_id list. */
@ -198,15 +200,15 @@ public:
void Describe(ODesc* d) const override; void Describe(ODesc* d) const override;
protected: protected:
ScriptFunc() : zeek::Func(SCRIPT_FUNC) {} ScriptFunc() : Func(SCRIPT_FUNC) {}
zeek::detail::StmtPtr AddInits( StmtPtr AddInits(
zeek::detail::StmtPtr body, StmtPtr body,
const std::vector<zeek::detail::IDPtr>& inits); const std::vector<IDPtr>& inits);
/** /**
* Clones this function along with its closures. * Clones this function along with its closures.
*/ */
zeek::FuncPtr DoClone() override; FuncPtr DoClone() override;
/** /**
* Performs a selective clone of *f* using the IDs that were * Performs a selective clone of *f* using the IDs that were
@ -214,7 +216,7 @@ protected:
* *
* @param f the frame to be cloned. * @param f the frame to be cloned.
*/ */
void SetClosureFrame(zeek::detail::Frame* f); void SetClosureFrame(Frame* f);
private: private:
size_t frame_size; size_t frame_size;
@ -222,19 +224,19 @@ private:
// List of the outer IDs used in the function. // List of the outer IDs used in the function.
IDPList outer_ids; IDPList outer_ids;
// The frame the ScriptFunc was initialized in. // The frame the ScriptFunc was initialized in.
zeek::detail::Frame* closure = nullptr; Frame* closure = nullptr;
bool weak_closure_ref = false; bool weak_closure_ref = false;
}; };
using built_in_func = BifReturnVal (*)(zeek::detail::Frame* frame, const zeek::Args* args); using built_in_func = BifReturnVal (*)(Frame* frame, const Args* args);
class BuiltinFunc final : public zeek::Func { class BuiltinFunc final : public Func {
public: public:
BuiltinFunc(built_in_func func, const char* name, bool is_pure); BuiltinFunc(built_in_func func, const char* name, bool is_pure);
~BuiltinFunc() override; ~BuiltinFunc() override;
bool IsPure() const override; bool IsPure() const override;
zeek::ValPtr Invoke(zeek::Args* args, zeek::detail::Frame* parent) const override; ValPtr Invoke(zeek::Args* args, Frame* parent) const override;
built_in_func TheFunc() const { return func; } built_in_func TheFunc() const { return func; }
void Describe(ODesc* d) const override; void Describe(ODesc* d) const override;
@ -246,10 +248,10 @@ protected:
bool is_pure; bool is_pure;
}; };
extern bool check_built_in_call(BuiltinFunc* f, zeek::detail::CallExpr* call); extern bool check_built_in_call(BuiltinFunc* f, CallExpr* call);
struct CallInfo { struct CallInfo {
const zeek::detail::CallExpr* call; const CallExpr* call;
const Func* func; const Func* func;
const zeek::Args& args; const zeek::Args& args;
}; };
@ -276,7 +278,7 @@ extern std::vector<CallInfo> call_stack;
extern bool did_builtin_init; extern bool did_builtin_init;
extern void emit_builtin_exception(const char* msg); extern void emit_builtin_exception(const char* msg);
extern void emit_builtin_exception(const char* msg, const zeek::ValPtr& arg); extern void emit_builtin_exception(const char* msg, const ValPtr& arg);
extern void emit_builtin_exception(const char* msg, Obj* arg); extern void emit_builtin_exception(const char* msg, Obj* arg);
} // namespace detail } // namespace detail
@ -285,7 +287,7 @@ extern std::string render_call_stack();
// These methods are used by BIFs, so they're in the public namespace. // These methods are used by BIFs, so they're in the public namespace.
extern void emit_builtin_error(const char* msg); extern void emit_builtin_error(const char* msg);
extern void emit_builtin_error(const char* msg, const zeek::ValPtr&); extern void emit_builtin_error(const char* msg, const ValPtr&);
extern void emit_builtin_error(const char* msg, Obj* arg); extern void emit_builtin_error(const char* msg, Obj* arg);
} // namespace zeek } // namespace zeek

View file

@ -46,7 +46,7 @@ void KeyedHash::InitializeSeeds(const std::array<uint32_t, SEED_INIT_SIZE>& seed
void KeyedHash::InitOptions() void KeyedHash::InitOptions()
{ {
calculate_digest(Hash_SHA256, zeek::BifConst::digest_salt->Bytes(), zeek::BifConst::digest_salt->Len(), reinterpret_cast<unsigned char*>(cluster_highwayhash_key)); calculate_digest(Hash_SHA256, BifConst::digest_salt->Bytes(), BifConst::digest_salt->Len(), reinterpret_cast<unsigned char*>(cluster_highwayhash_key));
} }
hash64_t KeyedHash::Hash64(const void* bytes, uint64_t size) hash64_t KeyedHash::Hash64(const void* bytes, uint64_t size)
@ -85,7 +85,7 @@ void init_hash_function()
{ {
// Make sure we have already called init_random_seed(). // Make sure we have already called init_random_seed().
if ( ! KeyedHash::IsInitialized() ) if ( ! KeyedHash::IsInitialized() )
zeek::reporter->InternalError("Zeek's hash functions aren't fully initialized"); reporter->InternalError("Zeek's hash functions aren't fully initialized");
} }
HashKey::HashKey(bro_int_t i) HashKey::HashKey(bro_int_t i)
@ -147,7 +147,7 @@ HashKey::HashKey(const char* s)
hash = HashBytes(key, size); hash = HashBytes(key, size);
} }
HashKey::HashKey(const zeek::String* s) HashKey::HashKey(const String* s)
{ {
size = s->Len(); size = s->Len();
key = (void*) s->Bytes(); key = (void*) s->Bytes();

View file

@ -199,17 +199,18 @@ 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::detail::hmac_md5(size_t size, const unsigned char* bytes, unsigned char digest[16]); friend void 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 BifFunc::md5_hmac_bif(zeek::detail::Frame* frame, const Args*);
}; };
typedef enum { typedef enum {
HASH_KEY_INT, HASH_KEY_INT,
HASH_KEY_DOUBLE, HASH_KEY_DOUBLE,
HASH_KEY_STRING HASH_KEY_STRING
#define NUM_HASH_KEYS (int(zeek::detail::HASH_KEY_STRING) + 1)
} HashKeyTag; } HashKeyTag;
constexpr int NUM_HASH_KEYS = HASH_KEY_STRING + 1;
class HashKey { class HashKey {
public: public:
explicit HashKey(bro_int_t i); explicit HashKey(bro_int_t i);
@ -219,7 +220,7 @@ public:
explicit HashKey(double d); explicit HashKey(double d);
explicit HashKey(const void* p); explicit HashKey(const void* p);
explicit HashKey(const char* s); explicit HashKey(const char* s);
explicit HashKey(const zeek::String* s); explicit HashKey(const String* s);
~HashKey() ~HashKey()
{ {
if ( is_our_dynamic ) if ( is_our_dynamic )
@ -258,7 +259,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) + zeek::util::pad_size(size); } unsigned int MemoryAllocation() const { return padded_sizeof(*this) + util::pad_size(size); }
static hash_t HashBytes(const void* bytes, int size); static hash_t HashBytes(const void* bytes, int size);
protected: protected:

122
src/ID.cc
View file

@ -20,94 +20,96 @@
#include "zeekygen/ScriptInfo.h" #include "zeekygen/ScriptInfo.h"
#include "module_util.h" #include "module_util.h"
zeek::RecordTypePtr zeek::id::conn_id; namespace zeek {
zeek::RecordTypePtr zeek::id::endpoint;
zeek::RecordTypePtr zeek::id::connection;
zeek::RecordTypePtr zeek::id::fa_file;
zeek::RecordTypePtr zeek::id::fa_metadata;
zeek::EnumTypePtr zeek::id::transport_proto;
zeek::TableTypePtr zeek::id::string_set;
zeek::TableTypePtr zeek::id::string_array;
zeek::TableTypePtr zeek::id::count_set;
zeek::VectorTypePtr zeek::id::string_vec;
zeek::VectorTypePtr zeek::id::index_vec;
const zeek::detail::IDPtr& zeek::id::find(std::string_view name) RecordTypePtr id::conn_id;
RecordTypePtr id::endpoint;
RecordTypePtr id::connection;
RecordTypePtr id::fa_file;
RecordTypePtr id::fa_metadata;
EnumTypePtr id::transport_proto;
TableTypePtr id::string_set;
TableTypePtr id::string_array;
TableTypePtr id::count_set;
VectorTypePtr id::string_vec;
VectorTypePtr id::index_vec;
const detail::IDPtr& id::find(std::string_view name)
{ {
return zeek::detail::global_scope()->Find(name); return zeek::detail::global_scope()->Find(name);
} }
const zeek::TypePtr& zeek::id::find_type(std::string_view name) const TypePtr& id::find_type(std::string_view name)
{ {
auto id = zeek::detail::global_scope()->Find(name); auto id = zeek::detail::global_scope()->Find(name);
if ( ! id ) if ( ! id )
zeek::reporter->InternalError("Failed to find type named: %s", reporter->InternalError("Failed to find type named: %s",
std::string(name).data()); std::string(name).data());
return id->GetType(); return id->GetType();
} }
const zeek::ValPtr& zeek::id::find_val(std::string_view name) const ValPtr& id::find_val(std::string_view name)
{ {
auto id = zeek::detail::global_scope()->Find(name); auto id = zeek::detail::global_scope()->Find(name);
if ( ! id ) if ( ! id )
zeek::reporter->InternalError("Failed to find variable named: %s", reporter->InternalError("Failed to find variable named: %s",
std::string(name).data()); std::string(name).data());
return id->GetVal(); return id->GetVal();
} }
const zeek::ValPtr& zeek::id::find_const(std::string_view name) const ValPtr& id::find_const(std::string_view name)
{ {
auto id = zeek::detail::global_scope()->Find(name); auto id = zeek::detail::global_scope()->Find(name);
if ( ! id ) if ( ! id )
zeek::reporter->InternalError("Failed to find variable named: %s", reporter->InternalError("Failed to find variable named: %s",
std::string(name).data()); std::string(name).data());
if ( ! id->IsConst() ) if ( ! id->IsConst() )
zeek::reporter->InternalError("Variable is not 'const', but expected to be: %s", reporter->InternalError("Variable is not 'const', but expected to be: %s",
std::string(name).data()); std::string(name).data());
return id->GetVal(); return id->GetVal();
} }
zeek::FuncPtr zeek::id::find_func(std::string_view name) FuncPtr id::find_func(std::string_view name)
{ {
const auto& v = zeek::id::find_val(name); const auto& v = id::find_val(name);
if ( ! v ) if ( ! v )
return nullptr; return nullptr;
if ( ! IsFunc(v->GetType()->Tag()) ) if ( ! IsFunc(v->GetType()->Tag()) )
zeek::reporter->InternalError("Expected variable '%s' to be a function", reporter->InternalError("Expected variable '%s' to be a function",
std::string(name).data()); std::string(name).data());
return v->AsFuncPtr(); return v->AsFuncPtr();
} }
void zeek::id::detail::init() void id::detail::init()
{ {
conn_id = zeek::id::find_type<zeek::RecordType>("conn_id"); conn_id = id::find_type<RecordType>("conn_id");
endpoint = zeek::id::find_type<zeek::RecordType>("endpoint"); endpoint = id::find_type<RecordType>("endpoint");
connection = zeek::id::find_type<zeek::RecordType>("connection"); connection = id::find_type<RecordType>("connection");
fa_file = zeek::id::find_type<zeek::RecordType>("fa_file"); fa_file = id::find_type<RecordType>("fa_file");
fa_metadata = zeek::id::find_type<zeek::RecordType>("fa_metadata"); fa_metadata = id::find_type<RecordType>("fa_metadata");
transport_proto = zeek::id::find_type<zeek::EnumType>("transport_proto"); transport_proto = id::find_type<EnumType>("transport_proto");
string_set = zeek::id::find_type<zeek::TableType>("string_set"); string_set = id::find_type<TableType>("string_set");
string_array = zeek::id::find_type<zeek::TableType>("string_array"); string_array = id::find_type<TableType>("string_array");
count_set = zeek::id::find_type<zeek::TableType>("count_set"); count_set = id::find_type<TableType>("count_set");
string_vec = zeek::id::find_type<zeek::VectorType>("string_vec"); string_vec = id::find_type<VectorType>("string_vec");
index_vec = zeek::id::find_type<zeek::VectorType>("index_vec"); index_vec = id::find_type<VectorType>("index_vec");
} }
namespace zeek::detail { namespace 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 = zeek::util::copy_string(arg_name); name = 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;
@ -131,7 +133,7 @@ std::string ID::ModuleName() const
return extract_module_name(name); return extract_module_name(name);
} }
void ID::SetType(zeek::TypePtr t) void ID::SetType(TypePtr t)
{ {
type = std::move(t); type = std::move(t);
} }
@ -146,7 +148,7 @@ void ID::ClearVal()
val = nullptr; val = nullptr;
} }
void ID::SetVal(zeek::ValPtr v) void ID::SetVal(ValPtr v)
{ {
val = std::move(v); val = std::move(v);
Modified(); Modified();
@ -159,12 +161,12 @@ void ID::SetVal(zeek::ValPtr v)
type->Tag() == TYPE_FUNC && type->Tag() == TYPE_FUNC &&
type->AsFuncType()->Flavor() == FUNC_FLAVOR_EVENT ) type->AsFuncType()->Flavor() == FUNC_FLAVOR_EVENT )
{ {
EventHandler* handler = zeek::event_registry->Lookup(name); EventHandler* handler = event_registry->Lookup(name);
if ( ! handler ) if ( ! handler )
{ {
handler = new EventHandler(name); handler = new EventHandler(name);
handler->SetFunc(val->AsFuncPtr()); handler->SetFunc(val->AsFuncPtr());
zeek::event_registry->Register(handler); event_registry->Register(handler);
} }
else else
{ {
@ -175,7 +177,7 @@ void ID::SetVal(zeek::ValPtr v)
} }
} }
void ID::SetVal(zeek::ValPtr v, InitClass c) void ID::SetVal(ValPtr v, InitClass c)
{ {
if ( c == INIT_NONE || c == INIT_FULL ) if ( c == INIT_NONE || c == INIT_FULL )
{ {
@ -257,7 +259,7 @@ void ID::UpdateValAttrs()
const auto& attr = attrs->Find(ATTR_ERROR_HANDLER); const auto& attr = attrs->Find(ATTR_ERROR_HANDLER);
if ( attr ) if ( attr )
zeek::event_registry->SetErrorHandler(Name()); event_registry->SetErrorHandler(Name());
} }
if ( GetType()->Tag() == TYPE_RECORD ) if ( GetType()->Tag() == TYPE_RECORD )
@ -267,15 +269,15 @@ void ID::UpdateValAttrs()
if ( attr ) if ( attr )
{ {
// Apply &log to all record fields. // Apply &log to all record fields.
zeek::RecordType* rt = GetType()->AsRecordType(); RecordType* rt = GetType()->AsRecordType();
for ( int i = 0; i < rt->NumFields(); ++i ) for ( int i = 0; i < rt->NumFields(); ++i )
{ {
TypeDecl* fd = rt->FieldDecl(i); TypeDecl* fd = rt->FieldDecl(i);
if ( ! fd->attrs ) if ( ! fd->attrs )
fd->attrs = zeek::make_intrusive<Attributes>(rt->GetFieldType(i), true, IsGlobal()); fd->attrs = make_intrusive<Attributes>(rt->GetFieldType(i), true, IsGlobal());
fd->attrs->AddAttr(zeek::make_intrusive<Attr>(ATTR_LOG)); fd->attrs->AddAttr(make_intrusive<Attr>(ATTR_LOG));
} }
} }
} }
@ -296,8 +298,8 @@ void ID::MakeDeprecated(ExprPtr deprecation)
if ( IsDeprecated() ) if ( IsDeprecated() )
return; return;
std::vector<AttrPtr> attrv{zeek::make_intrusive<Attr>(ATTR_DEPRECATED, std::move(deprecation))}; std::vector<AttrPtr> attrv{make_intrusive<Attr>(ATTR_DEPRECATED, std::move(deprecation))};
AddAttrs(zeek::make_intrusive<Attributes>(std::move(attrv), GetType(), false, IsGlobal())); AddAttrs(make_intrusive<Attributes>(std::move(attrv), GetType(), false, IsGlobal()));
} }
std::string ID::GetDeprecationWarning() const std::string ID::GetDeprecationWarning() const
@ -309,9 +311,9 @@ std::string ID::GetDeprecationWarning() const
result = depr_attr->DeprecationMessage(); result = depr_attr->DeprecationMessage();
if ( result.empty() ) if ( result.empty() )
return zeek::util::fmt("deprecated (%s)", Name()); return util::fmt("deprecated (%s)", Name());
else else
return zeek::util::fmt("deprecated (%s): %s", Name(), result.c_str()); return util::fmt("deprecated (%s): %s", Name(), result.c_str());
} }
void ID::AddAttrs(AttributesPtr a) void ID::AddAttrs(AttributesPtr a)
@ -340,18 +342,18 @@ void ID::SetOption()
// option implied redefinable // option implied redefinable
if ( ! IsRedefinable() ) if ( ! IsRedefinable() )
{ {
std::vector<AttrPtr> attrv{zeek::make_intrusive<Attr>(ATTR_REDEF)}; std::vector<AttrPtr> attrv{make_intrusive<Attr>(ATTR_REDEF)};
AddAttrs(zeek::make_intrusive<Attributes>(std::move(attrv), GetType(), false, IsGlobal())); AddAttrs(make_intrusive<Attributes>(std::move(attrv), GetType(), false, IsGlobal()));
} }
} }
void ID::EvalFunc(ExprPtr ef, ExprPtr ev) void ID::EvalFunc(ExprPtr ef, ExprPtr ev)
{ {
auto arg1 = zeek::make_intrusive<zeek::detail::ConstExpr>(val); auto arg1 = make_intrusive<detail::ConstExpr>(val);
auto args = zeek::make_intrusive<zeek::detail::ListExpr>(); auto args = make_intrusive<detail::ListExpr>();
args->Append(std::move(arg1)); args->Append(std::move(arg1));
args->Append(std::move(ev)); args->Append(std::move(ev));
auto ce = zeek::make_intrusive<CallExpr>(std::move(ef), std::move(args)); auto ce = make_intrusive<CallExpr>(std::move(ef), std::move(args));
SetVal(ce->Eval(nullptr)); SetVal(ce->Eval(nullptr));
} }
@ -371,7 +373,7 @@ TraversalCode ID::Traverse(TraversalCallback* cb) const
// FIXME: Perhaps we should be checking at other than global scope. // FIXME: Perhaps we should be checking at other than global scope.
else if ( val && IsFunc(val->GetType()->Tag()) && else if ( val && IsFunc(val->GetType()->Tag()) &&
cb->current_scope == zeek::detail::global_scope() ) cb->current_scope == detail::global_scope() )
{ {
tc = val->AsFunc()->Traverse(cb); tc = val->AsFunc()->Traverse(cb);
HANDLE_TC_STMT_PRE(tc); HANDLE_TC_STMT_PRE(tc);
@ -614,10 +616,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 = zeek::util::strreplace(redef_str, "\n", " "); redef_str = util::strreplace(redef_str, "\n", " ");
d->Add(":Redefinition: "); d->Add(":Redefinition: ");
d->Add(zeek::util::fmt("from :doc:`/scripts/%s`", ir->from_script.data())); d->Add(util::fmt("from :doc:`/scripts/%s`", ir->from_script.data()));
d->NL(); d->NL();
d->PushIndent(); d->PushIndent();
@ -648,7 +650,7 @@ void ID::UpdateValID()
} }
#endif #endif
void ID::AddOptionHandler(zeek::FuncPtr callback, int priority) void ID::AddOptionHandler(FuncPtr callback, int priority)
{ {
option_handlers.emplace(priority, std::move(callback)); option_handlers.emplace(priority, std::move(callback));
} }
@ -664,4 +666,6 @@ std::vector<Func*> ID::GetOptionHandlers() const
return v; return v;
} }
} } // namespace detail
} // namespace zeek

View file

@ -22,13 +22,13 @@ ZEEK_FORWARD_DECLARE_NAMESPACED(EnumType, zeek);
namespace zeek { namespace zeek {
class Type; class Type;
using TypePtr = zeek::IntrusivePtr<zeek::Type>; using TypePtr = IntrusivePtr<Type>;
using RecordTypePtr = zeek::IntrusivePtr<zeek::RecordType>; using RecordTypePtr = IntrusivePtr<RecordType>;
using TableTypePtr = zeek::IntrusivePtr<zeek::TableType>; using TableTypePtr = IntrusivePtr<TableType>;
using VectorTypePtr = zeek::IntrusivePtr<zeek::VectorType>; using VectorTypePtr = IntrusivePtr<VectorType>;
using EnumTypePtr = zeek::IntrusivePtr<zeek::EnumType>; using EnumTypePtr = IntrusivePtr<EnumType>;
using ValPtr = zeek::IntrusivePtr<zeek::Val>; using ValPtr = IntrusivePtr<Val>;
using FuncPtr = zeek::IntrusivePtr<zeek::Func>; using FuncPtr = IntrusivePtr<Func>;
} }
using BroType [[deprecated("Remove in v4.1. Use zeek::Type instead.")]] = zeek::Type; using BroType [[deprecated("Remove in v4.1. Use zeek::Type instead.")]] = zeek::Type;
@ -37,15 +37,15 @@ namespace zeek::detail {
class Attributes; class Attributes;
class Expr; class Expr;
using ExprPtr = zeek::IntrusivePtr<Expr>; using ExprPtr = IntrusivePtr<Expr>;
enum InitClass { INIT_NONE, INIT_FULL, INIT_EXTRA, INIT_REMOVE, }; enum InitClass { INIT_NONE, INIT_FULL, INIT_EXTRA, INIT_REMOVE, };
enum IDScope { SCOPE_FUNCTION, SCOPE_MODULE, SCOPE_GLOBAL }; enum IDScope { SCOPE_FUNCTION, SCOPE_MODULE, SCOPE_GLOBAL };
class ID; class ID;
using IDPtr = zeek::IntrusivePtr<ID>; using IDPtr = IntrusivePtr<ID>;
class ID final : public Obj, public zeek::notifier::detail::Modifiable { class ID final : public Obj, public notifier::detail::Modifiable {
public: public:
static inline const IDPtr nil; static inline const IDPtr nil;
@ -63,7 +63,7 @@ public:
std::string ModuleName() const; std::string ModuleName() const;
void SetType(zeek::TypePtr t); void SetType(TypePtr t);
[[deprecated("Remove in v4.1. Use version that takes IntrusivePtr.")]] [[deprecated("Remove in v4.1. Use version that takes IntrusivePtr.")]]
void SetType(zeek::Type* t); void SetType(zeek::Type* t);
@ -76,8 +76,8 @@ public:
{ return type; } { return type; }
template <class T> template <class T>
zeek::IntrusivePtr<T> GetType() const IntrusivePtr<T> GetType() const
{ return zeek::cast_intrusive<T>(type); } { return cast_intrusive<T>(type); }
[[deprecated("Remove in v4.1. Use IsType() and GetType().")]] [[deprecated("Remove in v4.1. Use IsType() and GetType().")]]
zeek::Type* AsType() { return is_type ? GetType().get() : nullptr; } zeek::Type* AsType() { return is_type ? GetType().get() : nullptr; }
@ -131,7 +131,7 @@ public:
[[deprecated("Remove in 4.1. Use GetAttrs().")]] [[deprecated("Remove in 4.1. Use GetAttrs().")]]
Attributes* Attrs() const { return attrs.get(); } Attributes* Attrs() const { return attrs.get(); }
const AttrPtr& GetAttr(zeek::detail::AttrTag t) const; const AttrPtr& GetAttr(AttrTag t) const;
bool IsDeprecated() const; bool IsDeprecated() const;
@ -158,7 +158,7 @@ public:
bool HasOptionHandlers() const bool HasOptionHandlers() const
{ return !option_handlers.empty(); } { return !option_handlers.empty(); }
void AddOptionHandler(zeek::FuncPtr callback, int priority); void AddOptionHandler(FuncPtr callback, int priority);
std::vector<Func*> GetOptionHandlers() const; std::vector<Func*> GetOptionHandlers() const;
protected: protected:
@ -178,11 +178,11 @@ protected:
ValPtr val; ValPtr val;
AttributesPtr attrs; AttributesPtr attrs;
// contains list of functions that are called when an option changes // contains list of functions that are called when an option changes
std::multimap<int, zeek::FuncPtr> option_handlers; std::multimap<int, FuncPtr> option_handlers;
}; };
} } // namespace zeek::detail
using ID [[deprecated("Remove in v4.1. Use zeek::detail::ID instead.")]] = zeek::detail::ID; using ID [[deprecated("Remove in v4.1. Use zeek::detail::ID instead.")]] = zeek::detail::ID;
@ -211,8 +211,8 @@ const TypePtr& find_type(std::string_view name);
* @return The type of the identifier. * @return The type of the identifier.
*/ */
template<class T> template<class T>
zeek::IntrusivePtr<T> find_type(std::string_view name) IntrusivePtr<T> find_type(std::string_view name)
{ return zeek::cast_intrusive<T>(find_type(name)); } { return cast_intrusive<T>(find_type(name)); }
/** /**
* Lookup an ID by its name and return its value. A fatal occurs if the ID * Lookup an ID by its name and return its value. A fatal occurs if the ID
@ -229,8 +229,8 @@ const ValPtr& find_val(std::string_view name);
* @return The current value of the identifier. * @return The current value of the identifier.
*/ */
template<class T> template<class T>
zeek::IntrusivePtr<T> find_val(std::string_view name) IntrusivePtr<T> find_val(std::string_view name)
{ return zeek::cast_intrusive<T>(find_val(name)); } { return cast_intrusive<T>(find_val(name)); }
/** /**
* Lookup an ID by its name and return its value. A fatal occurs if the ID * Lookup an ID by its name and return its value. A fatal occurs if the ID
@ -247,8 +247,8 @@ const ValPtr& find_const(std::string_view name);
* @return The current value of the identifier. * @return The current value of the identifier.
*/ */
template<class T> template<class T>
zeek::IntrusivePtr<T> find_const(std::string_view name) IntrusivePtr<T> find_const(std::string_view name)
{ return zeek::cast_intrusive<T>(find_const(name)); } { return cast_intrusive<T>(find_const(name)); }
/** /**
* Lookup an ID by its name and return the function it references. * Lookup an ID by its name and return the function it references.
@ -256,7 +256,7 @@ zeek::IntrusivePtr<T> find_const(std::string_view name)
* @param name The identifier name to lookup * @param name The identifier name to lookup
* @return The current function value the identifier references. * @return The current function value the identifier references.
*/ */
zeek::FuncPtr find_func(std::string_view name); FuncPtr find_func(std::string_view name);
extern RecordTypePtr conn_id; extern RecordTypePtr conn_id;
extern RecordTypePtr endpoint; extern RecordTypePtr endpoint;
@ -274,8 +274,7 @@ namespace detail {
void init(); void init();
} // namespace zeek::id::detail } // namespace detail
} // namespace zeek::id } // namespace zeek::id
using ID [[deprecated("Remove in v4.1 Use zeek::detail::ID instead.")]] = zeek::detail::ID; using ID [[deprecated("Remove in v4.1 Use zeek::detail::ID instead.")]] = zeek::detail::ID;

362
src/IP.cc
View file

@ -13,22 +13,24 @@
#include "ZeekString.h" #include "ZeekString.h"
#include "Reporter.h" #include "Reporter.h"
static zeek::VectorValPtr BuildOptionsVal(const u_char* data, int len) namespace zeek {
static VectorValPtr BuildOptionsVal(const u_char* data, int len)
{ {
auto vv = zeek::make_intrusive<zeek::VectorVal>(zeek::id::find_type<zeek::VectorType>("ip6_options")); auto vv = make_intrusive<VectorVal>(id::find_type<VectorType>("ip6_options"));
while ( len > 0 ) while ( len > 0 )
{ {
static auto ip6_option_type = zeek::id::find_type<zeek::RecordType>("ip6_option"); static auto ip6_option_type = id::find_type<RecordType>("ip6_option");
const struct ip6_opt* opt = (const struct ip6_opt*) data; const struct ip6_opt* opt = (const struct ip6_opt*) data;
auto rv = zeek::make_intrusive<zeek::RecordVal>(ip6_option_type); auto rv = make_intrusive<RecordVal>(ip6_option_type);
rv->Assign(0, zeek::val_mgr->Count(opt->ip6o_type)); rv->Assign(0, val_mgr->Count(opt->ip6o_type));
if ( opt->ip6o_type == 0 ) if ( opt->ip6o_type == 0 )
{ {
// Pad1 option // Pad1 option
rv->Assign(1, zeek::val_mgr->Count(0)); rv->Assign(1, val_mgr->Count(0));
rv->Assign(2, zeek::val_mgr->EmptyString()); rv->Assign(2, val_mgr->EmptyString());
data += sizeof(uint8_t); data += sizeof(uint8_t);
len -= sizeof(uint8_t); len -= sizeof(uint8_t);
} }
@ -36,9 +38,9 @@ static zeek::VectorValPtr BuildOptionsVal(const u_char* data, int len)
{ {
// PadN or other option // PadN or other option
uint16_t off = 2 * sizeof(uint8_t); uint16_t off = 2 * sizeof(uint8_t);
rv->Assign(1, zeek::val_mgr->Count(opt->ip6o_len)); rv->Assign(1, val_mgr->Count(opt->ip6o_len));
rv->Assign(2, zeek::make_intrusive<zeek::StringVal>( rv->Assign(2, make_intrusive<StringVal>(
new zeek::String(data + off, opt->ip6o_len, true))); new String(data + off, opt->ip6o_len, true)));
data += opt->ip6o_len + off; data += opt->ip6o_len + off;
len -= opt->ip6o_len + off; len -= opt->ip6o_len + off;
} }
@ -49,39 +51,37 @@ static zeek::VectorValPtr BuildOptionsVal(const u_char* data, int len)
return vv; return vv;
} }
namespace zeek { RecordValPtr IPv6_Hdr::ToVal(VectorValPtr chain) const
zeek::RecordValPtr IPv6_Hdr::ToVal(zeek::VectorValPtr chain) const
{ {
zeek::RecordValPtr rv; RecordValPtr rv;
switch ( type ) { switch ( type ) {
case IPPROTO_IPV6: case IPPROTO_IPV6:
{ {
static auto ip6_hdr_type = zeek::id::find_type<zeek::RecordType>("ip6_hdr"); static auto ip6_hdr_type = id::find_type<RecordType>("ip6_hdr");
rv = zeek::make_intrusive<zeek::RecordVal>(ip6_hdr_type); rv = make_intrusive<RecordVal>(ip6_hdr_type);
const struct ip6_hdr* ip6 = (const struct ip6_hdr*)data; const struct ip6_hdr* ip6 = (const struct ip6_hdr*)data;
rv->Assign(0, zeek::val_mgr->Count((ntohl(ip6->ip6_flow) & 0x0ff00000)>>20)); rv->Assign(0, val_mgr->Count((ntohl(ip6->ip6_flow) & 0x0ff00000)>>20));
rv->Assign(1, zeek::val_mgr->Count(ntohl(ip6->ip6_flow) & 0x000fffff)); rv->Assign(1, val_mgr->Count(ntohl(ip6->ip6_flow) & 0x000fffff));
rv->Assign(2, zeek::val_mgr->Count(ntohs(ip6->ip6_plen))); rv->Assign(2, val_mgr->Count(ntohs(ip6->ip6_plen)));
rv->Assign(3, zeek::val_mgr->Count(ip6->ip6_nxt)); rv->Assign(3, val_mgr->Count(ip6->ip6_nxt));
rv->Assign(4, zeek::val_mgr->Count(ip6->ip6_hlim)); rv->Assign(4, val_mgr->Count(ip6->ip6_hlim));
rv->Assign(5, zeek::make_intrusive<zeek::AddrVal>(IPAddr(ip6->ip6_src))); rv->Assign(5, make_intrusive<AddrVal>(IPAddr(ip6->ip6_src)));
rv->Assign(6, zeek::make_intrusive<zeek::AddrVal>(IPAddr(ip6->ip6_dst))); rv->Assign(6, make_intrusive<AddrVal>(IPAddr(ip6->ip6_dst)));
if ( ! chain ) if ( ! chain )
chain = zeek::make_intrusive<zeek::VectorVal>( chain = make_intrusive<VectorVal>(
zeek::id::find_type<zeek::VectorType>("ip6_ext_hdr_chain")); id::find_type<VectorType>("ip6_ext_hdr_chain"));
rv->Assign(7, std::move(chain)); rv->Assign(7, std::move(chain));
} }
break; break;
case IPPROTO_HOPOPTS: case IPPROTO_HOPOPTS:
{ {
static auto ip6_hopopts_type = zeek::id::find_type<zeek::RecordType>("ip6_hopopts"); static auto ip6_hopopts_type = id::find_type<RecordType>("ip6_hopopts");
rv = zeek::make_intrusive<zeek::RecordVal>(ip6_hopopts_type); rv = make_intrusive<RecordVal>(ip6_hopopts_type);
const struct ip6_hbh* hbh = (const struct ip6_hbh*)data; const struct ip6_hbh* hbh = (const struct ip6_hbh*)data;
rv->Assign(0, zeek::val_mgr->Count(hbh->ip6h_nxt)); rv->Assign(0, val_mgr->Count(hbh->ip6h_nxt));
rv->Assign(1, zeek::val_mgr->Count(hbh->ip6h_len)); rv->Assign(1, val_mgr->Count(hbh->ip6h_len));
uint16_t off = 2 * sizeof(uint8_t); uint16_t off = 2 * sizeof(uint8_t);
rv->Assign(2, BuildOptionsVal(data + off, Length() - off)); rv->Assign(2, BuildOptionsVal(data + off, Length() - off));
@ -90,11 +90,11 @@ zeek::RecordValPtr IPv6_Hdr::ToVal(zeek::VectorValPtr chain) const
case IPPROTO_DSTOPTS: case IPPROTO_DSTOPTS:
{ {
static auto ip6_dstopts_type = zeek::id::find_type<zeek::RecordType>("ip6_dstopts"); static auto ip6_dstopts_type = id::find_type<RecordType>("ip6_dstopts");
rv = zeek::make_intrusive<zeek::RecordVal>(ip6_dstopts_type); rv = make_intrusive<RecordVal>(ip6_dstopts_type);
const struct ip6_dest* dst = (const struct ip6_dest*)data; const struct ip6_dest* dst = (const struct ip6_dest*)data;
rv->Assign(0, zeek::val_mgr->Count(dst->ip6d_nxt)); rv->Assign(0, val_mgr->Count(dst->ip6d_nxt));
rv->Assign(1, zeek::val_mgr->Count(dst->ip6d_len)); rv->Assign(1, val_mgr->Count(dst->ip6d_len));
uint16_t off = 2 * sizeof(uint8_t); uint16_t off = 2 * sizeof(uint8_t);
rv->Assign(2, BuildOptionsVal(data + off, Length() - off)); rv->Assign(2, BuildOptionsVal(data + off, Length() - off));
} }
@ -102,95 +102,95 @@ zeek::RecordValPtr IPv6_Hdr::ToVal(zeek::VectorValPtr chain) const
case IPPROTO_ROUTING: case IPPROTO_ROUTING:
{ {
static auto ip6_routing_type = zeek::id::find_type<zeek::RecordType>("ip6_routing"); static auto ip6_routing_type = id::find_type<RecordType>("ip6_routing");
rv = zeek::make_intrusive<zeek::RecordVal>(ip6_routing_type); rv = make_intrusive<RecordVal>(ip6_routing_type);
const struct ip6_rthdr* rt = (const struct ip6_rthdr*)data; const struct ip6_rthdr* rt = (const struct ip6_rthdr*)data;
rv->Assign(0, zeek::val_mgr->Count(rt->ip6r_nxt)); rv->Assign(0, val_mgr->Count(rt->ip6r_nxt));
rv->Assign(1, zeek::val_mgr->Count(rt->ip6r_len)); rv->Assign(1, val_mgr->Count(rt->ip6r_len));
rv->Assign(2, zeek::val_mgr->Count(rt->ip6r_type)); rv->Assign(2, val_mgr->Count(rt->ip6r_type));
rv->Assign(3, zeek::val_mgr->Count(rt->ip6r_segleft)); rv->Assign(3, val_mgr->Count(rt->ip6r_segleft));
uint16_t off = 4 * sizeof(uint8_t); uint16_t off = 4 * sizeof(uint8_t);
rv->Assign(4, zeek::make_intrusive<zeek::StringVal>(new zeek::String(data + off, Length() - off, true))); rv->Assign(4, make_intrusive<StringVal>(new String(data + off, Length() - off, true)));
} }
break; break;
case IPPROTO_FRAGMENT: case IPPROTO_FRAGMENT:
{ {
static auto ip6_fragment_type = zeek::id::find_type<zeek::RecordType>("ip6_fragment"); static auto ip6_fragment_type = id::find_type<RecordType>("ip6_fragment");
rv = zeek::make_intrusive<zeek::RecordVal>(ip6_fragment_type); rv = make_intrusive<RecordVal>(ip6_fragment_type);
const struct ip6_frag* frag = (const struct ip6_frag*)data; const struct ip6_frag* frag = (const struct ip6_frag*)data;
rv->Assign(0, zeek::val_mgr->Count(frag->ip6f_nxt)); rv->Assign(0, val_mgr->Count(frag->ip6f_nxt));
rv->Assign(1, zeek::val_mgr->Count(frag->ip6f_reserved)); rv->Assign(1, val_mgr->Count(frag->ip6f_reserved));
rv->Assign(2, zeek::val_mgr->Count((ntohs(frag->ip6f_offlg) & 0xfff8)>>3)); rv->Assign(2, val_mgr->Count((ntohs(frag->ip6f_offlg) & 0xfff8)>>3));
rv->Assign(3, zeek::val_mgr->Count((ntohs(frag->ip6f_offlg) & 0x0006)>>1)); rv->Assign(3, val_mgr->Count((ntohs(frag->ip6f_offlg) & 0x0006)>>1));
rv->Assign(4, zeek::val_mgr->Bool(ntohs(frag->ip6f_offlg) & 0x0001)); rv->Assign(4, val_mgr->Bool(ntohs(frag->ip6f_offlg) & 0x0001));
rv->Assign(5, zeek::val_mgr->Count(ntohl(frag->ip6f_ident))); rv->Assign(5, val_mgr->Count(ntohl(frag->ip6f_ident)));
} }
break; break;
case IPPROTO_AH: case IPPROTO_AH:
{ {
static auto ip6_ah_type = zeek::id::find_type<zeek::RecordType>("ip6_ah"); static auto ip6_ah_type = id::find_type<RecordType>("ip6_ah");
rv = zeek::make_intrusive<zeek::RecordVal>(ip6_ah_type); rv = make_intrusive<RecordVal>(ip6_ah_type);
rv->Assign(0, zeek::val_mgr->Count(((ip6_ext*)data)->ip6e_nxt)); rv->Assign(0, val_mgr->Count(((ip6_ext*)data)->ip6e_nxt));
rv->Assign(1, zeek::val_mgr->Count(((ip6_ext*)data)->ip6e_len)); rv->Assign(1, val_mgr->Count(((ip6_ext*)data)->ip6e_len));
rv->Assign(2, zeek::val_mgr->Count(ntohs(((uint16_t*)data)[1]))); rv->Assign(2, val_mgr->Count(ntohs(((uint16_t*)data)[1])));
rv->Assign(3, zeek::val_mgr->Count(ntohl(((uint32_t*)data)[1]))); rv->Assign(3, val_mgr->Count(ntohl(((uint32_t*)data)[1])));
if ( Length() >= 12 ) if ( Length() >= 12 )
{ {
// Sequence Number and ICV fields can only be extracted if // Sequence Number and ICV fields can only be extracted if
// Payload Len was non-zero for this header. // Payload Len was non-zero for this header.
rv->Assign(4, zeek::val_mgr->Count(ntohl(((uint32_t*)data)[2]))); rv->Assign(4, val_mgr->Count(ntohl(((uint32_t*)data)[2])));
uint16_t off = 3 * sizeof(uint32_t); uint16_t off = 3 * sizeof(uint32_t);
rv->Assign(5, zeek::make_intrusive<zeek::StringVal>(new zeek::String(data + off, Length() - off, true))); rv->Assign(5, make_intrusive<StringVal>(new String(data + off, Length() - off, true)));
} }
} }
break; break;
case IPPROTO_ESP: case IPPROTO_ESP:
{ {
static auto ip6_esp_type = zeek::id::find_type<zeek::RecordType>("ip6_esp"); static auto ip6_esp_type = id::find_type<RecordType>("ip6_esp");
rv = zeek::make_intrusive<zeek::RecordVal>(ip6_esp_type); rv = make_intrusive<RecordVal>(ip6_esp_type);
const uint32_t* esp = (const uint32_t*)data; const uint32_t* esp = (const uint32_t*)data;
rv->Assign(0, zeek::val_mgr->Count(ntohl(esp[0]))); rv->Assign(0, val_mgr->Count(ntohl(esp[0])));
rv->Assign(1, zeek::val_mgr->Count(ntohl(esp[1]))); rv->Assign(1, val_mgr->Count(ntohl(esp[1])));
} }
break; break;
#ifdef ENABLE_MOBILE_IPV6 #ifdef ENABLE_MOBILE_IPV6
case IPPROTO_MOBILITY: case IPPROTO_MOBILITY:
{ {
static auto ip6_mob_type = zeek::id::find_type<zeek::RecordType>("ip6_mobility_hdr"); static auto ip6_mob_type = id::find_type<RecordType>("ip6_mobility_hdr");
rv = zeek::make_intrusive<zeek::RecordVal>(ip6_mob_type); rv = make_intrusive<RecordVal>(ip6_mob_type);
const struct ip6_mobility* mob = (const struct ip6_mobility*) data; const struct ip6_mobility* mob = (const struct ip6_mobility*) data;
rv->Assign(0, zeek::val_mgr->Count(mob->ip6mob_payload)); rv->Assign(0, val_mgr->Count(mob->ip6mob_payload));
rv->Assign(1, zeek::val_mgr->Count(mob->ip6mob_len)); rv->Assign(1, val_mgr->Count(mob->ip6mob_len));
rv->Assign(2, zeek::val_mgr->Count(mob->ip6mob_type)); rv->Assign(2, val_mgr->Count(mob->ip6mob_type));
rv->Assign(3, zeek::val_mgr->Count(mob->ip6mob_rsv)); rv->Assign(3, val_mgr->Count(mob->ip6mob_rsv));
rv->Assign(4, zeek::val_mgr->Count(ntohs(mob->ip6mob_chksum))); rv->Assign(4, val_mgr->Count(ntohs(mob->ip6mob_chksum)));
static auto ip6_mob_msg_type = zeek::id::find_type<zeek::RecordType>("ip6_mobility_msg"); static auto ip6_mob_msg_type = id::find_type<RecordType>("ip6_mobility_msg");
auto msg = zeek::make_intrusive<zeek::RecordVal>(ip6_mob_msg_type); auto msg = make_intrusive<RecordVal>(ip6_mob_msg_type);
msg->Assign(0, zeek::val_mgr->Count(mob->ip6mob_type)); msg->Assign(0, val_mgr->Count(mob->ip6mob_type));
uint16_t off = sizeof(ip6_mobility); uint16_t off = sizeof(ip6_mobility);
const u_char* msg_data = data + off; const u_char* msg_data = data + off;
static auto ip6_mob_brr_type = zeek::id::find_type<zeek::RecordType>("ip6_mobility_brr"); static auto ip6_mob_brr_type = id::find_type<RecordType>("ip6_mobility_brr");
static auto ip6_mob_hoti_type = zeek::id::find_type<zeek::RecordType>("ip6_mobility_hoti"); static auto ip6_mob_hoti_type = id::find_type<RecordType>("ip6_mobility_hoti");
static auto ip6_mob_coti_type = zeek::id::find_type<zeek::RecordType>("ip6_mobility_coti"); static auto ip6_mob_coti_type = id::find_type<RecordType>("ip6_mobility_coti");
static auto ip6_mob_hot_type = zeek::id::find_type<zeek::RecordType>("ip6_mobility_hot"); static auto ip6_mob_hot_type = id::find_type<RecordType>("ip6_mobility_hot");
static auto ip6_mob_cot_type = zeek::id::find_type<zeek::RecordType>("ip6_mobility_cot"); static auto ip6_mob_cot_type = id::find_type<RecordType>("ip6_mobility_cot");
static auto ip6_mob_bu_type = zeek::id::find_type<zeek::RecordType>("ip6_mobility_bu"); static auto ip6_mob_bu_type = id::find_type<RecordType>("ip6_mobility_bu");
static auto ip6_mob_back_type = zeek::id::find_type<zeek::RecordType>("ip6_mobility_back"); static auto ip6_mob_back_type = id::find_type<RecordType>("ip6_mobility_back");
static auto ip6_mob_be_type = zeek::id::find_type<zeek::RecordType>("ip6_mobility_be"); static auto ip6_mob_be_type = id::find_type<RecordType>("ip6_mobility_be");
switch ( mob->ip6mob_type ) { switch ( mob->ip6mob_type ) {
case 0: case 0:
{ {
auto m = zeek::make_intrusive<zeek::RecordVal>(ip6_mob_brr_type); auto m = make_intrusive<RecordVal>(ip6_mob_brr_type);
m->Assign(0, zeek::val_mgr->Count(ntohs(*((uint16_t*)msg_data)))); m->Assign(0, val_mgr->Count(ntohs(*((uint16_t*)msg_data))));
off += sizeof(uint16_t); off += sizeof(uint16_t);
m->Assign(1, BuildOptionsVal(data + off, Length() - off)); m->Assign(1, BuildOptionsVal(data + off, Length() - off));
msg->Assign(1, std::move(m)); msg->Assign(1, std::move(m));
@ -199,9 +199,9 @@ zeek::RecordValPtr IPv6_Hdr::ToVal(zeek::VectorValPtr chain) const
case 1: case 1:
{ {
auto m = zeek::make_intrusive<zeek::RecordVal>(ip6_mob_hoti_type); auto m = make_intrusive<RecordVal>(ip6_mob_hoti_type);
m->Assign(0, zeek::val_mgr->Count(ntohs(*((uint16_t*)msg_data)))); m->Assign(0, val_mgr->Count(ntohs(*((uint16_t*)msg_data))));
m->Assign(1, zeek::val_mgr->Count(ntohll(*((uint64_t*)(msg_data + sizeof(uint16_t)))))); m->Assign(1, val_mgr->Count(ntohll(*((uint64_t*)(msg_data + sizeof(uint16_t))))));
off += sizeof(uint16_t) + sizeof(uint64_t); off += sizeof(uint16_t) + sizeof(uint64_t);
m->Assign(2, BuildOptionsVal(data + off, Length() - off)); m->Assign(2, BuildOptionsVal(data + off, Length() - off));
msg->Assign(2, std::move(m)); msg->Assign(2, std::move(m));
@ -210,9 +210,9 @@ zeek::RecordValPtr IPv6_Hdr::ToVal(zeek::VectorValPtr chain) const
case 2: case 2:
{ {
auto m = zeek::make_intrusive<zeek::RecordVal>(ip6_mob_coti_type); auto m = make_intrusive<RecordVal>(ip6_mob_coti_type);
m->Assign(0, zeek::val_mgr->Count(ntohs(*((uint16_t*)msg_data)))); m->Assign(0, val_mgr->Count(ntohs(*((uint16_t*)msg_data))));
m->Assign(1, zeek::val_mgr->Count(ntohll(*((uint64_t*)(msg_data + sizeof(uint16_t)))))); m->Assign(1, val_mgr->Count(ntohll(*((uint64_t*)(msg_data + sizeof(uint16_t))))));
off += sizeof(uint16_t) + sizeof(uint64_t); off += sizeof(uint16_t) + sizeof(uint64_t);
m->Assign(2, BuildOptionsVal(data + off, Length() - off)); m->Assign(2, BuildOptionsVal(data + off, Length() - off));
msg->Assign(3, std::move(m)); msg->Assign(3, std::move(m));
@ -221,10 +221,10 @@ zeek::RecordValPtr IPv6_Hdr::ToVal(zeek::VectorValPtr chain) const
case 3: case 3:
{ {
auto m = zeek::make_intrusive<zeek::RecordVal>(ip6_mob_hot_type); auto m = make_intrusive<RecordVal>(ip6_mob_hot_type);
m->Assign(0, zeek::val_mgr->Count(ntohs(*((uint16_t*)msg_data)))); m->Assign(0, val_mgr->Count(ntohs(*((uint16_t*)msg_data))));
m->Assign(1, zeek::val_mgr->Count(ntohll(*((uint64_t*)(msg_data + sizeof(uint16_t)))))); m->Assign(1, val_mgr->Count(ntohll(*((uint64_t*)(msg_data + sizeof(uint16_t))))));
m->Assign(2, zeek::val_mgr->Count(ntohll(*((uint64_t*)(msg_data + sizeof(uint16_t) + sizeof(uint64_t)))))); m->Assign(2, val_mgr->Count(ntohll(*((uint64_t*)(msg_data + sizeof(uint16_t) + sizeof(uint64_t))))));
off += sizeof(uint16_t) + 2 * sizeof(uint64_t); off += sizeof(uint16_t) + 2 * sizeof(uint64_t);
m->Assign(3, BuildOptionsVal(data + off, Length() - off)); m->Assign(3, BuildOptionsVal(data + off, Length() - off));
msg->Assign(4, std::move(m)); msg->Assign(4, std::move(m));
@ -233,10 +233,10 @@ zeek::RecordValPtr IPv6_Hdr::ToVal(zeek::VectorValPtr chain) const
case 4: case 4:
{ {
auto m = zeek::make_intrusive<zeek::RecordVal>(ip6_mob_cot_type); auto m = make_intrusive<RecordVal>(ip6_mob_cot_type);
m->Assign(0, zeek::val_mgr->Count(ntohs(*((uint16_t*)msg_data)))); m->Assign(0, val_mgr->Count(ntohs(*((uint16_t*)msg_data))));
m->Assign(1, zeek::val_mgr->Count(ntohll(*((uint64_t*)(msg_data + sizeof(uint16_t)))))); m->Assign(1, val_mgr->Count(ntohll(*((uint64_t*)(msg_data + sizeof(uint16_t))))));
m->Assign(2, zeek::val_mgr->Count(ntohll(*((uint64_t*)(msg_data + sizeof(uint16_t) + sizeof(uint64_t)))))); m->Assign(2, val_mgr->Count(ntohll(*((uint64_t*)(msg_data + sizeof(uint16_t) + sizeof(uint64_t))))));
off += sizeof(uint16_t) + 2 * sizeof(uint64_t); off += sizeof(uint16_t) + 2 * sizeof(uint64_t);
m->Assign(3, BuildOptionsVal(data + off, Length() - off)); m->Assign(3, BuildOptionsVal(data + off, Length() - off));
msg->Assign(5, std::move(m)); msg->Assign(5, std::move(m));
@ -245,13 +245,13 @@ zeek::RecordValPtr IPv6_Hdr::ToVal(zeek::VectorValPtr chain) const
case 5: case 5:
{ {
auto m = zeek::make_intrusive<zeek::RecordVal>(ip6_mob_bu_type); auto m = make_intrusive<RecordVal>(ip6_mob_bu_type);
m->Assign(0, zeek::val_mgr->Count(ntohs(*((uint16_t*)msg_data)))); m->Assign(0, val_mgr->Count(ntohs(*((uint16_t*)msg_data))));
m->Assign(1, zeek::val_mgr->Bool(ntohs(*((uint16_t*)(msg_data + sizeof(uint16_t)))) & 0x8000)); m->Assign(1, val_mgr->Bool(ntohs(*((uint16_t*)(msg_data + sizeof(uint16_t)))) & 0x8000));
m->Assign(2, zeek::val_mgr->Bool(ntohs(*((uint16_t*)(msg_data + sizeof(uint16_t)))) & 0x4000)); m->Assign(2, val_mgr->Bool(ntohs(*((uint16_t*)(msg_data + sizeof(uint16_t)))) & 0x4000));
m->Assign(3, zeek::val_mgr->Bool(ntohs(*((uint16_t*)(msg_data + sizeof(uint16_t)))) & 0x2000)); m->Assign(3, val_mgr->Bool(ntohs(*((uint16_t*)(msg_data + sizeof(uint16_t)))) & 0x2000));
m->Assign(4, zeek::val_mgr->Bool(ntohs(*((uint16_t*)(msg_data + sizeof(uint16_t)))) & 0x1000)); m->Assign(4, val_mgr->Bool(ntohs(*((uint16_t*)(msg_data + sizeof(uint16_t)))) & 0x1000));
m->Assign(5, zeek::val_mgr->Count(ntohs(*((uint16_t*)(msg_data + 2*sizeof(uint16_t)))))); m->Assign(5, val_mgr->Count(ntohs(*((uint16_t*)(msg_data + 2*sizeof(uint16_t))))));
off += 3 * sizeof(uint16_t); off += 3 * sizeof(uint16_t);
m->Assign(6, BuildOptionsVal(data + off, Length() - off)); m->Assign(6, BuildOptionsVal(data + off, Length() - off));
msg->Assign(6, std::move(m)); msg->Assign(6, std::move(m));
@ -260,11 +260,11 @@ zeek::RecordValPtr IPv6_Hdr::ToVal(zeek::VectorValPtr chain) const
case 6: case 6:
{ {
auto m = zeek::make_intrusive<zeek::RecordVal>(ip6_mob_back_type); auto m = make_intrusive<RecordVal>(ip6_mob_back_type);
m->Assign(0, zeek::val_mgr->Count(*((uint8_t*)msg_data))); m->Assign(0, val_mgr->Count(*((uint8_t*)msg_data)));
m->Assign(1, zeek::val_mgr->Bool(*((uint8_t*)(msg_data + sizeof(uint8_t))) & 0x80)); m->Assign(1, val_mgr->Bool(*((uint8_t*)(msg_data + sizeof(uint8_t))) & 0x80));
m->Assign(2, zeek::val_mgr->Count(ntohs(*((uint16_t*)(msg_data + sizeof(uint16_t)))))); m->Assign(2, val_mgr->Count(ntohs(*((uint16_t*)(msg_data + sizeof(uint16_t))))));
m->Assign(3, zeek::val_mgr->Count(ntohs(*((uint16_t*)(msg_data + 2*sizeof(uint16_t)))))); m->Assign(3, val_mgr->Count(ntohs(*((uint16_t*)(msg_data + 2*sizeof(uint16_t))))));
off += 3 * sizeof(uint16_t); off += 3 * sizeof(uint16_t);
m->Assign(4, BuildOptionsVal(data + off, Length() - off)); m->Assign(4, BuildOptionsVal(data + off, Length() - off));
msg->Assign(7, std::move(m)); msg->Assign(7, std::move(m));
@ -273,10 +273,10 @@ zeek::RecordValPtr IPv6_Hdr::ToVal(zeek::VectorValPtr chain) const
case 7: case 7:
{ {
auto m = zeek::make_intrusive<zeek::RecordVal>(ip6_mob_be_type); auto m = make_intrusive<RecordVal>(ip6_mob_be_type);
m->Assign(0, zeek::val_mgr->Count(*((uint8_t*)msg_data))); m->Assign(0, val_mgr->Count(*((uint8_t*)msg_data)));
const in6_addr* hoa = (const in6_addr*)(msg_data + sizeof(uint16_t)); const in6_addr* hoa = (const in6_addr*)(msg_data + sizeof(uint16_t));
m->Assign(1, zeek::make_intrusive<zeek::AddrVal>(IPAddr(*hoa))); m->Assign(1, make_intrusive<AddrVal>(IPAddr(*hoa)));
off += sizeof(uint16_t) + sizeof(in6_addr); off += sizeof(uint16_t) + sizeof(in6_addr);
m->Assign(2, BuildOptionsVal(data + off, Length() - off)); m->Assign(2, BuildOptionsVal(data + off, Length() - off));
msg->Assign(8, std::move(m)); msg->Assign(8, std::move(m));
@ -284,7 +284,7 @@ zeek::RecordValPtr IPv6_Hdr::ToVal(zeek::VectorValPtr chain) const
} }
default: default:
zeek::reporter->Weird("unknown_mobility_type", zeek::util::fmt("%d", mob->ip6mob_type)); reporter->Weird("unknown_mobility_type", util::fmt("%d", mob->ip6mob_type));
break; break;
} }
@ -300,12 +300,12 @@ zeek::RecordValPtr IPv6_Hdr::ToVal(zeek::VectorValPtr chain) const
return rv; return rv;
} }
zeek::RecordValPtr IPv6_Hdr::ToVal() const RecordValPtr IPv6_Hdr::ToVal() const
{ return ToVal(nullptr); } { return ToVal(nullptr); }
zeek::RecordVal* IPv6_Hdr::BuildRecordVal(zeek::VectorVal* chain) const RecordVal* IPv6_Hdr::BuildRecordVal(VectorVal* chain) const
{ {
return ToVal({zeek::AdoptRef{}, chain}).release(); return ToVal({AdoptRef{}, chain}).release();
} }
IPAddr IP_Hdr::IPHeaderSrcAddr() const IPAddr IP_Hdr::IPHeaderSrcAddr() const
@ -328,22 +328,22 @@ IPAddr IP_Hdr::DstAddr() const
return ip4 ? IPAddr(ip4->ip_dst) : ip6_hdrs->DstAddr(); return ip4 ? IPAddr(ip4->ip_dst) : ip6_hdrs->DstAddr();
} }
zeek::RecordValPtr IP_Hdr::ToIPHdrVal() const RecordValPtr IP_Hdr::ToIPHdrVal() const
{ {
zeek::RecordValPtr rval; RecordValPtr rval;
if ( ip4 ) if ( ip4 )
{ {
static auto ip4_hdr_type = zeek::id::find_type<zeek::RecordType>("ip4_hdr"); static auto ip4_hdr_type = id::find_type<RecordType>("ip4_hdr");
rval = zeek::make_intrusive<zeek::RecordVal>(ip4_hdr_type); rval = make_intrusive<RecordVal>(ip4_hdr_type);
rval->Assign(0, zeek::val_mgr->Count(ip4->ip_hl * 4)); rval->Assign(0, val_mgr->Count(ip4->ip_hl * 4));
rval->Assign(1, zeek::val_mgr->Count(ip4->ip_tos)); rval->Assign(1, val_mgr->Count(ip4->ip_tos));
rval->Assign(2, zeek::val_mgr->Count(ntohs(ip4->ip_len))); rval->Assign(2, val_mgr->Count(ntohs(ip4->ip_len)));
rval->Assign(3, zeek::val_mgr->Count(ntohs(ip4->ip_id))); rval->Assign(3, val_mgr->Count(ntohs(ip4->ip_id)));
rval->Assign(4, zeek::val_mgr->Count(ip4->ip_ttl)); rval->Assign(4, val_mgr->Count(ip4->ip_ttl));
rval->Assign(5, zeek::val_mgr->Count(ip4->ip_p)); rval->Assign(5, val_mgr->Count(ip4->ip_p));
rval->Assign(6, zeek::make_intrusive<zeek::AddrVal>(ip4->ip_src.s_addr)); rval->Assign(6, make_intrusive<AddrVal>(ip4->ip_src.s_addr));
rval->Assign(7, zeek::make_intrusive<zeek::AddrVal>(ip4->ip_dst.s_addr)); rval->Assign(7, make_intrusive<AddrVal>(ip4->ip_dst.s_addr));
} }
else else
{ {
@ -353,27 +353,27 @@ zeek::RecordValPtr IP_Hdr::ToIPHdrVal() const
return rval; return rval;
} }
zeek::RecordVal* IP_Hdr::BuildIPHdrVal() const RecordVal* IP_Hdr::BuildIPHdrVal() const
{ {
return ToIPHdrVal().release(); return ToIPHdrVal().release();
} }
zeek::RecordValPtr IP_Hdr::ToPktHdrVal() const RecordValPtr IP_Hdr::ToPktHdrVal() const
{ {
static auto pkt_hdr_type = zeek::id::find_type<zeek::RecordType>("pkt_hdr"); static auto pkt_hdr_type = id::find_type<RecordType>("pkt_hdr");
return ToPktHdrVal(zeek::make_intrusive<zeek::RecordVal>(pkt_hdr_type), 0); return ToPktHdrVal(make_intrusive<RecordVal>(pkt_hdr_type), 0);
} }
zeek::RecordVal* IP_Hdr::BuildPktHdrVal() const RecordVal* IP_Hdr::BuildPktHdrVal() const
{ {
return ToPktHdrVal().release(); return ToPktHdrVal().release();
} }
zeek::RecordValPtr IP_Hdr::ToPktHdrVal(zeek::RecordValPtr pkt_hdr, int sindex) const RecordValPtr IP_Hdr::ToPktHdrVal(RecordValPtr pkt_hdr, int sindex) const
{ {
static auto tcp_hdr_type = zeek::id::find_type<zeek::RecordType>("tcp_hdr"); static auto tcp_hdr_type = id::find_type<RecordType>("tcp_hdr");
static auto udp_hdr_type = zeek::id::find_type<zeek::RecordType>("udp_hdr"); static auto udp_hdr_type = id::find_type<RecordType>("udp_hdr");
static auto icmp_hdr_type = zeek::id::find_type<zeek::RecordType>("icmp_hdr"); static auto icmp_hdr_type = id::find_type<RecordType>("icmp_hdr");
if ( ip4 ) if ( ip4 )
pkt_hdr->Assign(sindex + 0, ToIPHdrVal()); pkt_hdr->Assign(sindex + 0, ToIPHdrVal());
@ -388,20 +388,20 @@ zeek::RecordValPtr IP_Hdr::ToPktHdrVal(zeek::RecordValPtr pkt_hdr, int sindex) c
case IPPROTO_TCP: case IPPROTO_TCP:
{ {
const struct tcphdr* tp = (const struct tcphdr*) data; const struct tcphdr* tp = (const struct tcphdr*) data;
auto tcp_hdr = zeek::make_intrusive<zeek::RecordVal>(tcp_hdr_type); auto tcp_hdr = make_intrusive<RecordVal>(tcp_hdr_type);
int tcp_hdr_len = tp->th_off * 4; int tcp_hdr_len = tp->th_off * 4;
int data_len = PayloadLen() - tcp_hdr_len; int data_len = PayloadLen() - tcp_hdr_len;
tcp_hdr->Assign(0, zeek::val_mgr->Port(ntohs(tp->th_sport), TRANSPORT_TCP)); tcp_hdr->Assign(0, val_mgr->Port(ntohs(tp->th_sport), TRANSPORT_TCP));
tcp_hdr->Assign(1, zeek::val_mgr->Port(ntohs(tp->th_dport), TRANSPORT_TCP)); tcp_hdr->Assign(1, val_mgr->Port(ntohs(tp->th_dport), TRANSPORT_TCP));
tcp_hdr->Assign(2, zeek::val_mgr->Count(uint32_t(ntohl(tp->th_seq)))); tcp_hdr->Assign(2, val_mgr->Count(uint32_t(ntohl(tp->th_seq))));
tcp_hdr->Assign(3, zeek::val_mgr->Count(uint32_t(ntohl(tp->th_ack)))); tcp_hdr->Assign(3, val_mgr->Count(uint32_t(ntohl(tp->th_ack))));
tcp_hdr->Assign(4, zeek::val_mgr->Count(tcp_hdr_len)); tcp_hdr->Assign(4, val_mgr->Count(tcp_hdr_len));
tcp_hdr->Assign(5, zeek::val_mgr->Count(data_len)); tcp_hdr->Assign(5, val_mgr->Count(data_len));
tcp_hdr->Assign(6, zeek::val_mgr->Count(tp->th_x2)); tcp_hdr->Assign(6, val_mgr->Count(tp->th_x2));
tcp_hdr->Assign(7, zeek::val_mgr->Count(tp->th_flags)); tcp_hdr->Assign(7, val_mgr->Count(tp->th_flags));
tcp_hdr->Assign(8, zeek::val_mgr->Count(ntohs(tp->th_win))); tcp_hdr->Assign(8, val_mgr->Count(ntohs(tp->th_win)));
pkt_hdr->Assign(sindex + 2, std::move(tcp_hdr)); pkt_hdr->Assign(sindex + 2, std::move(tcp_hdr));
break; break;
@ -410,11 +410,11 @@ zeek::RecordValPtr IP_Hdr::ToPktHdrVal(zeek::RecordValPtr pkt_hdr, int sindex) c
case IPPROTO_UDP: case IPPROTO_UDP:
{ {
const struct udphdr* up = (const struct udphdr*) data; const struct udphdr* up = (const struct udphdr*) data;
auto udp_hdr = zeek::make_intrusive<zeek::RecordVal>(udp_hdr_type); auto udp_hdr = make_intrusive<RecordVal>(udp_hdr_type);
udp_hdr->Assign(0, zeek::val_mgr->Port(ntohs(up->uh_sport), TRANSPORT_UDP)); udp_hdr->Assign(0, val_mgr->Port(ntohs(up->uh_sport), TRANSPORT_UDP));
udp_hdr->Assign(1, zeek::val_mgr->Port(ntohs(up->uh_dport), TRANSPORT_UDP)); udp_hdr->Assign(1, val_mgr->Port(ntohs(up->uh_dport), TRANSPORT_UDP));
udp_hdr->Assign(2, zeek::val_mgr->Count(ntohs(up->uh_ulen))); udp_hdr->Assign(2, val_mgr->Count(ntohs(up->uh_ulen)));
pkt_hdr->Assign(sindex + 3, std::move(udp_hdr)); pkt_hdr->Assign(sindex + 3, std::move(udp_hdr));
break; break;
@ -423,9 +423,9 @@ zeek::RecordValPtr IP_Hdr::ToPktHdrVal(zeek::RecordValPtr pkt_hdr, int sindex) c
case IPPROTO_ICMP: case IPPROTO_ICMP:
{ {
const struct icmp* icmpp = (const struct icmp *) data; const struct icmp* icmpp = (const struct icmp *) data;
auto icmp_hdr = zeek::make_intrusive<zeek::RecordVal>(icmp_hdr_type); auto icmp_hdr = make_intrusive<RecordVal>(icmp_hdr_type);
icmp_hdr->Assign(0, zeek::val_mgr->Count(icmpp->icmp_type)); icmp_hdr->Assign(0, val_mgr->Count(icmpp->icmp_type));
pkt_hdr->Assign(sindex + 4, std::move(icmp_hdr)); pkt_hdr->Assign(sindex + 4, std::move(icmp_hdr));
break; break;
@ -434,9 +434,9 @@ zeek::RecordValPtr IP_Hdr::ToPktHdrVal(zeek::RecordValPtr pkt_hdr, int sindex) c
case IPPROTO_ICMPV6: case IPPROTO_ICMPV6:
{ {
const struct icmp6_hdr* icmpp = (const struct icmp6_hdr*) data; const struct icmp6_hdr* icmpp = (const struct icmp6_hdr*) data;
auto icmp_hdr = zeek::make_intrusive<zeek::RecordVal>(icmp_hdr_type); auto icmp_hdr = make_intrusive<RecordVal>(icmp_hdr_type);
icmp_hdr->Assign(0, zeek::val_mgr->Count(icmpp->icmp6_type)); icmp_hdr->Assign(0, val_mgr->Count(icmpp->icmp6_type));
pkt_hdr->Assign(sindex + 4, std::move(icmp_hdr)); pkt_hdr->Assign(sindex + 4, std::move(icmp_hdr));
break; break;
@ -452,9 +452,9 @@ zeek::RecordValPtr IP_Hdr::ToPktHdrVal(zeek::RecordValPtr pkt_hdr, int sindex) c
return pkt_hdr; return pkt_hdr;
} }
zeek::RecordVal* IP_Hdr::BuildPktHdrVal(zeek::RecordVal* pkt_hdr, int sindex) const RecordVal* IP_Hdr::BuildPktHdrVal(RecordVal* pkt_hdr, int sindex) const
{ {
return ToPktHdrVal({zeek::AdoptRef{}, pkt_hdr}, sindex).release(); return ToPktHdrVal({AdoptRef{}, pkt_hdr}, sindex).release();
} }
static inline bool isIPv6ExtHeader(uint8_t type) static inline bool isIPv6ExtHeader(uint8_t type)
@ -494,7 +494,7 @@ void IPv6_Hdr_Chain::Init(const struct ip6_hdr* ip6, int total_len,
if ( total_len < (int)sizeof(struct ip6_hdr) ) if ( total_len < (int)sizeof(struct ip6_hdr) )
{ {
zeek::reporter->InternalWarning("truncated IP header in IPv6_HdrChain::Init"); reporter->InternalWarning("truncated IP header in IPv6_HdrChain::Init");
return; return;
} }
@ -552,7 +552,7 @@ bool IPv6_Hdr_Chain::IsFragment() const
{ {
if ( chain.empty() ) if ( chain.empty() )
{ {
zeek::reporter->InternalWarning("empty IPv6 header chain"); reporter->InternalWarning("empty IPv6 header chain");
return false; return false;
} }
@ -567,7 +567,7 @@ IPAddr IPv6_Hdr_Chain::SrcAddr() const
#endif #endif
if ( chain.empty() ) if ( chain.empty() )
{ {
zeek::reporter->InternalWarning("empty IPv6 header chain"); reporter->InternalWarning("empty IPv6 header chain");
return IPAddr(); return IPAddr();
} }
@ -581,7 +581,7 @@ IPAddr IPv6_Hdr_Chain::DstAddr() const
if ( chain.empty() ) if ( chain.empty() )
{ {
zeek::reporter->InternalWarning("empty IPv6 header chain"); reporter->InternalWarning("empty IPv6 header chain");
return IPAddr(); return IPAddr();
} }
@ -593,7 +593,7 @@ void IPv6_Hdr_Chain::ProcessRoutingHeader(const struct ip6_rthdr* r, uint16_t le
if ( finalDst ) if ( finalDst )
{ {
// RFC 2460 section 4.1 says Routing should occur at most once. // RFC 2460 section 4.1 says Routing should occur at most once.
zeek::reporter->Weird(SrcAddr(), DstAddr(), "multiple_routing_headers"); reporter->Weird(SrcAddr(), DstAddr(), "multiple_routing_headers");
return; return;
} }
@ -608,11 +608,11 @@ void IPv6_Hdr_Chain::ProcessRoutingHeader(const struct ip6_rthdr* r, uint16_t le
if ( r->ip6r_len % 2 == 0 ) if ( r->ip6r_len % 2 == 0 )
finalDst = new IPAddr(*addr); finalDst = new IPAddr(*addr);
else else
zeek::reporter->Weird(SrcAddr(), DstAddr(), "odd_routing0_len"); reporter->Weird(SrcAddr(), DstAddr(), "odd_routing0_len");
} }
// Always raise a weird since this type is deprecated. // Always raise a weird since this type is deprecated.
zeek::reporter->Weird(SrcAddr(), DstAddr(), "routing0_hdr"); reporter->Weird(SrcAddr(), DstAddr(), "routing0_hdr");
} }
break; break;
@ -624,15 +624,15 @@ void IPv6_Hdr_Chain::ProcessRoutingHeader(const struct ip6_rthdr* r, uint16_t le
if ( r->ip6r_len == 2 ) if ( r->ip6r_len == 2 )
finalDst = new IPAddr(*addr); finalDst = new IPAddr(*addr);
else else
zeek::reporter->Weird(SrcAddr(), DstAddr(), "bad_routing2_len"); reporter->Weird(SrcAddr(), DstAddr(), "bad_routing2_len");
} }
} }
break; break;
#endif #endif
default: default:
zeek::reporter->Weird(SrcAddr(), DstAddr(), "unknown_routing_type", reporter->Weird(SrcAddr(), DstAddr(), "unknown_routing_type",
zeek::util::fmt("%d", r->ip6r_type)); util::fmt("%d", r->ip6r_type));
break; break;
} }
} }
@ -652,11 +652,11 @@ void IPv6_Hdr_Chain::ProcessDstOpts(const struct ip6_dest* d, uint16_t len)
{ {
if ( opt->ip6o_len == 16 ) if ( opt->ip6o_len == 16 )
if ( homeAddr ) if ( homeAddr )
zeek::reporter->Weird(SrcAddr(), DstAddr(), "multiple_home_addr_opts"); reporter->Weird(SrcAddr(), DstAddr(), "multiple_home_addr_opts");
else else
homeAddr = new IPAddr(*((const in6_addr*)(data + 2))); homeAddr = new IPAddr(*((const in6_addr*)(data + 2)));
else else
zeek::reporter->Weird(SrcAddr(), DstAddr(), "bad_home_addr_len"); reporter->Weird(SrcAddr(), DstAddr(), "bad_home_addr_len");
} }
break; break;
@ -678,24 +678,24 @@ void IPv6_Hdr_Chain::ProcessDstOpts(const struct ip6_dest* d, uint16_t len)
} }
#endif #endif
zeek::VectorValPtr IPv6_Hdr_Chain::ToVal() const VectorValPtr IPv6_Hdr_Chain::ToVal() const
{ {
static auto ip6_ext_hdr_type = zeek::id::find_type<zeek::RecordType>("ip6_ext_hdr"); static auto ip6_ext_hdr_type = id::find_type<RecordType>("ip6_ext_hdr");
static auto ip6_hopopts_type = zeek::id::find_type<zeek::RecordType>("ip6_hopopts"); static auto ip6_hopopts_type = id::find_type<RecordType>("ip6_hopopts");
static auto ip6_dstopts_type = zeek::id::find_type<zeek::RecordType>("ip6_dstopts"); static auto ip6_dstopts_type = id::find_type<RecordType>("ip6_dstopts");
static auto ip6_routing_type = zeek::id::find_type<zeek::RecordType>("ip6_routing"); static auto ip6_routing_type = id::find_type<RecordType>("ip6_routing");
static auto ip6_fragment_type = zeek::id::find_type<zeek::RecordType>("ip6_fragment"); static auto ip6_fragment_type = id::find_type<RecordType>("ip6_fragment");
static auto ip6_ah_type = zeek::id::find_type<zeek::RecordType>("ip6_ah"); static auto ip6_ah_type = id::find_type<RecordType>("ip6_ah");
static auto ip6_esp_type = zeek::id::find_type<zeek::RecordType>("ip6_esp"); static auto ip6_esp_type = id::find_type<RecordType>("ip6_esp");
static auto ip6_ext_hdr_chain_type = zeek::id::find_type<zeek::VectorType>("ip6_ext_hdr_chain"); static auto ip6_ext_hdr_chain_type = id::find_type<VectorType>("ip6_ext_hdr_chain");
auto rval = zeek::make_intrusive<zeek::VectorVal>(ip6_ext_hdr_chain_type); auto rval = make_intrusive<VectorVal>(ip6_ext_hdr_chain_type);
for ( size_t i = 1; i < chain.size(); ++i ) for ( size_t i = 1; i < chain.size(); ++i )
{ {
auto v = chain[i]->ToVal(); auto v = chain[i]->ToVal();
auto ext_hdr = zeek::make_intrusive<zeek::RecordVal>(ip6_ext_hdr_type); auto ext_hdr = make_intrusive<RecordVal>(ip6_ext_hdr_type);
uint8_t type = chain[i]->Type(); uint8_t type = chain[i]->Type();
ext_hdr->Assign(0, zeek::val_mgr->Count(type)); ext_hdr->Assign(0, val_mgr->Count(type));
switch (type) { switch (type) {
case IPPROTO_HOPOPTS: case IPPROTO_HOPOPTS:
@ -722,7 +722,7 @@ zeek::VectorValPtr IPv6_Hdr_Chain::ToVal() const
break; break;
#endif #endif
default: default:
zeek::reporter->InternalWarning("IPv6_Hdr_Chain bad header %d", type); reporter->InternalWarning("IPv6_Hdr_Chain bad header %d", type);
continue; continue;
} }
@ -732,7 +732,7 @@ zeek::VectorValPtr IPv6_Hdr_Chain::ToVal() const
return rval; return rval;
} }
zeek::VectorVal* IPv6_Hdr_Chain::BuildVal() const VectorVal* IPv6_Hdr_Chain::BuildVal() const
{ {
return ToVal().release(); return ToVal().release();
} }
@ -768,7 +768,7 @@ IPv6_Hdr_Chain* IPv6_Hdr_Chain::Copy(const ip6_hdr* new_hdr) const
if ( chain.empty() ) if ( chain.empty() )
{ {
zeek::reporter->InternalWarning("empty IPv6 header chain"); reporter->InternalWarning("empty IPv6 header chain");
delete rval; delete rval;
return nullptr; return nullptr;
} }

View file

@ -22,8 +22,8 @@ ZEEK_FORWARD_DECLARE_NAMESPACED(VectorVal, zeek);
ZEEK_FORWARD_DECLARE_NAMESPACED(FragReassembler, zeek::detail); ZEEK_FORWARD_DECLARE_NAMESPACED(FragReassembler, zeek::detail);
namespace zeek { namespace zeek {
using RecordValPtr = zeek::IntrusivePtr<RecordVal>; using RecordValPtr = IntrusivePtr<RecordVal>;
using VectorValPtr = zeek::IntrusivePtr<VectorVal>; using VectorValPtr = IntrusivePtr<VectorVal>;
#ifdef ENABLE_MOBILE_IPV6 #ifdef ENABLE_MOBILE_IPV6
@ -141,11 +141,11 @@ public:
/** /**
* Returns the script-layer record representation of the header. * Returns the script-layer record representation of the header.
*/ */
zeek::RecordValPtr ToVal(zeek::VectorValPtr chain) const; RecordValPtr ToVal(VectorValPtr chain) const;
zeek::RecordValPtr ToVal() const; RecordValPtr ToVal() const;
[[deprecated("Remove in v4.1. Use ToVal() instead.")]] [[deprecated("Remove in v4.1. Use ToVal() instead.")]]
zeek::RecordVal* BuildRecordVal(zeek::VectorVal* chain = nullptr) const; RecordVal* BuildRecordVal(VectorVal* chain = nullptr) const;
protected: protected:
uint8_t type; uint8_t type;
@ -221,23 +221,23 @@ public:
* option as defined by Mobile IPv6 (RFC 6275), then return it, else * option as defined by Mobile IPv6 (RFC 6275), then return it, else
* return the source address in the main IPv6 header. * return the source address in the main IPv6 header.
*/ */
zeek::IPAddr SrcAddr() const; IPAddr SrcAddr() const;
/** /**
* If the chain contains a Routing header with non-zero segments left, * If the chain contains a Routing header with non-zero segments left,
* then return the last address of the first such header, else return * then return the last address of the first such header, else return
* the destination address of the main IPv6 header. * the destination address of the main IPv6 header.
*/ */
zeek::IPAddr DstAddr() const; IPAddr DstAddr() const;
/** /**
* Returns a vector of ip6_ext_hdr RecordVals that includes script-layer * Returns a vector of ip6_ext_hdr RecordVals that includes script-layer
* representation of all extension headers in the chain. * representation of all extension headers in the chain.
*/ */
zeek::VectorValPtr ToVal() const; VectorValPtr ToVal() const;
[[deprecated("Remove in v4.1. Use ToVal() instead.")]] [[deprecated("Remove in v4.1. Use ToVal() instead.")]]
zeek::VectorVal* BuildVal() const; VectorVal* BuildVal() const;
protected: protected:
// for access to protected ctor that changes next header values that // for access to protected ctor that changes next header values that
@ -286,14 +286,14 @@ protected:
/** /**
* Home Address of the packet's source as defined by Mobile IPv6 (RFC 6275). * Home Address of the packet's source as defined by Mobile IPv6 (RFC 6275).
*/ */
zeek::IPAddr* homeAddr = nullptr; IPAddr* homeAddr = nullptr;
#endif #endif
/** /**
* The final destination address in chain's first Routing header that has * The final destination address in chain's first Routing header that has
* non-zero segments left. * non-zero segments left.
*/ */
zeek::IPAddr* finalDst = nullptr; IPAddr* finalDst = nullptr;
}; };
/** /**
@ -365,19 +365,19 @@ public:
/** /**
* Returns the source address held in the IP header. * Returns the source address held in the IP header.
*/ */
zeek::IPAddr IPHeaderSrcAddr() const; IPAddr IPHeaderSrcAddr() const;
/** /**
* Returns the destination address held in the IP header. * Returns the destination address held in the IP header.
*/ */
zeek::IPAddr IPHeaderDstAddr() const; IPAddr IPHeaderDstAddr() const;
/** /**
* For IPv4 or IPv6 headers that don't contain a Home Address option * For IPv4 or IPv6 headers that don't contain a Home Address option
* (Mobile IPv6, RFC 6275), return source address held in the IP header. * (Mobile IPv6, RFC 6275), return source address held in the IP header.
* For IPv6 headers that contain a Home Address option, return that address. * For IPv6 headers that contain a Home Address option, return that address.
*/ */
zeek::IPAddr SrcAddr() const; IPAddr SrcAddr() const;
/** /**
* For IPv4 or IPv6 headers that don't contain a Routing header with * For IPv4 or IPv6 headers that don't contain a Routing header with
@ -385,7 +385,7 @@ public:
* For IPv6 headers with a Routing header that has non-zero segments left, * For IPv6 headers with a Routing header that has non-zero segments left,
* return the last address in the first such Routing header. * return the last address in the first such Routing header.
*/ */
zeek::IPAddr DstAddr() const; IPAddr DstAddr() const;
/** /**
* Returns a pointer to the payload of the IP packet, usually an * Returns a pointer to the payload of the IP packet, usually an
@ -531,28 +531,28 @@ public:
/** /**
* Returns an ip_hdr or ip6_hdr_chain RecordVal. * Returns an ip_hdr or ip6_hdr_chain RecordVal.
*/ */
zeek::RecordValPtr ToIPHdrVal() const; RecordValPtr ToIPHdrVal() const;
[[deprecated("Remove in v4.1. Use ToIPHdrVal() instead.")]] [[deprecated("Remove in v4.1. Use ToIPHdrVal() instead.")]]
zeek::RecordVal* BuildIPHdrVal() const; RecordVal* BuildIPHdrVal() const;
/** /**
* Returns a pkt_hdr RecordVal, which includes not only the IP header, but * Returns a pkt_hdr RecordVal, which includes not only the IP header, but
* also upper-layer (tcp/udp/icmp) headers. * also upper-layer (tcp/udp/icmp) headers.
*/ */
zeek::RecordValPtr ToPktHdrVal() const; RecordValPtr ToPktHdrVal() const;
[[deprecated("Remove in v4.1. Use ToPktHdrVal() instead.")]] [[deprecated("Remove in v4.1. Use ToPktHdrVal() instead.")]]
zeek::RecordVal* BuildPktHdrVal() const; RecordVal* BuildPktHdrVal() const;
/** /**
* Same as above, but simply add our values into the record at the * Same as above, but simply add our values into the record at the
* specified starting index. * specified starting index.
*/ */
zeek::RecordValPtr ToPktHdrVal(zeek::RecordValPtr pkt_hdr, int sindex) const; RecordValPtr ToPktHdrVal(RecordValPtr pkt_hdr, int sindex) const;
[[deprecated("Remove in v4.1. Use ToPktHdrVal() instead.")]] [[deprecated("Remove in v4.1. Use ToPktHdrVal() instead.")]]
zeek::RecordVal* BuildPktHdrVal(zeek::RecordVal* pkt_hdr, int sindex) const; RecordVal* BuildPktHdrVal(RecordVal* pkt_hdr, int sindex) const;
private: private:
const struct ip* ip4 = nullptr; const struct ip* ip4 = nullptr;

View file

@ -12,11 +12,13 @@
#include "analyzer/Manager.h" #include "analyzer/Manager.h"
const zeek::IPAddr zeek::IPAddr::v4_unspecified = zeek::IPAddr(in4_addr{}); namespace zeek {
const zeek::IPAddr zeek::IPAddr::v6_unspecified = zeek::IPAddr(); const IPAddr IPAddr::v4_unspecified = IPAddr(in4_addr{});
zeek::detail::ConnIDKey zeek::detail::BuildConnIDKey(const ConnID& id) const IPAddr IPAddr::v6_unspecified = IPAddr();
detail::ConnIDKey detail::BuildConnIDKey(const ConnID& id)
{ {
ConnIDKey key; ConnIDKey key;
@ -43,19 +45,17 @@ zeek::detail::ConnIDKey zeek::detail::BuildConnIDKey(const ConnID& id)
return key; return key;
} }
namespace zeek { IPAddr::IPAddr(const String& s)
IPAddr::IPAddr(const zeek::String& s)
{ {
Init(s.CheckString()); Init(s.CheckString());
} }
zeek::detail::HashKey* IPAddr::GetHashKey() const detail::HashKey* IPAddr::GetHashKey() const
{ return MakeHashKey().release(); } { return MakeHashKey().release(); }
std::unique_ptr<zeek::detail::HashKey> IPAddr::MakeHashKey() const std::unique_ptr<detail::HashKey> IPAddr::MakeHashKey() const
{ {
return std::make_unique<zeek::detail::HashKey>((void*)in6.s6_addr, sizeof(in6.s6_addr)); return std::make_unique<detail::HashKey>((void*)in6.s6_addr, sizeof(in6.s6_addr));
} }
static inline uint32_t bit_mask32(int bottom_bits) static inline uint32_t bit_mask32(int bottom_bits)
@ -70,7 +70,7 @@ void IPAddr::Mask(int top_bits_to_keep)
{ {
if ( top_bits_to_keep < 0 || top_bits_to_keep > 128 ) if ( top_bits_to_keep < 0 || top_bits_to_keep > 128 )
{ {
zeek::reporter->Error("Bad IPAddr::Mask value %d", top_bits_to_keep); reporter->Error("Bad IPAddr::Mask value %d", top_bits_to_keep);
return; return;
} }
@ -94,7 +94,7 @@ void IPAddr::ReverseMask(int top_bits_to_chop)
{ {
if ( top_bits_to_chop < 0 || top_bits_to_chop > 128 ) if ( top_bits_to_chop < 0 || top_bits_to_chop > 128 )
{ {
zeek::reporter->Error("Bad IPAddr::ReverseMask value %d", top_bits_to_chop); reporter->Error("Bad IPAddr::ReverseMask value %d", top_bits_to_chop);
return; return;
} }
@ -149,7 +149,7 @@ void IPAddr::Init(const char* s)
{ {
if ( ! ConvertString(s, &in6) ) if ( ! ConvertString(s, &in6) )
{ {
zeek::reporter->Error("Bad IP address: %s", s); reporter->Error("Bad IP address: %s", s);
memset(in6.s6_addr, 0, sizeof(in6.s6_addr)); memset(in6.s6_addr, 0, sizeof(in6.s6_addr));
} }
} }
@ -235,7 +235,7 @@ IPPrefix::IPPrefix(const in4_addr& in4, uint8_t length)
{ {
if ( length > 32 ) if ( length > 32 )
{ {
zeek::reporter->Error("Bad in4_addr IPPrefix length : %d", length); reporter->Error("Bad in4_addr IPPrefix length : %d", length);
this->length = 0; this->length = 0;
} }
@ -247,7 +247,7 @@ IPPrefix::IPPrefix(const in6_addr& in6, uint8_t length)
{ {
if ( length > 128 ) if ( length > 128 )
{ {
zeek::reporter->Error("Bad in6_addr IPPrefix length : %d", length); reporter->Error("Bad in6_addr IPPrefix length : %d", length);
this->length = 0; this->length = 0;
} }
@ -284,7 +284,7 @@ IPPrefix::IPPrefix(const IPAddr& addr, uint8_t length, bool len_is_v6_relative)
else else
{ {
auto vstr = prefix.GetFamily() == IPv4 ? "v4" : "v6"; auto vstr = prefix.GetFamily() == IPv4 ? "v4" : "v6";
zeek::reporter->Error("Bad IPAddr(%s) IPPrefix length : %d", vstr, length); reporter->Error("Bad IPAddr(%s) IPPrefix length : %d", vstr, length);
this->length = 0; this->length = 0;
} }
@ -303,10 +303,10 @@ std::string IPPrefix::AsString() const
return prefix.AsString() +"/" + l; return prefix.AsString() +"/" + l;
} }
zeek::detail::HashKey* IPPrefix::GetHashKey() const detail::HashKey* IPPrefix::GetHashKey() const
{ return MakeHashKey().release(); } { return MakeHashKey().release(); }
std::unique_ptr<zeek::detail::HashKey> IPPrefix::MakeHashKey() const std::unique_ptr<detail::HashKey> IPPrefix::MakeHashKey() const
{ {
struct { struct {
in6_addr ip; in6_addr ip;
@ -316,7 +316,7 @@ std::unique_ptr<zeek::detail::HashKey> IPPrefix::MakeHashKey() const
key.ip = prefix.in6; key.ip = prefix.in6;
key.len = Length(); key.len = Length();
return std::make_unique<zeek::detail::HashKey>(&key, sizeof(key)); return std::make_unique<detail::HashKey>(&key, sizeof(key));
} }
bool IPPrefix::ConvertString(const char* text, IPPrefix* result) bool IPPrefix::ConvertString(const char* text, IPPrefix* result)

View file

@ -124,7 +124,7 @@ public:
* @param s String containing an IP address as either a dotted IPv4 * @param s String containing an IP address as either a dotted IPv4
* address or a hex IPv6 address. * address or a hex IPv6 address.
*/ */
explicit IPAddr(const zeek::String& s); explicit IPAddr(const String& s);
/** /**
* Constructs an address instance from a raw byte representation. * Constructs an address instance from a raw byte representation.
@ -262,10 +262,10 @@ public:
/** /**
* Returns a key that can be used to lookup the IP Address in a hash table. * Returns a key that can be used to lookup the IP Address in a hash table.
*/ */
std::unique_ptr<zeek::detail::HashKey> MakeHashKey() const; std::unique_ptr<detail::HashKey> MakeHashKey() const;
[[deprecated("Remove in v4.1. Use MakeHashKey().")]] [[deprecated("Remove in v4.1. Use MakeHashKey().")]]
zeek::detail::HashKey* GetHashKey() const; detail::HashKey* GetHashKey() const;
/** /**
* Masks out lower bits of the address. * Masks out lower bits of the address.
@ -644,10 +644,10 @@ public:
/** /**
* Returns a key that can be used to lookup the IP Prefix in a hash table. * Returns a key that can be used to lookup the IP Prefix in a hash table.
*/ */
std::unique_ptr<zeek::detail::HashKey> MakeHashKey() const; std::unique_ptr<detail::HashKey> MakeHashKey() const;
[[deprecated("Remove in v4.1. Use MakeHashKey().")]] [[deprecated("Remove in v4.1. Use MakeHashKey().")]]
zeek::detail::HashKey* GetHashKey() const; detail::HashKey* GetHashKey() const;
/** Converts the prefix into the type used internally by the /** Converts the prefix into the type used internally by the
* inter-thread communication. * inter-thread communication.

View file

@ -99,7 +99,7 @@ public:
} }
IntrusivePtr(const IntrusivePtr& other) noexcept IntrusivePtr(const IntrusivePtr& other) noexcept
: IntrusivePtr(zeek::NewRef{}, other.get()) : IntrusivePtr(NewRef{}, other.get())
{ {
} }
@ -183,7 +183,7 @@ template <class T, class... Ts>
IntrusivePtr<T> make_intrusive(Ts&&... args) IntrusivePtr<T> make_intrusive(Ts&&... args)
{ {
// Assumes that objects start with a reference count of 1! // Assumes that objects start with a reference count of 1!
return {zeek::AdoptRef{}, new T(std::forward<Ts>(args)...)}; return {AdoptRef{}, new T(std::forward<Ts>(args)...)};
} }
/** /**
@ -195,7 +195,7 @@ IntrusivePtr<T> make_intrusive(Ts&&... args)
template <class T, class U> template <class T, class U>
IntrusivePtr<T> cast_intrusive(IntrusivePtr<U> p) noexcept IntrusivePtr<T> cast_intrusive(IntrusivePtr<U> p) noexcept
{ {
return {zeek::AdoptRef{}, static_cast<T*>(p.release())}; return {AdoptRef{}, static_cast<T*>(p.release())};
} }
} // namespace zeek } // namespace zeek

View file

@ -51,7 +51,7 @@ public:
max_entries = size; max_entries = size;
entries = (T*) zeek::util::safe_malloc(max_entries * sizeof(T)); entries = (T*) 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*) zeek::util::safe_malloc(max_entries * sizeof(T)); entries = (T*) 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*) zeek::util::safe_malloc(max_entries * sizeof(T)); entries = (T*) 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 *) zeek::util::safe_malloc(max_entries * sizeof(T)); entries = (T *) 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*) zeek::util::safe_realloc((void*) entries, sizeof(T) * new_size); entries = (T*) util::safe_realloc((void*) entries, sizeof(T) * new_size);
if ( entries ) if ( entries )
max_entries = new_size; max_entries = new_size;
else else
@ -159,7 +159,7 @@ public:
} }
int MemoryAllocation() const int MemoryAllocation() const
{ return padded_sizeof(*this) + zeek::util::pad_size(max_entries * sizeof(T)); } { return padded_sizeof(*this) + util::pad_size(max_entries * sizeof(T)); }
void push_front(const T& a) void push_front(const T& a)
{ {

View file

@ -23,9 +23,9 @@ ZEEK_FORWARD_DECLARE_NAMESPACED(Func, zeek);
namespace zeek::detail { namespace zeek::detail {
class NFA_State; class NFA_State;
using NFA_state_list = zeek::PList<NFA_State>; using NFA_state_list = PList<NFA_State>;
class NFA_State : public zeek::Obj { class NFA_State : public Obj {
public: public:
NFA_State(int sym, EquivClass* ec); NFA_State(int sym, EquivClass* ec);
explicit NFA_State(CCL* ccl); explicit NFA_State(CCL* ccl);
@ -82,7 +82,7 @@ public:
EpsilonState() : NFA_State(SYM_EPSILON, nullptr) { } EpsilonState() : NFA_State(SYM_EPSILON, nullptr) { }
}; };
class NFA_Machine : public zeek::Obj { class NFA_Machine : public Obj {
public: public:
explicit NFA_Machine(NFA_State* first, NFA_State* final = nullptr); explicit NFA_Machine(NFA_State* first, NFA_State* final = nullptr);
~NFA_Machine() override; ~NFA_Machine() override;

View file

@ -102,10 +102,6 @@ zeek::StringVal* cmd_line_bpf_filter;
zeek::StringVal* global_hash_seed; zeek::StringVal* global_hash_seed;
// Because of how the BIF include files are built with namespaces already in them,
// these files need to be included separately before the namespace is opened below.
namespace zeek::detail { namespace zeek::detail {
int watchdog_interval; int watchdog_interval;
@ -200,6 +196,9 @@ bro_uint_t bits_per_uid;
} // namespace zeek::detail. The namespace has be closed here before we include the netvar_def files. } // namespace zeek::detail. The namespace has be closed here before we include the netvar_def files.
// Because of how the BIF include files are built with namespaces already in them,
// these files need to be included separately before the namespace is opened below.
static void bif_init_event_handlers() static void bif_init_event_handlers()
{ {
#include "event.bif.netvar_init" #include "event.bif.netvar_init"
@ -229,14 +228,14 @@ void init_event_handlers()
void init_general_global_var() void init_general_global_var()
{ {
table_expire_interval = zeek::id::find_val("table_expire_interval")->AsInterval(); table_expire_interval = id::find_val("table_expire_interval")->AsInterval();
table_expire_delay = zeek::id::find_val("table_expire_delay")->AsInterval(); table_expire_delay = id::find_val("table_expire_delay")->AsInterval();
table_incremental_step = zeek::id::find_val("table_incremental_step")->AsCount(); table_incremental_step = id::find_val("table_incremental_step")->AsCount();
packet_filter_default = zeek::id::find_val("packet_filter_default")->AsBool(); packet_filter_default = id::find_val("packet_filter_default")->AsBool();
sig_max_group_size = zeek::id::find_val("sig_max_group_size")->AsCount(); sig_max_group_size = id::find_val("sig_max_group_size")->AsCount();
check_for_unused_event_handlers = zeek::id::find_val("check_for_unused_event_handlers")->AsBool(); check_for_unused_event_handlers = id::find_val("check_for_unused_event_handlers")->AsBool();
record_all_packets = zeek::id::find_val("record_all_packets")->AsBool(); record_all_packets = id::find_val("record_all_packets")->AsBool();
bits_per_uid = zeek::id::find_val("bits_per_uid")->AsCount(); bits_per_uid = id::find_val("bits_per_uid")->AsCount();
} }
extern void zeek_legacy_netvar_init(); extern void zeek_legacy_netvar_init();
@ -245,107 +244,107 @@ void init_net_var()
{ {
bif_init_net_var(); bif_init_net_var();
zeek::id::detail::init(); id::detail::init();
zeek_legacy_netvar_init(); zeek_legacy_netvar_init();
ignore_checksums = zeek::id::find_val("ignore_checksums")->AsBool(); ignore_checksums = id::find_val("ignore_checksums")->AsBool();
partial_connection_ok = zeek::id::find_val("partial_connection_ok")->AsBool(); partial_connection_ok = id::find_val("partial_connection_ok")->AsBool();
tcp_SYN_ack_ok = zeek::id::find_val("tcp_SYN_ack_ok")->AsBool(); tcp_SYN_ack_ok = id::find_val("tcp_SYN_ack_ok")->AsBool();
tcp_match_undelivered = zeek::id::find_val("tcp_match_undelivered")->AsBool(); tcp_match_undelivered = id::find_val("tcp_match_undelivered")->AsBool();
encap_hdr_size = zeek::id::find_val("encap_hdr_size")->AsCount(); encap_hdr_size = id::find_val("encap_hdr_size")->AsCount();
frag_timeout = zeek::id::find_val("frag_timeout")->AsInterval(); frag_timeout = id::find_val("frag_timeout")->AsInterval();
tcp_SYN_timeout = zeek::id::find_val("tcp_SYN_timeout")->AsInterval(); tcp_SYN_timeout = id::find_val("tcp_SYN_timeout")->AsInterval();
tcp_session_timer = zeek::id::find_val("tcp_session_timer")->AsInterval(); tcp_session_timer = id::find_val("tcp_session_timer")->AsInterval();
tcp_connection_linger = zeek::id::find_val("tcp_connection_linger")->AsInterval(); tcp_connection_linger = id::find_val("tcp_connection_linger")->AsInterval();
tcp_attempt_delay = zeek::id::find_val("tcp_attempt_delay")->AsInterval(); tcp_attempt_delay = id::find_val("tcp_attempt_delay")->AsInterval();
tcp_close_delay = zeek::id::find_val("tcp_close_delay")->AsInterval(); tcp_close_delay = id::find_val("tcp_close_delay")->AsInterval();
tcp_reset_delay = zeek::id::find_val("tcp_reset_delay")->AsInterval(); tcp_reset_delay = id::find_val("tcp_reset_delay")->AsInterval();
tcp_partial_close_delay = zeek::id::find_val("tcp_partial_close_delay")->AsInterval(); tcp_partial_close_delay = id::find_val("tcp_partial_close_delay")->AsInterval();
tcp_max_initial_window = zeek::id::find_val("tcp_max_initial_window")->AsCount(); tcp_max_initial_window = id::find_val("tcp_max_initial_window")->AsCount();
tcp_max_above_hole_without_any_acks = zeek::id::find_val("tcp_max_above_hole_without_any_acks")->AsCount(); tcp_max_above_hole_without_any_acks = id::find_val("tcp_max_above_hole_without_any_acks")->AsCount();
tcp_excessive_data_without_further_acks = zeek::id::find_val("tcp_excessive_data_without_further_acks")->AsCount(); tcp_excessive_data_without_further_acks = id::find_val("tcp_excessive_data_without_further_acks")->AsCount();
tcp_max_old_segments = zeek::id::find_val("tcp_max_old_segments")->AsCount(); tcp_max_old_segments = id::find_val("tcp_max_old_segments")->AsCount();
non_analyzed_lifetime = zeek::id::find_val("non_analyzed_lifetime")->AsInterval(); non_analyzed_lifetime = id::find_val("non_analyzed_lifetime")->AsInterval();
tcp_inactivity_timeout = zeek::id::find_val("tcp_inactivity_timeout")->AsInterval(); tcp_inactivity_timeout = id::find_val("tcp_inactivity_timeout")->AsInterval();
udp_inactivity_timeout = zeek::id::find_val("udp_inactivity_timeout")->AsInterval(); udp_inactivity_timeout = id::find_val("udp_inactivity_timeout")->AsInterval();
icmp_inactivity_timeout = zeek::id::find_val("icmp_inactivity_timeout")->AsInterval(); icmp_inactivity_timeout = id::find_val("icmp_inactivity_timeout")->AsInterval();
tcp_storm_thresh = zeek::id::find_val("tcp_storm_thresh")->AsCount(); tcp_storm_thresh = id::find_val("tcp_storm_thresh")->AsCount();
tcp_storm_interarrival_thresh = zeek::id::find_val("tcp_storm_interarrival_thresh")->AsInterval(); tcp_storm_interarrival_thresh = id::find_val("tcp_storm_interarrival_thresh")->AsInterval();
tcp_content_deliver_all_orig = tcp_content_deliver_all_orig =
bool(zeek::id::find_val("tcp_content_deliver_all_orig")->AsBool()); bool(id::find_val("tcp_content_deliver_all_orig")->AsBool());
tcp_content_deliver_all_resp = tcp_content_deliver_all_resp =
bool(zeek::id::find_val("tcp_content_deliver_all_resp")->AsBool()); bool(id::find_val("tcp_content_deliver_all_resp")->AsBool());
udp_content_deliver_all_orig = udp_content_deliver_all_orig =
bool(zeek::id::find_val("udp_content_deliver_all_orig")->AsBool()); bool(id::find_val("udp_content_deliver_all_orig")->AsBool());
udp_content_deliver_all_resp = udp_content_deliver_all_resp =
bool(zeek::id::find_val("udp_content_deliver_all_resp")->AsBool()); bool(id::find_val("udp_content_deliver_all_resp")->AsBool());
udp_content_delivery_ports_use_resp = udp_content_delivery_ports_use_resp =
bool(zeek::id::find_val("udp_content_delivery_ports_use_resp")->AsBool()); bool(id::find_val("udp_content_delivery_ports_use_resp")->AsBool());
dns_session_timeout = zeek::id::find_val("dns_session_timeout")->AsInterval(); dns_session_timeout = id::find_val("dns_session_timeout")->AsInterval();
rpc_timeout = zeek::id::find_val("rpc_timeout")->AsInterval(); rpc_timeout = id::find_val("rpc_timeout")->AsInterval();
watchdog_interval = int(zeek::id::find_val("watchdog_interval")->AsInterval()); watchdog_interval = int(id::find_val("watchdog_interval")->AsInterval());
max_timer_expires = zeek::id::find_val("max_timer_expires")->AsCount(); max_timer_expires = id::find_val("max_timer_expires")->AsCount();
mime_segment_length = zeek::id::find_val("mime_segment_length")->AsCount(); mime_segment_length = id::find_val("mime_segment_length")->AsCount();
mime_segment_overlap_length = zeek::id::find_val("mime_segment_overlap_length")->AsCount(); mime_segment_overlap_length = id::find_val("mime_segment_overlap_length")->AsCount();
http_entity_data_delivery_size = zeek::id::find_val("http_entity_data_delivery_size")->AsCount(); http_entity_data_delivery_size = id::find_val("http_entity_data_delivery_size")->AsCount();
truncate_http_URI = zeek::id::find_val("truncate_http_URI")->AsInt(); truncate_http_URI = id::find_val("truncate_http_URI")->AsInt();
dns_skip_all_auth = zeek::id::find_val("dns_skip_all_auth")->AsBool(); dns_skip_all_auth = id::find_val("dns_skip_all_auth")->AsBool();
dns_skip_all_addl = zeek::id::find_val("dns_skip_all_addl")->AsBool(); dns_skip_all_addl = id::find_val("dns_skip_all_addl")->AsBool();
dns_max_queries = zeek::id::find_val("dns_max_queries")->AsCount(); dns_max_queries = id::find_val("dns_max_queries")->AsCount();
stp_delta = 0.0; stp_delta = 0.0;
if ( const auto& v = zeek::id::find_val("stp_delta") ) stp_delta = v->AsInterval(); if ( const auto& v = id::find_val("stp_delta") ) stp_delta = v->AsInterval();
stp_idle_min = 0.0; stp_idle_min = 0.0;
if ( const auto& v = zeek::id::find_val("stp_idle_min") ) stp_delta = v->AsInterval(); if ( const auto& v = id::find_val("stp_idle_min") ) stp_delta = v->AsInterval();
orig_addr_anonymization = 0; orig_addr_anonymization = 0;
if ( const auto& id = zeek::id::find("orig_addr_anonymization") ) if ( const auto& id = id::find("orig_addr_anonymization") )
if ( const auto& v = id->GetVal() ) if ( const auto& v = id->GetVal() )
orig_addr_anonymization = v->AsInt(); orig_addr_anonymization = v->AsInt();
resp_addr_anonymization = 0; resp_addr_anonymization = 0;
if ( const auto& id = zeek::id::find("resp_addr_anonymization") ) if ( const auto& id = id::find("resp_addr_anonymization") )
if ( const auto& v = id->GetVal() ) if ( const auto& v = id->GetVal() )
resp_addr_anonymization = v->AsInt(); resp_addr_anonymization = v->AsInt();
other_addr_anonymization = 0; other_addr_anonymization = 0;
if ( const auto& id = zeek::id::find("other_addr_anonymization") ) if ( const auto& id = id::find("other_addr_anonymization") )
if ( const auto& v = id->GetVal() ) if ( const auto& v = id->GetVal() )
other_addr_anonymization = v->AsInt(); other_addr_anonymization = v->AsInt();
connection_status_update_interval = 0.0; connection_status_update_interval = 0.0;
if ( const auto& id = zeek::id::find("connection_status_update_interval") ) if ( const auto& id = id::find("connection_status_update_interval") )
if ( const auto& v = id->GetVal() ) if ( const auto& v = id->GetVal() )
connection_status_update_interval = v->AsInterval(); connection_status_update_interval = v->AsInterval();
expensive_profiling_multiple = zeek::id::find_val("expensive_profiling_multiple")->AsCount(); expensive_profiling_multiple = id::find_val("expensive_profiling_multiple")->AsCount();
profiling_interval = zeek::id::find_val("profiling_interval")->AsInterval(); profiling_interval = id::find_val("profiling_interval")->AsInterval();
segment_profiling = zeek::id::find_val("segment_profiling")->AsBool(); segment_profiling = id::find_val("segment_profiling")->AsBool();
pkt_profile_mode = zeek::id::find_val("pkt_profile_mode")->InternalInt(); pkt_profile_mode = id::find_val("pkt_profile_mode")->InternalInt();
pkt_profile_freq = zeek::id::find_val("pkt_profile_freq")->AsDouble(); pkt_profile_freq = id::find_val("pkt_profile_freq")->AsDouble();
load_sample_freq = zeek::id::find_val("load_sample_freq")->AsCount(); load_sample_freq = id::find_val("load_sample_freq")->AsCount();
dpd_reassemble_first_packets = zeek::id::find_val("dpd_reassemble_first_packets")->AsBool(); dpd_reassemble_first_packets = id::find_val("dpd_reassemble_first_packets")->AsBool();
dpd_buffer_size = zeek::id::find_val("dpd_buffer_size")->AsCount(); dpd_buffer_size = id::find_val("dpd_buffer_size")->AsCount();
dpd_match_only_beginning = zeek::id::find_val("dpd_match_only_beginning")->AsBool(); dpd_match_only_beginning = id::find_val("dpd_match_only_beginning")->AsBool();
dpd_late_match_stop = zeek::id::find_val("dpd_late_match_stop")->AsBool(); dpd_late_match_stop = id::find_val("dpd_late_match_stop")->AsBool();
dpd_ignore_ports = zeek::id::find_val("dpd_ignore_ports")->AsBool(); dpd_ignore_ports = id::find_val("dpd_ignore_ports")->AsBool();
timer_mgr_inactivity_timeout = zeek::id::find_val("timer_mgr_inactivity_timeout")->AsInterval(); timer_mgr_inactivity_timeout = id::find_val("timer_mgr_inactivity_timeout")->AsInterval();
} }
} // namespace zeek::detail } // namespace zeek::detail

View file

@ -12,12 +12,12 @@ namespace zeek::notifier::detail {
Receiver::Receiver() Receiver::Receiver()
{ {
DBG_LOG(zeek::DBG_NOTIFIERS, "creating receiver %p", this); DBG_LOG(DBG_NOTIFIERS, "creating receiver %p", this);
} }
Receiver::~Receiver() Receiver::~Receiver()
{ {
DBG_LOG(zeek::DBG_NOTIFIERS, "deleting receiver %p", this); DBG_LOG(DBG_NOTIFIERS, "deleting receiver %p", this);
} }
Registry::~Registry() Registry::~Registry()
@ -28,7 +28,7 @@ Registry::~Registry()
void Registry::Register(Modifiable* m, Receiver* r) void Registry::Register(Modifiable* m, Receiver* r)
{ {
DBG_LOG(zeek::DBG_NOTIFIERS, "registering object %p for receiver %p", m, r); DBG_LOG(DBG_NOTIFIERS, "registering object %p for receiver %p", m, r);
registrations.insert({m, r}); registrations.insert({m, r});
++m->num_receivers; ++m->num_receivers;
@ -36,7 +36,7 @@ void Registry::Register(Modifiable* m, Receiver* r)
void Registry::Unregister(Modifiable* m, Receiver* r) void Registry::Unregister(Modifiable* m, Receiver* r)
{ {
DBG_LOG(zeek::DBG_NOTIFIERS, "unregistering object %p from receiver %p", m, r); DBG_LOG(DBG_NOTIFIERS, "unregistering object %p from receiver %p", m, r);
auto x = registrations.equal_range(m); auto x = registrations.equal_range(m);
for ( auto i = x.first; i != x.second; i++ ) for ( auto i = x.first; i != x.second; i++ )
@ -52,7 +52,7 @@ void Registry::Unregister(Modifiable* m, Receiver* r)
void Registry::Unregister(Modifiable* m) void Registry::Unregister(Modifiable* m)
{ {
DBG_LOG(zeek::DBG_NOTIFIERS, "unregistering object %p from all notifiers", m); DBG_LOG(DBG_NOTIFIERS, "unregistering object %p from all notifiers", m);
auto x = registrations.equal_range(m); auto x = registrations.equal_range(m);
for ( auto i = x.first; i != x.second; i++ ) for ( auto i = x.first; i != x.second; i++ )
@ -63,7 +63,7 @@ void Registry::Unregister(Modifiable* m)
void Registry::Modified(Modifiable* m) void Registry::Modified(Modifiable* m)
{ {
DBG_LOG(zeek::DBG_NOTIFIERS, "object %p has been modified", m); DBG_LOG(DBG_NOTIFIERS, "object %p has been modified", m);
auto x = registrations.equal_range(m); auto x = registrations.equal_range(m);
for ( auto i = x.first; i != x.second; i++ ) for ( auto i = x.first; i != x.second; i++ )

View file

@ -16,7 +16,7 @@ namespace detail {
Location start_location("<start uninitialized>", 0, 0, 0, 0); Location start_location("<start uninitialized>", 0, 0, 0, 0);
Location end_location("<end uninitialized>", 0, 0, 0, 0); Location end_location("<end uninitialized>", 0, 0, 0, 0);
void Location::Describe(zeek::ODesc* d) const void Location::Describe(ODesc* d) const
{ {
if ( filename ) if ( filename )
{ {
@ -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 && zeek::util::streq(filename, l.filename)) ) (filename && l.filename && 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;
@ -65,10 +65,10 @@ Obj::~Obj()
void Obj::Warn(const char* msg, const Obj* obj2, bool pinpoint_only, const detail::Location* expr_location) const void Obj::Warn(const char* msg, const Obj* obj2, bool pinpoint_only, const detail::Location* expr_location) const
{ {
zeek::ODesc d; ODesc d;
DoMsg(&d, msg, obj2, pinpoint_only, expr_location); DoMsg(&d, msg, obj2, pinpoint_only, expr_location);
zeek::reporter->Warning("%s", d.Description()); reporter->Warning("%s", d.Description());
zeek::reporter->PopLocation(); reporter->PopLocation();
} }
void Obj::Error(const char* msg, const Obj* obj2, bool pinpoint_only, const detail::Location* expr_location) const void Obj::Error(const char* msg, const Obj* obj2, bool pinpoint_only, const detail::Location* expr_location) const
@ -76,10 +76,10 @@ void Obj::Error(const char* msg, const Obj* obj2, bool pinpoint_only, const deta
if ( suppress_errors ) if ( suppress_errors )
return; return;
zeek::ODesc d; ODesc d;
DoMsg(&d, msg, obj2, pinpoint_only, expr_location); DoMsg(&d, msg, obj2, pinpoint_only, expr_location);
zeek::reporter->Error("%s", d.Description()); reporter->Error("%s", d.Description());
zeek::reporter->PopLocation(); reporter->PopLocation();
} }
void Obj::BadTag(const char* msg, const char* t1, const char* t2) const void Obj::BadTag(const char* msg, const char* t1, const char* t2) const
@ -93,35 +93,35 @@ void Obj::BadTag(const char* msg, const char* t1, const char* t2) const
else else
snprintf(out, sizeof(out), "%s", msg); snprintf(out, sizeof(out), "%s", msg);
zeek::ODesc d; ODesc d;
DoMsg(&d, out); DoMsg(&d, out);
zeek::reporter->FatalErrorWithCore("%s", d.Description()); reporter->FatalErrorWithCore("%s", d.Description());
zeek::reporter->PopLocation(); reporter->PopLocation();
} }
void Obj::Internal(const char* msg) const void Obj::Internal(const char* msg) const
{ {
zeek::ODesc d; ODesc d;
DoMsg(&d, msg); DoMsg(&d, msg);
auto rcs = zeek::render_call_stack(); auto rcs = render_call_stack();
if ( rcs.empty() ) if ( rcs.empty() )
zeek::reporter->InternalError("%s", d.Description()); reporter->InternalError("%s", d.Description());
else else
zeek::reporter->InternalError("%s, call stack: %s", d.Description(), rcs.data()); reporter->InternalError("%s, call stack: %s", d.Description(), rcs.data());
zeek::reporter->PopLocation(); reporter->PopLocation();
} }
void Obj::InternalWarning(const char* msg) const void Obj::InternalWarning(const char* msg) const
{ {
zeek::ODesc d; ODesc d;
DoMsg(&d, msg); DoMsg(&d, msg);
zeek::reporter->InternalWarning("%s", d.Description()); reporter->InternalWarning("%s", d.Description());
zeek::reporter->PopLocation(); reporter->PopLocation();
} }
void Obj::AddLocation(zeek::ODesc* d) const void Obj::AddLocation(ODesc* d) const
{ {
if ( ! location ) if ( ! location )
{ {
@ -137,10 +137,10 @@ bool Obj::SetLocationInfo(const detail::Location* start, const detail::Location*
if ( ! start || ! end ) if ( ! start || ! end )
return false; return false;
if ( end->filename && ! zeek::util::streq(start->filename, end->filename) ) if ( end->filename && ! 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 == &detail::no_location || end == &detail::no_location) )
// We already have a better location, so don't use this one. // We already have a better location, so don't use this one.
return true; return true;
@ -162,7 +162,7 @@ void Obj::UpdateLocationEndInfo(const detail::Location& end)
location->last_column = end.last_column; location->last_column = end.last_column;
} }
void Obj::DoMsg(zeek::ODesc* d, const char s1[], const Obj* obj2, void Obj::DoMsg(ODesc* d, const char s1[], const Obj* obj2,
bool pinpoint_only, const detail::Location* expr_location) const bool pinpoint_only, const detail::Location* expr_location) const
{ {
d->SetShort(); d->SetShort();
@ -171,16 +171,16 @@ void Obj::DoMsg(zeek::ODesc* d, const char s1[], const Obj* obj2,
PinPoint(d, obj2, pinpoint_only); PinPoint(d, obj2, pinpoint_only);
const detail::Location* loc2 = nullptr; const detail::Location* loc2 = nullptr;
if ( obj2 && obj2->GetLocationInfo() != &zeek::detail::no_location && if ( obj2 && obj2->GetLocationInfo() != &detail::no_location &&
*obj2->GetLocationInfo() != *GetLocationInfo() ) *obj2->GetLocationInfo() != *GetLocationInfo() )
loc2 = obj2->GetLocationInfo(); loc2 = obj2->GetLocationInfo();
else if ( expr_location ) else if ( expr_location )
loc2 = expr_location; loc2 = expr_location;
zeek::reporter->PushLocation(GetLocationInfo(), loc2); reporter->PushLocation(GetLocationInfo(), loc2);
} }
void Obj::PinPoint(zeek::ODesc* d, const Obj* obj2, bool pinpoint_only) const void Obj::PinPoint(ODesc* d, const Obj* obj2, bool pinpoint_only) const
{ {
d->Add(" ("); d->Add(" (");
Describe(d); Describe(d);
@ -195,15 +195,15 @@ void Obj::PinPoint(zeek::ODesc* d, const Obj* obj2, bool pinpoint_only) const
void Obj::Print() const void Obj::Print() const
{ {
static zeek::File fstderr(stderr); static File fstderr(stderr);
zeek::ODesc d(DESC_READABLE, &fstderr); ODesc d(DESC_READABLE, &fstderr);
Describe(&d); Describe(&d);
d.Add("\n"); d.Add("\n");
} }
void bad_ref(int type) void bad_ref(int type)
{ {
zeek::reporter->InternalError("bad reference count [%d]", type); reporter->InternalError("bad reference count [%d]", type);
abort(); abort();
} }

View file

@ -21,7 +21,7 @@ public:
Location() = default; Location() = default;
void Describe(zeek::ODesc* d) const; void Describe(ODesc* d) const;
bool operator==(const Location& l) const; bool operator==(const Location& l) const;
bool operator!=(const Location& l) const bool operator!=(const Location& l) const
@ -105,9 +105,9 @@ public:
[[noreturn]] void Internal(const char* msg) const; [[noreturn]] void Internal(const char* msg) const;
void InternalWarning(const char* msg) const; void InternalWarning(const char* msg) const;
virtual void Describe(zeek::ODesc* d) const { /* FIXME: Add code */ }; virtual void Describe(ODesc* d) const { /* FIXME: Add code */ };
void AddLocation(zeek::ODesc* d) const; void AddLocation(ODesc* d) const;
// Get location info for debugging. // Get location info for debugging.
const detail::Location* GetLocationInfo() const const detail::Location* GetLocationInfo() const
@ -144,9 +144,9 @@ protected:
private: private:
friend class SuppressErrors; friend class SuppressErrors;
void DoMsg(zeek::ODesc* d, const char s1[], const Obj* obj2 = nullptr, void DoMsg(ODesc* d, const char s1[], const Obj* obj2 = nullptr,
bool pinpoint_only = false, const detail::Location* expr_location = nullptr) const; bool pinpoint_only = false, const detail::Location* expr_location = nullptr) const;
void PinPoint(zeek::ODesc* d, const Obj* obj2 = nullptr, void PinPoint(ODesc* d, const Obj* obj2 = nullptr,
bool pinpoint_only = false) const; bool pinpoint_only = false) const;
friend inline void Ref(Obj* o); friend inline void Ref(Obj* o);

View file

@ -39,10 +39,10 @@ OpaqueMgr* OpaqueMgr::mgr()
return &mgr; return &mgr;
} }
OpaqueVal::OpaqueVal(zeek::OpaqueType* t) : OpaqueVal({zeek::NewRef{}, t}) OpaqueVal::OpaqueVal(OpaqueType* t) : OpaqueVal({NewRef{}, t})
{} {}
OpaqueVal::OpaqueVal(zeek::OpaqueTypePtr t) : Val(std::move(t)) OpaqueVal::OpaqueVal(OpaqueTypePtr t) : Val(std::move(t))
{} {}
OpaqueVal::~OpaqueVal() OpaqueVal::~OpaqueVal()
@ -54,7 +54,7 @@ const std::string& OpaqueMgr::TypeID(const OpaqueVal* v) const
auto x = _types.find(v->OpaqueName()); auto x = _types.find(v->OpaqueName());
if ( x == _types.end() ) if ( x == _types.end() )
zeek::reporter->InternalError("OpaqueMgr::TypeID: opaque type %s not registered", reporter->InternalError("OpaqueMgr::TypeID: opaque type %s not registered",
v->OpaqueName()); v->OpaqueName());
return x->first; return x->first;
@ -98,12 +98,12 @@ OpaqueValPtr OpaqueVal::Unserialize(const broker::data& data)
return val; return val;
} }
broker::expected<broker::data> OpaqueVal::SerializeType(const zeek::TypePtr& t) broker::expected<broker::data> OpaqueVal::SerializeType(const TypePtr& t)
{ {
if ( t->InternalType() == zeek::TYPE_INTERNAL_ERROR ) if ( t->InternalType() == TYPE_INTERNAL_ERROR )
return broker::ec::invalid_data; return broker::ec::invalid_data;
if ( t->InternalType() == zeek::TYPE_INTERNAL_OTHER ) if ( t->InternalType() == TYPE_INTERNAL_OTHER )
{ {
// Serialize by name. // Serialize by name.
assert(t->GetName().size()); assert(t->GetName().size());
@ -114,7 +114,7 @@ broker::expected<broker::data> OpaqueVal::SerializeType(const zeek::TypePtr& t)
return {broker::vector{false, static_cast<uint64_t>(t->Tag())}}; return {broker::vector{false, static_cast<uint64_t>(t->Tag())}};
} }
zeek::TypePtr OpaqueVal::UnserializeType(const broker::data& data) TypePtr OpaqueVal::UnserializeType(const broker::data& data)
{ {
auto v = caf::get_if<broker::vector>(&data); auto v = caf::get_if<broker::vector>(&data);
if ( ! (v && v->size() == 2) ) if ( ! (v && v->size() == 2) )
@ -130,7 +130,7 @@ zeek::TypePtr OpaqueVal::UnserializeType(const broker::data& data)
if ( ! name ) if ( ! name )
return nullptr; return nullptr;
const auto& id = zeek::detail::global_scope()->Find(*name); const auto& id = detail::global_scope()->Find(*name);
if ( ! id ) if ( ! id )
return nullptr; return nullptr;
@ -144,7 +144,7 @@ zeek::TypePtr OpaqueVal::UnserializeType(const broker::data& data)
if ( ! tag ) if ( ! tag )
return nullptr; return nullptr;
return zeek::base_type(static_cast<zeek::TypeTag>(*tag)); return base_type(static_cast<TypeTag>(*tag));
} }
ValPtr OpaqueVal::DoClone(CloneState* state) ValPtr OpaqueVal::DoClone(CloneState* state)
@ -174,7 +174,7 @@ bool HashVal::Init()
StringValPtr HashVal::Get() StringValPtr HashVal::Get()
{ {
if ( ! valid ) if ( ! valid )
return zeek::val_mgr->EmptyString(); return val_mgr->EmptyString();
auto result = DoGet(); auto result = DoGet();
valid = false; valid = false;
@ -205,15 +205,15 @@ bool HashVal::DoFeed(const void*, size_t)
StringValPtr HashVal::DoGet() StringValPtr HashVal::DoGet()
{ {
assert(! "missing implementation of DoGet()"); assert(! "missing implementation of DoGet()");
return zeek::val_mgr->EmptyString(); return val_mgr->EmptyString();
} }
HashVal::HashVal(zeek::OpaqueTypePtr t) : OpaqueVal(std::move(t)) HashVal::HashVal(OpaqueTypePtr t) : OpaqueVal(std::move(t))
{ {
valid = false; valid = false;
} }
HashVal::HashVal(zeek::OpaqueType* t) : HashVal({zeek::NewRef{}, t}) HashVal::HashVal(OpaqueType* t) : HashVal({NewRef{}, t})
{} {}
MD5Val::MD5Val() : HashVal(md5_type) MD5Val::MD5Val() : HashVal(md5_type)
@ -228,16 +228,16 @@ MD5Val::~MD5Val()
void HashVal::digest_one(EVP_MD_CTX* h, const Val* v) void HashVal::digest_one(EVP_MD_CTX* h, const Val* v)
{ {
if ( v->GetType()->Tag() == zeek::TYPE_STRING ) if ( v->GetType()->Tag() == TYPE_STRING )
{ {
const String* str = v->AsString(); const String* str = v->AsString();
zeek::detail::hash_update(h, str->Bytes(), str->Len()); detail::hash_update(h, str->Bytes(), str->Len());
} }
else else
{ {
ODesc d(DESC_BINARY); ODesc d(DESC_BINARY);
v->Describe(&d); v->Describe(&d);
zeek::detail::hash_update(h, (const u_char *) d.Bytes(), d.Len()); detail::hash_update(h, (const u_char *) d.Bytes(), d.Len());
} }
} }
@ -248,7 +248,7 @@ void HashVal::digest_one(EVP_MD_CTX* h, const ValPtr& v)
ValPtr MD5Val::DoClone(CloneState* state) ValPtr MD5Val::DoClone(CloneState* state)
{ {
auto out = zeek::make_intrusive<MD5Val>(); auto out = make_intrusive<MD5Val>();
if ( IsValid() ) if ( IsValid() )
{ {
@ -264,7 +264,7 @@ ValPtr MD5Val::DoClone(CloneState* state)
bool MD5Val::DoInit() bool MD5Val::DoInit()
{ {
assert(! IsValid()); assert(! IsValid());
ctx = zeek::detail::hash_init(zeek::detail::Hash_MD5); ctx = detail::hash_init(detail::Hash_MD5);
return true; return true;
} }
@ -273,18 +273,18 @@ bool MD5Val::DoFeed(const void* data, size_t size)
if ( ! IsValid() ) if ( ! IsValid() )
return false; return false;
zeek::detail::hash_update(ctx, data, size); detail::hash_update(ctx, data, size);
return true; return true;
} }
StringValPtr MD5Val::DoGet() StringValPtr MD5Val::DoGet()
{ {
if ( ! IsValid() ) if ( ! IsValid() )
return zeek::val_mgr->EmptyString(); return val_mgr->EmptyString();
u_char digest[MD5_DIGEST_LENGTH]; u_char digest[MD5_DIGEST_LENGTH];
zeek::detail::hash_final(ctx, digest); detail::hash_final(ctx, digest);
return zeek::make_intrusive<StringVal>(zeek::detail::md5_digest_print(digest)); return make_intrusive<StringVal>(detail::md5_digest_print(digest));
} }
IMPLEMENT_OPAQUE_VALUE(MD5Val) IMPLEMENT_OPAQUE_VALUE(MD5Val)
@ -368,7 +368,7 @@ SHA1Val::~SHA1Val()
ValPtr SHA1Val::DoClone(CloneState* state) ValPtr SHA1Val::DoClone(CloneState* state)
{ {
auto out = zeek::make_intrusive<SHA1Val>(); auto out = make_intrusive<SHA1Val>();
if ( IsValid() ) if ( IsValid() )
{ {
@ -384,7 +384,7 @@ ValPtr SHA1Val::DoClone(CloneState* state)
bool SHA1Val::DoInit() bool SHA1Val::DoInit()
{ {
assert(! IsValid()); assert(! IsValid());
ctx = zeek::detail::hash_init(zeek::detail::Hash_SHA1); ctx = detail::hash_init(detail::Hash_SHA1);
return true; return true;
} }
@ -393,18 +393,18 @@ bool SHA1Val::DoFeed(const void* data, size_t size)
if ( ! IsValid() ) if ( ! IsValid() )
return false; return false;
zeek::detail::hash_update(ctx, data, size); detail::hash_update(ctx, data, size);
return true; return true;
} }
StringValPtr SHA1Val::DoGet() StringValPtr SHA1Val::DoGet()
{ {
if ( ! IsValid() ) if ( ! IsValid() )
return zeek::val_mgr->EmptyString(); return val_mgr->EmptyString();
u_char digest[SHA_DIGEST_LENGTH]; u_char digest[SHA_DIGEST_LENGTH];
zeek::detail::hash_final(ctx, digest); detail::hash_final(ctx, digest);
return zeek::make_intrusive<StringVal>(zeek::detail::sha1_digest_print(digest)); return make_intrusive<StringVal>(detail::sha1_digest_print(digest));
} }
IMPLEMENT_OPAQUE_VALUE(SHA1Val) IMPLEMENT_OPAQUE_VALUE(SHA1Val)
@ -491,7 +491,7 @@ SHA256Val::~SHA256Val()
ValPtr SHA256Val::DoClone(CloneState* state) ValPtr SHA256Val::DoClone(CloneState* state)
{ {
auto out = zeek::make_intrusive<SHA256Val>(); auto out = make_intrusive<SHA256Val>();
if ( IsValid() ) if ( IsValid() )
{ {
@ -507,7 +507,7 @@ ValPtr SHA256Val::DoClone(CloneState* state)
bool SHA256Val::DoInit() bool SHA256Val::DoInit()
{ {
assert( ! IsValid() ); assert( ! IsValid() );
ctx = zeek::detail::hash_init(zeek::detail::Hash_SHA256); ctx = detail::hash_init(detail::Hash_SHA256);
return true; return true;
} }
@ -516,18 +516,18 @@ bool SHA256Val::DoFeed(const void* data, size_t size)
if ( ! IsValid() ) if ( ! IsValid() )
return false; return false;
zeek::detail::hash_update(ctx, data, size); detail::hash_update(ctx, data, size);
return true; return true;
} }
StringValPtr SHA256Val::DoGet() StringValPtr SHA256Val::DoGet()
{ {
if ( ! IsValid() ) if ( ! IsValid() )
return zeek::val_mgr->EmptyString(); return val_mgr->EmptyString();
u_char digest[SHA256_DIGEST_LENGTH]; u_char digest[SHA256_DIGEST_LENGTH];
zeek::detail::hash_final(ctx, digest); detail::hash_final(ctx, digest);
return zeek::make_intrusive<StringVal>(zeek::detail::sha256_digest_print(digest)); return make_intrusive<StringVal>(detail::sha256_digest_print(digest));
} }
IMPLEMENT_OPAQUE_VALUE(SHA256Val) IMPLEMENT_OPAQUE_VALUE(SHA256Val)
@ -706,7 +706,7 @@ BloomFilterVal::BloomFilterVal()
bloom_filter = nullptr; bloom_filter = nullptr;
} }
BloomFilterVal::BloomFilterVal(zeek::probabilistic::BloomFilter* bf) BloomFilterVal::BloomFilterVal(probabilistic::BloomFilter* bf)
: OpaqueVal(bloomfilter_type) : OpaqueVal(bloomfilter_type)
{ {
hash = nullptr; hash = nullptr;
@ -717,24 +717,24 @@ ValPtr BloomFilterVal::DoClone(CloneState* state)
{ {
if ( bloom_filter ) if ( bloom_filter )
{ {
auto bf = zeek::make_intrusive<BloomFilterVal>(bloom_filter->Clone()); auto bf = make_intrusive<BloomFilterVal>(bloom_filter->Clone());
bf->Typify(type); bf->Typify(type);
return state->NewClone(this, std::move(bf)); return state->NewClone(this, std::move(bf));
} }
return state->NewClone(this, zeek::make_intrusive<BloomFilterVal>()); return state->NewClone(this, make_intrusive<BloomFilterVal>());
} }
bool BloomFilterVal::Typify(zeek::TypePtr arg_type) bool BloomFilterVal::Typify(TypePtr arg_type)
{ {
if ( type ) if ( type )
return false; return false;
type = std::move(arg_type); type = std::move(arg_type);
auto tl = zeek::make_intrusive<zeek::TypeList>(type); auto tl = make_intrusive<TypeList>(type);
tl->Append(type); tl->Append(type);
hash = new zeek::detail::CompositeHash(std::move(tl)); hash = new detail::CompositeHash(std::move(tl));
return true; return true;
} }
@ -774,30 +774,30 @@ BloomFilterValPtr BloomFilterVal::Merge(const BloomFilterVal* x,
y->Type() && y->Type() &&
! same_type(x->Type(), y->Type()) ) ! same_type(x->Type(), y->Type()) )
{ {
zeek::reporter->Error("cannot merge Bloom filters with different types"); reporter->Error("cannot merge Bloom filters with different types");
return nullptr; return nullptr;
} }
if ( typeid(*x->bloom_filter) != typeid(*y->bloom_filter) ) if ( typeid(*x->bloom_filter) != typeid(*y->bloom_filter) )
{ {
zeek::reporter->Error("cannot merge different Bloom filter types"); reporter->Error("cannot merge different Bloom filter types");
return nullptr; return nullptr;
} }
zeek::probabilistic::BloomFilter* copy = x->bloom_filter->Clone(); probabilistic::BloomFilter* copy = x->bloom_filter->Clone();
if ( ! copy->Merge(y->bloom_filter) ) if ( ! copy->Merge(y->bloom_filter) )
{ {
delete copy; delete copy;
zeek::reporter->Error("failed to merge Bloom filter"); reporter->Error("failed to merge Bloom filter");
return nullptr; return nullptr;
} }
auto merged = zeek::make_intrusive<BloomFilterVal>(copy); auto merged = make_intrusive<BloomFilterVal>(copy);
if ( x->Type() && ! merged->Typify(x->Type()) ) if ( x->Type() && ! merged->Typify(x->Type()) )
{ {
zeek::reporter->Error("failed to set type on merged Bloom filter"); reporter->Error("failed to set type on merged Bloom filter");
return nullptr; return nullptr;
} }
@ -851,7 +851,7 @@ bool BloomFilterVal::DoUnserialize(const broker::data& data)
return false; return false;
} }
auto bf = zeek::probabilistic::BloomFilter::Unserialize((*v)[1]); auto bf = probabilistic::BloomFilter::Unserialize((*v)[1]);
if ( ! bf ) if ( ! bf )
return false; return false;
@ -865,7 +865,7 @@ CardinalityVal::CardinalityVal() : OpaqueVal(cardinality_type)
hash = nullptr; hash = nullptr;
} }
CardinalityVal::CardinalityVal(zeek::probabilistic::detail::CardinalityCounter* arg_c) CardinalityVal::CardinalityVal(probabilistic::detail::CardinalityCounter* arg_c)
: OpaqueVal(cardinality_type) : OpaqueVal(cardinality_type)
{ {
c = arg_c; c = arg_c;
@ -881,19 +881,19 @@ CardinalityVal::~CardinalityVal()
ValPtr CardinalityVal::DoClone(CloneState* state) ValPtr CardinalityVal::DoClone(CloneState* state)
{ {
return state->NewClone(this, return state->NewClone(this,
zeek::make_intrusive<CardinalityVal>(new zeek::probabilistic::detail::CardinalityCounter(*c))); make_intrusive<CardinalityVal>(new probabilistic::detail::CardinalityCounter(*c)));
} }
bool CardinalityVal::Typify(zeek::TypePtr arg_type) bool CardinalityVal::Typify(TypePtr arg_type)
{ {
if ( type ) if ( type )
return false; return false;
type = std::move(arg_type); type = std::move(arg_type);
auto tl = zeek::make_intrusive<zeek::TypeList>(type); auto tl = make_intrusive<TypeList>(type);
tl->Append(type); tl->Append(type);
hash = new zeek::detail::CompositeHash(std::move(tl)); hash = new detail::CompositeHash(std::move(tl));
return true; return true;
} }
@ -945,7 +945,7 @@ bool CardinalityVal::DoUnserialize(const broker::data& data)
return false; return false;
} }
auto cu = zeek::probabilistic::detail::CardinalityCounter::Unserialize((*v)[1]); auto cu = probabilistic::detail::CardinalityCounter::Unserialize((*v)[1]);
if ( ! cu ) if ( ! cu )
return false; return false;
@ -961,12 +961,12 @@ ParaglobVal::ParaglobVal(std::unique_ptr<paraglob::Paraglob> p)
VectorValPtr ParaglobVal::Get(StringVal* &pattern) VectorValPtr ParaglobVal::Get(StringVal* &pattern)
{ {
auto rval = zeek::make_intrusive<VectorVal>(zeek::id::string_vec); auto rval = make_intrusive<VectorVal>(id::string_vec);
std::string string_pattern (reinterpret_cast<const char*>(pattern->Bytes()), pattern->Len()); std::string string_pattern (reinterpret_cast<const char*>(pattern->Bytes()), pattern->Len());
std::vector<std::string> matches = this->internal_paraglob->get(string_pattern); std::vector<std::string> matches = this->internal_paraglob->get(string_pattern);
for ( size_t i = 0; i < matches.size(); i++ ) for ( size_t i = 0; i < matches.size(); i++ )
rval->Assign(i, zeek::make_intrusive<StringVal>(matches.at(i))); rval->Assign(i, make_intrusive<StringVal>(matches.at(i)));
return rval; return rval;
} }
@ -1008,12 +1008,12 @@ bool ParaglobVal::DoUnserialize(const broker::data& data)
} }
catch (const paraglob::underflow_error& e) catch (const paraglob::underflow_error& e)
{ {
zeek::reporter->Error("Paraglob underflow error -> %s", e.what()); reporter->Error("Paraglob underflow error -> %s", e.what());
return false; return false;
} }
catch (const paraglob::overflow_error& e) catch (const paraglob::overflow_error& e)
{ {
zeek::reporter->Error("Paraglob overflow error -> %s", e.what()); reporter->Error("Paraglob overflow error -> %s", e.what());
return false; return false;
} }
@ -1023,17 +1023,17 @@ bool ParaglobVal::DoUnserialize(const broker::data& data)
ValPtr ParaglobVal::DoClone(CloneState* state) ValPtr ParaglobVal::DoClone(CloneState* state)
{ {
try { try {
return zeek::make_intrusive<ParaglobVal> return make_intrusive<ParaglobVal>
(std::make_unique<paraglob::Paraglob>(this->internal_paraglob->serialize())); (std::make_unique<paraglob::Paraglob>(this->internal_paraglob->serialize()));
} }
catch (const paraglob::underflow_error& e) catch (const paraglob::underflow_error& e)
{ {
zeek::reporter->Error("Paraglob underflow error while cloning -> %s", e.what()); reporter->Error("Paraglob underflow error while cloning -> %s", e.what());
return nullptr; return nullptr;
} }
catch (const paraglob::overflow_error& e) catch (const paraglob::overflow_error& e)
{ {
zeek::reporter->Error("Paraglob overflow error while cloning -> %s", e.what()); reporter->Error("Paraglob overflow error while cloning -> %s", e.what());
return nullptr; return nullptr;
} }
} }

View file

@ -20,10 +20,10 @@ ZEEK_FORWARD_DECLARE_NAMESPACED(CardinalityCounter, zeek, probabilistic, detail)
namespace zeek { namespace zeek {
class OpaqueVal; class OpaqueVal;
using OpaqueValPtr = zeek::IntrusivePtr<OpaqueVal>; using OpaqueValPtr = IntrusivePtr<OpaqueVal>;
class BloomFilterVal; class BloomFilterVal;
using BloomFilterValPtr = zeek::IntrusivePtr<BloomFilterVal>; using BloomFilterValPtr = IntrusivePtr<BloomFilterVal>;
/** /**
* Singleton that registers all available all available types of opaque * Singleton that registers all available all available types of opaque
@ -98,8 +98,8 @@ private:
class OpaqueVal : public Val { class OpaqueVal : public Val {
public: public:
[[deprecated("Remove in v4.1. Construct from IntrusivePtr instead.")]] [[deprecated("Remove in v4.1. Construct from IntrusivePtr instead.")]]
explicit OpaqueVal(zeek::OpaqueType* t); explicit OpaqueVal(OpaqueType* t);
explicit OpaqueVal(zeek::OpaqueTypePtr t); explicit OpaqueVal(OpaqueTypePtr t);
~OpaqueVal() override; ~OpaqueVal() override;
/** /**
@ -158,26 +158,26 @@ protected:
* Helper function for derived class that need to record a type * Helper function for derived class that need to record a type
* during serialization. * during serialization.
*/ */
static broker::expected<broker::data> SerializeType(const zeek::TypePtr& t); static broker::expected<broker::data> SerializeType(const TypePtr& t);
/** /**
* Helper function for derived class that need to restore a type * Helper function for derived class that need to restore a type
* during unserialization. Returns the type at reference count +1. * during unserialization. Returns the type at reference count +1.
*/ */
static zeek::TypePtr UnserializeType(const broker::data& data); static TypePtr UnserializeType(const broker::data& data);
}; };
class HashVal : public OpaqueVal { class HashVal : public OpaqueVal {
public: public:
template <class T> template <class T>
static void digest_all(zeek::detail::HashAlgorithm alg, const T& vlist, u_char* result) static void digest_all(detail::HashAlgorithm alg, const T& vlist, u_char* result)
{ {
auto h = zeek::detail::hash_init(alg); auto h = detail::hash_init(alg);
for ( const auto& v : vlist ) for ( const auto& v : vlist )
digest_one(h, v); digest_one(h, v);
zeek::detail::hash_final(h, result); detail::hash_final(h, result);
} }
bool IsValid() const; bool IsValid() const;
@ -192,8 +192,8 @@ protected:
HashVal() { valid = false; } HashVal() { valid = false; }
[[deprecated("Remove in v4.1. Construct from IntrusivePtr instead.")]] [[deprecated("Remove in v4.1. Construct from IntrusivePtr instead.")]]
explicit HashVal(zeek::OpaqueType* t); explicit HashVal(OpaqueType* t);
explicit HashVal(zeek::OpaqueTypePtr t); explicit HashVal(OpaqueTypePtr t);
virtual bool DoInit(); virtual bool DoInit();
virtual bool DoFeed(const void* data, size_t size); virtual bool DoFeed(const void* data, size_t size);
@ -208,7 +208,7 @@ class MD5Val : public HashVal {
public: public:
template <class T> template <class T>
static void digest(const T& vlist, u_char result[MD5_DIGEST_LENGTH]) static void digest(const T& vlist, u_char result[MD5_DIGEST_LENGTH])
{ digest_all(zeek::detail::Hash_MD5, vlist, result); } { digest_all(detail::Hash_MD5, vlist, result); }
template <class T> template <class T>
static void hmac(const T& vlist, static void hmac(const T& vlist,
@ -220,7 +220,7 @@ public:
for ( int i = 0; i < MD5_DIGEST_LENGTH; ++i ) for ( int i = 0; i < MD5_DIGEST_LENGTH; ++i )
result[i] ^= key[i]; result[i] ^= key[i];
zeek::detail::internal_md5(result, MD5_DIGEST_LENGTH, result); detail::internal_md5(result, MD5_DIGEST_LENGTH, result);
} }
MD5Val(); MD5Val();
@ -244,7 +244,7 @@ class SHA1Val : public HashVal {
public: public:
template <class T> template <class T>
static void digest(const T& vlist, u_char result[SHA_DIGEST_LENGTH]) static void digest(const T& vlist, u_char result[SHA_DIGEST_LENGTH])
{ digest_all(zeek::detail::Hash_SHA1, vlist, result); } { digest_all(detail::Hash_SHA1, vlist, result); }
SHA1Val(); SHA1Val();
~SHA1Val(); ~SHA1Val();
@ -267,7 +267,7 @@ class SHA256Val : public HashVal {
public: public:
template <class T> template <class T>
static void digest(const T& vlist, u_char result[SHA256_DIGEST_LENGTH]) static void digest(const T& vlist, u_char result[SHA256_DIGEST_LENGTH])
{ digest_all(zeek::detail::Hash_SHA256, vlist, result); } { digest_all(detail::Hash_SHA256, vlist, result); }
SHA256Val(); SHA256Val();
~SHA256Val(); ~SHA256Val();
@ -299,20 +299,20 @@ protected:
DECLARE_OPAQUE_VALUE(EntropyVal) DECLARE_OPAQUE_VALUE(EntropyVal)
private: private:
zeek::detail::RandTest state; detail::RandTest state;
}; };
class BloomFilterVal : public OpaqueVal { class BloomFilterVal : public OpaqueVal {
public: public:
explicit BloomFilterVal(zeek::probabilistic::BloomFilter* bf); explicit BloomFilterVal(probabilistic::BloomFilter* bf);
~BloomFilterVal() override; ~BloomFilterVal() override;
ValPtr DoClone(CloneState* state) override; ValPtr DoClone(CloneState* state) override;
const zeek::TypePtr& Type() const const TypePtr& Type() const
{ return type; } { return type; }
bool Typify(zeek::TypePtr type); bool Typify(TypePtr type);
void Add(const Val* val); void Add(const Val* val);
size_t Count(const Val* val) const; size_t Count(const Val* val) const;
@ -333,36 +333,36 @@ private:
BloomFilterVal(const BloomFilterVal&); BloomFilterVal(const BloomFilterVal&);
BloomFilterVal& operator=(const BloomFilterVal&); BloomFilterVal& operator=(const BloomFilterVal&);
zeek::TypePtr type; TypePtr type;
zeek::detail::CompositeHash* hash; detail::CompositeHash* hash;
zeek::probabilistic::BloomFilter* bloom_filter; probabilistic::BloomFilter* bloom_filter;
}; };
class CardinalityVal : public OpaqueVal { class CardinalityVal : public OpaqueVal {
public: public:
explicit CardinalityVal(zeek::probabilistic::detail::CardinalityCounter*); explicit CardinalityVal(probabilistic::detail::CardinalityCounter*);
~CardinalityVal() override; ~CardinalityVal() override;
ValPtr DoClone(CloneState* state) override; ValPtr DoClone(CloneState* state) override;
void Add(const Val* val); void Add(const Val* val);
const zeek::TypePtr& Type() const const TypePtr& Type() const
{ return type; } { return type; }
bool Typify(zeek::TypePtr type); bool Typify(TypePtr type);
zeek::probabilistic::detail::CardinalityCounter* Get() { return c; }; probabilistic::detail::CardinalityCounter* Get() { return c; };
protected: protected:
CardinalityVal(); CardinalityVal();
DECLARE_OPAQUE_VALUE(CardinalityVal) DECLARE_OPAQUE_VALUE(CardinalityVal)
private: private:
zeek::TypePtr type; TypePtr type;
zeek::detail::CompositeHash* hash; detail::CompositeHash* hash;
zeek::probabilistic::detail::CardinalityCounter* c; probabilistic::detail::CardinalityCounter* c;
}; };
class ParaglobVal : public OpaqueVal { class ParaglobVal : public OpaqueVal {

View file

@ -68,7 +68,7 @@ void Options::filter_supervised_node_options()
bool fake_dns() bool fake_dns()
{ {
return zeek::util::zeekenv("ZEEK_DNS_FAKE"); return util::zeekenv("ZEEK_DNS_FAKE");
} }
extern const char* zeek_version(); extern const char* zeek_version();
@ -123,16 +123,16 @@ void 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", zeek::util::zeek_path().c_str()); fprintf(stderr, " $ZEEKPATH | file search path (%s)\n", util::zeek_path().c_str());
fprintf(stderr, " $ZEEK_PLUGIN_PATH | plugin search path (%s)\n", zeek::util::zeek_plugin_path()); fprintf(stderr, " $ZEEK_PLUGIN_PATH | plugin search path (%s)\n", util::zeek_plugin_path());
fprintf(stderr, " $ZEEK_PLUGIN_ACTIVATE | plugins to always activate (%s)\n", zeek::util::zeek_plugin_activate()); fprintf(stderr, " $ZEEK_PLUGIN_ACTIVATE | plugins to always activate (%s)\n", util::zeek_plugin_activate());
fprintf(stderr, " $ZEEK_PREFIXES | prefix list (%s)\n", zeek::util::zeek_prefixes().c_str()); fprintf(stderr, " $ZEEK_PREFIXES | prefix list (%s)\n", 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", 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", 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", zeek::util::zeekenv("ZEEK_DISABLE_ZEEKYGEN") ? "set" : "not set"); fprintf(stderr, " $ZEEK_DISABLE_ZEEKYGEN | Disable Zeekygen documentation support (%s)\n", util::zeekenv("ZEEK_DISABLE_ZEEKYGEN") ? "set" : "not set");
fprintf(stderr, " $ZEEK_DNS_RESOLVER | IPv4/IPv6 address of DNS resolver to use (%s)\n", zeek::util::zeekenv("ZEEK_DNS_RESOLVER") ? zeek::util::zeekenv("ZEEK_DNS_RESOLVER") : "not set, will use first IPv4 address from /etc/resolv.conf"); fprintf(stderr, " $ZEEK_DNS_RESOLVER | IPv4/IPv6 address of DNS resolver to use (%s)\n", util::zeekenv("ZEEK_DNS_RESOLVER") ? 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");
@ -238,7 +238,7 @@ Options parse_cmdline(int argc, char** argv)
}; };
char opts[256]; char opts[256];
zeek::util::safe_strncpy(opts, "B:e:f:G:H:I:i:j::n:p:r:s:T:t:U:w:X:CDFNPQSWabdhv", 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
@ -344,9 +344,9 @@ Options parse_cmdline(int argc, char** argv)
rval.pseudo_realtime = atof(optarg); rval.pseudo_realtime = atof(optarg);
break; break;
case 'F': case 'F':
if ( rval.dns_mode != zeek::detail::DNS_DEFAULT ) if ( rval.dns_mode != detail::DNS_DEFAULT )
usage(zargs[0], 1); usage(zargs[0], 1);
rval.dns_mode = zeek::detail::DNS_FORCE; rval.dns_mode = detail::DNS_FORCE;
break; break;
case 'G': case 'G':
rval.random_seed_input_file = optarg; rval.random_seed_input_file = optarg;
@ -361,9 +361,9 @@ Options parse_cmdline(int argc, char** argv)
++rval.print_plugins; ++rval.print_plugins;
break; break;
case 'P': case 'P':
if ( rval.dns_mode != zeek::detail::DNS_DEFAULT ) if ( rval.dns_mode != detail::DNS_DEFAULT )
usage(zargs[0], 1); usage(zargs[0], 1);
rval.dns_mode = zeek::detail::DNS_PRIME; rval.dns_mode = detail::DNS_PRIME;
break; break;
case 'Q': case 'Q':
rval.print_execution_time = true; rval.print_execution_time = true;
@ -433,7 +433,7 @@ Options parse_cmdline(int argc, char** argv)
if ( path->empty() ) if ( path->empty() )
return; return;
*path = zeek::util::detail::normalize_path(*path); *path = util::detail::normalize_path(*path);
if ( (*path)[0] == '/' || (*path)[0] == '~' ) if ( (*path)[0] == '/' || (*path)[0] == '~' )
// Absolute path // Absolute path
@ -442,7 +442,7 @@ Options parse_cmdline(int argc, char** argv)
if ( (*path)[0] != '.' ) if ( (*path)[0] != '.' )
{ {
// Look up file in ZEEKPATH // Look up file in ZEEKPATH
auto res = zeek::util::find_script_file(*path, zeek::util::zeek_path()); auto res = util::find_script_file(*path, util::zeek_path());
if ( res.empty() ) if ( res.empty() )
{ {

View file

@ -45,7 +45,7 @@ struct Options {
bool ignore_checksums = false; bool ignore_checksums = false;
bool use_watchdog = false; bool use_watchdog = false;
double pseudo_realtime = 0; double pseudo_realtime = 0;
zeek::detail::DNS_MgrMode dns_mode = zeek::detail::DNS_DEFAULT; detail::DNS_MgrMode dns_mode = detail::DNS_DEFAULT;
bool supervisor_mode = false; bool supervisor_mode = false;
bool parse_only = false; bool parse_only = false;
@ -82,7 +82,7 @@ struct Options {
* @param argv argument strings (same semantics as arguments to main()) * @param argv argument strings (same semantics as arguments to main())
* @return the parsed command-line options * @return the parsed command-line options
*/ */
zeek::Options parse_cmdline(int argc, char** argv); Options parse_cmdline(int argc, char** argv);
/** /**
* Print command-line Zeek usage information and exit. * Print command-line Zeek usage information and exit.

View file

@ -14,7 +14,7 @@ PacketDumper::PacketDumper(pcap_dumper_t* arg_pkt_dump)
pkt_dump = arg_pkt_dump; pkt_dump = arg_pkt_dump;
if ( ! pkt_dump ) if ( ! pkt_dump )
zeek::reporter->InternalError("PacketDumper: nil dump file"); reporter->InternalError("PacketDumper: nil dump file");
} }
void PacketDumper::DumpPacket(const struct pcap_pkthdr* hdr, void PacketDumper::DumpPacket(const struct pcap_pkthdr* hdr,
@ -25,7 +25,7 @@ void PacketDumper::DumpPacket(const struct pcap_pkthdr* hdr,
struct pcap_pkthdr h = *hdr; struct pcap_pkthdr h = *hdr;
h.caplen = len; h.caplen = len;
if ( h.caplen > hdr->caplen ) if ( h.caplen > hdr->caplen )
zeek::reporter->InternalError("bad modified caplen"); reporter->InternalError("bad modified caplen");
pcap_dump((u_char*) pkt_dump, &h, pkt); pcap_dump((u_char*) pkt_dump, &h, pkt);
} }
@ -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 ( zeek::util::time_compare(&last_timestamp, timestamp) > 0 ) if ( util::time_compare(&last_timestamp, timestamp) > 0 )
*timestamp = last_timestamp; *timestamp = last_timestamp;
else else
last_timestamp = *timestamp; last_timestamp = *timestamp;

View file

@ -16,71 +16,71 @@ PacketFilter::PacketFilter(bool arg_default)
dst_filter.SetDeleteFunction(PacketFilter::DeleteFilter); dst_filter.SetDeleteFunction(PacketFilter::DeleteFilter);
} }
void PacketFilter::AddSrc(const zeek::IPAddr& src, uint32_t tcp_flags, double probability) void PacketFilter::AddSrc(const IPAddr& 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::detail::max_random()); f->probability = probability * static_cast<double>(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;
} }
void PacketFilter::AddSrc(zeek::Val* src, uint32_t tcp_flags, double probability) void PacketFilter::AddSrc(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::detail::max_random()); f->probability = probability * static_cast<double>(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;
} }
void PacketFilter::AddDst(const zeek::IPAddr& dst, uint32_t tcp_flags, double probability) void PacketFilter::AddDst(const IPAddr& 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::detail::max_random()); f->probability = probability * static_cast<double>(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;
} }
void PacketFilter::AddDst(zeek::Val* dst, uint32_t tcp_flags, double probability) void PacketFilter::AddDst(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::detail::max_random()); f->probability = probability * static_cast<double>(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;
} }
bool PacketFilter::RemoveSrc(const zeek::IPAddr& src) bool PacketFilter::RemoveSrc(const IPAddr& src)
{ {
auto f = static_cast<Filter*>(src_filter.Remove(src, 128)); auto f = static_cast<Filter*>(src_filter.Remove(src, 128));
delete f; delete f;
return f != nullptr; return f != nullptr;
} }
bool PacketFilter::RemoveSrc(zeek::Val* src) bool PacketFilter::RemoveSrc(Val* src)
{ {
auto f = static_cast<Filter*>(src_filter.Remove(src)); auto f = static_cast<Filter*>(src_filter.Remove(src));
delete f; delete f;
return f != nullptr; return f != nullptr;
} }
bool PacketFilter::RemoveDst(const zeek::IPAddr& dst) bool PacketFilter::RemoveDst(const IPAddr& dst)
{ {
auto f = static_cast<Filter*>(dst_filter.Remove(dst, 128)); auto f = static_cast<Filter*>(dst_filter.Remove(dst, 128));
delete f; delete f;
return f != nullptr; return f != nullptr;
} }
bool PacketFilter::RemoveDst(zeek::Val* dst) bool PacketFilter::RemoveDst(Val* dst)
{ {
auto f = static_cast<Filter*>(dst_filter.Remove(dst)); auto f = static_cast<Filter*>(dst_filter.Remove(dst));
delete f; delete f;
return f != nullptr; return f != nullptr;
} }
bool PacketFilter::Match(const zeek::IP_Hdr* ip, int len, int caplen) bool PacketFilter::Match(const IP_Hdr* ip, int len, int caplen)
{ {
Filter* f = (Filter*) src_filter.Lookup(ip->SrcAddr(), 128); Filter* f = (Filter*) src_filter.Lookup(ip->SrcAddr(), 128);
if ( f ) if ( f )
@ -93,7 +93,7 @@ bool PacketFilter::Match(const zeek::IP_Hdr* ip, int len, int caplen)
return default_match; return default_match;
} }
bool PacketFilter::MatchFilter(const Filter& f, const zeek::IP_Hdr& ip, bool PacketFilter::MatchFilter(const Filter& f, const IP_Hdr& ip,
int len, int caplen) int len, int caplen)
{ {
if ( ip.NextProto() == IPPROTO_TCP && f.tcp_flags ) if ( ip.NextProto() == IPPROTO_TCP && f.tcp_flags )
@ -115,7 +115,7 @@ bool PacketFilter::MatchFilter(const Filter& f, const zeek::IP_Hdr& ip,
return false; return false;
} }
return zeek::util::detail::random_number() < f.probability; return util::detail::random_number() < f.probability;
} }
} // namespace zeek::detail } // namespace zeek::detail

View file

@ -18,20 +18,20 @@ public:
// Drops all packets from a particular source (which may be given // Drops all packets from a particular source (which may be given
// as an AddrVal or a SubnetVal) which hasn't any of TCP flags set // as an AddrVal or a SubnetVal) which hasn't any of TCP flags set
// (TH_*) with the given probability (from 0..MAX_PROB). // (TH_*) with the given probability (from 0..MAX_PROB).
void AddSrc(const zeek::IPAddr& src, uint32_t tcp_flags, double probability); void AddSrc(const IPAddr& src, uint32_t tcp_flags, double probability);
void AddSrc(zeek::Val* src, uint32_t tcp_flags, double probability); void AddSrc(Val* src, uint32_t tcp_flags, double probability);
void AddDst(const zeek::IPAddr& src, uint32_t tcp_flags, double probability); void AddDst(const IPAddr& src, uint32_t tcp_flags, double probability);
void AddDst(zeek::Val* src, uint32_t tcp_flags, double probability); void AddDst(Val* src, uint32_t tcp_flags, double probability);
// Removes the filter entry for the given src/dst // Removes the filter entry for the given src/dst
// Returns false if filter doesn not exist. // Returns false if filter doesn not exist.
bool RemoveSrc(const zeek::IPAddr& src); bool RemoveSrc(const IPAddr& src);
bool RemoveSrc(zeek::Val* dst); bool RemoveSrc(Val* dst);
bool RemoveDst(const zeek::IPAddr& dst); bool RemoveDst(const IPAddr& dst);
bool RemoveDst(zeek::Val* dst); bool RemoveDst(Val* dst);
// Returns true if packet matches a drop filter // Returns true if packet matches a drop filter
bool Match(const zeek::IP_Hdr* ip, int len, int caplen); bool Match(const IP_Hdr* ip, int len, int caplen);
private: private:
struct Filter { struct Filter {
@ -41,7 +41,7 @@ private:
static void DeleteFilter(void* data); static void DeleteFilter(void* data);
bool MatchFilter(const Filter& f, const zeek::IP_Hdr& ip, int len, int caplen); bool MatchFilter(const Filter& f, const IP_Hdr& ip, int len, int caplen);
bool default_match; bool default_match;
PrefixTable src_filter; PrefixTable src_filter;

View file

@ -7,15 +7,15 @@
#include <errno.h> #include <errno.h>
#include <cstdio> #include <cstdio>
using namespace zeek::detail; namespace zeek::detail {
static void pipe_fail(int eno) static void pipe_fail(int eno)
{ {
char tmp[256]; char tmp[256];
zeek::util::zeek_strerror_r(eno, tmp, sizeof(tmp)); zeek::util::zeek_strerror_r(eno, tmp, sizeof(tmp));
if ( zeek::reporter ) if ( reporter )
zeek::reporter->FatalError("Pipe failure: %s", tmp); reporter->FatalError("Pipe failure: %s", tmp);
else else
fprintf(stderr, "Pipe failure: %s", tmp); fprintf(stderr, "Pipe failure: %s", tmp);
} }
@ -156,3 +156,5 @@ PipePair::PipePair(int flags, int status_flags, int* fds)
Pipe(flags, flags, status_flags, status_flags, fds ? fds + 2 : nullptr)} Pipe(flags, flags, status_flags, status_flags, fds ? fds + 2 : nullptr)}
{ {
} }
} // namespace zeek::detail

View file

@ -34,12 +34,12 @@ namespace zeek::detail {
int how_many_lines_in(const char* policy_filename) int how_many_lines_in(const char* policy_filename)
{ {
if ( ! policy_filename ) if ( ! policy_filename )
zeek::reporter->InternalError("NULL value passed to how_many_lines_in\n"); reporter->InternalError("NULL value passed to how_many_lines_in\n");
FILE* throwaway = fopen(policy_filename, "r"); FILE* throwaway = fopen(policy_filename, "r");
if ( ! throwaway ) if ( ! throwaway )
{ {
zeek::detail::debug_msg("No such policy file: %s.\n", policy_filename); debug_msg("No such policy file: %s.\n", policy_filename);
return -1; return -1;
} }
@ -53,7 +53,7 @@ int how_many_lines_in(const char* policy_filename)
match = policy_files.find(policy_filename); match = policy_files.find(policy_filename);
if ( match == policy_files.end() ) if ( match == policy_files.end() )
{ {
zeek::detail::debug_msg("Policy file %s was not loaded.\n", policy_filename); debug_msg("Policy file %s was not loaded.\n", policy_filename);
return -1; return -1;
} }
} }
@ -71,14 +71,14 @@ bool LoadPolicyFileText(const char* policy_filename)
if ( ! f ) if ( ! f )
{ {
zeek::detail::debug_msg("No such policy file: %s.\n", policy_filename); debug_msg("No such policy file: %s.\n", policy_filename);
return false; return false;
} }
PolicyFile* pf = new PolicyFile; PolicyFile* pf = new PolicyFile;
if ( policy_files.find(policy_filename) != policy_files.end() ) if ( policy_files.find(policy_filename) != policy_files.end() )
zeek::detail::debug_msg("Policy file %s already loaded\n", policy_filename); debug_msg("Policy file %s already loaded\n", policy_filename);
policy_files.insert(PolicyFileMap::value_type(policy_filename, pf)); policy_files.insert(PolicyFileMap::value_type(policy_filename, pf));
@ -86,8 +86,8 @@ bool LoadPolicyFileText(const char* policy_filename)
if ( fstat(fileno(f), &st) != 0 ) if ( fstat(fileno(f), &st) != 0 )
{ {
char buf[256]; char buf[256];
zeek::util::zeek_strerror_r(errno, buf, sizeof(buf)); util::zeek_strerror_r(errno, buf, sizeof(buf));
zeek::reporter->Error("fstat failed on %s: %s", policy_filename, buf); reporter->Error("fstat failed on %s: %s", policy_filename, buf);
fclose(f); fclose(f);
return false; return false;
} }
@ -99,7 +99,7 @@ bool LoadPolicyFileText(const char* policy_filename)
// (probably fine with UTF-8) // (probably fine with UTF-8)
pf->filedata = new char[size+1]; pf->filedata = new char[size+1];
if ( fread(pf->filedata, size, 1, f) != 1 ) if ( fread(pf->filedata, size, 1, f) != 1 )
zeek::reporter->InternalError("Failed to fread() file data"); reporter->InternalError("Failed to fread() file data");
pf->filedata[size] = 0; pf->filedata[size] = 0;
fclose(f); fclose(f);
@ -131,7 +131,7 @@ bool PrintLines(const char* policy_filename, unsigned int start_line,
FILE* throwaway = fopen(policy_filename, "r"); FILE* throwaway = fopen(policy_filename, "r");
if ( ! throwaway ) if ( ! throwaway )
{ {
zeek::detail::debug_msg("No such policy file: %s.\n", policy_filename); debug_msg("No such policy file: %s.\n", policy_filename);
return false; return false;
} }
@ -145,7 +145,7 @@ bool PrintLines(const char* policy_filename, unsigned int start_line,
match = policy_files.find(policy_filename); match = policy_files.find(policy_filename);
if ( match == policy_files.end() ) if ( match == policy_files.end() )
{ {
zeek::detail::debug_msg("Policy file %s was not loaded.\n", policy_filename); debug_msg("Policy file %s was not loaded.\n", policy_filename);
return false; return false;
} }
} }
@ -157,7 +157,7 @@ bool PrintLines(const char* policy_filename, unsigned int start_line,
if ( start_line > pf->lines.size() ) if ( start_line > pf->lines.size() )
{ {
zeek::detail::debug_msg("Line number %d out of range; %s has %d lines\n", debug_msg("Line number %d out of range; %s has %d lines\n",
start_line, policy_filename, int(pf->lines.size())); start_line, policy_filename, int(pf->lines.size()));
return false; return false;
} }
@ -168,10 +168,10 @@ bool PrintLines(const char* policy_filename, unsigned int start_line,
for ( unsigned int i = 0; i < how_many_lines; ++i ) for ( unsigned int i = 0; i < how_many_lines; ++i )
{ {
if ( show_numbers ) if ( show_numbers )
zeek::detail::debug_msg("%d\t", i + start_line); debug_msg("%d\t", i + start_line);
const char* line = pf->lines[start_line + i - 1]; const char* line = pf->lines[start_line + i - 1];
zeek::detail::debug_msg("%s\n", line); debug_msg("%s\n", line);
} }
return true; return true;

View file

@ -4,9 +4,9 @@
namespace zeek::detail { namespace zeek::detail {
prefix_t* PrefixTable::MakePrefix(const zeek::IPAddr& addr, int width) prefix_t* PrefixTable::MakePrefix(const IPAddr& addr, int width)
{ {
prefix_t* prefix = (prefix_t*) zeek::util::safe_malloc(sizeof(prefix_t)); prefix_t* prefix = (prefix_t*) util::safe_malloc(sizeof(prefix_t));
addr.CopyIPv6(&prefix->add.sin6); addr.CopyIPv6(&prefix->add.sin6);
prefix->family = AF_INET6; prefix->family = AF_INET6;
@ -16,12 +16,13 @@ prefix_t* PrefixTable::MakePrefix(const zeek::IPAddr& addr, int width)
return prefix; return prefix;
} }
zeek::IPPrefix PrefixTable::PrefixToIPPrefix(prefix_t* prefix) IPPrefix PrefixTable::PrefixToIPPrefix(prefix_t* prefix)
{ {
return zeek::IPPrefix(zeek::IPAddr(IPv6, reinterpret_cast<const uint32_t*>(&prefix->add.sin6), zeek::IPAddr::Network), prefix->bitlen, true); return IPPrefix(IPAddr(IPv6, reinterpret_cast<const uint32_t*>(&prefix->add.sin6),
IPAddr::Network), prefix->bitlen, true);
} }
void* PrefixTable::Insert(const zeek::IPAddr& addr, int width, void* data) void* PrefixTable::Insert(const IPAddr& addr, int width, void* data)
{ {
prefix_t* prefix = MakePrefix(addr, width); prefix_t* prefix = MakePrefix(addr, width);
patricia_node_t* node = patricia_lookup(tree, prefix); patricia_node_t* node = patricia_lookup(tree, prefix);
@ -29,7 +30,7 @@ void* PrefixTable::Insert(const zeek::IPAddr& addr, int width, void* data)
if ( ! node ) if ( ! node )
{ {
zeek::reporter->InternalWarning("Cannot create node in patricia tree"); reporter->InternalWarning("Cannot create node in patricia tree");
return nullptr; return nullptr;
} }
@ -42,32 +43,32 @@ void* PrefixTable::Insert(const zeek::IPAddr& addr, int width, void* data)
return old; return old;
} }
void* PrefixTable::Insert(const zeek::Val* value, void* data) void* PrefixTable::Insert(const Val* value, void* data)
{ {
// [elem] -> elem // [elem] -> elem
if ( value->GetType()->Tag() == zeek::TYPE_LIST && if ( value->GetType()->Tag() == TYPE_LIST &&
value->AsListVal()->Length() == 1 ) value->AsListVal()->Length() == 1 )
value = value->AsListVal()->Idx(0).get(); value = value->AsListVal()->Idx(0).get();
switch ( value->GetType()->Tag() ) { switch ( value->GetType()->Tag() ) {
case zeek::TYPE_ADDR: case TYPE_ADDR:
return Insert(value->AsAddr(), 128, data); return Insert(value->AsAddr(), 128, data);
break; break;
case zeek::TYPE_SUBNET: case TYPE_SUBNET:
return Insert(value->AsSubNet().Prefix(), return Insert(value->AsSubNet().Prefix(),
value->AsSubNet().LengthIPv6(), data); value->AsSubNet().LengthIPv6(), data);
break; break;
default: default:
zeek::reporter->InternalWarning("Wrong index type for PrefixTable"); reporter->InternalWarning("Wrong index type for PrefixTable");
return nullptr; return nullptr;
} }
} }
std::list<std::tuple<zeek::IPPrefix,void*>> PrefixTable::FindAll(const zeek::IPAddr& addr, int width) const std::list<std::tuple<IPPrefix,void*>> PrefixTable::FindAll(const IPAddr& addr, int width) const
{ {
std::list<std::tuple<zeek::IPPrefix,void*>> out; std::list<std::tuple<IPPrefix,void*>> out;
prefix_t* prefix = MakePrefix(addr, width); prefix_t* prefix = MakePrefix(addr, width);
int elems = 0; int elems = 0;
@ -83,12 +84,12 @@ std::list<std::tuple<zeek::IPPrefix,void*>> PrefixTable::FindAll(const zeek::IPA
return out; return out;
} }
std::list<std::tuple<zeek::IPPrefix,void*>> PrefixTable::FindAll(const zeek::SubNetVal* value) const std::list<std::tuple<IPPrefix,void*>> PrefixTable::FindAll(const SubNetVal* value) const
{ {
return FindAll(value->AsSubNet().Prefix(), value->AsSubNet().LengthIPv6()); return FindAll(value->AsSubNet().Prefix(), value->AsSubNet().LengthIPv6());
} }
void* PrefixTable::Lookup(const zeek::IPAddr& addr, int width, bool exact) const void* PrefixTable::Lookup(const IPAddr& addr, int width, bool exact) const
{ {
prefix_t* prefix = MakePrefix(addr, width); prefix_t* prefix = MakePrefix(addr, width);
patricia_node_t* node = patricia_node_t* node =
@ -102,31 +103,31 @@ void* PrefixTable::Lookup(const zeek::IPAddr& addr, int width, bool exact) const
return node ? node->data : nullptr; return node ? node->data : nullptr;
} }
void* PrefixTable::Lookup(const zeek::Val* value, bool exact) const void* PrefixTable::Lookup(const Val* value, bool exact) const
{ {
// [elem] -> elem // [elem] -> elem
if ( value->GetType()->Tag() == zeek::TYPE_LIST && if ( value->GetType()->Tag() == TYPE_LIST &&
value->AsListVal()->Length() == 1 ) value->AsListVal()->Length() == 1 )
value = value->AsListVal()->Idx(0).get(); value = value->AsListVal()->Idx(0).get();
switch ( value->GetType()->Tag() ) { switch ( value->GetType()->Tag() ) {
case zeek::TYPE_ADDR: case TYPE_ADDR:
return Lookup(value->AsAddr(), 128, exact); return Lookup(value->AsAddr(), 128, exact);
break; break;
case zeek::TYPE_SUBNET: case TYPE_SUBNET:
return Lookup(value->AsSubNet().Prefix(), return Lookup(value->AsSubNet().Prefix(),
value->AsSubNet().LengthIPv6(), exact); value->AsSubNet().LengthIPv6(), exact);
break; break;
default: default:
zeek::reporter->InternalWarning("Wrong index type %d for PrefixTable", reporter->InternalWarning("Wrong index type %d for PrefixTable",
value->GetType()->Tag()); value->GetType()->Tag());
return nullptr; return nullptr;
} }
} }
void* PrefixTable::Remove(const zeek::IPAddr& addr, int width) void* PrefixTable::Remove(const IPAddr& addr, int width)
{ {
prefix_t* prefix = MakePrefix(addr, width); prefix_t* prefix = MakePrefix(addr, width);
patricia_node_t* node = patricia_search_exact(tree, prefix); patricia_node_t* node = patricia_search_exact(tree, prefix);
@ -141,25 +142,25 @@ void* PrefixTable::Remove(const zeek::IPAddr& addr, int width)
return old; return old;
} }
void* PrefixTable::Remove(const zeek::Val* value) void* PrefixTable::Remove(const Val* value)
{ {
// [elem] -> elem // [elem] -> elem
if ( value->GetType()->Tag() == zeek::TYPE_LIST && if ( value->GetType()->Tag() == TYPE_LIST &&
value->AsListVal()->Length() == 1 ) value->AsListVal()->Length() == 1 )
value = value->AsListVal()->Idx(0).get(); value = value->AsListVal()->Idx(0).get();
switch ( value->GetType()->Tag() ) { switch ( value->GetType()->Tag() ) {
case zeek::TYPE_ADDR: case TYPE_ADDR:
return Remove(value->AsAddr(), 128); return Remove(value->AsAddr(), 128);
break; break;
case zeek::TYPE_SUBNET: case TYPE_SUBNET:
return Remove(value->AsSubNet().Prefix(), return Remove(value->AsSubNet().Prefix(),
value->AsSubNet().LengthIPv6()); value->AsSubNet().LengthIPv6());
break; break;
default: default:
zeek::reporter->InternalWarning("Wrong index type for PrefixTable"); reporter->InternalWarning("Wrong index type for PrefixTable");
return nullptr; return nullptr;
} }
} }

View file

@ -29,24 +29,24 @@ public:
// Addr in network byte order. If data is zero, acts like a set. // Addr in network byte order. If data is zero, acts like a set.
// Returns ptr to old data if already existing. // Returns ptr to old data if already existing.
// For existing items without data, returns non-nil if found. // For existing items without data, returns non-nil if found.
void* Insert(const zeek::IPAddr& addr, int width, void* data = nullptr); void* Insert(const IPAddr& addr, int width, void* data = nullptr);
// Value may be addr or subnet. // Value may be addr or subnet.
void* Insert(const zeek::Val* value, void* data = nullptr); void* Insert(const Val* value, void* data = nullptr);
// Returns nil if not found, pointer to data otherwise. // Returns nil if not found, pointer to data otherwise.
// For items without data, returns non-nil if found. // For items without data, returns non-nil if found.
// If exact is false, performs exact rather than longest-prefix match. // If exact is false, performs exact rather than longest-prefix match.
void* Lookup(const zeek::IPAddr& addr, int width, bool exact = false) const; void* Lookup(const IPAddr& addr, int width, bool exact = false) const;
void* Lookup(const zeek::Val* value, bool exact = false) const; void* Lookup(const Val* value, bool exact = false) const;
// Returns list of all found matches or empty list otherwise. // Returns list of all found matches or empty list otherwise.
std::list<std::tuple<zeek::IPPrefix, void*>> FindAll(const zeek::IPAddr& addr, int width) const; std::list<std::tuple<IPPrefix, void*>> FindAll(const IPAddr& addr, int width) const;
std::list<std::tuple<zeek::IPPrefix, void*>> FindAll(const zeek::SubNetVal* value) const; std::list<std::tuple<IPPrefix, void*>> FindAll(const SubNetVal* value) const;
// Returns pointer to data or nil if not found. // Returns pointer to data or nil if not found.
void* Remove(const zeek::IPAddr& addr, int width); void* Remove(const IPAddr& addr, int width);
void* Remove(const zeek::Val* value); void* Remove(const Val* value);
void Clear() { Clear_Patricia(tree, delete_function); } void Clear() { Clear_Patricia(tree, delete_function); }
@ -57,8 +57,8 @@ public:
void* GetNext(iterator* i); void* GetNext(iterator* i);
private: private:
static prefix_t* MakePrefix(const zeek::IPAddr& addr, int width); static prefix_t* MakePrefix(const IPAddr& addr, int width);
static zeek::IPPrefix PrefixToIPPrefix(prefix_t* p); static IPPrefix PrefixToIPPrefix(prefix_t* p);
patricia_tree_t* tree; patricia_tree_t* tree;
data_fn_t delete_function; data_fn_t delete_function;

View file

@ -51,7 +51,7 @@ PQ_Element* PriorityQueue::Remove(PQ_Element* e)
PQ_Element* e2 = Remove(); PQ_Element* e2 = Remove();
if ( e != e2 ) if ( e != e2 )
zeek::reporter->InternalError("inconsistency in PriorityQueue::Remove"); reporter->InternalError("inconsistency in PriorityQueue::Remove");
return e2; return e2;
} }

View file

@ -135,7 +135,7 @@ bool Specific_RE_Matcher::Compile(bool lazy)
if ( parse_status ) if ( parse_status )
{ {
zeek::reporter->Error("error compiling pattern /%s/", pattern_text); reporter->Error("error compiling pattern /%s/", pattern_text);
Unref(nfa); Unref(nfa);
nfa = nullptr; nfa = nullptr;
return false; return false;
@ -157,7 +157,7 @@ bool Specific_RE_Matcher::Compile(bool lazy)
bool Specific_RE_Matcher::CompileSet(const string_list& set, const int_list& idx) bool Specific_RE_Matcher::CompileSet(const string_list& set, const int_list& idx)
{ {
if ( (size_t)set.length() != idx.size() ) if ( (size_t)set.length() != idx.size() )
zeek::reporter->InternalError("compileset: lengths of sets differ"); reporter->InternalError("compileset: lengths of sets differ");
rem = this; rem = this;
@ -171,7 +171,7 @@ bool Specific_RE_Matcher::CompileSet(const string_list& set, const int_list& idx
if ( parse_status ) if ( parse_status )
{ {
zeek::reporter->Error("error compiling pattern /%s/", set[i]); reporter->Error("error compiling pattern /%s/", set[i]);
if ( set_nfa && set_nfa != nfa ) if ( set_nfa && set_nfa != nfa )
Unref(set_nfa); Unref(set_nfa);
@ -215,7 +215,7 @@ bool Specific_RE_Matcher::MatchAll(const char* s)
return MatchAll((const u_char*)(s), strlen(s)); return MatchAll((const u_char*)(s), strlen(s));
} }
bool Specific_RE_Matcher::MatchAll(const zeek::String* s) bool Specific_RE_Matcher::MatchAll(const String* s)
{ {
// s->Len() does not include '\0'. // s->Len() does not include '\0'.
return MatchAll(s->Bytes(), s->Len()); return MatchAll(s->Bytes(), s->Len());
@ -226,7 +226,7 @@ int Specific_RE_Matcher::Match(const char* s)
return Match((const u_char*)(s), strlen(s)); return Match((const u_char*)(s), strlen(s));
} }
int Specific_RE_Matcher::Match(const zeek::String* s) int Specific_RE_Matcher::Match(const String* s)
{ {
return Match(s->Bytes(), s->Len()); return Match(s->Bytes(), s->Len());
} }
@ -236,7 +236,7 @@ int Specific_RE_Matcher::LongestMatch(const char* s)
return LongestMatch((const u_char*)(s), strlen(s)); return LongestMatch((const u_char*)(s), strlen(s));
} }
int Specific_RE_Matcher::LongestMatch(const zeek::String* s) int Specific_RE_Matcher::LongestMatch(const String* s)
{ {
return LongestMatch(s->Bytes(), s->Len()); return LongestMatch(s->Bytes(), s->Len());
} }
@ -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 += zeek::util::pad_size(sizeof(CCL*) * ccl_dict.size()); size += 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) + zeek::util::pad_size(sizeof(std::string::value_type) * entry.first.size()); size += padded_sizeof(std::string) + 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) + zeek::util::pad_size(sizeof(std::string::value_type) * entry.first.size()); size += padded_sizeof(std::string) + util::pad_size(sizeof(std::string::value_type) * entry.first.size());
size += padded_sizeof(std::string) + zeek::util::pad_size(sizeof(std::string::value_type) * entry.second.size()); size += padded_sizeof(std::string) + util::pad_size(sizeof(std::string::value_type) * entry.second.size());
} }
return size + padded_sizeof(*this) return size + padded_sizeof(*this)
+ (pattern_text ? zeek::util::pad_size(strlen(pattern_text) + 1) : 0) + (pattern_text ? 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?
@ -479,23 +479,23 @@ RE_Matcher* RE_Matcher_disjunction(const RE_Matcher* re1, const RE_Matcher* re2)
RE_Matcher::RE_Matcher() RE_Matcher::RE_Matcher()
{ {
re_anywhere = new detail::Specific_RE_Matcher(zeek::detail::MATCH_ANYWHERE); re_anywhere = new detail::Specific_RE_Matcher(detail::MATCH_ANYWHERE);
re_exact = new detail::Specific_RE_Matcher(zeek::detail::MATCH_EXACTLY); re_exact = new detail::Specific_RE_Matcher(detail::MATCH_EXACTLY);
} }
RE_Matcher::RE_Matcher(const char* pat) RE_Matcher::RE_Matcher(const char* pat)
{ {
re_anywhere = new detail::Specific_RE_Matcher(zeek::detail::MATCH_ANYWHERE); re_anywhere = new detail::Specific_RE_Matcher(detail::MATCH_ANYWHERE);
re_exact = new detail::Specific_RE_Matcher(zeek::detail::MATCH_EXACTLY); re_exact = new detail::Specific_RE_Matcher(detail::MATCH_EXACTLY);
AddPat(pat); AddPat(pat);
} }
RE_Matcher::RE_Matcher(const char* exact_pat, const char* anywhere_pat) RE_Matcher::RE_Matcher(const char* exact_pat, const char* anywhere_pat)
{ {
re_anywhere = new detail::Specific_RE_Matcher(zeek::detail::MATCH_ANYWHERE); re_anywhere = new detail::Specific_RE_Matcher(detail::MATCH_ANYWHERE);
re_anywhere->SetPat(anywhere_pat); re_anywhere->SetPat(anywhere_pat);
re_exact = new detail::Specific_RE_Matcher(zeek::detail::MATCH_EXACTLY); re_exact = new detail::Specific_RE_Matcher(detail::MATCH_EXACTLY);
re_exact->SetPat(exact_pat); re_exact->SetPat(exact_pat);
} }

View file

@ -32,7 +32,7 @@ namespace detail {
extern int case_insensitive; extern int case_insensitive;
extern CCL* curr_ccl; extern CCL* curr_ccl;
extern zeek::detail::NFA_Machine* nfa; extern NFA_Machine* nfa;
extern Specific_RE_Matcher* rem; extern Specific_RE_Matcher* rem;
extern const char* RE_parse_input; extern const char* RE_parse_input;
@ -43,7 +43,7 @@ using AcceptIdx = int;
using AcceptingSet = std::set<AcceptIdx>; using AcceptingSet = std::set<AcceptIdx>;
using MatchPos = uint64_t; using MatchPos = uint64_t;
using AcceptingMatchSet = std::map<AcceptIdx, MatchPos>; using AcceptingMatchSet = std::map<AcceptIdx, MatchPos>;
using string_list = zeek::name_list; using string_list = name_list;
enum match_type { MATCH_ANYWHERE, MATCH_EXACTLY }; enum match_type { MATCH_ANYWHERE, MATCH_EXACTLY };
@ -59,7 +59,7 @@ public:
void MakeCaseInsensitive(); void MakeCaseInsensitive();
void SetPat(const char* pat) { pattern_text = zeek::util::copy_string(pat); } void SetPat(const char* pat) { pattern_text = util::copy_string(pat); }
bool Compile(bool lazy = false); bool Compile(bool lazy = false);
@ -88,7 +88,7 @@ public:
void ConvertCCLs(); void ConvertCCLs();
bool MatchAll(const char* s); bool MatchAll(const char* s);
bool MatchAll(const zeek::String* s); bool MatchAll(const String* s);
// Compiles a set of regular expressions simultaniously. // Compiles a set of regular expressions simultaniously.
// 'idx' contains indizes associated with the expressions. // 'idx' contains indizes associated with the expressions.
@ -101,17 +101,17 @@ public:
// if the pattern matches empty strings, matching continues // if the pattern matches empty strings, matching continues
// in an attempt to match at least one character. // in an attempt to match at least one character.
int Match(const char* s); int Match(const char* s);
int Match(const zeek::String* s); int Match(const String* s);
int LongestMatch(const char* s); int LongestMatch(const char* s);
int LongestMatch(const zeek::String* s); int LongestMatch(const String* s);
int LongestMatch(const u_char* bv, int n); int LongestMatch(const u_char* bv, int n);
EquivClass* EC() { return &equiv_class; } EquivClass* EC() { return &equiv_class; }
const char* PatternText() const { return pattern_text; } const char* PatternText() const { return pattern_text; }
zeek::detail::DFA_Machine* DFA() const { return dfa; } DFA_Machine* DFA() const { return dfa; }
void Dump(FILE* f); void Dump(FILE* f);
@ -135,10 +135,10 @@ protected:
std::map<std::string, std::string> defs; std::map<std::string, std::string> defs;
std::map<std::string, CCL*> ccl_dict; std::map<std::string, CCL*> ccl_dict;
zeek::PList<CCL> ccl_list; PList<CCL> ccl_list;
EquivClass equiv_class; EquivClass equiv_class;
int* ecs; int* ecs;
zeek::detail::DFA_Machine* dfa; DFA_Machine* dfa;
CCL* any_ccl; CCL* any_ccl;
AcceptingSet* accepted; AcceptingSet* accepted;
}; };
@ -173,11 +173,11 @@ public:
void AddMatches(const AcceptingSet& as, MatchPos position); void AddMatches(const AcceptingSet& as, MatchPos position);
protected: protected:
zeek::detail::DFA_Machine* dfa; DFA_Machine* dfa;
int* ecs; int* ecs;
AcceptingMatchSet accepted_matches; AcceptingMatchSet accepted_matches;
zeek::detail::DFA_State* current_state; DFA_State* current_state;
int current_pos; int current_pos;
}; };
@ -203,7 +203,7 @@ public:
// Returns true if s exactly matches the pattern, false otherwise. // Returns true if s exactly matches the pattern, false otherwise.
bool MatchExactly(const char* s) bool MatchExactly(const char* s)
{ return re_exact->MatchAll(s); } { return re_exact->MatchAll(s); }
bool MatchExactly(const zeek::String* s) bool MatchExactly(const String* s)
{ return re_exact->MatchAll(s); } { return re_exact->MatchAll(s); }
// Returns the position in s just beyond where the first match // Returns the position in s just beyond where the first match
@ -212,14 +212,14 @@ public:
// in an attempt to match at least one character. // in an attempt to match at least one character.
int MatchAnywhere(const char* s) int MatchAnywhere(const char* s)
{ return re_anywhere->Match(s); } { return re_anywhere->Match(s); }
int MatchAnywhere(const zeek::String* s) int MatchAnywhere(const String* s)
{ return re_anywhere->Match(s); } { return re_anywhere->Match(s); }
// Note: it matches the *longest* prefix and returns the // Note: it matches the *longest* prefix and returns the
// length of matched prefix. It returns -1 on mismatch. // length of matched prefix. It returns -1 on mismatch.
int MatchPrefix(const char* s) int MatchPrefix(const char* s)
{ return re_exact->LongestMatch(s); } { return re_exact->LongestMatch(s); }
int MatchPrefix(const zeek::String* s) int MatchPrefix(const String* s)
{ return re_exact->LongestMatch(s); } { return re_exact->LongestMatch(s); }
int MatchPrefix(const u_char* s, int n) int MatchPrefix(const u_char* s, int n)
{ return re_exact->LongestMatch(s, n); } { return re_exact->LongestMatch(s, n); }

View file

@ -371,7 +371,7 @@ uint64_t Reassembler::TotalSize() const
return block_list.DataSize() + old_block_list.DataSize(); return block_list.DataSize() + old_block_list.DataSize();
} }
void Reassembler::Describe(zeek::ODesc* d) const void Reassembler::Describe(ODesc* d) const
{ {
d->Add("reassembler"); d->Add("reassembler");
} }

View file

@ -252,7 +252,7 @@ private:
DataBlockMap block_map; DataBlockMap block_map;
}; };
class Reassembler : public zeek::Obj { class Reassembler : public Obj {
public: public:
Reassembler(uint64_t init_seq, ReassemblerType reassem_type = REASSEM_UNKNOWN); Reassembler(uint64_t init_seq, ReassemblerType reassem_type = REASSEM_UNKNOWN);
~Reassembler() override {} ~Reassembler() override {}
@ -280,7 +280,7 @@ public:
uint64_t TotalSize() const; // number of bytes buffered up uint64_t TotalSize() const; // number of bytes buffered up
void Describe(zeek::ODesc* d) const override; void Describe(ODesc* d) const override;
// Sum over all data buffered in some reassembler. // Sum over all data buffered in some reassembler.
static uint64_t TotalMemoryAllocation() { return total_size; } static uint64_t TotalMemoryAllocation() { return total_size; }

View file

@ -66,18 +66,18 @@ Reporter::~Reporter()
void Reporter::InitOptions() void Reporter::InitOptions()
{ {
info_to_stderr = zeek::id::find_val("Reporter::info_to_stderr")->AsBool(); info_to_stderr = id::find_val("Reporter::info_to_stderr")->AsBool();
warnings_to_stderr = zeek::id::find_val("Reporter::warnings_to_stderr")->AsBool(); warnings_to_stderr = id::find_val("Reporter::warnings_to_stderr")->AsBool();
errors_to_stderr = zeek::id::find_val("Reporter::errors_to_stderr")->AsBool(); errors_to_stderr = id::find_val("Reporter::errors_to_stderr")->AsBool();
weird_sampling_rate = zeek::id::find_val("Weird::sampling_rate")->AsCount(); weird_sampling_rate = id::find_val("Weird::sampling_rate")->AsCount();
weird_sampling_threshold = zeek::id::find_val("Weird::sampling_threshold")->AsCount(); weird_sampling_threshold = id::find_val("Weird::sampling_threshold")->AsCount();
weird_sampling_duration = zeek::id::find_val("Weird::sampling_duration")->AsInterval(); weird_sampling_duration = id::find_val("Weird::sampling_duration")->AsInterval();
auto wl_val = zeek::id::find_val("Weird::sampling_whitelist")->AsTableVal(); auto wl_val = id::find_val("Weird::sampling_whitelist")->AsTableVal();
auto wl_table = wl_val->AsTable(); auto wl_table = wl_val->AsTable();
zeek::detail::HashKey* k; detail::HashKey* k;
zeek::IterCookie* c = wl_table->InitForIteration(); IterCookie* c = wl_table->InitForIteration();
zeek::TableEntryVal* v; TableEntryVal* v;
while ( (v = wl_table->NextEntry(k, c)) ) while ( (v = wl_table->NextEntry(k, c)) )
{ {
@ -126,7 +126,7 @@ void Reporter::FatalError(const char* fmt, ...)
va_end(ap); va_end(ap);
zeek::util::detail::set_processing_status("TERMINATED", "fatal_error"); util::detail::set_processing_status("TERMINATED", "fatal_error");
fflush(stderr); fflush(stderr);
fflush(stdout); fflush(stdout);
_exit(1); _exit(1);
@ -142,11 +142,11 @@ void Reporter::FatalErrorWithCore(const char* fmt, ...)
va_end(ap); va_end(ap);
zeek::util::detail::set_processing_status("TERMINATED", "fatal_error"); util::detail::set_processing_status("TERMINATED", "fatal_error");
abort(); abort();
} }
void Reporter::ExprRuntimeError(const zeek::detail::Expr* expr, const char* fmt, ...) void Reporter::ExprRuntimeError(const detail::Expr* expr, const char* fmt, ...)
{ {
++errors; ++errors;
@ -168,7 +168,7 @@ void Reporter::ExprRuntimeError(const zeek::detail::Expr* expr, const char* fmt,
throw InterpreterException(); throw InterpreterException();
} }
void Reporter::RuntimeError(const zeek::detail::Location* location, const char* fmt, ...) void Reporter::RuntimeError(const detail::Location* location, const char* fmt, ...)
{ {
++errors; ++errors;
PushLocation(location); PushLocation(location);
@ -195,11 +195,11 @@ void Reporter::InternalError(const char* fmt, ...)
va_end(ap); va_end(ap);
zeek::util::detail::set_processing_status("TERMINATED", "internal_error"); util::detail::set_processing_status("TERMINATED", "internal_error");
abort(); abort();
} }
void Reporter::AnalyzerError(zeek::analyzer::Analyzer* a, const char* fmt, ...) void Reporter::AnalyzerError(analyzer::Analyzer* a, const char* fmt, ...)
{ {
if ( a ) if ( a )
a->SetSkip(true); a->SetSkip(true);
@ -226,7 +226,7 @@ void Reporter::InternalWarning(const char* fmt, ...)
void Reporter::Syslog(const char* fmt, ...) void Reporter::Syslog(const char* fmt, ...)
{ {
if ( zeek::run_state::reading_traces ) if ( run_state::reading_traces )
return; return;
va_list ap; va_list ap;
@ -249,45 +249,45 @@ void Reporter::UpdateWeirdStats(const char* name)
++weird_count_by_type[name]; ++weird_count_by_type[name];
} }
class NetWeirdTimer final : public zeek::detail::Timer { class NetWeirdTimer final : public detail::Timer {
public: public:
NetWeirdTimer(double t, const char* name, double timeout) NetWeirdTimer(double t, const char* name, double timeout)
: zeek::detail::Timer(t + timeout, zeek::detail::TIMER_NET_WEIRD_EXPIRE), : detail::Timer(t + timeout, detail::TIMER_NET_WEIRD_EXPIRE),
weird_name(name) weird_name(name)
{} {}
void Dispatch(double t, bool is_expire) override void Dispatch(double t, bool is_expire) override
{ zeek::reporter->ResetNetWeird(weird_name); } { reporter->ResetNetWeird(weird_name); }
std::string weird_name; std::string weird_name;
}; };
class FlowWeirdTimer final : public zeek::detail::Timer { class FlowWeirdTimer final : public detail::Timer {
public: public:
using IPPair = std::pair<zeek::IPAddr, zeek::IPAddr>; using IPPair = std::pair<IPAddr, IPAddr>;
FlowWeirdTimer(double t, IPPair p, double timeout) FlowWeirdTimer(double t, IPPair p, double timeout)
: zeek::detail::Timer(t + timeout, zeek::detail::TIMER_FLOW_WEIRD_EXPIRE), : detail::Timer(t + timeout, detail::TIMER_FLOW_WEIRD_EXPIRE),
endpoints(std::move(p)) endpoints(std::move(p))
{} {}
void Dispatch(double t, bool is_expire) override void Dispatch(double t, bool is_expire) override
{ zeek::reporter->ResetFlowWeird(endpoints.first, endpoints.second); } { reporter->ResetFlowWeird(endpoints.first, endpoints.second); }
IPPair endpoints; IPPair endpoints;
}; };
class ConnTupleWeirdTimer final : public zeek::detail::Timer { class ConnTupleWeirdTimer final : public detail::Timer {
public: public:
using ConnTuple = Reporter::ConnTuple; using ConnTuple = Reporter::ConnTuple;
ConnTupleWeirdTimer(double t, ConnTuple id, double timeout) ConnTupleWeirdTimer(double t, ConnTuple id, double timeout)
: zeek::detail::Timer(t + timeout, zeek::detail::TIMER_CONN_TUPLE_WEIRD_EXPIRE), : detail::Timer(t + timeout, detail::TIMER_CONN_TUPLE_WEIRD_EXPIRE),
conn_id(std::move(id)) conn_id(std::move(id))
{} {}
void Dispatch(double t, bool is_expire) override void Dispatch(double t, bool is_expire) override
{ zeek::reporter->ResetExpiredConnWeird(conn_id); } { reporter->ResetExpiredConnWeird(conn_id); }
ConnTuple conn_id; ConnTuple conn_id;
}; };
@ -297,7 +297,7 @@ void Reporter::ResetNetWeird(const std::string& name)
net_weird_state.erase(name); net_weird_state.erase(name);
} }
void Reporter::ResetFlowWeird(const zeek::IPAddr& orig, const zeek::IPAddr& resp) void Reporter::ResetFlowWeird(const IPAddr& orig, const IPAddr& resp)
{ {
flow_weird_state.erase(std::make_pair(orig, resp)); flow_weird_state.erase(std::make_pair(orig, resp));
} }
@ -313,8 +313,8 @@ bool Reporter::PermitNetWeird(const char* name)
++count; ++count;
if ( count == 1 ) if ( count == 1 )
zeek::detail::timer_mgr->Add(new NetWeirdTimer(zeek::run_state::network_time, name, detail::timer_mgr->Add(new NetWeirdTimer(run_state::network_time, name,
weird_sampling_duration)); weird_sampling_duration));
if ( count <= weird_sampling_threshold ) if ( count <= weird_sampling_threshold )
return true; return true;
@ -327,14 +327,14 @@ bool Reporter::PermitNetWeird(const char* name)
} }
bool Reporter::PermitFlowWeird(const char* name, bool Reporter::PermitFlowWeird(const char* name,
const zeek::IPAddr& orig, const zeek::IPAddr& resp) const IPAddr& orig, const IPAddr& resp)
{ {
auto endpoints = std::make_pair(orig, resp); auto endpoints = std::make_pair(orig, resp);
auto& map = flow_weird_state[endpoints]; auto& map = flow_weird_state[endpoints];
if ( map.empty() ) if ( map.empty() )
zeek::detail::timer_mgr->Add(new FlowWeirdTimer(zeek::run_state::network_time, endpoints, detail::timer_mgr->Add(new FlowWeirdTimer(run_state::network_time, endpoints,
weird_sampling_duration)); weird_sampling_duration));
auto& count = map[name]; auto& count = map[name];
++count; ++count;
@ -349,7 +349,7 @@ bool Reporter::PermitFlowWeird(const char* name,
return false; return false;
} }
bool Reporter::PermitExpiredConnWeird(const char* name, const zeek::RecordVal& conn_id) bool Reporter::PermitExpiredConnWeird(const char* name, const RecordVal& conn_id)
{ {
auto conn_tuple = std::make_tuple(conn_id.GetField("orig_h")->AsAddr(), auto conn_tuple = std::make_tuple(conn_id.GetField("orig_h")->AsAddr(),
conn_id.GetField("resp_h")->AsAddr(), conn_id.GetField("resp_h")->AsAddr(),
@ -360,9 +360,9 @@ bool Reporter::PermitExpiredConnWeird(const char* name, const zeek::RecordVal& c
auto& map = expired_conn_weird_state[conn_tuple]; auto& map = expired_conn_weird_state[conn_tuple];
if ( map.empty() ) if ( map.empty() )
zeek::detail::timer_mgr->Add(new ConnTupleWeirdTimer(zeek::run_state::network_time, detail::timer_mgr->Add(new ConnTupleWeirdTimer(run_state::network_time,
std::move(conn_tuple), std::move(conn_tuple),
weird_sampling_duration)); weird_sampling_duration));
auto& count = map[name]; auto& count = map[name];
++count; ++count;
@ -388,7 +388,7 @@ void Reporter::Weird(const char* name, const char* addl)
return; return;
} }
WeirdHelper(net_weird, {new zeek::StringVal(addl)}, "%s", name); WeirdHelper(net_weird, {new StringVal(addl)}, "%s", name);
} }
void Reporter::Weird(file_analysis::File* f, const char* name, const char* addl) void Reporter::Weird(file_analysis::File* f, const char* name, const char* addl)
@ -402,7 +402,7 @@ void Reporter::Weird(file_analysis::File* f, const char* name, const char* addl)
return; return;
} }
WeirdHelper(file_weird, {f->ToVal()->Ref(), new zeek::StringVal(addl)}, WeirdHelper(file_weird, {f->ToVal()->Ref(), new StringVal(addl)},
"%s", name); "%s", name);
} }
@ -417,11 +417,11 @@ void Reporter::Weird(Connection* conn, const char* name, const char* addl)
return; return;
} }
WeirdHelper(conn_weird, {conn->ConnVal()->Ref(), new zeek::StringVal(addl)}, WeirdHelper(conn_weird, {conn->ConnVal()->Ref(), new StringVal(addl)},
"%s", name); "%s", name);
} }
void Reporter::Weird(zeek::RecordValPtr conn_id, zeek::StringValPtr uid, void Reporter::Weird(RecordValPtr conn_id, StringValPtr uid,
const char* name, const char* addl) const char* name, const char* addl)
{ {
UpdateWeirdStats(name); UpdateWeirdStats(name);
@ -433,11 +433,11 @@ void Reporter::Weird(zeek::RecordValPtr conn_id, zeek::StringValPtr uid,
} }
WeirdHelper(expired_conn_weird, WeirdHelper(expired_conn_weird,
{conn_id.release(), uid.release(), new zeek::StringVal(addl)}, {conn_id.release(), uid.release(), new StringVal(addl)},
"%s", name); "%s", name);
} }
void Reporter::Weird(const zeek::IPAddr& orig, const zeek::IPAddr& resp, const char* name, const char* addl) void Reporter::Weird(const IPAddr& orig, const IPAddr& resp, const char* name, const char* addl)
{ {
UpdateWeirdStats(name); UpdateWeirdStats(name);
@ -448,7 +448,7 @@ void Reporter::Weird(const zeek::IPAddr& orig, const zeek::IPAddr& resp, const c
} }
WeirdHelper(flow_weird, WeirdHelper(flow_weird,
{new zeek::AddrVal(orig), new zeek::AddrVal(resp), new zeek::StringVal(addl)}, {new AddrVal(orig), new AddrVal(resp), new StringVal(addl)},
"%s", name); "%s", name);
} }
@ -473,11 +473,11 @@ void Reporter::DoLog(const char* prefix, EventHandlerPtr event, FILE* out,
{ {
ODesc d; ODesc d;
std::pair<const zeek::detail::Location*, const zeek::detail::Location*> locs = locations.back(); std::pair<const detail::Location*, const detail::Location*> locs = locations.back();
if ( locs.first ) if ( locs.first )
{ {
if ( locs.first != &zeek::detail::no_location ) if ( locs.first != &detail::no_location )
locs.first->Describe(&d); locs.first->Describe(&d);
else else
@ -487,7 +487,7 @@ void Reporter::DoLog(const char* prefix, EventHandlerPtr event, FILE* out,
{ {
d.Add(" and "); d.Add(" and ");
if ( locs.second != &zeek::detail::no_location ) if ( locs.second != &detail::no_location )
locs.second->Describe(&d); locs.second->Describe(&d);
else else
@ -558,29 +558,29 @@ void Reporter::DoLog(const char* prefix, EventHandlerPtr event, FILE* out,
auto vl_size = 1 + (bool)time + (bool)location + (bool)conn + auto vl_size = 1 + (bool)time + (bool)location + (bool)conn +
(addl ? addl->length() : 0); (addl ? addl->length() : 0);
zeek::Args vl; Args vl;
vl.reserve(vl_size); vl.reserve(vl_size);
if ( time ) if ( time )
vl.emplace_back(zeek::make_intrusive<zeek::TimeVal>( vl.emplace_back(make_intrusive<TimeVal>(
zeek::run_state::network_time ? zeek::run_state::network_time : zeek::util::current_time())); run_state::network_time ? run_state::network_time : util::current_time()));
vl.emplace_back(zeek::make_intrusive<zeek::StringVal>(buffer)); vl.emplace_back(make_intrusive<StringVal>(buffer));
if ( location ) if ( location )
vl.emplace_back(zeek::make_intrusive<zeek::StringVal>(loc_str.c_str())); vl.emplace_back(make_intrusive<StringVal>(loc_str.c_str()));
if ( conn ) if ( conn )
vl.emplace_back(conn->ConnVal()); vl.emplace_back(conn->ConnVal());
if ( addl ) if ( addl )
for ( auto v : *addl ) for ( auto v : *addl )
vl.emplace_back(zeek::AdoptRef{}, v); vl.emplace_back(AdoptRef{}, v);
if ( conn ) if ( conn )
conn->EnqueueEvent(event, nullptr, std::move(vl)); conn->EnqueueEvent(event, nullptr, std::move(vl));
else else
zeek::event_mgr.Enqueue(event, std::move(vl)); event_mgr.Enqueue(event, std::move(vl));
} }
else else
{ {
@ -595,10 +595,10 @@ void Reporter::DoLog(const char* prefix, EventHandlerPtr event, FILE* out,
{ {
std::string s = ""; std::string s = "";
if ( zeek::run_state::zeek_start_network_time != 0.0 ) if ( run_state::zeek_start_network_time != 0.0 )
{ {
char tmp[32]; char tmp[32];
snprintf(tmp, 32, "%.6f", zeek::run_state::network_time); snprintf(tmp, 32, "%.6f", run_state::network_time);
s += std::string(tmp) + " "; s += std::string(tmp) + " ";
} }

View file

@ -28,8 +28,8 @@ ZEEK_FORWARD_DECLARE_NAMESPACED(Reporter, zeek);
namespace zeek { namespace zeek {
template <class T> class IntrusivePtr; template <class T> class IntrusivePtr;
using RecordValPtr = zeek::IntrusivePtr<RecordVal>; using RecordValPtr = IntrusivePtr<RecordVal>;
using StringValPtr = zeek::IntrusivePtr<StringVal>; using StringValPtr = IntrusivePtr<StringVal>;
// One cannot raise this exception directly, go through the // One cannot raise this exception directly, go through the
// Reporter's methods instead. // Reporter's methods instead.
@ -50,8 +50,8 @@ protected:
class Reporter { class Reporter {
public: public:
using IPPair = std::pair<zeek::IPAddr, zeek::IPAddr>; using IPPair = std::pair<IPAddr, IPAddr>;
using ConnTuple = std::tuple<zeek::IPAddr, zeek::IPAddr, uint32_t, uint32_t, TransportProto>; using ConnTuple = std::tuple<IPAddr, IPAddr, uint32_t, uint32_t, TransportProto>;
using WeirdCountMap = std::unordered_map<std::string, uint64_t>; using WeirdCountMap = std::unordered_map<std::string, uint64_t>;
using WeirdFlowMap = std::map<IPPair, WeirdCountMap>; using WeirdFlowMap = std::map<IPPair, WeirdCountMap>;
using WeirdConnTupleMap = std::map<ConnTuple, WeirdCountMap>; using WeirdConnTupleMap = std::map<ConnTuple, WeirdCountMap>;
@ -87,20 +87,20 @@ public:
// Report a runtime error in evaluating a Bro script expression. This // Report a runtime error in evaluating a Bro script expression. This
// function will not return but raise an InterpreterException. // function will not return but raise an InterpreterException.
[[noreturn]] void ExprRuntimeError(const zeek::detail::Expr* expr, const char* fmt, ...) __attribute__((format(printf, 3, 4))); [[noreturn]] void ExprRuntimeError(const detail::Expr* expr, const char* fmt, ...) __attribute__((format(printf, 3, 4)));
// Report a runtime error in evaluating a Bro script expression. This // Report a runtime error in evaluating a Bro script expression. This
// function will not return but raise an InterpreterException. // function will not return but raise an InterpreterException.
[[noreturn]] void RuntimeError(const zeek::detail::Location* location, const char* fmt, ...) __attribute__((format(printf, 3, 4))); [[noreturn]] void RuntimeError(const detail::Location* location, const char* fmt, ...) __attribute__((format(printf, 3, 4)));
// Report a traffic weirdness, i.e., an unexpected protocol situation // Report a traffic weirdness, i.e., an unexpected protocol situation
// that may lead to incorrectly processing a connnection. // that may lead to incorrectly processing a connnection.
void Weird(const char* name, const char* addl = ""); // Raises net_weird(). void Weird(const char* name, const char* addl = ""); // Raises net_weird().
void Weird(file_analysis::File* f, const char* name, const char* addl = ""); // Raises file_weird(). void Weird(file_analysis::File* f, const char* name, const char* addl = ""); // Raises file_weird().
void Weird(Connection* conn, const char* name, const char* addl = ""); // Raises conn_weird(). void Weird(Connection* conn, const char* name, const char* addl = ""); // Raises conn_weird().
void Weird(zeek::RecordValPtr conn_id, zeek::StringValPtr uid, void Weird(RecordValPtr conn_id, StringValPtr uid,
const char* name, const char* addl = ""); // Raises expired_conn_weird(). const char* name, const char* addl = ""); // Raises expired_conn_weird().
void Weird(const zeek::IPAddr& orig, const zeek::IPAddr& resp, const char* name, const char* addl = ""); // Raises flow_weird(). void Weird(const IPAddr& orig, const IPAddr& resp, const char* name, const char* addl = ""); // Raises flow_weird().
// Syslog a message. This methods does nothing if we're running // Syslog a message. This methods does nothing if we're running
// offline from a trace. // offline from a trace.
@ -116,7 +116,7 @@ public:
// Report an analyzer error. That analyzer will be set to not process // Report an analyzer error. That analyzer will be set to not process
// any further input, but Bro otherwise continues normally. // any further input, but Bro otherwise continues normally.
void AnalyzerError(zeek::analyzer::Analyzer* a, const char* fmt, ...) __attribute__((format(printf, 3, 4)));; void AnalyzerError(analyzer::Analyzer* a, const char* fmt, ...) __attribute__((format(printf, 3, 4)));;
// Toggle whether non-fatal messages should be reported through the // Toggle whether non-fatal messages should be reported through the
// scripting layer rather on standard output. Fatal errors are always // scripting layer rather on standard output. Fatal errors are always
@ -127,11 +127,11 @@ public:
// stack of location so that the most recent is always the one that // stack of location so that the most recent is always the one that
// will be assumed to be the current one. The pointer must remain // will be assumed to be the current one. The pointer must remain
// valid until the location is popped. // valid until the location is popped.
void PushLocation(const zeek::detail::Location* location) void PushLocation(const detail::Location* location)
{ locations.push_back(std::pair<const zeek::detail::Location*, const zeek::detail::Location*>(location, 0)); } { locations.push_back(std::pair<const detail::Location*, const detail::Location*>(location, 0)); }
void PushLocation(const zeek::detail::Location* loc1, const zeek::detail::Location* loc2) void PushLocation(const detail::Location* loc1, const detail::Location* loc2)
{ locations.push_back(std::pair<const zeek::detail::Location*, const zeek::detail::Location*>(loc1, loc2)); } { locations.push_back(std::pair<const detail::Location*, const detail::Location*>(loc1, loc2)); }
// Removes the top-most location information from stack. // Removes the top-most location information from stack.
void PopLocation() void PopLocation()
@ -151,7 +151,7 @@ public:
/** /**
* Reset/cleanup state tracking for a "flow" weird. * Reset/cleanup state tracking for a "flow" weird.
*/ */
void ResetFlowWeird(const zeek::IPAddr& orig, const zeek::IPAddr& resp); void ResetFlowWeird(const IPAddr& orig, const IPAddr& resp);
/** /**
* Reset/cleanup state tracking for a "expired conn" weird. * Reset/cleanup state tracking for a "expired conn" weird.
@ -259,19 +259,19 @@ public:
{ after_zeek_init = true; } { after_zeek_init = true; }
private: private:
void DoLog(const char* prefix, zeek::EventHandlerPtr event, FILE* out, void DoLog(const char* prefix, EventHandlerPtr event, FILE* out,
Connection* conn, ValPList* addl, bool location, bool time, Connection* conn, ValPList* addl, bool location, bool time,
const char* postfix, const char* fmt, va_list ap) __attribute__((format(printf, 10, 0))); const char* postfix, const char* fmt, va_list ap) __attribute__((format(printf, 10, 0)));
// WeirdHelper doesn't really have to be variadic, but it calls DoLog // WeirdHelper doesn't really have to be variadic, but it calls DoLog
// and that takes va_list anyway. // and that takes va_list anyway.
void WeirdHelper(zeek::EventHandlerPtr event, ValPList vl, const char* fmt_name, ...) __attribute__((format(printf, 4, 5)));; void WeirdHelper(EventHandlerPtr event, ValPList vl, const char* fmt_name, ...) __attribute__((format(printf, 4, 5)));;
void UpdateWeirdStats(const char* name); void UpdateWeirdStats(const char* name);
inline bool WeirdOnSamplingWhiteList(const char* name) inline bool WeirdOnSamplingWhiteList(const char* name)
{ return weird_sampling_whitelist.find(name) != weird_sampling_whitelist.end(); } { return weird_sampling_whitelist.find(name) != weird_sampling_whitelist.end(); }
bool PermitNetWeird(const char* name); bool PermitNetWeird(const char* name);
bool PermitFlowWeird(const char* name, const zeek::IPAddr& o, const zeek::IPAddr& r); bool PermitFlowWeird(const char* name, const IPAddr& o, const IPAddr& r);
bool PermitExpiredConnWeird(const char* name, const zeek::RecordVal& conn_id); bool PermitExpiredConnWeird(const char* name, const RecordVal& conn_id);
bool EmitToStderr(bool flag) bool EmitToStderr(bool flag)
{ return flag || ! after_zeek_init; } { return flag || ! after_zeek_init; }
@ -285,7 +285,7 @@ private:
bool after_zeek_init; bool after_zeek_init;
bool abort_on_scripting_errors = false; bool abort_on_scripting_errors = false;
std::list<std::pair<const zeek::detail::Location*, const zeek::detail::Location*> > locations; std::list<std::pair<const detail::Location*, const detail::Location*> > locations;
uint64_t weird_count; uint64_t weird_count;
WeirdCountMap weird_count_by_type; WeirdCountMap weird_count_by_type;

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 = zeek::util::copy_string(str); p->pattern = 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 = zeek::util::copy_string(id); p->id = 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

@ -17,14 +17,14 @@ ZEEK_FORWARD_DECLARE_NAMESPACED(Rule, zeek::detail);
namespace zeek::detail { namespace zeek::detail {
using rule_list = zeek::PList<Rule>; using rule_list = PList<Rule>;
using rule_dict = std::map<std::string, Rule*>; using rule_dict = std::map<std::string, Rule*>;
class Rule { class Rule {
public: public:
Rule(const char* arg_id, const zeek::detail::Location& arg_location) Rule(const char* arg_id, const Location& arg_location)
{ {
id = zeek::util::copy_string(arg_id); id = util::copy_string(arg_id);
idx = rule_counter++; idx = rule_counter++;
location = arg_location; location = arg_location;
active = true; active = true;
@ -50,7 +50,7 @@ public:
uint32_t offset = 0, uint32_t depth = INT_MAX); uint32_t offset = 0, uint32_t depth = INT_MAX);
void AddRequires(const char* id, bool opposite_direction, bool negate); void AddRequires(const char* id, bool opposite_direction, bool negate);
const zeek::detail::Location& GetLocation() const { return location; } const Location& GetLocation() const { return location; }
void PrintDebug(); void PrintDebug();
@ -61,9 +61,9 @@ private:
void SortHdrTests(); void SortHdrTests();
using rule_action_list = zeek::PList<RuleAction>; using rule_action_list = PList<RuleAction>;
using rule_condition_list = zeek::PList<RuleCondition>; using rule_condition_list = PList<RuleCondition>;
using rule_hdr_test_list = zeek::PList<RuleHdrTest>; using rule_hdr_test_list = PList<RuleHdrTest>;
rule_hdr_test_list hdr_tests; rule_hdr_test_list hdr_tests;
rule_condition_list conditions; rule_condition_list conditions;
@ -77,7 +77,7 @@ private:
bool negate; // negate test bool negate; // negate test
}; };
using precond_list = zeek::PList<Precond>; using precond_list = PList<Precond>;
precond_list preconds; precond_list preconds;
rule_list dependents; // rules w/ us as a precondition rule_list dependents; // rules w/ us as a precondition
@ -95,13 +95,13 @@ private:
uint32_t depth; uint32_t depth;
}; };
using pattern_list = zeek::PList<Pattern>; using pattern_list = PList<Pattern>;
pattern_list patterns; pattern_list patterns;
Rule* next; // Linkage within RuleHdrTest tree: Rule* next; // Linkage within RuleHdrTest tree:
// Ptr to next rule using the same RuleHdrTests // Ptr to next rule using the same RuleHdrTests
zeek::detail::Location location; Location location;
// Rules and payloads are numbered individually. // Rules and payloads are numbered individually.
static unsigned int rule_counter; static unsigned int rule_counter;

View file

@ -16,18 +16,18 @@ namespace zeek::detail {
RuleActionEvent::RuleActionEvent(const char* arg_msg) RuleActionEvent::RuleActionEvent(const char* arg_msg)
{ {
msg = zeek::util::copy_string(arg_msg); msg = util::copy_string(arg_msg);
} }
void RuleActionEvent::DoAction(const Rule* parent, RuleEndpointState* state, void RuleActionEvent::DoAction(const Rule* parent, RuleEndpointState* state,
const u_char* data, int len) const u_char* data, int len)
{ {
if ( signature_match ) if ( signature_match )
zeek::event_mgr.Enqueue( event_mgr.Enqueue(
signature_match, signature_match,
zeek::IntrusivePtr{zeek::AdoptRef{}, rule_matcher->BuildRuleStateValue(parent, state)}, IntrusivePtr{AdoptRef{}, rule_matcher->BuildRuleStateValue(parent, state)},
zeek::make_intrusive<zeek::StringVal>(msg), make_intrusive<StringVal>(msg),
data ? zeek::make_intrusive<zeek::StringVal>(len, (const char*)data) : zeek::val_mgr->EmptyString() data ? make_intrusive<StringVal>(len, (const char*)data) : val_mgr->EmptyString()
); );
} }
@ -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 = zeek::util::copy_string(arg_mime); mime = util::copy_string(arg_mime);
strength = arg_strength; strength = arg_strength;
} }
@ -52,31 +52,31 @@ RuleActionAnalyzer::RuleActionAnalyzer(const char* arg_analyzer)
string str(arg_analyzer); string str(arg_analyzer);
string::size_type pos = str.find(':'); string::size_type pos = str.find(':');
string arg = str.substr(0, pos); string arg = str.substr(0, pos);
analyzer = zeek::analyzer_mgr->GetComponentTag(arg.c_str()); analyzer = analyzer_mgr->GetComponentTag(arg.c_str());
if ( ! analyzer ) if ( ! analyzer )
zeek::reporter->Warning("unknown analyzer '%s' specified in rule", arg.c_str()); reporter->Warning("unknown analyzer '%s' specified in rule", arg.c_str());
if ( pos != string::npos ) if ( pos != string::npos )
{ {
arg = str.substr(pos + 1); arg = str.substr(pos + 1);
child_analyzer = zeek::analyzer_mgr->GetComponentTag(arg.c_str()); child_analyzer = analyzer_mgr->GetComponentTag(arg.c_str());
if ( ! child_analyzer ) if ( ! child_analyzer )
zeek::reporter->Warning("unknown analyzer '%s' specified in rule", arg.c_str()); reporter->Warning("unknown analyzer '%s' specified in rule", arg.c_str());
} }
else else
child_analyzer = zeek::analyzer::Tag(); child_analyzer = analyzer::Tag();
} }
void RuleActionAnalyzer::PrintDebug() void RuleActionAnalyzer::PrintDebug()
{ {
if ( ! child_analyzer ) if ( ! child_analyzer )
fprintf(stderr, "|%s|\n", zeek::analyzer_mgr->GetComponentName(analyzer).c_str()); fprintf(stderr, "|%s|\n", analyzer_mgr->GetComponentName(analyzer).c_str());
else else
fprintf(stderr, "|%s:%s|\n", fprintf(stderr, "|%s:%s|\n",
zeek::analyzer_mgr->GetComponentName(analyzer).c_str(), analyzer_mgr->GetComponentName(analyzer).c_str(),
zeek::analyzer_mgr->GetComponentName(child_analyzer).c_str()); analyzer_mgr->GetComponentName(child_analyzer).c_str());
} }
@ -85,7 +85,7 @@ void RuleActionEnable::DoAction(const Rule* parent, RuleEndpointState* state,
{ {
if ( ! ChildAnalyzer() ) if ( ! ChildAnalyzer() )
{ {
if ( ! zeek::analyzer_mgr->IsEnabled(Analyzer()) ) if ( ! analyzer_mgr->IsEnabled(Analyzer()) )
return; return;
if ( state->PIA() ) if ( state->PIA() )
@ -93,7 +93,7 @@ void RuleActionEnable::DoAction(const Rule* parent, RuleEndpointState* state,
} }
else else
{ {
if ( ! zeek::analyzer_mgr->IsEnabled(ChildAnalyzer()) ) if ( ! analyzer_mgr->IsEnabled(ChildAnalyzer()) )
return; return;
// This is ugly and works only if there exists only one // This is ugly and works only if there exists only one

View file

@ -71,12 +71,12 @@ public:
void PrintDebug() override; void PrintDebug() override;
zeek::analyzer::Tag Analyzer() const { return analyzer; } analyzer::Tag Analyzer() const { return analyzer; }
zeek::analyzer::Tag ChildAnalyzer() const { return child_analyzer; } analyzer::Tag ChildAnalyzer() const { return child_analyzer; }
private: private:
zeek::analyzer::Tag analyzer; analyzer::Tag analyzer;
zeek::analyzer::Tag child_analyzer; analyzer::Tag child_analyzer;
}; };
class RuleActionEnable : public RuleActionAnalyzer { class RuleActionEnable : public RuleActionAnalyzer {

View file

@ -25,12 +25,12 @@ namespace zeek::detail {
bool RuleConditionTCPState::DoMatch(Rule* rule, RuleEndpointState* state, bool RuleConditionTCPState::DoMatch(Rule* rule, RuleEndpointState* state,
const u_char* data, int len) const u_char* data, int len)
{ {
zeek::analyzer::Analyzer* root = state->GetAnalyzer()->Conn()->GetRootAnalyzer(); analyzer::Analyzer* root = state->GetAnalyzer()->Conn()->GetRootAnalyzer();
if ( ! root || ! root->IsAnalyzer("TCP") ) if ( ! root || ! root->IsAnalyzer("TCP") )
return false; return false;
auto* ta = static_cast<zeek::analyzer::tcp::TCP_Analyzer*>(root); auto* ta = static_cast<analyzer::tcp::TCP_Analyzer*>(root);
if ( tcpstates & STATE_STATELESS ) if ( tcpstates & STATE_STATELESS )
return true; return true;
@ -122,7 +122,7 @@ bool RuleConditionPayloadSize::DoMatch(Rule* rule, RuleEndpointState* state,
return payload_size >= val; return payload_size >= val;
default: default:
zeek::reporter->InternalError("unknown comparison type"); reporter->InternalError("unknown comparison type");
} }
// Should not be reached // Should not be reached
@ -131,25 +131,25 @@ bool RuleConditionPayloadSize::DoMatch(Rule* rule, RuleEndpointState* state,
RuleConditionEval::RuleConditionEval(const char* func) RuleConditionEval::RuleConditionEval(const char* func)
{ {
id = zeek::detail::global_scope()->Find(func).get(); id = global_scope()->Find(func).get();
if ( ! id ) if ( ! id )
{ {
rules_error("unknown identifier", func); rules_error("unknown identifier", func);
return; return;
} }
if ( id->GetType()->Tag() == zeek::TYPE_FUNC ) if ( id->GetType()->Tag() == TYPE_FUNC )
{ {
// Validate argument quantity and type. // Validate argument quantity and type.
zeek::FuncType* f = id->GetType()->AsFuncType(); FuncType* f = id->GetType()->AsFuncType();
if ( f->Yield()->Tag() != zeek::TYPE_BOOL ) if ( f->Yield()->Tag() != TYPE_BOOL )
rules_error("eval function type must yield a 'bool'", func); rules_error("eval function type must yield a 'bool'", func);
static auto signature_state = zeek::id::find_type<zeek::RecordType>("signature_state"); static auto signature_state = id::find_type<RecordType>("signature_state");
zeek::TypeList tl; TypeList tl;
tl.Append(signature_state); tl.Append(signature_state);
tl.Append(zeek::base_type(zeek::TYPE_STRING)); tl.Append(base_type(TYPE_STRING));
if ( ! f->CheckArgs(tl.GetTypes()) ) if ( ! f->CheckArgs(tl.GetTypes()) )
rules_error("eval function parameters must be a 'signature_state' " rules_error("eval function parameters must be a 'signature_state' "
@ -162,22 +162,22 @@ bool RuleConditionEval::DoMatch(Rule* rule, RuleEndpointState* state,
{ {
if ( ! id->HasVal() ) if ( ! id->HasVal() )
{ {
zeek::reporter->Error("undefined value"); reporter->Error("undefined value");
return false; return false;
} }
if ( id->GetType()->Tag() != zeek::TYPE_FUNC ) if ( id->GetType()->Tag() != TYPE_FUNC )
return id->GetVal()->AsBool(); return id->GetVal()->AsBool();
// Call function with a signature_state value as argument. // Call function with a signature_state value as argument.
zeek::Args args; Args args;
args.reserve(2); args.reserve(2);
args.emplace_back(zeek::AdoptRef{}, rule_matcher->BuildRuleStateValue(rule, state)); args.emplace_back(AdoptRef{}, rule_matcher->BuildRuleStateValue(rule, state));
if ( data ) if ( data )
args.emplace_back(zeek::make_intrusive<zeek::StringVal>(len, (const char*) data)); args.emplace_back(make_intrusive<StringVal>(len, (const char*) data));
else else
args.emplace_back(zeek::val_mgr->EmptyString()); args.emplace_back(val_mgr->EmptyString());
bool result = false; bool result = false;

View file

@ -114,7 +114,7 @@ public:
void PrintDebug() override; void PrintDebug() override;
private: private:
zeek::detail::ID* id; ID* id;
}; };
} // namespace zeek::detail } // namespace zeek::detail

View file

@ -48,7 +48,7 @@ static bool is_member_of(const int_list& l, int_list::value_type v)
} }
RuleHdrTest::RuleHdrTest(Prot arg_prot, uint32_t arg_offset, uint32_t arg_size, RuleHdrTest::RuleHdrTest(Prot arg_prot, uint32_t arg_offset, uint32_t arg_size,
Comp arg_comp, maskedvalue_list* arg_vals) Comp arg_comp, maskedvalue_list* arg_vals)
{ {
prot = arg_prot; prot = arg_prot;
offset = arg_offset; offset = arg_offset;
@ -64,7 +64,7 @@ RuleHdrTest::RuleHdrTest(Prot arg_prot, uint32_t arg_offset, uint32_t arg_size,
level = 0; level = 0;
} }
RuleHdrTest::RuleHdrTest(Prot arg_prot, Comp arg_comp, vector<zeek::IPPrefix> arg_v) RuleHdrTest::RuleHdrTest(Prot arg_prot, Comp arg_comp, vector<IPPrefix> arg_v)
{ {
prot = arg_prot; prot = arg_prot;
offset = 0; offset = 0;
@ -81,15 +81,15 @@ RuleHdrTest::RuleHdrTest(Prot arg_prot, Comp arg_comp, vector<zeek::IPPrefix> ar
level = 0; level = 0;
} }
zeek::Val* RuleMatcher::BuildRuleStateValue(const Rule* rule, Val* RuleMatcher::BuildRuleStateValue(const Rule* rule,
const RuleEndpointState* state) const const RuleEndpointState* state) const
{ {
static auto signature_state = zeek::id::find_type<zeek::RecordType>("signature_state"); static auto signature_state = id::find_type<RecordType>("signature_state");
auto* val = new zeek::RecordVal(signature_state); auto* val = new RecordVal(signature_state);
val->Assign(0, zeek::make_intrusive<zeek::StringVal>(rule->ID())); val->Assign(0, make_intrusive<StringVal>(rule->ID()));
val->Assign(1, state->GetAnalyzer()->ConnVal()); val->Assign(1, state->GetAnalyzer()->ConnVal());
val->Assign(2, zeek::val_mgr->Bool(state->is_orig)); val->Assign(2, val_mgr->Bool(state->is_orig));
val->Assign(3, zeek::val_mgr->Count(state->payload_size)); val->Assign(3, val_mgr->Count(state->payload_size));
return val; return val;
} }
@ -114,7 +114,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(zeek::util::copy_string(pattern)); copied_set->patterns.push_back(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?
@ -184,9 +184,9 @@ void RuleHdrTest::PrintDebug()
fprintf(stderr, "\n"); fprintf(stderr, "\n");
} }
RuleEndpointState::RuleEndpointState(zeek::analyzer::Analyzer* arg_analyzer, bool arg_is_orig, RuleEndpointState::RuleEndpointState(analyzer::Analyzer* arg_analyzer, bool arg_is_orig,
RuleEndpointState* arg_opposite, RuleEndpointState* arg_opposite,
zeek::analyzer::pia::PIA* arg_PIA) analyzer::pia::PIA* arg_PIA)
{ {
payload_size = -1; payload_size = -1;
analyzer = arg_analyzer; analyzer = arg_analyzer;
@ -262,11 +262,11 @@ bool RuleMatcher::ReadFiles(const std::vector<std::string>& files)
for ( const auto& f : files ) for ( const auto& f : files )
{ {
rules_in = zeek::util::open_file(zeek::util::find_file(f, zeek::util::zeek_path(), ".sig")); rules_in = util::open_file(util::find_file(f, util::zeek_path(), ".sig"));
if ( ! rules_in ) if ( ! rules_in )
{ {
zeek::reporter->Error("Can't open signature file %s", f.data()); reporter->Error("Can't open signature file %s", f.data());
return false; return false;
} }
@ -332,7 +332,7 @@ void RuleMatcher::BuildRulesTree()
} }
void RuleMatcher::InsertRuleIntoTree(Rule* r, int testnr, void RuleMatcher::InsertRuleIntoTree(Rule* r, int testnr,
RuleHdrTest* dest, int level) RuleHdrTest* dest, int level)
{ {
// Initiliaze the preconditions // Initiliaze the preconditions
for ( const auto& pc : r->preconds ) for ( const auto& pc : r->preconds )
@ -384,7 +384,7 @@ void RuleMatcher::InsertRuleIntoTree(Rule* r, int testnr,
} }
void RuleMatcher::BuildRegEx(RuleHdrTest* hdr_test, string_list* exprs, void RuleMatcher::BuildRegEx(RuleHdrTest* hdr_test, string_list* exprs,
int_list* ids) int_list* ids)
{ {
// For each type, get all patterns on this node. // For each type, get all patterns on this node.
for ( Rule* r = hdr_test->pattern_rules; r; r = r->next ) for ( Rule* r = hdr_test->pattern_rules; r; r = r->next )
@ -435,7 +435,7 @@ void RuleMatcher::BuildRegEx(RuleHdrTest* hdr_test, string_list* exprs,
} }
void RuleMatcher::BuildPatternSets(RuleHdrTest::pattern_set_list* dst, void RuleMatcher::BuildPatternSets(RuleHdrTest::pattern_set_list* dst,
const string_list& exprs, const int_list& ids) const string_list& exprs, const int_list& ids)
{ {
assert(static_cast<size_t>(exprs.length()) == ids.size()); assert(static_cast<size_t>(exprs.length()) == ids.size());
@ -483,7 +483,7 @@ static inline uint32_t getval(const u_char* data, int size)
return ntohl(*(uint32_t*) data); return ntohl(*(uint32_t*) data);
default: default:
zeek::reporter->InternalError("illegal HdrTest size"); reporter->InternalError("illegal HdrTest size");
} }
// Should not be reached. // Should not be reached.
@ -506,12 +506,12 @@ static inline bool match_or(const maskedvalue_list& mvals, uint32_t v, FuncT com
// Evaluate a prefix list (matches if at least one value matches). // Evaluate a prefix list (matches if at least one value matches).
template <typename FuncT> template <typename FuncT>
static inline bool match_or(const vector<zeek::IPPrefix>& prefixes, const zeek::IPAddr& a, static inline bool match_or(const vector<IPPrefix>& prefixes, const IPAddr& a,
FuncT comp) FuncT comp)
{ {
for ( size_t i = 0; i < prefixes.size(); ++i ) for ( size_t i = 0; i < prefixes.size(); ++i )
{ {
zeek::IPAddr masked(a); IPAddr masked(a);
masked.Mask(prefixes[i].LengthIPv6()); masked.Mask(prefixes[i].LengthIPv6());
if ( comp(masked, prefixes[i].Prefix()) ) if ( comp(masked, prefixes[i].Prefix()) )
return true; return true;
@ -535,12 +535,12 @@ static inline bool match_not_and(const maskedvalue_list& mvals, uint32_t v,
// Evaluate a prefix list (doesn't match if any value matches). // Evaluate a prefix list (doesn't match if any value matches).
template <typename FuncT> template <typename FuncT>
static inline bool match_not_and(const vector<zeek::IPPrefix>& prefixes, static inline bool match_not_and(const vector<IPPrefix>& prefixes,
const zeek::IPAddr& a, FuncT comp) const IPAddr& a, FuncT comp)
{ {
for ( size_t i = 0; i < prefixes.size(); ++i ) for ( size_t i = 0; i < prefixes.size(); ++i )
{ {
zeek::IPAddr masked(a); IPAddr masked(a);
masked.Mask(prefixes[i].LengthIPv6()); masked.Mask(prefixes[i].LengthIPv6());
if ( comp(masked, prefixes[i].Prefix()) ) if ( comp(masked, prefixes[i].Prefix()) )
return false; return false;
@ -577,42 +577,42 @@ static inline bool compare(const maskedvalue_list& mvals, uint32_t v,
break; break;
default: default:
zeek::reporter->InternalError("unknown RuleHdrTest comparison type"); reporter->InternalError("unknown RuleHdrTest comparison type");
break; break;
} }
return false; return false;
} }
static inline bool compare(const vector<zeek::IPPrefix>& prefixes, const zeek::IPAddr& a, static inline bool compare(const vector<IPPrefix>& prefixes, const IPAddr& a,
RuleHdrTest::Comp comp) RuleHdrTest::Comp comp)
{ {
switch ( comp ) { switch ( comp ) {
case RuleHdrTest::EQ: case RuleHdrTest::EQ:
return match_or(prefixes, a, std::equal_to<zeek::IPAddr>()); return match_or(prefixes, a, std::equal_to<IPAddr>());
break; break;
case RuleHdrTest::NE: case RuleHdrTest::NE:
return match_not_and(prefixes, a, std::equal_to<zeek::IPAddr>()); return match_not_and(prefixes, a, std::equal_to<IPAddr>());
break; break;
case RuleHdrTest::LT: case RuleHdrTest::LT:
return match_or(prefixes, a, std::less<zeek::IPAddr>()); return match_or(prefixes, a, std::less<IPAddr>());
break; break;
case RuleHdrTest::GT: case RuleHdrTest::GT:
return match_or(prefixes, a, std::greater<zeek::IPAddr>()); return match_or(prefixes, a, std::greater<IPAddr>());
break; break;
case RuleHdrTest::LE: case RuleHdrTest::LE:
return match_or(prefixes, a, std::less_equal<zeek::IPAddr>()); return match_or(prefixes, a, std::less_equal<IPAddr>());
break; break;
case RuleHdrTest::GE: case RuleHdrTest::GE:
return match_or(prefixes, a, std::greater_equal<zeek::IPAddr>()); return match_or(prefixes, a, std::greater_equal<IPAddr>());
break; break;
default: default:
zeek::reporter->InternalError("unknown RuleHdrTest comparison type"); reporter->InternalError("unknown RuleHdrTest comparison type");
break; break;
} }
return false; return false;
@ -638,7 +638,7 @@ RuleFileMagicState* RuleMatcher::InitFileMagic() const
bool RuleMatcher::AllRulePatternsMatched(const Rule* r, MatchPos matchpos, bool RuleMatcher::AllRulePatternsMatched(const Rule* r, MatchPos matchpos,
const AcceptingMatchSet& ams) const AcceptingMatchSet& ams)
{ {
DBG_LOG(zeek::DBG_RULES, "Checking rule: %s", r->id); DBG_LOG(DBG_RULES, "Checking rule: %s", r->id);
// Check whether all patterns of the rule have matched. // Check whether all patterns of the rule have matched.
for ( const auto& pattern : r->patterns ) for ( const auto& pattern : r->patterns )
@ -653,7 +653,7 @@ bool RuleMatcher::AllRulePatternsMatched(const Rule* r, MatchPos matchpos,
// FIXME: How to check for offset ??? ### // FIXME: How to check for offset ??? ###
} }
DBG_LOG(zeek::DBG_RULES, "All patterns of rule satisfied"); DBG_LOG(DBG_RULES, "All patterns of rule satisfied");
return true; return true;
} }
@ -667,16 +667,16 @@ RuleMatcher::MIME_Matches* RuleMatcher::Match(RuleFileMagicState* state,
if ( ! state ) if ( ! state )
{ {
zeek::reporter->Warning("RuleFileMagicState not initialized yet."); reporter->Warning("RuleFileMagicState not initialized yet.");
return rval; return rval;
} }
#ifdef DEBUG #ifdef DEBUG
if ( debug_logger.IsEnabled(zeek::DBG_RULES) ) if ( debug_logger.IsEnabled(DBG_RULES) )
{ {
const char* s = zeek::util::fmt_bytes(reinterpret_cast<const char*>(data), const char* s = 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(DBG_RULES, "Matching %s rules on |%s%s|",
Rule::TypeToString(Rule::FILE_MAGIC), s, Rule::TypeToString(Rule::FILE_MAGIC), s,
len > 40 ? "..." : ""); len > 40 ? "..." : "");
} }
@ -693,7 +693,7 @@ RuleMatcher::MIME_Matches* RuleMatcher::Match(RuleFileMagicState* state,
if ( ! newmatch ) if ( ! newmatch )
return rval; return rval;
DBG_LOG(zeek::DBG_RULES, "New pattern match found"); DBG_LOG(DBG_RULES, "New pattern match found");
AcceptingMatchSet accepted_matches; AcceptingMatchSet accepted_matches;
@ -739,10 +739,10 @@ RuleMatcher::MIME_Matches* RuleMatcher::Match(RuleFileMagicState* state,
return rval; return rval;
} }
RuleEndpointState* RuleMatcher::InitEndpoint(zeek::analyzer::Analyzer* analyzer, RuleEndpointState* RuleMatcher::InitEndpoint(analyzer::Analyzer* analyzer,
const zeek::IP_Hdr* ip, int caplen, const IP_Hdr* ip, int caplen,
RuleEndpointState* opposite, RuleEndpointState* opposite,
bool from_orig, zeek::analyzer::pia::PIA* pia) bool from_orig, analyzer::pia::PIA* pia)
{ {
RuleEndpointState* state = RuleEndpointState* state =
new RuleEndpointState(analyzer, from_orig, opposite, pia); new RuleEndpointState(analyzer, from_orig, opposite, pia);
@ -754,7 +754,7 @@ RuleEndpointState* RuleMatcher::InitEndpoint(zeek::analyzer::Analyzer* analyzer,
{ {
RuleHdrTest* hdr_test = tests[h]; RuleHdrTest* hdr_test = tests[h];
DBG_LOG(zeek::DBG_RULES, "HdrTest %d matches (%s%s)", hdr_test->id, DBG_LOG(DBG_RULES, "HdrTest %d matches (%s%s)", hdr_test->id,
hdr_test->pattern_rules ? "+" : "-", hdr_test->pattern_rules ? "+" : "-",
hdr_test->pure_rules ? "+" : "-"); hdr_test->pure_rules ? "+" : "-");
@ -779,8 +779,7 @@ RuleEndpointState* RuleMatcher::InitEndpoint(zeek::analyzer::Analyzer* analyzer,
{ {
assert(set->re); assert(set->re);
RuleEndpointState::Matcher* m = auto* m = new RuleEndpointState::Matcher;
new RuleEndpointState::Matcher;
m->state = new RE_Match_State(set->re); m->state = new RE_Match_State(set->re);
m->type = (Rule::PatternType) i; m->type = (Rule::PatternType) i;
state->matchers.push_back(m); state->matchers.push_back(m);
@ -832,7 +831,7 @@ RuleEndpointState* RuleMatcher::InitEndpoint(zeek::analyzer::Analyzer* analyzer,
break; break;
default: default:
zeek::reporter->InternalError("unknown RuleHdrTest protocol type"); reporter->InternalError("unknown RuleHdrTest protocol type");
break; break;
} }
@ -852,12 +851,12 @@ RuleEndpointState* RuleMatcher::InitEndpoint(zeek::analyzer::Analyzer* analyzer,
} }
void RuleMatcher::Match(RuleEndpointState* state, Rule::PatternType type, void RuleMatcher::Match(RuleEndpointState* state, Rule::PatternType type,
const u_char* data, int data_len, const u_char* data, int data_len,
bool bol, bool eol, bool clear) bool bol, bool eol, bool clear)
{ {
if ( ! state ) if ( ! state )
{ {
zeek::reporter->Warning("RuleEndpointState not initialized yet."); reporter->Warning("RuleEndpointState not initialized yet.");
return; return;
} }
@ -869,12 +868,12 @@ void RuleMatcher::Match(RuleEndpointState* state, Rule::PatternType type,
bool newmatch = false; bool newmatch = false;
#ifdef DEBUG #ifdef DEBUG
if ( debug_logger.IsEnabled(zeek::DBG_RULES) ) if ( debug_logger.IsEnabled(DBG_RULES) )
{ {
const char* s = const char* s =
zeek::util::fmt_bytes((const char *) data, min(40, data_len)); 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(DBG_RULES, "Matching %s rules [%d,%d] on |%s%s|",
Rule::TypeToString(type), bol, eol, s, Rule::TypeToString(type), bol, eol, s,
data_len > 40 ? "..." : ""); data_len > 40 ? "..." : "");
} }
@ -905,7 +904,7 @@ void RuleMatcher::Match(RuleEndpointState* state, Rule::PatternType type,
if ( ! newmatch ) if ( ! newmatch )
return; return;
DBG_LOG(zeek::DBG_RULES, "New pattern match found"); DBG_LOG(DBG_RULES, "New pattern match found");
AcceptingMatchSet accepted_matches; AcceptingMatchSet accepted_matches;
@ -941,17 +940,17 @@ void RuleMatcher::Match(RuleEndpointState* state, Rule::PatternType type,
{ {
Rule* r = *it; Rule* r = *it;
DBG_LOG(zeek::DBG_RULES, "Accepted rule: %s", r->id); DBG_LOG(DBG_RULES, "Accepted rule: %s", r->id);
for ( const auto& h : state->hdr_tests ) for ( const auto& h : state->hdr_tests )
{ {
DBG_LOG(zeek::DBG_RULES, "Checking for accepted rule on HdrTest %d", h->id); DBG_LOG(DBG_RULES, "Checking for accepted rule on HdrTest %d", h->id);
// Skip if rule does not belong to this node. // Skip if rule does not belong to this node.
if ( ! h->ruleset->Contains(r->Index()) ) if ( ! h->ruleset->Contains(r->Index()) )
continue; continue;
DBG_LOG(zeek::DBG_RULES, "On current node"); DBG_LOG(DBG_RULES, "On current node");
// Skip if rule already fired for this connection. // Skip if rule already fired for this connection.
if ( is_member_of(state->matched_rules, r->Index()) ) if ( is_member_of(state->matched_rules, r->Index()) )
@ -961,11 +960,11 @@ void RuleMatcher::Match(RuleEndpointState* state, Rule::PatternType type,
if ( ! state->matched_by_patterns.is_member(r) ) if ( ! state->matched_by_patterns.is_member(r) )
{ {
state->matched_by_patterns.push_back(r); state->matched_by_patterns.push_back(r);
zeek::String* s = new zeek::String(data, data_len, false); String* s = new String(data, data_len, false);
state->matched_text.push_back(s); state->matched_text.push_back(s);
} }
DBG_LOG(zeek::DBG_RULES, "And has not already fired"); DBG_LOG(DBG_RULES, "And has not already fired");
// Eval additional conditions. // Eval additional conditions.
if ( ! EvalRuleConditions(r, state, data, data_len, false) ) if ( ! EvalRuleConditions(r, state, data, data_len, false) )
continue; continue;
@ -1001,17 +1000,17 @@ void RuleMatcher::ExecPureRules(RuleEndpointState* state, bool eos)
} }
} }
bool RuleMatcher::ExecRulePurely(Rule* r, zeek::String* s, bool RuleMatcher::ExecRulePurely(Rule* r, String* s,
RuleEndpointState* state, bool eos) RuleEndpointState* state, bool eos)
{ {
if ( is_member_of(state->matched_rules, r->Index()) ) if ( is_member_of(state->matched_rules, r->Index()) )
return false; return false;
DBG_LOG(zeek::DBG_RULES, "Checking rule %s purely", r->ID()); DBG_LOG(DBG_RULES, "Checking rule %s purely", r->ID());
if ( EvalRuleConditions(r, state, nullptr, 0, eos) ) if ( EvalRuleConditions(r, state, nullptr, 0, eos) )
{ {
DBG_LOG(zeek::DBG_RULES, "MATCH!"); DBG_LOG(DBG_RULES, "MATCH!");
if ( s ) if ( s )
ExecRuleActions(r, state, s->Bytes(), s->Len(), eos); ExecRuleActions(r, state, s->Bytes(), s->Len(), eos);
@ -1027,7 +1026,7 @@ bool RuleMatcher::ExecRulePurely(Rule* r, zeek::String* s,
bool RuleMatcher::EvalRuleConditions(Rule* r, RuleEndpointState* state, bool RuleMatcher::EvalRuleConditions(Rule* r, RuleEndpointState* state,
const u_char* data, int len, bool eos) const u_char* data, int len, bool eos)
{ {
DBG_LOG(zeek::DBG_RULES, "Evaluating conditions for rule %s", r->ID()); DBG_LOG(DBG_RULES, "Evaluating conditions for rule %s", r->ID());
// Check for other rules which have to match first. // Check for other rules which have to match first.
for ( const auto& pc : r->preconds ) for ( const auto& pc : r->preconds )
@ -1064,7 +1063,7 @@ bool RuleMatcher::EvalRuleConditions(Rule* r, RuleEndpointState* state,
if ( ! cond->DoMatch(r, state, data, len) ) if ( ! cond->DoMatch(r, state, data, len) )
return false; return false;
DBG_LOG(zeek::DBG_RULES, "Conditions met: MATCH! %s", r->ID()); DBG_LOG(DBG_RULES, "Conditions met: MATCH! %s", r->ID());
return true; return true;
} }
@ -1230,22 +1229,22 @@ void RuleMatcher::GetStats(Stats* stats, RuleHdrTest* hdr_test)
GetStats(stats, h); GetStats(stats, h);
} }
void RuleMatcher::DumpStats(zeek::File* f) void RuleMatcher::DumpStats(File* f)
{ {
Stats stats; Stats stats;
GetStats(&stats); GetStats(&stats);
f->Write(zeek::util::fmt("%.6f computed dfa states = %d; classes = ??; " f->Write(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::run_state::network_time, stats.dfa_states, stats.computed, run_state::network_time, stats.dfa_states, stats.computed,
stats.matchers, stats.mem)); stats.matchers, stats.mem));
f->Write(zeek::util::fmt("%.6f DFA cache hits = %d; misses = %d\n", zeek::run_state::network_time, f->Write(util::fmt("%.6f DFA cache hits = %d; misses = %d\n", run_state::network_time,
stats.hits, stats.misses)); stats.hits, stats.misses));
DumpStateStats(f, root); DumpStateStats(f, root);
} }
void RuleMatcher::DumpStateStats(zeek::File* f, RuleHdrTest* hdr_test) void RuleMatcher::DumpStateStats(File* f, RuleHdrTest* hdr_test)
{ {
if ( ! hdr_test ) if ( ! hdr_test )
return; return;
@ -1257,15 +1256,15 @@ 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(zeek::util::fmt("%.6f %d DFA states in %s group %d from sigs ", f->Write(util::fmt("%.6f %d DFA states in %s group %d from sigs ",
zeek::run_state::network_time, run_state::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(zeek::util::fmt("%s ", r->ID())); f->Write(util::fmt("%s ", r->ID()));
} }
f->Write("\n"); f->Write("\n");
@ -1276,9 +1275,9 @@ void RuleMatcher::DumpStateStats(zeek::File* f, RuleHdrTest* hdr_test)
DumpStateStats(f, h); DumpStateStats(f, h);
} }
static zeek::Val* get_bro_val(const char* label) static Val* get_bro_val(const char* label)
{ {
auto id = zeek::detail::lookup_ID(label, GLOBAL_MODULE_NAME, false); auto id = lookup_ID(label, GLOBAL_MODULE_NAME, false);
if ( ! id ) if ( ! id )
{ {
rules_error("unknown script-level identifier", label); rules_error("unknown script-level identifier", label);
@ -1292,26 +1291,26 @@ static zeek::Val* get_bro_val(const char* label)
// Converts an atomic Val and appends it to the list. For subnet types, // Converts an atomic Val and appends it to the list. For subnet types,
// if the prefix_vector param isn't null, appending to that is preferred // if the prefix_vector param isn't null, appending to that is preferred
// over appending to the masked val list. // over appending to the masked val list.
static bool val_to_maskedval(zeek::Val* v, maskedvalue_list* append_to, static bool val_to_maskedval(Val* v, maskedvalue_list* append_to,
vector<zeek::IPPrefix>* prefix_vector) vector<IPPrefix>* prefix_vector)
{ {
MaskedValue* mval = new MaskedValue; MaskedValue* mval = new MaskedValue;
switch ( v->GetType()->Tag() ) { switch ( v->GetType()->Tag() ) {
case zeek::TYPE_PORT: case TYPE_PORT:
mval->val = v->AsPortVal()->Port(); mval->val = v->AsPortVal()->Port();
mval->mask = 0xffffffff; mval->mask = 0xffffffff;
break; break;
case zeek::TYPE_BOOL: case TYPE_BOOL:
case zeek::TYPE_COUNT: case TYPE_COUNT:
case zeek::TYPE_ENUM: case TYPE_ENUM:
case zeek::TYPE_INT: case TYPE_INT:
mval->val = v->CoerceToUnsigned(); mval->val = v->CoerceToUnsigned();
mval->mask = 0xffffffff; mval->mask = 0xffffffff;
break; break;
case zeek::TYPE_SUBNET: case TYPE_SUBNET:
{ {
if ( prefix_vector ) if ( prefix_vector )
{ {
@ -1360,13 +1359,13 @@ static bool val_to_maskedval(zeek::Val* v, maskedvalue_list* append_to,
} }
void id_to_maskedvallist(const char* id, maskedvalue_list* append_to, void id_to_maskedvallist(const char* id, maskedvalue_list* append_to,
vector<zeek::IPPrefix>* prefix_vector) vector<IPPrefix>* prefix_vector)
{ {
zeek::Val* v = get_bro_val(id); Val* v = get_bro_val(id);
if ( ! v ) if ( ! v )
return; return;
if ( v->GetType()->Tag() == zeek::TYPE_TABLE ) if ( v->GetType()->Tag() == TYPE_TABLE )
{ {
auto lv = v->AsTableVal()->ToPureListVal(); auto lv = v->AsTableVal()->ToPureListVal();
@ -1381,14 +1380,14 @@ void id_to_maskedvallist(const char* id, maskedvalue_list* append_to,
char* id_to_str(const char* id) char* id_to_str(const char* id)
{ {
const zeek::String* src; const String* src;
char* dst; char* dst;
zeek::Val* v = get_bro_val(id); Val* v = get_bro_val(id);
if ( ! v ) if ( ! v )
goto error; goto error;
if ( v->GetType()->Tag() != zeek::TYPE_STRING ) if ( v->GetType()->Tag() != TYPE_STRING )
{ {
rules_error("Identifier must refer to string"); rules_error("Identifier must refer to string");
goto error; goto error;
@ -1401,28 +1400,28 @@ char* id_to_str(const char* id)
return dst; return dst;
error: error:
char* dummy = zeek::util::copy_string("<error>"); char* dummy = util::copy_string("<error>");
return dummy; return dummy;
} }
uint32_t id_to_uint(const char* id) uint32_t id_to_uint(const char* id)
{ {
zeek::Val* v = get_bro_val(id); Val* v = get_bro_val(id);
if ( ! v ) if ( ! v )
return 0; return 0;
zeek::TypeTag t = v->GetType()->Tag(); TypeTag t = v->GetType()->Tag();
if ( t == zeek::TYPE_BOOL || t == zeek::TYPE_COUNT || t == zeek::TYPE_ENUM || if ( t == TYPE_BOOL || t == TYPE_COUNT || t == TYPE_ENUM ||
t == zeek::TYPE_INT || t == zeek::TYPE_PORT ) t == TYPE_INT || t == TYPE_PORT )
return v->CoerceToUnsigned(); return v->CoerceToUnsigned();
rules_error("Identifier must refer to integer"); rules_error("Identifier must refer to integer");
return 0; return 0;
} }
void RuleMatcherState::InitEndpointMatcher(zeek::analyzer::Analyzer* analyzer, const zeek::IP_Hdr* ip, void RuleMatcherState::InitEndpointMatcher(analyzer::Analyzer* analyzer, const IP_Hdr* ip,
int caplen, bool from_orig, zeek::analyzer::pia::PIA* pia) int caplen, bool from_orig, analyzer::pia::PIA* pia)
{ {
if ( ! rule_matcher ) if ( ! rule_matcher )
return; return;
@ -1471,9 +1470,9 @@ void RuleMatcherState::FinishEndpointMatcher()
orig_match_state = resp_match_state = nullptr; orig_match_state = resp_match_state = nullptr;
} }
void RuleMatcherState::Match(Rule::PatternType type, const u_char* data, void RuleMatcherState::Match(Rule::PatternType type, const u_char* data,
int data_len, bool from_orig, int data_len, bool from_orig,
bool bol, bool eol, bool clear) bool bol, bool eol, bool clear)
{ {
if ( ! rule_matcher ) if ( ! rule_matcher )
return; return;

View file

@ -57,13 +57,13 @@ struct MaskedValue {
uint32_t mask; uint32_t mask;
}; };
using maskedvalue_list = zeek::PList<MaskedValue>; using maskedvalue_list = PList<MaskedValue>;
using string_list = zeek::PList<char>; using string_list = PList<char>;
using bstr_list = zeek::PList<zeek::String>; using bstr_list = PList<String>;
// Get values from Bro's script-level variables. // Get values from Bro's script-level variables.
extern void id_to_maskedvallist(const char* id, maskedvalue_list* append_to, extern void id_to_maskedvallist(const char* id, maskedvalue_list* append_to,
std::vector<zeek::IPPrefix>* prefix_vector = nullptr); std::vector<IPPrefix>* prefix_vector = nullptr);
extern char* id_to_str(const char* id); extern char* id_to_str(const char* id);
extern uint32_t id_to_uint(const char* id); extern uint32_t id_to_uint(const char* id);
@ -75,7 +75,7 @@ public:
RuleHdrTest(Prot arg_prot, uint32_t arg_offset, uint32_t arg_size, RuleHdrTest(Prot arg_prot, uint32_t arg_offset, uint32_t arg_size,
Comp arg_comp, maskedvalue_list* arg_vals); Comp arg_comp, maskedvalue_list* arg_vals);
RuleHdrTest(Prot arg_prot, Comp arg_comp, std::vector<zeek::IPPrefix> arg_v); RuleHdrTest(Prot arg_prot, Comp arg_comp, std::vector<IPPrefix> arg_v);
~RuleHdrTest(); ~RuleHdrTest();
void PrintDebug(); void PrintDebug();
@ -92,7 +92,7 @@ private:
Prot prot; Prot prot;
Comp comp; Comp comp;
maskedvalue_list* vals; maskedvalue_list* vals;
std::vector<zeek::IPPrefix> prefix_vals; // for use with IPSrc/IPDst comparisons std::vector<IPPrefix> prefix_vals; // for use with IPSrc/IPDst comparisons
uint32_t offset; uint32_t offset;
uint32_t size; uint32_t size;
@ -117,7 +117,7 @@ private:
int_list ids; // (only needed for debugging) int_list ids; // (only needed for debugging)
}; };
using pattern_set_list = zeek::PList<PatternSet>; using pattern_set_list = PList<PatternSet>;
pattern_set_list psets[Rule::TYPES]; pattern_set_list psets[Rule::TYPES];
// List of rules belonging to this node. // List of rules belonging to this node.
@ -131,7 +131,7 @@ private:
RuleHdrTest* child; RuleHdrTest* child;
}; };
using rule_hdr_test_list = zeek::PList<RuleHdrTest>; using rule_hdr_test_list = PList<RuleHdrTest>;
// RuleEndpointState keeps the per-stream matching state of one // RuleEndpointState keeps the per-stream matching state of one
// connection endpoint. // connection endpoint.
@ -139,7 +139,7 @@ class RuleEndpointState {
public: public:
~RuleEndpointState(); ~RuleEndpointState();
zeek::analyzer::Analyzer* GetAnalyzer() const { return analyzer; } analyzer::Analyzer* GetAnalyzer() const { return analyzer; }
bool IsOrig() { return is_orig; } bool IsOrig() { return is_orig; }
// For flipping roles. // For flipping roles.
@ -151,26 +151,26 @@ public:
// Returns -1 if no chunk has been fed yet at all. // Returns -1 if no chunk has been fed yet at all.
int PayloadSize() { return payload_size; } int PayloadSize() { return payload_size; }
zeek::analyzer::pia::PIA* PIA() const { return pia; } analyzer::pia::PIA* PIA() const { return pia; }
private: private:
friend class RuleMatcher; friend class RuleMatcher;
// Constructor is private; use RuleMatcher::InitEndpoint() // Constructor is private; use RuleMatcher::InitEndpoint()
// for creating an instance. // for creating an instance.
RuleEndpointState(zeek::analyzer::Analyzer* arg_analyzer, bool arg_is_orig, RuleEndpointState(analyzer::Analyzer* arg_analyzer, bool arg_is_orig,
RuleEndpointState* arg_opposite, zeek::analyzer::pia::PIA* arg_PIA); RuleEndpointState* arg_opposite, analyzer::pia::PIA* arg_PIA);
struct Matcher { struct Matcher {
RE_Match_State* state; RE_Match_State* state;
Rule::PatternType type; Rule::PatternType type;
}; };
using matcher_list = zeek::PList<Matcher>; using matcher_list = PList<Matcher>;
zeek::analyzer::Analyzer* analyzer; analyzer::Analyzer* analyzer;
RuleEndpointState* opposite; RuleEndpointState* opposite;
zeek::analyzer::pia::PIA* pia; analyzer::pia::PIA* pia;
matcher_list matchers; matcher_list matchers;
rule_hdr_test_list hdr_tests; rule_hdr_test_list hdr_tests;
@ -205,7 +205,7 @@ private:
RE_Match_State* state; RE_Match_State* state;
}; };
using matcher_list = zeek::PList<Matcher>; using matcher_list = PList<Matcher>;
matcher_list matchers; matcher_list matchers;
}; };
@ -262,9 +262,9 @@ public:
// the given packet (which should be the first packet encountered for // the given packet (which should be the first packet encountered for
// this endpoint). If the matching is triggered by an PIA, a pointer to // this endpoint). If the matching is triggered by an PIA, a pointer to
// it needs to be given. // it needs to be given.
RuleEndpointState* InitEndpoint(zeek::analyzer::Analyzer* analyzer, const zeek::IP_Hdr* ip, RuleEndpointState* InitEndpoint(analyzer::Analyzer* analyzer, const IP_Hdr* ip,
int caplen, RuleEndpointState* opposite, bool is_orig, int caplen, RuleEndpointState* opposite, bool is_orig,
zeek::analyzer::pia::PIA* pia); analyzer::pia::PIA* pia);
// Finish matching for this stream. // Finish matching for this stream.
void FinishEndpoint(RuleEndpointState* state); void FinishEndpoint(RuleEndpointState* state);
@ -304,11 +304,11 @@ public:
unsigned int misses; // # cache misses unsigned int misses; // # cache misses
}; };
zeek::Val* BuildRuleStateValue(const Rule* rule, Val* BuildRuleStateValue(const Rule* rule,
const RuleEndpointState* state) const; const RuleEndpointState* state) const;
void GetStats(Stats* stats, RuleHdrTest* hdr_test = nullptr); void GetStats(Stats* stats, RuleHdrTest* hdr_test = nullptr);
void DumpStats(zeek::File* f); void DumpStats(File* f);
private: private:
// Delete node and all children. // Delete node and all children.
@ -338,7 +338,7 @@ private:
// Eval a rule under the assumption that all its patterns // Eval a rule under the assumption that all its patterns
// have already matched. s holds the text the rule matched, // have already matched. s holds the text the rule matched,
// or nil if N/A. // or nil if N/A.
bool ExecRulePurely(Rule* r, zeek::String* s, bool ExecRulePurely(Rule* r, String* s,
RuleEndpointState* state, bool eos); RuleEndpointState* state, bool eos);
// Execute the actions associated with a rule. // Execute the actions associated with a rule.
@ -351,7 +351,7 @@ private:
void PrintTreeDebug(RuleHdrTest* node); void PrintTreeDebug(RuleHdrTest* node);
void DumpStateStats(zeek::File* f, RuleHdrTest* hdr_test); void DumpStateStats(File* f, RuleHdrTest* hdr_test);
static bool AllRulePatternsMatched(const Rule* r, MatchPos matchpos, static bool AllRulePatternsMatched(const Rule* r, MatchPos matchpos,
const AcceptingMatchSet& ams); const AcceptingMatchSet& ams);
@ -372,8 +372,8 @@ public:
{ delete orig_match_state; delete resp_match_state; } { delete orig_match_state; delete resp_match_state; }
// ip may be nil. // ip may be nil.
void InitEndpointMatcher(zeek::analyzer::Analyzer* analyzer, const zeek::IP_Hdr* ip, void InitEndpointMatcher(analyzer::Analyzer* analyzer, const IP_Hdr* ip,
int caplen, bool from_orig, zeek::analyzer::pia::PIA* pia = nullptr); int caplen, bool from_orig, analyzer::pia::PIA* pia = nullptr);
// bol/eol should be set to false for type Rule::PAYLOAD; they're // bol/eol should be set to false for type Rule::PAYLOAD; they're
// deduced automatically. // deduced automatically.

View file

@ -47,9 +47,9 @@ extern int signal_val;
namespace zeek::run_state { namespace zeek::run_state {
namespace detail { namespace detail {
zeek::iosource::PktDumper* pkt_dumper = nullptr; iosource::PktDumper* pkt_dumper = nullptr;
zeek::iosource::PktSrc* current_pktsrc = nullptr; iosource::PktSrc* current_pktsrc = nullptr;
zeek::iosource::IOSource* current_iosrc = nullptr; iosource::IOSource* current_iosrc = nullptr;
bool have_pending_timers = false; bool have_pending_timers = false;
RETSIGTYPE watchdog(int /* signo */) RETSIGTYPE watchdog(int /* signo */)
@ -79,7 +79,7 @@ RETSIGTYPE watchdog(int /* signo */)
// handler and the allocation routines are not // handler and the allocation routines are not
// reentrant. // reentrant.
double ct = zeek::util::current_time(); double ct = 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);
@ -96,10 +96,10 @@ RETSIGTYPE watchdog(int /* signo */)
// saving the packet which caused the // saving the packet which caused the
// watchdog to trigger may be helpful, // watchdog to trigger may be helpful,
// so we'll save that one nevertheless. // so we'll save that one nevertheless.
pkt_dumper = zeek::iosource_mgr->OpenPktDumper("watchdog-pkt.pcap", false); pkt_dumper = iosource_mgr->OpenPktDumper("watchdog-pkt.pcap", false);
if ( ! pkt_dumper || pkt_dumper->IsError() ) if ( ! pkt_dumper || pkt_dumper->IsError() )
{ {
zeek::reporter->Error("watchdog: can't open watchdog-pkt.pcap for writing"); reporter->Error("watchdog: can't open watchdog-pkt.pcap for writing");
pkt_dumper = nullptr; pkt_dumper = nullptr;
} }
} }
@ -112,7 +112,7 @@ RETSIGTYPE watchdog(int /* signo */)
get_final_stats(); get_final_stats();
finish_run(0); finish_run(0);
zeek::reporter->FatalErrorWithCore( reporter->FatalErrorWithCore(
"**watchdog timer expired, t = %d.%06d, start = %d.%06d, dispatched = %d", "**watchdog timer expired, t = %d.%06d, start = %d.%06d, dispatched = %d",
int_ct, frac_ct, int_pst, frac_pst, int_ct, frac_ct, int_pst, frac_pst,
current_dispatched); current_dispatched);
@ -141,23 +141,23 @@ void init_run(const std::optional<std::string>& interface,
reading_live = pseudo_realtime > 0.0; reading_live = pseudo_realtime > 0.0;
reading_traces = true; reading_traces = true;
zeek::iosource::PktSrc* ps = zeek::iosource_mgr->OpenPktSrc(*pcap_input_file, false); iosource::PktSrc* ps = iosource_mgr->OpenPktSrc(*pcap_input_file, false);
assert(ps); assert(ps);
if ( ! ps->IsOpen() ) if ( ! ps->IsOpen() )
zeek::reporter->FatalError("problem with trace file %s (%s)", reporter->FatalError("problem with trace file %s (%s)",
pcap_input_file->c_str(), ps->ErrorMsg()); pcap_input_file->c_str(), ps->ErrorMsg());
} }
else if ( interface ) else if ( interface )
{ {
reading_live = true; reading_live = true;
reading_traces = false; reading_traces = false;
zeek::iosource::PktSrc* ps = zeek::iosource_mgr->OpenPktSrc(*interface, true); iosource::PktSrc* ps = iosource_mgr->OpenPktSrc(*interface, true);
assert(ps); assert(ps);
if ( ! ps->IsOpen() ) if ( ! ps->IsOpen() )
zeek::reporter->FatalError("problem with interface %s (%s)", reporter->FatalError("problem with interface %s (%s)",
interface->c_str(), ps->ErrorMsg()); interface->c_str(), ps->ErrorMsg());
} }
@ -171,22 +171,22 @@ void init_run(const std::optional<std::string>& interface,
if ( pcap_output_file ) if ( pcap_output_file )
{ {
const char* writefile = pcap_output_file->data(); const char* writefile = pcap_output_file->data();
pkt_dumper = zeek::iosource_mgr->OpenPktDumper(writefile, false); pkt_dumper = iosource_mgr->OpenPktDumper(writefile, false);
assert(pkt_dumper); assert(pkt_dumper);
if ( ! pkt_dumper->IsOpen() ) if ( ! pkt_dumper->IsOpen() )
zeek::reporter->FatalError("problem opening dump file %s (%s)", reporter->FatalError("problem opening dump file %s (%s)",
writefile, pkt_dumper->ErrorMsg()); writefile, pkt_dumper->ErrorMsg());
if ( const auto& id = zeek::detail::global_scope()->Find("trace_output_file") ) if ( const auto& id = zeek::detail::global_scope()->Find("trace_output_file") )
id->SetVal(zeek::make_intrusive<zeek::StringVal>(writefile)); id->SetVal(make_intrusive<StringVal>(writefile));
else else
zeek::reporter->Error("trace_output_file not defined in bro.init"); reporter->Error("trace_output_file not defined in bro.init");
} }
zeek::detail::init_ip_addr_anonymizers(); zeek::detail::init_ip_addr_anonymizers();
zeek::sessions = new zeek::NetSessions(); sessions = new NetSessions();
if ( do_watchdog ) if ( do_watchdog )
{ {
@ -196,7 +196,7 @@ void init_run(const std::optional<std::string>& interface,
} }
} }
void expire_timers(zeek::iosource::PktSrc* src_ps) void expire_timers(iosource::PktSrc* src_ps)
{ {
zeek::detail::SegmentProfiler prof(zeek::detail::segment_logger, "expiring-timers"); zeek::detail::SegmentProfiler prof(zeek::detail::segment_logger, "expiring-timers");
@ -205,14 +205,14 @@ void expire_timers(zeek::iosource::PktSrc* src_ps)
zeek::detail::max_timer_expires - current_dispatched); zeek::detail::max_timer_expires - current_dispatched);
} }
void dispatch_packet(double t, const zeek::Packet* pkt, zeek::iosource::PktSrc* src_ps) void dispatch_packet(double t, const Packet* pkt, iosource::PktSrc* src_ps)
{ {
if ( ! zeek_start_network_time ) if ( ! zeek_start_network_time )
{ {
zeek_start_network_time = t; zeek_start_network_time = t;
if ( network_time_init ) if ( network_time_init )
zeek::event_mgr.Enqueue(network_time_init, zeek::Args{}); event_mgr.Enqueue(network_time_init, Args{});
} }
// network_time never goes back. // network_time never goes back.
@ -233,19 +233,19 @@ void dispatch_packet(double t, const zeek::Packet* pkt, zeek::iosource::PktSrc*
if ( load_freq == 0 ) if ( load_freq == 0 )
load_freq = uint32_t(0xffffffff) / uint32_t(zeek::detail::load_sample_freq); load_freq = uint32_t(0xffffffff) / uint32_t(zeek::detail::load_sample_freq);
if ( uint32_t(zeek::util::detail::random_number() & 0xffffffff) < load_freq ) if ( uint32_t(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.
zeek::event_mgr.Drain(); event_mgr.Drain();
zeek::detail::sample_logger = new zeek::detail::SampleLogger(); zeek::detail::sample_logger = new zeek::detail::SampleLogger();
sp = new zeek::detail::SegmentProfiler(zeek::detail::sample_logger, "load-samp"); sp = new zeek::detail::SegmentProfiler(zeek::detail::sample_logger, "load-samp");
} }
} }
zeek::sessions->NextPacket(t, pkt); sessions->NextPacket(t, pkt);
zeek::event_mgr.Drain(); event_mgr.Drain();
if ( sp ) if ( sp )
{ {
@ -262,15 +262,15 @@ void dispatch_packet(double t, const zeek::Packet* pkt, zeek::iosource::PktSrc*
void run_loop() void run_loop()
{ {
zeek::util::detail::set_processing_status("RUNNING", "run_loop"); util::detail::set_processing_status("RUNNING", "run_loop");
std::vector<zeek::iosource::IOSource*> ready; std::vector<iosource::IOSource*> ready;
ready.reserve(zeek::iosource_mgr->TotalSize()); ready.reserve(iosource_mgr->TotalSize());
while ( zeek::iosource_mgr->Size() || while ( iosource_mgr->Size() ||
(zeek::BifConst::exit_only_after_terminate && ! terminating) ) (BifConst::exit_only_after_terminate && ! terminating) )
{ {
zeek::iosource_mgr->FindReadySources(&ready); iosource_mgr->FindReadySources(&ready);
#ifdef DEBUG #ifdef DEBUG
static int loop_counter = 0; static int loop_counter = 0;
@ -279,38 +279,38 @@ void run_loop()
// starting with the first. // starting with the first.
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(DBG_MAINLOOP, "realtime=%.6f ready_count=%zu",
zeek::util::current_time(), ready.size()); util::current_time(), ready.size());
if ( ! ready.empty() ) if ( ! ready.empty() )
loop_counter = 0; loop_counter = 0;
} }
#endif #endif
current_iosrc = nullptr; current_iosrc = nullptr;
auto communication_enabled = zeek::broker_mgr->Active(); auto communication_enabled = broker_mgr->Active();
if ( ! ready.empty() ) if ( ! ready.empty() )
{ {
for ( auto src : ready ) for ( auto src : ready )
{ {
DBG_LOG(zeek::DBG_MAINLOOP, "processing source %s", src->Tag()); DBG_LOG(DBG_MAINLOOP, "processing source %s", src->Tag());
current_iosrc = src; current_iosrc = src;
src->Process(); src->Process();
} }
} }
else if ( (have_pending_timers || communication_enabled || else if ( (have_pending_timers || communication_enabled ||
zeek::BifConst::exit_only_after_terminate) && BifConst::exit_only_after_terminate) &&
! pseudo_realtime ) ! pseudo_realtime )
{ {
// Take advantage of the lull to get up to // Take advantage of the lull to get up to
// 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.
update_network_time(zeek::util::current_time()); update_network_time(util::current_time());
expire_timers(); expire_timers();
} }
zeek::event_mgr.Drain(); event_mgr.Drain();
processing_start_time = 0.0; // = "we're not processing now" processing_start_time = 0.0; // = "we're not processing now"
current_dispatched = 0; current_dispatched = 0;
@ -331,7 +331,7 @@ void run_loop()
{ {
auto have_active_packet_source = false; auto have_active_packet_source = false;
zeek::iosource::PktSrc* ps = zeek::iosource_mgr->GetPktSrc(); iosource::PktSrc* ps = iosource_mgr->GetPktSrc();
if ( ps && ps->IsOpen() ) if ( ps && ps->IsOpen() )
have_active_packet_source = true; have_active_packet_source = true;
@ -350,30 +350,30 @@ void run_loop()
void get_final_stats() void get_final_stats()
{ {
zeek::iosource::PktSrc* ps = zeek::iosource_mgr->GetPktSrc(); iosource::PktSrc* ps = iosource_mgr->GetPktSrc();
if ( ps && ps->IsLive() ) if ( ps && ps->IsLive() )
{ {
zeek::iosource::PktSrc::Stats s; iosource::PktSrc::Stats s;
ps->Statistics(&s); ps->Statistics(&s);
double dropped_pct = s.dropped > 0.0 ? ((double)s.dropped / ((double)s.received + (double)s.dropped)) * 100.0 : 0.0; double dropped_pct = s.dropped > 0.0 ? ((double)s.dropped / ((double)s.received + (double)s.dropped)) * 100.0 : 0.0;
zeek::reporter->Info("%" PRIu64 " packets received on interface %s, %" PRIu64 " (%.2f%%) dropped", reporter->Info("%" PRIu64 " packets received on interface %s, %" PRIu64 " (%.2f%%) dropped",
s.received, ps->Path().c_str(), s.dropped, dropped_pct); s.received, ps->Path().c_str(), s.dropped, dropped_pct);
} }
} }
void finish_run(int drain_events) void finish_run(int drain_events)
{ {
zeek::util::detail::set_processing_status("TERMINATING", "finish_run"); util::detail::set_processing_status("TERMINATING", "finish_run");
if ( drain_events ) if ( drain_events )
{ {
if ( zeek::sessions ) if ( sessions )
zeek::sessions->Drain(); sessions->Drain();
zeek::event_mgr.Drain(); event_mgr.Drain();
if ( zeek::sessions ) if ( sessions )
zeek::sessions->Done(); sessions->Done();
} }
#ifdef DEBUG #ifdef DEBUG
@ -388,9 +388,9 @@ void finish_run(int drain_events)
void delete_run() void delete_run()
{ {
zeek::util::detail::set_processing_status("TERMINATING", "delete_run"); util::detail::set_processing_status("TERMINATING", "delete_run");
delete zeek::sessions; delete sessions;
for ( int i = 0; i < zeek::detail::NUM_ADDR_ANONYMIZATION_METHODS; ++i ) for ( int i = 0; i < zeek::detail::NUM_ADDR_ANONYMIZATION_METHODS; ++i )
delete zeek::detail::ip_anonymizer[i]; delete zeek::detail::ip_anonymizer[i];
@ -409,7 +409,7 @@ double zeek_start_network_time; // timestamp of first packet
bool terminating = false; // whether we're done reading and finishing up bool terminating = false; // whether we're done reading and finishing up
bool is_parsing = false; bool is_parsing = false;
const zeek::Packet *current_pkt = nullptr; const Packet *current_pkt = nullptr;
int current_dispatched = 0; int current_dispatched = 0;
double current_timestamp = 0.0; double current_timestamp = 0.0;
@ -418,7 +418,7 @@ static int _processing_suspended = 0;
void suspend_processing() void suspend_processing()
{ {
if ( _processing_suspended == 0 ) if ( _processing_suspended == 0 )
zeek::reporter->Info("processing suspended"); reporter->Info("processing suspended");
++_processing_suspended; ++_processing_suspended;
} }
@ -427,8 +427,8 @@ void continue_processing()
{ {
if ( _processing_suspended == 1 ) if ( _processing_suspended == 1 )
{ {
zeek::reporter->Info("processing continued"); reporter->Info("processing continued");
if ( zeek::iosource::PktSrc* ps = zeek::iosource_mgr->GetPktSrc() ) if ( iosource::PktSrc* ps = iosource_mgr->GetPktSrc() )
ps->ContinueAfterSuspend(); ps->ContinueAfterSuspend();
} }

View file

@ -12,13 +12,13 @@
namespace zeek::detail { namespace zeek::detail {
using scope_list = zeek::PList<Scope>; using scope_list = PList<Scope>;
static scope_list scopes; static scope_list scopes;
static Scope* top_scope; static Scope* top_scope;
Scope::Scope(zeek::detail::IDPtr id, Scope::Scope(IDPtr id,
std::unique_ptr<std::vector<zeek::detail::AttrPtr>> al) std::unique_ptr<std::vector<AttrPtr>> al)
: scope_id(std::move(id)), attrs(std::move(al)) : scope_id(std::move(id)), attrs(std::move(al))
{ {
return_type = nullptr; return_type = nullptr;
@ -27,27 +27,27 @@ Scope::Scope(zeek::detail::IDPtr id,
{ {
const auto& id_type = scope_id->GetType(); const auto& id_type = scope_id->GetType();
if ( id_type->Tag() == zeek::TYPE_ERROR ) if ( id_type->Tag() == TYPE_ERROR )
return; return;
else if ( id_type->Tag() != zeek::TYPE_FUNC ) else if ( id_type->Tag() != TYPE_FUNC )
zeek::reporter->InternalError("bad scope id"); reporter->InternalError("bad scope id");
zeek::FuncType* ft = id->GetType()->AsFuncType(); FuncType* ft = id->GetType()->AsFuncType();
return_type = ft->Yield(); return_type = ft->Yield();
} }
} }
const zeek::detail::IDPtr& Scope::Find(std::string_view name) const const IDPtr& Scope::Find(std::string_view name) const
{ {
auto entry = local.find(name); auto entry = local.find(name);
if ( entry != local.end() ) if ( entry != local.end() )
return entry->second; return entry->second;
return zeek::detail::ID::nil; return ID::nil;
} }
zeek::detail::IDPtr Scope::Remove(std::string_view name) IDPtr Scope::Remove(std::string_view name)
{ {
auto entry = local.find(name); auto entry = local.find(name);
@ -61,12 +61,12 @@ zeek::detail::IDPtr Scope::Remove(std::string_view name)
return nullptr; return nullptr;
} }
zeek::detail::IDPtr Scope::GenerateTemporary(const char* name) IDPtr Scope::GenerateTemporary(const char* name)
{ {
return zeek::make_intrusive<zeek::detail::ID>(name, zeek::detail::SCOPE_FUNCTION, false); return make_intrusive<ID>(name, SCOPE_FUNCTION, false);
} }
std::vector<zeek::detail::IDPtr> Scope::GetInits() std::vector<IDPtr> Scope::GetInits()
{ {
auto rval = std::move(inits); auto rval = std::move(inits);
inits = {}; inits = {};
@ -102,7 +102,7 @@ void Scope::Describe(ODesc* d) const
for ( const auto& entry : local ) for ( const auto& entry : local )
{ {
zeek::detail::ID* id = entry.second.get(); ID* id = entry.second.get();
id->Describe(d); id->Describe(d);
d->NL(); d->NL();
} }
@ -112,7 +112,7 @@ TraversalCode Scope::Traverse(TraversalCallback* cb) const
{ {
for ( const auto& entry : local ) for ( const auto& entry : local )
{ {
zeek::detail::ID* id = entry.second.get(); ID* id = entry.second.get();
TraversalCode tc = id->Traverse(cb); TraversalCode tc = id->Traverse(cb);
HANDLE_TC_STMT_PRE(tc); HANDLE_TC_STMT_PRE(tc);
} }
@ -121,9 +121,9 @@ TraversalCode Scope::Traverse(TraversalCallback* cb) const
} }
const zeek::detail::IDPtr& lookup_ID(const char* name, const char* curr_module, const IDPtr& lookup_ID(const char* name, const char* curr_module,
bool no_global, bool same_module_only, bool no_global, bool same_module_only,
bool check_export) bool check_export)
{ {
std::string fullname = make_full_var_name(curr_module, name); std::string fullname = make_full_var_name(curr_module, name);
@ -138,8 +138,8 @@ const zeek::detail::IDPtr& lookup_ID(const char* name, const char* curr_module,
if ( id ) if ( id )
{ {
if ( need_export && ! id->IsExport() && ! in_debug ) if ( need_export && ! id->IsExport() && ! in_debug )
zeek::reporter->Error("identifier is not exported: %s", reporter->Error("identifier is not exported: %s",
fullname.c_str()); fullname.c_str());
return id; return id;
} }
@ -152,30 +152,30 @@ const zeek::detail::IDPtr& lookup_ID(const char* name, const char* curr_module,
return global_scope()->Find(globalname); return global_scope()->Find(globalname);
} }
return zeek::detail::ID::nil; return ID::nil;
} }
zeek::detail::IDPtr install_ID(const char* name, const char* module_name, IDPtr install_ID(const char* name, const char* module_name,
bool is_global, bool is_export) bool is_global, bool is_export)
{ {
if ( scopes.empty() && ! is_global ) if ( scopes.empty() && ! is_global )
zeek::reporter->InternalError("local identifier in global scope"); reporter->InternalError("local identifier in global scope");
zeek::detail::IDScope scope; IDScope scope;
if ( is_export || ! module_name || if ( is_export || ! module_name ||
(is_global && (is_global &&
normalized_module_name(module_name) == GLOBAL_MODULE_NAME) ) normalized_module_name(module_name) == GLOBAL_MODULE_NAME) )
scope = zeek::detail::SCOPE_GLOBAL; scope = SCOPE_GLOBAL;
else if ( is_global ) else if ( is_global )
scope = zeek::detail::SCOPE_MODULE; scope = SCOPE_MODULE;
else else
scope = zeek::detail::SCOPE_FUNCTION; scope = SCOPE_FUNCTION;
std::string full_name = make_full_var_name(module_name, name); std::string full_name = make_full_var_name(module_name, name);
auto id = zeek::make_intrusive<zeek::detail::ID>(full_name.data(), scope, is_export); auto id = make_intrusive<ID>(full_name.data(), scope, is_export);
if ( zeek::detail::SCOPE_FUNCTION != scope ) if ( SCOPE_FUNCTION != scope )
global_scope()->Insert(std::move(full_name), id); global_scope()->Insert(std::move(full_name), id);
else else
{ {
@ -191,8 +191,8 @@ void push_existing_scope(Scope* scope)
scopes.push_back(scope); scopes.push_back(scope);
} }
void push_scope(zeek::detail::IDPtr id, void push_scope(IDPtr id,
std::unique_ptr<std::vector<zeek::detail::AttrPtr>> attrs) std::unique_ptr<std::vector<AttrPtr>> attrs)
{ {
top_scope = new Scope(std::move(id), std::move(attrs)); top_scope = new Scope(std::move(id), std::move(attrs));
scopes.push_back(top_scope); scopes.push_back(top_scope);
@ -201,14 +201,14 @@ void push_scope(zeek::detail::IDPtr id,
ScopePtr pop_scope() ScopePtr pop_scope()
{ {
if ( scopes.empty() ) if ( scopes.empty() )
zeek::reporter->InternalError("scope underflow"); reporter->InternalError("scope underflow");
scopes.pop_back(); scopes.pop_back();
Scope* old_top = top_scope; Scope* old_top = top_scope;
top_scope = scopes.empty() ? nullptr : scopes.back(); top_scope = scopes.empty() ? nullptr : scopes.back();
return {zeek::AdoptRef{}, old_top}; return {AdoptRef{}, old_top};
} }
Scope* current_scope() Scope* current_scope()
@ -221,7 +221,7 @@ Scope* global_scope()
return scopes.empty() ? 0 : scopes.front(); return scopes.empty() ? 0 : scopes.front();
} }
} } // namespace zeek::detail
zeek::detail::ID* lookup_ID( zeek::detail::ID* lookup_ID(
const char* name, const char* module, const char* name, const char* module,

View file

@ -21,59 +21,59 @@ ZEEK_FORWARD_DECLARE_NAMESPACED(Attr, zeek::detail);
namespace zeek { namespace zeek {
template <class T> class IntrusivePtr; template <class T> class IntrusivePtr;
using TypePtr = zeek::IntrusivePtr<Type>; using TypePtr = IntrusivePtr<Type>;
namespace detail { namespace detail {
using AttrPtr = zeek::IntrusivePtr<Attr>; using AttrPtr = IntrusivePtr<Attr>;
using IDPtr = zeek::IntrusivePtr<ID>; using IDPtr = IntrusivePtr<ID>;
class Scope; class Scope;
using ScopePtr = zeek::IntrusivePtr<Scope>; using ScopePtr = IntrusivePtr<Scope>;
class Scope : public Obj { class Scope : public Obj {
public: public:
explicit Scope(zeek::detail::IDPtr id, explicit Scope(IDPtr id,
std::unique_ptr<std::vector<zeek::detail::AttrPtr>> al); std::unique_ptr<std::vector<AttrPtr>> al);
const zeek::detail::IDPtr& Find(std::string_view name) const; const IDPtr& Find(std::string_view name) const;
template<typename N> template<typename N>
[[deprecated("Remove in v4.1. Use Find().")]] [[deprecated("Remove in v4.1. Use Find().")]]
zeek::detail::ID* Lookup(N&& name) const ID* Lookup(N&& name) const
{ return Find(name).get(); } { return Find(name).get(); }
template<typename N, typename I> template<typename N, typename I>
void Insert(N&& name, I&& id) { local[std::forward<N>(name)] = std::forward<I>(id); } void Insert(N&& name, I&& id) { local[std::forward<N>(name)] = std::forward<I>(id); }
zeek::detail::IDPtr Remove(std::string_view name); IDPtr Remove(std::string_view name);
[[deprecated("Remove in v4.1. Use GetID().")]] [[deprecated("Remove in v4.1. Use GetID().")]]
zeek::detail::ID* ScopeID() const { return scope_id.get(); } ID* ScopeID() const { return scope_id.get(); }
const zeek::detail::IDPtr& GetID() const const IDPtr& GetID() const
{ return scope_id; } { return scope_id; }
const std::unique_ptr<std::vector<zeek::detail::AttrPtr>>& Attrs() const const std::unique_ptr<std::vector<AttrPtr>>& Attrs() const
{ return attrs; } { return attrs; }
[[deprecated("Remove in v4.1. Use GetReturnTrype().")]] [[deprecated("Remove in v4.1. Use GetReturnTrype().")]]
zeek::Type* ReturnType() const { return return_type.get(); } Type* ReturnType() const { return return_type.get(); }
const zeek::TypePtr& GetReturnType() const const TypePtr& GetReturnType() const
{ return return_type; } { return return_type; }
size_t Length() const { return local.size(); } size_t Length() const { return local.size(); }
const auto& Vars() { return local; } const auto& Vars() { return local; }
zeek::detail::IDPtr GenerateTemporary(const char* name); IDPtr GenerateTemporary(const char* name);
// Returns the list of variables needing initialization, and // Returns the list of variables needing initialization, and
// removes it from this Scope. // removes it from this Scope.
std::vector<zeek::detail::IDPtr> GetInits(); std::vector<IDPtr> GetInits();
// Adds a variable to the list. // Adds a variable to the list.
void AddInit(zeek::detail::IDPtr id) void AddInit(IDPtr id)
{ inits.emplace_back(std::move(id)); } { inits.emplace_back(std::move(id)); }
void Describe(ODesc* d) const override; void Describe(ODesc* d) const override;
@ -81,26 +81,25 @@ public:
TraversalCode Traverse(TraversalCallback* cb) const; TraversalCode Traverse(TraversalCallback* cb) const;
protected: protected:
zeek::detail::IDPtr scope_id; IDPtr scope_id;
std::unique_ptr<std::vector<zeek::detail::AttrPtr>> attrs; std::unique_ptr<std::vector<AttrPtr>> attrs;
zeek::TypePtr return_type; TypePtr return_type;
std::map<std::string, zeek::detail::IDPtr, std::less<>> local; std::map<std::string, IDPtr, std::less<>> local;
std::vector<zeek::detail::IDPtr> inits; std::vector<IDPtr> inits;
}; };
// If no_global is true, don't search in the default "global" namespace. // If no_global is true, don't search in the default "global" namespace.
extern const zeek::detail::IDPtr& lookup_ID( extern const IDPtr& lookup_ID(
const char* name, const char* module, const char* name, const char* module,
bool no_global = false, bool no_global = false,
bool same_module_only = false, bool same_module_only = false,
bool check_export = true); bool check_export = true);
extern zeek::detail::IDPtr install_ID( extern IDPtr install_ID(
const char* name, const char* module_name, const char* name, const char* module_name,
bool is_global, bool is_export); bool is_global, bool is_export);
extern void push_scope(zeek::detail::IDPtr id, extern void push_scope(IDPtr id, std::unique_ptr<std::vector<AttrPtr>> attrs);
std::unique_ptr<std::vector<zeek::detail::AttrPtr>> attrs);
extern void push_existing_scope(Scope* scope); extern void push_existing_scope(Scope* scope);
// Returns the one popped off. // Returns the one popped off.

View file

@ -28,18 +28,18 @@ ScriptCoverageManager::~ScriptCoverageManager()
Unref(s); Unref(s);
} }
void ScriptCoverageManager::AddStmt(zeek::detail::Stmt* s) void ScriptCoverageManager::AddStmt(Stmt* s)
{ {
if ( ignoring != 0 ) if ( ignoring != 0 )
return; return;
zeek::Ref(s); Ref(s);
stmts.push_back(s); stmts.push_back(s);
} }
bool ScriptCoverageManager::ReadStats() bool ScriptCoverageManager::ReadStats()
{ {
char* bf = zeek::util::zeekenv("ZEEK_PROFILER_FILE"); char* bf = 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;
zeek::util::tokenize_string(file_contents, "\n", &lines); 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;
zeek::util::tokenize_string(line, delimiter, &line_components); 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;
zeek::util::atoi_n(cnt.size(), cnt.c_str(), nullptr, 10, count); 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,16 +89,16 @@ bool ScriptCoverageManager::ReadStats()
bool ScriptCoverageManager::WriteStats() bool ScriptCoverageManager::WriteStats()
{ {
char* bf = zeek::util::zeekenv("ZEEK_PROFILER_FILE"); char* bf = util::zeekenv("ZEEK_PROFILER_FILE");
if ( ! bf ) if ( ! bf )
return false; return false;
zeek::util::SafeDirname dirname{bf}; util::SafeDirname dirname{bf};
if ( ! zeek::util::detail::ensure_intermediate_dirs(dirname.result.data()) ) if ( ! util::detail::ensure_intermediate_dirs(dirname.result.data()) )
{ {
zeek::reporter->Error("Failed to open ZEEK_PROFILER_FILE destination '%s' for writing", bf); reporter->Error("Failed to open ZEEK_PROFILER_FILE destination '%s' for writing", bf);
return false; return false;
} }
@ -113,7 +113,7 @@ bool ScriptCoverageManager::WriteStats()
if ( fd == -1 ) if ( fd == -1 )
{ {
zeek::reporter->Error("Failed to generate unique file name from ZEEK_PROFILER_FILE: %s", bf); reporter->Error("Failed to generate unique file name from ZEEK_PROFILER_FILE: %s", bf);
return false; return false;
} }
f = fdopen(fd, "w"); f = fdopen(fd, "w");
@ -125,11 +125,11 @@ bool ScriptCoverageManager::WriteStats()
if ( ! f ) if ( ! f )
{ {
zeek::reporter->Error("Failed to open ZEEK_PROFILER_FILE destination '%s' for writing", bf); reporter->Error("Failed to open ZEEK_PROFILER_FILE destination '%s' for writing", bf);
return false; return false;
} }
for ( list<zeek::detail::Stmt*>::const_iterator it = stmts.begin(); for ( list<Stmt*>::const_iterator it = stmts.begin();
it != stmts.end(); ++it ) it != stmts.end(); ++it )
{ {
ODesc location_info; ODesc location_info;

View file

@ -42,13 +42,13 @@ public:
void IncIgnoreDepth() { ignoring++; } void IncIgnoreDepth() { ignoring++; }
void DecIgnoreDepth() { ignoring--; } void DecIgnoreDepth() { ignoring--; }
void AddStmt(zeek::detail::Stmt* s); void AddStmt(Stmt* s);
private: private:
/** /**
* The current, global ScriptCoverageManager instance creates this list at parse-time. * The current, global ScriptCoverageManager instance creates this list at parse-time.
*/ */
std::list<zeek::detail::Stmt*> stmts; std::list<Stmt*> stmts;
/** /**
* Indicates whether new statments will not be considered as part of * Indicates whether new statments will not be considered as part of

View file

@ -45,7 +45,7 @@ void SerializationFormat::StartWrite()
if ( ! output ) if ( ! output )
{ {
output = (char*)zeek::util::safe_malloc(INITIAL_SIZE); output = (char*)util::safe_malloc(INITIAL_SIZE);
output_size = INITIAL_SIZE; output_size = INITIAL_SIZE;
} }
@ -67,7 +67,7 @@ bool SerializationFormat::ReadData(void* b, size_t count)
{ {
if ( input_pos + count > input_len ) if ( input_pos + count > input_len )
{ {
zeek::reporter->Error("data underflow during read in binary format"); reporter->Error("data underflow during read in binary format");
abort(); abort();
return false; return false;
} }
@ -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*)zeek::util::safe_realloc(output, output_size); output = (char*)util::safe_realloc(output, output_size);
memcpy(output + output_pos, b, count); memcpy(output + output_pos, b, count);
output_pos += count; output_pos += count;
@ -109,7 +109,7 @@ bool BinarySerializationFormat::Read(int* v, const char* tag)
return false; return false;
*v = (int) ntohl(tmp); *v = (int) ntohl(tmp);
DBG_LOG(zeek::DBG_SERIAL, "Read int %d [%s]", *v, tag); DBG_LOG(DBG_SERIAL, "Read int %d [%s]", *v, tag);
return true; return true;
} }
@ -119,7 +119,7 @@ bool BinarySerializationFormat::Read(uint16_t* v, const char* tag)
return false; return false;
*v = ntohs(*v); *v = ntohs(*v);
DBG_LOG(zeek::DBG_SERIAL, "Read uint16_t %hu [%s]", *v, tag); DBG_LOG(DBG_SERIAL, "Read uint16_t %hu [%s]", *v, tag);
return true; return true;
} }
@ -129,7 +129,7 @@ bool BinarySerializationFormat::Read(uint32_t* v, const char* tag)
return false; return false;
*v = ntohl(*v); *v = ntohl(*v);
DBG_LOG(zeek::DBG_SERIAL, "Read uint32_t %" PRIu32 " [%s]", *v, tag); DBG_LOG(DBG_SERIAL, "Read uint32_t %" PRIu32 " [%s]", *v, tag);
return true; return true;
} }
@ -141,7 +141,7 @@ bool BinarySerializationFormat::Read(int64_t* v, const char* tag)
return false; return false;
*v = ((int64_t(ntohl(x[0]))) << 32) | ntohl(x[1]); *v = ((int64_t(ntohl(x[0]))) << 32) | ntohl(x[1]);
DBG_LOG(zeek::DBG_SERIAL, "Read int64_t %" PRId64 " [%s]", *v, tag); DBG_LOG(DBG_SERIAL, "Read int64_t %" PRId64 " [%s]", *v, tag);
return true; return true;
} }
@ -152,7 +152,7 @@ bool BinarySerializationFormat::Read(uint64_t* v, const char* tag)
return false; return false;
*v = ((uint64_t(ntohl(x[0]))) << 32) | ntohl(x[1]); *v = ((uint64_t(ntohl(x[0]))) << 32) | ntohl(x[1]);
DBG_LOG(zeek::DBG_SERIAL, "Read uint64_t %" PRIu64 " [%s]", *v, tag); DBG_LOG(DBG_SERIAL, "Read uint64_t %" PRIu64 " [%s]", *v, tag);
return true; return true;
} }
@ -163,7 +163,7 @@ bool BinarySerializationFormat::Read(bool* v, const char* tag)
return false; return false;
*v = c == '\1' ? true : false; *v = c == '\1' ? true : false;
DBG_LOG(zeek::DBG_SERIAL, "Read bool %s [%s]", *v ? "true" : "false", tag); DBG_LOG(DBG_SERIAL, "Read bool %s [%s]", *v ? "true" : "false", tag);
return true; return true;
} }
@ -173,14 +173,14 @@ bool BinarySerializationFormat::Read(double* d, const char* tag)
return false; return false;
*d = ntohd(*d); *d = ntohd(*d);
DBG_LOG(zeek::DBG_SERIAL, "Read double %.6f [%s]", *d, tag); DBG_LOG(DBG_SERIAL, "Read double %.6f [%s]", *d, tag);
return true; return true;
} }
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]", zeek::util::fmt_bytes(v, 1), tag); DBG_LOG(DBG_SERIAL, "Read char %s [%s]", util::fmt_bytes(v, 1), tag);
return ret; return ret;
} }
@ -209,7 +209,7 @@ bool BinarySerializationFormat::Read(char** str, int* len, const char* tag)
for ( int i = 0; i < l; i++ ) for ( int i = 0; i < l; i++ )
if ( ! s[i] ) if ( ! s[i] )
{ {
zeek::reporter->Error("binary Format: string contains null; replaced by '_'"); reporter->Error("binary Format: string contains null; replaced by '_'");
s[i] = '_'; s[i] = '_';
} }
} }
@ -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, zeek::util::fmt_bytes(*str, l), tag); DBG_LOG(DBG_SERIAL, "Read %d bytes |%s| [%s]", l, util::fmt_bytes(*str, l), tag);
return true; return true;
} }
@ -236,7 +236,7 @@ bool BinarySerializationFormat::Read(std::string* v, const char* tag)
return true; return true;
} }
bool BinarySerializationFormat::Read(zeek::IPAddr* addr, const char* tag) bool BinarySerializationFormat::Read(IPAddr* addr, const char* tag)
{ {
int n = 0; int n = 0;
if ( ! Read(&n, "addr-len") ) if ( ! Read(&n, "addr-len") )
@ -256,22 +256,22 @@ bool BinarySerializationFormat::Read(zeek::IPAddr* addr, const char* tag)
} }
if ( n == 1 ) if ( n == 1 )
*addr = zeek::IPAddr(IPv4, raw, zeek::IPAddr::Network); *addr = IPAddr(IPv4, raw, IPAddr::Network);
else else
*addr = zeek::IPAddr(IPv6, raw, zeek::IPAddr::Network); *addr = IPAddr(IPv6, raw, IPAddr::Network);
return true; return true;
} }
bool BinarySerializationFormat::Read(zeek::IPPrefix* prefix, const char* tag) bool BinarySerializationFormat::Read(IPPrefix* prefix, const char* tag)
{ {
zeek::IPAddr addr; IPAddr addr;
int len; int len;
if ( ! (Read(&addr, "prefix") && Read(&len, "width")) ) if ( ! (Read(&addr, "prefix") && Read(&len, "width")) )
return false; return false;
*prefix = zeek::IPPrefix(addr, len); *prefix = IPPrefix(addr, len);
return true; return true;
} }
@ -303,34 +303,34 @@ 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]", zeek::util::fmt_bytes(&v, 1), tag); DBG_LOG(DBG_SERIAL, "Write char %s [%s]", util::fmt_bytes(&v, 1), tag);
return WriteData(&v, 1); return WriteData(&v, 1);
} }
bool BinarySerializationFormat::Write(uint16_t v, const char* tag) bool BinarySerializationFormat::Write(uint16_t v, const char* tag)
{ {
DBG_LOG(zeek::DBG_SERIAL, "Write uint16_t %hu [%s]", v, tag); DBG_LOG(DBG_SERIAL, "Write uint16_t %hu [%s]", v, tag);
v = htons(v); v = htons(v);
return WriteData(&v, sizeof(v)); return WriteData(&v, sizeof(v));
} }
bool BinarySerializationFormat::Write(uint32_t v, const char* tag) bool BinarySerializationFormat::Write(uint32_t v, const char* tag)
{ {
DBG_LOG(zeek::DBG_SERIAL, "Write uint32_t %" PRIu32 " [%s]", v, tag); DBG_LOG(DBG_SERIAL, "Write uint32_t %" PRIu32 " [%s]", v, tag);
v = htonl(v); v = htonl(v);
return WriteData(&v, sizeof(v)); return WriteData(&v, sizeof(v));
} }
bool BinarySerializationFormat::Write(int v, const char* tag) bool BinarySerializationFormat::Write(int v, const char* tag)
{ {
DBG_LOG(zeek::DBG_SERIAL, "Write int %d [%s]", v, tag); DBG_LOG(DBG_SERIAL, "Write int %d [%s]", v, tag);
uint32_t tmp = htonl((uint32_t) v); uint32_t tmp = htonl((uint32_t) v);
return WriteData(&tmp, sizeof(tmp)); return WriteData(&tmp, sizeof(tmp));
} }
bool BinarySerializationFormat::Write(uint64_t v, const char* tag) bool BinarySerializationFormat::Write(uint64_t v, const char* tag)
{ {
DBG_LOG(zeek::DBG_SERIAL, "Write uint64_t %" PRIu64 " [%s]", v, tag); DBG_LOG(DBG_SERIAL, "Write uint64_t %" PRIu64 " [%s]", v, tag);
uint32_t x[2]; uint32_t x[2];
x[0] = htonl(v >> 32); x[0] = htonl(v >> 32);
x[1] = htonl(v & 0xffffffff); x[1] = htonl(v & 0xffffffff);
@ -339,7 +339,7 @@ bool BinarySerializationFormat::Write(uint64_t v, const char* tag)
bool BinarySerializationFormat::Write(int64_t v, const char* tag) bool BinarySerializationFormat::Write(int64_t v, const char* tag)
{ {
DBG_LOG(zeek::DBG_SERIAL, "Write int64_t %" PRId64 " [%s]", v, tag); DBG_LOG(DBG_SERIAL, "Write int64_t %" PRId64 " [%s]", v, tag);
uint32_t x[2]; uint32_t x[2];
x[0] = htonl(v >> 32); x[0] = htonl(v >> 32);
x[1] = htonl(v & 0xffffffff); x[1] = htonl(v & 0xffffffff);
@ -348,14 +348,14 @@ bool BinarySerializationFormat::Write(int64_t v, const char* tag)
bool BinarySerializationFormat::Write(double d, const char* tag) bool BinarySerializationFormat::Write(double d, const char* tag)
{ {
DBG_LOG(zeek::DBG_SERIAL, "Write double %.6f [%s]", d, tag); DBG_LOG(DBG_SERIAL, "Write double %.6f [%s]", d, tag);
d = htond(d); d = htond(d);
return WriteData(&d, sizeof(d)); return WriteData(&d, sizeof(d));
} }
bool BinarySerializationFormat::Write(bool v, const char* tag) bool BinarySerializationFormat::Write(bool v, const char* tag)
{ {
DBG_LOG(zeek::DBG_SERIAL, "Write bool %s [%s]", v ? "true" : "false", tag); DBG_LOG(DBG_SERIAL, "Write bool %s [%s]", v ? "true" : "false", tag);
char c = v ? '\1' : '\0'; char c = v ? '\1' : '\0';
return WriteData(&c, 1); return WriteData(&c, 1);
} }
@ -370,7 +370,7 @@ bool BinarySerializationFormat::Write(const std::string& s, const char* tag)
return Write(s.data(), s.size(), tag); return Write(s.data(), s.size(), tag);
} }
bool BinarySerializationFormat::Write(const zeek::IPAddr& addr, const char* tag) bool BinarySerializationFormat::Write(const IPAddr& addr, const char* tag)
{ {
const uint32_t* raw; const uint32_t* raw;
int n = addr.GetBytes(&raw); int n = addr.GetBytes(&raw);
@ -389,7 +389,7 @@ bool BinarySerializationFormat::Write(const zeek::IPAddr& addr, const char* tag)
return true; return true;
} }
bool BinarySerializationFormat::Write(const zeek::IPPrefix& prefix, const char* tag) bool BinarySerializationFormat::Write(const IPPrefix& prefix, const char* tag)
{ {
return Write(prefix.Prefix(), "prefix") && Write(prefix.Length(), "width"); return Write(prefix.Prefix(), "prefix") && Write(prefix.Length(), "width");
} }
@ -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]", zeek::util::fmt_bytes(buf, len), tag); DBG_LOG(DBG_SERIAL, "Write bytes |%s| [%s]", 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);
} }

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