diff --git a/CHANGES b/CHANGES index 706db77a6b..f407ba843b 100644 --- a/CHANGES +++ b/CHANGES @@ -1,4 +1,38 @@ +3.2.0-dev.853 | 2020-07-02 19:24:09 -0700 + + * Rename BroString files to ZeekString (Tim Wojtulewicz, Corelight) + + * Rename BroObj to Obj (Tim Wojtulewicz, Corelight) + + * Rename BroString to zeek::String (Tim Wojtulewicz, Corelight) + + * Move Func up to zeek namespace, rename BroFunc to ScriptFunc (Tim Wojtulewicz, Corelight) + + * Mark global val_mgr as deprecated and fix uses of it to use namespaced version (Tim Wojtulewicz, Corelight) + + * Update binpac and bifcl submodules with review changes (Tim Wojtulewicz, Corelight) + + * Move Location to zeek::detail and BroObj to zeek (Tim Wojtulewicz, Corelight) + + * Move BroString to zeek namespace (Tim Wojtulewicz, Corelight) + + * Move Dictionary/PDict, List/PList, and Queue/PQueue to zeek namespace (Tim Wojtulewicz, Corelight) + + * Remove typedef that should have been removed in 3.1 (Tim Wojtulewicz, Corelight) + + * Move Func and associated classes into zeek::detail namespace (Tim Wojtulewicz, Corelight) + + * Move Frame and Scope to zeek::detail namespace (Tim Wojtulewicz) + + * Move all Val classes to the zeek namespaces (Tim Wojtulewicz, Corelight) + + * Use type aliases for IntrusivePtr definitions (Tim Wojtulewicz, Corelight) + + * Move deprecation macro to zeek-config.h.in to avoid having to over-include util.h (Tim Wojtulewicz, Corelight) + + * Move IntrusivePtr and utility methods to the zeek namespace (Tim Wojtulewicz, Corelight) + 3.2.0-dev.834 | 2020-07-02 15:57:09 -0700 * GH-786: fix Val::As methods casting incomplete types (Jon Siwek, Corelight) diff --git a/NEWS b/NEWS index b4c5d7bf92..e506c099f2 100644 --- a/NEWS +++ b/NEWS @@ -113,6 +113,10 @@ Changed Functionality but the Deprecated Functionality section below will mention those ones specifically). + This includes a number of renames to classes, removing 'Bro' from their + names. Deprecation warnings should notify plugin developers of these + name changes. + Removed Functionality --------------------- @@ -249,6 +253,8 @@ Deprecated Functionality - The ``Val(double, TypeTag)`` constructor is deprecated, use either ``IntervalVal()``, ``TimeVal()`` or ``DoubleVal()`` constructors. +- The "BroString.h" file is deprecated, use "ZeekString.h" + Zeek 3.1.0 ========== diff --git a/VERSION b/VERSION index 2104f8aaa9..2cf04cac85 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -3.2.0-dev.834 +3.2.0-dev.853 diff --git a/auxil/bifcl b/auxil/bifcl index 9c10bb74bb..3266a0429b 160000 --- a/auxil/bifcl +++ b/auxil/bifcl @@ -1 +1 @@ -Subproject commit 9c10bb74bb62aa7fb10efc079f1b2e5926e9798c +Subproject commit 3266a0429b366abd96234911ecf1de284f43a167 diff --git a/auxil/binpac b/auxil/binpac index 9c3211ff12..881a5eb49b 160000 --- a/auxil/binpac +++ b/auxil/binpac @@ -1 +1 @@ -Subproject commit 9c3211ff121ddc677d0ed8bd3a85783f87921cce +Subproject commit 881a5eb49ba1c22623777009b98a667fb183aeca diff --git a/doc b/doc index e738208f9c..3769071844 160000 --- a/doc +++ b/doc @@ -1 +1 @@ -Subproject commit e738208f9c4c385b42de7066a71de0a2bcf52ec6 +Subproject commit 376907184474f6592ab871b9bd2161140daadb17 diff --git a/src/Anon.cc b/src/Anon.cc index bb878061ae..98d98a9f99 100644 --- a/src/Anon.cc +++ b/src/Anon.cc @@ -358,9 +358,9 @@ AnonymizeIPAddr_A50::Node* AnonymizeIPAddr_A50::find_node(ipaddr32_t a) return nullptr; } -static IntrusivePtr anon_preserve_orig_addr; -static IntrusivePtr anon_preserve_resp_addr; -static IntrusivePtr anon_preserve_other_addr; +static zeek::TableValPtr anon_preserve_orig_addr; +static zeek::TableValPtr anon_preserve_resp_addr; +static zeek::TableValPtr anon_preserve_other_addr; void zeek::detail::init_ip_addr_anonymizers() { @@ -373,23 +373,23 @@ void zeek::detail::init_ip_addr_anonymizers() auto id = global_scope()->Find("preserve_orig_addr"); if ( id ) - anon_preserve_orig_addr = cast_intrusive(id->GetVal()); + anon_preserve_orig_addr = zeek::cast_intrusive(id->GetVal()); id = global_scope()->Find("preserve_resp_addr"); if ( id ) - anon_preserve_resp_addr = cast_intrusive(id->GetVal()); + anon_preserve_resp_addr = zeek::cast_intrusive(id->GetVal()); id = global_scope()->Find("preserve_other_addr"); if ( id ) - anon_preserve_other_addr = cast_intrusive(id->GetVal()); + anon_preserve_other_addr = zeek::cast_intrusive(id->GetVal()); } ipaddr32_t zeek::detail::anonymize_ip(ipaddr32_t ip, enum ip_addr_anonymization_class_t cl) { TableVal* preserve_addr = nullptr; - auto addr = make_intrusive(ip); + auto addr = zeek::make_intrusive(ip); int method = -1; @@ -445,8 +445,8 @@ void zeek::detail::log_anonymization_mapping(ipaddr32_t input, ipaddr32_t output { if ( anonymization_mapping ) mgr.Enqueue(anonymization_mapping, - make_intrusive(input), - make_intrusive(output) + zeek::make_intrusive(input), + zeek::make_intrusive(output) ); } diff --git a/src/Attr.cc b/src/Attr.cc index 61c1f0979b..a32cc89668 100644 --- a/src/Attr.cc +++ b/src/Attr.cc @@ -25,7 +25,7 @@ const char* attr_name(AttrTag t) return attr_names[int(t)]; } -Attr::Attr(AttrTag t, IntrusivePtr e) +Attr::Attr(AttrTag t, ExprPtr e) : expr(std::move(e)) { tag = t; @@ -37,7 +37,7 @@ Attr::Attr(AttrTag t) { } -void Attr::SetAttrExpr(IntrusivePtr e) +void Attr::SetAttrExpr(ExprPtr e) { expr = std::move(e); } void Attr::Describe(ODesc* d) const @@ -136,7 +136,7 @@ void Attr::AddTag(ODesc* d) const d->Add(attr_name(Tag())); } -Attributes::Attributes(attr_list* a, IntrusivePtr t, bool arg_in_record, bool is_global) +Attributes::Attributes(attr_list* a, TypePtr t, bool arg_in_record, bool is_global) { attrs_list.resize(a->length()); attrs.reserve(a->length()); @@ -150,20 +150,18 @@ Attributes::Attributes(attr_list* a, IntrusivePtr t, bool arg_in_record, b // the necessary checking gets done. for ( const auto& attr : *a ) - AddAttr({NewRef{}, attr}); + AddAttr({zeek::NewRef{}, attr}); delete a; } -Attributes::Attributes(IntrusivePtr t, - bool arg_in_record, bool is_global) - : Attributes(std::vector>{}, std::move(t), +Attributes::Attributes(TypePtr t, bool arg_in_record, bool is_global) + : Attributes(std::vector{}, std::move(t), arg_in_record, is_global) {} -Attributes::Attributes(std::vector> a, - IntrusivePtr t, - bool arg_in_record, bool is_global) +Attributes::Attributes(std::vector a, + TypePtr t, bool arg_in_record, bool is_global) : type(std::move(t)) { attrs_list.resize(a.size()); @@ -181,7 +179,7 @@ Attributes::Attributes(std::vector> a, AddAttr(std::move(attr)); } -void Attributes::AddAttr(IntrusivePtr attr) +void Attributes::AddAttr(AttrPtr attr) { // We overwrite old attributes by deleting them first. RemoveAttr(attr->Tag()); @@ -197,7 +195,7 @@ void Attributes::AddAttr(IntrusivePtr attr) if ( (attr->Tag() == ATTR_ADD_FUNC || attr->Tag() == ATTR_DEL_FUNC) && ! Find(ATTR_REDEF) ) { - auto a = make_intrusive(ATTR_REDEF); + auto a = zeek::make_intrusive(ATTR_REDEF); attrs_list.push_back(a.get()); attrs.emplace_back(std::move(a)); } @@ -206,13 +204,13 @@ void Attributes::AddAttr(IntrusivePtr attr) if ( ! global_var && attr->Tag() == ATTR_DEFAULT && ! Find(ATTR_OPTIONAL) ) { - auto a = make_intrusive(ATTR_OPTIONAL); + auto a = zeek::make_intrusive(ATTR_OPTIONAL); attrs_list.push_back(a.get()); attrs.emplace_back(std::move(a)); } } -void Attributes::AddAttrs(const IntrusivePtr& a) +void Attributes::AddAttrs(const AttributesPtr& a) { for ( const auto& attr : a->GetAttrs() ) AddAttr(attr); @@ -235,7 +233,7 @@ Attr* Attributes::FindAttr(AttrTag t) const return nullptr; } -const IntrusivePtr& Attributes::Find(AttrTag t) const +const AttrPtr& Attributes::Find(AttrTag t) const { for ( const auto& a : attrs ) if ( a->Tag() == t ) diff --git a/src/Attr.h b/src/Attr.h index db70a57b3d..4439701f86 100644 --- a/src/Attr.h +++ b/src/Attr.h @@ -14,7 +14,15 @@ ZEEK_FORWARD_DECLARE_NAMESPACED(Expr, zeek::detail); // modify expressions or supply metadata on types, and the kind that // are extra metadata on every variable instance. -namespace zeek::detail { + +namespace zeek { + +class Type; +using TypePtr = IntrusivePtr; + +namespace detail { + +using ExprPtr = zeek::IntrusivePtr; enum AttrTag { ATTR_OPTIONAL, @@ -38,11 +46,16 @@ enum AttrTag { NUM_ATTRS // this item should always be last }; -class Attr final : public BroObj { -public: - static inline const IntrusivePtr nil; +class Attr; +using AttrPtr = zeek::IntrusivePtr; +class Attributes; +using AttributesPtr = zeek::IntrusivePtr; - Attr(AttrTag t, IntrusivePtr e); +class Attr final : public Obj { +public: + static inline const AttrPtr nil; + + Attr(AttrTag t, ExprPtr e); explicit Attr(AttrTag t); ~Attr() override = default; @@ -52,10 +65,10 @@ public: [[deprecated("Remove in v4.1. Use GetExpr().")]] zeek::detail::Expr* AttrExpr() const { return expr.get(); } - const IntrusivePtr& GetExpr() const + const ExprPtr& GetExpr() const { return expr; } - void SetAttrExpr(IntrusivePtr e); + void SetAttrExpr(ExprPtr e); void Describe(ODesc* d) const override; void DescribeReST(ODesc* d, bool shorten = false) const; @@ -78,24 +91,24 @@ protected: void AddTag(ODesc* d) const; AttrTag tag; - IntrusivePtr expr; + ExprPtr expr; }; // Manages a collection of attributes. -class Attributes final : public BroObj { +class Attributes final : public Obj { public: [[deprecated("Remove in v4.1. Construct using IntrusivePtrs instead.")]] - Attributes(attr_list* a, IntrusivePtr t, bool in_record, bool is_global); + Attributes(attr_list* a, zeek::TypePtr t, bool in_record, bool is_global); - Attributes(std::vector> a, IntrusivePtr t, + Attributes(std::vector a, zeek::TypePtr t, bool in_record, bool is_global); - Attributes(IntrusivePtr t, bool in_record, bool is_global); + Attributes(TypePtr t, bool in_record, bool is_global); ~Attributes() override = default; - void AddAttr(IntrusivePtr a); + void AddAttr(AttrPtr a); - void AddAttrs(const IntrusivePtr& a); + void AddAttrs(const AttributesPtr& a); [[deprecated("Remove in v4.1. Pass IntrusivePtr instead.")]] void AddAttrs(Attributes* a); // Unref's 'a' when done @@ -103,7 +116,7 @@ public: [[deprecated("Remove in v4.1. Use Find().")]] Attr* FindAttr(AttrTag t) const; - const IntrusivePtr& Find(AttrTag t) const; + const AttrPtr& Find(AttrTag t) const; void RemoveAttr(AttrTag t); @@ -114,7 +127,7 @@ public: const attr_list* Attrs() const { return &attrs_list; } - const std::vector>& GetAttrs() const + const std::vector& GetAttrs() const { return attrs; } bool operator==(const Attributes& other) const; @@ -122,8 +135,8 @@ public: protected: void CheckAttr(Attr* attr); - IntrusivePtr type; - std::vector> attrs; + TypePtr type; + std::vector attrs; // Remove in v4.1. This is used by Attrs(), which is deprecated. attr_list attrs_list; @@ -131,7 +144,8 @@ protected: bool global_var; }; -} +} // namespace detail +} // namespace zeek using Attr [[deprecated("Remove in v4.1. Use zeek::detail::Attr instead.")]] = zeek::detail::Attr; using Attributes [[deprecated("Remove in v4.1. Use zeek::detail::Attr instead.")]] = zeek::detail::Attributes; diff --git a/src/Base64.cc b/src/Base64.cc index 419e6faf8c..443370f542 100644 --- a/src/Base64.cc +++ b/src/Base64.cc @@ -1,6 +1,6 @@ #include "zeek-config.h" #include "Base64.h" -#include "BroString.h" +#include "ZeekString.h" #include "Reporter.h" #include "Conn.h" @@ -35,7 +35,7 @@ void Base64Converter::Encode(int len, const unsigned char* data, int* pblen, cha for ( int i = 0, j = 0; (i < len) && ( j < blen ); ) { uint32_t bit32 = data[i++] << 16; - bit32 += (i++ < len ? data[i-1] : 0) << 8; + bit32 += (i++ < len ? data[i-1] : 0) << 8; bit32 += i++ < len ? data[i-1] : 0; buf[j++] = alphabet[(bit32 >> 18) & 0x3f]; @@ -228,7 +228,7 @@ void Base64Converter::IllegalEncoding(const char* msg) reporter->Error("%s", msg); } -BroString* decode_base64(const BroString* s, const BroString* a, Connection* conn) +zeek::String* decode_base64(const zeek::String* s, const zeek::String* a, Connection* conn) { if ( a && a->Len() != 0 && a->Len() != 64 ) { @@ -255,14 +255,14 @@ BroString* decode_base64(const BroString* s, const BroString* a, Connection* con rlen += rlen2; rbuf[rlen] = '\0'; - return new BroString(true, (u_char*) rbuf, rlen); + return new zeek::String(true, (u_char*) rbuf, rlen); err: delete [] rbuf; return nullptr; } -BroString* encode_base64(const BroString* s, const BroString* a, Connection* conn) +zeek::String* encode_base64(const zeek::String* s, const zeek::String* a, Connection* conn) { if ( a && a->Len() != 0 && a->Len() != 64 ) { @@ -276,5 +276,5 @@ BroString* encode_base64(const BroString* s, const BroString* a, Connection* con Base64Converter enc(conn, a ? a->CheckString() : ""); enc.Encode(s->Len(), (const unsigned char*) s->Bytes(), &outlen, &outbuf); - return new BroString(true, (u_char*)outbuf, outlen); + return new zeek::String(true, (u_char*)outbuf, outlen); } diff --git a/src/Base64.h b/src/Base64.h index a138a3aa8e..81ac32b695 100644 --- a/src/Base64.h +++ b/src/Base64.h @@ -1,8 +1,11 @@ #pragma once +#include "zeek-config.h" #include -class BroString; +namespace zeek { class String; } +using BroString [[deprecated("Remove in v4.1. Use zeek::String instead.")]] = zeek::String; + class Connection; // Maybe we should have a base class for generic decoders? @@ -57,5 +60,5 @@ protected: }; -BroString* decode_base64(const BroString* s, const BroString* a = nullptr, Connection* conn = nullptr); -BroString* encode_base64(const BroString* s, const BroString* a = nullptr, Connection* conn = nullptr); +zeek::String* decode_base64(const zeek::String* s, const zeek::String* a = nullptr, Connection* conn = nullptr); +zeek::String* encode_base64(const zeek::String* s, const zeek::String* a = nullptr, Connection* conn = nullptr); diff --git a/src/BifReturnVal.cc b/src/BifReturnVal.cc index 8a8444161b..51f066d977 100644 --- a/src/BifReturnVal.cc +++ b/src/BifReturnVal.cc @@ -6,6 +6,6 @@ BifReturnVal::BifReturnVal(std::nullptr_t) noexcept {} -BifReturnVal::BifReturnVal(Val* v) noexcept - : rval(AdoptRef{}, v) +BifReturnVal::BifReturnVal(zeek::Val* v) noexcept + : rval(zeek::AdoptRef{}, v) {} diff --git a/src/BifReturnVal.h b/src/BifReturnVal.h index 2f6293cdf8..47bc6bbc7a 100644 --- a/src/BifReturnVal.h +++ b/src/BifReturnVal.h @@ -2,9 +2,13 @@ #pragma once +#include "zeek-config.h" #include "IntrusivePtr.h" -class Val; +ZEEK_FORWARD_DECLARE_NAMESPACED(Val, zeek); +namespace zeek { +using ValPtr = zeek::IntrusivePtr; +} /** * A simple wrapper class to use for the return value of BIFs so that @@ -15,14 +19,14 @@ class BifReturnVal { public: template - BifReturnVal(IntrusivePtr v) noexcept - : rval(AdoptRef{}, v.release()) + BifReturnVal(zeek::IntrusivePtr v) noexcept + : rval(zeek::AdoptRef{}, v.release()) { } BifReturnVal(std::nullptr_t) noexcept; [[deprecated("Remove in v4.1. Return an IntrusivePtr instead.")]] - BifReturnVal(Val* v) noexcept; + BifReturnVal(zeek::Val* v) noexcept; - IntrusivePtr rval; + zeek::ValPtr rval; }; diff --git a/src/BroList.h b/src/BroList.h index a1463603eb..cd80531d4a 100644 --- a/src/BroList.h +++ b/src/BroList.h @@ -4,24 +4,24 @@ #include "List.h" -class Val; -using val_list = PList; +ZEEK_FORWARD_DECLARE_NAMESPACED(Val, zeek); +using val_list = zeek::PList; ZEEK_FORWARD_DECLARE_NAMESPACED(Expr, zeek::detail); -using expr_list = PList; +using expr_list = zeek::PList; ZEEK_FORWARD_DECLARE_NAMESPACED(ID, zeek::detail); -using id_list = PList; +using id_list = zeek::PList; ZEEK_FORWARD_DECLARE_NAMESPACED(Stmt, zeek::detail); -using stmt_list = PList; +using stmt_list = zeek::PList; namespace zeek { class Type; } using BroType [[deprecated("Remove in v4.1. Use zeek::Type instead.")]] = zeek::Type; -using type_list = PList; +using type_list = zeek::PList; ZEEK_FORWARD_DECLARE_NAMESPACED(Attr, zeek::detail); -using attr_list = PList; +using attr_list = zeek::PList; class Timer; -using timer_list = PList; +using timer_list = zeek::PList; diff --git a/src/BroString.h b/src/BroString.h index 66c3bce4b7..8d48b3acbd 100644 --- a/src/BroString.h +++ b/src/BroString.h @@ -1,184 +1,2 @@ -// See the file "COPYING" in the main distribution directory for copyright. - -#pragma once - -#include -#include -#include - -#include - -typedef u_char* byte_vec; - -// Forward declaration, for helper functions that convert (sub)string vectors -// to and from policy-level representations. -// -class VectorVal; - -class BroString { -public: - typedef std::vector Vec; - typedef Vec::iterator VecIt; - typedef Vec::const_iterator VecCIt; - - typedef std::vector CVec; - typedef Vec::iterator CVecIt; - typedef Vec::const_iterator CVecCIt; - - // IdxVecs are vectors of indices of characters in a string. - typedef std::vector IdxVec; - typedef IdxVec::iterator IdxVecIt; - typedef IdxVec::const_iterator IdxVecCIt; - - // Constructors creating internal copies of the data passed in. - BroString(const u_char* str, int arg_n, bool add_NUL); - explicit BroString(const char* str); - explicit BroString(const std::string& str); - BroString(const BroString& bs); - - // Constructor that takes owernship of the vector passed in. - BroString(bool arg_final_NUL, byte_vec str, int arg_n); - - BroString(); - ~BroString() { Reset(); } - - const BroString& operator=(const BroString& bs); - bool operator==(const BroString& bs) const; - bool operator<(const BroString& bs) const; - - byte_vec Bytes() const { return b; } - int Len() const { return n; } - - // Releases the string's current contents, if any, and - // adopts the byte vector of given length. The string will - // manage the memory occupied by the string afterwards. - // - void Adopt(byte_vec bytes, int len); - - // Various flavors of methods that release the string's - // current contents, if any, and then set the string's - // contents to a copy of the string given by the arguments. - // - void Set(const u_char* str, int len, bool add_NUL=true); - void Set(const char* str); - void Set(const std::string& str); - void Set(const BroString &str); - - void SetUseFreeToDelete(int use_it) - { use_free_to_delete = use_it; } - - const char* CheckString() const; - - enum render_style { - ESC_NONE = 0, - ESC_ESC = (1 << 1), // '\' -> "\\" - ESC_QUOT = (1 << 2), // '"' -> "\"", ''' -> "\'" - ESC_HEX = (1 << 3), // Not in [32, 126]? -> "\xXX" - ESC_DOT = (1 << 4), // Not in [32, 126]? -> "." - - // For serialization: ' ' - ESC_SER = (1 << 7), - }; - - static const int EXPANDED_STRING = // the original style - ESC_HEX; - - static const int BRO_STRING_LITERAL = // as in a Bro string literal - ESC_ESC | ESC_QUOT | ESC_HEX; - - // Renders a string into a newly allocated character array that - // you have to delete[]. You can combine the render styles given - // above to achieve the representation you desire. If you pass a - // pointer to an integer as the final argument, you'll receive the - // entire length of the resulting char* in it. - // - // Note that you need to delete[] the resulting string. - // - char* Render(int format = EXPANDED_STRING, int* len = nullptr) const; - - // Similar to the above, but useful for output streams. - // Also more useful for debugging purposes since no deallocation - // is required on your part here. - // - std::ostream& Render(std::ostream& os, int format = ESC_SER) const; - - // Reads a string from an input stream. Unless you use a render - // style combination that uses ESC_SER, note that the streams - // will consider whitespace as a field delimiter. - // - std::istream& Read(std::istream& is, int format = ESC_SER); - - // XXX Fix redundancy: strings.bif implements both to_lower - // XXX and to_upper; the latter doesn't use BroString::ToUpper(). - void ToUpper(); - - unsigned int MemoryAllocation() const; - - // Returns new string containing the substring of this string, - // starting at @start >= 0 for going up to @length elements, - // A negative @length means "until end of string". Other invalid - // values result in a return value of 0. - // - BroString* GetSubstring(int start, int length) const; - - // Returns the start index of s in this string, counting from 0. - // If s is not found, -1 is returned. - // - int FindSubstring(const BroString* s) const; - - // Splits the string into substrings, taking all the indices in - // the given vector as cutting points. The vector does not need - // to be sorted, and can have multiple entries. Out-of-bounds - // indices are ignored. All returned strings are newly allocated. - // - Vec* Split(const IdxVec& indices) const; - - // Helper functions for vectors: - static VectorVal* VecToPolicy(Vec* vec); - static Vec* VecFromPolicy(VectorVal* vec); - static char* VecToString(const Vec* vec); - -protected: - void Reset(); - - byte_vec b; - int n; - bool final_NUL; // whether we have added a final NUL - bool use_free_to_delete; // free() vs. operator delete -}; - -// A comparison class that sorts pointers to BroString's according to -// the length of the pointed-to strings. Sort order can be specified -// through the constructor. -// -class BroStringLenCmp { -public: - explicit BroStringLenCmp(bool increasing = true) { _increasing = increasing; } - bool operator()(BroString*const& bst1, BroString*const& bst2); - - private: - unsigned int _increasing; -}; - -// Default output stream operator, using rendering mode EXPANDED_STRING. -std::ostream& operator<<(std::ostream& os, const BroString& bs); - -extern int Bstr_eq(const BroString* s1, const BroString* s2); -extern int Bstr_cmp(const BroString* s1, const BroString* s2); - -// A data_chunk_t specifies a length-delimited constant string. It is -// often used for substrings of other BroString's to avoid memory copy, -// which would be necessary if BroString were used. Unlike BroString, -// the string should not be deallocated on destruction. -// -// "BroConstString" might be a better name here. - -struct data_chunk_t { - int length; - const char* data; -}; - -extern BroString* concatenate(std::vector& v); -extern BroString* concatenate(BroString::Vec& v); -extern BroString* concatenate(BroString::CVec& v); -extern void delete_strings(std::vector& v); +#warning "BroString.h is deprecated and will be removed in v4.1. Use ZeekString.h instead." +#include "ZeekString.h" diff --git a/src/Brofiler.cc b/src/Brofiler.cc index 4eeb456380..951062a17b 100644 --- a/src/Brofiler.cc +++ b/src/Brofiler.cc @@ -31,7 +31,7 @@ void Brofiler::AddStmt(zeek::detail::Stmt* s) if ( ignoring != 0 ) return; - ::Ref(s); + zeek::Ref(s); stmts.push_back(s); } diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 933c3010bb..1d2d5c5a9b 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -220,7 +220,6 @@ set(MAIN_SRCS Base64.cc BifReturnVal.cc Brofiler.cc - BroString.cc CCL.cc CompHash.cc Conn.cc @@ -290,6 +289,7 @@ set(MAIN_SRCS Var.cc WeirdState.cc ZeekArgs.cc + ZeekString.cc legacy-netvar-init.cc bsd-getopt-long.c bro_inet_ntop.c diff --git a/src/CompHash.cc b/src/CompHash.cc index 0b08aafb5b..2518490f59 100644 --- a/src/CompHash.cc +++ b/src/CompHash.cc @@ -7,7 +7,7 @@ #include #include "CompHash.h" -#include "BroString.h" +#include "ZeekString.h" #include "Dict.h" #include "Val.h" #include "RE.h" @@ -15,7 +15,7 @@ #include "Func.h" #include "IPAddr.h" -CompositeHash::CompositeHash(IntrusivePtr composite_type) +CompositeHash::CompositeHash(zeek::TypeListPtr composite_type) : type(std::move(composite_type)) { singleton_tag = zeek::TYPE_INTERNAL_ERROR; @@ -72,7 +72,7 @@ CompositeHash::~CompositeHash() // Computes the piece of the hash for Val*, returning the new kp. char* CompositeHash::SingleValHash(bool type_check, char* kp0, - zeek::Type* bt, Val* v, bool optional) const + zeek::Type* bt, zeek::Val* v, bool optional) const { char* kp1 = nullptr; zeek::InternalTypeTag t = bt->InternalType(); @@ -176,7 +176,7 @@ char* CompositeHash::SingleValHash(bool type_check, char* kp0, case zeek::TYPE_RECORD: { char* kp = kp0; - RecordVal* rv = v->AsRecordVal(); + zeek::RecordVal* rv = v->AsRecordVal(); zeek::RecordType* rt = bt->AsRecordType(); int num_fields = rt->NumFields(); @@ -203,13 +203,13 @@ char* CompositeHash::SingleValHash(bool type_check, char* kp0, case zeek::TYPE_TABLE: { int* kp = AlignAndPadType(kp0); - TableVal* tv = v->AsTableVal(); + zeek::TableVal* tv = v->AsTableVal(); *kp = tv->Size(); kp1 = reinterpret_cast(kp+1); auto tbl = tv->AsTable(); auto it = tbl->InitForIteration(); - auto lv = make_intrusive(zeek::TYPE_ANY); + auto lv = zeek::make_intrusive(zeek::TYPE_ANY); struct HashKeyComparer { bool operator()(const HashKey* a, const HashKey* b) const @@ -262,7 +262,7 @@ char* CompositeHash::SingleValHash(bool type_check, char* kp0, case zeek::TYPE_VECTOR: { unsigned int* kp = AlignAndPadType(kp0); - VectorVal* vv = v->AsVectorVal(); + zeek::VectorVal* vv = v->AsVectorVal(); zeek::VectorType* vt = v->GetType()->AsVectorType(); *kp = vv->Size(); kp1 = reinterpret_cast(kp+1); @@ -290,12 +290,12 @@ char* CompositeHash::SingleValHash(bool type_check, char* kp0, case zeek::TYPE_LIST: { int* kp = AlignAndPadType(kp0); - ListVal* lv = v->AsListVal(); + zeek::ListVal* lv = v->AsListVal(); *kp = lv->Length(); kp1 = reinterpret_cast(kp+1); for ( int i = 0; i < lv->Length(); ++i ) { - Val* v = lv->Idx(i).get(); + zeek::Val* v = lv->Idx(i).get(); if ( ! (kp1 = SingleValHash(type_check, kp1, v->GetType().get(), v, false)) ) return nullptr; @@ -317,7 +317,7 @@ char* CompositeHash::SingleValHash(bool type_check, char* kp0, { // Align to int for the length field. int* kp = AlignAndPadType(kp0); - const BroString* sval = v->AsString(); + const zeek::String* sval = v->AsString(); *kp = sval->Len(); // so we can recover the value @@ -336,7 +336,7 @@ char* CompositeHash::SingleValHash(bool type_check, char* kp0, } -std::unique_ptr CompositeHash::MakeHashKey(const Val& argv, bool type_check) const +std::unique_ptr CompositeHash::MakeHashKey(const zeek::Val& argv, bool type_check) const { auto v = &argv; @@ -345,13 +345,13 @@ std::unique_ptr CompositeHash::MakeHashKey(const Val& argv, bool type_c if ( is_complex_type && v->GetType()->Tag() != zeek::TYPE_LIST ) { - ListVal lv(zeek::TYPE_ANY); + zeek::ListVal lv(zeek::TYPE_ANY); // Cast away const to use ListVal - but since we // re-introduce const on the recursive call, it should // be okay; the only thing is that the ListVal unref's it. - Val* ncv = (Val*) v; - lv.Append({NewRef{}, ncv}); + zeek::Val* ncv = (zeek::Val*) v; + lv.Append({zeek::NewRef{}, ncv}); return MakeHashKey(lv, type_check); } @@ -388,7 +388,7 @@ std::unique_ptr CompositeHash::MakeHashKey(const Val& argv, bool type_c return std::make_unique((k == key), (void*) k, kp - k); } -std::unique_ptr CompositeHash::ComputeSingletonHash(const Val* v, bool type_check) const +std::unique_ptr CompositeHash::ComputeSingletonHash(const zeek::Val* v, bool type_check) const { if ( v->GetType()->Tag() == zeek::TYPE_LIST ) { @@ -450,9 +450,9 @@ std::unique_ptr CompositeHash::ComputeSingletonHash(const Val* v, bool } } -int CompositeHash::SingleTypeKeySize(zeek::Type* bt, const Val* v, - bool type_check, int sz, bool optional, - bool calc_static_size) const +int CompositeHash::SingleTypeKeySize(zeek::Type* bt, const zeek::Val* v, + bool type_check, int sz, bool optional, + bool calc_static_size) const { zeek::InternalTypeTag t = bt->InternalType(); @@ -509,7 +509,7 @@ int CompositeHash::SingleTypeKeySize(zeek::Type* bt, const Val* v, case zeek::TYPE_RECORD: { - const RecordVal* rv = v ? v->AsRecordVal() : nullptr; + const zeek::RecordVal* rv = v ? v->AsRecordVal() : nullptr; zeek::RecordType* rt = bt->AsRecordType(); int num_fields = rt->NumFields(); @@ -535,7 +535,7 @@ int CompositeHash::SingleTypeKeySize(zeek::Type* bt, const Val* v, return (optional && ! calc_static_size) ? sz : 0; sz = SizeAlign(sz, sizeof(int)); - TableVal* tv = const_cast(v->AsTableVal()); + zeek::TableVal* tv = const_cast(v->AsTableVal()); auto lv = tv->ToListVal(); for ( int i = 0; i < tv->Size(); ++i ) { @@ -564,7 +564,7 @@ int CompositeHash::SingleTypeKeySize(zeek::Type* bt, const Val* v, return (optional && ! calc_static_size) ? sz : 0; sz = SizeAlign(sz, sizeof(unsigned int)); - VectorVal* vv = const_cast(v->AsVectorVal()); + zeek::VectorVal* vv = const_cast(v->AsVectorVal()); for ( unsigned int i = 0; i < vv->Size(); ++i ) { const auto& val = vv->At(i); @@ -586,7 +586,7 @@ int CompositeHash::SingleTypeKeySize(zeek::Type* bt, const Val* v, return (optional && ! calc_static_size) ? sz : 0; sz = SizeAlign(sz, sizeof(int)); - ListVal* lv = const_cast(v->AsListVal()); + zeek::ListVal* lv = const_cast(v->AsListVal()); for ( int i = 0; i < lv->Length(); ++i ) { sz = SingleTypeKeySize(lv->Idx(i)->GetType().get(), lv->Idx(i).get(), @@ -623,7 +623,7 @@ int CompositeHash::SingleTypeKeySize(zeek::Type* bt, const Val* v, return sz; } -int CompositeHash::ComputeKeySize(const Val* v, bool type_check, bool calc_static_size) const +int CompositeHash::ComputeKeySize(const zeek::Val* v, bool type_check, bool calc_static_size) const { const auto& tl = type->GetTypes(); @@ -709,16 +709,16 @@ int CompositeHash::SizeAlign(int offset, unsigned int size) const return offset; } -IntrusivePtr CompositeHash::RecoverVals(const HashKey& k) const +zeek::ListValPtr CompositeHash::RecoverVals(const HashKey& k) const { - auto l = make_intrusive(zeek::TYPE_ANY); + auto l = zeek::make_intrusive(zeek::TYPE_ANY); const auto& tl = type->GetTypes(); const char* kp = (const char*) k.Key(); const char* const k_end = kp + k.Size(); for ( const auto& type : tl ) { - IntrusivePtr v; + zeek::ValPtr v; kp = RecoverOneVal(k, kp, k_end, type.get(), &v, false); ASSERT(v); l->Append(std::move(v)); @@ -730,9 +730,10 @@ IntrusivePtr CompositeHash::RecoverVals(const HashKey& k) const return l; } -const char* CompositeHash::RecoverOneVal(const HashKey& k, const char* kp0, - const char* const k_end, zeek::Type* t, - IntrusivePtr* pval, bool optional) const +const char* CompositeHash::RecoverOneVal( + const HashKey& k, const char* kp0, + const char* const k_end, zeek::Type* t, + zeek::ValPtr* pval, bool optional) const { // k->Size() == 0 for a single empty string. if ( kp0 >= k_end && k.Size() > 0 ) @@ -763,9 +764,9 @@ const char* CompositeHash::RecoverOneVal(const HashKey& k, const char* kp0, if ( tag == zeek::TYPE_ENUM ) *pval = t->AsEnumType()->GetVal(*kp); else if ( tag == zeek::TYPE_BOOL ) - *pval = val_mgr->Bool(*kp); + *pval = zeek::val_mgr->Bool(*kp); else if ( tag == zeek::TYPE_INT ) - *pval = val_mgr->Int(*kp); + *pval = zeek::val_mgr->Int(*kp); else { reporter->InternalError("bad internal unsigned int in CompositeHash::RecoverOneVal()"); @@ -782,11 +783,11 @@ const char* CompositeHash::RecoverOneVal(const HashKey& k, const char* kp0, switch ( tag ) { case zeek::TYPE_COUNT: case zeek::TYPE_COUNTER: - *pval = val_mgr->Count(*kp); + *pval = zeek::val_mgr->Count(*kp); break; case zeek::TYPE_PORT: - *pval = val_mgr->Port(*kp); + *pval = zeek::val_mgr->Port(*kp); break; default: @@ -803,11 +804,11 @@ const char* CompositeHash::RecoverOneVal(const HashKey& k, const char* kp0, kp1 = reinterpret_cast(kp+1); if ( tag == zeek::TYPE_INTERVAL ) - *pval = make_intrusive(*kp, 1.0); + *pval = zeek::make_intrusive(*kp, 1.0); else if ( tag == zeek::TYPE_TIME ) - *pval = make_intrusive(*kp); + *pval = zeek::make_intrusive(*kp); else - *pval = make_intrusive(*kp); + *pval = zeek::make_intrusive(*kp); } break; @@ -820,7 +821,7 @@ const char* CompositeHash::RecoverOneVal(const HashKey& k, const char* kp0, switch ( tag ) { case zeek::TYPE_ADDR: - *pval = make_intrusive(addr); + *pval = zeek::make_intrusive(addr); break; default: @@ -835,7 +836,7 @@ const char* CompositeHash::RecoverOneVal(const HashKey& k, const char* kp0, { const uint32_t* const kp = AlignType(kp0); kp1 = reinterpret_cast(kp+5); - *pval = make_intrusive(kp, kp[4]); + *pval = zeek::make_intrusive(kp, kp[4]); } break; @@ -848,12 +849,12 @@ const char* CompositeHash::RecoverOneVal(const HashKey& k, const char* kp0, const uint32_t* const kp = AlignType(kp0); kp1 = reinterpret_cast(kp+1); - const auto& f = Func::GetFuncPtrByID(*kp); + const auto& f = zeek::Func::GetFuncPtrByID(*kp); if ( ! f ) reporter->InternalError("failed to look up unique function id %" PRIu32 " in CompositeHash::RecoverOneVal()", *kp); - *pval = make_intrusive(f); + *pval = zeek::make_intrusive(f); const auto& pvt = (*pval)->GetType(); if ( ! pvt ) @@ -893,7 +894,7 @@ const char* CompositeHash::RecoverOneVal(const HashKey& k, const char* kp0, reporter->InternalError("failed compiling table/set key pattern: %s", re->PatternText()); - *pval = make_intrusive(re); + *pval = zeek::make_intrusive(re); } break; @@ -903,11 +904,11 @@ const char* CompositeHash::RecoverOneVal(const HashKey& k, const char* kp0, zeek::RecordType* rt = t->AsRecordType(); int num_fields = rt->NumFields(); - std::vector> values; + std::vector values; int i; for ( i = 0; i < num_fields; ++i ) { - IntrusivePtr v; + zeek::ValPtr v; zeek::detail::Attributes* a = rt->FieldDecl(i)->attrs.get(); bool optional = (a && a->Find(zeek::detail::ATTR_OPTIONAL)); @@ -930,7 +931,7 @@ const char* CompositeHash::RecoverOneVal(const HashKey& k, const char* kp0, ASSERT(int(values.size()) == num_fields); - auto rv = make_intrusive(IntrusivePtr{NewRef{}, rt}); + auto rv = zeek::make_intrusive(zeek::IntrusivePtr{zeek::NewRef{}, rt}); for ( int i = 0; i < num_fields; ++i ) rv->Assign(i, std::move(values[i])); @@ -947,18 +948,18 @@ const char* CompositeHash::RecoverOneVal(const HashKey& k, const char* kp0, n = *kp; kp1 = reinterpret_cast(kp+1); zeek::TableType* tt = t->AsTableType(); - auto tv = make_intrusive(IntrusivePtr{NewRef{}, tt}); + auto tv = zeek::make_intrusive(zeek::IntrusivePtr{zeek::NewRef{}, tt}); for ( int i = 0; i < n; ++i ) { - IntrusivePtr key; + zeek::ValPtr key; kp1 = RecoverOneVal(k, kp1, k_end, tt->GetIndices().get(), &key, false); if ( t->IsSet() ) tv->Assign(std::move(key), nullptr); else { - IntrusivePtr value; + zeek::ValPtr value; kp1 = RecoverOneVal(k, kp1, k_end, tt->Yield().get(), &value, false); tv->Assign(std::move(key), std::move(value)); @@ -976,7 +977,7 @@ const char* CompositeHash::RecoverOneVal(const HashKey& k, const char* kp0, n = *kp; kp1 = reinterpret_cast(kp+1); zeek::VectorType* vt = t->AsVectorType(); - auto vv = make_intrusive(IntrusivePtr{NewRef{}, vt}); + auto vv = zeek::make_intrusive(zeek::IntrusivePtr{zeek::NewRef{}, vt}); for ( unsigned int i = 0; i < n; ++i ) { @@ -986,7 +987,7 @@ const char* CompositeHash::RecoverOneVal(const HashKey& k, const char* kp0, kp = AlignType(kp1); unsigned int have_val = *kp; kp1 = reinterpret_cast(kp+1); - IntrusivePtr value; + zeek::ValPtr value; if ( have_val ) kp1 = RecoverOneVal(k, kp1, k_end, vt->Yield().get(), &value, @@ -1006,11 +1007,11 @@ const char* CompositeHash::RecoverOneVal(const HashKey& k, const char* kp0, n = *kp; kp1 = reinterpret_cast(kp+1); zeek::TypeList* tl = t->AsTypeList(); - auto lv = make_intrusive(zeek::TYPE_ANY); + auto lv = zeek::make_intrusive(zeek::TYPE_ANY); for ( int i = 0; i < n; ++i ) { - IntrusivePtr v; + zeek::ValPtr v; zeek::Type* it = tl->GetTypes()[i].get(); kp1 = RecoverOneVal(k, kp1, k_end, it, &v, false); lv->Append(std::move(v)); @@ -1046,7 +1047,7 @@ const char* CompositeHash::RecoverOneVal(const HashKey& k, const char* kp0, kp1 = reinterpret_cast(kp+1); } - *pval = make_intrusive(new BroString((const byte_vec) kp1, n, true)); + *pval = zeek::make_intrusive(new zeek::String((const zeek::byte_vec) kp1, n, true)); kp1 += n; } break; diff --git a/src/CompHash.h b/src/CompHash.h index 367fd445a0..a779c6bf2c 100644 --- a/src/CompHash.h +++ b/src/CompHash.h @@ -7,46 +7,50 @@ #include "Type.h" #include "IntrusivePtr.h" -class ListVal; +ZEEK_FORWARD_DECLARE_NAMESPACED(ListVal, zeek); class HashKey; +namespace zeek { +using ListValPtr = zeek::IntrusivePtr; +} + class CompositeHash { public: - explicit CompositeHash(IntrusivePtr composite_type); + explicit CompositeHash(zeek::TypeListPtr composite_type); ~CompositeHash(); // Compute the hash corresponding to the given index val, // or nullptr if it fails to typecheck. - std::unique_ptr MakeHashKey(const Val& v, bool type_check) const; + std::unique_ptr MakeHashKey(const zeek::Val& v, bool type_check) const; [[deprecated("Remove in v4.1. Use MakeHashKey().")]] - HashKey* ComputeHash(const Val* v, bool type_check) const + HashKey* ComputeHash(const zeek::Val* v, bool type_check) const { return MakeHashKey(*v, type_check).release(); } // Given a hash key, recover the values used to create it. - IntrusivePtr RecoverVals(const HashKey& k) const; + zeek::ListValPtr RecoverVals(const HashKey& k) const; [[deprecated("Remove in v4.1. Pass in HashKey& instead.")]] - IntrusivePtr RecoverVals(const HashKey* k) const + zeek::ListValPtr RecoverVals(const HashKey* k) const { return RecoverVals(*k); } unsigned int MemoryAllocation() const { return padded_sizeof(*this) + pad_size(size); } protected: - std::unique_ptr ComputeSingletonHash(const Val* v, bool type_check) const; + std::unique_ptr ComputeSingletonHash(const zeek::Val* v, bool type_check) const; // Computes the piece of the hash for Val*, returning the new kp. // Used as a helper for ComputeHash in the non-singleton case. - char* SingleValHash(bool type_check, char* kp, zeek::Type* bt, Val* v, - bool optional) const; + char* SingleValHash(bool type_check, char* kp, zeek::Type* bt, zeek::Val* v, + bool optional) const; // Recovers just one Val of possibly many; called from RecoverVals. // Upon return, pval will point to the recovered Val of type t. // Returns and updated kp for the next Val. Calls reporter->InternalError() // upon errors, so there is no return value for invalid input. - const char* RecoverOneVal(const HashKey& k, - const char* kp, const char* const k_end, - zeek::Type* t, IntrusivePtr* pval, bool optional) const; + const char* RecoverOneVal( + const HashKey& k, const char* kp, const char* const k_end, + zeek::Type* t, zeek::ValPtr* pval, bool optional) const; // Rounds the given pointer up to the nearest multiple of the // given size, if not already a multiple. @@ -82,14 +86,14 @@ protected: // the value is computed for the particular list of values. // Returns 0 if the key has an indeterminant size (if v not given), // or if v doesn't match the index type (if given). - int ComputeKeySize(const Val* v, bool type_check, - bool calc_static_size) const; + int ComputeKeySize(const zeek::Val* v, bool type_check, + bool calc_static_size) const; - int SingleTypeKeySize(zeek::Type*, const Val*, - bool type_check, int sz, bool optional, - bool calc_static_size) const; + int SingleTypeKeySize(zeek::Type*, const zeek::Val*, + bool type_check, int sz, bool optional, + bool calc_static_size) const; - IntrusivePtr type; + zeek::TypeListPtr type; char* key; // space for composite key int size; bool is_singleton; // if just one type in index diff --git a/src/Conn.cc b/src/Conn.cc index f934a025de..a0f1fcaea0 100644 --- a/src/Conn.cc +++ b/src/Conn.cc @@ -266,8 +266,8 @@ void Connection::HistoryThresholdEvent(EventHandlerPtr e, bool is_orig, EnqueueEvent(e, nullptr, ConnVal(), - val_mgr->Bool(is_orig), - val_mgr->Count(threshold) + zeek::val_mgr->Bool(is_orig), + zeek::val_mgr->Count(threshold) ); } @@ -337,74 +337,74 @@ void Connection::StatusUpdateTimer(double t) TIMER_CONN_STATUS_UPDATE); } -RecordVal* Connection::BuildConnVal() +zeek::RecordVal* Connection::BuildConnVal() { return ConnVal()->Ref()->AsRecordVal(); } -const IntrusivePtr& Connection::ConnVal() +const zeek::RecordValPtr& Connection::ConnVal() { if ( ! conn_val ) { - conn_val = make_intrusive(zeek::id::connection); + conn_val = zeek::make_intrusive(zeek::id::connection); TransportProto prot_type = ConnTransport(); - auto id_val = make_intrusive(zeek::id::conn_id); - id_val->Assign(0, make_intrusive(orig_addr)); - id_val->Assign(1, val_mgr->Port(ntohs(orig_port), prot_type)); - id_val->Assign(2, make_intrusive(resp_addr)); - id_val->Assign(3, val_mgr->Port(ntohs(resp_port), prot_type)); + auto id_val = zeek::make_intrusive(zeek::id::conn_id); + id_val->Assign(0, zeek::make_intrusive(orig_addr)); + id_val->Assign(1, zeek::val_mgr->Port(ntohs(orig_port), prot_type)); + id_val->Assign(2, zeek::make_intrusive(resp_addr)); + id_val->Assign(3, zeek::val_mgr->Port(ntohs(resp_port), prot_type)); - auto orig_endp = make_intrusive(zeek::id::endpoint); - orig_endp->Assign(0, val_mgr->Count(0)); - orig_endp->Assign(1, val_mgr->Count(0)); - orig_endp->Assign(4, val_mgr->Count(orig_flow_label)); + auto orig_endp = zeek::make_intrusive(zeek::id::endpoint); + orig_endp->Assign(0, zeek::val_mgr->Count(0)); + orig_endp->Assign(1, zeek::val_mgr->Count(0)); + orig_endp->Assign(4, zeek::val_mgr->Count(orig_flow_label)); const int l2_len = sizeof(orig_l2_addr); char null[l2_len]{}; if ( memcmp(&orig_l2_addr, &null, l2_len) != 0 ) - orig_endp->Assign(5, make_intrusive(fmt_mac(orig_l2_addr, l2_len))); + orig_endp->Assign(5, zeek::make_intrusive(fmt_mac(orig_l2_addr, l2_len))); - auto resp_endp = make_intrusive(zeek::id::endpoint); - resp_endp->Assign(0, val_mgr->Count(0)); - resp_endp->Assign(1, val_mgr->Count(0)); - resp_endp->Assign(4, val_mgr->Count(resp_flow_label)); + auto resp_endp = zeek::make_intrusive(zeek::id::endpoint); + resp_endp->Assign(0, zeek::val_mgr->Count(0)); + resp_endp->Assign(1, zeek::val_mgr->Count(0)); + resp_endp->Assign(4, zeek::val_mgr->Count(resp_flow_label)); if ( memcmp(&resp_l2_addr, &null, l2_len) != 0 ) - resp_endp->Assign(5, make_intrusive(fmt_mac(resp_l2_addr, l2_len))); + resp_endp->Assign(5, zeek::make_intrusive(fmt_mac(resp_l2_addr, l2_len))); conn_val->Assign(0, std::move(id_val)); conn_val->Assign(1, std::move(orig_endp)); conn_val->Assign(2, std::move(resp_endp)); // 3 and 4 are set below. - conn_val->Assign(5, make_intrusive(zeek::id::string_set)); // service - conn_val->Assign(6, val_mgr->EmptyString()); // history + conn_val->Assign(5, zeek::make_intrusive(zeek::id::string_set)); // service + conn_val->Assign(6, zeek::val_mgr->EmptyString()); // history if ( ! uid ) uid.Set(bits_per_uid); - conn_val->Assign(7, make_intrusive(uid.Base62("C").c_str())); + conn_val->Assign(7, zeek::make_intrusive(uid.Base62("C").c_str())); if ( encapsulation && encapsulation->Depth() > 0 ) conn_val->Assign(8, encapsulation->ToVal()); if ( vlan != 0 ) - conn_val->Assign(9, val_mgr->Int(vlan)); + conn_val->Assign(9, zeek::val_mgr->Int(vlan)); if ( inner_vlan != 0 ) - conn_val->Assign(10, val_mgr->Int(inner_vlan)); + conn_val->Assign(10, zeek::val_mgr->Int(inner_vlan)); } if ( root_analyzer ) root_analyzer->UpdateConnVal(conn_val.get()); - conn_val->Assign(3, make_intrusive(start_time)); // ### - conn_val->Assign(4, make_intrusive(last_time - start_time)); - conn_val->Assign(6, make_intrusive(history.c_str())); - conn_val->Assign(11, val_mgr->Bool(is_successful)); + conn_val->Assign(3, zeek::make_intrusive(start_time)); // ### + conn_val->Assign(4, zeek::make_intrusive(last_time - start_time)); + conn_val->Assign(6, zeek::make_intrusive(history.c_str())); + conn_val->Assign(11, zeek::val_mgr->Bool(is_successful)); conn_val->SetOrigin(this); @@ -433,7 +433,7 @@ void Connection::AppendAddl(const char* str) const char* old = cv->GetField(6)->AsString()->CheckString(); const char* format = *old ? "%s %s" : "%s%s"; - cv->Assign(6, make_intrusive(fmt(format, old, str))); + cv->Assign(6, zeek::make_intrusive(fmt(format, old, str))); } // Returns true if the character at s separates a version number. @@ -470,12 +470,12 @@ void Connection::Event(EventHandlerPtr f, analyzer::Analyzer* analyzer, const ch return; if ( name ) - EnqueueEvent(f, analyzer, make_intrusive(name), ConnVal()); + EnqueueEvent(f, analyzer, zeek::make_intrusive(name), ConnVal()); else EnqueueEvent(f, analyzer, ConnVal()); } -void Connection::Event(EventHandlerPtr f, analyzer::Analyzer* analyzer, Val* v1, Val* v2) +void Connection::Event(EventHandlerPtr f, analyzer::Analyzer* analyzer, zeek::Val* v1, zeek::Val* v2) { if ( ! f ) { @@ -487,12 +487,12 @@ void Connection::Event(EventHandlerPtr f, analyzer::Analyzer* analyzer, Val* v1, if ( v2 ) EnqueueEvent(f, analyzer, ConnVal(), - IntrusivePtr{AdoptRef{}, v1}, - IntrusivePtr{AdoptRef{}, v2}); + zeek::IntrusivePtr{zeek::AdoptRef{}, v1}, + zeek::IntrusivePtr{zeek::AdoptRef{}, v2}); else EnqueueEvent(f, analyzer, ConnVal(), - IntrusivePtr{AdoptRef{}, v1}); + zeek::IntrusivePtr{zeek::AdoptRef{}, v1}); } void Connection::ConnectionEvent(EventHandlerPtr f, analyzer::Analyzer* a, val_list vl) @@ -697,8 +697,8 @@ void Connection::CheckFlowLabel(bool is_orig, uint32_t flow_label) { if ( conn_val ) { - RecordVal* endp = conn_val->GetField(is_orig ? 1 : 2)->AsRecordVal(); - endp->Assign(4, val_mgr->Count(flow_label)); + zeek::RecordVal* endp = conn_val->GetField(is_orig ? 1 : 2)->AsRecordVal(); + endp->Assign(4, zeek::val_mgr->Count(flow_label)); } if ( connection_flow_label_changed && @@ -706,9 +706,9 @@ void Connection::CheckFlowLabel(bool is_orig, uint32_t flow_label) { EnqueueEvent(connection_flow_label_changed, nullptr, ConnVal(), - val_mgr->Bool(is_orig), - val_mgr->Count(my_flow_label), - val_mgr->Count(flow_label) + zeek::val_mgr->Bool(is_orig), + zeek::val_mgr->Count(my_flow_label), + zeek::val_mgr->Count(flow_label) ); } diff --git a/src/Conn.h b/src/Conn.h index 161bb6b759..a8f6864335 100644 --- a/src/Conn.h +++ b/src/Conn.h @@ -29,8 +29,13 @@ class RuleHdrTest; class Specific_RE_Matcher; class RuleEndpointState; class EncapsulationStack; -class Val; -class RecordVal; + +ZEEK_FORWARD_DECLARE_NAMESPACED(Val, zeek); + +namespace zeek { +using ValPtr = zeek::IntrusivePtr; +using RecordValPtr = zeek::IntrusivePtr; +} namespace analyzer { class TransportLayerAnalyzer; } @@ -59,7 +64,7 @@ static inline int addr_port_canon_lt(const IPAddr& addr1, uint32_t p1, namespace analyzer { class Analyzer; } -class Connection final : public BroObj { +class Connection final : public zeek::Obj { public: Connection(NetSessions* s, const ConnIDKey& k, double t, const ConnID* id, uint32_t flow, const Packet* pkt, const EncapsulationStack* arg_encap); @@ -164,12 +169,12 @@ public: void EnableStatusUpdateTimer(); [[deprecated("Remove in v4.1. Use ConnVal() instead.")]] - RecordVal* BuildConnVal(); + zeek::RecordVal* BuildConnVal(); /** * Returns the associated "connection" record. */ - const IntrusivePtr& ConnVal(); + const zeek::RecordValPtr& ConnVal(); void AppendAddl(const char* str); @@ -194,7 +199,7 @@ public: // argument is the connection value, second argument is 'v1', and if 'v2' // 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).")]] - void Event(EventHandlerPtr f, analyzer::Analyzer* analyzer, Val* v1, Val* v2 = nullptr); + void Event(EventHandlerPtr f, analyzer::Analyzer* analyzer, zeek::Val* v1, zeek::Val* v2 = nullptr); // 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 @@ -234,8 +239,8 @@ public: */ template std::enable_if_t< - std::is_convertible_v< - std::tuple_element_t<0, std::tuple>, IntrusivePtr>> + std::is_convertible_v< + std::tuple_element_t<0, std::tuple>, zeek::ValPtr>> EnqueueEvent(EventHandlerPtr h, analyzer::Analyzer* analyzer, Args&&... args) { return EnqueueEvent(h, analyzer, zeek::Args{std::forward(args)...}); } @@ -355,7 +360,7 @@ protected: u_char resp_l2_addr[Packet::l2_addr_len]; // Link-layer responder address, if available double start_time, last_time; double inactivity_timeout; - IntrusivePtr conn_val; + zeek::RecordValPtr conn_val; LoginConn* login_conn; // either nil, or this const EncapsulationStack* encapsulation; // tunnels int suppress_event; // suppress certain events to once per conn. diff --git a/src/Continuation.h b/src/Continuation.h index 039b37f249..455cf52a73 100644 --- a/src/Continuation.h +++ b/src/Continuation.h @@ -49,7 +49,6 @@ private: int current_level; int suspend_level; - typedef PList voidp_list; - + using voidp_list = zeek::PList; voidp_list states; }; diff --git a/src/DFA.h b/src/DFA.h index 332cdaff8e..99aac3d47e 100644 --- a/src/DFA.h +++ b/src/DFA.h @@ -24,7 +24,7 @@ class DFA_State; class DFA_Machine; class DFA_State; -class DFA_State : public BroObj { +class DFA_State : public zeek::Obj { public: DFA_State(int state_num, const EquivClass* ec, NFA_state_list* nfa_states, AcceptingSet* accept); @@ -109,7 +109,7 @@ private: std::map states; }; -class DFA_Machine : public BroObj { +class DFA_Machine : public zeek::Obj { public: DFA_Machine(NFA_Machine* n, EquivClass* ec); ~DFA_Machine() override; diff --git a/src/DNS_Mgr.cc b/src/DNS_Mgr.cc index 346fc348b7..be458ebe60 100644 --- a/src/DNS_Mgr.cc +++ b/src/DNS_Mgr.cc @@ -31,7 +31,7 @@ #include -#include "BroString.h" +#include "ZeekString.h" #include "Expr.h" #include "Event.h" #include "Net.h" @@ -122,9 +122,9 @@ public: return req_host ? req_host : req_addr.AsString(); } - IntrusivePtr Addrs(); - IntrusivePtr AddrsSet(); // addresses returned as a set - IntrusivePtr Host(); + zeek::ListValPtr Addrs(); + zeek::TableValPtr AddrsSet(); // addresses returned as a set + zeek::StringValPtr Host(); double CreationTime() const { return creation_time; } @@ -155,11 +155,11 @@ protected: int num_names; char** names; - IntrusivePtr host_val; + zeek::StringValPtr host_val; int num_addrs; IPAddr* addrs; - IntrusivePtr addrs_val; + zeek::ListValPtr addrs_val; double creation_time; int map_type; @@ -173,13 +173,13 @@ void DNS_Mgr_mapping_delete_func(void* v) delete (DNS_Mapping*) v; } -static IntrusivePtr empty_addr_set() +static zeek::TableValPtr empty_addr_set() { auto addr_t = zeek::base_type(zeek::TYPE_ADDR); - auto set_index = make_intrusive(addr_t); + auto set_index = zeek::make_intrusive(addr_t); set_index->Append(std::move(addr_t)); - auto s = make_intrusive(std::move(set_index), nullptr); - return make_intrusive(std::move(s)); + auto s = zeek::make_intrusive(std::move(set_index), nullptr); + return zeek::make_intrusive(std::move(s)); } DNS_Mapping::DNS_Mapping(const char* host, struct hostent* h, uint32_t ttl) @@ -276,23 +276,23 @@ DNS_Mapping::~DNS_Mapping() delete [] addrs; } -IntrusivePtr DNS_Mapping::Addrs() +zeek::ListValPtr DNS_Mapping::Addrs() { if ( failed ) return nullptr; if ( ! addrs_val ) { - addrs_val = make_intrusive(zeek::TYPE_ADDR); + addrs_val = zeek::make_intrusive(zeek::TYPE_ADDR); for ( int i = 0; i < num_addrs; ++i ) - addrs_val->Append(make_intrusive(addrs[i])); + addrs_val->Append(zeek::make_intrusive(addrs[i])); } return addrs_val; } -IntrusivePtr DNS_Mapping::AddrsSet() { +zeek::TableValPtr DNS_Mapping::AddrsSet() { auto l = Addrs(); if ( ! l ) @@ -301,13 +301,13 @@ IntrusivePtr DNS_Mapping::AddrsSet() { return l->ToSetVal(); } -IntrusivePtr DNS_Mapping::Host() +zeek::StringValPtr DNS_Mapping::Host() { if ( failed || num_names == 0 || ! names[0] ) return nullptr; if ( ! host_val ) - host_val = make_intrusive(names[0]); + host_val = zeek::make_intrusive(names[0]); return host_val; } @@ -461,12 +461,12 @@ void DNS_Mgr::InitPostScript() LoadCache(fopen(cache_name, "r")); } -static IntrusivePtr fake_name_lookup_result(const char* name) +static zeek::TableValPtr fake_name_lookup_result(const char* name) { hash128_t hash; KeyedHash::StaticHash128(name, strlen(name), &hash); - auto hv = make_intrusive(zeek::TYPE_ADDR); - hv->Append(make_intrusive(reinterpret_cast(&hash))); + auto hv = zeek::make_intrusive(zeek::TYPE_ADDR); + hv->Append(zeek::make_intrusive(reinterpret_cast(&hash))); return hv->ToSetVal(); } @@ -485,7 +485,7 @@ static const char* fake_addr_lookup_result(const IPAddr& addr) return tmp; } -IntrusivePtr DNS_Mgr::LookupHost(const char* name) +zeek::TableValPtr DNS_Mgr::LookupHost(const char* name) { if ( mode == DNS_FAKE ) return fake_name_lookup_result(name); @@ -542,7 +542,7 @@ IntrusivePtr DNS_Mgr::LookupHost(const char* name) } } -IntrusivePtr DNS_Mgr::LookupAddr(const IPAddr& addr) +zeek::ValPtr DNS_Mgr::LookupAddr(const IPAddr& addr) { InitSource(); @@ -559,7 +559,7 @@ IntrusivePtr DNS_Mgr::LookupAddr(const IPAddr& addr) { string s(addr); reporter->Warning("can't resolve IP address: %s", s.c_str()); - return make_intrusive(s.c_str()); + return zeek::make_intrusive(s.c_str()); } } } @@ -568,7 +568,7 @@ IntrusivePtr DNS_Mgr::LookupAddr(const IPAddr& addr) switch ( mode ) { case DNS_PRIME: requests.push_back(new DNS_Mgr_Request(addr)); - return make_intrusive(""); + return zeek::make_intrusive(""); case DNS_FORCE: reporter->FatalError("can't find DNS entry for %s in cache", @@ -698,7 +698,7 @@ void DNS_Mgr::Event(EventHandlerPtr e, DNS_Mapping* dm) } void DNS_Mgr::Event(EventHandlerPtr e, DNS_Mapping* dm, - IntrusivePtr l1, IntrusivePtr l2) + zeek::ListValPtr l1, zeek::ListValPtr l2) { if ( ! e ) return; @@ -714,17 +714,17 @@ void DNS_Mgr::Event(EventHandlerPtr e, DNS_Mapping* old_dm, DNS_Mapping* new_dm) mgr.Enqueue(e, BuildMappingVal(old_dm), BuildMappingVal(new_dm)); } -IntrusivePtr DNS_Mgr::BuildMappingVal(DNS_Mapping* dm) +zeek::ValPtr DNS_Mgr::BuildMappingVal(DNS_Mapping* dm) { - auto r = make_intrusive(dm_rec); + auto r = zeek::make_intrusive(dm_rec); - r->Assign(0, make_intrusive(dm->CreationTime())); - r->Assign(1, make_intrusive(dm->ReqHost() ? dm->ReqHost() : "")); - r->Assign(2, make_intrusive(dm->ReqAddr())); - r->Assign(3, val_mgr->Bool(dm->Valid())); + r->Assign(0, zeek::make_intrusive(dm->CreationTime())); + r->Assign(1, zeek::make_intrusive(dm->ReqHost() ? dm->ReqHost() : "")); + r->Assign(2, zeek::make_intrusive(dm->ReqAddr())); + r->Assign(3, zeek::val_mgr->Bool(dm->Valid())); auto h = dm->Host(); - r->Assign(4, h ? std::move(h) : make_intrusive("")); + r->Assign(4, h ? std::move(h) : zeek::make_intrusive("")); r->Assign(5, dm->AddrsSet()); return r; @@ -870,9 +870,9 @@ 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)); } -IntrusivePtr DNS_Mgr::AddrListDelta(ListVal* al1, ListVal* al2) +zeek::ListValPtr DNS_Mgr::AddrListDelta(zeek::ListVal* al1, zeek::ListVal* al2) { - auto delta = make_intrusive(zeek::TYPE_ADDR); + auto delta = zeek::make_intrusive(zeek::TYPE_ADDR); for ( int i = 0; i < al1->Length(); ++i ) { @@ -894,7 +894,7 @@ IntrusivePtr DNS_Mgr::AddrListDelta(ListVal* al1, ListVal* al2) return delta; } -void DNS_Mgr::DumpAddrList(FILE* f, ListVal* al) +void DNS_Mgr::DumpAddrList(FILE* f, zeek::ListVal* al) { for ( int i = 0; i < al->Length(); ++i ) { @@ -980,7 +980,7 @@ const char* DNS_Mgr::LookupAddrInCache(const IPAddr& addr) return d->names ? d->names[0] : "<\?\?\?>"; } -IntrusivePtr DNS_Mgr::LookupNameInCache(const string& name) +zeek::TableValPtr DNS_Mgr::LookupNameInCache(const string& name) { HostMap::iterator it = host_mappings.find(name); if ( it == host_mappings.end() ) @@ -1030,7 +1030,7 @@ const char* DNS_Mgr::LookupTextInCache(const string& name) } static void resolve_lookup_cb(DNS_Mgr::LookupCallback* callback, - IntrusivePtr result) + zeek::TableValPtr result) { callback->Resolved(result.get()); delete callback; diff --git a/src/DNS_Mgr.h b/src/DNS_Mgr.h index 4e5079c585..e4f7d8dc01 100644 --- a/src/DNS_Mgr.h +++ b/src/DNS_Mgr.h @@ -13,17 +13,22 @@ #include "IPAddr.h" #include "util.h" -template class IntrusivePtr; -class Val; -class ListVal; -class TableVal; -class Func; class EventHandler; class DNS_Mgr_Request; ZEEK_FORWARD_DECLARE_NAMESPACED(RecordType, zeek); +ZEEK_FORWARD_DECLARE_NAMESPACED(Val, zeek); +ZEEK_FORWARD_DECLARE_NAMESPACED(ListVal, zeek); +ZEEK_FORWARD_DECLARE_NAMESPACED(TableVal, zeek); -typedef PList DNS_mgr_request_list; +namespace zeek { +template class IntrusivePtr; +using ValPtr = zeek::IntrusivePtr; +using ListValPtr = zeek::IntrusivePtr; +using TableValPtr = zeek::IntrusivePtr; +} + +using DNS_mgr_request_list = zeek::PList; struct nb_dns_info; struct nb_dns_result; @@ -50,9 +55,9 @@ public: // Looks up the address or addresses of the given host, and returns // a set of addr. - IntrusivePtr LookupHost(const char* host); + zeek::TableValPtr LookupHost(const char* host); - IntrusivePtr LookupAddr(const IPAddr& addr); + zeek::ValPtr LookupAddr(const IPAddr& addr); // Define the directory where to store the data. void SetDir(const char* arg_dir) { dir = copy_string(arg_dir); } @@ -62,7 +67,7 @@ public: bool Save(); const char* LookupAddrInCache(const IPAddr& addr); - IntrusivePtr LookupNameInCache(const std::string& name); + zeek::TableValPtr LookupNameInCache(const std::string& name); const char* LookupTextInCache(const std::string& name); // Support for async lookups. @@ -72,7 +77,7 @@ public: virtual ~LookupCallback() { } virtual void Resolved(const char* name) { }; - virtual void Resolved(TableVal* addrs) { }; + virtual void Resolved(zeek::TableVal* addrs) { }; virtual void Timeout() = 0; }; @@ -100,15 +105,15 @@ protected: void Event(EventHandlerPtr e, DNS_Mapping* dm); void Event(EventHandlerPtr e, DNS_Mapping* dm, - IntrusivePtr l1, IntrusivePtr l2); + zeek::ListValPtr l1, zeek::ListValPtr l2); void Event(EventHandlerPtr e, DNS_Mapping* old_dm, DNS_Mapping* new_dm); - IntrusivePtr BuildMappingVal(DNS_Mapping* dm); + zeek::ValPtr BuildMappingVal(DNS_Mapping* dm); void AddResult(DNS_Mgr_Request* dr, struct nb_dns_result* r); void CompareMappings(DNS_Mapping* prev_dm, DNS_Mapping* new_dm); - IntrusivePtr AddrListDelta(ListVal* al1, ListVal* al2); - void DumpAddrList(FILE* f, ListVal* al); + zeek::ListValPtr AddrListDelta(zeek::ListVal* al1, zeek::ListVal* al2); + void DumpAddrList(FILE* f, zeek::ListVal* al); typedef std::map > HostMap; typedef std::map AddrMap; @@ -151,7 +156,7 @@ protected: bool did_init; - IntrusivePtr dm_rec; + zeek::RecordTypePtr dm_rec; typedef std::list CallbackList; @@ -179,7 +184,7 @@ protected: processed = true; } - void Resolved(TableVal* addrs) + void Resolved(zeek::TableVal* addrs) { for ( CallbackList::iterator i = callbacks.begin(); i != callbacks.end(); ++i ) diff --git a/src/DbgBreakpoint.cc b/src/DbgBreakpoint.cc index 472924aba4..eda86b483b 100644 --- a/src/DbgBreakpoint.cc +++ b/src/DbgBreakpoint.cc @@ -13,7 +13,6 @@ #include "Scope.h" #include "Frame.h" #include "Func.h" -#include "IntrusivePtr.h" #include "Val.h" #include "Stmt.h" #include "Timer.h" @@ -142,7 +141,7 @@ bool DbgBreakpoint::SetLocation(ParseLocationRec plr, std::string_view loc_str) at_stmt = plr.stmt; snprintf(description, sizeof(description), "%s:%d", - source_filename, source_line); + source_filename, source_line); debug_msg("Breakpoint %d set at %s\n", GetID(), Description()); } @@ -151,12 +150,12 @@ bool DbgBreakpoint::SetLocation(ParseLocationRec plr, std::string_view loc_str) { std::string loc_s(loc_str); kind = BP_FUNC; - function_name = make_full_var_name(current_module.c_str(), - loc_s.c_str()); + function_name = make_full_var_name(zeek::detail::current_module.c_str(), + loc_s.c_str()); at_stmt = plr.stmt; - const Location* loc = at_stmt->GetLocationInfo(); + const zeek::detail::Location* loc = at_stmt->GetLocationInfo(); 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); debug_msg("Breakpoint %d set at %s\n", GetID(), Description()); } @@ -177,7 +176,7 @@ bool DbgBreakpoint::SetLocation(zeek::detail::Stmt* stmt) SetEnable(true); AddToGlobalMap(); - const Location* loc = stmt->GetLocationInfo(); + const zeek::detail::Location* loc = stmt->GetLocationInfo(); snprintf(description, sizeof(description), "%s:%d", loc->filename, loc->last_line); @@ -351,13 +350,13 @@ void DbgBreakpoint::PrintHitMsg() case BP_LINE: { ODesc d; - Frame* f = g_frame_stack.back(); - const BroFunc* func = f->GetFunction(); + zeek::detail::Frame* f = g_frame_stack.back(); + const zeek::detail::ScriptFunc* func = f->GetFunction(); if ( func ) func->DescribeDebug (&d, f->GetFuncArgs()); - const Location* loc = at_stmt->GetLocationInfo(); + const zeek::detail::Location* loc = at_stmt->GetLocationInfo(); debug_msg("Breakpoint %d, %s at %s:%d\n", GetID(), d.Description(), diff --git a/src/DbgWatch.cc b/src/DbgWatch.cc index 5d286afc1c..157ab70c35 100644 --- a/src/DbgWatch.cc +++ b/src/DbgWatch.cc @@ -7,7 +7,7 @@ #include "Reporter.h" // Support classes -DbgWatch::DbgWatch(BroObj* var_to_watch) +DbgWatch::DbgWatch(zeek::Obj* var_to_watch) { reporter->InternalError("DbgWatch unimplemented"); } diff --git a/src/DbgWatch.h b/src/DbgWatch.h index 72a0bbe7fd..a66d9d1bc1 100644 --- a/src/DbgWatch.h +++ b/src/DbgWatch.h @@ -4,17 +4,17 @@ #include "util.h" -class BroObj; - ZEEK_FORWARD_DECLARE_NAMESPACED(Expr, zeek::detail); +namespace zeek { class Obj; } +using BroObj [[deprecated("Remove in v4.1. Use zeek:Obj instead.")]] = zeek::Obj; class DbgWatch { public: - explicit DbgWatch(BroObj* var_to_watch); + explicit DbgWatch(zeek::Obj* var_to_watch); explicit DbgWatch(zeek::detail::Expr* expr_to_watch); ~DbgWatch(); protected: - BroObj* var; + zeek::Obj* var; zeek::detail::Expr* expr; }; diff --git a/src/Debug.cc b/src/Debug.cc index f1e94e96c9..3322251d83 100644 --- a/src/Debug.cc +++ b/src/Debug.cc @@ -44,7 +44,7 @@ std::map g_dbgfilemaps; // current context; you don't want to do it after a step or next // command unless you've exited a function. static bool step_or_next_pending = false; -static Frame* last_frame; +static zeek::detail::Frame* last_frame; DebuggerState::DebuggerState() { @@ -55,7 +55,7 @@ DebuggerState::DebuggerState() BreakFromSignal(false); // ### Don't choose this arbitrary size! Extend Frame. - dbg_locals = new Frame(1024, /* func = */ nullptr, /* fn_args = */ nullptr); + dbg_locals = new zeek::detail::Frame(1024, /* func = */ nullptr, /* fn_args = */ nullptr); } DebuggerState::~DebuggerState() @@ -136,7 +136,7 @@ int TraceState::LogTrace(const char* fmt, ...) fprintf(trace_file, "%.6f ", network_time); const zeek::detail::Stmt* stmt; - Location loc; + zeek::detail::Location loc; loc.filename = nullptr; if ( g_frame_stack.size() > 0 && g_frame_stack.back() ) @@ -146,7 +146,7 @@ int TraceState::LogTrace(const char* fmt, ...) loc = *stmt->GetLocationInfo(); else { - const BroFunc* f = g_frame_stack.back()->GetFunction(); + const zeek::detail::ScriptFunc* f = g_frame_stack.back()->GetFunction(); if ( f ) loc = *f->GetLocationInfo(); } @@ -174,7 +174,7 @@ int TraceState::LogTrace(const char* fmt, ...) // Helper functions. -void get_first_statement(zeek::detail::Stmt* list, zeek::detail::Stmt*& first, Location& loc) +void get_first_statement(zeek::detail::Stmt* list, zeek::detail::Stmt*& first, zeek::detail::Location& loc) { if ( ! list ) { @@ -197,11 +197,11 @@ void get_first_statement(zeek::detail::Stmt* list, zeek::detail::Stmt*& first, L static void parse_function_name(vector& result, ParseLocationRec& plr, const string& s) { // function name - const auto& id = lookup_ID(s.c_str(), current_module.c_str()); + const auto& id = zeek::detail::lookup_ID(s.c_str(), zeek::detail::current_module.c_str()); if ( ! id ) { - string fullname = make_full_var_name(current_module.c_str(), s.c_str()); + string fullname = make_full_var_name(zeek::detail::current_module.c_str(), s.c_str()); debug_msg("Function %s not defined.\n", fullname.c_str()); plr.type = plrUnknown; return; @@ -221,8 +221,8 @@ static void parse_function_name(vector& result, return; } - const Func* func = id->GetVal()->AsFunc(); - const vector& bodies = func->GetBodies(); + const zeek::Func* func = id->GetVal()->AsFunc(); + const vector& bodies = func->GetBodies(); if ( bodies.size() == 0 ) { @@ -244,7 +244,7 @@ static void parse_function_name(vector& result, for ( unsigned int i = 0; i < bodies.size(); ++i ) { zeek::detail::Stmt* first; - Location stmt_loc; + zeek::detail::Location 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); } @@ -287,7 +287,7 @@ static void parse_function_name(vector& result, // Find first atomic (non-STMT_LIST) statement zeek::detail::Stmt* first; - Location stmt_loc; + zeek::detail::Location stmt_loc; if ( body ) { @@ -728,17 +728,17 @@ static char* get_prompt(bool reset_counter = false) return prompt; } -string get_context_description(const zeek::detail::Stmt* stmt, const Frame* frame) +string get_context_description(const zeek::detail::Stmt* stmt, const zeek::detail::Frame* frame) { ODesc d; - const BroFunc* func = frame ? frame->GetFunction() : nullptr; + const zeek::detail::ScriptFunc* func = frame ? frame->GetFunction() : nullptr; if ( func ) func->DescribeDebug(&d, frame->GetFuncArgs()); else d.Add("", 0); - Location loc; + zeek::detail::Location loc; if ( stmt ) loc = *stmt->GetLocationInfo(); else @@ -769,18 +769,18 @@ int dbg_handle_debug_input() g_debugger_state.BreakFromSignal(false); } - Frame* curr_frame = g_frame_stack.back(); - const BroFunc* func = curr_frame->GetFunction(); + zeek::detail::Frame* curr_frame = g_frame_stack.back(); + const zeek::detail::ScriptFunc* func = curr_frame->GetFunction(); if ( func ) - current_module = extract_module_name(func->Name()); + zeek::detail::current_module = extract_module_name(func->Name()); else - current_module = GLOBAL_MODULE_NAME; + zeek::detail::current_module = GLOBAL_MODULE_NAME; const zeek::detail::Stmt* stmt = curr_frame->GetNextStmt(); if ( ! stmt ) reporter->InternalError("Assertion failed: stmt != 0"); - const Location loc = *stmt->GetLocationInfo(); + const zeek::detail::Location loc = *stmt->GetLocationInfo(); if ( ! step_or_next_pending || g_frame_stack.back() != last_frame ) { @@ -840,7 +840,7 @@ int dbg_handle_debug_input() // Return true to continue execution, false to abort. -bool pre_execute_stmt(zeek::detail::Stmt* stmt, Frame* f) +bool pre_execute_stmt(zeek::detail::Stmt* stmt, zeek::detail::Frame* f) { if ( ! g_policy_debug || stmt->Tag() == STMT_LIST || stmt->Tag() == STMT_NULL ) @@ -905,7 +905,7 @@ bool pre_execute_stmt(zeek::detail::Stmt* stmt, Frame* f) return true; } -bool post_execute_stmt(zeek::detail::Stmt* stmt, Frame* f, Val* result, stmt_flow_type* flow) +bool post_execute_stmt(zeek::detail::Stmt* stmt, zeek::detail::Frame* f, zeek::Val* result, stmt_flow_type* flow) { // Handle the case where someone issues a "next" debugger command, // but we're at a return statement, so the next statement is in @@ -948,7 +948,7 @@ extern YYLTYPE yylloc; // holds start line and column of token extern int line_number; extern const char* filename; -IntrusivePtr dbg_eval_expr(const char* expr) +zeek::ValPtr dbg_eval_expr(const char* expr) { // Push the current frame's associated scope. // Note: g_debugger_state.curr_frame_idx is the user-visible number, @@ -959,15 +959,15 @@ IntrusivePtr dbg_eval_expr(const char* expr) if ( ! (frame_idx >= 0 && (unsigned) frame_idx < g_frame_stack.size()) ) reporter->InternalError("Assertion failed: frame_idx >= 0 && (unsigned) frame_idx < g_frame_stack.size()"); - Frame* frame = g_frame_stack[frame_idx]; + zeek::detail::Frame* frame = g_frame_stack[frame_idx]; if ( ! (frame) ) reporter->InternalError("Assertion failed: frame"); - const BroFunc* func = frame->GetFunction(); + const zeek::detail::ScriptFunc* func = frame->GetFunction(); if ( func ) { Ref(func->GetScope()); - push_existing_scope(func->GetScope()); + zeek::detail::push_existing_scope(func->GetScope()); } // ### Possibly push a debugger-local scope? @@ -983,7 +983,7 @@ IntrusivePtr dbg_eval_expr(const char* expr) yylloc.first_line = yylloc.last_line = line_number = 1; // Parse the thing into an expr. - IntrusivePtr result; + zeek::ValPtr result; if ( yyparse() ) { if ( g_curr_debug_error ) @@ -1001,7 +1001,7 @@ IntrusivePtr dbg_eval_expr(const char* expr) result = g_curr_debug_expr->Eval(frame); if ( func ) - pop_scope(); + zeek::detail::pop_scope(); delete g_curr_debug_expr; g_curr_debug_expr = nullptr; diff --git a/src/Debug.h b/src/Debug.h index e467c00a0e..1829c7a473 100644 --- a/src/Debug.h +++ b/src/Debug.h @@ -11,10 +11,14 @@ #include #include -template class IntrusivePtr; -class Val; - +ZEEK_FORWARD_DECLARE_NAMESPACED(Frame, zeek::detail); ZEEK_FORWARD_DECLARE_NAMESPACED(Stmt, zeek::detail); +ZEEK_FORWARD_DECLARE_NAMESPACED(Val, zeek); + +namespace zeek { +template class IntrusivePtr; +using ValPtr = zeek::IntrusivePtr; +} // This needs to be defined before we do the includes that come after it. enum ParseLocationRecType { plrUnknown, plrFileAndLine, plrFunction }; @@ -26,9 +30,8 @@ struct ParseLocationRec { }; class StmtLocMapping; -typedef PQueue Filemap; // mapping for a single file +typedef zeek::PQueue Filemap; // mapping for a single file -class Frame; class DbgBreakpoint; class DbgWatch; class DbgDisplay; @@ -37,7 +40,9 @@ class StmtHashFn; typedef std::map BPIDMapType; typedef std::multimap BPMapType; +namespace zeek { extern std::string current_module; +} class TraceState { public: @@ -84,7 +89,7 @@ public: bool already_did_list; // did we already do a 'list' command? - Location last_loc; // used by 'list'; the last location listed + zeek::detail::Location last_loc; // used by 'list'; the last location listed BPIDMapType breakpoints; // BPID -> Breakpoint std::vector watches; @@ -98,7 +103,7 @@ protected: int next_bp_id, next_watch_id, next_display_id; private: - Frame* dbg_locals; // unused + zeek::detail::Frame* dbg_locals; // unused }; // Source line -> statement mapping. @@ -106,14 +111,14 @@ private: class StmtLocMapping { public: StmtLocMapping() { } - StmtLocMapping(const Location* l, zeek::detail::Stmt* s) { loc = *l; stmt = s; } + StmtLocMapping(const zeek::detail::Location* l, zeek::detail::Stmt* s) { loc = *l; stmt = s; } bool StartsAfter(const StmtLocMapping* m2); - const Location& Loc() const { return loc; } + const zeek::detail::Location& Loc() const { return loc; } zeek::detail::Stmt* Statement() const { return stmt; } protected: - Location loc; + zeek::detail::Location loc; zeek::detail::Stmt* stmt; }; @@ -145,8 +150,8 @@ std::vector parse_location_string(const std::string& s); // Debugging hooks. // Return true to continue execution, false to abort. -bool pre_execute_stmt(zeek::detail::Stmt* stmt, Frame* f); -bool post_execute_stmt(zeek::detail::Stmt* stmt, Frame* f, Val* result, stmt_flow_type* flow); +bool pre_execute_stmt(zeek::detail::Stmt* stmt, zeek::detail::Frame* f); +bool post_execute_stmt(zeek::detail::Stmt* stmt, zeek::detail::Frame* f, zeek::Val* result, stmt_flow_type* flow); // Returns 1 if successful, 0 otherwise. // If cmdfile is non-nil, it contains the location of a file of commands @@ -162,7 +167,7 @@ int dbg_handle_debug_input(); // read a line and then have it executed int dbg_execute_command(const char* cmd); // Interactive expression evaluation. -IntrusivePtr dbg_eval_expr(const char* expr); +zeek::ValPtr dbg_eval_expr(const char* expr); // Extra debugging facilities. // TODO: current connections, memory allocated, other internal data structures. @@ -170,9 +175,9 @@ IntrusivePtr dbg_eval_expr(const char* expr); int dbg_read_internal_state(); // Get line that looks like "In FnFoo(arg = val) at File:Line". -std::string get_context_description(const zeek::detail::Stmt* stmt, const Frame* frame); +std::string get_context_description(const zeek::detail::Stmt* stmt, const zeek::detail::Frame* frame); -extern Frame* g_dbg_locals; // variables created within debugger context +extern zeek::detail::Frame* g_dbg_locals; // variables created within debugger context extern std::map g_dbgfilemaps; // filename => filemap diff --git a/src/DebugCmds.cc b/src/DebugCmds.cc index b7c411989a..c2723ce930 100644 --- a/src/DebugCmds.cc +++ b/src/DebugCmds.cc @@ -15,7 +15,6 @@ #include "Desc.h" #include "DbgBreakpoint.h" #include "ID.h" -#include "IntrusivePtr.h" #include "Frame.h" #include "Func.h" #include "Stmt.h" @@ -58,7 +57,7 @@ static void lookup_global_symbols_regex(const string& orig_regex, vectorVars(); zeek::detail::ID* nextid; @@ -124,7 +123,7 @@ static void choose_global_symbols_regex(const string& regex, vector g_DebugCmdInfos; +zeek::PQueue g_DebugCmdInfos; DebugCmdInfo::DebugCmdInfo(const DebugCmdInfo& info) : cmd(info.cmd), helpstring(nullptr) @@ -215,7 +214,7 @@ static int dbg_backtrace_internal(int start, int end) for ( int i = start; i >= end; --i ) { - const Frame* f = g_frame_stack[i]; + const zeek::detail::Frame* f = g_frame_stack[i]; const zeek::detail::Stmt* stmt = f ? f->GetNextStmt() : nullptr; string context = get_context_description(stmt, f); @@ -337,7 +336,7 @@ int dbg_cmd_frame(DebugCmd cmd, const vector& args) if ( ! stmt ) reporter->InternalError("Assertion failed: %s", "stmt != 0"); - const Location loc = *stmt->GetLocationInfo(); + const zeek::detail::Location loc = *stmt->GetLocationInfo(); g_debugger_state.last_loc = loc; g_debugger_state.already_did_list = false; diff --git a/src/DebugCmds.h b/src/DebugCmds.h index ff318140e0..9753923903 100644 --- a/src/DebugCmds.h +++ b/src/DebugCmds.h @@ -41,7 +41,7 @@ protected: bool repeatable; }; -extern PQueue g_DebugCmdInfos; +extern zeek::PQueue g_DebugCmdInfos; void init_global_dbg_constants (); diff --git a/src/Desc.cc b/src/Desc.cc index 624aeaaa6b..9d41ca8b27 100644 --- a/src/Desc.cc +++ b/src/Desc.cc @@ -197,7 +197,7 @@ void ODesc::AddCS(const char* s) Add(s); } -void ODesc::AddBytes(const BroString* s) +void ODesc::AddBytes(const zeek::String* s) { if ( IsReadable() ) { @@ -205,7 +205,7 @@ void ODesc::AddBytes(const BroString* s) AddBytes(reinterpret_cast(s->Bytes()), s->Len()); else { - const char* str = s->Render(BroString::EXPANDED_STRING); + const char* str = s->Render(zeek::String::EXPANDED_STRING); Add(str); delete [] str; } diff --git a/src/Desc.h b/src/Desc.h index 7a009caa57..fc02b1113d 100644 --- a/src/Desc.h +++ b/src/Desc.h @@ -2,7 +2,7 @@ #pragma once -#include "BroString.h" // for byte_vec +#include "ZeekString.h" // for byte_vec #include "util.h" // for bro_int_t #include @@ -93,7 +93,7 @@ public: // Add s as a counted string. void AddCS(const char* s); - void AddBytes(const BroString* s); + void AddBytes(const zeek::String* s); void Add(const char* s1, const char* s2) { Add(s1); Add(s2); } @@ -130,7 +130,7 @@ public: const char* Description() const { return (const char*) base; } const u_char* Bytes() const { return (const u_char *) base; } - byte_vec TakeBytes() + zeek::byte_vec TakeBytes() { const void* t = base; base = nullptr; @@ -139,7 +139,7 @@ public: // Don't clear offset, as we want to still support // subsequent calls to Len(). - return byte_vec(t); + return zeek::byte_vec(t); } int Len() const { return offset; } diff --git a/src/Dict.cc b/src/Dict.cc index 2fa2eae0a6..2d1f82f40f 100644 --- a/src/Dict.cc +++ b/src/Dict.cc @@ -13,17 +13,18 @@ // If the mean bucket length exceeds the following then Insert() will // increase the size of the hash table. -#define DEFAULT_DENSITY_THRESH 3.0 +constexpr double DEFAULT_DENSITY_THRESH = 3.0; // Threshold above which we do not try to ensure that the hash size // is prime. -#define PRIME_THRESH 1000 +constexpr int PRIME_THRESH = 1000; // Default number of hash buckets in dictionary. The dictionary will // increase the size of the hash table as needed. -#define DEFAULT_DICT_SIZE 16 +constexpr int DEFAULT_DICT_SIZE = 16; -TEST_SUITE_BEGIN("Dict"); +namespace zeek { +namespace detail { class DictEntry { public: @@ -40,6 +41,8 @@ public: void* value; }; +} //namespace detail + // The value of an iteration cookie is the bucket and offset within the // bucket at which to start looking for the next value to return. class IterCookie { @@ -47,25 +50,29 @@ public: IterCookie(int b, int o) : bucket(b), offset(o) {} int bucket, offset; - PList** ttbl = nullptr; + zeek::PList** ttbl = nullptr; const int* num_buckets_p = nullptr; - PList inserted; // inserted while iterating + zeek::PList inserted; // inserted while iterating }; +} // namespace zeek + +TEST_SUITE_BEGIN("Dict"); + TEST_CASE("dict construction") { - PDict dict; + zeek::PDict dict; CHECK(dict.IsOrdered() == false); CHECK(dict.Length() == 0); - PDict dict2(ORDERED); + zeek::PDict dict2(zeek::ORDERED); CHECK(dict2.IsOrdered() == true); CHECK(dict2.Length() == 0); } TEST_CASE("dict operation") { - PDict dict; + zeek::PDict dict; uint32_t val = 10; uint32_t key_val = 5; @@ -111,8 +118,8 @@ TEST_CASE("dict operation") TEST_CASE("dict nthentry") { - PDict unordered(UNORDERED); - PDict ordered(ORDERED); + zeek::PDict unordered(zeek::UNORDERED); + zeek::PDict ordered(zeek::ORDERED); uint32_t val = 15; uint32_t key_val = 5; @@ -147,7 +154,7 @@ TEST_CASE("dict nthentry") TEST_CASE("dict iteration") { - PDict dict; + zeek::PDict dict; uint32_t val = 15; uint32_t key_val = 5; @@ -161,7 +168,7 @@ TEST_CASE("dict iteration") dict.Insert(key2, &val2); HashKey* it_key; - IterCookie* it = dict.InitForIteration(); + zeek::IterCookie* it = dict.InitForIteration(); CHECK(it != nullptr); int count = 0; @@ -186,10 +193,14 @@ TEST_CASE("dict iteration") delete key2; } -Dictionary::Dictionary(dict_order ordering, int initial_size) +TEST_SUITE_END(); + +namespace zeek { + +Dictionary::Dictionary(DictOrder ordering, int initial_size) { if ( ordering == ORDERED ) - order = new PList; + order = new zeek::PList; if ( initial_size > 0 ) Init(initial_size); @@ -218,7 +229,7 @@ void Dictionary::DeInit() for ( int i = 0; i < num_buckets; ++i ) if ( tbl[i] ) { - PList* chain = tbl[i]; + zeek::PList* chain = tbl[i]; for ( const auto& e : *chain ) { if ( delete_func ) @@ -238,7 +249,7 @@ void Dictionary::DeInit() for ( int i = 0; i < num_buckets2; ++i ) if ( tbl2[i] ) { - PList* chain = tbl2[i]; + zeek::PList* chain = tbl2[i]; for ( const auto& e : *chain ) { if ( delete_func ) @@ -259,7 +270,7 @@ void* Dictionary::Lookup(const void* key, int key_size, hash_t hash) const return nullptr; hash_t h; - PList* chain; + zeek::PList* chain; // Figure out which hash table to look in. h = hash % num_buckets; @@ -287,12 +298,12 @@ void* Dictionary::Insert(void* key, int key_size, hash_t hash, void* val, if ( ! tbl ) Init(DEFAULT_DICT_SIZE); - DictEntry* new_entry = new DictEntry(key, key_size, hash, val); + detail::DictEntry* new_entry = new detail::DictEntry(key, key_size, hash, val); void* old_val = Insert(new_entry, copy_key); if ( old_val ) { - // We didn't need the new DictEntry, the key was already + // We didn't need the new detail::DictEntry, the key was already // present. delete new_entry; } @@ -315,7 +326,7 @@ void* Dictionary::Remove(const void* key, int key_size, hash_t hash, return nullptr; hash_t h; - PList* chain; + zeek::PList* chain; int* num_entries_ptr; // Figure out which hash table to look in @@ -338,7 +349,7 @@ void* Dictionary::Remove(const void* key, int key_size, hash_t hash, for ( auto i = 0u; i < chain_length; ++i ) { - DictEntry* entry = (*chain)[i]; + detail::DictEntry* entry = (*chain)[i]; if ( entry->hash == hash && entry->len == key_size && ! memcmp(key, entry->key, key_size) ) @@ -357,8 +368,8 @@ void* Dictionary::Remove(const void* key, int key_size, hash_t hash, return nullptr; } -void* Dictionary::DoRemove(DictEntry* entry, hash_t h, - PList* chain, int chain_offset) +void* Dictionary::DoRemove(detail::DictEntry* entry, hash_t h, + zeek::PList* chain, int chain_offset) { void* entry_value = entry->value; @@ -397,7 +408,7 @@ void* Dictionary::NthEntry(int n, const void*& key, int& key_len) const if ( ! order || n < 0 || n >= Length() ) return nullptr; - DictEntry* entry = (*order)[n]; + detail::DictEntry* entry = (*order)[n]; key = entry->key; key_len = entry->len; return entry->value; @@ -417,7 +428,7 @@ void* Dictionary::NextEntry(HashKey*& h, IterCookie*& cookie, int return_hash) c { if ( ! tbl && ! tbl2 ) { - const_cast*>(&cookies)->remove(cookie); + const_cast*>(&cookies)->remove(cookie); delete cookie; cookie = nullptr; return nullptr; @@ -427,7 +438,7 @@ void* Dictionary::NextEntry(HashKey*& h, IterCookie*& cookie, int return_hash) c // That keeps the list small and helps avoiding searching // a large list when deleting an entry. - DictEntry* entry; + detail::DictEntry* entry; if ( cookie->inserted.length() ) { @@ -442,7 +453,7 @@ void* Dictionary::NextEntry(HashKey*& h, IterCookie*& cookie, int return_hash) c int b = cookie->bucket; int o = cookie->offset; - PList** ttbl; + zeek::PList** ttbl; const int* num_buckets_p; if ( ! cookie->ttbl ) @@ -484,7 +495,7 @@ void* Dictionary::NextEntry(HashKey*& h, IterCookie*& cookie, int return_hash) c // FIXME: I don't like removing the const here. But is there // a better way? - const_cast*>(&cookies)->remove(cookie); + const_cast*>(&cookies)->remove(cookie); delete cookie; cookie = nullptr; return nullptr; @@ -503,7 +514,7 @@ void* Dictionary::NextEntry(HashKey*& h, IterCookie*& cookie, int return_hash) c void Dictionary::Init(int size) { num_buckets = NextPrime(size); - tbl = new PList*[num_buckets]; + tbl = new zeek::PList*[num_buckets]; for ( int i = 0; i < num_buckets; ++i ) tbl[i] = nullptr; @@ -515,7 +526,7 @@ void Dictionary::Init(int size) void Dictionary::Init2(int size) { num_buckets2 = NextPrime(size); - tbl2 = new PList*[num_buckets2]; + tbl2 = new zeek::PList*[num_buckets2]; for ( int i = 0; i < num_buckets2; ++i ) tbl2[i] = nullptr; @@ -524,12 +535,12 @@ void Dictionary::Init2(int size) } // private -void* Dictionary::Insert(DictEntry* new_entry, bool copy_key) +void* Dictionary::Insert(detail::DictEntry* new_entry, bool copy_key) { if ( ! tbl ) Init(DEFAULT_DICT_SIZE); - PList** ttbl; + zeek::PList** ttbl; int* num_entries_ptr; int* max_num_entries_ptr; hash_t h = new_entry->hash % num_buckets; @@ -554,7 +565,7 @@ void* Dictionary::Insert(DictEntry* new_entry, bool copy_key) max_num_entries_ptr = &max_num_entries2; } - PList* chain = ttbl[h]; + zeek::PList* chain = ttbl[h]; int n = new_entry->len; @@ -562,7 +573,7 @@ void* Dictionary::Insert(DictEntry* new_entry, bool copy_key) { for ( int i = 0; i < chain->length(); ++i ) { - DictEntry* entry = (*chain)[i]; + detail::DictEntry* entry = (*chain)[i]; if ( entry->hash == new_entry->hash && entry->len == n && @@ -576,7 +587,7 @@ void* Dictionary::Insert(DictEntry* new_entry, bool copy_key) } else // Create new chain. - chain = ttbl[h] = new PList; + chain = ttbl[h] = new zeek::PList; // If we got this far, then we couldn't use an existing copy // of the key, so make a new one if necessary. @@ -660,7 +671,7 @@ void Dictionary::MoveChains() do { - PList* chain = tbl[tbl_next_ind++]; + zeek::PList* chain = tbl[tbl_next_ind++]; if ( ! chain ) continue; @@ -720,13 +731,13 @@ unsigned int Dictionary::MemoryAllocation() const for ( int i = 0; i < num_buckets; ++i ) if ( tbl[i] ) { - PList* chain = tbl[i]; + zeek::PList* chain = tbl[i]; for ( const auto& c : *chain ) - size += padded_sizeof(DictEntry) + pad_size(c->len); + size += padded_sizeof(detail::DictEntry) + pad_size(c->len); size += chain->MemoryAllocation(); } - size += pad_size(num_buckets * sizeof(PList*)); + size += pad_size(num_buckets * sizeof(zeek::PList*)); if ( order ) size += order->MemoryAllocation(); @@ -736,13 +747,13 @@ unsigned int Dictionary::MemoryAllocation() const for ( int i = 0; i < num_buckets2; ++i ) if ( tbl2[i] ) { - PList* chain = tbl2[i]; + zeek::PList* chain = tbl2[i]; for ( const auto& c : *chain ) - size += padded_sizeof(DictEntry) + pad_size(c->len); + size += padded_sizeof(detail::DictEntry) + pad_size(c->len); size += chain->MemoryAllocation(); } - size += pad_size(num_buckets2 * sizeof(PList*)); + size += pad_size(num_buckets2 * sizeof(zeek::PList*)); } return size; @@ -753,4 +764,4 @@ void generic_delete_func(void* v) free(v); } -TEST_SUITE_END(); +} // namespace zeek diff --git a/src/Dict.h b/src/Dict.h index 22840a0dad..3210605944 100644 --- a/src/Dict.h +++ b/src/Dict.h @@ -2,27 +2,31 @@ #pragma once +#include "zeek-config.h" + #include "List.h" #include "Hash.h" -class Dictionary; -class DictEntry; -class IterCookie; - -// Type indicating whether the dictionary should keep track of the order -// of insertions. -enum dict_order { ORDERED, UNORDERED }; +ZEEK_FORWARD_DECLARE_NAMESPACED(DictEntry, zeek::detail); +ZEEK_FORWARD_DECLARE_NAMESPACED(IterCookie, zeek); // Type for function to be called when deleting elements. typedef void (*dict_delete_func)(void*); +namespace zeek { + +// Type indicating whether the dictionary should keep track of the order +// of insertions. +enum DictOrder { ORDERED, UNORDERED }; + // A dict_delete_func that just calls delete. extern void generic_delete_func(void*); class Dictionary { public: - explicit Dictionary(dict_order ordering = UNORDERED, - int initial_size = 0); + explicit Dictionary(DictOrder ordering = UNORDERED, + int initial_size = 0); + ~Dictionary(); // Member functions for looking up a key, inserting/changing its @@ -125,10 +129,10 @@ private: void DeInit(); // Internal version of Insert(). - void* Insert(DictEntry* entry, bool copy_key); + void* Insert(zeek::detail::DictEntry* entry, bool copy_key); - void* DoRemove(DictEntry* entry, hash_t h, - PList* chain, int chain_offset); + void* DoRemove(zeek::detail::DictEntry* entry, hash_t h, + zeek::PList* chain, int chain_offset); int NextPrime(int n) const; bool IsPrime(int n) const; @@ -158,7 +162,7 @@ private: // When we're resizing, we'll have tbl (old) and tbl2 (new) // tbl_next_ind keeps track of how much we've moved to tbl2 // (it's the next index we're going to move). - PList** tbl = nullptr; + zeek::PList** tbl = nullptr; int num_buckets = 0; int num_entries = 0; int max_num_entries = 0; @@ -167,7 +171,7 @@ private: double den_thresh = 0.0; // Resizing table (replicates tbl above). - PList** tbl2 = nullptr; + zeek::PList** tbl2 = nullptr; int num_buckets2 = 0; int num_entries2 = 0; int max_num_entries2 = 0; @@ -177,16 +181,16 @@ private: hash_t tbl_next_ind = 0; - PList* order = nullptr; + zeek::PList* order = nullptr; dict_delete_func delete_func = nullptr; - PList cookies; + zeek::PList cookies; }; template class PDict : public Dictionary { public: - explicit PDict(dict_order ordering = UNORDERED, int initial_size = 0) : + explicit PDict(DictOrder ordering = UNORDERED, int initial_size = 0) : Dictionary(ordering, initial_size) {} T* Lookup(const char* key) const { @@ -221,3 +225,8 @@ public: T* RemoveEntry(const HashKey& key) { return (T*) Remove(key.Key(), key.Size(), key.Hash()); } }; + +} //namespace zeek + +using Dictionary [[deprecated("Remove in v4.1. Use zeek::Dictionary instead.")]] = zeek::Dictionary; +template using PDict [[deprecated("Remove in v4.1. Use zeek::PDict instead.")]] = zeek::PDict; diff --git a/src/Discard.cc b/src/Discard.cc index 6625786e3b..053bed4e78 100644 --- a/src/Discard.cc +++ b/src/Discard.cc @@ -6,7 +6,7 @@ #include -#include "BroString.h" +#include "ZeekString.h" #include "Net.h" #include "Func.h" #include "Var.h" @@ -93,7 +93,7 @@ bool Discarder::NextPacket(const IP_Hdr* ip, int len, int caplen) zeek::Args args{ ip->ToPktHdrVal(), - {AdoptRef{}, BuildData(data, th_len, len, caplen)}, + {zeek::AdoptRef{}, BuildData(data, th_len, len, caplen)}, }; try @@ -117,7 +117,7 @@ bool Discarder::NextPacket(const IP_Hdr* ip, int len, int caplen) zeek::Args args{ ip->ToPktHdrVal(), - {AdoptRef{}, BuildData(data, uh_len, len, caplen)}, + {zeek::AdoptRef{}, BuildData(data, uh_len, len, caplen)}, }; try @@ -155,7 +155,7 @@ bool Discarder::NextPacket(const IP_Hdr* ip, int len, int caplen) return discard_packet; } -Val* Discarder::BuildData(const u_char* data, int hdrlen, int len, int caplen) +zeek::Val* Discarder::BuildData(const u_char* data, int hdrlen, int len, int caplen) { len -= hdrlen; caplen -= hdrlen; @@ -163,5 +163,5 @@ Val* Discarder::BuildData(const u_char* data, int hdrlen, int len, int caplen) len = std::max(std::min(std::min(len, caplen), discarder_maxlen), 0); - return new StringVal(new BroString(data, len, true)); + return new zeek::StringVal(new zeek::String(data, len, true)); } diff --git a/src/Discard.h b/src/Discard.h index ac69db845f..97b469cbd8 100644 --- a/src/Discard.h +++ b/src/Discard.h @@ -7,8 +7,13 @@ #include "IntrusivePtr.h" class IP_Hdr; -class Val; -class Func; + +ZEEK_FORWARD_DECLARE_NAMESPACED(Func, zeek); +ZEEK_FORWARD_DECLARE_NAMESPACED(Val, zeek); + +namespace zeek { +using FuncPtr = zeek::IntrusivePtr; +} class Discarder { public: @@ -20,12 +25,12 @@ public: bool NextPacket(const IP_Hdr* ip, int len, int caplen); protected: - Val* BuildData(const u_char* data, int hdrlen, int len, int caplen); + zeek::Val* BuildData(const u_char* data, int hdrlen, int len, int caplen); - IntrusivePtr check_ip; - IntrusivePtr check_tcp; - IntrusivePtr check_udp; - IntrusivePtr check_icmp; + zeek::FuncPtr check_ip; + zeek::FuncPtr check_tcp; + zeek::FuncPtr check_udp; + zeek::FuncPtr check_icmp; // Maximum amount of application data passed to filtering functions. int discarder_maxlen; diff --git a/src/Event.cc b/src/Event.cc index 0f8c3b468b..c9012f5ed5 100644 --- a/src/Event.cc +++ b/src/Event.cc @@ -19,7 +19,7 @@ uint64_t num_events_queued = 0; uint64_t num_events_dispatched = 0; Event::Event(EventHandlerPtr arg_handler, zeek::Args arg_args, - SourceID arg_src, analyzer::ID arg_aid, BroObj* arg_obj) + SourceID arg_src, analyzer::ID arg_aid, Obj* arg_obj) : handler(arg_handler), args(std::move(arg_args)), src(arg_src), @@ -95,14 +95,14 @@ EventMgr::~EventMgr() void EventMgr::QueueEventFast(const EventHandlerPtr &h, val_list vl, SourceID src, analyzer::ID aid, TimerMgr* mgr, - BroObj* obj) + Obj* obj) { QueueEvent(new Event(h, zeek::val_list_to_args(vl), src, aid, obj)); } void EventMgr::QueueEvent(const EventHandlerPtr &h, val_list vl, SourceID src, analyzer::ID aid, - TimerMgr* mgr, BroObj* obj) + TimerMgr* mgr, Obj* obj) { auto args = zeek::val_list_to_args(vl); @@ -112,7 +112,7 @@ void EventMgr::QueueEvent(const EventHandlerPtr &h, val_list vl, void EventMgr::QueueEvent(const EventHandlerPtr &h, val_list* vl, SourceID src, analyzer::ID aid, - TimerMgr* mgr, BroObj* obj) + TimerMgr* mgr, Obj* obj) { auto args = zeek::val_list_to_args(*vl); delete vl; @@ -122,7 +122,7 @@ void EventMgr::QueueEvent(const EventHandlerPtr &h, val_list* vl, } void EventMgr::Enqueue(const EventHandlerPtr& h, zeek::Args vl, - SourceID src, analyzer::ID aid, BroObj* obj) + SourceID src, analyzer::ID aid, Obj* obj) { QueueEvent(new Event(h, std::move(vl), src, aid, obj)); } diff --git a/src/Event.h b/src/Event.h index 69e9fe37f9..41620a906a 100644 --- a/src/Event.h +++ b/src/Event.h @@ -14,11 +14,11 @@ class EventMgr; -class Event final : public BroObj { +class Event final : public zeek::Obj { public: Event(EventHandlerPtr handler, zeek::Args args, SourceID src = SOURCE_LOCAL, analyzer::ID aid = 0, - BroObj* obj = nullptr); + zeek::Obj* obj = nullptr); void SetNext(Event* n) { next_event = n; } Event* NextEvent() const { return next_event; } @@ -41,14 +41,14 @@ protected: zeek::Args args; SourceID src; analyzer::ID aid; - BroObj* obj; + zeek::Obj* obj; Event* next_event; }; extern uint64_t num_events_queued; extern uint64_t num_events_dispatched; -class EventMgr final : public BroObj, public iosource::IOSource { +class EventMgr final : public zeek::Obj, public iosource::IOSource { public: EventMgr(); ~EventMgr() override; @@ -64,7 +64,7 @@ public: [[deprecated("Remove in v4.1. Use Enqueue() instead.")]] void QueueEventFast(const EventHandlerPtr &h, val_list vl, SourceID src = SOURCE_LOCAL, analyzer::ID aid = 0, - TimerMgr* mgr = nullptr, BroObj* obj = nullptr); + TimerMgr* mgr = nullptr, zeek::Obj* obj = nullptr); // Queues an event if there's an event handler (or remote consumer). This // function always takes ownership of decrementing the reference count of @@ -75,7 +75,7 @@ public: [[deprecated("Remove in v4.1. Use Enqueue() instead.")]] void QueueEvent(const EventHandlerPtr &h, val_list vl, SourceID src = SOURCE_LOCAL, analyzer::ID aid = 0, - TimerMgr* mgr = nullptr, BroObj* obj = nullptr); + TimerMgr* mgr = nullptr, zeek::Obj* obj = nullptr); // Same as QueueEvent, except taking the event's argument list via a // pointer instead of by value. This function takes ownership of the @@ -84,7 +84,7 @@ public: [[deprecated("Remove in v4.1. Use Enqueue() instead.")]] void QueueEvent(const EventHandlerPtr &h, val_list* vl, SourceID src = SOURCE_LOCAL, analyzer::ID aid = 0, - TimerMgr* mgr = nullptr, BroObj* obj = nullptr); + TimerMgr* mgr = nullptr, zeek::Obj* obj = nullptr); /** * Adds an event to the queue. If no handler is found for the event @@ -100,15 +100,15 @@ public: */ void Enqueue(const EventHandlerPtr& h, zeek::Args vl, SourceID src = SOURCE_LOCAL, analyzer::ID aid = 0, - BroObj* obj = nullptr); + zeek::Obj* obj = nullptr); /** * A version of Enqueue() taking a variable number of arguments. */ template std::enable_if_t< - std::is_convertible_v< - std::tuple_element_t<0, std::tuple>, IntrusivePtr>> + std::is_convertible_v< + std::tuple_element_t<0, std::tuple>, zeek::ValPtr>> Enqueue(const EventHandlerPtr& h, Args&&... args) { return Enqueue(h, zeek::Args{std::forward(args)...}); } @@ -143,7 +143,7 @@ protected: Event* tail; SourceID current_src; analyzer::ID current_aid; - RecordVal* src_val; + zeek::RecordVal* src_val; bool draining; zeek::detail::Flare queue_flare; }; diff --git a/src/EventHandler.cc b/src/EventHandler.cc index 60ae89536f..830a031f0e 100644 --- a/src/EventHandler.cc +++ b/src/EventHandler.cc @@ -26,13 +26,13 @@ EventHandler::operator bool() const || ! auto_publish.empty()); } -const IntrusivePtr& EventHandler::GetType(bool check_export) +const zeek::FuncTypePtr& EventHandler::GetType(bool check_export) { if ( type ) return type; - const auto& id = lookup_ID(name.data(), current_module.c_str(), false, false, - check_export); + const auto& id = zeek::detail::lookup_ID(name.data(), zeek::detail::current_module.c_str(), + false, false, check_export); if ( ! id ) return zeek::FuncType::nil; @@ -44,11 +44,11 @@ const IntrusivePtr& EventHandler::GetType(bool check_export) return type; } -void EventHandler::SetFunc(IntrusivePtr f) +void EventHandler::SetFunc(zeek::FuncPtr f) { local = std::move(f); } -void EventHandler::SetLocalHandler(Func* f) - { SetFunc({NewRef{}, f}); } +void EventHandler::SetLocalHandler(zeek::Func* f) + { SetFunc({zeek::NewRef{}, f}); } void EventHandler::Call(zeek::Args* vl, bool no_remote) { @@ -118,7 +118,7 @@ void EventHandler::NewEvent(zeek::Args* vl) const auto& args = GetType()->Params(); static auto call_argument_vector = zeek::id::find_type("call_argument_vector"); - auto vargs = make_intrusive(call_argument_vector); + auto vargs = zeek::make_intrusive(call_argument_vector); for ( int i = 0; i < args->NumFields(); i++ ) { @@ -127,13 +127,13 @@ void EventHandler::NewEvent(zeek::Args* vl) auto fdefault = args->FieldDefault(i); static auto call_argument = zeek::id::find_type("call_argument"); - auto rec = make_intrusive(call_argument); - rec->Assign(0, make_intrusive(fname)); + auto rec = zeek::make_intrusive(call_argument); + rec->Assign(0, zeek::make_intrusive(fname)); ODesc d; d.SetShort(); ftype->Describe(&d); - rec->Assign(1, make_intrusive(d.Description())); + rec->Assign(1, zeek::make_intrusive(d.Description())); if ( fdefault ) rec->Assign(2, std::move(fdefault)); @@ -145,8 +145,8 @@ void EventHandler::NewEvent(zeek::Args* vl) } Event* ev = new Event(new_event, { - make_intrusive(name), - std::move(vargs), - }); + zeek::make_intrusive(name), + std::move(vargs), + }); mgr.Dispatch(ev); } diff --git a/src/EventHandler.h b/src/EventHandler.h index 4016328655..7e1e96fc6d 100644 --- a/src/EventHandler.h +++ b/src/EventHandler.h @@ -9,7 +9,10 @@ #include #include -class Func; +ZEEK_FORWARD_DECLARE_NAMESPACED(Func, zeek); +namespace zeek { +using FuncPtr = zeek::IntrusivePtr; +} class EventHandler { public: @@ -17,22 +20,22 @@ public: const char* Name() { return name.data(); } - const IntrusivePtr& GetFunc() + const zeek::FuncPtr& GetFunc() { return local; } [[deprecated("Remove in v4.1. Use GetFunc().")]] - Func* LocalHandler() { return local.get(); } + zeek::Func* LocalHandler() { return local.get(); } - const IntrusivePtr& GetType(bool check_export = true); + const zeek::FuncTypePtr& GetType(bool check_export = true); [[deprecated("Remove in v4.1. Use GetType().")]] zeek::FuncType* FType(bool check_export = true) { return GetType().get(); } - void SetFunc(IntrusivePtr f); + void SetFunc(zeek::FuncPtr f); [[deprecated("Remove in v4.1. Use SetFunc().")]] - void SetLocalHandler(Func* f); + void SetLocalHandler(zeek::Func* f); void AutoPublish(std::string topic) { @@ -68,8 +71,8 @@ private: void NewEvent(zeek::Args* vl); // Raise new_event() meta event. std::string name; - IntrusivePtr local; - IntrusivePtr type; + zeek::FuncPtr local; + zeek::FuncTypePtr type; bool used; // this handler is indeed used somewhere bool enabled; bool error_handler; // this handler reports error messages. diff --git a/src/Expr.cc b/src/Expr.cc index 5d289b92ea..2742232357 100644 --- a/src/Expr.cc +++ b/src/Expr.cc @@ -130,12 +130,12 @@ void Expr::Delete(Frame* /* f */) Internal("Expr::Delete called"); } -IntrusivePtr Expr::MakeLvalue() +ExprPtr Expr::MakeLvalue() { if ( ! IsError() ) ExprError("can't be assigned to"); - return {NewRef{}, this}; + return {zeek::NewRef{}, this}; } void Expr::EvalIntoAggregate(const zeek::Type* /* t */, Val* /* aggr */, @@ -144,12 +144,12 @@ void Expr::EvalIntoAggregate(const zeek::Type* /* t */, Val* /* aggr */, Internal("Expr::EvalIntoAggregate called"); } -void Expr::Assign(Frame* /* f */, IntrusivePtr /* v */) +void Expr::Assign(Frame* /* f */, ValPtr /* v */) { Internal("Expr::Assign called"); } -IntrusivePtr Expr::InitType() const +zeek::TypePtr Expr::InitType() const { return type; } @@ -164,7 +164,7 @@ bool Expr::IsPure() const return true; } -IntrusivePtr Expr::InitVal(const zeek::Type* t, IntrusivePtr aggr) const +ValPtr Expr::InitVal(const zeek::Type* t, ValPtr aggr) const { if ( aggr ) { @@ -230,7 +230,7 @@ void Expr::Canonicize() { } -void Expr::SetType(IntrusivePtr t) +void Expr::SetType(zeek::TypePtr t) { if ( ! type || type->Tag() != zeek::TYPE_ERROR ) type = std::move(t); @@ -263,13 +263,13 @@ void Expr::RuntimeErrorWithCallStack(const std::string& msg) const } } -NameExpr::NameExpr(IntrusivePtr arg_id, bool const_init) +NameExpr::NameExpr(zeek::detail::IDPtr arg_id, bool const_init) : Expr(EXPR_NAME), id(std::move(arg_id)) { in_const_init = const_init; if ( id->IsType() ) - SetType(make_intrusive(id->GetType())); + SetType(zeek::make_intrusive(id->GetType())); else SetType(id->GetType()); @@ -278,12 +278,12 @@ NameExpr::NameExpr(IntrusivePtr arg_id, bool const_init) h->SetUsed(); } -IntrusivePtr NameExpr::Eval(Frame* f) const +ValPtr NameExpr::Eval(Frame* f) const { - IntrusivePtr v; + ValPtr v; if ( id->IsType() ) - return make_intrusive(id->GetType(), true); + return zeek::make_intrusive(id->GetType(), true); if ( id->IsGlobal() ) v = id->GetVal(); @@ -304,7 +304,7 @@ IntrusivePtr NameExpr::Eval(Frame* f) const } } -IntrusivePtr NameExpr::MakeLvalue() +ExprPtr NameExpr::MakeLvalue() { if ( id->IsType() ) ExprError("Type name is not an lvalue"); @@ -315,10 +315,10 @@ IntrusivePtr NameExpr::MakeLvalue() if ( id->IsOption() && ! in_const_init ) ExprError("option is not a modifiable lvalue"); - return make_intrusive(IntrusivePtr{NewRef{}, this}); + return zeek::make_intrusive(IntrusivePtr{zeek::NewRef{}, this}); } -void NameExpr::Assign(Frame* f, IntrusivePtr v) +void NameExpr::Assign(Frame* f, ValPtr v) { if ( id->IsGlobal() ) id->SetVal(std::move(v)); @@ -357,7 +357,7 @@ void NameExpr::ExprDescribe(ODesc* d) const } } -ConstExpr::ConstExpr(IntrusivePtr arg_val) +ConstExpr::ConstExpr(ValPtr arg_val) : Expr(EXPR_CONST), val(std::move(arg_val)) { if ( val->GetType()->Tag() == zeek::TYPE_LIST && val->AsListVal()->Length() == 1 ) @@ -371,9 +371,9 @@ void ConstExpr::ExprDescribe(ODesc* d) const val->Describe(d); } -IntrusivePtr ConstExpr::Eval(Frame* /* f */) const +ValPtr ConstExpr::Eval(Frame* /* f */) const { - return {NewRef{}, Value()}; + return {zeek::NewRef{}, Value()}; } TraversalCode ConstExpr::Traverse(TraversalCallback* cb) const @@ -385,14 +385,14 @@ TraversalCode ConstExpr::Traverse(TraversalCallback* cb) const HANDLE_TC_EXPR_POST(tc); } -UnaryExpr::UnaryExpr(BroExprTag arg_tag, IntrusivePtr arg_op) +UnaryExpr::UnaryExpr(BroExprTag arg_tag, ExprPtr arg_op) : Expr(arg_tag), op(std::move(arg_op)) { if ( op->IsError() ) SetError(); } -IntrusivePtr UnaryExpr::Eval(Frame* f) const +ValPtr UnaryExpr::Eval(Frame* f) const { if ( IsError() ) return nullptr; @@ -405,14 +405,14 @@ IntrusivePtr UnaryExpr::Eval(Frame* f) const if ( is_vector(v) && Tag() != EXPR_IS && Tag() != EXPR_CAST ) { VectorVal* v_op = v->AsVectorVal(); - IntrusivePtr out_t; + zeek::VectorTypePtr out_t; if ( GetType()->Tag() == zeek::TYPE_ANY ) out_t = v->GetType(); else out_t = GetType(); - auto result = make_intrusive(std::move(out_t)); + auto result = zeek::make_intrusive(std::move(out_t)); for ( unsigned int i = 0; i < v_op->Size(); ++i ) { @@ -445,9 +445,9 @@ TraversalCode UnaryExpr::Traverse(TraversalCallback* cb) const HANDLE_TC_EXPR_POST(tc); } -IntrusivePtr UnaryExpr::Fold(Val* v) const +ValPtr UnaryExpr::Fold(Val* v) const { - return {NewRef{}, v}; + return {zeek::NewRef{}, v}; } void UnaryExpr::ExprDescribe(ODesc* d) const @@ -474,7 +474,7 @@ void UnaryExpr::ExprDescribe(ODesc* d) const } } -IntrusivePtr BinaryExpr::Eval(Frame* f) const +ValPtr BinaryExpr::Eval(Frame* f) const { if ( IsError() ) return nullptr; @@ -503,7 +503,7 @@ IntrusivePtr BinaryExpr::Eval(Frame* f) const return nullptr; } - auto v_result = make_intrusive(GetType()); + auto v_result = zeek::make_intrusive(GetType()); for ( unsigned int i = 0; i < v_op1->Size(); ++i ) { @@ -520,7 +520,7 @@ IntrusivePtr BinaryExpr::Eval(Frame* f) const if ( IsVector(GetType()->Tag()) && (is_vec1 || is_vec2) ) { // fold vector against scalar VectorVal* vv = (is_vec1 ? v1 : v2)->AsVectorVal(); - auto v_result = make_intrusive(GetType()); + auto v_result = zeek::make_intrusive(GetType()); for ( unsigned int i = 0; i < vv->Size(); ++i ) { @@ -571,7 +571,7 @@ void BinaryExpr::ExprDescribe(ODesc* d) const op2->Describe(d); } -IntrusivePtr BinaryExpr::Fold(Val* v1, Val* v2) const +ValPtr BinaryExpr::Fold(Val* v1, Val* v2) const { InternalTypeTag it = v1->GetType()->InternalType(); @@ -725,23 +725,23 @@ IntrusivePtr BinaryExpr::Fold(Val* v1, Val* v2) const const auto& ret_type = IsVector(GetType()->Tag()) ? GetType()->Yield() : GetType(); if ( ret_type->Tag() == zeek::TYPE_INTERVAL ) - return make_intrusive(d3); + return zeek::make_intrusive(d3); else if ( ret_type->Tag() == zeek::TYPE_TIME ) - return make_intrusive(d3); + return zeek::make_intrusive(d3); else if ( ret_type->Tag() == zeek::TYPE_DOUBLE ) - return make_intrusive(d3); + return zeek::make_intrusive(d3); else if ( ret_type->InternalType() == zeek::TYPE_INTERNAL_UNSIGNED ) - return val_mgr->Count(u3); + return zeek::val_mgr->Count(u3); else if ( ret_type->Tag() == zeek::TYPE_BOOL ) - return val_mgr->Bool(i3); + return zeek::val_mgr->Bool(i3); else - return val_mgr->Int(i3); + return zeek::val_mgr->Int(i3); } -IntrusivePtr BinaryExpr::StringFold(Val* v1, Val* v2) const +ValPtr BinaryExpr::StringFold(Val* v1, Val* v2) const { - const BroString* s1 = v1->AsString(); - const BroString* s2 = v2->AsString(); + const String* s1 = v1->AsString(); + const String* s2 = v2->AsString(); int result = 0; switch ( tag ) { @@ -758,22 +758,22 @@ IntrusivePtr BinaryExpr::StringFold(Val* v1, Val* v2) const case EXPR_ADD: case EXPR_ADD_TO: { - std::vector strings; + std::vector strings; strings.push_back(s1); strings.push_back(s2); - return make_intrusive(concatenate(strings)); + return zeek::make_intrusive(concatenate(strings)); } default: BadTag("BinaryExpr::StringFold", expr_name(tag)); } - return val_mgr->Bool(result); + return zeek::val_mgr->Bool(result); } -IntrusivePtr BinaryExpr::PatternFold(Val* v1, Val* v2) const +ValPtr BinaryExpr::PatternFold(Val* v1, Val* v2) const { const RE_Matcher* re1 = v1->AsPattern(); const RE_Matcher* re2 = v2->AsPattern(); @@ -785,10 +785,10 @@ IntrusivePtr BinaryExpr::PatternFold(Val* v1, Val* v2) const RE_Matcher_conjunction(re1, re2) : RE_Matcher_disjunction(re1, re2); - return make_intrusive(res); + return zeek::make_intrusive(res); } -IntrusivePtr BinaryExpr::SetFold(Val* v1, Val* v2) const +ValPtr BinaryExpr::SetFold(Val* v1, Val* v2) const { TableVal* tv1 = v1->AsTableVal(); TableVal* tv2 = v2->AsTableVal(); @@ -845,10 +845,10 @@ IntrusivePtr BinaryExpr::SetFold(Val* v1, Val* v2) const return nullptr; } - return val_mgr->Bool(res); + return zeek::val_mgr->Bool(res); } -IntrusivePtr BinaryExpr::AddrFold(Val* v1, Val* v2) const +ValPtr BinaryExpr::AddrFold(Val* v1, Val* v2) const { IPAddr a1 = v1->AsAddr(); IPAddr a2 = v2->AsAddr(); @@ -879,10 +879,10 @@ IntrusivePtr BinaryExpr::AddrFold(Val* v1, Val* v2) const BadTag("BinaryExpr::AddrFold", expr_name(tag)); } - return val_mgr->Bool(result); + return zeek::val_mgr->Bool(result); } -IntrusivePtr BinaryExpr::SubNetFold(Val* v1, Val* v2) const +ValPtr BinaryExpr::SubNetFold(Val* v1, Val* v2) const { const IPPrefix& n1 = v1->AsSubNet(); const IPPrefix& n2 = v2->AsSubNet(); @@ -892,7 +892,7 @@ IntrusivePtr BinaryExpr::SubNetFold(Val* v1, Val* v2) const if ( tag == EXPR_NE ) result = ! result; - return val_mgr->Bool(result); + return zeek::val_mgr->Bool(result); } void BinaryExpr::SwapOps() @@ -919,9 +919,9 @@ void BinaryExpr::PromoteOps(TypeTag t) reporter->Warning("mixing vector and scalar operands is deprecated"); if ( bt1 != t ) - op1 = make_intrusive(op1, t); + op1 = zeek::make_intrusive(op1, t); if ( bt2 != t ) - op2 = make_intrusive(op2, t); + op2 = zeek::make_intrusive(op2, t); } void BinaryExpr::PromoteType(TypeTag t, bool is_vector) @@ -929,12 +929,12 @@ void BinaryExpr::PromoteType(TypeTag t, bool is_vector) PromoteOps(t); if ( is_vector) - SetType(make_intrusive(base_type(t))); + SetType(zeek::make_intrusive(base_type(t))); else SetType(base_type(t)); } -CloneExpr::CloneExpr(IntrusivePtr arg_op) +CloneExpr::CloneExpr(ExprPtr arg_op) : UnaryExpr(EXPR_CLONE, std::move(arg_op)) { if ( IsError() ) @@ -943,7 +943,7 @@ CloneExpr::CloneExpr(IntrusivePtr arg_op) SetType(op->GetType()); } -IntrusivePtr CloneExpr::Eval(Frame* f) const +ValPtr CloneExpr::Eval(Frame* f) const { if ( IsError() ) return nullptr; @@ -954,12 +954,12 @@ IntrusivePtr CloneExpr::Eval(Frame* f) const return nullptr; } -IntrusivePtr CloneExpr::Fold(Val* v) const +ValPtr CloneExpr::Fold(Val* v) const { return v->Clone(); } -IncrExpr::IncrExpr(BroExprTag arg_tag, IntrusivePtr arg_op) +IncrExpr::IncrExpr(BroExprTag arg_tag, ExprPtr arg_op) : UnaryExpr(arg_tag, arg_op->MakeLvalue()) { if ( IsError() ) @@ -986,7 +986,7 @@ IncrExpr::IncrExpr(BroExprTag arg_tag, IntrusivePtr arg_op) } } -IntrusivePtr IncrExpr::DoSingleEval(Frame* f, Val* v) const +ValPtr IncrExpr::DoSingleEval(Frame* f, Val* v) const { bro_int_t k = v->CoerceToInt(); @@ -1004,13 +1004,13 @@ IntrusivePtr IncrExpr::DoSingleEval(Frame* f, Val* v) const const auto& ret_type = IsVector(GetType()->Tag()) ? GetType()->Yield() : GetType(); if ( ret_type->Tag() == zeek::TYPE_INT ) - return val_mgr->Int(k); + return zeek::val_mgr->Int(k); else - return val_mgr->Count(k); + return zeek::val_mgr->Count(k); } -IntrusivePtr IncrExpr::Eval(Frame* f) const +ValPtr IncrExpr::Eval(Frame* f) const { auto v = op->Eval(f); @@ -1019,7 +1019,7 @@ IntrusivePtr IncrExpr::Eval(Frame* f) const if ( is_vector(v) ) { - IntrusivePtr v_vec{NewRef{}, v->AsVectorVal()}; + VectorValPtr v_vec{zeek::NewRef{}, v->AsVectorVal()}; for ( unsigned int i = 0; i < v_vec->Size(); ++i ) { @@ -1047,7 +1047,7 @@ bool IncrExpr::IsPure() const return false; } -ComplementExpr::ComplementExpr(IntrusivePtr arg_op) +ComplementExpr::ComplementExpr(ExprPtr arg_op) : UnaryExpr(EXPR_COMPLEMENT, std::move(arg_op)) { if ( IsError() ) @@ -1062,12 +1062,12 @@ ComplementExpr::ComplementExpr(IntrusivePtr arg_op) SetType(base_type(zeek::TYPE_COUNT)); } -IntrusivePtr ComplementExpr::Fold(Val* v) const +ValPtr ComplementExpr::Fold(Val* v) const { - return val_mgr->Count(~ v->InternalUnsigned()); + return zeek::val_mgr->Count(~ v->InternalUnsigned()); } -NotExpr::NotExpr(IntrusivePtr arg_op) +NotExpr::NotExpr(ExprPtr arg_op) : UnaryExpr(EXPR_NOT, std::move(arg_op)) { if ( IsError() ) @@ -1081,12 +1081,12 @@ NotExpr::NotExpr(IntrusivePtr arg_op) SetType(base_type(zeek::TYPE_BOOL)); } -IntrusivePtr NotExpr::Fold(Val* v) const +ValPtr NotExpr::Fold(Val* v) const { - return val_mgr->Bool(! v->InternalInt()); + return zeek::val_mgr->Bool(! v->InternalInt()); } -PosExpr::PosExpr(IntrusivePtr arg_op) +PosExpr::PosExpr(ExprPtr arg_op) : UnaryExpr(EXPR_POSITIVE, std::move(arg_op)) { if ( IsError() ) @@ -1095,7 +1095,7 @@ PosExpr::PosExpr(IntrusivePtr arg_op) const auto& t = IsVector(op->GetType()->Tag()) ? op->GetType()->Yield() : op->GetType(); TypeTag bt = t->Tag(); - IntrusivePtr base_result_type; + zeek::TypePtr base_result_type; if ( IsIntegral(bt) ) // Promote count and counter to int. @@ -1106,22 +1106,22 @@ PosExpr::PosExpr(IntrusivePtr arg_op) ExprError("requires an integral or double operand"); if ( is_vector(op) ) - SetType(make_intrusive(std::move(base_result_type))); + SetType(zeek::make_intrusive(std::move(base_result_type))); else SetType(std::move(base_result_type)); } -IntrusivePtr PosExpr::Fold(Val* v) const +ValPtr PosExpr::Fold(Val* v) const { TypeTag t = v->GetType()->Tag(); if ( t == zeek::TYPE_DOUBLE || t == zeek::TYPE_INTERVAL || t == zeek::TYPE_INT ) - return {NewRef{}, v}; + return {zeek::NewRef{}, v}; else - return val_mgr->Int(v->CoerceToInt()); + return zeek::val_mgr->Int(v->CoerceToInt()); } -NegExpr::NegExpr(IntrusivePtr arg_op) +NegExpr::NegExpr(ExprPtr arg_op) : UnaryExpr(EXPR_NEGATE, std::move(arg_op)) { if ( IsError() ) @@ -1130,7 +1130,7 @@ NegExpr::NegExpr(IntrusivePtr arg_op) const auto& t = IsVector(op->GetType()->Tag()) ? op->GetType()->Yield() : op->GetType(); TypeTag bt = t->Tag(); - IntrusivePtr base_result_type; + zeek::TypePtr base_result_type; if ( IsIntegral(bt) ) // Promote count and counter to int. @@ -1141,22 +1141,22 @@ NegExpr::NegExpr(IntrusivePtr arg_op) ExprError("requires an integral or double operand"); if ( is_vector(op) ) - SetType(make_intrusive(std::move(base_result_type))); + SetType(zeek::make_intrusive(std::move(base_result_type))); else SetType(std::move(base_result_type)); } -IntrusivePtr NegExpr::Fold(Val* v) const +ValPtr NegExpr::Fold(Val* v) const { if ( v->GetType()->Tag() == zeek::TYPE_DOUBLE ) - return make_intrusive(- v->InternalDouble()); + return zeek::make_intrusive(- v->InternalDouble()); else if ( v->GetType()->Tag() == zeek::TYPE_INTERVAL ) - return make_intrusive(- v->InternalDouble()); + return zeek::make_intrusive(- v->InternalDouble()); else - return val_mgr->Int(- v->CoerceToInt()); + return zeek::val_mgr->Int(- v->CoerceToInt()); } -SizeExpr::SizeExpr(IntrusivePtr arg_op) +SizeExpr::SizeExpr(ExprPtr arg_op) : UnaryExpr(EXPR_SIZE, std::move(arg_op)) { if ( IsError() ) @@ -1168,7 +1168,7 @@ SizeExpr::SizeExpr(IntrusivePtr arg_op) SetType(base_type(zeek::TYPE_COUNT)); } -IntrusivePtr SizeExpr::Eval(Frame* f) const +ValPtr SizeExpr::Eval(Frame* f) const { auto v = op->Eval(f); @@ -1178,12 +1178,12 @@ IntrusivePtr SizeExpr::Eval(Frame* f) const return Fold(v.get()); } -IntrusivePtr SizeExpr::Fold(Val* v) const +ValPtr SizeExpr::Fold(Val* v) const { return v->SizeVal(); } -AddExpr::AddExpr(IntrusivePtr arg_op1, IntrusivePtr arg_op2) +AddExpr::AddExpr(ExprPtr arg_op1, ExprPtr arg_op2) : BinaryExpr(EXPR_ADD, std::move(arg_op1), std::move(arg_op2)) { if ( IsError() ) @@ -1199,7 +1199,7 @@ AddExpr::AddExpr(IntrusivePtr arg_op1, IntrusivePtr arg_op2) if ( IsVector(bt2) ) bt2 = op2->GetType()->AsVectorType()->Yield()->Tag(); - IntrusivePtr base_result_type; + zeek::TypePtr base_result_type; if ( bt2 == zeek::TYPE_INTERVAL && ( bt1 == zeek::TYPE_TIME || bt1 == zeek::TYPE_INTERVAL ) ) base_result_type = base_type(bt1); @@ -1215,7 +1215,7 @@ AddExpr::AddExpr(IntrusivePtr arg_op1, IntrusivePtr arg_op2) if ( base_result_type ) { if ( is_vector(op1) || is_vector(op2) ) - SetType(make_intrusive(std::move(base_result_type))); + SetType(zeek::make_intrusive(std::move(base_result_type))); else SetType(std::move(base_result_type)); } @@ -1230,7 +1230,7 @@ void AddExpr::Canonicize() SwapOps(); } -AddToExpr::AddToExpr(IntrusivePtr arg_op1, IntrusivePtr arg_op2) +AddToExpr::AddToExpr(ExprPtr arg_op1, ExprPtr arg_op2) : BinaryExpr(EXPR_ADD_TO, is_vector(arg_op1) ? std::move(arg_op1) : arg_op1->MakeLvalue(), std::move(arg_op2)) @@ -1255,7 +1255,7 @@ AddToExpr::AddToExpr(IntrusivePtr arg_op1, IntrusivePtr arg_op2) if ( IsArithmetic(bt2) ) { if ( bt2 != bt1 ) - op2 = make_intrusive(std::move(op2), bt1); + op2 = zeek::make_intrusive(std::move(op2), bt1); SetType(op1->GetType()); } @@ -1276,7 +1276,7 @@ AddToExpr::AddToExpr(IntrusivePtr arg_op1, IntrusivePtr arg_op2) ExprError("requires two arithmetic or two string operands"); } -IntrusivePtr AddToExpr::Eval(Frame* f) const +ValPtr AddToExpr::Eval(Frame* f) const { auto v1 = op1->Eval(f); @@ -1307,7 +1307,7 @@ IntrusivePtr AddToExpr::Eval(Frame* f) const return nullptr; } -SubExpr::SubExpr(IntrusivePtr arg_op1, IntrusivePtr arg_op2) +SubExpr::SubExpr(ExprPtr arg_op1, ExprPtr arg_op2) : BinaryExpr(EXPR_SUB, std::move(arg_op1), std::move(arg_op2)) { if ( IsError() ) @@ -1324,7 +1324,7 @@ SubExpr::SubExpr(IntrusivePtr arg_op1, IntrusivePtr arg_op2) if ( IsVector(bt2) ) bt2 = t2->AsVectorType()->Yield()->Tag(); - IntrusivePtr base_result_type; + zeek::TypePtr base_result_type; if ( bt2 == zeek::TYPE_INTERVAL && ( bt1 == zeek::TYPE_TIME || bt1 == zeek::TYPE_INTERVAL ) ) base_result_type = base_type(bt1); @@ -1349,14 +1349,13 @@ SubExpr::SubExpr(IntrusivePtr arg_op1, IntrusivePtr arg_op2) if ( base_result_type ) { if ( is_vector(op1) || is_vector(op2) ) - SetType(make_intrusive(std::move(base_result_type))); + SetType(zeek::make_intrusive(std::move(base_result_type))); else SetType(std::move(base_result_type)); } } -RemoveFromExpr::RemoveFromExpr(IntrusivePtr arg_op1, - IntrusivePtr arg_op2) +RemoveFromExpr::RemoveFromExpr(ExprPtr arg_op1, ExprPtr arg_op2) : BinaryExpr(EXPR_REMOVE_FROM, arg_op1->MakeLvalue(), std::move(arg_op2)) { if ( IsError() ) @@ -1373,7 +1372,7 @@ RemoveFromExpr::RemoveFromExpr(IntrusivePtr arg_op1, ExprError("requires two arithmetic operands"); } -IntrusivePtr RemoveFromExpr::Eval(Frame* f) const +ValPtr RemoveFromExpr::Eval(Frame* f) const { auto v1 = op1->Eval(f); @@ -1394,7 +1393,7 @@ IntrusivePtr RemoveFromExpr::Eval(Frame* f) const return nullptr; } -TimesExpr::TimesExpr(IntrusivePtr arg_op1, IntrusivePtr arg_op2) +TimesExpr::TimesExpr(ExprPtr arg_op1, ExprPtr arg_op2) : BinaryExpr(EXPR_TIMES, std::move(arg_op1), std::move(arg_op2)) { if ( IsError() ) @@ -1432,8 +1431,7 @@ void TimesExpr::Canonicize() SwapOps(); } -DivideExpr::DivideExpr(IntrusivePtr arg_op1, - IntrusivePtr arg_op2) +DivideExpr::DivideExpr(ExprPtr arg_op1, ExprPtr arg_op2) : BinaryExpr(EXPR_DIVIDE, std::move(arg_op1), std::move(arg_op2)) { if ( IsError() ) @@ -1456,7 +1454,7 @@ DivideExpr::DivideExpr(IntrusivePtr arg_op1, else if ( bt1 == zeek::TYPE_INTERVAL && bt2 == zeek::TYPE_INTERVAL ) { if ( is_vector(op1) || is_vector(op2) ) - SetType(make_intrusive(base_type(zeek::TYPE_DOUBLE))); + SetType(zeek::make_intrusive(base_type(zeek::TYPE_DOUBLE))); else SetType(base_type(zeek::TYPE_DOUBLE)); } @@ -1475,7 +1473,7 @@ DivideExpr::DivideExpr(IntrusivePtr arg_op1, ExprError("requires arithmetic operands"); } -IntrusivePtr DivideExpr::AddrFold(Val* v1, Val* v2) const +ValPtr DivideExpr::AddrFold(Val* v1, Val* v2) const { uint32_t mask; @@ -1497,10 +1495,10 @@ IntrusivePtr DivideExpr::AddrFold(Val* v1, Val* v2) const RuntimeError(fmt("bad IPv6 subnet prefix length: %" PRIu32, mask)); } - return make_intrusive(a, mask); + return zeek::make_intrusive(a, mask); } -ModExpr::ModExpr(IntrusivePtr arg_op1, IntrusivePtr arg_op2) +ModExpr::ModExpr(ExprPtr arg_op1, ExprPtr arg_op2) : BinaryExpr(EXPR_MOD, std::move(arg_op1), std::move(arg_op2)) { if ( IsError() ) @@ -1522,8 +1520,7 @@ ModExpr::ModExpr(IntrusivePtr arg_op1, IntrusivePtr arg_op2) ExprError("requires integral operands"); } -BoolExpr::BoolExpr(BroExprTag arg_tag, - IntrusivePtr arg_op1, IntrusivePtr arg_op2) +BoolExpr::BoolExpr(BroExprTag arg_tag, ExprPtr arg_op1, ExprPtr arg_op2) : BinaryExpr(arg_tag, std::move(arg_op1), std::move(arg_op2)) { if ( IsError() ) @@ -1545,7 +1542,7 @@ BoolExpr::BoolExpr(BroExprTag arg_tag, { if ( ! (is_vector(op1) && is_vector(op2)) ) reporter->Warning("mixing vector and scalar operands is deprecated"); - SetType(make_intrusive(base_type(zeek::TYPE_BOOL))); + SetType(zeek::make_intrusive(base_type(zeek::TYPE_BOOL))); } else SetType(base_type(zeek::TYPE_BOOL)); @@ -1554,7 +1551,7 @@ BoolExpr::BoolExpr(BroExprTag arg_tag, ExprError("requires boolean operands"); } -IntrusivePtr BoolExpr::DoSingleEval(Frame* f, IntrusivePtr v1, Expr* op2) const +ValPtr BoolExpr::DoSingleEval(Frame* f, ValPtr v1, Expr* op2) const { if ( ! v1 ) return nullptr; @@ -1576,7 +1573,7 @@ IntrusivePtr BoolExpr::DoSingleEval(Frame* f, IntrusivePtr v1, Expr* o } } -IntrusivePtr BoolExpr::Eval(Frame* f) const +ValPtr BoolExpr::Eval(Frame* f) const { if ( IsError() ) return nullptr; @@ -1598,31 +1595,31 @@ IntrusivePtr BoolExpr::Eval(Frame* f) const // a vector in order to find out its length. if ( ! (is_vec1 && is_vec2) ) { // Only one is a vector. - IntrusivePtr scalar_v; - IntrusivePtr vector_v; + ValPtr scalar_v; + VectorValPtr vector_v; if ( is_vec1 ) { scalar_v = op2->Eval(f); - vector_v = {AdoptRef{}, v1.release()->AsVectorVal()}; + vector_v = {zeek::AdoptRef{}, v1.release()->AsVectorVal()}; } else { scalar_v = std::move(v1); - vector_v = {AdoptRef{}, op2->Eval(f).release()->AsVectorVal()}; + vector_v = {zeek::AdoptRef{}, op2->Eval(f).release()->AsVectorVal()}; } if ( ! scalar_v || ! vector_v ) return nullptr; - IntrusivePtr result; + VectorValPtr result; // It's either an EXPR_AND_AND or an EXPR_OR_OR. bool is_and = (tag == EXPR_AND_AND); if ( scalar_v->IsZero() == is_and ) { - result = make_intrusive(GetType()); + result = zeek::make_intrusive(GetType()); result->Resize(vector_v->Size()); result->AssignRepeat(0, result->Size(), std::move(scalar_v)); } @@ -1647,7 +1644,7 @@ IntrusivePtr BoolExpr::Eval(Frame* f) const return nullptr; } - auto result = make_intrusive(GetType()); + auto result = zeek::make_intrusive(GetType()); result->Resize(vec_v1->Size()); for ( unsigned int i = 0; i < vec_v1->Size(); ++i ) @@ -1660,7 +1657,7 @@ IntrusivePtr BoolExpr::Eval(Frame* f) const (! op1->IsZero() && ! op2->IsZero()) : (! op1->IsZero() || ! op2->IsZero()); - result->Assign(i, val_mgr->Bool(local_result)); + result->Assign(i, zeek::val_mgr->Bool(local_result)); } else result->Assign(i, nullptr); @@ -1669,8 +1666,7 @@ IntrusivePtr BoolExpr::Eval(Frame* f) const return result; } -BitExpr::BitExpr(BroExprTag arg_tag, - IntrusivePtr arg_op1, IntrusivePtr arg_op2) +BitExpr::BitExpr(BroExprTag arg_tag, ExprPtr arg_op1, ExprPtr arg_op2) : BinaryExpr(arg_tag, std::move(arg_op1), std::move(arg_op2)) { if ( IsError() ) @@ -1695,7 +1691,7 @@ BitExpr::BitExpr(BroExprTag arg_tag, if ( bt1 == zeek::TYPE_COUNTER && bt2 == zeek::TYPE_COUNTER ) ExprError("cannot apply a bitwise operator to two \"counter\" operands"); else if ( is_vector(op1) || is_vector(op2) ) - SetType(make_intrusive(base_type(zeek::TYPE_COUNT))); + SetType(zeek::make_intrusive(base_type(zeek::TYPE_COUNT))); else SetType(base_type(zeek::TYPE_COUNT)); } @@ -1722,8 +1718,7 @@ BitExpr::BitExpr(BroExprTag arg_tag, ExprError("requires \"count\" or compatible \"set\" operands"); } -EqExpr::EqExpr(BroExprTag arg_tag, - IntrusivePtr arg_op1, IntrusivePtr arg_op2) +EqExpr::EqExpr(BroExprTag arg_tag, ExprPtr arg_op1, ExprPtr arg_op2) : BinaryExpr(arg_tag, std::move(arg_op1), std::move(arg_op2)) { if ( IsError() ) @@ -1743,7 +1738,7 @@ EqExpr::EqExpr(BroExprTag arg_tag, bt2 = t2->AsVectorType()->Yield()->Tag(); if ( is_vector(op1) || is_vector(op2) ) - SetType(make_intrusive(base_type(zeek::TYPE_BOOL))); + SetType(zeek::make_intrusive(base_type(zeek::TYPE_BOOL))); else SetType(base_type(zeek::TYPE_BOOL)); @@ -1808,24 +1803,23 @@ void EqExpr::Canonicize() SwapOps(); } -IntrusivePtr EqExpr::Fold(Val* v1, Val* v2) const +ValPtr EqExpr::Fold(Val* v1, Val* v2) const { if ( op1->GetType()->Tag() == zeek::TYPE_PATTERN ) { RE_Matcher* re = v1->AsPattern(); - const BroString* s = v2->AsString(); + const String* s = v2->AsString(); if ( tag == EXPR_EQ ) - return val_mgr->Bool(re->MatchExactly(s)); + return zeek::val_mgr->Bool(re->MatchExactly(s)); else - return val_mgr->Bool(! re->MatchExactly(s)); + return zeek::val_mgr->Bool(! re->MatchExactly(s)); } else return BinaryExpr::Fold(v1, v2); } -RelExpr::RelExpr(BroExprTag arg_tag, - IntrusivePtr arg_op1, IntrusivePtr arg_op2) +RelExpr::RelExpr(BroExprTag arg_tag, ExprPtr arg_op1, ExprPtr arg_op2) : BinaryExpr(arg_tag, std::move(arg_op1), std::move(arg_op2)) { if ( IsError() ) @@ -1845,7 +1839,7 @@ RelExpr::RelExpr(BroExprTag arg_tag, bt2 = t2->AsVectorType()->Yield()->Tag(); if ( is_vector(op1) || is_vector(op2) ) - SetType(make_intrusive(base_type(zeek::TYPE_BOOL))); + SetType(zeek::make_intrusive(base_type(zeek::TYPE_BOOL))); else SetType(base_type(zeek::TYPE_BOOL)); @@ -1882,8 +1876,7 @@ void RelExpr::Canonicize() } } -CondExpr::CondExpr(IntrusivePtr arg_op1, IntrusivePtr arg_op2, - IntrusivePtr arg_op3) +CondExpr::CondExpr(ExprPtr arg_op1, ExprPtr arg_op2, ExprPtr arg_op3) : Expr(EXPR_COND), op1(std::move(arg_op1)), op2(std::move(arg_op2)), op3(std::move(arg_op3)) { @@ -1920,12 +1913,12 @@ CondExpr::CondExpr(IntrusivePtr arg_op1, IntrusivePtr arg_op2, { TypeTag t = max_type(bt2, bt3); if ( bt2 != t ) - op2 = make_intrusive(std::move(op2), t); + op2 = zeek::make_intrusive(std::move(op2), t); if ( bt3 != t ) - op3 = make_intrusive(std::move(op3), t); + op3 = zeek::make_intrusive(std::move(op3), t); if ( is_vector(op2) ) - SetType(make_intrusive(base_type(t))); + SetType(zeek::make_intrusive(base_type(t))); else SetType(base_type(t)); } @@ -1944,7 +1937,7 @@ CondExpr::CondExpr(IntrusivePtr arg_op1, IntrusivePtr arg_op2, } } -IntrusivePtr CondExpr::Eval(Frame* f) const +ValPtr CondExpr::Eval(Frame* f) const { if ( ! is_vector(op1) ) { @@ -1979,7 +1972,7 @@ IntrusivePtr CondExpr::Eval(Frame* f) const return nullptr; } - auto result = make_intrusive(GetType()); + auto result = zeek::make_intrusive(GetType()); result->Resize(cond->Size()); for ( unsigned int i = 0; i < cond->Size(); ++i ) @@ -2030,7 +2023,7 @@ void CondExpr::ExprDescribe(ODesc* d) const op3->Describe(d); } -RefExpr::RefExpr(IntrusivePtr arg_op) +RefExpr::RefExpr(ExprPtr arg_op) : UnaryExpr(EXPR_REF, std::move(arg_op)) { if ( IsError() ) @@ -2042,19 +2035,20 @@ RefExpr::RefExpr(IntrusivePtr arg_op) SetType(op->GetType()); } -IntrusivePtr RefExpr::MakeLvalue() +ExprPtr RefExpr::MakeLvalue() { - return {NewRef{}, this}; + return {zeek::NewRef{}, this}; } -void RefExpr::Assign(Frame* f, IntrusivePtr v) +void RefExpr::Assign(Frame* f, ValPtr v) { op->Assign(f, std::move(v)); } -AssignExpr::AssignExpr(IntrusivePtr arg_op1, IntrusivePtr arg_op2, - bool arg_is_init, IntrusivePtr arg_val, - const IntrusivePtr& attrs) +AssignExpr::AssignExpr(ExprPtr arg_op1, + ExprPtr arg_op2, + bool arg_is_init, ValPtr arg_val, + const AttributesPtr& attrs) : BinaryExpr(EXPR_ASSIGN, arg_is_init ? std::move(arg_op1) : arg_op1->MakeLvalue(), std::move(arg_op2)) @@ -2086,7 +2080,7 @@ AssignExpr::AssignExpr(IntrusivePtr arg_op1, IntrusivePtr arg_op2, SetLocationInfo(op1->GetLocationInfo(), op2->GetLocationInfo()); } -bool AssignExpr::TypeCheck(const IntrusivePtr& attrs) +bool AssignExpr::TypeCheck(const AttributesPtr& attrs) { TypeTag bt1 = op1->GetType()->Tag(); TypeTag bt2 = op2->GetType()->Tag(); @@ -2108,32 +2102,32 @@ bool AssignExpr::TypeCheck(const IntrusivePtr& attrs) if ( bt1 == zeek::TYPE_TIME && IsArithmetic(bt2) && op2->IsZero() ) { // Allow assignments to zero as a special case. - op2 = make_intrusive(std::move(op2), bt1); + op2 = zeek::make_intrusive(std::move(op2), bt1); return true; } if ( bt1 == zeek::TYPE_TABLE && bt2 == bt1 && op2->GetType()->AsTableType()->IsUnspecifiedTable() ) { - op2 = make_intrusive(std::move(op2), op1->GetType()); + op2 = zeek::make_intrusive(std::move(op2), op1->GetType()); return true; } if ( bt1 == zeek::TYPE_TABLE && op2->Tag() == EXPR_LIST ) { - std::unique_ptr>> attr_copy; + std::unique_ptr> attr_copy; if ( attrs ) - attr_copy = std::make_unique>>(attrs->GetAttrs()); + attr_copy = std::make_unique>(attrs->GetAttrs()); bool empty_list_assignment = (op2->AsListExpr()->Exprs().empty()); if ( op1->GetType()->IsSet() ) - op2 = make_intrusive( - cast_intrusive(op2), std::move(attr_copy)); + op2 = zeek::make_intrusive( + zeek::cast_intrusive(op2), std::move(attr_copy)); else - op2 = make_intrusive( - cast_intrusive(op2), std::move(attr_copy)); + op2 = zeek::make_intrusive( + zeek::cast_intrusive(op2), std::move(attr_copy)); if ( ! empty_list_assignment && ! same_type(op1->GetType(), op2->GetType()) ) { @@ -2152,15 +2146,15 @@ bool AssignExpr::TypeCheck(const IntrusivePtr& attrs) { if ( bt2 == bt1 && op2->GetType()->AsVectorType()->IsUnspecifiedVector() ) { - op2 = make_intrusive(std::move(op2), op1->GetType()); + op2 = zeek::make_intrusive(std::move(op2), op1->GetType()); return true; } if ( op2->Tag() == EXPR_LIST ) { - op2 = make_intrusive( - IntrusivePtr{AdoptRef{}, op2.release()->AsListExpr()}, - op1->GetType()); + op2 = zeek::make_intrusive( + IntrusivePtr{zeek::AdoptRef{}, op2.release()->AsListExpr()}, + op1->GetType()); return true; } } @@ -2186,7 +2180,7 @@ bool AssignExpr::TypeCheck(const IntrusivePtr& attrs) } // Need to coerce. - op2 = make_intrusive(std::move(op2), op1->GetType()); + op2 = zeek::make_intrusive(std::move(op2), op1->GetType()); return true; } @@ -2215,20 +2209,20 @@ bool AssignExpr::TypeCheck(const IntrusivePtr& attrs) return false; } - std::unique_ptr>> attr_copy; + std::unique_ptr> attr_copy; if ( sce->GetAttrs() ) { const auto& a = sce->GetAttrs()->GetAttrs(); - attr_copy = std::make_unique>>(a); + attr_copy = std::make_unique>(a); } int errors_before = reporter->Errors(); - op2 = make_intrusive( - IntrusivePtr{NewRef{}, ctor_list}, - std::move(attr_copy), - op1->GetType()); + op2 = zeek::make_intrusive( + IntrusivePtr{zeek::NewRef{}, ctor_list}, + std::move(attr_copy), + op1->GetType()); int errors_after = reporter->Errors(); if ( errors_after > errors_before ) @@ -2266,7 +2260,7 @@ bool AssignExpr::TypeCheckArithmetics(TypeTag bt1, TypeTag bt2) if ( bt2 == zeek::TYPE_DOUBLE ) { Warn("dangerous assignment of double to integral"); - op2 = make_intrusive(std::move(op2), bt1); + op2 = zeek::make_intrusive(std::move(op2), bt1); bt2 = op2->GetType()->Tag(); } @@ -2277,7 +2271,7 @@ bool AssignExpr::TypeCheckArithmetics(TypeTag bt1, TypeTag bt2) if ( bt2 == zeek::TYPE_INT ) { Warn("dangerous assignment of integer to count"); - op2 = make_intrusive(std::move(op2), bt1); + op2 = zeek::make_intrusive(std::move(op2), bt1); } // Assignment of count to counter or vice @@ -2289,7 +2283,7 @@ bool AssignExpr::TypeCheckArithmetics(TypeTag bt1, TypeTag bt2) } -IntrusivePtr AssignExpr::Eval(Frame* f) const +ValPtr AssignExpr::Eval(Frame* f) const { if ( is_init ) { @@ -2310,7 +2304,7 @@ IntrusivePtr AssignExpr::Eval(Frame* f) const return nullptr; } -IntrusivePtr AssignExpr::InitType() const +zeek::TypePtr AssignExpr::InitType() const { if ( op1->Tag() != EXPR_LIST ) { @@ -2322,8 +2316,9 @@ IntrusivePtr AssignExpr::InitType() const if ( tl->Tag() != zeek::TYPE_LIST ) Internal("inconsistent list expr in AssignExpr::InitType"); - return make_intrusive(IntrusivePtr{NewRef{}, tl->AsTypeList()}, - op2->GetType()); + return zeek::make_intrusive( + IntrusivePtr{zeek::NewRef{}, tl->AsTypeList()}, + op2->GetType()); } void AssignExpr::EvalIntoAggregate(const zeek::Type* t, Val* aggr, Frame* f) const @@ -2375,7 +2370,7 @@ void AssignExpr::EvalIntoAggregate(const zeek::Type* t, Val* aggr, Frame* f) con RuntimeError("type clash in table assignment"); } -IntrusivePtr AssignExpr::InitVal(const zeek::Type* t, IntrusivePtr aggr) const +ValPtr AssignExpr::InitVal(const zeek::Type* t, ValPtr aggr) const { if ( ! aggr ) { @@ -2430,7 +2425,7 @@ IntrusivePtr AssignExpr::InitVal(const zeek::Type* t, IntrusivePtr agg if ( aggr->GetType()->Tag() != zeek::TYPE_TABLE ) Internal("bad aggregate in AssignExpr::InitVal"); - auto tv = cast_intrusive(std::move(aggr)); + auto tv = zeek::cast_intrusive(std::move(aggr)); const TableType* tt = tv->GetType()->AsTableType(); const auto& yt = tv->GetType()->Yield(); @@ -2475,13 +2470,12 @@ bool AssignExpr::IsPure() const return false; } -IndexSliceAssignExpr::IndexSliceAssignExpr(IntrusivePtr op1, - IntrusivePtr op2, bool is_init) +IndexSliceAssignExpr::IndexSliceAssignExpr(ExprPtr op1, ExprPtr op2, bool is_init) : AssignExpr(std::move(op1), std::move(op2), is_init) { } -IntrusivePtr IndexSliceAssignExpr::Eval(Frame* f) const +ValPtr IndexSliceAssignExpr::Eval(Frame* f) const { if ( is_init ) { @@ -2495,8 +2489,7 @@ IntrusivePtr IndexSliceAssignExpr::Eval(Frame* f) const return nullptr; } -IndexExpr::IndexExpr(IntrusivePtr arg_op1, - IntrusivePtr arg_op2, bool arg_is_slice) +IndexExpr::IndexExpr(ExprPtr arg_op1, ListExprPtr arg_op2, bool arg_is_slice) : BinaryExpr(EXPR_INDEX, std::move(arg_op1), std::move(arg_op2)), is_slice(arg_is_slice) { @@ -2544,7 +2537,7 @@ IndexExpr::IndexExpr(IntrusivePtr arg_op1, SetType(op1->GetType()->Yield()); else if ( match_type == MATCHES_INDEX_VECTOR ) - SetType(make_intrusive(op1->GetType()->Yield())); + SetType(zeek::make_intrusive(op1->GetType()->Yield())); else ExprError("Unknown MatchesIndex() return value"); @@ -2603,15 +2596,15 @@ void IndexExpr::Delete(Frame* f) v1->AsTableVal()->Remove(*v2); } -IntrusivePtr IndexExpr::MakeLvalue() +ExprPtr IndexExpr::MakeLvalue() { if ( IsString(op1->GetType()->Tag()) ) ExprError("cannot assign to string index expression"); - return make_intrusive(IntrusivePtr{NewRef{}, this}); + return zeek::make_intrusive(IntrusivePtr{zeek::NewRef{}, this}); } -IntrusivePtr IndexExpr::Eval(Frame* f) const +ValPtr IndexExpr::Eval(Frame* f) const { auto v1 = op1->Eval(f); @@ -2629,7 +2622,7 @@ IntrusivePtr IndexExpr::Eval(Frame* f) const { VectorVal* v_v1 = v1->AsVectorVal(); VectorVal* v_v2 = indv->AsVectorVal(); - auto v_result = make_intrusive(GetType()); + auto v_result = zeek::make_intrusive(GetType()); // Booleans select each element (or not). if ( IsBool(v_v2->GetType()->Yield()->Tag()) ) @@ -2672,12 +2665,12 @@ static int get_slice_index(int idx, int len) return idx; } -IntrusivePtr IndexExpr::Fold(Val* v1, Val* v2) const +ValPtr IndexExpr::Fold(Val* v1, Val* v2) const { if ( IsError() ) return nullptr; - IntrusivePtr v; + ValPtr v; switch ( v1->GetType()->Tag() ) { case zeek::TYPE_VECTOR: @@ -2690,7 +2683,7 @@ IntrusivePtr IndexExpr::Fold(Val* v1, Val* v2) const else { size_t len = vect->Size(); - auto result = make_intrusive(vect->GetType()); + auto result = zeek::make_intrusive(vect->GetType()); bro_int_t first = get_slice_index(lv->Idx(0)->CoerceToInt(), len); bro_int_t last = get_slice_index(lv->Idx(1)->CoerceToInt(), len); @@ -2710,15 +2703,15 @@ IntrusivePtr IndexExpr::Fold(Val* v1, Val* v2) const break; case zeek::TYPE_TABLE: - v = v1->AsTableVal()->FindOrDefault({NewRef{}, v2}); // Then, we jump into the TableVal here. + v = v1->AsTableVal()->FindOrDefault({zeek::NewRef{}, v2}); // Then, we jump into the TableVal here. break; case zeek::TYPE_STRING: { const ListVal* lv = v2->AsListVal(); - const BroString* s = v1->AsString(); + const String* s = v1->AsString(); int len = s->Len(); - BroString* substring = nullptr; + String* substring = nullptr; if ( lv->Length() == 1 ) { @@ -2742,7 +2735,7 @@ IntrusivePtr IndexExpr::Fold(Val* v1, Val* v2) const substring = s->GetSubstring(first, substring_len); } - return make_intrusive(substring ? substring : new BroString("")); + return zeek::make_intrusive(substring ? substring : new String("")); } default: @@ -2757,7 +2750,7 @@ IntrusivePtr IndexExpr::Fold(Val* v1, Val* v2) const return nullptr; } -void IndexExpr::Assign(Frame* f, IntrusivePtr v) +void IndexExpr::Assign(Frame* f, ValPtr v) { if ( IsError() ) return; @@ -2877,7 +2870,7 @@ TraversalCode IndexExpr::Traverse(TraversalCallback* cb) const HANDLE_TC_EXPR_POST(tc); } -FieldExpr::FieldExpr(IntrusivePtr arg_op, const char* arg_field_name) +FieldExpr::FieldExpr(ExprPtr arg_op, const char* arg_field_name) : UnaryExpr(EXPR_FIELD, std::move(arg_op)), field_name(copy_string(arg_field_name)), td(nullptr), field(0) { @@ -2909,9 +2902,9 @@ FieldExpr::~FieldExpr() delete [] field_name; } -IntrusivePtr FieldExpr::MakeLvalue() +ExprPtr FieldExpr::MakeLvalue() { - return make_intrusive(IntrusivePtr{NewRef{}, this}); + return zeek::make_intrusive(IntrusivePtr{zeek::NewRef{}, this}); } bool FieldExpr::CanDel() const @@ -2919,7 +2912,7 @@ bool FieldExpr::CanDel() const return td->GetAttr(ATTR_DEFAULT) || td->GetAttr(ATTR_OPTIONAL); } -void FieldExpr::Assign(Frame* f, IntrusivePtr v) +void FieldExpr::Assign(Frame* f, ValPtr v) { if ( IsError() ) return; @@ -2936,7 +2929,7 @@ void FieldExpr::Delete(Frame* f) Assign(f, nullptr); } -IntrusivePtr FieldExpr::Fold(Val* v) const +ValPtr FieldExpr::Fold(Val* v) const { if ( const auto& result = v->AsRecordVal()->GetField(field) ) return result; @@ -2968,8 +2961,7 @@ void FieldExpr::ExprDescribe(ODesc* d) const d->Add(field); } -HasFieldExpr::HasFieldExpr(IntrusivePtr arg_op, - const char* arg_field_name) +HasFieldExpr::HasFieldExpr(ExprPtr arg_op, const char* arg_field_name) : UnaryExpr(EXPR_HAS_FIELD, std::move(arg_op)), field_name(arg_field_name), field(0) { @@ -2997,10 +2989,10 @@ HasFieldExpr::~HasFieldExpr() delete field_name; } -IntrusivePtr HasFieldExpr::Fold(Val* v) const +ValPtr HasFieldExpr::Fold(Val* v) const { auto rv = v->AsRecordVal(); - return val_mgr->Bool(rv->GetField(field) != nullptr); + return zeek::val_mgr->Bool(rv->GetField(field) != nullptr); } void HasFieldExpr::ExprDescribe(ODesc* d) const @@ -3018,7 +3010,7 @@ void HasFieldExpr::ExprDescribe(ODesc* d) const d->Add(field); } -RecordConstructorExpr::RecordConstructorExpr(IntrusivePtr constructor_list) +RecordConstructorExpr::RecordConstructorExpr(ListExprPtr constructor_list) : UnaryExpr(EXPR_RECORD_CONSTRUCTOR, std::move(constructor_list)) { if ( IsError() ) @@ -3045,14 +3037,14 @@ RecordConstructorExpr::RecordConstructorExpr(IntrusivePtr constructor_ record_types->push_back(new TypeDecl(field_name, field_type)); } - SetType(make_intrusive(record_types)); + SetType(zeek::make_intrusive(record_types)); } RecordConstructorExpr::~RecordConstructorExpr() { } -IntrusivePtr RecordConstructorExpr::InitVal(const zeek::Type* t, IntrusivePtr aggr) const +ValPtr RecordConstructorExpr::InitVal(const zeek::Type* t, ValPtr aggr) const { auto v = Eval(nullptr); @@ -3060,8 +3052,8 @@ IntrusivePtr RecordConstructorExpr::InitVal(const zeek::Type* t, IntrusiveP { RecordVal* rv = v->AsRecordVal(); auto bt = const_cast(t); - IntrusivePtr rt{NewRef{}, bt->AsRecordType()}; - auto aggr_rec = cast_intrusive(std::move(aggr)); + RecordTypePtr rt{zeek::NewRef{}, bt->AsRecordType()}; + auto aggr_rec = zeek::cast_intrusive(std::move(aggr)); auto ar = rv->CoerceTo(std::move(rt), std::move(aggr_rec)); if ( ar ) @@ -3072,15 +3064,15 @@ IntrusivePtr RecordConstructorExpr::InitVal(const zeek::Type* t, IntrusiveP return nullptr; } -IntrusivePtr RecordConstructorExpr::Fold(Val* v) const +ValPtr RecordConstructorExpr::Fold(Val* v) const { ListVal* lv = v->AsListVal(); - auto rt = cast_intrusive(type); + auto rt = zeek::cast_intrusive(type); if ( lv->Length() != rt->NumFields() ) RuntimeErrorWithCallStack("inconsistency evaluating record constructor"); - auto rv = make_intrusive(std::move(rt)); + auto rv = zeek::make_intrusive(std::move(rt)); for ( int i = 0; i < lv->Length(); ++i ) rv->Assign(i, lv->Idx(i)); @@ -3095,9 +3087,9 @@ void RecordConstructorExpr::ExprDescribe(ODesc* d) const d->Add("]"); } -TableConstructorExpr::TableConstructorExpr(IntrusivePtr constructor_list, - std::unique_ptr>> arg_attrs, - IntrusivePtr arg_type) +TableConstructorExpr::TableConstructorExpr(ListExprPtr constructor_list, + std::unique_ptr> arg_attrs, + zeek::TypePtr arg_type) : UnaryExpr(EXPR_TABLE_CONSTRUCTOR, std::move(constructor_list)) { if ( IsError() ) @@ -3117,7 +3109,7 @@ TableConstructorExpr::TableConstructorExpr(IntrusivePtr constructor_li else { if ( op->AsListExpr()->Exprs().empty() ) - SetType(make_intrusive(make_intrusive(base_type(zeek::TYPE_ANY)), nullptr)); + SetType(zeek::make_intrusive(zeek::make_intrusive(base_type(zeek::TYPE_ANY)), nullptr)); else { SetType(init_type(op.get())); @@ -3132,7 +3124,7 @@ TableConstructorExpr::TableConstructorExpr(IntrusivePtr constructor_li } if ( arg_attrs ) - attrs = make_intrusive(std::move(*arg_attrs), type, false, false); + attrs = zeek::make_intrusive(std::move(*arg_attrs), type, false, false); const auto& indices = type->AsTableType()->GetIndices()->GetTypes(); const expr_list& cle = op->AsListExpr()->Exprs(); @@ -3175,12 +3167,12 @@ TableConstructorExpr::TableConstructorExpr(IntrusivePtr constructor_li } } -IntrusivePtr TableConstructorExpr::Eval(Frame* f) const +ValPtr TableConstructorExpr::Eval(Frame* f) const { if ( IsError() ) return nullptr; - auto aggr = make_intrusive(GetType(), attrs); + auto aggr = zeek::make_intrusive(GetType(), attrs); const expr_list& exprs = op->AsListExpr()->Exprs(); for ( const auto& expr : exprs ) @@ -3191,7 +3183,7 @@ IntrusivePtr TableConstructorExpr::Eval(Frame* f) const return aggr; } -IntrusivePtr TableConstructorExpr::InitVal(const zeek::Type* t, IntrusivePtr aggr) const +ValPtr TableConstructorExpr::InitVal(const zeek::Type* t, ValPtr aggr) const { if ( IsError() ) return nullptr; @@ -3199,8 +3191,8 @@ IntrusivePtr TableConstructorExpr::InitVal(const zeek::Type* t, IntrusivePt auto tt = GetType(); auto tval = aggr ? - IntrusivePtr{AdoptRef{}, aggr.release()->AsTableVal()} : - make_intrusive(std::move(tt), attrs); + TableValPtr{zeek::AdoptRef{}, aggr.release()->AsTableVal()} : + zeek::make_intrusive(std::move(tt), attrs); const expr_list& exprs = op->AsListExpr()->Exprs(); for ( const auto& expr : exprs ) @@ -3216,9 +3208,9 @@ void TableConstructorExpr::ExprDescribe(ODesc* d) const d->Add(")"); } -SetConstructorExpr::SetConstructorExpr(IntrusivePtr constructor_list, - std::unique_ptr>> arg_attrs, - IntrusivePtr arg_type) +SetConstructorExpr::SetConstructorExpr(ListExprPtr constructor_list, + std::unique_ptr> arg_attrs, + zeek::TypePtr arg_type) : UnaryExpr(EXPR_SET_CONSTRUCTOR, std::move(constructor_list)) { if ( IsError() ) @@ -3238,7 +3230,7 @@ SetConstructorExpr::SetConstructorExpr(IntrusivePtr constructor_list, else { if ( op->AsListExpr()->Exprs().empty() ) - SetType(make_intrusive(make_intrusive(zeek::base_type(zeek::TYPE_ANY)), nullptr)); + SetType(zeek::make_intrusive(zeek::make_intrusive(zeek::base_type(zeek::TYPE_ANY)), nullptr)); else SetType(init_type(op.get())); } @@ -3250,7 +3242,7 @@ SetConstructorExpr::SetConstructorExpr(IntrusivePtr constructor_list, SetError("values in set(...) constructor do not specify a set"); if ( arg_attrs ) - attrs = make_intrusive(std::move(*arg_attrs), type, false, false); + attrs = zeek::make_intrusive(std::move(*arg_attrs), type, false, false); const auto& indices = type->AsTableType()->GetIndices()->GetTypes(); expr_list& cle = op->AsListExpr()->Exprs(); @@ -3284,12 +3276,12 @@ SetConstructorExpr::SetConstructorExpr(IntrusivePtr constructor_list, } } -IntrusivePtr SetConstructorExpr::Eval(Frame* f) const +ValPtr SetConstructorExpr::Eval(Frame* f) const { if ( IsError() ) return nullptr; - auto aggr = make_intrusive(IntrusivePtr{NewRef{}, type->AsTableType()}, + auto aggr = zeek::make_intrusive(IntrusivePtr{zeek::NewRef{}, type->AsTableType()}, attrs); const expr_list& exprs = op->AsListExpr()->Exprs(); @@ -3302,7 +3294,7 @@ IntrusivePtr SetConstructorExpr::Eval(Frame* f) const return aggr; } -IntrusivePtr SetConstructorExpr::InitVal(const zeek::Type* t, IntrusivePtr aggr) const +ValPtr SetConstructorExpr::InitVal(const zeek::Type* t, ValPtr aggr) const { if ( IsError() ) return nullptr; @@ -3310,8 +3302,8 @@ IntrusivePtr SetConstructorExpr::InitVal(const zeek::Type* t, IntrusivePtr< const auto& index_type = t->AsTableType()->GetIndices(); auto tt = GetType(); auto tval = aggr ? - IntrusivePtr{AdoptRef{}, aggr.release()->AsTableVal()} : - make_intrusive(std::move(tt), attrs); + TableValPtr{zeek::AdoptRef{}, aggr.release()->AsTableVal()} : + zeek::make_intrusive(std::move(tt), attrs); const expr_list& exprs = op->AsListExpr()->Exprs(); for ( const auto& e : exprs ) @@ -3335,8 +3327,8 @@ void SetConstructorExpr::ExprDescribe(ODesc* d) const d->Add(")"); } -VectorConstructorExpr::VectorConstructorExpr(IntrusivePtr constructor_list, - IntrusivePtr arg_type) +VectorConstructorExpr::VectorConstructorExpr(ListExprPtr constructor_list, + zeek::TypePtr arg_type) : UnaryExpr(EXPR_VECTOR_CONSTRUCTOR, std::move(constructor_list)) { if ( IsError() ) @@ -3360,12 +3352,12 @@ VectorConstructorExpr::VectorConstructorExpr(IntrusivePtr constructor_ // vector(). // By default, assign VOID type here. A vector with // void type set is seen as an unspecified vector. - SetType(make_intrusive(zeek::base_type(zeek::TYPE_VOID))); + SetType(zeek::make_intrusive(zeek::base_type(zeek::TYPE_VOID))); return; } if ( auto t = merge_type_list(op->AsListExpr()) ) - SetType(make_intrusive(std::move(t))); + SetType(zeek::make_intrusive(std::move(t))); else { SetError(); @@ -3378,12 +3370,12 @@ VectorConstructorExpr::VectorConstructorExpr(IntrusivePtr constructor_ ExprError("inconsistent types in vector constructor"); } -IntrusivePtr VectorConstructorExpr::Eval(Frame* f) const +ValPtr VectorConstructorExpr::Eval(Frame* f) const { if ( IsError() ) return nullptr; - auto vec = make_intrusive(GetType()); + auto vec = zeek::make_intrusive(GetType()); const expr_list& exprs = op->AsListExpr()->Exprs(); loop_over_list(exprs, i) @@ -3400,15 +3392,15 @@ IntrusivePtr VectorConstructorExpr::Eval(Frame* f) const return vec; } -IntrusivePtr VectorConstructorExpr::InitVal(const zeek::Type* t, IntrusivePtr aggr) const +ValPtr VectorConstructorExpr::InitVal(const zeek::Type* t, ValPtr aggr) const { if ( IsError() ) return nullptr; auto vt = GetType(); auto vec = aggr ? - IntrusivePtr{AdoptRef{}, aggr.release()->AsVectorVal()} : - make_intrusive(std::move(vt)); + VectorValPtr{zeek::AdoptRef{}, aggr.release()->AsVectorVal()} : + zeek::make_intrusive(std::move(vt)); const expr_list& exprs = op->AsListExpr()->Exprs(); loop_over_list(exprs, i) @@ -3433,8 +3425,7 @@ void VectorConstructorExpr::ExprDescribe(ODesc* d) const d->Add(")"); } -FieldAssignExpr::FieldAssignExpr(const char* arg_field_name, - IntrusivePtr value) +FieldAssignExpr::FieldAssignExpr(const char* arg_field_name, ExprPtr value) : UnaryExpr(EXPR_FIELD_ASSIGN, std::move(value)), field_name(arg_field_name) { SetType(op->GetType()); @@ -3480,7 +3471,7 @@ void FieldAssignExpr::ExprDescribe(ODesc* d) const op->Describe(d); } -ArithCoerceExpr::ArithCoerceExpr(IntrusivePtr arg_op, TypeTag t) +ArithCoerceExpr::ArithCoerceExpr(ExprPtr arg_op, TypeTag t) : UnaryExpr(EXPR_ARITH_COERCE, std::move(arg_op)) { if ( IsError() ) @@ -3491,7 +3482,7 @@ ArithCoerceExpr::ArithCoerceExpr(IntrusivePtr arg_op, TypeTag t) if ( IsVector(bt) ) { - SetType(make_intrusive(zeek::base_type(t))); + SetType(zeek::make_intrusive(zeek::base_type(t))); vbt = op->GetType()->AsVectorType()->Yield()->Tag(); } else @@ -3509,17 +3500,17 @@ ArithCoerceExpr::ArithCoerceExpr(IntrusivePtr arg_op, TypeTag t) ExprError("bad coercion value"); } -IntrusivePtr ArithCoerceExpr::FoldSingleVal(Val* v, InternalTypeTag t) const +ValPtr ArithCoerceExpr::FoldSingleVal(Val* v, InternalTypeTag t) const { switch ( t ) { case zeek::TYPE_INTERNAL_DOUBLE: - return make_intrusive(v->CoerceToDouble()); + return zeek::make_intrusive(v->CoerceToDouble()); case zeek::TYPE_INTERNAL_INT: - return val_mgr->Int(v->CoerceToInt()); + return zeek::val_mgr->Int(v->CoerceToInt()); case zeek::TYPE_INTERNAL_UNSIGNED: - return val_mgr->Count(v->CoerceToUnsigned()); + return zeek::val_mgr->Count(v->CoerceToUnsigned()); default: RuntimeErrorWithCallStack("bad type in CoerceExpr::Fold"); @@ -3527,7 +3518,7 @@ IntrusivePtr ArithCoerceExpr::FoldSingleVal(Val* v, InternalTypeTag t) cons } } -IntrusivePtr ArithCoerceExpr::Fold(Val* v) const +ValPtr ArithCoerceExpr::Fold(Val* v) const { InternalTypeTag t = type->InternalType(); @@ -3545,7 +3536,7 @@ IntrusivePtr ArithCoerceExpr::Fold(Val* v) const t = GetType()->AsVectorType()->Yield()->InternalType(); VectorVal* vv = v->AsVectorVal(); - auto result = make_intrusive(GetType()); + auto result = zeek::make_intrusive(GetType()); for ( unsigned int i = 0; i < vv->Size(); ++i ) { @@ -3558,8 +3549,7 @@ IntrusivePtr ArithCoerceExpr::Fold(Val* v) const return result; } -RecordCoerceExpr::RecordCoerceExpr(IntrusivePtr arg_op, - IntrusivePtr r) +RecordCoerceExpr::RecordCoerceExpr(ExprPtr arg_op, zeek::RecordTypePtr r) : UnaryExpr(EXPR_RECORD_COERCE, std::move(arg_op)), map(nullptr), map_size(0) { @@ -3671,14 +3661,14 @@ RecordCoerceExpr::~RecordCoerceExpr() delete [] map; } -IntrusivePtr RecordCoerceExpr::InitVal(const zeek::Type* t, IntrusivePtr aggr) const +ValPtr RecordCoerceExpr::InitVal(const zeek::Type* t, ValPtr aggr) const { if ( auto v = Eval(nullptr) ) { RecordVal* rv = v->AsRecordVal(); auto bt = const_cast(t); - IntrusivePtr rt{NewRef{}, bt->AsRecordType()}; - auto aggr_rec = cast_intrusive(std::move(aggr)); + zeek::RecordTypePtr rt{zeek::NewRef{}, bt->AsRecordType()}; + auto aggr_rec = zeek::cast_intrusive(std::move(aggr)); if ( auto ar = rv->CoerceTo(std::move(rt), std::move(aggr_rec)) ) return ar; @@ -3688,9 +3678,9 @@ IntrusivePtr RecordCoerceExpr::InitVal(const zeek::Type* t, IntrusivePtr RecordCoerceExpr::Fold(Val* v) const +ValPtr RecordCoerceExpr::Fold(Val* v) const { - auto val = make_intrusive(GetType()); + auto val = zeek::make_intrusive(GetType()); RecordType* val_type = val->GetType()->AsRecordType(); RecordVal* rv = v->AsRecordVal(); @@ -3726,7 +3716,7 @@ IntrusivePtr RecordCoerceExpr::Fold(Val* v) const field_type->Tag() == zeek::TYPE_RECORD && ! same_type(rhs_type, field_type) ) { - if ( auto new_val = rhs->AsRecordVal()->CoerceTo(cast_intrusive(field_type)) ) + if ( auto new_val = rhs->AsRecordVal()->CoerceTo(zeek::cast_intrusive(field_type)) ) rhs = std::move(new_val); } else if ( BothArithmetic(rhs_type->Tag(), field_type->Tag()) && @@ -3753,7 +3743,7 @@ IntrusivePtr RecordCoerceExpr::Fold(Val* v) const ! same_type(def_type, field_type) ) { auto tmp = def_val->AsRecordVal()->CoerceTo( - cast_intrusive(field_type)); + zeek::cast_intrusive(field_type)); if ( tmp ) def_val = std::move(tmp); @@ -3769,8 +3759,7 @@ IntrusivePtr RecordCoerceExpr::Fold(Val* v) const return val; } -TableCoerceExpr::TableCoerceExpr(IntrusivePtr arg_op, - IntrusivePtr r) +TableCoerceExpr::TableCoerceExpr(ExprPtr arg_op, zeek::TableTypePtr r) : UnaryExpr(EXPR_TABLE_COERCE, std::move(arg_op)) { if ( IsError() ) @@ -3790,18 +3779,17 @@ TableCoerceExpr::~TableCoerceExpr() { } -IntrusivePtr TableCoerceExpr::Fold(Val* v) const +ValPtr TableCoerceExpr::Fold(Val* v) const { TableVal* tv = v->AsTableVal(); if ( tv->Size() > 0 ) RuntimeErrorWithCallStack("coercion of non-empty table/set"); - return make_intrusive(GetType(), tv->GetAttrs()); + return zeek::make_intrusive(GetType(), tv->GetAttrs()); } -VectorCoerceExpr::VectorCoerceExpr(IntrusivePtr arg_op, - IntrusivePtr v) +VectorCoerceExpr::VectorCoerceExpr(ExprPtr arg_op, zeek::VectorTypePtr v) : UnaryExpr(EXPR_VECTOR_COERCE, std::move(arg_op)) { if ( IsError() ) @@ -3821,14 +3809,14 @@ VectorCoerceExpr::~VectorCoerceExpr() { } -IntrusivePtr VectorCoerceExpr::Fold(Val* v) const +ValPtr VectorCoerceExpr::Fold(Val* v) const { VectorVal* vv = v->AsVectorVal(); if ( vv->Size() > 0 ) RuntimeErrorWithCallStack("coercion of non-empty vector"); - return make_intrusive(GetType()); + return zeek::make_intrusive(GetType()); } ScheduleTimer::ScheduleTimer(const EventHandlerPtr& arg_event, zeek::Args arg_args, @@ -3848,8 +3836,7 @@ void ScheduleTimer::Dispatch(double /* t */, bool /* is_expire */) mgr.Enqueue(event, std::move(args)); } -ScheduleExpr::ScheduleExpr(IntrusivePtr arg_when, - IntrusivePtr arg_event) +ScheduleExpr::ScheduleExpr(ExprPtr arg_when, EventExprPtr arg_event) : Expr(EXPR_SCHEDULE), when(std::move(arg_when)), event(std::move(arg_event)) { @@ -3869,7 +3856,7 @@ bool ScheduleExpr::IsPure() const return false; } -IntrusivePtr ScheduleExpr::Eval(Frame* f) const +ValPtr ScheduleExpr::Eval(Frame* f) const { if ( terminating ) return nullptr; @@ -3927,7 +3914,7 @@ void ScheduleExpr::ExprDescribe(ODesc* d) const event->Describe(d); } -InExpr::InExpr(IntrusivePtr arg_op1, IntrusivePtr arg_op2) +InExpr::InExpr(ExprPtr arg_op1, ExprPtr arg_op2) : BinaryExpr(EXPR_IN, std::move(arg_op1), std::move(arg_op2)) { if ( IsError() ) @@ -3993,7 +3980,7 @@ InExpr::InExpr(IntrusivePtr arg_op1, IntrusivePtr arg_op2) } if ( op1->Tag() != EXPR_LIST ) - op1 = make_intrusive(std::move(op1)); + op1 = zeek::make_intrusive(std::move(op1)); ListExpr* lop1 = op1->AsListExpr(); @@ -4004,42 +3991,41 @@ InExpr::InExpr(IntrusivePtr arg_op1, IntrusivePtr arg_op2) } } -IntrusivePtr InExpr::Fold(Val* v1, Val* v2) const +ValPtr InExpr::Fold(Val* v1, Val* v2) const { if ( v1->GetType()->Tag() == zeek::TYPE_PATTERN ) { RE_Matcher* re = v1->AsPattern(); - const BroString* s = v2->AsString(); - return val_mgr->Bool(re->MatchAnywhere(s) != 0); + const String* s = v2->AsString(); + return zeek::val_mgr->Bool(re->MatchAnywhere(s) != 0); } if ( v2->GetType()->Tag() == zeek::TYPE_STRING ) { - const BroString* s1 = v1->AsString(); - const BroString* s2 = v2->AsString(); + const String* s1 = v1->AsString(); + const String* s2 = v2->AsString(); // Could do better here e.g. Boyer-Moore if done repeatedly. auto s = reinterpret_cast(s1->CheckString()); auto res = strstr_n(s2->Len(), s2->Bytes(), s1->Len(), s) != -1; - return val_mgr->Bool(res); + return zeek::val_mgr->Bool(res); } if ( v1->GetType()->Tag() == zeek::TYPE_ADDR && v2->GetType()->Tag() == zeek::TYPE_SUBNET ) - return val_mgr->Bool(v2->AsSubNetVal()->Contains(v1->AsAddr())); + return zeek::val_mgr->Bool(v2->AsSubNetVal()->Contains(v1->AsAddr())); bool res; if ( is_vector(v2) ) res = (bool)v2->AsVectorVal()->At(v1->AsListVal()->Idx(0)->CoerceToUnsigned()); else - res = (bool)v2->AsTableVal()->Find({NewRef{}, v1}); + res = (bool)v2->AsTableVal()->Find({zeek::NewRef{}, v1}); - return val_mgr->Bool(res); + return zeek::val_mgr->Bool(res); } -CallExpr::CallExpr(IntrusivePtr arg_func, - IntrusivePtr arg_args, bool in_hook) +CallExpr::CallExpr(ExprPtr arg_func, ListExprPtr arg_args, bool in_hook) : Expr(EXPR_CALL), func(std::move(arg_func)), args(std::move(arg_args)) { if ( func->IsError() || args->IsError() ) @@ -4099,7 +4085,7 @@ CallExpr::CallExpr(IntrusivePtr arg_func, SetType(yield); // Check for call to built-ins that can be statically analyzed. - IntrusivePtr func_val; + ValPtr func_val; if ( func->Tag() == EXPR_NAME && // This is cheating, but without it processing gets @@ -4113,8 +4099,8 @@ CallExpr::CallExpr(IntrusivePtr arg_func, did_builtin_init && (func_val = func->Eval(nullptr)) ) { - ::Func* f = func_val->AsFunc(); - if ( f->GetKind() == Func::BUILTIN_FUNC && + zeek::Func* f = func_val->AsFunc(); + if ( f->GetKind() == zeek::Func::BUILTIN_FUNC && ! check_built_in_call((BuiltinFunc*) f, this) ) SetError(); } @@ -4134,7 +4120,7 @@ bool CallExpr::IsPure() const if ( ! func_val ) return false; - ::Func* f = func_val->AsFunc(); + zeek::Func* f = func_val->AsFunc(); // Only recurse for built-in functions, as recursing on script // functions can lead to infinite recursion if the function being @@ -4142,13 +4128,13 @@ bool CallExpr::IsPure() const // or indirectly). bool pure = false; - if ( f->GetKind() == Func::BUILTIN_FUNC ) + if ( f->GetKind() == zeek::Func::BUILTIN_FUNC ) pure = f->IsPure() && args->IsPure(); return pure; } -IntrusivePtr CallExpr::Eval(Frame* f) const +ValPtr CallExpr::Eval(Frame* f) const { if ( IsError() ) return nullptr; @@ -4165,18 +4151,18 @@ IntrusivePtr CallExpr::Eval(Frame* f) const DBG_LOG(DBG_NOTIFIERS, "%s: provides cached function result", trigger->Name()); - return {NewRef{}, v}; + return {zeek::NewRef{}, v}; } } } - IntrusivePtr ret; + ValPtr ret; auto func_val = func->Eval(f); auto v = eval_list(f, args.get()); if ( func_val && v ) { - const ::Func* funcv = func_val->AsFunc(); + const zeek::Func* funcv = func_val->AsFunc(); const CallExpr* current_call = f ? f->GetCall() : nullptr; if ( f ) @@ -4230,7 +4216,7 @@ LambdaExpr::LambdaExpr(std::unique_ptr arg_ing, // Install a dummy version of the function globally for use only // when broker provides a closure. - auto dummy_func = make_intrusive( + auto dummy_func = zeek::make_intrusive( ingredients->id, ingredients->body, ingredients->inits, @@ -4268,7 +4254,7 @@ LambdaExpr::LambdaExpr(std::unique_ptr arg_ing, // Update lamb's name dummy_func->SetName(my_name.c_str()); - auto v = make_intrusive(std::move(dummy_func)); + auto v = zeek::make_intrusive(std::move(dummy_func)); id->SetVal(std::move(v)); id->SetType(ingredients->id->GetType()); id->SetConst(); @@ -4279,9 +4265,9 @@ Scope* LambdaExpr::GetScope() const return ingredients->scope.get(); } -IntrusivePtr LambdaExpr::Eval(Frame* f) const +ValPtr LambdaExpr::Eval(Frame* f) const { - auto lamb = make_intrusive( + auto lamb = zeek::make_intrusive( ingredients->id, ingredients->body, ingredients->inits, @@ -4294,7 +4280,7 @@ IntrusivePtr LambdaExpr::Eval(Frame* f) const // Allows for lookups by the receiver. lamb->SetName(my_name.c_str()); - return make_intrusive(std::move(lamb)); + return zeek::make_intrusive(std::move(lamb)); } void LambdaExpr::ExprDescribe(ODesc* d) const @@ -4315,7 +4301,7 @@ TraversalCode LambdaExpr::Traverse(TraversalCallback* cb) const HANDLE_TC_EXPR_POST(tc); } -EventExpr::EventExpr(const char* arg_name, IntrusivePtr arg_args) +EventExpr::EventExpr(const char* arg_name, ListExprPtr arg_args) : Expr(EXPR_EVENT), name(arg_name), args(std::move(arg_args)) { EventHandler* h = event_registry->Lookup(name); @@ -4357,7 +4343,7 @@ EventExpr::EventExpr(const char* arg_name, IntrusivePtr arg_args) } } -IntrusivePtr EventExpr::Eval(Frame* f) const +ValPtr EventExpr::Eval(Frame* f) const { if ( IsError() ) return nullptr; @@ -4397,12 +4383,12 @@ void EventExpr::ExprDescribe(ODesc* d) const ListExpr::ListExpr() : Expr(EXPR_LIST) { - SetType(make_intrusive()); + SetType(zeek::make_intrusive()); } -ListExpr::ListExpr(IntrusivePtr e) : Expr(EXPR_LIST) +ListExpr::ListExpr(ExprPtr e) : Expr(EXPR_LIST) { - SetType(make_intrusive()); + SetType(zeek::make_intrusive()); Append(std::move(e)); } @@ -4412,7 +4398,7 @@ ListExpr::~ListExpr() Unref(expr); } -void ListExpr::Append(IntrusivePtr e) +void ListExpr::Append(ExprPtr e) { exprs.push_back(e.release()); ((TypeList*) type.get())->Append(exprs.back()->GetType()); @@ -4427,9 +4413,9 @@ bool ListExpr::IsPure() const return true; } -IntrusivePtr ListExpr::Eval(Frame* f) const +ValPtr ListExpr::Eval(Frame* f) const { - auto v = make_intrusive(zeek::TYPE_ANY); + auto v = zeek::make_intrusive(zeek::TYPE_ANY); for ( const auto& expr : exprs ) { @@ -4447,7 +4433,7 @@ IntrusivePtr ListExpr::Eval(Frame* f) const return v; } -IntrusivePtr ListExpr::InitType() const +zeek::TypePtr ListExpr::InitType() const { if ( exprs.empty() ) { @@ -4473,12 +4459,12 @@ IntrusivePtr ListExpr::InitType() const } - return make_intrusive(types); + return zeek::make_intrusive(types); } else { - auto tl = make_intrusive(); + auto tl = zeek::make_intrusive(); for ( const auto& e : exprs ) { @@ -4493,7 +4479,7 @@ IntrusivePtr ListExpr::InitType() const if ( ! til->IsPure() || ! til->AllMatch(til->GetPureType(), true) ) - tl->Append({NewRef{}, til}); + tl->Append({zeek::NewRef{}, til}); else tl->Append(til->GetPureType()); } @@ -4505,7 +4491,7 @@ IntrusivePtr ListExpr::InitType() const } } -IntrusivePtr ListExpr::InitVal(const zeek::Type* t, IntrusivePtr aggr) const +ValPtr ListExpr::InitVal(const zeek::Type* t, ValPtr aggr) const { // While fairly similar to the EvalIntoAggregate() code, // we keep this separate since it also deals with initialization @@ -4518,7 +4504,7 @@ IntrusivePtr ListExpr::InitVal(const zeek::Type* t, IntrusivePtr aggr) // in which case we should expand as a ListVal. if ( ! aggr && type->AsTypeList()->AllMatch(t, true) ) { - auto v = make_intrusive(zeek::TYPE_ANY); + auto v = zeek::make_intrusive(zeek::TYPE_ANY); const auto& tl = type->AsTypeList()->GetTypes(); if ( exprs.length() != static_cast(tl.size()) ) @@ -4555,7 +4541,7 @@ IntrusivePtr ListExpr::InitVal(const zeek::Type* t, IntrusivePtr aggr) return nullptr; } - auto v = make_intrusive(zeek::TYPE_ANY); + auto v = zeek::make_intrusive(zeek::TYPE_ANY); loop_over_list(exprs, i) { @@ -4649,7 +4635,7 @@ IntrusivePtr ListExpr::InitVal(const zeek::Type* t, IntrusivePtr aggr) return aggr; } -IntrusivePtr ListExpr::AddSetInit(const zeek::Type* t, IntrusivePtr aggr) const +ValPtr ListExpr::AddSetInit(const zeek::Type* t, ValPtr aggr) const { if ( aggr->GetType()->Tag() != zeek::TYPE_TABLE ) Internal("bad aggregate in ListExpr::InitVal"); @@ -4660,7 +4646,7 @@ IntrusivePtr ListExpr::AddSetInit(const zeek::Type* t, IntrusivePtr ag for ( const auto& expr : exprs ) { - IntrusivePtr element; + ValPtr element; if ( expr->GetType()->IsSet() ) // A set to flatten. @@ -4715,16 +4701,16 @@ void ListExpr::ExprDescribe(ODesc* d) const } } -IntrusivePtr ListExpr::MakeLvalue() +ExprPtr ListExpr::MakeLvalue() { for ( const auto & expr : exprs ) if ( expr->Tag() != EXPR_NAME ) ExprError("can only assign to list of identifiers"); - return make_intrusive(IntrusivePtr{NewRef{}, this}); + return zeek::make_intrusive(IntrusivePtr{zeek::NewRef{}, this}); } -void ListExpr::Assign(Frame* f, IntrusivePtr v) +void ListExpr::Assign(Frame* f, ValPtr v) { ListVal* lv = v->AsListVal(); @@ -4750,8 +4736,8 @@ TraversalCode ListExpr::Traverse(TraversalCallback* cb) const HANDLE_TC_EXPR_POST(tc); } -RecordAssignExpr::RecordAssignExpr(const IntrusivePtr& record, - const IntrusivePtr& init_list, bool is_init) +RecordAssignExpr::RecordAssignExpr(const ExprPtr& record, + const ExprPtr& init_list, bool is_init) { const expr_list& inits = init_list->AsListExpr()->Exprs(); @@ -4776,8 +4762,8 @@ RecordAssignExpr::RecordAssignExpr(const IntrusivePtr& record, if ( field >= 0 && same_type(lhs->GetFieldType(field), t->GetFieldType(j)) ) { - auto fe_lhs = make_intrusive(record, field_name); - auto fe_rhs = make_intrusive(IntrusivePtr{NewRef{}, init}, field_name); + auto fe_lhs = zeek::make_intrusive(record, field_name); + auto fe_rhs = zeek::make_intrusive(IntrusivePtr{zeek::NewRef{}, init}, field_name); Append(get_assign_expr(std::move(fe_lhs), std::move(fe_rhs), is_init)); } } @@ -4791,8 +4777,8 @@ RecordAssignExpr::RecordAssignExpr(const IntrusivePtr& record, const char* field_name = ""; // rf->FieldName(); if ( lhs->HasField(field_name) ) { - auto fe_lhs = make_intrusive(record, field_name); - IntrusivePtr fe_rhs = {NewRef{}, rf->Op()}; + auto fe_lhs = zeek::make_intrusive(record, field_name); + ExprPtr fe_rhs = {zeek::NewRef{}, rf->Op()}; Append(get_assign_expr(std::move(fe_lhs), std::move(fe_rhs), is_init)); } else @@ -4812,7 +4798,7 @@ RecordAssignExpr::RecordAssignExpr(const IntrusivePtr& record, } } -CastExpr::CastExpr(IntrusivePtr arg_op, IntrusivePtr t) +CastExpr::CastExpr(ExprPtr arg_op, zeek::TypePtr t) : UnaryExpr(EXPR_CAST, std::move(arg_op)) { auto stype = Op()->GetType(); @@ -4823,7 +4809,7 @@ CastExpr::CastExpr(IntrusivePtr arg_op, IntrusivePtr t) ExprError("cast not supported"); } -IntrusivePtr CastExpr::Eval(Frame* f) const +ValPtr CastExpr::Eval(Frame* f) const { if ( IsError() ) return nullptr; @@ -4860,18 +4846,18 @@ void CastExpr::ExprDescribe(ODesc* d) const GetType()->Describe(d); } -IsExpr::IsExpr(IntrusivePtr arg_op, IntrusivePtr arg_t) +IsExpr::IsExpr(ExprPtr arg_op, zeek::TypePtr arg_t) : UnaryExpr(EXPR_IS, std::move(arg_op)), t(std::move(arg_t)) { SetType(zeek::base_type(zeek::TYPE_BOOL)); } -IntrusivePtr IsExpr::Fold(Val* v) const +ValPtr IsExpr::Fold(Val* v) const { if ( IsError() ) return nullptr; - return val_mgr->Bool(can_cast_value_to_type(v, t.get())); + return zeek::val_mgr->Bool(can_cast_value_to_type(v, t.get())); } void IsExpr::ExprDescribe(ODesc* d) const @@ -4881,36 +4867,35 @@ void IsExpr::ExprDescribe(ODesc* d) const t->Describe(d); } -IntrusivePtr get_assign_expr(IntrusivePtr op1, - IntrusivePtr op2, bool is_init) +ExprPtr get_assign_expr(ExprPtr op1, ExprPtr op2, bool is_init) { if ( op1->GetType()->Tag() == zeek::TYPE_RECORD && op2->GetType()->Tag() == zeek::TYPE_LIST ) - return make_intrusive(std::move(op1), std::move(op2), - is_init); + return zeek::make_intrusive( + std::move(op1), std::move(op2), is_init); else if ( op1->Tag() == EXPR_INDEX && op1->AsIndexExpr()->IsSlice() ) - return make_intrusive(std::move(op1), - std::move(op2), is_init); + return zeek::make_intrusive( + std::move(op1), std::move(op2), is_init); else - return make_intrusive(std::move(op1), std::move(op2), - is_init); + return zeek::make_intrusive( + std::move(op1), std::move(op2), is_init); } -IntrusivePtr check_and_promote_expr(Expr* const e, zeek::Type* t) +ExprPtr check_and_promote_expr(Expr* const e, zeek::Type* t) { const auto& et = e->GetType(); TypeTag e_tag = et->Tag(); TypeTag t_tag = t->Tag(); if ( t->Tag() == zeek::TYPE_ANY ) - return {NewRef{}, e}; + return {zeek::NewRef{}, e}; if ( EitherArithmetic(t_tag, e_tag) ) { if ( e_tag == t_tag ) - return {NewRef{}, e}; + return {zeek::NewRef{}, e}; if ( ! BothArithmetic(t_tag, e_tag) ) { @@ -4925,7 +4910,7 @@ IntrusivePtr check_and_promote_expr(Expr* const e, zeek::Type* t) return nullptr; } - return make_intrusive(IntrusivePtr{NewRef{}, e}, t_tag); + return zeek::make_intrusive(IntrusivePtr{zeek::NewRef{}, e}, t_tag); } if ( t->Tag() == zeek::TYPE_RECORD && et->Tag() == zeek::TYPE_RECORD ) @@ -4943,13 +4928,14 @@ IntrusivePtr check_and_promote_expr(Expr* const e, zeek::Type* t) if ( same_attrs(td1->attrs.get(), td2->attrs.get()) ) // Everything matches perfectly. - return {NewRef{}, e}; + return {zeek::NewRef{}, e}; } } if ( record_promotion_compatible(t_r, et_r) ) - return make_intrusive(IntrusivePtr{NewRef{}, e}, - IntrusivePtr{NewRef{}, t_r}); + return zeek::make_intrusive( + IntrusivePtr{zeek::NewRef{}, e}, + IntrusivePtr{zeek::NewRef{}, t_r}); t->Error("incompatible record types", e); return nullptr; @@ -4960,19 +4946,21 @@ IntrusivePtr check_and_promote_expr(Expr* const e, zeek::Type* t) { if ( t->Tag() == zeek::TYPE_TABLE && et->Tag() == zeek::TYPE_TABLE && et->AsTableType()->IsUnspecifiedTable() ) - return make_intrusive(IntrusivePtr{NewRef{}, e}, - IntrusivePtr{NewRef{}, t->AsTableType()}); + return zeek::make_intrusive( + IntrusivePtr{zeek::NewRef{}, e}, + IntrusivePtr{zeek::NewRef{}, t->AsTableType()}); if ( t->Tag() == zeek::TYPE_VECTOR && et->Tag() == zeek::TYPE_VECTOR && et->AsVectorType()->IsUnspecifiedVector() ) - return make_intrusive(IntrusivePtr{NewRef{}, e}, - IntrusivePtr{NewRef{}, t->AsVectorType()}); + return zeek::make_intrusive( + IntrusivePtr{zeek::NewRef{}, e}, + IntrusivePtr{zeek::NewRef{}, t->AsVectorType()}); t->Error("type clash", e); return nullptr; } - return {NewRef{}, e}; + return {zeek::NewRef{}, e}; } bool check_and_promote_exprs(ListExpr* const elements, TypeList* types) @@ -5082,10 +5070,10 @@ bool check_and_promote_exprs_to_type(ListExpr* const elements, zeek::Type* type) return true; } -std::optional>> eval_list(Frame* f, const ListExpr* l) +std::optional> eval_list(Frame* f, const ListExpr* l) { const expr_list& e = l->Exprs(); - auto rval = std::make_optional>>(); + auto rval = std::make_optional>(); rval->reserve(e.length()); for ( const auto& expr : e ) diff --git a/src/Expr.h b/src/Expr.h index d70fbf1635..615dc93a13 100644 --- a/src/Expr.h +++ b/src/Expr.h @@ -17,12 +17,18 @@ #include "Val.h" #include "ZeekArgs.h" -template class IntrusivePtr; -class Frame; -class Scope; -struct function_ingredients; +ZEEK_FORWARD_DECLARE_NAMESPACED(Frame, zeek::detail); +ZEEK_FORWARD_DECLARE_NAMESPACED(Scope, zeek::detail); -namespace zeek::detail { +namespace zeek::detail { struct function_ingredients; } +using function_ingredients [[deprecated("Remove in v4.1. Use zeek::detail::function_ingredients.")]] = zeek::detail::function_ingredients; + +namespace zeek { +template class IntrusivePtr; + +namespace detail { + +using IDPtr = zeek::IntrusivePtr; enum BroExprTag : int { EXPR_ANY = -1, @@ -73,39 +79,43 @@ class CallExpr; class EventExpr; class Stmt; -class Expr : public BroObj { +class Expr; +using ExprPtr = zeek::IntrusivePtr; +using EventExprPtr = zeek::IntrusivePtr; +using ListExprPtr = zeek::IntrusivePtr; + +class Expr : public Obj { public: [[deprecated("Remove in v4.1. Use GetType().")]] zeek::Type* Type() const { return type.get(); } - const IntrusivePtr& GetType() const + const zeek::TypePtr& GetType() const { return type; } template - IntrusivePtr GetType() const - { return cast_intrusive(type); } + zeek::IntrusivePtr GetType() const + { return zeek::cast_intrusive(type); } BroExprTag Tag() const { return tag; } - Expr* Ref() { ::Ref(this); return this; } + Expr* Ref() { zeek::Ref(this); return this; } // Evaluates the expression and returns a corresponding Val*, // or nil if the expression's value isn't fixed. - virtual IntrusivePtr Eval(Frame* f) const = 0; + virtual ValPtr Eval(Frame* f) const = 0; // Same, but the context is that we are adding an element // into the given aggregate of the given type. Note that // return type is void since it's updating an existing // value, rather than creating a new one. - virtual void EvalIntoAggregate(const zeek::Type* t, Val* aggr, Frame* f) - const; + virtual void EvalIntoAggregate(const zeek::Type* t, Val* aggr, Frame* f) const; // Assign to the given value, if appropriate. - virtual void Assign(Frame* f, IntrusivePtr v); + virtual void Assign(Frame* f, ValPtr v); // Returns the type corresponding to this expression interpreted // as an initialization. Returns nil if the initialization is illegal. - virtual IntrusivePtr InitType() const; + virtual zeek::TypePtr InitType() const; // Returns true if this expression, interpreted as an initialization, // constitutes a record element, false otherwise. If the TypeDecl* @@ -118,7 +128,7 @@ public: // with the given type. If "aggr" is non-nil, then this expression // is an element of the given aggregate, and it is added to it // accordingly. - virtual IntrusivePtr InitVal(const zeek::Type* t, IntrusivePtr aggr) const; + virtual ValPtr InitVal(const zeek::Type* t, ValPtr aggr) const; // True if the expression has no side effects, false otherwise. virtual bool IsPure() const; @@ -154,7 +164,7 @@ public: // Return the expression converted to L-value form. If expr // cannot be used as an L-value, reports an error and returns // the current value of expr (this is the default method). - virtual IntrusivePtr MakeLvalue(); + virtual ExprPtr MakeLvalue(); // Marks the expression as one requiring (or at least appearing // with) parentheses. Used for pretty-printing. @@ -187,7 +197,7 @@ protected: // Puts the expression in canonical form. virtual void Canonicize(); - void SetType(IntrusivePtr t); + void SetType(zeek::TypePtr t); // Reports the given error and sets the expression's type to // TYPE_ERROR. @@ -199,19 +209,19 @@ protected: [[noreturn]] void RuntimeErrorWithCallStack(const std::string& msg) const; BroExprTag tag; - IntrusivePtr type; + zeek::TypePtr type; bool paren; }; class NameExpr final : public Expr { public: - explicit NameExpr(IntrusivePtr id, bool const_init = false); + explicit NameExpr(zeek::detail::IDPtr id, bool const_init = false); ID* Id() const { return id.get(); } - IntrusivePtr Eval(Frame* f) const override; - void Assign(Frame* f, IntrusivePtr v) override; - IntrusivePtr MakeLvalue() override; + ValPtr Eval(Frame* f) const override; + void Assign(Frame* f, ValPtr v) override; + ExprPtr MakeLvalue() override; bool IsPure() const override; TraversalCode Traverse(TraversalCallback* cb) const override; @@ -219,23 +229,23 @@ public: protected: void ExprDescribe(ODesc* d) const override; - IntrusivePtr id; + zeek::detail::IDPtr id; bool in_const_init; }; class ConstExpr final : public Expr { public: - explicit ConstExpr(IntrusivePtr val); + explicit ConstExpr(ValPtr val); Val* Value() const { return val.get(); } - IntrusivePtr Eval(Frame* f) const override; + ValPtr Eval(Frame* f) const override; TraversalCode Traverse(TraversalCallback* cb) const override; protected: void ExprDescribe(ODesc* d) const override; - IntrusivePtr val; + ValPtr val; }; class UnaryExpr : public Expr { @@ -245,21 +255,21 @@ public: // UnaryExpr::Eval correctly handles vector types. Any child // class that overrides Eval() should be modified to handle // vectors correctly as necessary. - IntrusivePtr Eval(Frame* f) const override; + ValPtr Eval(Frame* f) const override; bool IsPure() const override; TraversalCode Traverse(TraversalCallback* cb) const override; protected: - UnaryExpr(BroExprTag arg_tag, IntrusivePtr arg_op); + UnaryExpr(BroExprTag arg_tag, ExprPtr arg_op); void ExprDescribe(ODesc* d) const override; // Returns the expression folded using the given constant. - virtual IntrusivePtr Fold(Val* v) const; + virtual ValPtr Fold(Val* v) const; - IntrusivePtr op; + ExprPtr op; }; class BinaryExpr : public Expr { @@ -272,13 +282,13 @@ public: // BinaryExpr::Eval correctly handles vector types. Any child // class that overrides Eval() should be modified to handle // vectors correctly as necessary. - IntrusivePtr Eval(Frame* f) const override; + ValPtr Eval(Frame* f) const override; TraversalCode Traverse(TraversalCallback* cb) const override; protected: BinaryExpr(BroExprTag arg_tag, - IntrusivePtr arg_op1, IntrusivePtr arg_op2) + ExprPtr arg_op1, ExprPtr arg_op2) : Expr(arg_tag), op1(std::move(arg_op1)), op2(std::move(arg_op2)) { if ( ! (op1 && op2) ) @@ -288,20 +298,20 @@ protected: } // Returns the expression folded using the given constants. - virtual IntrusivePtr Fold(Val* v1, Val* v2) const; + virtual ValPtr Fold(Val* v1, Val* v2) const; // Same for when the constants are strings. - virtual IntrusivePtr StringFold(Val* v1, Val* v2) const; + virtual ValPtr StringFold(Val* v1, Val* v2) const; // Same for when the constants are patterns. - virtual IntrusivePtr PatternFold(Val* v1, Val* v2) const; + virtual ValPtr PatternFold(Val* v1, Val* v2) const; // Same for when the constants are sets. - virtual IntrusivePtr SetFold(Val* v1, Val* v2) const; + virtual ValPtr SetFold(Val* v1, Val* v2) const; // Same for when the constants are addresses or subnets. - virtual IntrusivePtr AddrFold(Val* v1, Val* v2) const; - virtual IntrusivePtr SubNetFold(Val* v1, Val* v2) const; + virtual ValPtr AddrFold(Val* v1, Val* v2) const; + virtual ValPtr SubNetFold(Val* v1, Val* v2) const; bool BothConst() const { return op1->IsConst() && op2->IsConst(); } @@ -317,148 +327,148 @@ protected: void ExprDescribe(ODesc* d) const override; - IntrusivePtr op1; - IntrusivePtr op2; + ExprPtr op1; + ExprPtr op2; }; class CloneExpr final : public UnaryExpr { public: - explicit CloneExpr(IntrusivePtr op); - IntrusivePtr Eval(Frame* f) const override; + explicit CloneExpr(ExprPtr op); + ValPtr Eval(Frame* f) const override; protected: - IntrusivePtr Fold(Val* v) const override; + ValPtr Fold(Val* v) const override; }; class IncrExpr final : public UnaryExpr { public: - IncrExpr(BroExprTag tag, IntrusivePtr op); + IncrExpr(BroExprTag tag, ExprPtr op); - IntrusivePtr Eval(Frame* f) const override; - IntrusivePtr DoSingleEval(Frame* f, Val* v) const; + ValPtr Eval(Frame* f) const override; + ValPtr DoSingleEval(Frame* f, Val* v) const; bool IsPure() const override; }; class ComplementExpr final : public UnaryExpr { public: - explicit ComplementExpr(IntrusivePtr op); + explicit ComplementExpr(ExprPtr op); protected: - IntrusivePtr Fold(Val* v) const override; + ValPtr Fold(Val* v) const override; }; class NotExpr final : public UnaryExpr { public: - explicit NotExpr(IntrusivePtr op); + explicit NotExpr(ExprPtr op); protected: - IntrusivePtr Fold(Val* v) const override; + ValPtr Fold(Val* v) const override; }; class PosExpr final : public UnaryExpr { public: - explicit PosExpr(IntrusivePtr op); + explicit PosExpr(ExprPtr op); protected: - IntrusivePtr Fold(Val* v) const override; + ValPtr Fold(Val* v) const override; }; class NegExpr final : public UnaryExpr { public: - explicit NegExpr(IntrusivePtr op); + explicit NegExpr(ExprPtr op); protected: - IntrusivePtr Fold(Val* v) const override; + ValPtr Fold(Val* v) const override; }; class SizeExpr final : public UnaryExpr { public: - explicit SizeExpr(IntrusivePtr op); - IntrusivePtr Eval(Frame* f) const override; + explicit SizeExpr(ExprPtr op); + ValPtr Eval(Frame* f) const override; protected: - IntrusivePtr Fold(Val* v) const override; + ValPtr Fold(Val* v) const override; }; class AddExpr final : public BinaryExpr { public: - AddExpr(IntrusivePtr op1, IntrusivePtr op2); + AddExpr(ExprPtr op1, ExprPtr op2); void Canonicize() override; }; class AddToExpr final : public BinaryExpr { public: - AddToExpr(IntrusivePtr op1, IntrusivePtr op2); - IntrusivePtr Eval(Frame* f) const override; + AddToExpr(ExprPtr op1, ExprPtr op2); + ValPtr Eval(Frame* f) const override; }; class RemoveFromExpr final : public BinaryExpr { public: - RemoveFromExpr(IntrusivePtr op1, IntrusivePtr op2); - IntrusivePtr Eval(Frame* f) const override; + RemoveFromExpr(ExprPtr op1, ExprPtr op2); + ValPtr Eval(Frame* f) const override; }; class SubExpr final : public BinaryExpr { public: - SubExpr(IntrusivePtr op1, IntrusivePtr op2); + SubExpr(ExprPtr op1, ExprPtr op2); }; class TimesExpr final : public BinaryExpr { public: - TimesExpr(IntrusivePtr op1, IntrusivePtr op2); + TimesExpr(ExprPtr op1, ExprPtr op2); void Canonicize() override; }; class DivideExpr final : public BinaryExpr { public: - DivideExpr(IntrusivePtr op1, IntrusivePtr op2); + DivideExpr(ExprPtr op1, ExprPtr op2); protected: - IntrusivePtr AddrFold(Val* v1, Val* v2) const override; + ValPtr AddrFold(Val* v1, Val* v2) const override; }; class ModExpr final : public BinaryExpr { public: - ModExpr(IntrusivePtr op1, IntrusivePtr op2); + ModExpr(ExprPtr op1, ExprPtr op2); }; class BoolExpr final : public BinaryExpr { public: - BoolExpr(BroExprTag tag, IntrusivePtr op1, IntrusivePtr op2); + BoolExpr(BroExprTag tag, ExprPtr op1, ExprPtr op2); - IntrusivePtr Eval(Frame* f) const override; - IntrusivePtr DoSingleEval(Frame* f, IntrusivePtr v1, Expr* op2) const; + ValPtr Eval(Frame* f) const override; + ValPtr DoSingleEval(Frame* f, ValPtr v1, Expr* op2) const; }; class BitExpr final : public BinaryExpr { public: - BitExpr(BroExprTag tag, IntrusivePtr op1, IntrusivePtr op2); + BitExpr(BroExprTag tag, ExprPtr op1, ExprPtr op2); }; class EqExpr final : public BinaryExpr { public: - EqExpr(BroExprTag tag, IntrusivePtr op1, IntrusivePtr op2); + EqExpr(BroExprTag tag, ExprPtr op1, ExprPtr op2); void Canonicize() override; protected: - IntrusivePtr Fold(Val* v1, Val* v2) const override; + ValPtr Fold(Val* v1, Val* v2) const override; }; class RelExpr final : public BinaryExpr { public: - RelExpr(BroExprTag tag, IntrusivePtr op1, IntrusivePtr op2); + RelExpr(BroExprTag tag, ExprPtr op1, ExprPtr op2); void Canonicize() override; }; class CondExpr final : public Expr { public: - CondExpr(IntrusivePtr op1, IntrusivePtr op2, IntrusivePtr op3); + CondExpr(ExprPtr op1, ExprPtr op2, ExprPtr op3); const Expr* Op1() const { return op1.get(); } const Expr* Op2() const { return op2.get(); } const Expr* Op3() const { return op3.get(); } - IntrusivePtr Eval(Frame* f) const override; + ValPtr Eval(Frame* f) const override; bool IsPure() const override; TraversalCode Traverse(TraversalCallback* cb) const override; @@ -466,53 +476,53 @@ public: protected: void ExprDescribe(ODesc* d) const override; - IntrusivePtr op1; - IntrusivePtr op2; - IntrusivePtr op3; + ExprPtr op1; + ExprPtr op2; + ExprPtr op3; }; class RefExpr final : public UnaryExpr { public: - explicit RefExpr(IntrusivePtr op); + explicit RefExpr(ExprPtr op); - void Assign(Frame* f, IntrusivePtr v) override; - IntrusivePtr MakeLvalue() override; + void Assign(Frame* f, ValPtr v) override; + ExprPtr MakeLvalue() override; }; class AssignExpr : public BinaryExpr { public: // If val is given, evaluating this expression will always yield the val // yet still perform the assignment. Used for triggers. - AssignExpr(IntrusivePtr op1, IntrusivePtr op2, bool is_init, - IntrusivePtr val = nullptr, - const IntrusivePtr& attrs = nullptr); + AssignExpr(ExprPtr op1, ExprPtr op2, bool is_init, + ValPtr val = nullptr, + const AttributesPtr& attrs = nullptr); - IntrusivePtr Eval(Frame* f) const override; + ValPtr Eval(Frame* f) const override; void EvalIntoAggregate(const zeek::Type* t, Val* aggr, Frame* f) const override; - IntrusivePtr InitType() const override; + zeek::TypePtr InitType() const override; bool IsRecordElement(TypeDecl* td) const override; - IntrusivePtr InitVal(const zeek::Type* t, IntrusivePtr aggr) const override; + ValPtr InitVal(const zeek::Type* t, ValPtr aggr) const override; bool IsPure() const override; protected: - bool TypeCheck(const IntrusivePtr& attrs = nullptr); + bool TypeCheck(const AttributesPtr& attrs = nullptr); bool TypeCheckArithmetics(TypeTag bt1, TypeTag bt2); bool is_init; - IntrusivePtr val; // optional + ValPtr val; // optional }; class IndexSliceAssignExpr final : public AssignExpr { public: - IndexSliceAssignExpr(IntrusivePtr op1, - IntrusivePtr op2, bool is_init); - IntrusivePtr Eval(Frame* f) const override; + IndexSliceAssignExpr(ExprPtr op1, + ExprPtr op2, bool is_init); + ValPtr Eval(Frame* f) const override; }; class IndexExpr final : public BinaryExpr { public: - IndexExpr(IntrusivePtr op1, - IntrusivePtr op2, bool is_slice = false); + IndexExpr(ExprPtr op1, + ListExprPtr op2, bool is_slice = false); bool CanAdd() const override; bool CanDel() const override; @@ -520,19 +530,19 @@ public: void Add(Frame* f) override; void Delete(Frame* f) override; - void Assign(Frame* f, IntrusivePtr v) override; - IntrusivePtr MakeLvalue() override; + void Assign(Frame* f, ValPtr v) override; + ExprPtr MakeLvalue() override; // Need to override Eval since it can take a vector arg but does // not necessarily return a vector. - IntrusivePtr Eval(Frame* f) const override; + ValPtr Eval(Frame* f) const override; TraversalCode Traverse(TraversalCallback* cb) const override; bool IsSlice() const { return is_slice; } protected: - IntrusivePtr Fold(Val* v1, Val* v2) const override; + ValPtr Fold(Val* v1, Val* v2) const override; void ExprDescribe(ODesc* d) const override; @@ -541,7 +551,7 @@ protected: class FieldExpr final : public UnaryExpr { public: - FieldExpr(IntrusivePtr op, const char* field_name); + FieldExpr(ExprPtr op, const char* field_name); ~FieldExpr() override; int Field() const { return field; } @@ -549,13 +559,13 @@ public: bool CanDel() const override; - void Assign(Frame* f, IntrusivePtr v) override; + void Assign(Frame* f, ValPtr v) override; void Delete(Frame* f) override; - IntrusivePtr MakeLvalue() override; + ExprPtr MakeLvalue() override; protected: - IntrusivePtr Fold(Val* v) const override; + ValPtr Fold(Val* v) const override; void ExprDescribe(ODesc* d) const override; @@ -568,13 +578,13 @@ protected: // "rec?$$attrname" is true if the attribute attrname is not nil. class HasFieldExpr final : public UnaryExpr { public: - HasFieldExpr(IntrusivePtr op, const char* field_name); + HasFieldExpr(ExprPtr op, const char* field_name); ~HasFieldExpr() override; const char* FieldName() const { return field_name; } protected: - IntrusivePtr Fold(Val* v) const override; + ValPtr Fold(Val* v) const override; void ExprDescribe(ODesc* d) const override; @@ -584,76 +594,76 @@ protected: class RecordConstructorExpr final : public UnaryExpr { public: - explicit RecordConstructorExpr(IntrusivePtr constructor_list); + explicit RecordConstructorExpr(ListExprPtr constructor_list); ~RecordConstructorExpr() override; protected: - IntrusivePtr InitVal(const zeek::Type* t, IntrusivePtr aggr) const override; - IntrusivePtr Fold(Val* v) const override; + ValPtr InitVal(const zeek::Type* t, ValPtr aggr) const override; + ValPtr Fold(Val* v) const override; void ExprDescribe(ODesc* d) const override; }; class TableConstructorExpr final : public UnaryExpr { public: - TableConstructorExpr(IntrusivePtr constructor_list, - std::unique_ptr>> attrs, - IntrusivePtr arg_type = nullptr); + TableConstructorExpr(ListExprPtr constructor_list, + std::unique_ptr> attrs, + zeek::TypePtr arg_type = nullptr); [[deprecated("Remove in v4.1. Use GetAttrs().")]] Attributes* Attrs() { return attrs.get(); } - const IntrusivePtr& GetAttrs() const + const AttributesPtr& GetAttrs() const { return attrs; } - IntrusivePtr Eval(Frame* f) const override; + ValPtr Eval(Frame* f) const override; protected: - IntrusivePtr InitVal(const zeek::Type* t, IntrusivePtr aggr) const override; + ValPtr InitVal(const zeek::Type* t, ValPtr aggr) const override; void ExprDescribe(ODesc* d) const override; - IntrusivePtr attrs; + AttributesPtr attrs; }; class SetConstructorExpr final : public UnaryExpr { public: - SetConstructorExpr(IntrusivePtr constructor_list, - std::unique_ptr>> attrs, - IntrusivePtr arg_type = nullptr); + SetConstructorExpr(ListExprPtr constructor_list, + std::unique_ptr> attrs, + zeek::TypePtr arg_type = nullptr); [[deprecated("Remove in v4.1. Use GetAttrs().")]] Attributes* Attrs() { return attrs.get(); } - const IntrusivePtr& GetAttrs() const + const AttributesPtr& GetAttrs() const { return attrs; } - IntrusivePtr Eval(Frame* f) const override; + ValPtr Eval(Frame* f) const override; protected: - IntrusivePtr InitVal(const zeek::Type* t, IntrusivePtr aggr) const override; + ValPtr InitVal(const zeek::Type* t, ValPtr aggr) const override; void ExprDescribe(ODesc* d) const override; - IntrusivePtr attrs; + AttributesPtr attrs; }; class VectorConstructorExpr final : public UnaryExpr { public: - explicit VectorConstructorExpr(IntrusivePtr constructor_list, - IntrusivePtr arg_type = nullptr); + explicit VectorConstructorExpr(ListExprPtr constructor_list, + zeek::TypePtr arg_type = nullptr); - IntrusivePtr Eval(Frame* f) const override; + ValPtr Eval(Frame* f) const override; protected: - IntrusivePtr InitVal(const zeek::Type* t, IntrusivePtr aggr) const override; + ValPtr InitVal(const zeek::Type* t, ValPtr aggr) const override; void ExprDescribe(ODesc* d) const override; }; class FieldAssignExpr final : public UnaryExpr { public: - FieldAssignExpr(const char* field_name, IntrusivePtr value); + FieldAssignExpr(const char* field_name, ExprPtr value); const char* FieldName() const { return field_name.c_str(); } @@ -668,21 +678,21 @@ protected: class ArithCoerceExpr final : public UnaryExpr { public: - ArithCoerceExpr(IntrusivePtr op, zeek::TypeTag t); + ArithCoerceExpr(ExprPtr op, zeek::TypeTag t); protected: - IntrusivePtr FoldSingleVal(Val* v, InternalTypeTag t) const; - IntrusivePtr Fold(Val* v) const override; + ValPtr FoldSingleVal(Val* v, InternalTypeTag t) const; + ValPtr Fold(Val* v) const override; }; class RecordCoerceExpr final : public UnaryExpr { public: - RecordCoerceExpr(IntrusivePtr op, IntrusivePtr r); + RecordCoerceExpr(ExprPtr op, RecordTypePtr r); ~RecordCoerceExpr() override; protected: - IntrusivePtr InitVal(const zeek::Type* t, IntrusivePtr aggr) const override; - IntrusivePtr Fold(Val* v) const override; + ValPtr InitVal(const zeek::Type* t, ValPtr aggr) const override; + ValPtr Fold(Val* v) const override; // For each super-record slot, gives subrecord slot with which to // fill it. @@ -692,20 +702,20 @@ protected: class TableCoerceExpr final : public UnaryExpr { public: - TableCoerceExpr(IntrusivePtr op, IntrusivePtr r); + TableCoerceExpr(ExprPtr op, TableTypePtr r); ~TableCoerceExpr() override; protected: - IntrusivePtr Fold(Val* v) const override; + ValPtr Fold(Val* v) const override; }; class VectorCoerceExpr final : public UnaryExpr { public: - VectorCoerceExpr(IntrusivePtr op, IntrusivePtr v); + VectorCoerceExpr(ExprPtr op, VectorTypePtr v); ~VectorCoerceExpr() override; protected: - IntrusivePtr Fold(Val* v) const override; + ValPtr Fold(Val* v) const override; }; class ScheduleTimer final : public Timer { @@ -722,11 +732,11 @@ protected: class ScheduleExpr final : public Expr { public: - ScheduleExpr(IntrusivePtr when, IntrusivePtr event); + ScheduleExpr(ExprPtr when, EventExprPtr event); bool IsPure() const override; - IntrusivePtr Eval(Frame* f) const override; + ValPtr Eval(Frame* f) const override; Expr* When() const { return when.get(); } EventExpr* Event() const { return event.get(); } @@ -736,22 +746,22 @@ public: protected: void ExprDescribe(ODesc* d) const override; - IntrusivePtr when; - IntrusivePtr event; + ExprPtr when; + EventExprPtr event; }; class InExpr final : public BinaryExpr { public: - InExpr(IntrusivePtr op1, IntrusivePtr op2); + InExpr(ExprPtr op1, ExprPtr op2); protected: - IntrusivePtr Fold(Val* v1, Val* v2) const override; + ValPtr Fold(Val* v1, Val* v2) const override; }; class CallExpr final : public Expr { public: - CallExpr(IntrusivePtr func, IntrusivePtr args, + CallExpr(ExprPtr func, ListExprPtr args, bool in_hook = false); Expr* Func() const { return func.get(); } @@ -759,15 +769,15 @@ public: bool IsPure() const override; - IntrusivePtr Eval(Frame* f) const override; + ValPtr Eval(Frame* f) const override; TraversalCode Traverse(TraversalCallback* cb) const override; protected: void ExprDescribe(ODesc* d) const override; - IntrusivePtr func; - IntrusivePtr args; + ExprPtr func; + ListExprPtr args; }; @@ -781,7 +791,7 @@ public: LambdaExpr(std::unique_ptr ingredients, id_list outer_ids); - IntrusivePtr Eval(Frame* f) const override; + ValPtr Eval(Frame* f) const override; TraversalCode Traverse(TraversalCallback* cb) const override; Scope* GetScope() const; @@ -798,13 +808,13 @@ private: class EventExpr final : public Expr { public: - EventExpr(const char* name, IntrusivePtr args); + EventExpr(const char* name, ListExprPtr args); const char* Name() const { return name.c_str(); } ListExpr* Args() const { return args.get(); } EventHandlerPtr Handler() const { return handler; } - IntrusivePtr Eval(Frame* f) const override; + ValPtr Eval(Frame* f) const override; TraversalCode Traverse(TraversalCallback* cb) const override; @@ -813,16 +823,16 @@ protected: std::string name; EventHandlerPtr handler; - IntrusivePtr args; + ListExprPtr args; }; class ListExpr : public Expr { public: ListExpr(); - explicit ListExpr(IntrusivePtr e); + explicit ListExpr(ExprPtr e); ~ListExpr() override; - void Append(IntrusivePtr e); + void Append(ExprPtr e); const expr_list& Exprs() const { return exprs; } expr_list& Exprs() { return exprs; } @@ -830,17 +840,17 @@ public: // True if the entire list represents pure values. bool IsPure() const override; - IntrusivePtr Eval(Frame* f) const override; + ValPtr Eval(Frame* f) const override; - IntrusivePtr InitType() const override; - IntrusivePtr InitVal(const zeek::Type* t, IntrusivePtr aggr) const override; - IntrusivePtr MakeLvalue() override; - void Assign(Frame* f, IntrusivePtr v) override; + zeek::TypePtr InitType() const override; + ValPtr InitVal(const zeek::Type* t, ValPtr aggr) const override; + ExprPtr MakeLvalue() override; + void Assign(Frame* f, ValPtr v) override; TraversalCode Traverse(TraversalCallback* cb) const override; protected: - IntrusivePtr AddSetInit(const zeek::Type* t, IntrusivePtr aggr) const; + ValPtr AddSetInit(const zeek::Type* t, ValPtr aggr) const; void ExprDescribe(ODesc* d) const override; @@ -850,28 +860,28 @@ protected: class RecordAssignExpr final : public ListExpr { public: - RecordAssignExpr(const IntrusivePtr& record, const IntrusivePtr& init_list, bool is_init); + RecordAssignExpr(const ExprPtr& record, const ExprPtr& init_list, bool is_init); }; class CastExpr final : public UnaryExpr { public: - CastExpr(IntrusivePtr op, IntrusivePtr t); + CastExpr(ExprPtr op, zeek::TypePtr t); protected: - IntrusivePtr Eval(Frame* f) const override; + ValPtr Eval(Frame* f) const override; void ExprDescribe(ODesc* d) const override; }; class IsExpr final : public UnaryExpr { public: - IsExpr(IntrusivePtr op, IntrusivePtr t); + IsExpr(ExprPtr op, zeek::TypePtr t); protected: - IntrusivePtr Fold(Val* v) const override; + ValPtr Fold(Val* v) const override; void ExprDescribe(ODesc* d) const override; private: - IntrusivePtr t; + zeek::TypePtr t; }; inline Val* Expr::ExprVal() const @@ -882,8 +892,9 @@ inline Val* Expr::ExprVal() const } // Decides whether to return an AssignExpr or a RecordAssignExpr. -IntrusivePtr get_assign_expr(IntrusivePtr op1, - IntrusivePtr op2, bool is_init); +ExprPtr get_assign_expr( + ExprPtr op1, + ExprPtr op2, bool is_init); // Type-check the given expression(s) against the given type(s). Complain // if the expression cannot match the given type, returning 0. If it can @@ -900,7 +911,7 @@ IntrusivePtr get_assign_expr(IntrusivePtr op1, * Returns nullptr if the expression cannot match or a promoted * expression. */ -extern IntrusivePtr check_and_promote_expr(Expr* e, Type* t); +extern ExprPtr check_and_promote_expr(Expr* e, Type* t); extern bool check_and_promote_exprs(ListExpr* elements, TypeList* types); extern bool check_and_promote_args(ListExpr* args, RecordType* types); @@ -908,7 +919,7 @@ extern bool check_and_promote_exprs_to_type(ListExpr* elements, Type* type); // Returns a ListExpr simplified down to a list a values, or nil // if they couldn't all be reduced. -std::optional>> eval_list(Frame* f, const ListExpr* l); +std::optional> eval_list(Frame* f, const ListExpr* l); // Returns true if e1 is "greater" than e2 - here "greater" is just // a heuristic, used with commutative operators to put them into @@ -917,9 +928,10 @@ extern bool expr_greater(const Expr* e1, const Expr* e2); // True if the given Expr* has a vector type inline bool is_vector(Expr* e) { return e->GetType()->Tag() == TYPE_VECTOR; } -inline bool is_vector(const IntrusivePtr& e) { return is_vector(e.get()); } +inline bool is_vector(const ExprPtr& e) { return is_vector(e.get()); } -} +} // namespace detail +} // namespace zeek using Expr [[deprecated("Remove in v4.1. Use zeek::detail::Expr instead.")]] = zeek::detail::Expr; using NameExpr [[deprecated("Remove in v4.1. Use zeek::detail::NameExpr instead.")]] = zeek::detail::NameExpr; diff --git a/src/File.cc b/src/File.cc index f5c25b9b96..3917267a35 100644 --- a/src/File.cc +++ b/src/File.cc @@ -269,7 +269,7 @@ void BroFile::SetAttrs(zeek::detail::Attributes* arg_attrs) EnableRawOutput(); } -RecordVal* BroFile::Rotate() +zeek::RecordVal* BroFile::Rotate() { if ( ! is_open ) return nullptr; @@ -279,7 +279,7 @@ RecordVal* BroFile::Rotate() return nullptr; static auto rotate_info = zeek::id::find_type("rotate_info"); - RecordVal* info = new RecordVal(rotate_info); + auto* info = new zeek::RecordVal(rotate_info); FILE* newf = rotate_file(name, info); if ( ! newf ) @@ -288,7 +288,7 @@ RecordVal* BroFile::Rotate() return nullptr; } - info->Assign(2, open_time); + info->Assign(2, open_time); Unlink(); @@ -328,8 +328,8 @@ void BroFile::RaiseOpenEvent() if ( ! ::file_opened ) return; - IntrusivePtr bf{NewRef{}, this}; - Event* event = new ::Event(::file_opened, {make_intrusive(std::move(bf))}); + BroFilePtr bf{zeek::NewRef{}, this}; + Event* event = new ::Event(::file_opened, {zeek::make_intrusive(std::move(bf))}); mgr.Dispatch(event, true); } @@ -346,11 +346,11 @@ double BroFile::Size() return s.st_size; } -IntrusivePtr BroFile::Get(const char* name) +BroFilePtr BroFile::Get(const char* name) { for ( const auto &el : open_files ) if ( el.first == name ) - return {NewRef{}, el.second}; + return {zeek::NewRef{}, el.second}; - return make_intrusive(name, "w"); + return zeek::make_intrusive(name, "w"); } diff --git a/src/File.h b/src/File.h index 8e57572a63..486b09d14e 100644 --- a/src/File.h +++ b/src/File.h @@ -16,15 +16,20 @@ #include "IntrusivePtr.h" #include "util.h" -class RecordVal; - -namespace zeek { class Type; } +namespace zeek { + class Type; + using TypePtr = zeek::IntrusivePtr; +} using BroType [[deprecated("Remove in v4.1. Use zeek::Type instead.")]] = zeek::Type; ZEEK_FORWARD_DECLARE_NAMESPACED(PrintStmt, zeek::detail); ZEEK_FORWARD_DECLARE_NAMESPACED(Attributes, zeek::detail); +ZEEK_FORWARD_DECLARE_NAMESPACED(RecordVal, zeek); -class BroFile final : public BroObj { +class BroFile; +using BroFilePtr = zeek::IntrusivePtr; + +class BroFile final : public zeek::Obj { public: explicit BroFile(FILE* arg_f); BroFile(FILE* arg_f, const char* filename, const char* access); @@ -45,7 +50,7 @@ public: [[deprecated("Remove in v4.1. Use GetType().")]] zeek::Type* FType() const { return t.get(); } - const IntrusivePtr& GetType() const + const zeek::TypePtr& GetType() const { return t; } // Whether the file is open in a general sense; it might @@ -60,7 +65,7 @@ public: void Describe(ODesc* d) const override; // Rotates the logfile. Returns rotate_info. - RecordVal* Rotate(); + zeek::RecordVal* Rotate(); // Set &raw_output attribute. void SetAttrs(zeek::detail::Attributes* attrs); @@ -72,7 +77,7 @@ public: static void CloseOpenFiles(); // Get the file with the given name, opening it if it doesn't yet exist. - static IntrusivePtr Get(const char* name); + static BroFilePtr Get(const char* name); [[deprecated("Remove in v4.1. Use BroFile::Get().")]] static BroFile* GetFile(const char* name) { return Get(name).release(); } @@ -106,7 +111,7 @@ protected: void RaiseOpenEvent(); FILE* f; - IntrusivePtr t; + zeek::TypePtr t; char* name; char* access; zeek::detail::Attributes* attrs; diff --git a/src/Frame.cc b/src/Frame.cc index 6962b1aa0e..4328cf49a3 100644 --- a/src/Frame.cc +++ b/src/Frame.cc @@ -7,14 +7,15 @@ #include "Func.h" #include "Desc.h" -#include "IntrusivePtr.h" #include "Trigger.h" #include "Val.h" #include "ID.h" -std::vector g_frame_stack; +std::vector g_frame_stack; -Frame::Frame(int arg_size, const BroFunc* func, const zeek::Args* fn_args) +namespace zeek::detail { + +Frame::Frame(int arg_size, const ScriptFunc* func, const zeek::Args* fn_args) { size = arg_size; frame = std::make_unique(size); @@ -52,32 +53,32 @@ Frame::~Frame() ClearElement(i); } -void Frame::AddFunctionWithClosureRef(BroFunc* func) +void Frame::AddFunctionWithClosureRef(ScriptFunc* func) { - ::Ref(func); + zeek::Ref(func); if ( ! functions_with_closure_frame_reference ) - functions_with_closure_frame_reference = std::make_unique>(); + functions_with_closure_frame_reference = std::make_unique>(); functions_with_closure_frame_reference->emplace_back(func); } -void Frame::SetElement(int n, Val* v) - { SetElement(n, {AdoptRef{}, v}); } +void Frame::SetElement(int n, zeek::Val* v) + { SetElement(n, {zeek::AdoptRef{}, v}); } -void Frame::SetElement(int n, IntrusivePtr v) +void Frame::SetElement(int n, zeek::ValPtr v) { ClearElement(n); frame[n] = {std::move(v), false}; } -void Frame::SetElementWeak(int n, Val* v) +void Frame::SetElementWeak(int n, zeek::Val* v) { ClearElement(n); - frame[n] = {{AdoptRef{}, v}, true}; + frame[n] = {{zeek::AdoptRef{}, v}, true}; } -void Frame::SetElement(const zeek::detail::ID* id, IntrusivePtr v) +void Frame::SetElement(const zeek::detail::ID* id, zeek::ValPtr v) { if ( closure ) { @@ -106,7 +107,7 @@ void Frame::SetElement(const zeek::detail::ID* id, IntrusivePtr v) SetElement(id->Offset(), std::move(v)); } -const IntrusivePtr& Frame::GetElementByID(const zeek::detail::ID* id) const +const zeek::ValPtr& Frame::GetElementByID(const zeek::detail::ID* id) const { if ( closure ) { @@ -173,7 +174,7 @@ Frame* Frame::Clone() const return other; } -static bool val_is_func(const IntrusivePtr& v, BroFunc* func) +static bool val_is_func(const zeek::ValPtr& v, ScriptFunc* func) { if ( v->GetType()->Tag() != zeek::TYPE_FUNC ) return false; @@ -181,7 +182,7 @@ static bool val_is_func(const IntrusivePtr& v, BroFunc* func) return v->AsFunc() == func; } -void Frame::CloneNonFuncElement(int offset, BroFunc* func, Frame* other) const +void Frame::CloneNonFuncElement(int offset, ScriptFunc* func, Frame* other) const { const auto& v = frame[offset].val; @@ -198,7 +199,7 @@ void Frame::CloneNonFuncElement(int offset, BroFunc* func, Frame* other) const other->SetElement(offset, std::move(rval)); } -Frame* Frame::SelectiveClone(const id_list& selection, BroFunc* func) const +Frame* Frame::SelectiveClone(const id_list& selection, ScriptFunc* func) const { if ( selection.length() == 0 ) return nullptr; @@ -348,14 +349,14 @@ broker::expected Frame::Serialize(const Frame* target, const id_li return {std::move(rval)}; } -std::pair> Frame::Unserialize(const broker::vector& data) +std::pair Frame::Unserialize(const broker::vector& data) { if ( data.size() == 0 ) return std::make_pair(true, nullptr); id_list outer_ids; OffsetMap offset_map; - IntrusivePtr closure; + FramePtr closure; auto where = data.begin(); @@ -437,7 +438,7 @@ std::pair> Frame::Unserialize(const broker::vector& da int frame_size = body.size(); // We'll associate this frame with a function later. - auto rf = make_intrusive(frame_size, nullptr, nullptr); + auto rf = zeek::make_intrusive(frame_size, nullptr, nullptr); rf->offset_map = std::make_unique(std::move(offset_map)); // Frame takes ownership of unref'ing elements in outer_ids @@ -492,7 +493,7 @@ void Frame::CaptureClosure(Frame* c, id_list arg_outer_ids) outer_ids = std::move(arg_outer_ids); for ( auto& i : outer_ids ) - ::Ref(i); + zeek::Ref(i); closure = c; if ( closure ) @@ -505,7 +506,7 @@ void Frame::CaptureClosure(Frame* c, id_list arg_outer_ids) // if (c) closure = c->SelectiveClone(outer_ids); } -void Frame::SetTrigger(IntrusivePtr arg_trigger) +void Frame::SetTrigger(zeek::detail::trigger::TriggerPtr arg_trigger) { trigger = std::move(arg_trigger); } @@ -617,3 +618,5 @@ Frame::UnserializeOffsetMap(const broker::vector& data) return std::make_pair(true, std::move(rval)); } + +} diff --git a/src/Frame.h b/src/Frame.h index 248e8e8f04..416e921b1f 100644 --- a/src/Frame.h +++ b/src/Frame.h @@ -16,12 +16,26 @@ #include #include -class BroFunc; - ZEEK_FORWARD_DECLARE_NAMESPACED(CallExpr, zeek::detail); ZEEK_FORWARD_DECLARE_NAMESPACED(Trigger, zeek::detail::trigger); -class Frame : public BroObj { +namespace zeek::detail { class ScriptFunc; } +using BroFunc [[deprecated("Remove in v4.1. Use zeek::detail::ScriptFunc instead.")]] = zeek::detail::ScriptFunc; + +namespace zeek { +using ValPtr = zeek::IntrusivePtr; + +namespace detail { +using IDPtr = zeek::IntrusivePtr; + +namespace trigger { +using TriggerPtr = zeek::IntrusivePtr; +} + +class Frame; +using FramePtr = zeek::IntrusivePtr; + +class Frame : public Obj { public: /** * Constructs a new frame belonging to *func* with *fn_args* @@ -31,7 +45,7 @@ public: * @param func the function that is creating this frame * @param fn_args the arguments being passed to that function. */ - Frame(int size, const BroFunc* func, const zeek::Args* fn_args); + Frame(int size, const ScriptFunc* func, const zeek::Args* fn_args); /** * Deletes the frame. Unrefs its trigger, the values that it @@ -43,21 +57,21 @@ public: * @param n the index to get. * @return the value at index *n* of the underlying array. */ - const IntrusivePtr& GetElement(int n) const + const zeek::ValPtr& GetElement(int n) const { return frame[n].val; } [[deprecated("Remove in v4.1. Use GetElement(int).")]] - Val* NthElement(int n) const { return frame[n].val.get(); } + zeek::Val* NthElement(int n) const { return frame[n].val.get(); } /** * Sets the element at index *n* of the underlying array to *v*. * @param n the index to set * @param v the value to set it to */ - void SetElement(int n, IntrusivePtr v); + void SetElement(int n, zeek::ValPtr v); [[deprecated("Remove in v4.1. Pass IntrusivePtr instead.")]] - void SetElement(int n, Val* v); + void SetElement(int n, zeek::Val* v); /** * Associates *id* and *v* in the frame. Future lookups of @@ -66,8 +80,8 @@ public: * @param id the ID to associate * @param v the value to associate it with */ - void SetElement(const zeek::detail::ID* id, IntrusivePtr v); - void SetElement(const IntrusivePtr& id, IntrusivePtr v) + void SetElement(const zeek::detail::ID* id, zeek::ValPtr v); + void SetElement(const zeek::detail::IDPtr& id, zeek::ValPtr v) { SetElement(id.get(), std::move(v)); } /** @@ -77,11 +91,11 @@ public: * @param id the id who's value to retreive * @return the value associated with *id* */ - const IntrusivePtr& GetElementByID(const IntrusivePtr& id) const + const zeek::ValPtr& GetElementByID(const zeek::detail::IDPtr& id) const { return GetElementByID(id.get()); } [[deprecated("Remove in v4.1. Use GetElementByID().")]] - Val* GetElement(const zeek::detail::ID* id) const + zeek::Val* GetElement(const zeek::detail::ID* id) const { return GetElementByID(id).get(); } /** @@ -99,7 +113,7 @@ public: /** * @return the function that the frame is associated with. */ - const BroFunc* GetFunction() const { return function; } + const ScriptFunc* GetFunction() const { return function; } /** * @return the arguments passed to the function that this frame @@ -112,7 +126,7 @@ public: * * @param func the function for the frame to be associated with. */ - void SetFunction(BroFunc* func) { function = func; } + void SetFunction(ScriptFunc* func) { function = func; } /** * Sets the next statement to be executed in the context of the frame. @@ -161,7 +175,7 @@ public: * *selection* have been cloned. All other values are made to be * null. */ - Frame* SelectiveClone(const id_list& selection, BroFunc* func) const; + Frame* SelectiveClone(const id_list& selection, ScriptFunc* func) const; /** * Serializes the Frame into a Broker representation. @@ -195,7 +209,7 @@ public: * and the second is the unserialized frame with reference count +1, or * null if the serialization wasn't successful. */ - static std::pair> Unserialize(const broker::vector& data); + static std::pair Unserialize(const broker::vector& data); /** * Sets the IDs that the frame knows offsets for. These offsets will @@ -216,7 +230,7 @@ public: // If the frame is run in the context of a trigger condition evaluation, // the trigger needs to be registered. - void SetTrigger(IntrusivePtr arg_trigger); + void SetTrigger(zeek::detail::trigger::TriggerPtr arg_trigger); void ClearTrigger(); zeek::detail::trigger::Trigger* GetTrigger() const { return trigger.get(); } @@ -234,20 +248,20 @@ public: * weak references prevents unbreakable circular references that * otherwise cause memory leaks. */ - void AddFunctionWithClosureRef(BroFunc* func); + void AddFunctionWithClosureRef(ScriptFunc* func); private: using OffsetMap = std::unordered_map; struct Element { - IntrusivePtr val; + zeek::ValPtr val; // Weak reference is used to prevent circular reference memory leaks // in lambdas/closures. bool weak_ref; }; - const IntrusivePtr& GetElementByID(const zeek::detail::ID* id) const; + const zeek::ValPtr& GetElementByID(const zeek::detail::ID* id) const; /** * Sets the element at index *n* of the underlying array to *v*, but does @@ -257,14 +271,14 @@ private: * @param v the value to set it to (caller has not Ref'd and Frame will * not Unref it) */ - void SetElementWeak(int n, Val* v); + void SetElementWeak(int n, zeek::Val* v); /** * Clone an element at an offset into other frame if not equal to a given * function (in that case just assigna weak reference). Used to break * circular references between lambda functions and closure frames. */ - void CloneNonFuncElement(int offset, BroFunc* func, Frame* other) const; + void CloneNonFuncElement(int offset, ScriptFunc* func, Frame* other) const; /** * Resets the value at offset 'n' frame (by decrementing reference @@ -315,19 +329,24 @@ private: std::unique_ptr offset_map; /** The function this frame is associated with. */ - const BroFunc* function; + const ScriptFunc* function; /** The arguments to the function that this Frame is associated with. */ const zeek::Args* func_args; /** The next statement to be evaluted in the context of this frame. */ zeek::detail::Stmt* next_stmt; - IntrusivePtr trigger; + zeek::detail::trigger::TriggerPtr trigger; const zeek::detail::CallExpr* call; - std::unique_ptr> functions_with_closure_frame_reference; + std::unique_ptr> functions_with_closure_frame_reference; }; +} // namespace detail +} // namespace zeek + +using Frame [[deprecated("Remove in v4.1. Use zeek::detail::Frame instead.")]] = zeek::detail::Frame; + /** * If we stopped using this and instead just made a struct of the information * that the debugger actually uses we could make the Frame a class a template. @@ -338,4 +357,4 @@ private: * DebugFrame which provides the information that the debugger uses. See: * https://stackoverflow.com/a/16211097 */ -extern std::vector g_frame_stack; +extern std::vector g_frame_stack; diff --git a/src/Func.cc b/src/Func.cc index 8bdcf2d2c5..97272efd1b 100644 --- a/src/Func.cc +++ b/src/Func.cc @@ -1,3 +1,4 @@ + // See the file "COPYING" in the main distribution directory for copyright. #include "zeek-config.h" @@ -54,22 +55,39 @@ #include "iosource/PktSrc.h" #include "iosource/PktDumper.h" +#include "zeek.bif.func_h" +#include "stats.bif.func_h" +#include "reporter.bif.func_h" +#include "strings.bif.func_h" +#include "option.bif.func_h" +#include "supervisor.bif.func_h" + +#include "zeek.bif.func_def" +#include "stats.bif.func_def" +#include "reporter.bif.func_def" +#include "strings.bif.func_def" +#include "option.bif.func_def" +#include "supervisor.bif.func_def" + extern RETSIGTYPE sig_handler(int signo); +namespace zeek::detail { std::vector call_stack; bool did_builtin_init = false; +static const std::pair empty_hook_result(false, nullptr); +} // namespace zeek::detail -static const std::pair> empty_hook_result(false, nullptr); +namespace zeek { std::string render_call_stack() { std::string rval; int lvl = 0; - if ( ! call_stack.empty() ) + if ( ! detail::call_stack.empty() ) rval += "| "; - for ( auto it = call_stack.rbegin(); it != call_stack.rend(); ++it ) + for ( auto it = detail::call_stack.rbegin(); it != detail::call_stack.rend(); ++it ) { if ( lvl > 0 ) rval += " | "; @@ -101,7 +119,7 @@ std::string render_call_stack() ++lvl; } - if ( ! call_stack.empty() ) + if ( ! detail::call_stack.empty() ) rval += " |"; return rval; @@ -110,34 +128,34 @@ std::string render_call_stack() Func::Func() { unique_id = unique_ids.size(); - unique_ids.push_back({NewRef{}, this}); + unique_ids.push_back({zeek::NewRef{}, this}); } Func::Func(Kind arg_kind) : kind(arg_kind) { unique_id = unique_ids.size(); - unique_ids.push_back({NewRef{}, this}); + unique_ids.push_back({zeek::NewRef{}, this}); } Func::~Func() = default; -void Func::AddBody(IntrusivePtr /* new_body */, - const std::vector>& /* new_inits */, +void Func::AddBody(zeek::detail::StmtPtr /* new_body */, + const std::vector& /* new_inits */, size_t /* new_frame_size */, int /* priority */) { Internal("Func::AddBody called"); } -void Func::SetScope(IntrusivePtr newscope) +void Func::SetScope(zeek::detail::ScopePtr newscope) { scope = std::move(newscope); } -IntrusivePtr Func::DoClone() +zeek::FuncPtr Func::DoClone() { // By default, ok just to return a reference. Func does not have any state // that is different across instances. - return {NewRef{}, this}; + return {zeek::NewRef{}, this}; } void Func::DescribeDebug(ODesc* d, const zeek::Args* args) const @@ -178,14 +196,14 @@ void Func::DescribeDebug(ODesc* d, const zeek::Args* args) const TraversalCode Func::Traverse(TraversalCallback* cb) const { // FIXME: Make a fake scope for builtins? - Scope* old_scope = cb->current_scope; + zeek::detail::Scope* old_scope = cb->current_scope; cb->current_scope = scope.get(); TraversalCode tc = cb->PreFunction(this); HANDLE_TC_STMT_PRE(tc); // FIXME: Traverse arguments to builtin functions, too. - if ( kind == BRO_FUNC && scope ) + if ( kind == SCRIPT_FUNC && scope ) { tc = scope->Traverse(cb); HANDLE_TC_STMT_PRE(tc); @@ -215,10 +233,10 @@ void Func::CopyStateInto(Func* other) const other->unique_id = unique_id; } -void Func::CheckPluginResult(bool handled, const IntrusivePtr& hook_result, +void Func::CheckPluginResult(bool handled, const zeek::ValPtr& hook_result, zeek::FunctionFlavor flavor) const { - // Helper function factoring out this code from BroFunc:Call() for + // Helper function factoring out this code from ScriptFunc:Call() for // better readability. if ( ! handled ) @@ -268,10 +286,18 @@ void Func::CheckPluginResult(bool handled, const IntrusivePtr& hook_result, } } -BroFunc::BroFunc(const IntrusivePtr& arg_id, IntrusivePtr arg_body, - const std::vector>& aggr_inits, - size_t arg_frame_size, int priority) - : Func(BRO_FUNC) +zeek::Val* Func::Call(val_list* args, zeek::detail::Frame* parent) const + { + auto zargs = zeek::val_list_to_args(*args); + return Invoke(&zargs, parent).release(); + }; + +namespace detail { + +ScriptFunc::ScriptFunc(const zeek::detail::IDPtr& arg_id, zeek::detail::StmtPtr arg_body, + const std::vector& aggr_inits, + size_t arg_frame_size, int priority) + : Func(SCRIPT_FUNC) { name = arg_id->Name(); type = arg_id->GetType(); @@ -286,25 +312,19 @@ BroFunc::BroFunc(const IntrusivePtr& arg_id, IntrusivePtrIsPure(); }); } -Val* Func::Call(val_list* args, Frame* parent) const - { - auto zargs = zeek::val_list_to_args(*args); - return Invoke(&zargs, parent).release(); - }; - -IntrusivePtr BroFunc::Invoke(zeek::Args* args, Frame* parent) const +zeek::ValPtr ScriptFunc::Invoke(zeek::Args* args, zeek::detail::Frame* parent) const { #ifdef PROFILE_BRO_FUNCTIONS DEBUG_MSG("Function: %s\n", Name()); @@ -327,10 +347,10 @@ IntrusivePtr BroFunc::Invoke(zeek::Args* args, Frame* parent) const { // Can only happen for events and hooks. assert(Flavor() == zeek::FUNC_FLAVOR_EVENT || Flavor() == zeek::FUNC_FLAVOR_HOOK); - return Flavor() == zeek::FUNC_FLAVOR_HOOK ? val_mgr->True() : nullptr; + return Flavor() == zeek::FUNC_FLAVOR_HOOK ? zeek::val_mgr->True() : nullptr; } - auto f = make_intrusive(frame_size, this, args); + auto f = zeek::make_intrusive(frame_size, this, args); if ( closure ) f->CaptureClosure(closure, outer_ids); @@ -338,7 +358,7 @@ IntrusivePtr BroFunc::Invoke(zeek::Args* args, Frame* parent) const // Hand down any trigger. if ( parent ) { - f->SetTrigger({NewRef{}, parent->GetTrigger()}); + f->SetTrigger({zeek::NewRef{}, parent->GetTrigger()}); f->SetCall(parent->GetCall()); } @@ -356,7 +376,7 @@ IntrusivePtr BroFunc::Invoke(zeek::Args* args, Frame* parent) const } stmt_flow_type flow = FLOW_NEXT; - IntrusivePtr result; + zeek::ValPtr result; for ( const auto& body : bodies ) { @@ -413,7 +433,7 @@ IntrusivePtr BroFunc::Invoke(zeek::Args* args, Frame* parent) const if ( flow == FLOW_BREAK ) { // Short-circuit execution of remaining hook handler bodies. - result = val_mgr->False(); + result = zeek::val_mgr->False(); break; } } @@ -424,7 +444,7 @@ IntrusivePtr BroFunc::Invoke(zeek::Args* args, Frame* parent) const if ( Flavor() == zeek::FUNC_FLAVOR_HOOK ) { if ( ! result ) - result = val_mgr->True(); + result = zeek::val_mgr->True(); } // Warn if the function returns something, but we returned from @@ -449,9 +469,9 @@ IntrusivePtr BroFunc::Invoke(zeek::Args* args, Frame* parent) const return result; } -void BroFunc::AddBody(IntrusivePtr new_body, - const std::vector>& new_inits, - size_t new_frame_size, int priority) +void ScriptFunc::AddBody(zeek::detail::StmtPtr new_body, + const std::vector& new_inits, + size_t new_frame_size, int priority) { if ( new_frame_size > frame_size ) frame_size = new_frame_size; @@ -478,7 +498,7 @@ void BroFunc::AddBody(IntrusivePtr new_body, sort(bodies.begin(), bodies.end()); } -void BroFunc::AddClosure(id_list ids, Frame* f) +void ScriptFunc::AddClosure(id_list ids, zeek::detail::Frame* f) { if ( ! f ) return; @@ -487,7 +507,7 @@ void BroFunc::AddClosure(id_list ids, Frame* f) SetClosureFrame(f); } -bool BroFunc::StrengthenClosureReference(Frame* f) +bool ScriptFunc::StrengthenClosureReference(zeek::detail::Frame* f) { if ( closure != f ) return false; @@ -500,10 +520,10 @@ bool BroFunc::StrengthenClosureReference(Frame* f) return true; } -void BroFunc::SetClosureFrame(Frame* f) +void ScriptFunc::SetClosureFrame(zeek::detail::Frame* f) { if ( closure ) - reporter->InternalError("Tried to override closure for BroFunc %s.", + reporter->InternalError("Tried to override closure for ScriptFunc %s.", Name()); // Have to use weak references initially because otherwise Ref'ing the @@ -518,9 +538,9 @@ void BroFunc::SetClosureFrame(Frame* f) f->AddFunctionWithClosureRef(this); } -bool BroFunc::UpdateClosure(const broker::vector& data) +bool ScriptFunc::UpdateClosure(const broker::vector& data) { - auto result = Frame::Unserialize(data); + auto result = zeek::detail::Frame::Unserialize(data); if ( ! result.first ) return false; @@ -540,11 +560,11 @@ bool BroFunc::UpdateClosure(const broker::vector& data) } -IntrusivePtr BroFunc::DoClone() +zeek::FuncPtr ScriptFunc::DoClone() { - // BroFunc 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. - auto other = IntrusivePtr{AdoptRef{}, new BroFunc()}; + auto other = zeek::IntrusivePtr{zeek::AdoptRef{}, new ScriptFunc()}; CopyStateInto(other.get()); @@ -556,12 +576,12 @@ IntrusivePtr BroFunc::DoClone() return other; } -broker::expected BroFunc::SerializeClosure() const +broker::expected ScriptFunc::SerializeClosure() const { - return Frame::Serialize(closure, outer_ids); + return zeek::detail::Frame::Serialize(closure, outer_ids); } -void BroFunc::Describe(ODesc* d) const +void ScriptFunc::Describe(ODesc* d) const { d->Add(Name()); @@ -574,13 +594,14 @@ void BroFunc::Describe(ODesc* d) const } } -IntrusivePtr BroFunc::AddInits(IntrusivePtr body, - const std::vector>& inits) +zeek::detail::StmtPtr ScriptFunc::AddInits( + zeek::detail::StmtPtr body, + const std::vector& inits) { if ( inits.empty() ) return body; - auto stmt_series = make_intrusive(); + auto stmt_series = zeek::make_intrusive(); stmt_series->Stmts().push_back(new zeek::detail::InitStmt(inits)); stmt_series->Stmts().push_back(body.release()); @@ -588,21 +609,21 @@ IntrusivePtr BroFunc::AddInits(IntrusivePtrInternalError("built-in function %s missing", Name()); if ( id->HasVal() ) reporter->InternalError("built-in function %s multiply defined", Name()); type = id->GetType(); - id->SetVal(make_intrusive(IntrusivePtr{NewRef{}, this})); + id->SetVal(zeek::make_intrusive(zeek::IntrusivePtr{zeek::NewRef{}, this})); } BuiltinFunc::~BuiltinFunc() @@ -614,7 +635,7 @@ bool BuiltinFunc::IsPure() const return is_pure; } -IntrusivePtr BuiltinFunc::Invoke(zeek::Args* args, Frame* parent) const +zeek::ValPtr BuiltinFunc::Invoke(zeek::Args* args, zeek::detail::Frame* parent) const { #ifdef PROFILE_BRO_FUNCTIONS DEBUG_MSG("Function: %s\n", Name()); @@ -663,132 +684,6 @@ void BuiltinFunc::Describe(ODesc* d) const d->AddCount(is_pure); } -void builtin_error(const char* msg) - { - builtin_error(msg, IntrusivePtr{}); - } - -void builtin_error(const char* msg, IntrusivePtr arg) - { - builtin_error(msg, arg.get()); - } - -void builtin_error(const char* msg, BroObj* arg) - { - auto emit = [=](const zeek::detail::CallExpr* ce) - { - if ( ce ) - ce->Error(msg, arg); - else - reporter->Error(msg, arg); - }; - - - if ( call_stack.empty() ) - { - emit(nullptr); - return; - } - - auto last_call = call_stack.back(); - - if ( call_stack.size() < 2 ) - { - // Don't need to check for wrapper function like "::__" - emit(last_call.call); - return; - } - - auto starts_with_double_underscore = [](const std::string& name) -> bool - { return name.size() > 2 && name[0] == '_' && name[1] == '_'; }; - std::string last_func = last_call.func->Name(); - - auto pos = last_func.find_first_of("::"); - std::string wrapper_func; - - if ( pos == std::string::npos ) - { - if ( ! starts_with_double_underscore(last_func) ) - { - emit(last_call.call); - return; - } - - wrapper_func = last_func.substr(2); - } - else - { - auto module_name = last_func.substr(0, pos); - auto func_name = last_func.substr(pos + 2); - - if ( ! starts_with_double_underscore(func_name) ) - { - emit(last_call.call); - return; - } - - wrapper_func = module_name + "::" + func_name.substr(2); - } - - auto parent_call = call_stack[call_stack.size() - 2]; - auto parent_func = parent_call.func->Name(); - - if ( wrapper_func == parent_func ) - emit(parent_call.call); - else - emit(last_call.call); - } - -#include "zeek.bif.func_h" -#include "stats.bif.func_h" -#include "reporter.bif.func_h" -#include "strings.bif.func_h" -#include "option.bif.func_h" -#include "supervisor.bif.func_h" - -#include "zeek.bif.func_def" -#include "stats.bif.func_def" -#include "reporter.bif.func_def" -#include "strings.bif.func_def" -#include "option.bif.func_def" -#include "supervisor.bif.func_def" - -#include "__all__.bif.cc" // Autogenerated for compiling in the bif_target() code. -#include "__all__.bif.register.cc" // Autogenerated for compiling in the bif_target() code. - -void init_builtin_funcs() - { - ProcStats = zeek::id::find_type("ProcStats"); - NetStats = zeek::id::find_type("NetStats"); - MatcherStats = zeek::id::find_type("MatcherStats"); - ConnStats = zeek::id::find_type("ConnStats"); - ReassemblerStats = zeek::id::find_type("ReassemblerStats"); - DNSStats = zeek::id::find_type("DNSStats"); - GapStats = zeek::id::find_type("GapStats"); - EventStats = zeek::id::find_type("EventStats"); - TimerStats = zeek::id::find_type("TimerStats"); - FileAnalysisStats = zeek::id::find_type("FileAnalysisStats"); - ThreadStats = zeek::id::find_type("ThreadStats"); - BrokerStats = zeek::id::find_type("BrokerStats"); - ReporterStats = zeek::id::find_type("ReporterStats"); - - var_sizes = zeek::id::find_type("var_sizes")->AsTableType(); - -#include "zeek.bif.func_init" -#include "stats.bif.func_init" -#include "reporter.bif.func_init" -#include "strings.bif.func_init" -#include "option.bif.func_init" -#include "supervisor.bif.func_init" - - did_builtin_init = true; - } - -void init_builtin_funcs_subdirs() -{ - #include "__all__.bif.init.cc" // Autogenerated for compiling in the bif_target() code. -} - bool check_built_in_call(BuiltinFunc* f, zeek::detail::CallExpr* call) { if ( f->TheFunc() != zeek::BifFunc::fmt_bif) @@ -844,7 +739,7 @@ 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 // problems. -static int get_func_priority(const std::vector>& attrs) +static int get_func_priority(const std::vector& attrs) { int priority = 0; @@ -879,7 +774,7 @@ static int get_func_priority(const std::vector> return priority; } -function_ingredients::function_ingredients(IntrusivePtr scope, IntrusivePtr body) +function_ingredients::function_ingredients(zeek::detail::ScopePtr scope, zeek::detail::StmtPtr body) { frame_size = scope->Length(); inits = scope->GetInits(); @@ -892,3 +787,134 @@ function_ingredients::function_ingredients(IntrusivePtr scope, IntrusiveP priority = (attrs ? get_func_priority(*attrs) : 0); this->body = std::move(body); } + +} // namespace detail + +void emit_builtin_error(const char* msg) + { + emit_builtin_error(msg, zeek::ValPtr{}); + } + +void emit_builtin_error(const char* msg, zeek::ValPtr arg) + { + emit_builtin_error(msg, arg.get()); + } + +void emit_builtin_error(const char* msg, Obj* arg) + { + auto emit = [=](const zeek::detail::CallExpr* ce) + { + if ( ce ) + ce->Error(msg, arg); + else + reporter->Error(msg, arg); + }; + + + if ( zeek::detail::call_stack.empty() ) + { + emit(nullptr); + return; + } + + auto last_call = zeek::detail::call_stack.back(); + + if ( zeek::detail::call_stack.size() < 2 ) + { + // Don't need to check for wrapper function like "::__" + emit(last_call.call); + return; + } + + auto starts_with_double_underscore = [](const std::string& name) -> bool + { return name.size() > 2 && name[0] == '_' && name[1] == '_'; }; + std::string last_func = last_call.func->Name(); + + auto pos = last_func.find_first_of("::"); + std::string wrapper_func; + + if ( pos == std::string::npos ) + { + if ( ! starts_with_double_underscore(last_func) ) + { + emit(last_call.call); + return; + } + + wrapper_func = last_func.substr(2); + } + else + { + auto module_name = last_func.substr(0, pos); + auto func_name = last_func.substr(pos + 2); + + if ( ! starts_with_double_underscore(func_name) ) + { + emit(last_call.call); + return; + } + + wrapper_func = module_name + "::" + func_name.substr(2); + } + + auto parent_call = zeek::detail::call_stack[zeek::detail::call_stack.size() - 2]; + auto parent_func = parent_call.func->Name(); + + if ( wrapper_func == parent_func ) + emit(parent_call.call); + else + emit(last_call.call); + } + +} // namespace zeek + +void builtin_error(const char* msg) + { + zeek::emit_builtin_error(msg); + } + +void builtin_error(const char* msg, zeek::ValPtr arg) + { + zeek::emit_builtin_error(msg, arg); + } + +void builtin_error(const char* msg, zeek::Obj* arg) + { + zeek::emit_builtin_error(msg, arg); + } + +#include "__all__.bif.cc" // Autogenerated for compiling in the bif_target() code. +#include "__all__.bif.register.cc" // Autogenerated for compiling in the bif_target() code. + +void init_builtin_funcs() + { + ProcStats = zeek::id::find_type("ProcStats"); + NetStats = zeek::id::find_type("NetStats"); + MatcherStats = zeek::id::find_type("MatcherStats"); + ConnStats = zeek::id::find_type("ConnStats"); + ReassemblerStats = zeek::id::find_type("ReassemblerStats"); + DNSStats = zeek::id::find_type("DNSStats"); + GapStats = zeek::id::find_type("GapStats"); + EventStats = zeek::id::find_type("EventStats"); + TimerStats = zeek::id::find_type("TimerStats"); + FileAnalysisStats = zeek::id::find_type("FileAnalysisStats"); + ThreadStats = zeek::id::find_type("ThreadStats"); + BrokerStats = zeek::id::find_type("BrokerStats"); + ReporterStats = zeek::id::find_type("ReporterStats"); + + var_sizes = zeek::id::find_type("var_sizes")->AsTableType(); + +#include "zeek.bif.func_init" +#include "stats.bif.func_init" +#include "reporter.bif.func_init" +#include "strings.bif.func_init" +#include "option.bif.func_init" +#include "supervisor.bif.func_init" + + zeek::detail::did_builtin_init = true; + } + +void init_builtin_funcs_subdirs() + { +#include "__all__.bif.init.cc" // Autogenerated for compiling in the bif_target() code. + } diff --git a/src/Func.h b/src/Func.h index b1a2eae796..2f3d703690 100644 --- a/src/Func.h +++ b/src/Func.h @@ -17,14 +17,19 @@ #include "ZeekArgs.h" #include "BifReturnVal.h" -class Val; -class Frame; -class Scope; - +ZEEK_FORWARD_DECLARE_NAMESPACED(Scope, zeek::detail); +ZEEK_FORWARD_DECLARE_NAMESPACED(Val, zeek); ZEEK_FORWARD_DECLARE_NAMESPACED(Stmt, zeek::detail); ZEEK_FORWARD_DECLARE_NAMESPACED(CallExpr, zeek::detail); ZEEK_FORWARD_DECLARE_NAMESPACED(ID, zeek::detail); ZEEK_FORWARD_DECLARE_NAMESPACED(FuncType, zeek); +ZEEK_FORWARD_DECLARE_NAMESPACED(Frame, zeek::detail); + +namespace zeek::detail { +using ScopePtr = zeek::IntrusivePtr; +using IDPtr = zeek::IntrusivePtr; +using StmtPtr = zeek::IntrusivePtr; +} namespace caf { template class expected; @@ -36,11 +41,18 @@ using vector = std::vector; using caf::expected; } -class Func : public BroObj { -public: - static inline const IntrusivePtr nil; +namespace zeek { - enum Kind { BRO_FUNC, BUILTIN_FUNC }; +class Func; +using FuncPtr = zeek::IntrusivePtr; + +class Func : public Obj { +public: + + static inline const FuncPtr nil; + + enum Kind { SCRIPT_FUNC, BUILTIN_FUNC }; + static constexpr auto BRO_FUNC [[deprecated("Remove in v4.1. Use Func::SCRIPT_FUNC instead.")]] = SCRIPT_FUNC; explicit Func(Kind arg_kind); @@ -50,7 +62,7 @@ public: zeek::FunctionFlavor Flavor() const { return GetType()->Flavor(); } struct Body { - IntrusivePtr stmts; + zeek::detail::StmtPtr stmts; int priority; bool operator<(const Body& other) const { return priority > other.priority; } // reverse sort @@ -60,7 +72,7 @@ public: bool HasBodies() const { return bodies.size(); } [[deprecated("Remove in v4.1. Use Invoke() instead.")]] - Val* Call(val_list* args, Frame* parent = nullptr) const; + zeek::Val* Call(val_list* args, zeek::detail::Frame* parent = nullptr) const; /** * Calls a Zeek function. @@ -68,17 +80,16 @@ public: * @param parent the frame from which the function is being called. * @return the return value of the function call. */ - virtual IntrusivePtr Invoke(zeek::Args* args, - Frame* parent = nullptr) const = 0; + virtual zeek::ValPtr Invoke( + zeek::Args* args, zeek::detail::Frame* parent = nullptr) const = 0; /** * A version of Invoke() taking a variable number of individual arguments. */ template std::enable_if_t< - std::is_convertible_v>, - IntrusivePtr>, - IntrusivePtr> + std::is_convertible_v>, zeek::ValPtr>, + zeek::ValPtr> Invoke(Args&&... args) const { auto zargs = zeek::Args{std::forward(args)...}; @@ -86,17 +97,17 @@ public: } // Add a new event handler to an existing function (event). - virtual void AddBody(IntrusivePtr new_body, - const std::vector>& new_inits, + virtual void AddBody(zeek::detail::StmtPtr new_body, + const std::vector& new_inits, size_t new_frame_size, int priority = 0); - virtual void SetScope(IntrusivePtr newscope); - virtual Scope* GetScope() const { return scope.get(); } + virtual void SetScope(zeek::detail::ScopePtr newscope); + virtual zeek::detail::Scope* GetScope() const { return scope.get(); } [[deprecated("Remove in v4.1. Use GetType().")]] virtual zeek::FuncType* FType() const { return type.get(); } - const IntrusivePtr& GetType() const + const zeek::FuncTypePtr& GetType() const { return type; } Kind GetKind() const { return kind; } @@ -107,12 +118,12 @@ public: void Describe(ODesc* d) const override = 0; virtual void DescribeDebug(ODesc* d, const zeek::Args* args) const; - virtual IntrusivePtr DoClone(); + virtual FuncPtr DoClone(); virtual TraversalCode Traverse(TraversalCallback* cb) const; uint32_t GetUniqueFuncID() const { return unique_id; } - static const IntrusivePtr& GetFuncPtrByID(uint32_t id) + static const FuncPtr& GetFuncPtrByID(uint32_t id) { return id >= unique_ids.size() ? Func::nil : unique_ids[id]; } protected: @@ -122,38 +133,39 @@ protected: void CopyStateInto(Func* other) const; // Helper function for checking result of plugin hook. - void CheckPluginResult(bool handled, const IntrusivePtr& hook_result, + void CheckPluginResult(bool handled, const zeek::ValPtr& hook_result, zeek::FunctionFlavor flavor) const; std::vector bodies; - IntrusivePtr scope; + zeek::detail::ScopePtr scope; Kind kind; uint32_t unique_id; - IntrusivePtr type; + zeek::FuncTypePtr type; std::string name; - static inline std::vector> unique_ids; + static inline std::vector unique_ids; }; +namespace detail { -class BroFunc final : public Func { +class ScriptFunc final : public zeek::Func { public: - BroFunc(const IntrusivePtr& id, IntrusivePtr body, - const std::vector>& inits, + ScriptFunc(const zeek::detail::IDPtr& id, zeek::detail::StmtPtr body, + const std::vector& inits, size_t frame_size, int priority); - ~BroFunc() override; + ~ScriptFunc() override; bool IsPure() const override; - IntrusivePtr Invoke(zeek::Args* args, Frame* parent) const override; + zeek::ValPtr Invoke(zeek::Args* args, zeek::detail::Frame* parent) const override; /** * Adds adds a closure to the function. Closures are cloned and - * future calls to BroFunc methods will not modify *f*. + * future calls to ScriptFunc methods will not modify *f*. * * @param ids IDs that are captured by the closure. * @param f the closure to be captured. */ - void AddClosure(id_list ids, Frame* f); + void AddClosure(id_list ids, zeek::detail::Frame* f); /** * Replaces the current closure with one built from *data* @@ -166,7 +178,7 @@ public: * 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. */ - bool StrengthenClosureReference(Frame* f); + bool StrengthenClosureReference(zeek::detail::Frame* f); /** * Serializes this function's closure. @@ -175,8 +187,8 @@ public: */ broker::expected SerializeClosure() const; - void AddBody(IntrusivePtr new_body, - const std::vector>& new_inits, + void AddBody(zeek::detail::StmtPtr new_body, + const std::vector& new_inits, size_t new_frame_size, int priority) override; /** Sets this function's outer_id list. */ @@ -186,15 +198,15 @@ public: void Describe(ODesc* d) const override; protected: - BroFunc() : Func(BRO_FUNC) {} - IntrusivePtr AddInits( - IntrusivePtr body, - const std::vector>& inits); + ScriptFunc() : zeek::Func(SCRIPT_FUNC) {} + zeek::detail::StmtPtr AddInits( + zeek::detail::StmtPtr body, + const std::vector& inits); /** * Clones this function along with its closures. */ - IntrusivePtr DoClone() override; + zeek::FuncPtr DoClone() override; /** * Performs a selective clone of *f* using the IDs that were @@ -202,27 +214,27 @@ protected: * * @param f the frame to be cloned. */ - void SetClosureFrame(Frame* f); + void SetClosureFrame(zeek::detail::Frame* f); private: size_t frame_size; // List of the outer IDs used in the function. id_list outer_ids; - // The frame the BroFunc was initialized in. - Frame* closure = nullptr; + // The frame the ScriptFunc was initialized in. + zeek::detail::Frame* closure = nullptr; bool weak_closure_ref = false; }; -using built_in_func = BifReturnVal (*)(Frame* frame, const zeek::Args* args); +using built_in_func = BifReturnVal (*)(zeek::detail::Frame* frame, const zeek::Args* args); -class BuiltinFunc final : public Func { +class BuiltinFunc final : public zeek::Func { public: BuiltinFunc(built_in_func func, const char* name, bool is_pure); ~BuiltinFunc() override; bool IsPure() const override; - IntrusivePtr Invoke(zeek::Args* args, Frame* parent) const override; + zeek::ValPtr Invoke(zeek::Args* args, zeek::detail::Frame* parent) const override; built_in_func TheFunc() const { return func; } void Describe(ODesc* d) const override; @@ -234,13 +246,6 @@ protected: bool is_pure; }; - -extern void builtin_error(const char* msg); -extern void builtin_error(const char* msg, IntrusivePtr); -extern void builtin_error(const char* msg, BroObj* arg); -extern void init_builtin_funcs(); -extern void init_builtin_funcs_subdirs(); - extern bool check_built_in_call(BuiltinFunc* f, zeek::detail::CallExpr* call); struct CallInfo { @@ -249,25 +254,59 @@ struct CallInfo { const zeek::Args& args; }; -// Struct that collects all the specifics defining a Func. Used for BroFuncs +// Struct that collects all the specifics defining a Func. Used for ScriptFuncs // with closures. struct function_ingredients { // Gathers all of the information from a scope and a function body needed // to build a function. - function_ingredients(IntrusivePtr scope, IntrusivePtr body); + function_ingredients(ScopePtr scope, StmtPtr body); - IntrusivePtr id; - IntrusivePtr body; - std::vector> inits; + IDPtr id; + StmtPtr body; + std::vector inits; int frame_size; int priority; - IntrusivePtr scope; + ScopePtr scope; }; extern std::vector call_stack; -extern std::string render_call_stack(); - // This is set to true after the built-in functions have been initialized. extern bool did_builtin_init; + +} // namespace detail + +extern std::string render_call_stack(); + +// 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, zeek::ValPtr); +extern void emit_builtin_error(const char* msg, Obj* arg); + +} // namespace zeek + +using Func [[deprecated("Remove in v4.1. Use zeek::Func.")]] = zeek::Func; +using BroFunc [[deprecated("Remove in v4.1. Use zeek::detail::ScriptFunc.")]] = zeek::detail::ScriptFunc; +using BuiltinFunc [[deprecated("Remove in v4.1. Use zeek::detail::BuiltinFunc.")]] = zeek::detail::BuiltinFunc; +using CallInfo [[deprecated("Remove in v4.1. Use zeek::detail::CallInfo.")]] = zeek::detail::CallInfo; +using function_ingredients [[deprecated("Remove in v4.1. Use zeek::detail::function_ingredients.")]] = zeek::detail::function_ingredients; + +constexpr auto check_built_in_call [[deprecated("Remove in v4.1. Use zeek::detail::check_built_in_call.")]] = zeek::detail::check_built_in_call; +constexpr auto render_call_stack [[deprecated("Remove in v4.1. Use zeek::render_call_stack.")]] = zeek::render_call_stack; + +// TODO: these are still here because of how all of the bif code gets included in Func.c. There could be a +// renamed version inside the namespace, but the way that the code gets included complicates the matter. It +// might need to be revisited after everything is namespaced everywhere else. +void init_builtin_funcs(); +void init_builtin_funcs_subdirs(); + +// TODO: do call_stack and did_builtin_init need to be aliased? + +// These have to be implemented as actual methods due to function overloading breaking the use of aliases. +[[deprecated("Remove in v4.1. Use zeek::emit_builtin_error.")]] +extern void builtin_error(const char* msg); +[[deprecated("Remove in v4.1. Use zeek::emit_builtin_error.")]] +extern void builtin_error(const char* msg, zeek::ValPtr); +[[deprecated("Remove in v4.1. Use zeek::emit_builtin_error.")]] +extern void builtin_error(const char* msg, zeek::Obj* arg); diff --git a/src/Hash.cc b/src/Hash.cc index ebc997f709..3735b4470d 100644 --- a/src/Hash.cc +++ b/src/Hash.cc @@ -5,7 +5,7 @@ #include "Hash.h" #include "digest.h" #include "Reporter.h" -#include "BroString.h" +#include "ZeekString.h" #include "Val.h" // needed for const.bif #include "const.bif.netvar_h" @@ -145,7 +145,7 @@ HashKey::HashKey(const char* s) hash = HashBytes(key, size); } -HashKey::HashKey(const BroString* s) +HashKey::HashKey(const zeek::String* s) { size = s->Len(); key = (void*) s->Bytes(); diff --git a/src/Hash.h b/src/Hash.h index 0bc4daeec0..3456eb0573 100644 --- a/src/Hash.h +++ b/src/Hash.h @@ -23,15 +23,17 @@ #include -class BroString; - // to allow bro_md5_hmac access to the hmac seed #include "ZeekArgs.h" -class Val; -class Frame; + +ZEEK_FORWARD_DECLARE_NAMESPACED(Frame, zeek::detail); + +namespace zeek { class String; } +using BroString [[deprecated("Remove in v4.1. Use zeek::String instead.")]] = zeek::String; + class BifReturnVal; namespace zeek::BifFunc { - extern BifReturnVal md5_hmac_bif(Frame* frame, const zeek::Args*); + extern BifReturnVal md5_hmac_bif(zeek::detail::Frame* frame, const zeek::Args*); } typedef uint64_t hash_t; @@ -196,7 +198,7 @@ private: inline static bool seeds_initialized = false; friend void hmac_md5(size_t size, const unsigned char* bytes, unsigned char digest[16]); - friend BifReturnVal zeek::BifFunc::md5_hmac_bif(Frame* frame, const zeek::Args*); + friend BifReturnVal zeek::BifFunc::md5_hmac_bif(zeek::detail::Frame* frame, const zeek::Args*); }; typedef enum { @@ -215,7 +217,7 @@ public: explicit HashKey(double d); explicit HashKey(const void* p); explicit HashKey(const char* s); - explicit HashKey(const BroString* s); + explicit HashKey(const zeek::String* s); ~HashKey() { if ( is_our_dynamic ) diff --git a/src/ID.cc b/src/ID.cc index 641b9a2ac7..ba184ccaec 100644 --- a/src/ID.cc +++ b/src/ID.cc @@ -1,3 +1,4 @@ + // See the file "COPYING" in the main distribution directory for copyright. #include "zeek-config.h" @@ -19,26 +20,26 @@ #include "zeekygen/ScriptInfo.h" #include "module_util.h" -IntrusivePtr zeek::id::conn_id; -IntrusivePtr zeek::id::endpoint; -IntrusivePtr zeek::id::connection; -IntrusivePtr zeek::id::fa_file; -IntrusivePtr zeek::id::fa_metadata; -IntrusivePtr zeek::id::transport_proto; -IntrusivePtr zeek::id::string_set; -IntrusivePtr zeek::id::string_array; -IntrusivePtr zeek::id::count_set; -IntrusivePtr zeek::id::string_vec; -IntrusivePtr zeek::id::index_vec; +zeek::RecordTypePtr zeek::id::conn_id; +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 IntrusivePtr& zeek::id::find(std::string_view name) +const zeek::detail::IDPtr& zeek::id::find(std::string_view name) { - return global_scope()->Find(name); + return zeek::detail::global_scope()->Find(name); } -const IntrusivePtr& zeek::id::find_type(std::string_view name) +const zeek::TypePtr& zeek::id::find_type(std::string_view name) { - auto id = global_scope()->Find(name); + auto id = zeek::detail::global_scope()->Find(name); if ( ! id ) reporter->InternalError("Failed to find type named: %s", @@ -47,9 +48,9 @@ const IntrusivePtr& zeek::id::find_type(std::string_view name) return id->GetType(); } -const IntrusivePtr& zeek::id::find_val(std::string_view name) +const zeek::ValPtr& zeek::id::find_val(std::string_view name) { - auto id = global_scope()->Find(name); + auto id = zeek::detail::global_scope()->Find(name); if ( ! id ) reporter->InternalError("Failed to find variable named: %s", @@ -58,9 +59,9 @@ const IntrusivePtr& zeek::id::find_val(std::string_view name) return id->GetVal(); } -const IntrusivePtr& zeek::id::find_const(std::string_view name) +const zeek::ValPtr& zeek::id::find_const(std::string_view name) { - auto id = global_scope()->Find(name); + auto id = zeek::detail::global_scope()->Find(name); if ( ! id ) reporter->InternalError("Failed to find variable named: %s", @@ -73,7 +74,7 @@ const IntrusivePtr& zeek::id::find_const(std::string_view name) return id->GetVal(); } -IntrusivePtr zeek::id::find_func(std::string_view name) +zeek::FuncPtr zeek::id::find_func(std::string_view name) { const auto& v = zeek::id::find_val(name); @@ -130,7 +131,7 @@ std::string ID::ModuleName() const return extract_module_name(name); } -void ID::SetType(IntrusivePtr t) +void ID::SetType(zeek::TypePtr t) { type = std::move(t); } @@ -140,7 +141,7 @@ void ID::ClearVal() val = nullptr; } -void ID::SetVal(IntrusivePtr v) +void ID::SetVal(zeek::ValPtr v) { val = std::move(v); Modified(); @@ -169,7 +170,7 @@ void ID::SetVal(IntrusivePtr v) } } -void ID::SetVal(IntrusivePtr v, InitClass c) +void ID::SetVal(zeek::ValPtr v, InitClass c) { if ( c == INIT_NONE || c == INIT_FULL ) { @@ -207,7 +208,7 @@ void ID::SetVal(IntrusivePtr v, InitClass c) } } -void ID::SetVal(IntrusivePtr ev, InitClass c) +void ID::SetVal(ExprPtr ev, InitClass c) { const auto& a = attrs->Find(c == INIT_EXTRA ? ATTR_ADD_FUNC : ATTR_DEL_FUNC); @@ -222,7 +223,7 @@ bool ID::IsRedefinable() const return GetAttr(ATTR_REDEF) != nullptr; } -void ID::SetAttrs(IntrusivePtr a) +void ID::SetAttrs(AttributesPtr a) { attrs = nullptr; AddAttrs(std::move(a)); @@ -260,15 +261,15 @@ void ID::UpdateValAttrs() TypeDecl* fd = rt->FieldDecl(i); if ( ! fd->attrs ) - fd->attrs = make_intrusive(rt->GetFieldType(i), true, IsGlobal()); + fd->attrs = zeek::make_intrusive(rt->GetFieldType(i), true, IsGlobal()); - fd->attrs->AddAttr(make_intrusive(ATTR_LOG)); + fd->attrs->AddAttr(zeek::make_intrusive(ATTR_LOG)); } } } } -const IntrusivePtr& ID::GetAttr(AttrTag t) const +const AttrPtr& ID::GetAttr(AttrTag t) const { return attrs ? attrs->Find(t) : Attr::nil; } @@ -278,13 +279,13 @@ bool ID::IsDeprecated() const return GetAttr(ATTR_DEPRECATED) != nullptr; } -void ID::MakeDeprecated(IntrusivePtr deprecation) +void ID::MakeDeprecated(ExprPtr deprecation) { if ( IsDeprecated() ) return; - std::vector> attrv{make_intrusive(ATTR_DEPRECATED, std::move(deprecation))}; - AddAttrs(make_intrusive(std::move(attrv), GetType(), false, IsGlobal())); + std::vector attrv{zeek::make_intrusive(ATTR_DEPRECATED, std::move(deprecation))}; + AddAttrs(zeek::make_intrusive(std::move(attrv), GetType(), false, IsGlobal())); } std::string ID::GetDeprecationWarning() const @@ -308,7 +309,7 @@ std::string ID::GetDeprecationWarning() const return fmt("deprecated (%s): %s", Name(), result.c_str()); } -void ID::AddAttrs(IntrusivePtr a) +void ID::AddAttrs(AttributesPtr a) { if ( attrs ) attrs->AddAttrs(a); @@ -334,18 +335,18 @@ void ID::SetOption() // option implied redefinable if ( ! IsRedefinable() ) { - std::vector> attrv{make_intrusive(ATTR_REDEF)}; - AddAttrs(make_intrusive(std::move(attrv), GetType(), false, IsGlobal())); + std::vector attrv{zeek::make_intrusive(ATTR_REDEF)}; + AddAttrs(zeek::make_intrusive(std::move(attrv), GetType(), false, IsGlobal())); } } -void ID::EvalFunc(IntrusivePtr ef, IntrusivePtr ev) +void ID::EvalFunc(ExprPtr ef, ExprPtr ev) { - auto arg1 = make_intrusive(val); - auto args = make_intrusive(); + auto arg1 = zeek::make_intrusive(val); + auto args = zeek::make_intrusive(); args->Append(std::move(arg1)); args->Append(std::move(ev)); - auto ce = make_intrusive(std::move(ef), std::move(args)); + auto ce = zeek::make_intrusive(std::move(ef), std::move(args)); SetVal(ce->Eval(nullptr)); } @@ -365,7 +366,7 @@ TraversalCode ID::Traverse(TraversalCallback* cb) const // FIXME: Perhaps we should be checking at other than global scope. else if ( val && IsFunc(val->GetType()->Tag()) && - cb->current_scope == global_scope() ) + cb->current_scope == zeek::detail::global_scope() ) { tc = val->AsFunc()->Traverse(cb); HANDLE_TC_STMT_PRE(tc); @@ -384,9 +385,9 @@ TraversalCode ID::Traverse(TraversalCallback* cb) const HANDLE_TC_EXPR_POST(tc); } -void ID::Error(const char* msg, const BroObj* o2) +void ID::Error(const char* msg, const Obj* o2) { - BroObj::Error(msg, o2, true); + Obj::Error(msg, o2, true); SetType(error_type()); } @@ -642,7 +643,7 @@ void ID::UpdateValID() } #endif -void ID::AddOptionHandler(IntrusivePtr callback, int priority) +void ID::AddOptionHandler(zeek::FuncPtr callback, int priority) { option_handlers.emplace(priority, std::move(callback)); } diff --git a/src/ID.h b/src/ID.h index 275a71559a..d1996ba695 100644 --- a/src/ID.h +++ b/src/ID.h @@ -13,28 +13,41 @@ #include #include -class Val; -class Func; - -namespace zeek { class Type; } -using BroType [[deprecated("Remove in v4.1. Use zeek::Type instead.")]] = zeek::Type; - +ZEEK_FORWARD_DECLARE_NAMESPACED(Func, zeek); +ZEEK_FORWARD_DECLARE_NAMESPACED(Val, zeek); ZEEK_FORWARD_DECLARE_NAMESPACED(RecordType, zeek); ZEEK_FORWARD_DECLARE_NAMESPACED(TableType, zeek); ZEEK_FORWARD_DECLARE_NAMESPACED(VectorType, zeek); ZEEK_FORWARD_DECLARE_NAMESPACED(EnumType, zeek); +namespace zeek { +class Type; +using TypePtr = zeek::IntrusivePtr; +using RecordTypePtr = zeek::IntrusivePtr; +using TableTypePtr = zeek::IntrusivePtr; +using VectorTypePtr = zeek::IntrusivePtr; +using EnumTypePtr = zeek::IntrusivePtr; +using ValPtr = zeek::IntrusivePtr; +using FuncPtr = zeek::IntrusivePtr; +} + +using BroType [[deprecated("Remove in v4.1. Use zeek::Type instead.")]] = zeek::Type; + namespace zeek::detail { class Attributes; class Expr; +using ExprPtr = zeek::IntrusivePtr; enum InitClass { INIT_NONE, INIT_FULL, INIT_EXTRA, INIT_REMOVE, }; enum IDScope { SCOPE_FUNCTION, SCOPE_MODULE, SCOPE_GLOBAL }; -class ID final : public BroObj, public notifier::Modifiable { +class ID; +using IDPtr = zeek::IntrusivePtr; + +class ID final : public Obj, public notifier::Modifiable { public: - static inline const IntrusivePtr nil; + static inline const IDPtr nil; ID(const char* name, IDScope arg_scope, bool arg_is_export); @@ -50,19 +63,19 @@ public: std::string ModuleName() const; - void SetType(IntrusivePtr t); + void SetType(TypePtr t); [[deprecated("Remove in v4.1. Use GetType().")]] zeek::Type* Type() { return type.get(); } [[deprecated("Remove in v4.1. Use GetType().")]] const zeek::Type* Type() const { return type.get(); } - const IntrusivePtr& GetType() const + const TypePtr& GetType() const { return type; } template - IntrusivePtr GetType() const - { return cast_intrusive(type); } + zeek::IntrusivePtr GetType() const + { return zeek::cast_intrusive(type); } [[deprecated("Remove in v4.1. Use IsType() and GetType().")]] zeek::Type* AsType() { return is_type ? GetType().get() : nullptr; } @@ -74,10 +87,10 @@ public: void MakeType() { is_type = true; } - void SetVal(IntrusivePtr v); + void SetVal(ValPtr v); - void SetVal(IntrusivePtr v, InitClass c); - void SetVal(IntrusivePtr ev, InitClass c); + void SetVal(ValPtr v, InitClass c); + void SetVal(ExprPtr ev, InitClass c); bool HasVal() const { return val != nullptr; } @@ -86,7 +99,7 @@ public: [[deprecated("Remove in v4.1. Use GetVal().")]] const Val* ID_Val() const { return val.get(); } - const IntrusivePtr& GetVal() const + const ValPtr& GetVal() const { return val; } void ClearVal(); @@ -105,26 +118,26 @@ public: bool IsRedefinable() const; - void SetAttrs(IntrusivePtr attr); - void AddAttrs(IntrusivePtr attr); - void RemoveAttr(zeek::detail::AttrTag a); + void SetAttrs(AttributesPtr attr); + void AddAttrs(AttributesPtr attr); + void RemoveAttr(AttrTag a); void UpdateValAttrs(); - const IntrusivePtr& GetAttrs() const + const AttributesPtr& GetAttrs() const { return attrs; } [[deprecated("Remove in 4.1. Use GetAttrs().")]] Attributes* Attrs() const { return attrs.get(); } - const IntrusivePtr& GetAttr(zeek::detail::AttrTag t) const; + const AttrPtr& GetAttr(zeek::detail::AttrTag t) const; bool IsDeprecated() const; - void MakeDeprecated(IntrusivePtr deprecation); + void MakeDeprecated(ExprPtr deprecation); std::string GetDeprecationWarning() const; - void Error(const char* msg, const BroObj* o2 = nullptr); + void Error(const char* msg, const Obj* o2 = nullptr); void Describe(ODesc* d) const override; // Adds type and value to description. @@ -143,11 +156,11 @@ public: bool HasOptionHandlers() const { return !option_handlers.empty(); } - void AddOptionHandler(IntrusivePtr callback, int priority); + void AddOptionHandler(zeek::FuncPtr callback, int priority); std::vector GetOptionHandlers() const; protected: - void EvalFunc(IntrusivePtr ef, IntrusivePtr ev); + void EvalFunc(ExprPtr ef, ExprPtr ev); #ifdef DEBUG void UpdateValID(); @@ -157,13 +170,13 @@ protected: IDScope scope; bool is_export; bool infer_return_type; - IntrusivePtr type; + TypePtr type; bool is_const, is_enum_const, is_type, is_option; int offset; - IntrusivePtr val; - IntrusivePtr attrs; + ValPtr val; + AttributesPtr attrs; // contains list of functions that are called when an option changes - std::multimap> option_handlers; + std::multimap option_handlers; }; @@ -179,7 +192,7 @@ namespace zeek::id { * @return The identifier, which may reference a nil object if no such * name exists. */ -const IntrusivePtr& find(std::string_view name); +const detail::IDPtr& find(std::string_view name); /** * Lookup an ID by its name and return its type. A fatal occurs if the ID @@ -187,7 +200,7 @@ const IntrusivePtr& find(std::string_view name); * @param name The identifier name to lookup * @return The type of the identifier. */ -const IntrusivePtr& find_type(std::string_view name); +const TypePtr& find_type(std::string_view name); /** * Lookup an ID by its name and return its type (as cast to @c T). @@ -196,8 +209,8 @@ const IntrusivePtr& find_type(std::string_view name); * @return The type of the identifier. */ template -IntrusivePtr find_type(std::string_view name) - { return cast_intrusive(find_type(name)); } +zeek::IntrusivePtr find_type(std::string_view name) + { return zeek::cast_intrusive(find_type(name)); } /** * Lookup an ID by its name and return its value. A fatal occurs if the ID @@ -205,7 +218,7 @@ IntrusivePtr find_type(std::string_view name) * @param name The identifier name to lookup * @return The current value of the identifier */ -const IntrusivePtr& find_val(std::string_view name); +const ValPtr& find_val(std::string_view name); /** * Lookup an ID by its name and return its value (as cast to @c T). @@ -214,8 +227,8 @@ const IntrusivePtr& find_val(std::string_view name); * @return The current value of the identifier. */ template -IntrusivePtr find_val(std::string_view name) - { return cast_intrusive(find_val(name)); } +zeek::IntrusivePtr find_val(std::string_view name) + { return zeek::cast_intrusive(find_val(name)); } /** * Lookup an ID by its name and return its value. A fatal occurs if the ID @@ -223,7 +236,7 @@ IntrusivePtr find_val(std::string_view name) * @param name The identifier name to lookup * @return The current value of the identifier */ -const IntrusivePtr& find_const(std::string_view name); +const ValPtr& find_const(std::string_view name); /** * Lookup an ID by its name and return its value (as cast to @c T). @@ -232,8 +245,8 @@ const IntrusivePtr& find_const(std::string_view name); * @return The current value of the identifier. */ template -IntrusivePtr find_const(std::string_view name) - { return cast_intrusive(find_const(name)); } +zeek::IntrusivePtr find_const(std::string_view name) + { return zeek::cast_intrusive(find_const(name)); } /** * Lookup an ID by its name and return the function it references. @@ -241,19 +254,19 @@ IntrusivePtr find_const(std::string_view name) * @param name The identifier name to lookup * @return The current function value the identifier references. */ -IntrusivePtr find_func(std::string_view name); +zeek::FuncPtr find_func(std::string_view name); -extern IntrusivePtr conn_id; -extern IntrusivePtr endpoint; -extern IntrusivePtr connection; -extern IntrusivePtr fa_file; -extern IntrusivePtr fa_metadata; -extern IntrusivePtr transport_proto; -extern IntrusivePtr string_set; -extern IntrusivePtr string_array; -extern IntrusivePtr count_set; -extern IntrusivePtr string_vec; -extern IntrusivePtr index_vec; +extern RecordTypePtr conn_id; +extern RecordTypePtr endpoint; +extern RecordTypePtr connection; +extern RecordTypePtr fa_file; +extern RecordTypePtr fa_metadata; +extern EnumTypePtr transport_proto; +extern TableTypePtr string_set; +extern TableTypePtr string_array; +extern TableTypePtr count_set; +extern VectorTypePtr string_vec; +extern VectorTypePtr index_vec; namespace detail { @@ -263,6 +276,8 @@ void init(); } // namespace zeek::id +using ID [[deprecated("Remove in v4.1 Use zeek::detail::ID instead.")]] = zeek::detail::ID; + using init_class [[deprecated("Remove in v4.1. Use zeek::detail::InitClass instead.")]] = zeek::detail::InitClass; [[deprecated("Remove in v4.1. Use zeek::detail::INIT_NONE instead.")]] constexpr auto INIT_NONE = zeek::detail::INIT_NONE; diff --git a/src/IP.cc b/src/IP.cc index 098ba3f468..422689239a 100644 --- a/src/IP.cc +++ b/src/IP.cc @@ -10,25 +10,25 @@ #include "Type.h" #include "Val.h" #include "Var.h" -#include "BroString.h" +#include "ZeekString.h" #include "Reporter.h" -static IntrusivePtr BuildOptionsVal(const u_char* data, int len) +static zeek::VectorValPtr BuildOptionsVal(const u_char* data, int len) { - auto vv = make_intrusive(zeek::id::find_type("ip6_options")); + auto vv = zeek::make_intrusive(zeek::id::find_type("ip6_options")); while ( len > 0 ) { static auto ip6_option_type = zeek::id::find_type("ip6_option"); const struct ip6_opt* opt = (const struct ip6_opt*) data; - auto rv = make_intrusive(ip6_option_type); - rv->Assign(0, val_mgr->Count(opt->ip6o_type)); + auto rv = zeek::make_intrusive(ip6_option_type); + rv->Assign(0, zeek::val_mgr->Count(opt->ip6o_type)); if ( opt->ip6o_type == 0 ) { // Pad1 option - rv->Assign(1, val_mgr->Count(0)); - rv->Assign(2, val_mgr->EmptyString()); + rv->Assign(1, zeek::val_mgr->Count(0)); + rv->Assign(2, zeek::val_mgr->EmptyString()); data += sizeof(uint8_t); len -= sizeof(uint8_t); } @@ -36,9 +36,9 @@ static IntrusivePtr BuildOptionsVal(const u_char* data, int len) { // PadN or other option uint16_t off = 2 * sizeof(uint8_t); - rv->Assign(1, val_mgr->Count(opt->ip6o_len)); - rv->Assign(2, make_intrusive( - new BroString(data + off, opt->ip6o_len, true))); + rv->Assign(1, zeek::val_mgr->Count(opt->ip6o_len)); + rv->Assign(2, zeek::make_intrusive( + new zeek::String(data + off, opt->ip6o_len, true))); data += opt->ip6o_len + off; len -= opt->ip6o_len + off; } @@ -49,25 +49,25 @@ static IntrusivePtr BuildOptionsVal(const u_char* data, int len) return vv; } -IntrusivePtr IPv6_Hdr::ToVal(IntrusivePtr chain) const +zeek::RecordValPtr IPv6_Hdr::ToVal(zeek::VectorValPtr chain) const { - IntrusivePtr rv; + zeek::RecordValPtr rv; switch ( type ) { case IPPROTO_IPV6: { static auto ip6_hdr_type = zeek::id::find_type("ip6_hdr"); - rv = make_intrusive(ip6_hdr_type); + rv = zeek::make_intrusive(ip6_hdr_type); const struct ip6_hdr* ip6 = (const struct ip6_hdr*)data; - rv->Assign(0, val_mgr->Count((ntohl(ip6->ip6_flow) & 0x0ff00000)>>20)); - rv->Assign(1, val_mgr->Count(ntohl(ip6->ip6_flow) & 0x000fffff)); - rv->Assign(2, val_mgr->Count(ntohs(ip6->ip6_plen))); - rv->Assign(3, val_mgr->Count(ip6->ip6_nxt)); - rv->Assign(4, val_mgr->Count(ip6->ip6_hlim)); - rv->Assign(5, make_intrusive(IPAddr(ip6->ip6_src))); - rv->Assign(6, make_intrusive(IPAddr(ip6->ip6_dst))); + rv->Assign(0, zeek::val_mgr->Count((ntohl(ip6->ip6_flow) & 0x0ff00000)>>20)); + rv->Assign(1, zeek::val_mgr->Count(ntohl(ip6->ip6_flow) & 0x000fffff)); + rv->Assign(2, zeek::val_mgr->Count(ntohs(ip6->ip6_plen))); + rv->Assign(3, zeek::val_mgr->Count(ip6->ip6_nxt)); + rv->Assign(4, zeek::val_mgr->Count(ip6->ip6_hlim)); + rv->Assign(5, zeek::make_intrusive(IPAddr(ip6->ip6_src))); + rv->Assign(6, zeek::make_intrusive(IPAddr(ip6->ip6_dst))); if ( ! chain ) - chain = make_intrusive( + chain = zeek::make_intrusive( zeek::id::find_type("ip6_ext_hdr_chain")); rv->Assign(7, std::move(chain)); } @@ -76,10 +76,10 @@ IntrusivePtr IPv6_Hdr::ToVal(IntrusivePtr chain) const case IPPROTO_HOPOPTS: { static auto ip6_hopopts_type = zeek::id::find_type("ip6_hopopts"); - rv = make_intrusive(ip6_hopopts_type); + rv = zeek::make_intrusive(ip6_hopopts_type); const struct ip6_hbh* hbh = (const struct ip6_hbh*)data; - rv->Assign(0, val_mgr->Count(hbh->ip6h_nxt)); - rv->Assign(1, val_mgr->Count(hbh->ip6h_len)); + rv->Assign(0, zeek::val_mgr->Count(hbh->ip6h_nxt)); + rv->Assign(1, zeek::val_mgr->Count(hbh->ip6h_len)); uint16_t off = 2 * sizeof(uint8_t); rv->Assign(2, BuildOptionsVal(data + off, Length() - off)); @@ -89,10 +89,10 @@ IntrusivePtr IPv6_Hdr::ToVal(IntrusivePtr chain) const case IPPROTO_DSTOPTS: { static auto ip6_dstopts_type = zeek::id::find_type("ip6_dstopts"); - rv = make_intrusive(ip6_dstopts_type); + rv = zeek::make_intrusive(ip6_dstopts_type); const struct ip6_dest* dst = (const struct ip6_dest*)data; - rv->Assign(0, val_mgr->Count(dst->ip6d_nxt)); - rv->Assign(1, val_mgr->Count(dst->ip6d_len)); + rv->Assign(0, zeek::val_mgr->Count(dst->ip6d_nxt)); + rv->Assign(1, zeek::val_mgr->Count(dst->ip6d_len)); uint16_t off = 2 * sizeof(uint8_t); rv->Assign(2, BuildOptionsVal(data + off, Length() - off)); } @@ -101,47 +101,47 @@ IntrusivePtr IPv6_Hdr::ToVal(IntrusivePtr chain) const case IPPROTO_ROUTING: { static auto ip6_routing_type = zeek::id::find_type("ip6_routing"); - rv = make_intrusive(ip6_routing_type); + rv = zeek::make_intrusive(ip6_routing_type); const struct ip6_rthdr* rt = (const struct ip6_rthdr*)data; - rv->Assign(0, val_mgr->Count(rt->ip6r_nxt)); - rv->Assign(1, val_mgr->Count(rt->ip6r_len)); - rv->Assign(2, val_mgr->Count(rt->ip6r_type)); - rv->Assign(3, val_mgr->Count(rt->ip6r_segleft)); + rv->Assign(0, zeek::val_mgr->Count(rt->ip6r_nxt)); + rv->Assign(1, zeek::val_mgr->Count(rt->ip6r_len)); + rv->Assign(2, zeek::val_mgr->Count(rt->ip6r_type)); + rv->Assign(3, zeek::val_mgr->Count(rt->ip6r_segleft)); uint16_t off = 4 * sizeof(uint8_t); - rv->Assign(4, make_intrusive(new BroString(data + off, Length() - off, true))); + rv->Assign(4, zeek::make_intrusive(new zeek::String(data + off, Length() - off, true))); } break; case IPPROTO_FRAGMENT: { static auto ip6_fragment_type = zeek::id::find_type("ip6_fragment"); - rv = make_intrusive(ip6_fragment_type); + rv = zeek::make_intrusive(ip6_fragment_type); const struct ip6_frag* frag = (const struct ip6_frag*)data; - rv->Assign(0, val_mgr->Count(frag->ip6f_nxt)); - rv->Assign(1, val_mgr->Count(frag->ip6f_reserved)); - rv->Assign(2, val_mgr->Count((ntohs(frag->ip6f_offlg) & 0xfff8)>>3)); - rv->Assign(3, val_mgr->Count((ntohs(frag->ip6f_offlg) & 0x0006)>>1)); - rv->Assign(4, val_mgr->Bool(ntohs(frag->ip6f_offlg) & 0x0001)); - rv->Assign(5, val_mgr->Count(ntohl(frag->ip6f_ident))); + rv->Assign(0, zeek::val_mgr->Count(frag->ip6f_nxt)); + rv->Assign(1, zeek::val_mgr->Count(frag->ip6f_reserved)); + rv->Assign(2, zeek::val_mgr->Count((ntohs(frag->ip6f_offlg) & 0xfff8)>>3)); + rv->Assign(3, zeek::val_mgr->Count((ntohs(frag->ip6f_offlg) & 0x0006)>>1)); + rv->Assign(4, zeek::val_mgr->Bool(ntohs(frag->ip6f_offlg) & 0x0001)); + rv->Assign(5, zeek::val_mgr->Count(ntohl(frag->ip6f_ident))); } break; case IPPROTO_AH: { static auto ip6_ah_type = zeek::id::find_type("ip6_ah"); - rv = make_intrusive(ip6_ah_type); - rv->Assign(0, val_mgr->Count(((ip6_ext*)data)->ip6e_nxt)); - rv->Assign(1, val_mgr->Count(((ip6_ext*)data)->ip6e_len)); - rv->Assign(2, val_mgr->Count(ntohs(((uint16_t*)data)[1]))); - rv->Assign(3, val_mgr->Count(ntohl(((uint32_t*)data)[1]))); + rv = zeek::make_intrusive(ip6_ah_type); + rv->Assign(0, zeek::val_mgr->Count(((ip6_ext*)data)->ip6e_nxt)); + rv->Assign(1, zeek::val_mgr->Count(((ip6_ext*)data)->ip6e_len)); + rv->Assign(2, zeek::val_mgr->Count(ntohs(((uint16_t*)data)[1]))); + rv->Assign(3, zeek::val_mgr->Count(ntohl(((uint32_t*)data)[1]))); if ( Length() >= 12 ) { // Sequence Number and ICV fields can only be extracted if // Payload Len was non-zero for this header. - rv->Assign(4, val_mgr->Count(ntohl(((uint32_t*)data)[2]))); + rv->Assign(4, zeek::val_mgr->Count(ntohl(((uint32_t*)data)[2]))); uint16_t off = 3 * sizeof(uint32_t); - rv->Assign(5, make_intrusive(new BroString(data + off, Length() - off, true))); + rv->Assign(5, zeek::make_intrusive(new zeek::String(data + off, Length() - off, true))); } } break; @@ -149,10 +149,10 @@ IntrusivePtr IPv6_Hdr::ToVal(IntrusivePtr chain) const case IPPROTO_ESP: { static auto ip6_esp_type = zeek::id::find_type("ip6_esp"); - rv = make_intrusive(ip6_esp_type); + rv = zeek::make_intrusive(ip6_esp_type); const uint32_t* esp = (const uint32_t*)data; - rv->Assign(0, val_mgr->Count(ntohl(esp[0]))); - rv->Assign(1, val_mgr->Count(ntohl(esp[1]))); + rv->Assign(0, zeek::val_mgr->Count(ntohl(esp[0]))); + rv->Assign(1, zeek::val_mgr->Count(ntohl(esp[1]))); } break; @@ -160,17 +160,17 @@ IntrusivePtr IPv6_Hdr::ToVal(IntrusivePtr chain) const case IPPROTO_MOBILITY: { static auto ip6_mob_type = zeek::id::find_type("ip6_mobility_hdr"); - rv = make_intrusive(ip6_mob_type); + rv = zeek::make_intrusive(ip6_mob_type); const struct ip6_mobility* mob = (const struct ip6_mobility*) data; - rv->Assign(0, val_mgr->Count(mob->ip6mob_payload)); - rv->Assign(1, val_mgr->Count(mob->ip6mob_len)); - rv->Assign(2, val_mgr->Count(mob->ip6mob_type)); - rv->Assign(3, val_mgr->Count(mob->ip6mob_rsv)); - rv->Assign(4, val_mgr->Count(ntohs(mob->ip6mob_chksum))); + rv->Assign(0, zeek::val_mgr->Count(mob->ip6mob_payload)); + rv->Assign(1, zeek::val_mgr->Count(mob->ip6mob_len)); + rv->Assign(2, zeek::val_mgr->Count(mob->ip6mob_type)); + rv->Assign(3, zeek::val_mgr->Count(mob->ip6mob_rsv)); + rv->Assign(4, zeek::val_mgr->Count(ntohs(mob->ip6mob_chksum))); static auto ip6_mob_msg_type = zeek::id::find_type("ip6_mobility_msg"); - auto msg = make_intrusive(ip6_mob_msg_type); - msg->Assign(0, val_mgr->Count(mob->ip6mob_type)); + auto msg = zeek::make_intrusive(ip6_mob_msg_type); + msg->Assign(0, zeek::val_mgr->Count(mob->ip6mob_type)); uint16_t off = sizeof(ip6_mobility); const u_char* msg_data = data + off; @@ -187,8 +187,8 @@ IntrusivePtr IPv6_Hdr::ToVal(IntrusivePtr chain) const switch ( mob->ip6mob_type ) { case 0: { - auto m = make_intrusive(ip6_mob_brr_type); - m->Assign(0, val_mgr->Count(ntohs(*((uint16_t*)msg_data)))); + auto m = zeek::make_intrusive(ip6_mob_brr_type); + m->Assign(0, zeek::val_mgr->Count(ntohs(*((uint16_t*)msg_data)))); off += sizeof(uint16_t); m->Assign(1, BuildOptionsVal(data + off, Length() - off)); msg->Assign(1, std::move(m)); @@ -197,9 +197,9 @@ IntrusivePtr IPv6_Hdr::ToVal(IntrusivePtr chain) const case 1: { - auto m = make_intrusive(ip6_mobility_hoti_type); - m->Assign(0, val_mgr->Count(ntohs(*((uint16_t*)msg_data)))); - m->Assign(1, val_mgr->Count(ntohll(*((uint64_t*)(msg_data + sizeof(uint16_t)))))); + auto m = zeek::make_intrusive(ip6_mobility_hoti_type); + m->Assign(0, zeek::val_mgr->Count(ntohs(*((uint16_t*)msg_data)))); + m->Assign(1, zeek::val_mgr->Count(ntohll(*((uint64_t*)(msg_data + sizeof(uint16_t)))))); off += sizeof(uint16_t) + sizeof(uint64_t); m->Assign(2, BuildOptionsVal(data + off, Length() - off)); msg->Assign(2, std::move(m)); @@ -208,9 +208,9 @@ IntrusivePtr IPv6_Hdr::ToVal(IntrusivePtr chain) const case 2: { - auto m = make_intrusive(ip6_mobility_coti_type); - m->Assign(0, val_mgr->Count(ntohs(*((uint16_t*)msg_data)))); - m->Assign(1, val_mgr->Count(ntohll(*((uint64_t*)(msg_data + sizeof(uint16_t)))))); + auto m = zeek::make_intrusive(ip6_mobility_coti_type); + m->Assign(0, zeek::val_mgr->Count(ntohs(*((uint16_t*)msg_data)))); + m->Assign(1, zeek::val_mgr->Count(ntohll(*((uint64_t*)(msg_data + sizeof(uint16_t)))))); off += sizeof(uint16_t) + sizeof(uint64_t); m->Assign(2, BuildOptionsVal(data + off, Length() - off)); msg->Assign(3, std::move(m)); @@ -219,10 +219,10 @@ IntrusivePtr IPv6_Hdr::ToVal(IntrusivePtr chain) const case 3: { - auto m = make_intrusive(ip6_mobility_hot_type); - m->Assign(0, val_mgr->Count(ntohs(*((uint16_t*)msg_data)))); - m->Assign(1, val_mgr->Count(ntohll(*((uint64_t*)(msg_data + sizeof(uint16_t)))))); - m->Assign(2, val_mgr->Count(ntohll(*((uint64_t*)(msg_data + sizeof(uint16_t) + sizeof(uint64_t)))))); + auto m = zeek::make_intrusive(ip6_mobility_hot_type); + m->Assign(0, zeek::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(2, zeek::val_mgr->Count(ntohll(*((uint64_t*)(msg_data + sizeof(uint16_t) + sizeof(uint64_t)))))); off += sizeof(uint16_t) + 2 * sizeof(uint64_t); m->Assign(3, BuildOptionsVal(data + off, Length() - off)); msg->Assign(4, std::move(m)); @@ -231,10 +231,10 @@ IntrusivePtr IPv6_Hdr::ToVal(IntrusivePtr chain) const case 4: { - auto m = make_intrusive(ip6_mobility_cot_type); - m->Assign(0, val_mgr->Count(ntohs(*((uint16_t*)msg_data)))); - m->Assign(1, val_mgr->Count(ntohll(*((uint64_t*)(msg_data + sizeof(uint16_t)))))); - m->Assign(2, val_mgr->Count(ntohll(*((uint64_t*)(msg_data + sizeof(uint16_t) + sizeof(uint64_t)))))); + auto m = zeek::make_intrusive(ip6_mobility_cot_type); + m->Assign(0, zeek::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(2, zeek::val_mgr->Count(ntohll(*((uint64_t*)(msg_data + sizeof(uint16_t) + sizeof(uint64_t)))))); off += sizeof(uint16_t) + 2 * sizeof(uint64_t); m->Assign(3, BuildOptionsVal(data + off, Length() - off)); msg->Assign(5, std::move(m)); @@ -243,13 +243,13 @@ IntrusivePtr IPv6_Hdr::ToVal(IntrusivePtr chain) const case 5: { - auto m = make_intrusive(ip6_mobility_bu_type); - m->Assign(0, val_mgr->Count(ntohs(*((uint16_t*)msg_data)))); - m->Assign(1, val_mgr->Bool(ntohs(*((uint16_t*)(msg_data + sizeof(uint16_t)))) & 0x8000)); - m->Assign(2, val_mgr->Bool(ntohs(*((uint16_t*)(msg_data + sizeof(uint16_t)))) & 0x4000)); - m->Assign(3, val_mgr->Bool(ntohs(*((uint16_t*)(msg_data + sizeof(uint16_t)))) & 0x2000)); - m->Assign(4, val_mgr->Bool(ntohs(*((uint16_t*)(msg_data + sizeof(uint16_t)))) & 0x1000)); - m->Assign(5, val_mgr->Count(ntohs(*((uint16_t*)(msg_data + 2*sizeof(uint16_t)))))); + auto m = zeek::make_intrusive(ip6_mobility_bu_type); + m->Assign(0, zeek::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(2, zeek::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(4, zeek::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)))))); off += 3 * sizeof(uint16_t); m->Assign(6, BuildOptionsVal(data + off, Length() - off)); msg->Assign(6, std::move(m)); @@ -258,11 +258,11 @@ IntrusivePtr IPv6_Hdr::ToVal(IntrusivePtr chain) const case 6: { - auto m = make_intrusive(ip6_mobility_back_type); - m->Assign(0, val_mgr->Count(*((uint8_t*)msg_data))); - m->Assign(1, val_mgr->Bool(*((uint8_t*)(msg_data + sizeof(uint8_t))) & 0x80)); - m->Assign(2, val_mgr->Count(ntohs(*((uint16_t*)(msg_data + sizeof(uint16_t)))))); - m->Assign(3, val_mgr->Count(ntohs(*((uint16_t*)(msg_data + 2*sizeof(uint16_t)))))); + auto m = zeek::make_intrusive(ip6_mobility_back_type); + m->Assign(0, zeek::val_mgr->Count(*((uint8_t*)msg_data))); + m->Assign(1, zeek::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(3, zeek::val_mgr->Count(ntohs(*((uint16_t*)(msg_data + 2*sizeof(uint16_t)))))); off += 3 * sizeof(uint16_t); m->Assign(4, BuildOptionsVal(data + off, Length() - off)); msg->Assign(7, std::move(m)); @@ -271,10 +271,10 @@ IntrusivePtr IPv6_Hdr::ToVal(IntrusivePtr chain) const case 7: { - auto m = make_intrusive(ip6_mobility_be_type); - m->Assign(0, val_mgr->Count(*((uint8_t*)msg_data))); + auto m = zeek::make_intrusive(ip6_mobility_be_type); + m->Assign(0, zeek::val_mgr->Count(*((uint8_t*)msg_data))); const in6_addr* hoa = (const in6_addr*)(msg_data + sizeof(uint16_t)); - m->Assign(1, make_intrusive(IPAddr(*hoa))); + m->Assign(1, zeek::make_intrusive(IPAddr(*hoa))); off += sizeof(uint16_t) + sizeof(in6_addr); m->Assign(2, BuildOptionsVal(data + off, Length() - off)); msg->Assign(8, std::move(m)); @@ -298,12 +298,12 @@ IntrusivePtr IPv6_Hdr::ToVal(IntrusivePtr chain) const return rv; } -IntrusivePtr IPv6_Hdr::ToVal() const +zeek::RecordValPtr IPv6_Hdr::ToVal() const { return ToVal(nullptr); } -RecordVal* IPv6_Hdr::BuildRecordVal(VectorVal* chain) const +zeek::RecordVal* IPv6_Hdr::BuildRecordVal(zeek::VectorVal* chain) const { - return ToVal({AdoptRef{}, chain}).release(); + return ToVal({zeek::AdoptRef{}, chain}).release(); } IPAddr IP_Hdr::IPHeaderSrcAddr() const @@ -326,22 +326,22 @@ IPAddr IP_Hdr::DstAddr() const return ip4 ? IPAddr(ip4->ip_dst) : ip6_hdrs->DstAddr(); } -IntrusivePtr IP_Hdr::ToIPHdrVal() const +zeek::RecordValPtr IP_Hdr::ToIPHdrVal() const { - IntrusivePtr rval; + zeek::RecordValPtr rval; if ( ip4 ) { static auto ip4_hdr_type = zeek::id::find_type("ip4_hdr"); - rval = make_intrusive(ip4_hdr_type); - rval->Assign(0, val_mgr->Count(ip4->ip_hl * 4)); - rval->Assign(1, val_mgr->Count(ip4->ip_tos)); - rval->Assign(2, val_mgr->Count(ntohs(ip4->ip_len))); - rval->Assign(3, val_mgr->Count(ntohs(ip4->ip_id))); - rval->Assign(4, val_mgr->Count(ip4->ip_ttl)); - rval->Assign(5, val_mgr->Count(ip4->ip_p)); - rval->Assign(6, make_intrusive(ip4->ip_src.s_addr)); - rval->Assign(7, make_intrusive(ip4->ip_dst.s_addr)); + rval = zeek::make_intrusive(ip4_hdr_type); + rval->Assign(0, zeek::val_mgr->Count(ip4->ip_hl * 4)); + rval->Assign(1, zeek::val_mgr->Count(ip4->ip_tos)); + rval->Assign(2, zeek::val_mgr->Count(ntohs(ip4->ip_len))); + rval->Assign(3, zeek::val_mgr->Count(ntohs(ip4->ip_id))); + rval->Assign(4, zeek::val_mgr->Count(ip4->ip_ttl)); + rval->Assign(5, zeek::val_mgr->Count(ip4->ip_p)); + rval->Assign(6, zeek::make_intrusive(ip4->ip_src.s_addr)); + rval->Assign(7, zeek::make_intrusive(ip4->ip_dst.s_addr)); } else { @@ -351,23 +351,23 @@ IntrusivePtr IP_Hdr::ToIPHdrVal() const return rval; } -RecordVal* IP_Hdr::BuildIPHdrVal() const +zeek::RecordVal* IP_Hdr::BuildIPHdrVal() const { return ToIPHdrVal().release(); } -IntrusivePtr IP_Hdr::ToPktHdrVal() const +zeek::RecordValPtr IP_Hdr::ToPktHdrVal() const { static auto pkt_hdr_type = zeek::id::find_type("pkt_hdr"); - return ToPktHdrVal(make_intrusive(pkt_hdr_type), 0); + return ToPktHdrVal(zeek::make_intrusive(pkt_hdr_type), 0); } -RecordVal* IP_Hdr::BuildPktHdrVal() const +zeek::RecordVal* IP_Hdr::BuildPktHdrVal() const { return ToPktHdrVal().release(); } -IntrusivePtr IP_Hdr::ToPktHdrVal(IntrusivePtr pkt_hdr, int sindex) const +zeek::RecordValPtr IP_Hdr::ToPktHdrVal(zeek::RecordValPtr pkt_hdr, int sindex) const { static auto tcp_hdr_type = zeek::id::find_type("tcp_hdr"); static auto udp_hdr_type = zeek::id::find_type("udp_hdr"); @@ -386,20 +386,20 @@ IntrusivePtr IP_Hdr::ToPktHdrVal(IntrusivePtr pkt_hdr, int case IPPROTO_TCP: { const struct tcphdr* tp = (const struct tcphdr*) data; - auto tcp_hdr = make_intrusive(tcp_hdr_type); + auto tcp_hdr = zeek::make_intrusive(tcp_hdr_type); int tcp_hdr_len = tp->th_off * 4; int data_len = PayloadLen() - tcp_hdr_len; - tcp_hdr->Assign(0, val_mgr->Port(ntohs(tp->th_sport), TRANSPORT_TCP)); - tcp_hdr->Assign(1, val_mgr->Port(ntohs(tp->th_dport), TRANSPORT_TCP)); - tcp_hdr->Assign(2, val_mgr->Count(uint32_t(ntohl(tp->th_seq)))); - tcp_hdr->Assign(3, val_mgr->Count(uint32_t(ntohl(tp->th_ack)))); - tcp_hdr->Assign(4, val_mgr->Count(tcp_hdr_len)); - tcp_hdr->Assign(5, val_mgr->Count(data_len)); - tcp_hdr->Assign(6, val_mgr->Count(tp->th_x2)); - tcp_hdr->Assign(7, val_mgr->Count(tp->th_flags)); - tcp_hdr->Assign(8, val_mgr->Count(ntohs(tp->th_win))); + tcp_hdr->Assign(0, zeek::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(2, zeek::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(4, zeek::val_mgr->Count(tcp_hdr_len)); + tcp_hdr->Assign(5, zeek::val_mgr->Count(data_len)); + tcp_hdr->Assign(6, zeek::val_mgr->Count(tp->th_x2)); + tcp_hdr->Assign(7, zeek::val_mgr->Count(tp->th_flags)); + tcp_hdr->Assign(8, zeek::val_mgr->Count(ntohs(tp->th_win))); pkt_hdr->Assign(sindex + 2, std::move(tcp_hdr)); break; @@ -408,11 +408,11 @@ IntrusivePtr IP_Hdr::ToPktHdrVal(IntrusivePtr pkt_hdr, int case IPPROTO_UDP: { const struct udphdr* up = (const struct udphdr*) data; - auto udp_hdr = make_intrusive(udp_hdr_type); + auto udp_hdr = zeek::make_intrusive(udp_hdr_type); - udp_hdr->Assign(0, val_mgr->Port(ntohs(up->uh_sport), TRANSPORT_UDP)); - udp_hdr->Assign(1, val_mgr->Port(ntohs(up->uh_dport), TRANSPORT_UDP)); - udp_hdr->Assign(2, val_mgr->Count(ntohs(up->uh_ulen))); + udp_hdr->Assign(0, zeek::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(2, zeek::val_mgr->Count(ntohs(up->uh_ulen))); pkt_hdr->Assign(sindex + 3, std::move(udp_hdr)); break; @@ -421,9 +421,9 @@ IntrusivePtr IP_Hdr::ToPktHdrVal(IntrusivePtr pkt_hdr, int case IPPROTO_ICMP: { const struct icmp* icmpp = (const struct icmp *) data; - auto icmp_hdr = make_intrusive(icmp_hdr_type); + auto icmp_hdr = zeek::make_intrusive(icmp_hdr_type); - icmp_hdr->Assign(0, val_mgr->Count(icmpp->icmp_type)); + icmp_hdr->Assign(0, zeek::val_mgr->Count(icmpp->icmp_type)); pkt_hdr->Assign(sindex + 4, std::move(icmp_hdr)); break; @@ -432,9 +432,9 @@ IntrusivePtr IP_Hdr::ToPktHdrVal(IntrusivePtr pkt_hdr, int case IPPROTO_ICMPV6: { const struct icmp6_hdr* icmpp = (const struct icmp6_hdr*) data; - auto icmp_hdr = make_intrusive(icmp_hdr_type); + auto icmp_hdr = zeek::make_intrusive(icmp_hdr_type); - icmp_hdr->Assign(0, val_mgr->Count(icmpp->icmp6_type)); + icmp_hdr->Assign(0, zeek::val_mgr->Count(icmpp->icmp6_type)); pkt_hdr->Assign(sindex + 4, std::move(icmp_hdr)); break; @@ -450,9 +450,9 @@ IntrusivePtr IP_Hdr::ToPktHdrVal(IntrusivePtr pkt_hdr, int return pkt_hdr; } -RecordVal* IP_Hdr::BuildPktHdrVal(RecordVal* pkt_hdr, int sindex) const +zeek::RecordVal* IP_Hdr::BuildPktHdrVal(zeek::RecordVal* pkt_hdr, int sindex) const { - return ToPktHdrVal({AdoptRef{}, pkt_hdr}, sindex).release(); + return ToPktHdrVal({zeek::AdoptRef{}, pkt_hdr}, sindex).release(); } static inline bool isIPv6ExtHeader(uint8_t type) @@ -676,7 +676,7 @@ void IPv6_Hdr_Chain::ProcessDstOpts(const struct ip6_dest* d, uint16_t len) } #endif -IntrusivePtr IPv6_Hdr_Chain::ToVal() const +zeek::VectorValPtr IPv6_Hdr_Chain::ToVal() const { static auto ip6_ext_hdr_type = zeek::id::find_type("ip6_ext_hdr"); static auto ip6_hopopts_type = zeek::id::find_type("ip6_hopopts"); @@ -686,14 +686,14 @@ IntrusivePtr IPv6_Hdr_Chain::ToVal() const static auto ip6_ah_type = zeek::id::find_type("ip6_ah"); static auto ip6_esp_type = zeek::id::find_type("ip6_esp"); static auto ip6_ext_hdr_chain_type = zeek::id::find_type("ip6_ext_hdr_chain"); - auto rval = make_intrusive(ip6_ext_hdr_chain_type); + auto rval = zeek::make_intrusive(ip6_ext_hdr_chain_type); for ( size_t i = 1; i < chain.size(); ++i ) { auto v = chain[i]->ToVal(); - auto ext_hdr = make_intrusive(ip6_ext_hdr_type); + auto ext_hdr = zeek::make_intrusive(ip6_ext_hdr_type); uint8_t type = chain[i]->Type(); - ext_hdr->Assign(0, val_mgr->Count(type)); + ext_hdr->Assign(0, zeek::val_mgr->Count(type)); switch (type) { case IPPROTO_HOPOPTS: @@ -730,7 +730,7 @@ IntrusivePtr IPv6_Hdr_Chain::ToVal() const return rval; } -VectorVal* IPv6_Hdr_Chain::BuildVal() const +zeek::VectorVal* IPv6_Hdr_Chain::BuildVal() const { return ToVal().release(); } diff --git a/src/IP.h b/src/IP.h index 3bb1a6c897..717225f541 100644 --- a/src/IP.h +++ b/src/IP.h @@ -17,8 +17,14 @@ #include "IntrusivePtr.h" class IPAddr; -class RecordVal; -class VectorVal; + +ZEEK_FORWARD_DECLARE_NAMESPACED(RecordVal, zeek); +ZEEK_FORWARD_DECLARE_NAMESPACED(VectorVal, zeek); + +namespace zeek { +using RecordValPtr = zeek::IntrusivePtr; +using VectorValPtr = zeek::IntrusivePtr; +} #ifdef ENABLE_MOBILE_IPV6 @@ -136,11 +142,11 @@ public: /** * Returns the script-layer record representation of the header. */ - IntrusivePtr ToVal(IntrusivePtr chain) const; - IntrusivePtr ToVal() const; + zeek::RecordValPtr ToVal(zeek::VectorValPtr chain) const; + zeek::RecordValPtr ToVal() const; [[deprecated("Remove in v4.1. Use ToVal() instead.")]] - RecordVal* BuildRecordVal(VectorVal* chain = nullptr) const; + zeek::RecordVal* BuildRecordVal(zeek::VectorVal* chain = nullptr) const; protected: uint8_t type; @@ -229,10 +235,10 @@ public: * Returns a vector of ip6_ext_hdr RecordVals that includes script-layer * representation of all extension headers in the chain. */ - IntrusivePtr ToVal() const; + zeek::VectorValPtr ToVal() const; [[deprecated("Remove in v4.1. Use ToVal() instead.")]] - VectorVal* BuildVal() const; + zeek::VectorVal* BuildVal() const; protected: // for access to protected ctor that changes next header values that @@ -526,28 +532,28 @@ public: /** * Returns an ip_hdr or ip6_hdr_chain RecordVal. */ - IntrusivePtr ToIPHdrVal() const; + zeek::RecordValPtr ToIPHdrVal() const; [[deprecated("Remove in v4.1. Use ToIPHdrVal() instead.")]] - RecordVal* BuildIPHdrVal() const; + zeek::RecordVal* BuildIPHdrVal() const; /** * Returns a pkt_hdr RecordVal, which includes not only the IP header, but * also upper-layer (tcp/udp/icmp) headers. */ - IntrusivePtr ToPktHdrVal() const; + zeek::RecordValPtr ToPktHdrVal() const; [[deprecated("Remove in v4.1. Use ToPktHdrVal() instead.")]] - RecordVal* BuildPktHdrVal() const; + zeek::RecordVal* BuildPktHdrVal() const; /** * Same as above, but simply add our values into the record at the * specified starting index. */ - IntrusivePtr ToPktHdrVal(IntrusivePtr pkt_hdr, int sindex) const; + zeek::RecordValPtr ToPktHdrVal(zeek::RecordValPtr pkt_hdr, int sindex) const; [[deprecated("Remove in v4.1. Use ToPktHdrVal() instead.")]] - RecordVal* BuildPktHdrVal(RecordVal* pkt_hdr, int sindex) const; + zeek::RecordVal* BuildPktHdrVal(zeek::RecordVal* pkt_hdr, int sindex) const; private: const struct ip* ip4 = nullptr; diff --git a/src/IPAddr.cc b/src/IPAddr.cc index 4db211da02..362d436ad1 100644 --- a/src/IPAddr.cc +++ b/src/IPAddr.cc @@ -5,7 +5,7 @@ #include #include "IPAddr.h" #include "Reporter.h" -#include "BroString.h" +#include "ZeekString.h" #include "Conn.h" #include "Hash.h" #include "bro_inet_ntop.h" @@ -47,7 +47,7 @@ ConnIDKey BuildConnIDKey(const ConnID& id) return key; } -IPAddr::IPAddr(const BroString& s) +IPAddr::IPAddr(const zeek::String& s) { Init(s.CheckString()); } diff --git a/src/IPAddr.h b/src/IPAddr.h index a945c8b53f..3a2b9d01ef 100644 --- a/src/IPAddr.h +++ b/src/IPAddr.h @@ -10,15 +10,16 @@ #include "threading/SerialTypes.h" +namespace zeek { class String; } +using BroString [[deprecated("Remove in v4.1. Use zeek::String instead.")]] = zeek::String; + struct ConnID; -class BroString; class HashKey; namespace analyzer { class ExpectedConn; } typedef in_addr in4_addr; -struct ConnIDKey - { +struct ConnIDKey { in6_addr ip1; in6_addr ip2; uint16_t port1; @@ -40,13 +41,12 @@ struct ConnIDKey return *this; } - }; +}; /** * Class storing both IPv4 and IPv6 addresses. */ -class IPAddr -{ +class IPAddr { public: /** * Address family. @@ -112,7 +112,7 @@ public: * @param s String containing an IP address as either a dotted IPv4 * address or a hex IPv6 address. */ - explicit IPAddr(const BroString& s); + explicit IPAddr(const zeek::String& s); /** * Constructs an address instance from a raw byte representation. diff --git a/src/IntrusivePtr.h b/src/IntrusivePtr.h index 6f09bd86cd..b98761a326 100644 --- a/src/IntrusivePtr.h +++ b/src/IntrusivePtr.h @@ -5,6 +5,8 @@ #include #include +namespace zeek { + /** * A tag class for the #IntrusivePtr constructor which means: adopt * the reference from the caller. @@ -31,7 +33,7 @@ struct NewRef {}; * for destroying the shared object. * * The @c IntrusivePtr works with any type that offers the two free functions, - * but most notably is designed to work with @c BroObj and its subtypes. + * but most notably is designed to work with @c Obj and its subtypes. * * The same object may get managed via @c IntrusivePtr in one part of the * code base while another part of the program manages it manually by passing @@ -97,7 +99,7 @@ public: } IntrusivePtr(const IntrusivePtr& other) noexcept - : IntrusivePtr(NewRef{}, other.get()) + : IntrusivePtr(zeek::NewRef{}, other.get()) { } @@ -181,7 +183,7 @@ template IntrusivePtr make_intrusive(Ts&&... args) { // Assumes that objects start with a reference count of 1! - return {AdoptRef{}, new T(std::forward(args)...)}; + return {zeek::AdoptRef{}, new T(std::forward(args)...)}; } /** @@ -193,16 +195,18 @@ IntrusivePtr make_intrusive(Ts&&... args) template IntrusivePtr cast_intrusive(IntrusivePtr p) noexcept { - return {AdoptRef{}, static_cast(p.release())}; + return {zeek::AdoptRef{}, static_cast(p.release())}; } +} + // -- comparison to nullptr ---------------------------------------------------- /** * @relates IntrusivePtr */ template -bool operator==(const IntrusivePtr& x, std::nullptr_t) { +bool operator==(const zeek::IntrusivePtr& x, std::nullptr_t) { return !x; } @@ -210,7 +214,7 @@ bool operator==(const IntrusivePtr& x, std::nullptr_t) { * @relates IntrusivePtr */ template -bool operator==(std::nullptr_t, const IntrusivePtr& x) { +bool operator==(std::nullptr_t, const zeek::IntrusivePtr& x) { return !x; } @@ -218,7 +222,7 @@ bool operator==(std::nullptr_t, const IntrusivePtr& x) { * @relates IntrusivePtr */ template -bool operator!=(const IntrusivePtr& x, std::nullptr_t) { +bool operator!=(const zeek::IntrusivePtr& x, std::nullptr_t) { return static_cast(x); } @@ -226,7 +230,7 @@ bool operator!=(const IntrusivePtr& x, std::nullptr_t) { * @relates IntrusivePtr */ template -bool operator!=(std::nullptr_t, const IntrusivePtr& x) { +bool operator!=(std::nullptr_t, const zeek::IntrusivePtr& x) { return static_cast(x); } @@ -236,7 +240,7 @@ bool operator!=(std::nullptr_t, const IntrusivePtr& x) { * @relates IntrusivePtr */ template -bool operator==(const IntrusivePtr& x, const T* y) { +bool operator==(const zeek::IntrusivePtr& x, const T* y) { return x.get() == y; } @@ -244,7 +248,7 @@ bool operator==(const IntrusivePtr& x, const T* y) { * @relates IntrusivePtr */ template -bool operator==(const T* x, const IntrusivePtr& y) { +bool operator==(const T* x, const zeek::IntrusivePtr& y) { return x == y.get(); } @@ -252,7 +256,7 @@ bool operator==(const T* x, const IntrusivePtr& y) { * @relates IntrusivePtr */ template -bool operator!=(const IntrusivePtr& x, const T* y) { +bool operator!=(const zeek::IntrusivePtr& x, const T* y) { return x.get() != y; } @@ -260,7 +264,7 @@ bool operator!=(const IntrusivePtr& x, const T* y) { * @relates IntrusivePtr */ template -bool operator!=(const T* x, const IntrusivePtr& y) { +bool operator!=(const T* x, const zeek::IntrusivePtr& y) { return x != y.get(); } @@ -273,7 +277,7 @@ bool operator!=(const T* x, const IntrusivePtr& y) { * @relates IntrusivePtr */ template -auto operator==(const IntrusivePtr& x, const IntrusivePtr& y) +auto operator==(const zeek::IntrusivePtr& x, const zeek::IntrusivePtr& y) -> decltype(x.get() == y.get()) { return x.get() == y.get(); @@ -283,9 +287,8 @@ auto operator==(const IntrusivePtr& x, const IntrusivePtr& y) * @relates IntrusivePtr */ template -auto operator!=(const IntrusivePtr& x, const IntrusivePtr& y) +auto operator!=(const zeek::IntrusivePtr& x, const zeek::IntrusivePtr& y) -> decltype(x.get() != y.get()) { return x.get() != y.get(); } - diff --git a/src/List.cc b/src/List.cc index c19353b341..375d0c21a0 100644 --- a/src/List.cc +++ b/src/List.cc @@ -3,17 +3,17 @@ TEST_CASE("list construction") { - List list; + zeek::List list; CHECK(list.empty()); - List list2(10); + zeek::List list2(10); CHECK(list2.empty()); CHECK(list2.max() == 10); } TEST_CASE("list operation") { - List list({ 1, 2, 3 }); + zeek::List list({ 1, 2, 3 }); CHECK(list.size() == 3); CHECK(list.max() == 3); CHECK(list[0] == 1); @@ -85,7 +85,7 @@ TEST_CASE("list operation") TEST_CASE("list iteration") { - List list({ 1, 2, 3, 4}); + zeek::List list({ 1, 2, 3, 4}); int index = 1; for ( int v : list ) @@ -98,7 +98,7 @@ TEST_CASE("list iteration") TEST_CASE("plists") { - PList list; + zeek::PList list; list.push_back(new int(1)); list.push_back(new int(2)); list.push_back(new int(3)); @@ -117,7 +117,7 @@ TEST_CASE("plists") TEST_CASE("unordered list operation") { - List list({1, 2, 3, 4}); + zeek::List list({1, 2, 3, 4}); CHECK(list.size() == 4); // An unordered list doesn't maintain the ordering of the elements when diff --git a/src/List.h b/src/List.h index c6d0902013..95733f01b4 100644 --- a/src/List.h +++ b/src/List.h @@ -26,8 +26,7 @@ #include #include "util.h" -// TODO: this can be removed in v3.1 when List::sort() is removed -typedef int (*list_cmp_func)(const void* v1, const void* v2); +namespace zeek { enum class ListOrder : int { ORDERED, UNORDERED }; @@ -334,7 +333,11 @@ template using PList = List; // Popular type of list: list of strings. -typedef PList name_list; +using name_list = PList; + +} // namespace zeek + +using ListOrder [[deprecated("Remove in v4.1. Use zeek::ListOrder instead.")]] = zeek::ListOrder; // Macro to visit each list element in turn. #define loop_over_list(list, iterator) \ diff --git a/src/NFA.h b/src/NFA.h index 77e0102fba..ce10aa4d08 100644 --- a/src/NFA.h +++ b/src/NFA.h @@ -6,11 +6,12 @@ #include "List.h" class CCL; -class Func; class NFA_State; class EquivClass; -typedef PList NFA_state_list; +ZEEK_FORWARD_DECLARE_NAMESPACED(Func, zeek); + +using NFA_state_list = zeek::PList; #define NO_ACCEPT 0 @@ -21,10 +22,10 @@ typedef PList NFA_state_list; #define NUM_SYM 258 #define SYM_EPSILON 259 -#define SYM_CCL 260 +#define SYM_CCL 260 -class NFA_State : public BroObj { +class NFA_State : public zeek::Obj { public: NFA_State(int sym, EquivClass* ec); explicit NFA_State(CCL* ccl); @@ -81,7 +82,7 @@ public: EpsilonState() : NFA_State(SYM_EPSILON, nullptr) { } }; -class NFA_Machine : public BroObj { +class NFA_Machine : public zeek::Obj { public: explicit NFA_Machine(NFA_State* first, NFA_State* final = nullptr); ~NFA_Machine() override; diff --git a/src/Net.cc b/src/Net.cc index 1574202266..97940a792d 100644 --- a/src/Net.cc +++ b/src/Net.cc @@ -193,8 +193,8 @@ void net_init(const std::optional& interface, reporter->FatalError("problem opening dump file %s (%s)", writefile, pkt_dumper->ErrorMsg()); - if ( const auto& id = global_scope()->Find("trace_output_file") ) - id->SetVal(make_intrusive(writefile)); + if ( const auto& id = zeek::detail::global_scope()->Find("trace_output_file") ) + id->SetVal(zeek::make_intrusive(writefile)); else reporter->Error("trace_output_file not defined in bro.init"); } diff --git a/src/NetVar.cc b/src/NetVar.cc index 27a8f98340..44d5950d27 100644 --- a/src/NetVar.cc +++ b/src/NetVar.cc @@ -66,17 +66,17 @@ double icmp_inactivity_timeout; int tcp_storm_thresh; double tcp_storm_interarrival_thresh; -TableVal* tcp_reassembler_ports_orig; -TableVal* tcp_reassembler_ports_resp; +zeek::TableVal* tcp_reassembler_ports_orig; +zeek::TableVal* tcp_reassembler_ports_resp; -TableVal* tcp_content_delivery_ports_orig; -TableVal* tcp_content_delivery_ports_resp; +zeek::TableVal* tcp_content_delivery_ports_orig; +zeek::TableVal* tcp_content_delivery_ports_resp; bool tcp_content_deliver_all_orig; bool tcp_content_deliver_all_resp; -TableVal* udp_content_delivery_ports_orig; -TableVal* udp_content_delivery_ports_resp; -TableVal* udp_content_ports; +zeek::TableVal* udp_content_delivery_ports_orig; +zeek::TableVal* udp_content_delivery_ports_resp; +zeek::TableVal* udp_content_ports; bool udp_content_deliver_all_orig; bool udp_content_deliver_all_resp; bool udp_content_delivery_ports_use_resp; @@ -112,15 +112,15 @@ zeek::RecordType* dns_rrsig_rr; zeek::RecordType* dns_dnskey_rr; zeek::RecordType* dns_nsec3_rr; zeek::RecordType* dns_ds_rr; -TableVal* dns_skip_auth; -TableVal* dns_skip_addl; +zeek::TableVal* dns_skip_auth; +zeek::TableVal* dns_skip_addl; int dns_skip_all_auth; int dns_skip_all_addl; int dns_max_queries; double stp_delta; double stp_idle_min; -TableVal* stp_skip_src; +zeek::TableVal* stp_skip_src; double table_expire_interval; double table_expire_delay; @@ -130,22 +130,22 @@ double connection_status_update_interval; int orig_addr_anonymization, resp_addr_anonymization; int other_addr_anonymization; -TableVal* preserve_orig_addr; -TableVal* preserve_resp_addr; -TableVal* preserve_other_addr; +zeek::TableVal* preserve_orig_addr; +zeek::TableVal* preserve_resp_addr; +zeek::TableVal* preserve_other_addr; zeek::RecordType* rotate_info; -StringVal* log_rotate_base_time; +zeek::StringVal* log_rotate_base_time; -StringVal* peer_description; +zeek::StringVal* peer_description; -Val* profiling_file; +zeek::Val* profiling_file; double profiling_interval; int expensive_profiling_multiple; int segment_profiling; int pkt_profile_mode; double pkt_profile_freq; -Val* pkt_profile_file; +zeek::Val* pkt_profile_file; int load_sample_freq; @@ -162,13 +162,13 @@ int dpd_match_only_beginning; int dpd_late_match_stop; int dpd_ignore_ports; -TableVal* likely_server_ports; +zeek::TableVal* likely_server_ports; int check_for_unused_event_handlers; double timer_mgr_inactivity_timeout; -StringVal* trace_output_file; +zeek::StringVal* trace_output_file; int record_all_packets; @@ -179,9 +179,9 @@ zeek::TableType* record_field_table; zeek::RecordType* call_argument; zeek::VectorType* call_argument_vector; -StringVal* cmd_line_bpf_filter; +zeek::StringVal* cmd_line_bpf_filter; -StringVal* global_hash_seed; +zeek::StringVal* global_hash_seed; bro_uint_t bits_per_uid; diff --git a/src/NetVar.h b/src/NetVar.h index 86116228af..3192007a4a 100644 --- a/src/NetVar.h +++ b/src/NetVar.h @@ -87,23 +87,23 @@ extern int tcp_storm_thresh; extern double tcp_storm_interarrival_thresh; [[deprecated("Remove in v4.1. Perform your own lookup.")]] -extern TableVal* tcp_reassembler_ports_orig; +extern zeek::TableVal* tcp_reassembler_ports_orig; [[deprecated("Remove in v4.1. Perform your own lookup.")]] -extern TableVal* tcp_reassembler_ports_resp; +extern zeek::TableVal* tcp_reassembler_ports_resp; [[deprecated("Remove in v4.1. Perform your own lookup.")]] -extern TableVal* tcp_content_delivery_ports_orig; +extern zeek::TableVal* tcp_content_delivery_ports_orig; [[deprecated("Remove in v4.1. Perform your own lookup.")]] -extern TableVal* tcp_content_delivery_ports_resp; +extern zeek::TableVal* tcp_content_delivery_ports_resp; extern bool tcp_content_deliver_all_orig; extern bool tcp_content_deliver_all_resp; [[deprecated("Remove in v4.1. Perform your own lookup.")]] -extern TableVal* udp_content_delivery_ports_orig; +extern zeek::TableVal* udp_content_delivery_ports_orig; [[deprecated("Remove in v4.1. Perform your own lookup.")]] -extern TableVal* udp_content_delivery_ports_resp; +extern zeek::TableVal* udp_content_delivery_ports_resp; [[deprecated("Remove in v4.1. Perform your own lookup.")]] -extern TableVal* udp_content_ports; +extern zeek::TableVal* udp_content_ports; extern bool udp_content_deliver_all_orig; extern bool udp_content_deliver_all_resp; extern bool udp_content_delivery_ports_use_resp; @@ -159,9 +159,9 @@ extern zeek::RecordType* dns_nsec3_rr; [[deprecated("Remove in v4.1. Perform your own lookup.")]] extern zeek::RecordType* dns_ds_rr; [[deprecated("Remove in v4.1. Perform your own lookup.")]] -extern TableVal* dns_skip_auth; +extern zeek::TableVal* dns_skip_auth; [[deprecated("Remove in v4.1. Perform your own lookup.")]] -extern TableVal* dns_skip_addl; +extern zeek::TableVal* dns_skip_addl; extern int dns_skip_all_auth; extern int dns_skip_all_addl; extern int dns_max_queries; @@ -169,7 +169,7 @@ extern int dns_max_queries; extern double stp_delta; extern double stp_idle_min; [[deprecated("Remove in v4.1. Perform your own lookup.")]] -extern TableVal* stp_skip_src; +extern zeek::TableVal* stp_skip_src; extern double table_expire_interval; extern double table_expire_delay; @@ -178,24 +178,24 @@ extern int table_incremental_step; extern int orig_addr_anonymization, resp_addr_anonymization; extern int other_addr_anonymization; [[deprecated("Remove in v4.1. Perform your own lookup.")]] -extern TableVal* preserve_orig_addr; +extern zeek::TableVal* preserve_orig_addr; [[deprecated("Remove in v4.1. Perform your own lookup.")]] -extern TableVal* preserve_resp_addr; +extern zeek::TableVal* preserve_resp_addr; [[deprecated("Remove in v4.1. Perform your own lookup.")]] -extern TableVal* preserve_other_addr; +extern zeek::TableVal* preserve_other_addr; extern double connection_status_update_interval; [[deprecated("Remove in v4.1. Perform your own lookup.")]] extern zeek::RecordType* rotate_info; [[deprecated("Remove in v4.1. Perform your own lookup.")]] -extern StringVal* log_rotate_base_time; +extern zeek::StringVal* log_rotate_base_time; [[deprecated("Remove in v4.1. Perform your own lookup.")]] -extern StringVal* peer_description; +extern zeek::StringVal* peer_description; [[deprecated("Remove in v4.1. Perform your own lookup.")]] -extern Val* profiling_file; +extern zeek::Val* profiling_file; extern double profiling_interval; extern int expensive_profiling_multiple; @@ -203,7 +203,7 @@ extern int segment_profiling; extern int pkt_profile_mode; extern double pkt_profile_freq; [[deprecated("Remove in v4.1. Perform your own lookup.")]] -extern Val* pkt_profile_file; +extern zeek::Val* pkt_profile_file; extern int load_sample_freq; @@ -223,14 +223,14 @@ extern int dpd_late_match_stop; extern int dpd_ignore_ports; [[deprecated("Remove in v4.1. Perform your own lookup.")]] -extern TableVal* likely_server_ports; +extern zeek::TableVal* likely_server_ports; extern int check_for_unused_event_handlers; extern double timer_mgr_inactivity_timeout; [[deprecated("Remove in v4.1. Perform your own lookup.")]] -extern StringVal* trace_output_file; +extern zeek::StringVal* trace_output_file; extern int record_all_packets; @@ -248,10 +248,10 @@ extern zeek::RecordType* call_argument; extern zeek::VectorType* call_argument_vector; [[deprecated("Remove in v4.1. Perform your own lookup.")]] -extern StringVal* cmd_line_bpf_filter; +extern zeek::StringVal* cmd_line_bpf_filter; [[deprecated("Remove in v4.1. Perform your own lookup.")]] -extern StringVal* global_hash_seed; +extern zeek::StringVal* global_hash_seed; extern bro_uint_t bits_per_uid; diff --git a/src/Obj.cc b/src/Obj.cc index 63f22f4506..b733ba0055 100644 --- a/src/Obj.cc +++ b/src/Obj.cc @@ -10,6 +10,9 @@ #include "File.h" #include "plugin/Manager.h" +namespace zeek { +namespace detail { + Location start_location("", 0, 0, 0, 0); Location end_location("", 0, 0, 0, 0); @@ -48,9 +51,11 @@ bool Location::operator==(const Location& l) const return false; } -int BroObj::suppress_errors = 0; +} // namespace detail -BroObj::~BroObj() +int Obj::suppress_errors = 0; + +Obj::~Obj() { if ( notify_plugins ) PLUGIN_HOOK_VOID(HOOK_BRO_OBJ_DTOR, HookBroObjDtor(this)); @@ -58,7 +63,7 @@ BroObj::~BroObj() delete location; } -void BroObj::Warn(const char* msg, const BroObj* obj2, bool pinpoint_only, const Location* expr_location) const +void Obj::Warn(const char* msg, const Obj* obj2, bool pinpoint_only, const detail::Location* expr_location) const { ODesc d; DoMsg(&d, msg, obj2, pinpoint_only, expr_location); @@ -66,7 +71,7 @@ void BroObj::Warn(const char* msg, const BroObj* obj2, bool pinpoint_only, const reporter->PopLocation(); } -void BroObj::Error(const char* msg, const BroObj* obj2, bool pinpoint_only, const Location* expr_location) const +void Obj::Error(const char* msg, const Obj* obj2, bool pinpoint_only, const detail::Location* expr_location) const { if ( suppress_errors ) return; @@ -77,7 +82,7 @@ void BroObj::Error(const char* msg, const BroObj* obj2, bool pinpoint_only, cons reporter->PopLocation(); } -void BroObj::BadTag(const char* msg, const char* t1, const char* t2) const +void Obj::BadTag(const char* msg, const char* t1, const char* t2) const { char out[512]; @@ -94,11 +99,11 @@ void BroObj::BadTag(const char* msg, const char* t1, const char* t2) const reporter->PopLocation(); } -void BroObj::Internal(const char* msg) const +void Obj::Internal(const char* msg) const { ODesc d; DoMsg(&d, msg); - auto rcs = render_call_stack(); + auto rcs = zeek::render_call_stack(); if ( rcs.empty() ) reporter->InternalError("%s", d.Description()); @@ -108,7 +113,7 @@ void BroObj::Internal(const char* msg) const reporter->PopLocation(); } -void BroObj::InternalWarning(const char* msg) const +void Obj::InternalWarning(const char* msg) const { ODesc d; DoMsg(&d, msg); @@ -116,7 +121,7 @@ void BroObj::InternalWarning(const char* msg) const reporter->PopLocation(); } -void BroObj::AddLocation(ODesc* d) const +void Obj::AddLocation(ODesc* d) const { if ( ! location ) { @@ -127,7 +132,7 @@ void BroObj::AddLocation(ODesc* d) const location->Describe(d); } -bool BroObj::SetLocationInfo(const Location* start, const Location* end) +bool Obj::SetLocationInfo(const detail::Location* start, const detail::Location* end) { if ( ! start || ! end ) return false; @@ -135,20 +140,20 @@ bool BroObj::SetLocationInfo(const Location* start, const Location* end) if ( end->filename && ! streq(start->filename, end->filename) ) return false; - if ( location && (start == &no_location || end == &no_location) ) + if ( location && (start == &zeek::detail::no_location || end == &zeek::detail::no_location) ) // We already have a better location, so don't use this one. return true; delete location; - location = new Location(start->filename, - start->first_line, end->last_line, - start->first_column, end->last_column); + location = new detail::Location(start->filename, + start->first_line, end->last_line, + start->first_column, end->last_column); return true; } -void BroObj::UpdateLocationEndInfo(const Location& end) +void Obj::UpdateLocationEndInfo(const detail::Location& end) { if ( ! location ) SetLocationInfo(&end, &end); @@ -157,16 +162,16 @@ void BroObj::UpdateLocationEndInfo(const Location& end) location->last_column = end.last_column; } -void BroObj::DoMsg(ODesc* d, const char s1[], const BroObj* obj2, - bool pinpoint_only, const Location* expr_location) const +void Obj::DoMsg(ODesc* d, const char s1[], const Obj* obj2, + bool pinpoint_only, const detail::Location* expr_location) const { d->SetShort(); d->Add(s1); PinPoint(d, obj2, pinpoint_only); - const Location* loc2 = nullptr; - if ( obj2 && obj2->GetLocationInfo() != &no_location && + const detail::Location* loc2 = nullptr; + if ( obj2 && obj2->GetLocationInfo() != &zeek::detail::no_location && *obj2->GetLocationInfo() != *GetLocationInfo() ) loc2 = obj2->GetLocationInfo(); else if ( expr_location ) @@ -175,7 +180,7 @@ void BroObj::DoMsg(ODesc* d, const char s1[], const BroObj* obj2, reporter->PushLocation(GetLocationInfo(), loc2); } -void BroObj::PinPoint(ODesc* d, const BroObj* obj2, bool pinpoint_only) const +void Obj::PinPoint(ODesc* d, const Obj* obj2, bool pinpoint_only) const { d->Add(" ("); Describe(d); @@ -188,11 +193,11 @@ void BroObj::PinPoint(ODesc* d, const BroObj* obj2, bool pinpoint_only) const d->Add(")"); } -void print(const BroObj* obj) +void Obj::Print() const { static BroFile fstderr(stderr); ODesc d(DESC_READABLE, &fstderr); - obj->Describe(&d); + Describe(&d); d.Add("\n"); } @@ -202,7 +207,14 @@ void bad_ref(int type) abort(); } -void bro_obj_delete_func(void* v) +void obj_delete_func(void* v) { - Unref((BroObj*) v); + Unref((Obj*) v); + } + +} // namespace zeek + +void print(const zeek::Obj* obj) + { + obj->Print(); } diff --git a/src/Obj.h b/src/Obj.h index cab0ab92d5..e121871036 100644 --- a/src/Obj.h +++ b/src/Obj.h @@ -6,8 +6,12 @@ class ODesc; +namespace zeek { +namespace detail { + class Location final { public: + constexpr Location(const char* fname, int line_f, int line_l, int col_f, int col_l) noexcept :filename(fname), first_line(line_f), last_line(line_l), @@ -26,7 +30,7 @@ public: int first_column = 0, last_column = 0; }; -#define YYLTYPE yyltype +#define YYLTYPE zeek::detail::yyltype typedef Location yyltype; YYLTYPE GetCurrentLocation(); @@ -49,9 +53,11 @@ inline void set_location(const Location start, const Location end) end_location = end; } -class BroObj { +} // namespace detail + +class Obj { public: - BroObj() + Obj() { // A bit of a hack. We'd like to associate location // information with every object created when parsing, @@ -67,23 +73,23 @@ public: // of 0, which should only happen if it's been assigned // to no_location (or hasn't been initialized at all). location = nullptr; - if ( start_location.first_line != 0 ) - SetLocationInfo(&start_location, &end_location); + if ( detail::start_location.first_line != 0 ) + SetLocationInfo(&detail::start_location, &detail::end_location); } - virtual ~BroObj(); + virtual ~Obj(); /* disallow copying */ - BroObj(const BroObj &) = delete; - BroObj &operator=(const BroObj &) = delete; + Obj(const Obj &) = delete; + Obj &operator=(const Obj &) = delete; // Report user warnings/errors. If obj2 is given, then it's // included in the message, though if pinpoint_only is non-zero, // then obj2 is only used to pinpoint the location. - void Warn(const char* msg, const BroObj* obj2 = nullptr, - bool pinpoint_only = false, const Location* expr_location = nullptr) const; - void Error(const char* msg, const BroObj* obj2 = nullptr, - bool pinpoint_only = false, const Location* expr_location = nullptr) const; + void Warn(const char* msg, const Obj* obj2 = nullptr, + bool pinpoint_only = false, const detail::Location* expr_location = nullptr) const; + void Error(const char* msg, const Obj* obj2 = nullptr, + bool pinpoint_only = false, const detail::Location* expr_location = nullptr) const; // Report internal errors. void BadTag(const char* msg, const char* t1 = nullptr, @@ -102,18 +108,18 @@ public: void AddLocation(ODesc* d) const; // Get location info for debugging. - const Location* GetLocationInfo() const - { return location ? location : &no_location; } + const detail::Location* GetLocationInfo() const + { return location ? location : &detail::no_location; } - virtual bool SetLocationInfo(const Location* loc) + virtual bool SetLocationInfo(const detail::Location* loc) { return SetLocationInfo(loc, loc); } // Location = range from start to end. - virtual bool SetLocationInfo(const Location* start, const Location* end); + virtual bool SetLocationInfo(const detail::Location* start, const detail::Location* end); // Set new end-of-location information. This is used to // extend compound objects such as statement lists. - virtual void UpdateLocationEndInfo(const Location& end); + virtual void UpdateLocationEndInfo(const detail::Location& end); // Enable notification of plugins when this objects gets destroyed. void NotifyPluginsOnDtor() { notify_plugins = true; } @@ -124,23 +130,25 @@ public: // as long as there exist any instances. class SuppressErrors { public: - SuppressErrors() { ++BroObj::suppress_errors; } - ~SuppressErrors() { --BroObj::suppress_errors; } + SuppressErrors() { ++Obj::suppress_errors; } + ~SuppressErrors() { --Obj::suppress_errors; } }; + void Print() const; + protected: - Location* location; // all that matters in real estate + detail::Location* location; // all that matters in real estate private: friend class SuppressErrors; - void DoMsg(ODesc* d, const char s1[], const BroObj* obj2 = nullptr, - bool pinpoint_only = false, const Location* expr_location = nullptr) const; - void PinPoint(ODesc* d, const BroObj* obj2 = nullptr, + void DoMsg(ODesc* d, const char s1[], const Obj* obj2 = nullptr, + bool pinpoint_only = false, const detail::Location* expr_location = nullptr) const; + void PinPoint(ODesc* d, const Obj* obj2 = nullptr, bool pinpoint_only = false) const; - friend inline void Ref(BroObj* o); - friend inline void Unref(BroObj* o); + friend inline void Ref(Obj* o); + friend inline void Unref(Obj* o); bool notify_plugins = false; int ref_cnt = 1; @@ -150,19 +158,16 @@ private: static int suppress_errors; }; -// Prints obj to stderr, primarily for debugging. -extern void print(const BroObj* obj); - -[[noreturn]] extern void bad_ref(int type); - -// Sometimes useful when dealing with BroObj subclasses that have their +// Sometimes useful when dealing with Obj subclasses that have their // own (protected) versions of Error. -inline void Error(const BroObj* o, const char* msg) +inline void Error(const Obj* o, const char* msg) { o->Error(msg); } -inline void Ref(BroObj* o) +[[noreturn]] extern void bad_ref(int type); + +inline void Ref(Obj* o) { if ( ++(o->ref_cnt) <= 1 ) bad_ref(0); @@ -170,7 +175,7 @@ inline void Ref(BroObj* o) bad_ref(1); } -inline void Unref(BroObj* o) +inline void Unref(Obj* o) { if ( o && --o->ref_cnt <= 0 ) { @@ -179,9 +184,18 @@ inline void Unref(BroObj* o) delete o; // We could do the following if o were passed by reference. - // o = (BroObj*) 0xcd; + // o = (Obj*) 0xcd; } } // A dict_delete_func that knows to Unref() dictionary entries. -extern void bro_obj_delete_func(void* v); +extern void obj_delete_func(void* v); + +} // namespace zeek + +using Location [[deprecated("Remove in v4.1. Use zeek::detail::Location instead.")]] = zeek::detail::Location; +using yyltype [[deprecated("Remove in v4.1. Use zeek::detail::yyltype instead.")]] = zeek::detail::yyltype; +using BroObj [[deprecated("Remove in v4.1. Use zeek::Obj instead.")]] = zeek::Obj; + +[[deprecated("Remove in v4.1. Use zeek::Obj::Print instead.")]] +extern void print(const zeek::Obj* obj); diff --git a/src/OpaqueVal.cc b/src/OpaqueVal.cc index f1d5c50fca..b1f0c741ad 100644 --- a/src/OpaqueVal.cc +++ b/src/OpaqueVal.cc @@ -15,6 +15,8 @@ #include #include +namespace zeek { + // Helper to retrieve a broker value out of a broker::vector at a specified // index, and casted to the expected destination type. template @@ -37,10 +39,10 @@ OpaqueMgr* OpaqueMgr::mgr() return &mgr; } -OpaqueVal::OpaqueVal(zeek::OpaqueType* t) : OpaqueVal({NewRef{}, t}) +OpaqueVal::OpaqueVal(zeek::OpaqueType* t) : OpaqueVal({zeek::NewRef{}, t}) {} -OpaqueVal::OpaqueVal(IntrusivePtr t) : Val(std::move(t)) +OpaqueVal::OpaqueVal(zeek::OpaqueTypePtr t) : Val(std::move(t)) {} OpaqueVal::~OpaqueVal() @@ -58,7 +60,7 @@ const std::string& OpaqueMgr::TypeID(const OpaqueVal* v) const return x->first; } -IntrusivePtr OpaqueMgr::Instantiate(const std::string& id) const +OpaqueValPtr OpaqueMgr::Instantiate(const std::string& id) const { auto x = _types.find(id); return x != _types.end() ? (*x->second)() : nullptr; @@ -75,7 +77,7 @@ broker::expected OpaqueVal::Serialize() const return {broker::vector{std::move(type), std::move(*d)}}; } -IntrusivePtr OpaqueVal::Unserialize(const broker::data& data) +OpaqueValPtr OpaqueVal::Unserialize(const broker::data& data) { auto v = caf::get_if(&data); @@ -96,7 +98,7 @@ IntrusivePtr OpaqueVal::Unserialize(const broker::data& data) return val; } -broker::expected OpaqueVal::SerializeType(const IntrusivePtr& t) +broker::expected OpaqueVal::SerializeType(const zeek::TypePtr& t) { if ( t->InternalType() == zeek::TYPE_INTERNAL_ERROR ) return broker::ec::invalid_data; @@ -112,7 +114,7 @@ broker::expected OpaqueVal::SerializeType(const IntrusivePtr(t->Tag())}}; } -IntrusivePtr OpaqueVal::UnserializeType(const broker::data& data) +zeek::TypePtr OpaqueVal::UnserializeType(const broker::data& data) { auto v = caf::get_if(&data); if ( ! (v && v->size() == 2) ) @@ -128,7 +130,7 @@ IntrusivePtr OpaqueVal::UnserializeType(const broker::data& data) if ( ! name ) return nullptr; - const auto& id = global_scope()->Find(*name); + const auto& id = zeek::detail::global_scope()->Find(*name); if ( ! id ) return nullptr; @@ -145,7 +147,7 @@ IntrusivePtr OpaqueVal::UnserializeType(const broker::data& data) return zeek::base_type(static_cast(*tag)); } -IntrusivePtr OpaqueVal::DoClone(CloneState* state) +ValPtr OpaqueVal::DoClone(CloneState* state) { auto d = OpaqueVal::Serialize(); if ( ! d ) @@ -169,10 +171,10 @@ bool HashVal::Init() return valid; } -IntrusivePtr HashVal::Get() +StringValPtr HashVal::Get() { if ( ! valid ) - return val_mgr->EmptyString(); + return zeek::val_mgr->EmptyString(); auto result = DoGet(); valid = false; @@ -200,18 +202,18 @@ bool HashVal::DoFeed(const void*, size_t) return false; } -IntrusivePtr HashVal::DoGet() +StringValPtr HashVal::DoGet() { assert(! "missing implementation of DoGet()"); - return val_mgr->EmptyString(); + return zeek::val_mgr->EmptyString(); } -HashVal::HashVal(IntrusivePtr t) : OpaqueVal(std::move(t)) +HashVal::HashVal(zeek::OpaqueTypePtr t) : OpaqueVal(std::move(t)) { valid = false; } -HashVal::HashVal(zeek::OpaqueType* t) : HashVal({NewRef{}, t}) +HashVal::HashVal(zeek::OpaqueType* t) : HashVal({zeek::NewRef{}, t}) {} MD5Val::MD5Val() : HashVal(md5_type) @@ -228,7 +230,7 @@ void HashVal::digest_one(EVP_MD_CTX* h, const Val* v) { if ( v->GetType()->Tag() == zeek::TYPE_STRING ) { - const BroString* str = v->AsString(); + const String* str = v->AsString(); hash_update(h, str->Bytes(), str->Len()); } else @@ -239,14 +241,14 @@ void HashVal::digest_one(EVP_MD_CTX* h, const Val* v) } } -void HashVal::digest_one(EVP_MD_CTX* h, const IntrusivePtr& v) +void HashVal::digest_one(EVP_MD_CTX* h, const ValPtr& v) { digest_one(h, v.get()); } -IntrusivePtr MD5Val::DoClone(CloneState* state) +ValPtr MD5Val::DoClone(CloneState* state) { - auto out = make_intrusive(); + auto out = zeek::make_intrusive(); if ( IsValid() ) { @@ -275,14 +277,14 @@ bool MD5Val::DoFeed(const void* data, size_t size) return true; } -IntrusivePtr MD5Val::DoGet() +StringValPtr MD5Val::DoGet() { if ( ! IsValid() ) - return val_mgr->EmptyString(); + return zeek::val_mgr->EmptyString(); u_char digest[MD5_DIGEST_LENGTH]; hash_final(ctx, digest); - return make_intrusive(md5_digest_print(digest)); + return zeek::make_intrusive(md5_digest_print(digest)); } IMPLEMENT_OPAQUE_VALUE(MD5Val) @@ -364,9 +366,9 @@ SHA1Val::~SHA1Val() EVP_MD_CTX_free(ctx); } -IntrusivePtr SHA1Val::DoClone(CloneState* state) +ValPtr SHA1Val::DoClone(CloneState* state) { - auto out = make_intrusive(); + auto out = zeek::make_intrusive(); if ( IsValid() ) { @@ -395,14 +397,14 @@ bool SHA1Val::DoFeed(const void* data, size_t size) return true; } -IntrusivePtr SHA1Val::DoGet() +StringValPtr SHA1Val::DoGet() { if ( ! IsValid() ) - return val_mgr->EmptyString(); + return zeek::val_mgr->EmptyString(); u_char digest[SHA_DIGEST_LENGTH]; hash_final(ctx, digest); - return make_intrusive(sha1_digest_print(digest)); + return zeek::make_intrusive(sha1_digest_print(digest)); } IMPLEMENT_OPAQUE_VALUE(SHA1Val) @@ -487,9 +489,9 @@ SHA256Val::~SHA256Val() EVP_MD_CTX_free(ctx); } -IntrusivePtr SHA256Val::DoClone(CloneState* state) +ValPtr SHA256Val::DoClone(CloneState* state) { - auto out = make_intrusive(); + auto out = zeek::make_intrusive(); if ( IsValid() ) { @@ -518,14 +520,14 @@ bool SHA256Val::DoFeed(const void* data, size_t size) return true; } -IntrusivePtr SHA256Val::DoGet() +StringValPtr SHA256Val::DoGet() { if ( ! IsValid() ) - return val_mgr->EmptyString(); + return zeek::val_mgr->EmptyString(); u_char digest[SHA256_DIGEST_LENGTH]; hash_final(ctx, digest); - return make_intrusive(sha256_digest_print(digest)); + return zeek::make_intrusive(sha256_digest_print(digest)); } IMPLEMENT_OPAQUE_VALUE(SHA256Val) @@ -711,26 +713,26 @@ BloomFilterVal::BloomFilterVal(probabilistic::BloomFilter* bf) bloom_filter = bf; } -IntrusivePtr BloomFilterVal::DoClone(CloneState* state) +ValPtr BloomFilterVal::DoClone(CloneState* state) { if ( bloom_filter ) { - auto bf = make_intrusive(bloom_filter->Clone()); + auto bf = zeek::make_intrusive(bloom_filter->Clone()); bf->Typify(type); return state->NewClone(this, std::move(bf)); } - return state->NewClone(this, make_intrusive()); + return state->NewClone(this, zeek::make_intrusive()); } -bool BloomFilterVal::Typify(IntrusivePtr arg_type) +bool BloomFilterVal::Typify(zeek::TypePtr arg_type) { if ( type ) return false; type = std::move(arg_type); - auto tl = make_intrusive(type); + auto tl = zeek::make_intrusive(type); tl->Append(type); hash = new CompositeHash(std::move(tl)); @@ -765,8 +767,8 @@ std::string BloomFilterVal::InternalState() const return bloom_filter->InternalState(); } -IntrusivePtr BloomFilterVal::Merge(const BloomFilterVal* x, - const BloomFilterVal* y) +BloomFilterValPtr BloomFilterVal::Merge(const BloomFilterVal* x, + const BloomFilterVal* y) { if ( x->Type() && // any one 0 is ok here y->Type() && @@ -791,7 +793,7 @@ IntrusivePtr BloomFilterVal::Merge(const BloomFilterVal* x, return nullptr; } - auto merged = make_intrusive(copy); + auto merged = zeek::make_intrusive(copy); if ( x->Type() && ! merged->Typify(x->Type()) ) { @@ -876,20 +878,20 @@ CardinalityVal::~CardinalityVal() delete hash; } -IntrusivePtr CardinalityVal::DoClone(CloneState* state) +ValPtr CardinalityVal::DoClone(CloneState* state) { return state->NewClone(this, - make_intrusive(new probabilistic::CardinalityCounter(*c))); + zeek::make_intrusive(new probabilistic::CardinalityCounter(*c))); } -bool CardinalityVal::Typify(IntrusivePtr arg_type) +bool CardinalityVal::Typify(zeek::TypePtr arg_type) { if ( type ) return false; type = std::move(arg_type); - auto tl = make_intrusive(type); + auto tl = zeek::make_intrusive(type); tl->Append(type); hash = new CompositeHash(std::move(tl)); @@ -957,14 +959,14 @@ ParaglobVal::ParaglobVal(std::unique_ptr p) this->internal_paraglob = std::move(p); } -IntrusivePtr ParaglobVal::Get(StringVal* &pattern) +VectorValPtr ParaglobVal::Get(StringVal* &pattern) { - auto rval = make_intrusive(zeek::id::string_vec); + auto rval = zeek::make_intrusive(zeek::id::string_vec); std::string string_pattern (reinterpret_cast(pattern->Bytes()), pattern->Len()); std::vector matches = this->internal_paraglob->get(string_pattern); for (unsigned int i = 0; i < matches.size(); i++) - rval->Assign(i, make_intrusive(matches.at(i))); + rval->Assign(i, zeek::make_intrusive(matches.at(i))); return rval; } @@ -1018,10 +1020,10 @@ bool ParaglobVal::DoUnserialize(const broker::data& data) return true; } -IntrusivePtr ParaglobVal::DoClone(CloneState* state) +ValPtr ParaglobVal::DoClone(CloneState* state) { try { - return make_intrusive + return zeek::make_intrusive (std::make_unique(this->internal_paraglob->serialize())); } catch (const paraglob::underflow_error& e) @@ -1035,3 +1037,5 @@ IntrusivePtr ParaglobVal::DoClone(CloneState* state) return nullptr; } } + +} diff --git a/src/OpaqueVal.h b/src/OpaqueVal.h index 848e6bed76..edfa7b6714 100644 --- a/src/OpaqueVal.h +++ b/src/OpaqueVal.h @@ -13,7 +13,19 @@ #include // for u_char namespace broker { class data; } + +namespace probabilistic { + class BloomFilter; + class CardinalityCounter; +} + +namespace zeek { + class OpaqueVal; +using OpaqueValPtr = zeek::IntrusivePtr; + +class BloomFilterVal; +using BloomFilterValPtr = zeek::IntrusivePtr; /** * Singleton that registers all available all available types of opaque @@ -21,7 +33,7 @@ class OpaqueVal; */ class OpaqueMgr { public: - using Factory = IntrusivePtr (); + using Factory = OpaqueValPtr (); /** * Return's a unique ID for the type of an opaque value. @@ -45,7 +57,7 @@ public: * is unknown, this will return null. * */ - IntrusivePtr Instantiate(const std::string& id) const; + OpaqueValPtr Instantiate(const std::string& id) const; /** Returns the global manager singleton object. */ static OpaqueMgr* mgr(); @@ -67,18 +79,18 @@ private: /** Macro to insert into an OpaqueVal-derived class's declaration. */ #define DECLARE_OPAQUE_VALUE(T) \ - friend class OpaqueMgr::Register; \ - friend IntrusivePtr make_intrusive(); \ + friend class zeek::OpaqueMgr::Register; \ + friend zeek::IntrusivePtr zeek::make_intrusive(); \ broker::expected DoSerialize() const override; \ bool DoUnserialize(const broker::data& data) override; \ const char* OpaqueName() const override { return #T; } \ - static IntrusivePtr OpaqueInstantiate() { return make_intrusive(); } + static zeek::OpaqueValPtr OpaqueInstantiate() { return zeek::make_intrusive(); } #define __OPAQUE_MERGE(a, b) a ## b #define __OPAQUE_ID(x) __OPAQUE_MERGE(_opaque, x) /** Macro to insert into an OpaqueVal-derived class's implementation file. */ -#define IMPLEMENT_OPAQUE_VALUE(T) static OpaqueMgr::Register __OPAQUE_ID(__LINE__)(#T); +#define IMPLEMENT_OPAQUE_VALUE(T) static zeek::OpaqueMgr::Register __OPAQUE_ID(__LINE__)(#T); /** * Base class for all opaque values. Opaque values are types that are managed @@ -89,7 +101,7 @@ class OpaqueVal : public Val { public: [[deprecated("Remove in v4.1. Construct from IntrusivePtr instead.")]] explicit OpaqueVal(zeek::OpaqueType* t); - explicit OpaqueVal(IntrusivePtr t); + explicit OpaqueVal(zeek::OpaqueTypePtr t); ~OpaqueVal() override; /** @@ -106,7 +118,7 @@ public: * @param data Broker representation as returned by *Serialize()*. * @return unserialized instances with reference count at +1 */ - static IntrusivePtr Unserialize(const broker::data& data); + static OpaqueValPtr Unserialize(const broker::data& data); protected: friend class Val; @@ -142,26 +154,21 @@ protected: * may also override this with a more efficient custom clone * implementation of their own. */ - IntrusivePtr DoClone(CloneState* state) override; + ValPtr DoClone(CloneState* state) override; /** * Helper function for derived class that need to record a type * during serialization. */ - static broker::expected SerializeType(const IntrusivePtr& t); + static broker::expected SerializeType(const zeek::TypePtr& t); /** * Helper function for derived class that need to restore a type * during unserialization. Returns the type at reference count +1. */ - static IntrusivePtr UnserializeType(const broker::data& data); + static zeek::TypePtr UnserializeType(const broker::data& data); }; -namespace probabilistic { - class BloomFilter; - class CardinalityCounter; -} - class HashVal : public OpaqueVal { public: template @@ -178,21 +185,21 @@ public: bool IsValid() const; bool Init(); bool Feed(const void* data, size_t size); - IntrusivePtr Get(); + StringValPtr Get(); protected: static void digest_one(EVP_MD_CTX* h, const Val* v); - static void digest_one(EVP_MD_CTX* h, const IntrusivePtr& v); + static void digest_one(EVP_MD_CTX* h, const ValPtr& v); HashVal() { valid = false; } [[deprecated("Remove in v4.1. Construct from IntrusivePtr instead.")]] explicit HashVal(zeek::OpaqueType* t); - explicit HashVal(IntrusivePtr t); + explicit HashVal(zeek::OpaqueTypePtr t); virtual bool DoInit(); virtual bool DoFeed(const void* data, size_t size); - virtual IntrusivePtr DoGet(); + virtual StringValPtr DoGet(); private: // This flag exists because Get() can only be called once. @@ -221,14 +228,14 @@ public: MD5Val(); ~MD5Val(); - IntrusivePtr DoClone(CloneState* state) override; + ValPtr DoClone(CloneState* state) override; protected: friend class Val; bool DoInit() override; bool DoFeed(const void* data, size_t size) override; - IntrusivePtr DoGet() override; + StringValPtr DoGet() override; DECLARE_OPAQUE_VALUE(MD5Val) private: @@ -244,14 +251,14 @@ public: SHA1Val(); ~SHA1Val(); - IntrusivePtr DoClone(CloneState* state) override; + ValPtr DoClone(CloneState* state) override; protected: friend class Val; bool DoInit() override; bool DoFeed(const void* data, size_t size) override; - IntrusivePtr DoGet() override; + StringValPtr DoGet() override; DECLARE_OPAQUE_VALUE(SHA1Val) private: @@ -267,14 +274,14 @@ public: SHA256Val(); ~SHA256Val(); - IntrusivePtr DoClone(CloneState* state) override; + ValPtr DoClone(CloneState* state) override; protected: friend class Val; bool DoInit() override; bool DoFeed(const void* data, size_t size) override; - IntrusivePtr DoGet() override; + StringValPtr DoGet() override; DECLARE_OPAQUE_VALUE(SHA256Val) private: @@ -302,12 +309,12 @@ public: explicit BloomFilterVal(probabilistic::BloomFilter* bf); ~BloomFilterVal() override; - IntrusivePtr DoClone(CloneState* state) override; + ValPtr DoClone(CloneState* state) override; - const IntrusivePtr& Type() const + const zeek::TypePtr& Type() const { return type; } - bool Typify(IntrusivePtr type); + bool Typify(zeek::TypePtr type); void Add(const Val* val); size_t Count(const Val* val) const; @@ -315,8 +322,8 @@ public: bool Empty() const; std::string InternalState() const; - static IntrusivePtr Merge(const BloomFilterVal* x, - const BloomFilterVal* y); + static BloomFilterValPtr Merge(const BloomFilterVal* x, + const BloomFilterVal* y); protected: friend class Val; @@ -328,25 +335,25 @@ private: BloomFilterVal(const BloomFilterVal&); BloomFilterVal& operator=(const BloomFilterVal&); - IntrusivePtr type; + zeek::TypePtr type; CompositeHash* hash; probabilistic::BloomFilter* bloom_filter; }; -class CardinalityVal: public OpaqueVal { +class CardinalityVal : public OpaqueVal { public: explicit CardinalityVal(probabilistic::CardinalityCounter*); ~CardinalityVal() override; - IntrusivePtr DoClone(CloneState* state) override; + ValPtr DoClone(CloneState* state) override; void Add(const Val* val); - const IntrusivePtr& Type() const + const zeek::TypePtr& Type() const { return type; } - bool Typify(IntrusivePtr type); + bool Typify(zeek::TypePtr type); probabilistic::CardinalityCounter* Get() { return c; }; @@ -355,7 +362,7 @@ protected: DECLARE_OPAQUE_VALUE(CardinalityVal) private: - IntrusivePtr type; + zeek::TypePtr type; CompositeHash* hash; probabilistic::CardinalityCounter* c; }; @@ -363,8 +370,8 @@ private: class ParaglobVal : public OpaqueVal { public: explicit ParaglobVal(std::unique_ptr p); - IntrusivePtr Get(StringVal* &pattern); - IntrusivePtr DoClone(CloneState* state) override; + VectorValPtr Get(StringVal* &pattern); + ValPtr DoClone(CloneState* state) override; bool operator==(const ParaglobVal& other) const; protected: @@ -375,3 +382,16 @@ protected: private: std::unique_ptr internal_paraglob; }; + +} + +using OpaqueMgr [[deprecated("Remove in v4.1. Use zeek::OpaqueMgr instead.")]] = zeek::OpaqueMgr; +using OpaqueVal [[deprecated("Remove in v4.1. Use zeek::OpaqueVal instead.")]] = zeek::OpaqueVal; +using HashVal [[deprecated("Remove in v4.1. Use zeek::HashVal instead.")]] = zeek::HashVal; +using MD5Val [[deprecated("Remove in v4.1. Use zeek::MD5Val instead.")]] = zeek::MD5Val; +using SHA1Val [[deprecated("Remove in v4.1. Use zeek::SHA1Val instead.")]] = zeek::SHA1Val; +using SHA256Val [[deprecated("Remove in v4.1. Use zeek::SHA256Val instead.")]] = zeek::SHA256Val; +using EntropyVal [[deprecated("Remove in v4.1. Use zeek::EntropyVal instead.")]] = zeek::EntropyVal; +using BloomFilterVal [[deprecated("Remove in v4.1. Use zeek::BloomFilterVal instead.")]] = zeek::BloomFilterVal; +using CardinalityVal [[deprecated("Remove in v4.1. Use zeek::CardinalityVal instead.")]] = zeek::CardinalityVal; +using ParaglobVal [[deprecated("Remove in v4.1. Use zeek::ParaglobVal instead.")]] = zeek::ParaglobVal; diff --git a/src/PacketFilter.cc b/src/PacketFilter.cc index 480326d070..61afbe0afd 100644 --- a/src/PacketFilter.cc +++ b/src/PacketFilter.cc @@ -23,7 +23,7 @@ void PacketFilter::AddSrc(const IPAddr& src, uint32_t tcp_flags, double probabil delete prev; } -void PacketFilter::AddSrc(Val* src, uint32_t tcp_flags, double probability) +void PacketFilter::AddSrc(zeek::Val* src, uint32_t tcp_flags, double probability) { Filter* f = new Filter; f->tcp_flags = tcp_flags; @@ -41,7 +41,7 @@ void PacketFilter::AddDst(const IPAddr& dst, uint32_t tcp_flags, double probabil delete prev; } -void PacketFilter::AddDst(Val* dst, uint32_t tcp_flags, double probability) +void PacketFilter::AddDst(zeek::Val* dst, uint32_t tcp_flags, double probability) { Filter* f = new Filter; f->tcp_flags = tcp_flags; @@ -57,7 +57,7 @@ bool PacketFilter::RemoveSrc(const IPAddr& src) return f != nullptr; } -bool PacketFilter::RemoveSrc(Val* src) +bool PacketFilter::RemoveSrc(zeek::Val* src) { auto f = static_cast(src_filter.Remove(src)); delete f; @@ -71,7 +71,7 @@ bool PacketFilter::RemoveDst(const IPAddr& dst) return f != nullptr; } -bool PacketFilter::RemoveDst(Val* dst) +bool PacketFilter::RemoveDst(zeek::Val* dst) { auto f = static_cast(dst_filter.Remove(dst)); delete f; diff --git a/src/PacketFilter.h b/src/PacketFilter.h index 4729a4cd5e..a485b604e8 100644 --- a/src/PacketFilter.h +++ b/src/PacketFilter.h @@ -6,7 +6,7 @@ #include "PrefixTable.h" class IP_Hdr; -class Val; +ZEEK_FORWARD_DECLARE_NAMESPACED(Val, zeek); class PacketFilter { public: @@ -17,16 +17,16 @@ public: // as an AddrVal or a SubnetVal) which hasn't any of TCP flags set // (TH_*) with the given probability (from 0..MAX_PROB). void AddSrc(const IPAddr& src, uint32_t tcp_flags, double probability); - void AddSrc(Val* src, uint32_t tcp_flags, double probability); + void AddSrc(zeek::Val* src, uint32_t tcp_flags, double probability); void AddDst(const IPAddr& src, uint32_t tcp_flags, double probability); - void AddDst(Val* src, uint32_t tcp_flags, double probability); + void AddDst(zeek::Val* src, uint32_t tcp_flags, double probability); // Removes the filter entry for the given src/dst // Returns false if filter doesn not exist. bool RemoveSrc(const IPAddr& src); - bool RemoveSrc(Val* dst); + bool RemoveSrc(zeek::Val* dst); bool RemoveDst(const IPAddr& dst); - bool RemoveDst(Val* dst); + bool RemoveDst(zeek::Val* dst); // Returns true if packet matches a drop filter bool Match(const IP_Hdr* ip, int len, int caplen); diff --git a/src/PrefixTable.cc b/src/PrefixTable.cc index 2ee59a2bf0..d3a481352c 100644 --- a/src/PrefixTable.cc +++ b/src/PrefixTable.cc @@ -40,7 +40,7 @@ void* PrefixTable::Insert(const IPAddr& addr, int width, void* data) return old; } -void* PrefixTable::Insert(const Val* value, void* data) +void* PrefixTable::Insert(const zeek::Val* value, void* data) { // [elem] -> elem if ( value->GetType()->Tag() == zeek::TYPE_LIST && @@ -81,7 +81,7 @@ std::list> PrefixTable::FindAll(const IPAddr& addr, i return out; } -std::list> PrefixTable::FindAll(const SubNetVal* value) const +std::list> PrefixTable::FindAll(const zeek::SubNetVal* value) const { return FindAll(value->AsSubNet().Prefix(), value->AsSubNet().LengthIPv6()); } @@ -100,7 +100,7 @@ void* PrefixTable::Lookup(const IPAddr& addr, int width, bool exact) const return node ? node->data : nullptr; } -void* PrefixTable::Lookup(const Val* value, bool exact) const +void* PrefixTable::Lookup(const zeek::Val* value, bool exact) const { // [elem] -> elem if ( value->GetType()->Tag() == zeek::TYPE_LIST && @@ -139,7 +139,7 @@ void* PrefixTable::Remove(const IPAddr& addr, int width) return old; } -void* PrefixTable::Remove(const Val* value) +void* PrefixTable::Remove(const zeek::Val* value) { // [elem] -> elem if ( value->GetType()->Tag() == zeek::TYPE_LIST && diff --git a/src/PrefixTable.h b/src/PrefixTable.h index 7d1bb96645..51b75d5456 100644 --- a/src/PrefixTable.h +++ b/src/PrefixTable.h @@ -8,8 +8,8 @@ extern "C" { #include "IPAddr.h" -class Val; -class SubNetVal; +ZEEK_FORWARD_DECLARE_NAMESPACED(Val, zeek); +ZEEK_FORWARD_DECLARE_NAMESPACED(SubNetVal, zeek); class PrefixTable { private: @@ -30,21 +30,21 @@ public: void* Insert(const IPAddr& addr, int width, void* data = nullptr); // Value may be addr or subnet. - void* Insert(const Val* value, void* data = nullptr); + void* Insert(const zeek::Val* value, void* data = nullptr); // Returns nil if not found, pointer to data otherwise. // For items without data, returns non-nil if found. // If exact is false, performs exact rather than longest-prefix match. void* Lookup(const IPAddr& addr, int width, bool exact = false) const; - void* Lookup(const Val* value, bool exact = false) const; + void* Lookup(const zeek::Val* value, bool exact = false) const; // Returns list of all found matches or empty list otherwise. std::list> FindAll(const IPAddr& addr, int width) const; - std::list> FindAll(const SubNetVal* value) const; + std::list> FindAll(const zeek::SubNetVal* value) const; // Returns pointer to data or nil if not found. void* Remove(const IPAddr& addr, int width); - void* Remove(const Val* value); + void* Remove(const zeek::Val* value); void Clear() { Clear_Patricia(tree, delete_function); } diff --git a/src/Queue.h b/src/Queue.h index 1e5447ef27..5d92e9b29c 100644 --- a/src/Queue.h +++ b/src/Queue.h @@ -2,6 +2,7 @@ #pragma once +#include #include // Queue.h -- @@ -22,6 +23,7 @@ // Entries must be either a pointer to the data or nonzero data with // sizeof(data) <= sizeof(void*). +namespace zeek { template class Queue { @@ -196,3 +198,8 @@ protected: template using PQueue = Queue; + +} // namespace zeek + +template using Queue [[deprecated("Remove in v4.1. Use zeek::Queue instead.")]] = zeek::Queue; +template using PQueue [[deprecated("Remove in v4.1. Use zeek::Queue instead.")]] = zeek::PQueue; diff --git a/src/RE.cc b/src/RE.cc index de8995fd4e..e553c1d3c0 100644 --- a/src/RE.cc +++ b/src/RE.cc @@ -10,7 +10,7 @@ #include "CCL.h" #include "EquivClass.h" #include "Reporter.h" -#include "BroString.h" +#include "ZeekString.h" CCL* curr_ccl = nullptr; @@ -209,7 +209,7 @@ bool Specific_RE_Matcher::MatchAll(const char* s) return MatchAll((const u_char*)(s), strlen(s)); } -bool Specific_RE_Matcher::MatchAll(const BroString* s) +bool Specific_RE_Matcher::MatchAll(const zeek::String* s) { // s->Len() does not include '\0'. return MatchAll(s->Bytes(), s->Len()); @@ -220,7 +220,7 @@ int Specific_RE_Matcher::Match(const char* s) return Match((const u_char*)(s), strlen(s)); } -int Specific_RE_Matcher::Match(const BroString* s) +int Specific_RE_Matcher::Match(const zeek::String* s) { return Match(s->Bytes(), s->Len()); } @@ -230,7 +230,7 @@ int Specific_RE_Matcher::LongestMatch(const char* s) return LongestMatch((const u_char*)(s), strlen(s)); } -int Specific_RE_Matcher::LongestMatch(const BroString* s) +int Specific_RE_Matcher::LongestMatch(const zeek::String* s) { return LongestMatch(s->Bytes(), s->Len()); } diff --git a/src/RE.h b/src/RE.h index dfadcaaf28..d639934f97 100644 --- a/src/RE.h +++ b/src/RE.h @@ -14,13 +14,15 @@ #include typedef int (*cce_func)(int); +namespace zeek { class String; } +using BroString [[deprecated("Remove in v4.1. Use zeek::String instead.")]] = zeek::String; + class CCL; class NFA_Machine; class DFA_Machine; class Specific_RE_Matcher; class RE_Matcher; class DFA_State; -class BroString; extern int case_insensitive; extern CCL* curr_ccl; @@ -36,7 +38,7 @@ typedef int AcceptIdx; typedef std::set AcceptingSet; typedef uint64_t MatchPos; typedef std::map AcceptingMatchSet; -typedef name_list string_list; +typedef zeek::name_list string_list; typedef enum { MATCH_ANYWHERE, MATCH_EXACTLY, } match_type; @@ -81,7 +83,7 @@ public: void ConvertCCLs(); bool MatchAll(const char* s); - bool MatchAll(const BroString* s); + bool MatchAll(const zeek::String* s); // Compiles a set of regular expressions simultaniously. // 'idx' contains indizes associated with the expressions. @@ -94,10 +96,10 @@ public: // if the pattern matches empty strings, matching continues // in an attempt to match at least one character. int Match(const char* s); - int Match(const BroString* s); + int Match(const zeek::String* s); int LongestMatch(const char* s); - int LongestMatch(const BroString* s); + int LongestMatch(const zeek::String* s); int LongestMatch(const u_char* bv, int n); EquivClass* EC() { return &equiv_class; } @@ -128,7 +130,7 @@ protected: std::map defs; std::map ccl_dict; - PList ccl_list; + zeek::PList ccl_list; EquivClass equiv_class; int* ecs; DFA_Machine* dfa; @@ -191,7 +193,7 @@ public: // Returns true if s exactly matches the pattern, false otherwise. bool MatchExactly(const char* s) { return re_exact->MatchAll(s); } - bool MatchExactly(const BroString* s) + bool MatchExactly(const zeek::String* s) { return re_exact->MatchAll(s); } // Returns the position in s just beyond where the first match @@ -200,14 +202,14 @@ public: // in an attempt to match at least one character. int MatchAnywhere(const char* s) { return re_anywhere->Match(s); } - int MatchAnywhere(const BroString* s) + int MatchAnywhere(const zeek::String* s) { return re_anywhere->Match(s); } // Note: it matches the *longest* prefix and returns the // length of matched prefix. It returns -1 on mismatch. int MatchPrefix(const char* s) { return re_exact->LongestMatch(s); } - int MatchPrefix(const BroString* s) + int MatchPrefix(const zeek::String* s) { return re_exact->LongestMatch(s); } int MatchPrefix(const u_char* s, int n) { return re_exact->LongestMatch(s, n); } diff --git a/src/RandTest.h b/src/RandTest.h index a030008eeb..fe6b871327 100644 --- a/src/RandTest.h +++ b/src/RandTest.h @@ -1,30 +1,31 @@ #pragma once +#include "zeek-config.h" #include #define RT_MONTEN 6 /* Bytes used as Monte Carlo co-ordinates. This should be no more bits than the mantissa of your "double" floating point type. */ -class EntropyVal; +ZEEK_FORWARD_DECLARE_NAMESPACED(EntropyVal, zeek); class RandTest { - public: - RandTest(); - void add(const void* buf, int bufl); - void end(double* r_ent, double* r_chisq, double* r_mean, - double* r_montepicalc, double* r_scc); +public: + RandTest(); + void add(const void* buf, int bufl); + void end(double* r_ent, double* r_chisq, double* r_mean, + double* r_montepicalc, double* r_scc); - private: - friend class EntropyVal; +private: + friend class zeek::EntropyVal; - int64_t ccount[256]; /* Bins to count occurrences of values */ - int64_t totalc; /* Total bytes counted */ - int mp; - int sccfirst; - unsigned int monte[RT_MONTEN]; - int64_t inmont, mcount; - double cexp, montex, montey, montepi, - sccu0, scclast, scct1, scct2, scct3; + int64_t ccount[256]; /* Bins to count occurrences of values */ + int64_t totalc; /* Total bytes counted */ + int mp; + int sccfirst; + unsigned int monte[RT_MONTEN]; + int64_t inmont, mcount; + double cexp, montex, montey, montepi, + sccu0, scclast, scct1, scct2, scct3; }; diff --git a/src/Reassem.h b/src/Reassem.h index 079de77584..3ca1bfc414 100644 --- a/src/Reassem.h +++ b/src/Reassem.h @@ -251,7 +251,7 @@ private: DataBlockMap block_map; }; -class Reassembler : public BroObj { +class Reassembler : public zeek::Obj { public: Reassembler(uint64_t init_seq, ReassemblerType reassem_type = REASSEM_UNKNOWN); ~Reassembler() override {} diff --git a/src/Reporter.cc b/src/Reporter.cc index 467ab7e0bf..893073fac7 100644 --- a/src/Reporter.cc +++ b/src/Reporter.cc @@ -73,8 +73,8 @@ void Reporter::InitOptions() auto wl_table = wl_val->AsTable(); HashKey* k; - IterCookie* c = wl_table->InitForIteration(); - TableEntryVal* v; + zeek::IterCookie* c = wl_table->InitForIteration(); + zeek::TableEntryVal* v; while ( (v = wl_table->NextEntry(k, c)) ) { @@ -165,7 +165,7 @@ void Reporter::ExprRuntimeError(const zeek::detail::Expr* expr, const char* fmt, throw InterpreterException(); } -void Reporter::RuntimeError(const Location* location, const char* fmt, ...) +void Reporter::RuntimeError(const zeek::detail::Location* location, const char* fmt, ...) { ++errors; PushLocation(location); @@ -345,7 +345,7 @@ bool Reporter::PermitFlowWeird(const char* name, return false; } -bool Reporter::PermitExpiredConnWeird(const char* name, const RecordVal& conn_id) +bool Reporter::PermitExpiredConnWeird(const char* name, const zeek::RecordVal& conn_id) { auto conn_tuple = std::make_tuple(conn_id.GetField("orig_h")->AsAddr(), conn_id.GetField("resp_h")->AsAddr(), @@ -384,7 +384,7 @@ void Reporter::Weird(const char* name, const char* addl) return; } - WeirdHelper(net_weird, {new StringVal(addl)}, "%s", name); + WeirdHelper(net_weird, {new zeek::StringVal(addl)}, "%s", name); } void Reporter::Weird(file_analysis::File* f, const char* name, const char* addl) @@ -398,7 +398,7 @@ void Reporter::Weird(file_analysis::File* f, const char* name, const char* addl) return; } - WeirdHelper(file_weird, {f->ToVal()->Ref(), new StringVal(addl)}, + WeirdHelper(file_weird, {f->ToVal()->Ref(), new zeek::StringVal(addl)}, "%s", name); } @@ -413,11 +413,11 @@ void Reporter::Weird(Connection* conn, const char* name, const char* addl) return; } - WeirdHelper(conn_weird, {conn->ConnVal()->Ref(), new StringVal(addl)}, + WeirdHelper(conn_weird, {conn->ConnVal()->Ref(), new zeek::StringVal(addl)}, "%s", name); } -void Reporter::Weird(IntrusivePtr conn_id, IntrusivePtr uid, +void Reporter::Weird(zeek::RecordValPtr conn_id, zeek::StringValPtr uid, const char* name, const char* addl) { UpdateWeirdStats(name); @@ -429,7 +429,7 @@ void Reporter::Weird(IntrusivePtr conn_id, IntrusivePtr ui } WeirdHelper(expired_conn_weird, - {conn_id.release(), uid.release(), new StringVal(addl)}, + {conn_id.release(), uid.release(), new zeek::StringVal(addl)}, "%s", name); } @@ -444,7 +444,7 @@ void Reporter::Weird(const IPAddr& orig, const IPAddr& resp, const char* name, c } WeirdHelper(flow_weird, - {new AddrVal(orig), new AddrVal(resp), new StringVal(addl)}, + {new zeek::AddrVal(orig), new zeek::AddrVal(resp), new zeek::StringVal(addl)}, "%s", name); } @@ -469,11 +469,11 @@ void Reporter::DoLog(const char* prefix, EventHandlerPtr event, FILE* out, { ODesc d; - std::pair locs = locations.back(); + std::pair locs = locations.back(); if ( locs.first ) { - if ( locs.first != &no_location ) + if ( locs.first != &zeek::detail::no_location ) locs.first->Describe(&d); else @@ -483,7 +483,7 @@ void Reporter::DoLog(const char* prefix, EventHandlerPtr event, FILE* out, { d.Add(" and "); - if ( locs.second != &no_location ) + if ( locs.second != &zeek::detail::no_location ) locs.second->Describe(&d); else @@ -558,19 +558,19 @@ void Reporter::DoLog(const char* prefix, EventHandlerPtr event, FILE* out, vl.reserve(vl_size); if ( time ) - vl.emplace_back(make_intrusive(network_time ? network_time : current_time())); + vl.emplace_back(zeek::make_intrusive(network_time ? network_time : current_time())); - vl.emplace_back(make_intrusive(buffer)); + vl.emplace_back(zeek::make_intrusive(buffer)); if ( location ) - vl.emplace_back(make_intrusive(loc_str.c_str())); + vl.emplace_back(zeek::make_intrusive(loc_str.c_str())); if ( conn ) vl.emplace_back(conn->ConnVal()); if ( addl ) for ( auto v : *addl ) - vl.emplace_back(AdoptRef{}, v); + vl.emplace_back(zeek::AdoptRef{}, v); if ( conn ) conn->EnqueueEvent(event, nullptr, std::move(vl)); diff --git a/src/Reporter.h b/src/Reporter.h index 0c09dfd722..d82e4d4ac9 100644 --- a/src/Reporter.h +++ b/src/Reporter.h @@ -18,13 +18,18 @@ namespace analyzer { class Analyzer; } namespace file_analysis { class File; } class Connection; -class Location; class Reporter; class EventHandlerPtr; -class RecordVal; -class StringVal; +ZEEK_FORWARD_DECLARE_NAMESPACED(RecordVal, zeek); +ZEEK_FORWARD_DECLARE_NAMESPACED(StringVal, zeek); +namespace zeek { template class IntrusivePtr; +using RecordValPtr = zeek::IntrusivePtr; +using StringValPtr = zeek::IntrusivePtr; +} + +ZEEK_FORWARD_DECLARE_NAMESPACED(Location, zeek::detail); // One cannot raise this exception directly, go through the // Reporter's methods instead. @@ -90,14 +95,14 @@ public: // Report a runtime error in evaluating a Bro script expression. This // function will not return but raise an InterpreterException. - [[noreturn]] void RuntimeError(const Location* location, const char* fmt, ...) __attribute__((format(printf, 3, 4))); + [[noreturn]] void RuntimeError(const zeek::detail::Location* location, const char* fmt, ...) __attribute__((format(printf, 3, 4))); // Report a traffic weirdness, i.e., an unexpected protocol situation // that may lead to incorrectly processing a connnection. 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(Connection* conn, const char* name, const char* addl = ""); // Raises conn_weird(). - void Weird(IntrusivePtr conn_id, IntrusivePtr uid, + void Weird(zeek::RecordValPtr conn_id, zeek::StringValPtr uid, const char* name, const char* addl = ""); // Raises expired_conn_weird(). void Weird(const IPAddr& orig, const IPAddr& resp, const char* name, const char* addl = ""); // Raises flow_weird(). @@ -126,11 +131,11 @@ public: // 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 // valid until the location is popped. - void PushLocation(const Location* location) - { locations.push_back(std::pair(location, 0)); } + void PushLocation(const zeek::detail::Location* location) + { locations.push_back(std::pair(location, 0)); } - void PushLocation(const Location* loc1, const Location* loc2) - { locations.push_back(std::pair(loc1, loc2)); } + void PushLocation(const zeek::detail::Location* loc1, const zeek::detail::Location* loc2) + { locations.push_back(std::pair(loc1, loc2)); } // Removes the top-most location information from stack. void PopLocation() @@ -270,7 +275,7 @@ private: { return weird_sampling_whitelist.find(name) != weird_sampling_whitelist.end(); } bool PermitNetWeird(const char* name); bool PermitFlowWeird(const char* name, const IPAddr& o, const IPAddr& r); - bool PermitExpiredConnWeird(const char* name, const RecordVal& conn_id); + bool PermitExpiredConnWeird(const char* name, const zeek::RecordVal& conn_id); bool EmitToStderr(bool flag) { return flag || ! after_zeek_init; } @@ -284,7 +289,7 @@ private: bool after_zeek_init; bool abort_on_scripting_errors = false; - std::list > locations; + std::list > locations; uint64_t weird_count; WeirdCountMap weird_count_by_type; diff --git a/src/Rule.h b/src/Rule.h index 29099dcb8e..5cfbcb3d4e 100644 --- a/src/Rule.h +++ b/src/Rule.h @@ -14,12 +14,12 @@ class RuleAction; class RuleHdrTest; class Rule; -typedef PList rule_list; -typedef std::map rule_dict; +using rule_list = zeek::PList; +using rule_dict = std::map; class Rule { public: - Rule(const char* arg_id, const Location& arg_location) + Rule(const char* arg_id, const zeek::detail::Location& arg_location) { id = copy_string(arg_id); idx = rule_counter++; @@ -47,7 +47,7 @@ public: uint32_t offset = 0, uint32_t depth = INT_MAX); void AddRequires(const char* id, bool opposite_direction, bool negate); - const Location& GetLocation() const { return location; } + const zeek::detail::Location& GetLocation() const { return location; } void PrintDebug(); @@ -58,9 +58,9 @@ private: void SortHdrTests(); - typedef PList rule_action_list; - typedef PList rule_condition_list; - typedef PList rule_hdr_test_list; + using rule_action_list = zeek::PList; + using rule_condition_list = zeek::PList; + using rule_hdr_test_list = zeek::PList; rule_hdr_test_list hdr_tests; rule_condition_list conditions; @@ -74,7 +74,7 @@ private: bool negate; // negate test }; - typedef PList precond_list; + using precond_list = zeek::PList; precond_list preconds; rule_list dependents; // rules w/ us as a precondition @@ -92,13 +92,13 @@ private: uint32_t depth; }; - typedef PList pattern_list; + using pattern_list = zeek::PList; pattern_list patterns; Rule* next; // Linkage within RuleHdrTest tree: // Ptr to next rule using the same RuleHdrTests - Location location; + zeek::detail::Location location; // Rules and payloads are numbered individually. static unsigned int rule_counter; diff --git a/src/RuleAction.cc b/src/RuleAction.cc index 031fa0e6b2..fde44ee464 100644 --- a/src/RuleAction.cc +++ b/src/RuleAction.cc @@ -22,9 +22,9 @@ void RuleActionEvent::DoAction(const Rule* parent, RuleEndpointState* state, { if ( signature_match ) mgr.Enqueue(signature_match, - IntrusivePtr{AdoptRef{}, rule_matcher->BuildRuleStateValue(parent, state)}, - make_intrusive(msg), - data ? make_intrusive(len, (const char*)data) : val_mgr->EmptyString() + zeek::IntrusivePtr{zeek::AdoptRef{}, rule_matcher->BuildRuleStateValue(parent, state)}, + zeek::make_intrusive(msg), + data ? zeek::make_intrusive(len, (const char*)data) : zeek::val_mgr->EmptyString() ); } diff --git a/src/RuleCondition.cc b/src/RuleCondition.cc index 2735a876b0..bb68a25483 100644 --- a/src/RuleCondition.cc +++ b/src/RuleCondition.cc @@ -129,7 +129,7 @@ bool RuleConditionPayloadSize::DoMatch(Rule* rule, RuleEndpointState* state, RuleConditionEval::RuleConditionEval(const char* func) { - id = global_scope()->Find(func).get(); + id = zeek::detail::global_scope()->Find(func).get(); if ( ! id ) { rules_error("unknown identifier", func); @@ -170,12 +170,12 @@ bool RuleConditionEval::DoMatch(Rule* rule, RuleEndpointState* state, // Call function with a signature_state value as argument. zeek::Args args; args.reserve(2); - args.emplace_back(AdoptRef{}, rule_matcher->BuildRuleStateValue(rule, state)); + args.emplace_back(zeek::AdoptRef{}, rule_matcher->BuildRuleStateValue(rule, state)); if ( data ) - args.emplace_back(make_intrusive(len, (const char*) data)); + args.emplace_back(zeek::make_intrusive(len, (const char*) data)); else - args.emplace_back(val_mgr->EmptyString()); + args.emplace_back(zeek::val_mgr->EmptyString()); bool result = false; diff --git a/src/RuleMatcher.cc b/src/RuleMatcher.cc index 3a314fde1f..622cac36d6 100644 --- a/src/RuleMatcher.cc +++ b/src/RuleMatcher.cc @@ -7,7 +7,7 @@ #include "RuleAction.h" #include "RuleCondition.h" -#include "BroString.h" +#include "ZeekString.h" #include "ID.h" #include "IntrusivePtr.h" #include "IntSet.h" @@ -78,15 +78,15 @@ RuleHdrTest::RuleHdrTest(Prot arg_prot, Comp arg_comp, vector arg_v) level = 0; } -Val* RuleMatcher::BuildRuleStateValue(const Rule* rule, - const RuleEndpointState* state) const +zeek::Val* RuleMatcher::BuildRuleStateValue(const Rule* rule, + const RuleEndpointState* state) const { static auto signature_state = zeek::id::find_type("signature_state"); - RecordVal* val = new RecordVal(signature_state); - val->Assign(0, make_intrusive(rule->ID())); + auto* val = new zeek::RecordVal(signature_state); + val->Assign(0, zeek::make_intrusive(rule->ID())); val->Assign(1, state->GetAnalyzer()->ConnVal()); - val->Assign(2, val_mgr->Bool(state->is_orig)); - val->Assign(3, val_mgr->Count(state->payload_size)); + val->Assign(2, zeek::val_mgr->Bool(state->is_orig)); + val->Assign(3, zeek::val_mgr->Count(state->payload_size)); return val; } @@ -958,7 +958,7 @@ void RuleMatcher::Match(RuleEndpointState* state, Rule::PatternType type, if ( ! state->matched_by_patterns.is_member(r) ) { state->matched_by_patterns.push_back(r); - BroString* s = new BroString(data, data_len, false); + zeek::String* s = new zeek::String(data, data_len, false); state->matched_text.push_back(s); } @@ -998,7 +998,7 @@ void RuleMatcher::ExecPureRules(RuleEndpointState* state, bool eos) } } -bool RuleMatcher::ExecRulePurely(Rule* r, BroString* s, +bool RuleMatcher::ExecRulePurely(Rule* r, zeek::String* s, RuleEndpointState* state, bool eos) { if ( is_member_of(state->matched_rules, r->Index()) ) @@ -1272,9 +1272,9 @@ void RuleMatcher::DumpStateStats(BroFile* f, RuleHdrTest* hdr_test) DumpStateStats(f, h); } -static Val* get_bro_val(const char* label) +static zeek::Val* get_bro_val(const char* label) { - auto id = lookup_ID(label, GLOBAL_MODULE_NAME, false); + auto id = zeek::detail::lookup_ID(label, GLOBAL_MODULE_NAME, false); if ( ! id ) { rules_error("unknown script-level identifier", label); @@ -1288,7 +1288,7 @@ static Val* get_bro_val(const char* label) // 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 // over appending to the masked val list. -static bool val_to_maskedval(Val* v, maskedvalue_list* append_to, +static bool val_to_maskedval(zeek::Val* v, maskedvalue_list* append_to, vector* prefix_vector) { MaskedValue* mval = new MaskedValue; @@ -1358,7 +1358,7 @@ static bool val_to_maskedval(Val* v, maskedvalue_list* append_to, void id_to_maskedvallist(const char* id, maskedvalue_list* append_to, vector* prefix_vector) { - Val* v = get_bro_val(id); + zeek::Val* v = get_bro_val(id); if ( ! v ) return; @@ -1377,10 +1377,10 @@ void id_to_maskedvallist(const char* id, maskedvalue_list* append_to, char* id_to_str(const char* id) { - const BroString* src; + const zeek::String* src; char* dst; - Val* v = get_bro_val(id); + zeek::Val* v = get_bro_val(id); if ( ! v ) goto error; @@ -1403,7 +1403,7 @@ error: uint32_t id_to_uint(const char* id) { - Val* v = get_bro_val(id); + zeek::Val* v = get_bro_val(id); if ( ! v ) return 0; diff --git a/src/RuleMatcher.h b/src/RuleMatcher.h index 8e644a2aa0..bdbea606ce 100644 --- a/src/RuleMatcher.h +++ b/src/RuleMatcher.h @@ -27,7 +27,6 @@ extern FILE* rules_in; extern int rules_line_number; extern const char* current_rule_file; -class Val; class BroFile; class IntSet; class IP_Hdr; @@ -37,6 +36,8 @@ class Specific_RE_Matcher; class RuleMatcher; extern RuleMatcher* rule_matcher; +ZEEK_FORWARD_DECLARE_NAMESPACED(Val, zeek); + namespace analyzer { namespace pia { class PIA; } class Analyzer; @@ -56,9 +57,9 @@ struct MaskedValue { uint32_t mask; }; -typedef PList maskedvalue_list; -typedef PList string_list; -typedef PList bstr_list; +using maskedvalue_list = zeek::PList; +using string_list = zeek::PList; +using bstr_list = zeek::PList; // Get values from Bro's script-level variables. extern void id_to_maskedvallist(const char* id, maskedvalue_list* append_to, @@ -116,7 +117,7 @@ private: int_list ids; // (only needed for debugging) }; - typedef PList pattern_set_list; + using pattern_set_list = zeek::PList; pattern_set_list psets[Rule::TYPES]; // List of rules belonging to this node. @@ -130,7 +131,7 @@ private: RuleHdrTest* child; }; -typedef PList rule_hdr_test_list; +using rule_hdr_test_list = zeek::PList; // RuleEndpointState keeps the per-stream matching state of one // connection endpoint. @@ -165,7 +166,7 @@ private: Rule::PatternType type; }; - typedef PList matcher_list; + using matcher_list = zeek::PList; analyzer::Analyzer* analyzer; RuleEndpointState* opposite; @@ -204,8 +205,7 @@ private: RE_Match_State* state; }; - typedef PList matcher_list; - + using matcher_list = zeek::PList; matcher_list matchers; }; @@ -304,8 +304,8 @@ public: unsigned int misses; // # cache misses }; - Val* BuildRuleStateValue(const Rule* rule, - const RuleEndpointState* state) const; + zeek::Val* BuildRuleStateValue(const Rule* rule, + const RuleEndpointState* state) const; void GetStats(Stats* stats, RuleHdrTest* hdr_test = nullptr); void DumpStats(BroFile* f); @@ -338,7 +338,7 @@ private: // Eval a rule under the assumption that all its patterns // have already matched. s holds the text the rule matched, // or nil if N/A. - bool ExecRulePurely(Rule* r, BroString* s, + bool ExecRulePurely(Rule* r, zeek::String* s, RuleEndpointState* state, bool eos); // Execute the actions associated with a rule. diff --git a/src/Scope.cc b/src/Scope.cc index fe0695d014..78d1aa8a44 100644 --- a/src/Scope.cc +++ b/src/Scope.cc @@ -10,13 +10,15 @@ #include "Reporter.h" #include "module_util.h" -typedef PList scope_list; +namespace zeek::detail { + +using scope_list = zeek::PList; static scope_list scopes; static Scope* top_scope; -Scope::Scope(IntrusivePtr id, - std::unique_ptr>> al) +Scope::Scope(zeek::detail::IDPtr id, + std::unique_ptr> al) : scope_id(std::move(id)), attrs(std::move(al)) { return_type = nullptr; @@ -35,7 +37,7 @@ Scope::Scope(IntrusivePtr id, } } -const IntrusivePtr& Scope::Find(std::string_view name) const +const zeek::detail::IDPtr& Scope::Find(std::string_view name) const { auto entry = local.find(name); @@ -45,7 +47,7 @@ const IntrusivePtr& Scope::Find(std::string_view name) const return zeek::detail::ID::nil; } -IntrusivePtr Scope::Remove(std::string_view name) +zeek::detail::IDPtr Scope::Remove(std::string_view name) { auto entry = local.find(name); @@ -59,12 +61,12 @@ IntrusivePtr Scope::Remove(std::string_view name) return nullptr; } -IntrusivePtr Scope::GenerateTemporary(const char* name) +zeek::detail::IDPtr Scope::GenerateTemporary(const char* name) { - return make_intrusive(name, zeek::detail::SCOPE_FUNCTION, false); + return zeek::make_intrusive(name, zeek::detail::SCOPE_FUNCTION, false); } -std::vector> Scope::GetInits() +std::vector Scope::GetInits() { auto rval = std::move(inits); inits = {}; @@ -119,9 +121,9 @@ TraversalCode Scope::Traverse(TraversalCallback* cb) const } -const IntrusivePtr& lookup_ID(const char* name, const char* curr_module, - bool no_global, bool same_module_only, - bool check_export) +const zeek::detail::IDPtr& lookup_ID(const char* name, const char* curr_module, + bool no_global, bool same_module_only, + bool check_export) { std::string fullname = make_full_var_name(curr_module, name); @@ -137,14 +139,14 @@ const IntrusivePtr& lookup_ID(const char* name, const char* cu { if ( need_export && ! id->IsExport() && ! in_debug ) reporter->Error("identifier is not exported: %s", - fullname.c_str()); + fullname.c_str()); return id; } } if ( ! no_global && (strcmp(GLOBAL_MODULE_NAME, curr_module) == 0 || - ! same_module_only) ) + ! same_module_only) ) { std::string globalname = make_full_var_name(GLOBAL_MODULE_NAME, name); return global_scope()->Find(globalname); @@ -153,8 +155,8 @@ const IntrusivePtr& lookup_ID(const char* name, const char* cu return zeek::detail::ID::nil; } -IntrusivePtr install_ID(const char* name, const char* module_name, - bool is_global, bool is_export) +zeek::detail::IDPtr install_ID(const char* name, const char* module_name, + bool is_global, bool is_export) { if ( scopes.empty() && ! is_global ) reporter->InternalError("local identifier in global scope"); @@ -171,7 +173,7 @@ IntrusivePtr install_ID(const char* name, const char* module_n std::string full_name = make_full_var_name(module_name, name); - auto id = make_intrusive(full_name.data(), scope, is_export); + auto id = zeek::make_intrusive(full_name.data(), scope, is_export); if ( zeek::detail::SCOPE_FUNCTION != scope ) global_scope()->Insert(std::move(full_name), id); @@ -189,14 +191,14 @@ void push_existing_scope(Scope* scope) scopes.push_back(scope); } -void push_scope(IntrusivePtr id, - std::unique_ptr>> attrs) +void push_scope(zeek::detail::IDPtr id, + std::unique_ptr> attrs) { top_scope = new Scope(std::move(id), std::move(attrs)); scopes.push_back(top_scope); } -IntrusivePtr pop_scope() +ScopePtr pop_scope() { if ( scopes.empty() ) reporter->InternalError("scope underflow"); @@ -206,7 +208,7 @@ IntrusivePtr pop_scope() top_scope = scopes.empty() ? nullptr : scopes.back(); - return {AdoptRef{}, old_top}; + return {zeek::AdoptRef{}, old_top}; } Scope* current_scope() @@ -218,3 +220,14 @@ Scope* global_scope() { return scopes.empty() ? 0 : scopes.front(); } + +} + +const zeek::detail::ID* lookup_ID( + const char* name, const char* module, + bool no_global, + bool same_module_only, + bool check_export) + { + return zeek::detail::lookup_ID(name, module, no_global, same_module_only, check_export).get(); + } diff --git a/src/Scope.h b/src/Scope.h index 0d09b9033c..522a335a08 100644 --- a/src/Scope.h +++ b/src/Scope.h @@ -12,19 +12,31 @@ #include "IntrusivePtr.h" #include "TraverseTypes.h" -template class IntrusivePtr; -class ListVal; - -namespace zeek { class Type; } +ZEEK_FORWARD_DECLARE_NAMESPACED(Type, zeek); using BroType [[deprecated("Remove in v4.1. Use zeek::Type instead.")]] = zeek::Type; + ZEEK_FORWARD_DECLARE_NAMESPACED(ID, zeek::detail); +ZEEK_FORWARD_DECLARE_NAMESPACED(Attr, zeek::detail); -class Scope : public BroObj { +namespace zeek { + +template class IntrusivePtr; +using TypePtr = zeek::IntrusivePtr; + +namespace detail { + +using AttrPtr = zeek::IntrusivePtr; +using IDPtr = zeek::IntrusivePtr; + +class Scope; +using ScopePtr = zeek::IntrusivePtr; + +class Scope : public Obj { public: - explicit Scope(IntrusivePtr id, - std::unique_ptr>> al); + explicit Scope(zeek::detail::IDPtr id, + std::unique_ptr> al); - const IntrusivePtr& Find(std::string_view name) const; + const zeek::detail::IDPtr& Find(std::string_view name) const; template [[deprecated("Remove in v4.1. Use Find().")]] @@ -34,34 +46,34 @@ public: template void Insert(N&& name, I&& id) { local[std::forward(name)] = std::forward(id); } - IntrusivePtr Remove(std::string_view name); + zeek::detail::IDPtr Remove(std::string_view name); [[deprecated("Remove in v4.1. Use GetID().")]] zeek::detail::ID* ScopeID() const { return scope_id.get(); } - const IntrusivePtr& GetID() const + const zeek::detail::IDPtr& GetID() const { return scope_id; } - const std::unique_ptr>>& Attrs() const + const std::unique_ptr>& Attrs() const { return attrs; } [[deprecated("Remove in v4.1. Use GetReturnTrype().")]] zeek::Type* ReturnType() const { return return_type.get(); } - const IntrusivePtr& GetReturnType() const + const zeek::TypePtr& GetReturnType() const { return return_type; } size_t Length() const { return local.size(); } const auto& Vars() { return local; } - IntrusivePtr GenerateTemporary(const char* name); + zeek::detail::IDPtr GenerateTemporary(const char* name); // Returns the list of variables needing initialization, and // removes it from this Scope. - std::vector> GetInits(); + std::vector GetInits(); // Adds a variable to the list. - void AddInit(IntrusivePtr id) + void AddInit(zeek::detail::IDPtr id) { inits.emplace_back(std::move(id)); } void Describe(ODesc* d) const override; @@ -69,33 +81,55 @@ public: TraversalCode Traverse(TraversalCallback* cb) const; protected: - IntrusivePtr scope_id; - std::unique_ptr>> attrs; - IntrusivePtr return_type; - std::map, std::less<>> local; - std::vector> inits; + zeek::detail::IDPtr scope_id; + std::unique_ptr> attrs; + zeek::TypePtr return_type; + std::map> local; + std::vector inits; }; - -extern bool in_debug; - // If no_global is true, don't search in the default "global" namespace. -extern const IntrusivePtr& lookup_ID(const char* name, const char* module, - bool no_global = false, - bool same_module_only = false, - bool check_export = true); +extern const zeek::detail::IDPtr& lookup_ID( + const char* name, const char* module, + bool no_global = false, + bool same_module_only = false, + bool check_export = true); -extern IntrusivePtr install_ID(const char* name, const char* module_name, - bool is_global, bool is_export); +extern zeek::detail::IDPtr install_ID( + const char* name, const char* module_name, + bool is_global, bool is_export); -extern void push_scope(IntrusivePtr id, - std::unique_ptr>> attrs); +extern void push_scope(zeek::detail::IDPtr id, + std::unique_ptr> attrs); extern void push_existing_scope(Scope* scope); // Returns the one popped off. -extern IntrusivePtr pop_scope(); +extern ScopePtr pop_scope(); extern Scope* current_scope(); extern Scope* global_scope(); // Current module (identified by its name). extern std::string current_module; + +} // namespace detail +} // namespace zeek + +extern bool in_debug; + +using Scope [[deprecated("Remove in v4.1. Use zeek::detail::Scope instead.")]] = zeek::detail::Scope; +extern std::string& current_module [[deprecated("Remove in v4.1. Use zeek::detail::current_module.")]]; + +constexpr auto install_ID [[deprecated("Remove in v4.1 Use zeek::detail::install_ID instead.")]] = zeek::detail::install_ID; +constexpr auto push_scope [[deprecated("Remove in v4.1 Use zeek::detail::push_scope instead.")]] = zeek::detail::push_scope; +constexpr auto push_existing_scope[[deprecated("Remove in v4.1 Use zeek::detail::push_existing_scope instead.")]] = zeek::detail::push_existing_scope; +constexpr auto pop_scope [[deprecated("Remove in v4.1 Use zeek::detail::pop_scope instead.")]] = zeek::detail::pop_scope; +constexpr auto current_scope [[deprecated("Remove in v4.1 Use zeek::detail::current_scope instead.")]] = zeek::detail::current_scope; +constexpr auto global_scope [[deprecated("Remove in v4.1 Use zeek::detail::global_scope instead.")]] = zeek::detail::global_scope; + +// Because of the use of default arguments, this function can't be aliased like the rest. +[[deprecated("Remove in v4.1 Use zeek::detail::lookup_ID instead.")]] +extern const zeek::detail::ID* lookup_ID( + const char* name, const char* module, + bool no_global = false, + bool same_module_only = false, + bool check_export = true); diff --git a/src/Sessions.cc b/src/Sessions.cc index c1981b3628..ec571f4bff 100644 --- a/src/Sessions.cc +++ b/src/Sessions.cc @@ -703,7 +703,7 @@ void NetSessions::DoNextPacket(double t, const Packet* pkt, const IP_Hdr* ip_hdr conn->CheckFlowLabel(is_orig, ip_hdr->FlowLabel()); - IntrusivePtr pkt_hdr_val; + zeek::ValPtr pkt_hdr_val; if ( ipv6_ext_headers && ip_hdr->NumHeaders() > 1 ) { @@ -920,7 +920,7 @@ FragReassembler* NetSessions::NextFragment(double t, const IP_Hdr* ip, return f; } -Connection* NetSessions::FindConnection(Val* v) +Connection* NetSessions::FindConnection(zeek::Val* v) { const auto& vt = v->GetType(); if ( ! zeek::IsRecord(vt->Tag()) ) @@ -958,8 +958,8 @@ Connection* NetSessions::FindConnection(Val* v) const IPAddr& orig_addr = (*vl)[orig_h]->AsAddr(); const IPAddr& resp_addr = (*vl)[resp_h]->AsAddr(); - PortVal* orig_portv = (*vl)[orig_p]->AsPortVal(); - PortVal* resp_portv = (*vl)[resp_p]->AsPortVal(); + zeek::PortVal* orig_portv = (*vl)[orig_p]->AsPortVal(); + zeek::PortVal* resp_portv = (*vl)[resp_p]->AsPortVal(); ConnID id; @@ -1236,7 +1236,7 @@ bool NetSessions::IsLikelyServerPort(uint32_t port, TransportProto proto) const if ( ! have_cache ) { - auto likely_server_ports = zeek::id::find_val("likely_server_ports"); + auto likely_server_ports = zeek::id::find_val("likely_server_ports"); auto lv = likely_server_ports->ToPureListVal(); for ( int i = 0; i < lv->Length(); i++ ) port_cache.insert(lv->Idx(i)->InternalUnsigned()); diff --git a/src/Sessions.h b/src/Sessions.h index d5edf62291..e128a1719a 100644 --- a/src/Sessions.h +++ b/src/Sessions.h @@ -61,7 +61,7 @@ public: // Looks up the connection referred to by the given Val, // which should be a conn_id record. Returns nil if there's // no such connection or the Val is ill-formed. - Connection* FindConnection(Val* v); + Connection* FindConnection(zeek::Val* v); void Remove(Connection* c); void Remove(FragReassembler* f); diff --git a/src/SmithWaterman.cc b/src/SmithWaterman.cc index f77f790055..4d24a0d70c 100644 --- a/src/SmithWaterman.cc +++ b/src/SmithWaterman.cc @@ -12,7 +12,7 @@ #include "Val.h" BroSubstring::BroSubstring(const BroSubstring& bst) -: BroString((const BroString&) bst), _num(), _new(bst._new) +: zeek::String((const zeek::String&) bst), _num(), _new(bst._new) { for ( BSSAlignVecCIt it = bst._aligns.begin(); it != bst._aligns.end(); ++it ) _aligns.push_back(*it); @@ -20,7 +20,7 @@ BroSubstring::BroSubstring(const BroSubstring& bst) const BroSubstring& BroSubstring::operator=(const BroSubstring& bst) { - BroString::operator=(bst); + zeek::String::operator=(bst); _aligns.clear(); @@ -32,7 +32,7 @@ const BroSubstring& BroSubstring::operator=(const BroSubstring& bst) return *this; } -void BroSubstring::AddAlignment(const BroString* str, int index) +void BroSubstring::AddAlignment(const zeek::String* str, int index) { _aligns.push_back(BSSAlign(str, index)); } @@ -56,14 +56,14 @@ bool BroSubstring::DoesCover(const BroSubstring* bst) const return true; } -VectorVal* BroSubstring::VecToPolicy(Vec* vec) +zeek::VectorVal* BroSubstring::VecToPolicy(Vec* vec) { static auto sw_substring_type = zeek::id::find_type("sw_substring"); static auto sw_align_type = zeek::id::find_type("sw_align"); static auto sw_align_vec_type = zeek::id::find_type("sw_align_vec"); static auto sw_substring_vec_type = zeek::id::find_type("sw_substring_vec"); - auto result = make_intrusive(sw_substring_vec_type); + auto result = zeek::make_intrusive(sw_substring_vec_type); if ( vec ) { @@ -71,24 +71,24 @@ VectorVal* BroSubstring::VecToPolicy(Vec* vec) { BroSubstring* bst = (*vec)[i]; - auto st_val = make_intrusive(sw_substring_type); - st_val->Assign(0, make_intrusive(new BroString(*bst))); + auto st_val = zeek::make_intrusive(sw_substring_type); + st_val->Assign(0, zeek::make_intrusive(new zeek::String(*bst))); - auto aligns = make_intrusive(sw_align_vec_type); + auto aligns = zeek::make_intrusive(sw_align_vec_type); for ( unsigned int j = 0; j < bst->GetNumAlignments(); ++j ) { const BSSAlign& align = (bst->GetAlignments())[j]; - auto align_val = make_intrusive(sw_align_type); - align_val->Assign(0, make_intrusive(new BroString(*align.string))); - align_val->Assign(1, val_mgr->Count(align.index)); + auto align_val = zeek::make_intrusive(sw_align_type); + align_val->Assign(0, zeek::make_intrusive(new zeek::String(*align.string))); + align_val->Assign(1, zeek::val_mgr->Count(align.index)); aligns->Assign(j + 1, std::move(align_val)); } st_val->Assign(1, std::move(aligns)); - st_val->Assign(2, val_mgr->Bool(bst->IsNewAlignment())); + st_val->Assign(2, zeek::val_mgr->Bool(bst->IsNewAlignment())); result->Assign(i + 1, std::move(st_val)); } } @@ -96,7 +96,7 @@ VectorVal* BroSubstring::VecToPolicy(Vec* vec) return result.release(); } -BroSubstring::Vec* BroSubstring::VecFromPolicy(VectorVal* vec) +BroSubstring::Vec* BroSubstring::VecFromPolicy(zeek::VectorVal* vec) { Vec* result = new Vec(); @@ -107,14 +107,14 @@ BroSubstring::Vec* BroSubstring::VecFromPolicy(VectorVal* vec) if ( ! v ) continue; - const BroString* str = v->AsRecordVal()->GetField(0)->AsString(); + const zeek::String* str = v->AsRecordVal()->GetField(0)->AsString(); BroSubstring* substr = new BroSubstring(*str); - const VectorVal* aligns = v->AsRecordVal()->GetField(1)->AsVectorVal(); + const zeek::VectorVal* aligns = v->AsRecordVal()->GetField(1)->AsVectorVal(); for ( unsigned int j = 1; j <= aligns->Size(); ++j ) { - const RecordVal* align = aligns->AsVectorVal()->At(j)->AsRecordVal(); - const BroString* str = align->GetField(0)->AsString(); + const zeek::RecordVal* align = aligns->AsVectorVal()->At(j)->AsRecordVal(); + const zeek::String* str = align->GetField(0)->AsString(); int index = align->GetField(1)->AsCount(); substr->AddAlignment(str, index); } @@ -142,9 +142,9 @@ char* BroSubstring::VecToString(Vec* vec) return strdup(result.c_str()); } -BroString::IdxVec* BroSubstring::GetOffsetsVec(const Vec* vec, unsigned int index) +zeek::String::IdxVec* BroSubstring::GetOffsetsVec(const Vec* vec, unsigned int index) { - BroString::IdxVec* result = new BroString::IdxVec(); + zeek::String::IdxVec* result = new zeek::String::IdxVec(); for ( VecCIt it = vec->begin(); it != vec->end(); ++it ) { @@ -209,7 +209,7 @@ struct SWNode { // class SWNodeMatrix { public: - SWNodeMatrix(const BroString* s1, const BroString* s2) + SWNodeMatrix(const zeek::String* s1, const zeek::String* s2) : _s1(s1), _s2(s2), _rows(s1->Len() + 1), _cols(s2->Len() + 1) { _nodes = new SWNode[_cols * _rows]; @@ -229,8 +229,8 @@ public: return &(_nodes[row * _cols + col]); } - const BroString* GetRowsString() const { return _s1; } - const BroString* GetColsString() const { return _s2; } + const zeek::String* GetRowsString() const { return _s1; } + const zeek::String* GetColsString() const { return _s2; } int GetHeight() const { return _rows; } int GetWidth() const { return _cols; } @@ -247,8 +247,8 @@ public: } private: - const BroString* _s1; - const BroString* _s2; + const zeek::String* _s1; + const zeek::String* _s2; int _rows, _cols; SWNode* _nodes; @@ -398,7 +398,7 @@ end_loop: // The main Smith-Waterman algorithm. // -BroSubstring::Vec* smith_waterman(const BroString* s1, const BroString* s2, +BroSubstring::Vec* smith_waterman(const zeek::String* s1, const zeek::String* s2, SWParams& params) { BroSubstring::Vec* result = new BroSubstring::Vec(); @@ -415,8 +415,8 @@ BroSubstring::Vec* smith_waterman(const BroString* s1, const BroString* s2, int row = 0, col = 0; - byte_vec string1 = s1->Bytes(); - byte_vec string2 = s2->Bytes(); + zeek::byte_vec string1 = s1->Bytes(); + zeek::byte_vec string2 = s2->Bytes(); SWNodeMatrix matrix(s1, s2); // dynamic programming matrix. SWNode* node_max = nullptr; // pointer to the best score's node diff --git a/src/SmithWaterman.h b/src/SmithWaterman.h index 3d29eb15a3..a93becffe3 100644 --- a/src/SmithWaterman.h +++ b/src/SmithWaterman.h @@ -2,7 +2,7 @@ #pragma once -#include "BroString.h" +#include "ZeekString.h" #include // BroSubstrings are essentially BroStrings, augmented with indexing @@ -11,7 +11,7 @@ // for each of which we store where the substring starts. // // -class BroSubstring : public BroString { +class BroSubstring : public zeek::String { public: typedef std::vector Vec; @@ -22,12 +22,12 @@ public: // struct BSSAlign { - BSSAlign(const BroString* string, int index) + BSSAlign(const zeek::String* string, int index) { this->string = string; this->index = index; } // The other string // - const BroString* string; + const zeek::String* string; // Offset in the string that substring // starts at, counting from 0. @@ -40,10 +40,10 @@ public: typedef BSSAlignVec::const_iterator BSSAlignVecCIt; explicit BroSubstring(const std::string& string) - : BroString(string), _num(), _new(false) { } + : zeek::String(string), _num(), _new(false) { } - explicit BroSubstring(const BroString& string) - : BroString(string), _num(), _new(false) { } + explicit BroSubstring(const zeek::String& string) + : zeek::String(string), _num(), _new(false) { } BroSubstring(const BroSubstring& bst); @@ -56,7 +56,7 @@ public: // bool DoesCover(const BroSubstring* bst) const; - void AddAlignment(const BroString* string, int index); + void AddAlignment(const zeek::String* string, int index); const BSSAlignVec& GetAlignments() const { return _aligns; } unsigned int GetNumAlignments() const { return _aligns.size(); } @@ -68,11 +68,11 @@ public: // Helper methods for vectors: // - static VectorVal* VecToPolicy(Vec* vec); - static Vec* VecFromPolicy(VectorVal* vec); + static zeek::VectorVal* VecToPolicy(Vec* vec); + static Vec* VecFromPolicy(zeek::VectorVal* vec); static char* VecToString(Vec* vec); - static BroString::IdxVec* GetOffsetsVec(const Vec* vec, - unsigned int index); + static zeek::String::IdxVec* GetOffsetsVec(const Vec* vec, + unsigned int index); private: typedef std::map DataMap; @@ -148,6 +148,6 @@ struct SWParams { // input strings where the string occurs. On error, or if no common // subsequence exists, an empty vector is returned. // -extern BroSubstring::Vec* smith_waterman(const BroString* s1, - const BroString* s2, - SWParams& params); +extern BroSubstring::Vec* smith_waterman(const zeek::String* s1, + const zeek::String* s2, + SWParams& params); diff --git a/src/Stats.cc b/src/Stats.cc index 759f95972b..b88c083612 100644 --- a/src/Stats.cc +++ b/src/Stats.cc @@ -240,7 +240,7 @@ void ProfileLogger::Log() // Script-level state. unsigned int size, mem = 0; - const auto& globals = global_scope()->Vars(); + const auto& globals = zeek::detail::global_scope()->Vars(); if ( expensive ) { @@ -313,14 +313,14 @@ void ProfileLogger::Log() if ( profiling_update ) { mgr.Dispatch(new Event(profiling_update, { - make_intrusive(IntrusivePtr{NewRef{}, file}), - val_mgr->Bool(expensive), - })); + zeek::make_intrusive(zeek::IntrusivePtr{zeek::NewRef{}, file}), + zeek::val_mgr->Bool(expensive), + })); } } -void ProfileLogger::SegmentProfile(const char* name, const Location* loc, - double dtime, int dmem) +void ProfileLogger::SegmentProfile(const char* name, const zeek::detail::Location* loc, + double dtime, int dmem) { if ( name ) file->Write(fmt("%.06f segment-%s dt=%.06f dmem=%d\n", @@ -344,7 +344,7 @@ SampleLogger::SampleLogger() if ( ! load_sample_info ) load_sample_info = zeek::id::find_type("load_sample_info")->AsTableType(); - load_samples = new TableVal({NewRef{}, load_sample_info}); + load_samples = new zeek::TableVal({zeek::NewRef{}, load_sample_info}); } SampleLogger::~SampleLogger() @@ -352,27 +352,27 @@ SampleLogger::~SampleLogger() Unref(load_samples); } -void SampleLogger::FunctionSeen(const Func* func) +void SampleLogger::FunctionSeen(const zeek::Func* func) { - auto idx = make_intrusive(func->Name()); + auto idx = zeek::make_intrusive(func->Name()); load_samples->Assign(std::move(idx), nullptr); } -void SampleLogger::LocationSeen(const Location* loc) +void SampleLogger::LocationSeen(const zeek::detail::Location* loc) { - auto idx = make_intrusive(loc->filename); + auto idx = zeek::make_intrusive(loc->filename); load_samples->Assign(std::move(idx), nullptr); } void SampleLogger::SegmentProfile(const char* /* name */, - const Location* /* loc */, - double dtime, int dmem) + const zeek::detail::Location* /* loc */, + double dtime, int dmem) { if ( load_sample ) mgr.Enqueue(load_sample, - IntrusivePtr{NewRef{}, load_samples}, - make_intrusive(dtime, Seconds), - val_mgr->Int(dmem) + zeek::IntrusivePtr{zeek::NewRef{}, load_samples}, + zeek::make_intrusive(dtime, Seconds), + zeek::val_mgr->Int(dmem) ); } diff --git a/src/Stats.h b/src/Stats.h index e2691968de..b9131d4d10 100644 --- a/src/Stats.h +++ b/src/Stats.h @@ -2,16 +2,19 @@ #pragma once +#include "zeek-config.h" + #include #include #include #include -class Func; -class TableVal; -class Location; class BroFile; +ZEEK_FORWARD_DECLARE_NAMESPACED(Func, zeek); +ZEEK_FORWARD_DECLARE_NAMESPACED(TableVal, zeek); +ZEEK_FORWARD_DECLARE_NAMESPACED(Location, zeek::detail); + // Object called by SegmentProfiler when it is done and reports its // cumulative CPU/memory statistics. class SegmentStatsReporter { @@ -19,7 +22,7 @@ public: SegmentStatsReporter() { } virtual ~SegmentStatsReporter() { } - virtual void SegmentProfile(const char* name, const Location* loc, + virtual void SegmentProfile(const char* name, const zeek::detail::Location* loc, double dtime, int dmem) = 0; }; @@ -41,7 +44,7 @@ public: } SegmentProfiler(SegmentStatsReporter* arg_reporter, - const Location* arg_loc) + const zeek::detail::Location* arg_loc) : reporter(arg_reporter), name(), loc(arg_loc), initial_rusage() { if ( reporter ) @@ -60,7 +63,7 @@ protected: SegmentStatsReporter* reporter; const char* name; - const Location* loc; + const zeek::detail::Location* loc; struct rusage initial_rusage; }; @@ -74,8 +77,8 @@ public: BroFile* File() { return file; } protected: - void SegmentProfile(const char* name, const Location* loc, - double dtime, int dmem) override; + void SegmentProfile(const char* name, const zeek::detail::Location* loc, + double dtime, int dmem) override; private: BroFile* file; @@ -91,14 +94,14 @@ public: // These are called to report that a given function or location // has been seen during the sampling. - void FunctionSeen(const Func* func); - void LocationSeen(const Location* loc); + void FunctionSeen(const zeek::Func* func); + void LocationSeen(const zeek::detail::Location* loc); protected: - void SegmentProfile(const char* name, const Location* loc, - double dtime, int dmem) override; + void SegmentProfile(const char* name, const zeek::detail::Location* loc, + double dtime, int dmem) override; - TableVal* load_samples; + zeek::TableVal* load_samples; }; diff --git a/src/Stmt.cc b/src/Stmt.cc index 98bcfb0bf5..8d12e3b93e 100644 --- a/src/Stmt.cc +++ b/src/Stmt.cc @@ -71,7 +71,7 @@ ForStmt* Stmt::AsForStmt() bool Stmt::SetLocationInfo(const Location* start, const Location* end) { - if ( ! BroObj::SetLocationInfo(start, end) ) + if ( ! Obj::SetLocationInfo(start, end) ) return false; // Update the Filemap of line number -> statement mapping for @@ -151,7 +151,7 @@ void Stmt::AccessStats(ODesc* d) const } } -ExprListStmt::ExprListStmt(BroStmtTag t, IntrusivePtr arg_l) +ExprListStmt::ExprListStmt(BroStmtTag t, ListExprPtr arg_l) : Stmt(t), l(std::move(arg_l)) { const expr_list& e = l->Exprs(); @@ -167,7 +167,7 @@ ExprListStmt::ExprListStmt(BroStmtTag t, IntrusivePtr arg_l) ExprListStmt::~ExprListStmt() = default; -IntrusivePtr ExprListStmt::Exec(Frame* f, stmt_flow_type& flow) const +ValPtr ExprListStmt::Exec(Frame* f, stmt_flow_type& flow) const { last_access = network_time; flow = FLOW_NEXT; @@ -205,7 +205,7 @@ TraversalCode ExprListStmt::Traverse(TraversalCallback* cb) const static BroFile* print_stdout = nullptr; -static IntrusivePtr lookup_enum_val(const char* module_name, const char* name) +static EnumValPtr lookup_enum_val(const char* module_name, const char* name) { const auto& id = lookup_ID(name, module_name); assert(id); @@ -219,27 +219,27 @@ static IntrusivePtr lookup_enum_val(const char* module_name, const char return et->GetVal(index); } -static void print_log(const std::vector>& vals) +static void print_log(const std::vector& vals) { static auto plval = lookup_enum_val("Log", "PRINTLOG"); static auto lpli = zeek::id::find_type("Log::PrintLogInfo"); - auto record = make_intrusive(lpli); - auto vec = make_intrusive(zeek::id::string_vec); + auto record = zeek::make_intrusive(lpli); + auto vec = zeek::make_intrusive(zeek::id::string_vec); for ( const auto& val : vals ) { ODesc d(DESC_READABLE); val->Describe(&d); - vec->Assign(vec->Size(), make_intrusive(d.Description())); + vec->Assign(vec->Size(), zeek::make_intrusive(d.Description())); } - record->Assign(0, make_intrusive(network_time)); + record->Assign(0, zeek::make_intrusive(network_time)); record->Assign(1, std::move(vec)); log_mgr->Write(plval.get(), record.get()); } -IntrusivePtr PrintStmt::DoExec(std::vector> vals, - stmt_flow_type& /* flow */) const +ValPtr PrintStmt::DoExec(std::vector vals, + stmt_flow_type& /* flow */) const { RegisterAccess(); @@ -308,7 +308,7 @@ IntrusivePtr PrintStmt::DoExec(std::vector> vals, return nullptr; } -ExprStmt::ExprStmt(IntrusivePtr arg_e) : Stmt(STMT_EXPR), e(std::move(arg_e)) +ExprStmt::ExprStmt(ExprPtr arg_e) : Stmt(STMT_EXPR), e(std::move(arg_e)) { if ( e && e->IsPure() ) Warn("expression value ignored"); @@ -316,7 +316,7 @@ ExprStmt::ExprStmt(IntrusivePtr arg_e) : Stmt(STMT_EXPR), e(std::move(arg_ SetLocationInfo(e->GetLocationInfo()); } -ExprStmt::ExprStmt(BroStmtTag t, IntrusivePtr arg_e) : Stmt(t), e(std::move(arg_e)) +ExprStmt::ExprStmt(BroStmtTag t, ExprPtr arg_e) : Stmt(t), e(std::move(arg_e)) { if ( e ) SetLocationInfo(e->GetLocationInfo()); @@ -324,7 +324,7 @@ ExprStmt::ExprStmt(BroStmtTag t, IntrusivePtr arg_e) : Stmt(t), e(std::mov ExprStmt::~ExprStmt() = default; -IntrusivePtr ExprStmt::Exec(Frame* f, stmt_flow_type& flow) const +ValPtr ExprStmt::Exec(Frame* f, stmt_flow_type& flow) const { RegisterAccess(); flow = FLOW_NEXT; @@ -337,7 +337,7 @@ IntrusivePtr ExprStmt::Exec(Frame* f, stmt_flow_type& flow) const return nullptr; } -IntrusivePtr ExprStmt::DoExec(Frame* /* f */, Val* /* v */, stmt_flow_type& /* flow */) const +ValPtr ExprStmt::DoExec(Frame* /* f */, Val* /* v */, stmt_flow_type& /* flow */) const { return nullptr; } @@ -383,8 +383,9 @@ TraversalCode ExprStmt::Traverse(TraversalCallback* cb) const HANDLE_TC_STMT_POST(tc); } -IfStmt::IfStmt(IntrusivePtr test, - IntrusivePtr arg_s1, IntrusivePtr arg_s2) +IfStmt::IfStmt(ExprPtr test, + StmtPtr arg_s1, + StmtPtr arg_s2) : ExprStmt(STMT_IF, std::move(test)), s1(std::move(arg_s1)), s2(std::move(arg_s2)) { @@ -398,7 +399,7 @@ IfStmt::IfStmt(IntrusivePtr test, IfStmt::~IfStmt() = default; -IntrusivePtr IfStmt::DoExec(Frame* f, Val* v, stmt_flow_type& flow) const +ValPtr IfStmt::DoExec(Frame* f, Val* v, stmt_flow_type& flow) const { // Treat 0 as false, but don't require 1 for true. Stmt* do_stmt = v->IsZero() ? s2.get() : s1.get(); @@ -483,8 +484,8 @@ static BroStmtTag get_last_stmt_tag(const Stmt* stmt) return get_last_stmt_tag(stmts->Stmts()[len - 1]); } -Case::Case(IntrusivePtr arg_expr_cases, id_list* arg_type_cases, - IntrusivePtr arg_s) +Case::Case(ListExprPtr arg_expr_cases, id_list* arg_type_cases, + StmtPtr arg_s) : expr_cases(std::move(arg_expr_cases)), type_cases(arg_type_cases), s(std::move(arg_s)) { @@ -601,14 +602,14 @@ static void int_del_func(void* v) void SwitchStmt::Init() { - auto t = make_intrusive(); + auto t = zeek::make_intrusive(); t->Append(e->GetType()); comp_hash = new CompositeHash(std::move(t)); case_label_value_map.SetDeleteFunc(int_del_func); } -SwitchStmt::SwitchStmt(IntrusivePtr index, case_list* arg_cases) +SwitchStmt::SwitchStmt(ExprPtr index, case_list* arg_cases) : ExprStmt(STMT_SWITCH, std::move(index)), cases(arg_cases), default_case_idx(-1) { @@ -814,9 +815,9 @@ std::pair SwitchStmt::FindCaseLabelMatch(const Val* v) const return std::make_pair(label_idx, label_id); } -IntrusivePtr SwitchStmt::DoExec(Frame* f, Val* v, stmt_flow_type& flow) const +ValPtr SwitchStmt::DoExec(Frame* f, Val* v, stmt_flow_type& flow) const { - IntrusivePtr rval; + ValPtr rval; auto m = FindCaseLabelMatch(v); int matching_label_idx = m.first; @@ -899,7 +900,7 @@ TraversalCode SwitchStmt::Traverse(TraversalCallback* cb) const HANDLE_TC_STMT_POST(tc); } -AddStmt::AddStmt(IntrusivePtr arg_e) : ExprStmt(STMT_ADD, std::move(arg_e)) +AddStmt::AddStmt(ExprPtr arg_e) : ExprStmt(STMT_ADD, std::move(arg_e)) { if ( ! e->CanAdd() ) Error("illegal add statement"); @@ -910,7 +911,7 @@ bool AddStmt::IsPure() const return false; } -IntrusivePtr AddStmt::Exec(Frame* f, stmt_flow_type& flow) const +ValPtr AddStmt::Exec(Frame* f, stmt_flow_type& flow) const { RegisterAccess(); flow = FLOW_NEXT; @@ -932,7 +933,7 @@ TraversalCode AddStmt::Traverse(TraversalCallback* cb) const HANDLE_TC_STMT_POST(tc); } -DelStmt::DelStmt(IntrusivePtr arg_e) : ExprStmt(STMT_DELETE, std::move(arg_e)) +DelStmt::DelStmt(ExprPtr arg_e) : ExprStmt(STMT_DELETE, std::move(arg_e)) { if ( e->IsError() ) return; @@ -946,7 +947,7 @@ bool DelStmt::IsPure() const return false; } -IntrusivePtr DelStmt::Exec(Frame* f, stmt_flow_type& flow) const +ValPtr DelStmt::Exec(Frame* f, stmt_flow_type& flow) const { RegisterAccess(); flow = FLOW_NEXT; @@ -967,12 +968,12 @@ TraversalCode DelStmt::Traverse(TraversalCallback* cb) const HANDLE_TC_STMT_POST(tc); } -EventStmt::EventStmt(IntrusivePtr arg_e) +EventStmt::EventStmt(EventExprPtr arg_e) : ExprStmt(STMT_EVENT, arg_e), event_expr(std::move(arg_e)) { } -IntrusivePtr EventStmt::Exec(Frame* f, stmt_flow_type& flow) const +ValPtr EventStmt::Exec(Frame* f, stmt_flow_type& flow) const { RegisterAccess(); auto args = eval_list(f, event_expr->Args()); @@ -998,8 +999,8 @@ TraversalCode EventStmt::Traverse(TraversalCallback* cb) const HANDLE_TC_STMT_POST(tc); } -WhileStmt::WhileStmt(IntrusivePtr arg_loop_condition, - IntrusivePtr arg_body) +WhileStmt::WhileStmt(ExprPtr arg_loop_condition, + StmtPtr arg_body) : loop_condition(std::move(arg_loop_condition)), body(std::move(arg_body)) { if ( ! loop_condition->IsError() && @@ -1048,11 +1049,11 @@ TraversalCode WhileStmt::Traverse(TraversalCallback* cb) const HANDLE_TC_STMT_POST(tc); } -IntrusivePtr WhileStmt::Exec(Frame* f, stmt_flow_type& flow) const +ValPtr WhileStmt::Exec(Frame* f, stmt_flow_type& flow) const { RegisterAccess(); flow = FLOW_NEXT; - IntrusivePtr rval; + ValPtr rval; for ( ; ; ) { @@ -1077,7 +1078,7 @@ IntrusivePtr WhileStmt::Exec(Frame* f, stmt_flow_type& flow) const return rval; } -ForStmt::ForStmt(id_list* arg_loop_vars, IntrusivePtr loop_expr) +ForStmt::ForStmt(id_list* arg_loop_vars, ExprPtr loop_expr) : ExprStmt(STMT_FOR, std::move(loop_expr)) { loop_vars = arg_loop_vars; @@ -1107,7 +1108,7 @@ ForStmt::ForStmt(id_list* arg_loop_vars, IntrusivePtr loop_expr) else { - add_local({NewRef{}, lv}, ind_type, INIT_NONE, + add_local({zeek::NewRef{}, lv}, ind_type, INIT_NONE, nullptr, nullptr, VAR_REGULAR); } } @@ -1124,7 +1125,7 @@ ForStmt::ForStmt(id_list* arg_loop_vars, IntrusivePtr loop_expr) const auto& t = (*loop_vars)[0]->GetType(); if ( ! t ) - add_local({NewRef{}, (*loop_vars)[0]}, base_type(TYPE_COUNT), + add_local({zeek::NewRef{}, (*loop_vars)[0]}, base_type(TYPE_COUNT), INIT_NONE, nullptr, nullptr, VAR_REGULAR); else if ( ! IsIntegral(t->Tag()) ) @@ -1145,7 +1146,7 @@ ForStmt::ForStmt(id_list* arg_loop_vars, IntrusivePtr loop_expr) const auto& t = (*loop_vars)[0]->GetType(); if ( ! t ) - add_local({NewRef{}, (*loop_vars)[0]}, + add_local({zeek::NewRef{}, (*loop_vars)[0]}, base_type(TYPE_STRING), INIT_NONE, nullptr, nullptr, VAR_REGULAR); @@ -1160,7 +1161,7 @@ ForStmt::ForStmt(id_list* arg_loop_vars, IntrusivePtr loop_expr) } ForStmt::ForStmt(id_list* arg_loop_vars, - IntrusivePtr loop_expr, IntrusivePtr val_var) + ExprPtr loop_expr, IDPtr val_var) : ForStmt(arg_loop_vars, std::move(loop_expr)) { value_var = std::move(val_var); @@ -1191,14 +1192,14 @@ ForStmt::~ForStmt() delete loop_vars; } -IntrusivePtr ForStmt::DoExec(Frame* f, Val* v, stmt_flow_type& flow) const +ValPtr ForStmt::DoExec(Frame* f, Val* v, stmt_flow_type& flow) const { - IntrusivePtr ret; + ValPtr ret; if ( v->GetType()->Tag() == TYPE_TABLE ) { TableVal* tv = v->AsTableVal(); - const PDict* loop_vals = tv->AsTable(); + const PDict* loop_vals = tv->AsTable(); if ( ! loop_vals->Length() ) return nullptr; @@ -1251,7 +1252,7 @@ IntrusivePtr ForStmt::DoExec(Frame* f, Val* v, stmt_flow_type& flow) const // Set the loop variable to the current index, and make // another pass over the loop body. - f->SetElement((*loop_vars)[0], val_mgr->Count(i)); + f->SetElement((*loop_vars)[0], zeek::val_mgr->Count(i)); flow = FLOW_NEXT; ret = body->Exec(f, flow); @@ -1265,7 +1266,7 @@ IntrusivePtr ForStmt::DoExec(Frame* f, Val* v, stmt_flow_type& flow) const for ( int i = 0; i < sval->Len(); ++i ) { - auto sv = make_intrusive(1, (const char*) sval->Bytes() + i); + auto sv = zeek::make_intrusive(1, (const char*) sval->Bytes() + i); f->SetElement((*loop_vars)[0], std::move(sv)); flow = FLOW_NEXT; ret = body->Exec(f, flow); @@ -1349,7 +1350,7 @@ TraversalCode ForStmt::Traverse(TraversalCallback* cb) const HANDLE_TC_STMT_POST(tc); } -IntrusivePtr NextStmt::Exec(Frame* /* f */, stmt_flow_type& flow) const +ValPtr NextStmt::Exec(Frame* /* f */, stmt_flow_type& flow) const { RegisterAccess(); flow = FLOW_LOOP; @@ -1376,7 +1377,7 @@ TraversalCode NextStmt::Traverse(TraversalCallback* cb) const HANDLE_TC_STMT_POST(tc); } -IntrusivePtr BreakStmt::Exec(Frame* /* f */, stmt_flow_type& flow) const +ValPtr BreakStmt::Exec(Frame* /* f */, stmt_flow_type& flow) const { RegisterAccess(); flow = FLOW_BREAK; @@ -1403,7 +1404,7 @@ TraversalCode BreakStmt::Traverse(TraversalCallback* cb) const HANDLE_TC_STMT_POST(tc); } -IntrusivePtr FallthroughStmt::Exec(Frame* /* f */, stmt_flow_type& flow) const +ValPtr FallthroughStmt::Exec(Frame* /* f */, stmt_flow_type& flow) const { RegisterAccess(); flow = FLOW_FALLTHROUGH; @@ -1430,7 +1431,7 @@ TraversalCode FallthroughStmt::Traverse(TraversalCallback* cb) const HANDLE_TC_STMT_POST(tc); } -ReturnStmt::ReturnStmt(IntrusivePtr arg_e) +ReturnStmt::ReturnStmt(ExprPtr arg_e) : ExprStmt(STMT_RETURN, std::move(arg_e)) { Scope* s = current_scope(); @@ -1474,7 +1475,7 @@ ReturnStmt::ReturnStmt(IntrusivePtr arg_e) } } -IntrusivePtr ReturnStmt::Exec(Frame* f, stmt_flow_type& flow) const +ValPtr ReturnStmt::Exec(Frame* f, stmt_flow_type& flow) const { RegisterAccess(); flow = FLOW_RETURN; @@ -1513,7 +1514,7 @@ StmtList::~StmtList() Unref(stmt); } -IntrusivePtr StmtList::Exec(Frame* f, stmt_flow_type& flow) const +ValPtr StmtList::Exec(Frame* f, stmt_flow_type& flow) const { RegisterAccess(); flow = FLOW_NEXT; @@ -1592,7 +1593,7 @@ TraversalCode StmtList::Traverse(TraversalCallback* cb) const HANDLE_TC_STMT_POST(tc); } -IntrusivePtr EventBodyList::Exec(Frame* f, stmt_flow_type& flow) const +ValPtr EventBodyList::Exec(Frame* f, stmt_flow_type& flow) const { RegisterAccess(); flow = FLOW_NEXT; @@ -1650,7 +1651,7 @@ void EventBodyList::Describe(ODesc* d) const StmtList::Describe(d); } -InitStmt::InitStmt(std::vector> arg_inits) : Stmt(STMT_INIT) +InitStmt::InitStmt(std::vector arg_inits) : Stmt(STMT_INIT) { inits = std::move(arg_inits); @@ -1658,7 +1659,7 @@ InitStmt::InitStmt(std::vector> arg_inits) : Stmt(STMT_INIT) SetLocationInfo(inits[0]->GetLocationInfo()); } -IntrusivePtr InitStmt::Exec(Frame* f, stmt_flow_type& flow) const +ValPtr InitStmt::Exec(Frame* f, stmt_flow_type& flow) const { RegisterAccess(); flow = FLOW_NEXT; @@ -1667,18 +1668,18 @@ IntrusivePtr InitStmt::Exec(Frame* f, stmt_flow_type& flow) const { const auto& t = aggr->GetType(); - IntrusivePtr v; + ValPtr v; switch ( t->Tag() ) { case TYPE_RECORD: - v = make_intrusive(cast_intrusive(t)); + v = zeek::make_intrusive(zeek::cast_intrusive(t)); break; case TYPE_VECTOR: - v = make_intrusive(cast_intrusive(t)); + v = zeek::make_intrusive(zeek::cast_intrusive(t)); break; case TYPE_TABLE: - v = make_intrusive(cast_intrusive(t), - aggr->GetAttrs()); + v = zeek::make_intrusive(zeek::cast_intrusive(t), + aggr->GetAttrs()); break; default: break; @@ -1723,7 +1724,7 @@ TraversalCode InitStmt::Traverse(TraversalCallback* cb) const HANDLE_TC_STMT_POST(tc); } -IntrusivePtr NullStmt::Exec(Frame* /* f */, stmt_flow_type& flow) const +ValPtr NullStmt::Exec(Frame* /* f */, stmt_flow_type& flow) const { RegisterAccess(); flow = FLOW_NEXT; @@ -1752,9 +1753,9 @@ TraversalCode NullStmt::Traverse(TraversalCallback* cb) const HANDLE_TC_STMT_POST(tc); } -WhenStmt::WhenStmt(IntrusivePtr arg_cond, - IntrusivePtr arg_s1, IntrusivePtr arg_s2, - IntrusivePtr arg_timeout, bool arg_is_return) +WhenStmt::WhenStmt(ExprPtr arg_cond, + StmtPtr arg_s1, StmtPtr arg_s2, + ExprPtr arg_timeout, bool arg_is_return) : Stmt(STMT_WHEN), cond(std::move(arg_cond)), s1(std::move(arg_s1)), s2(std::move(arg_s2)), timeout(std::move(arg_timeout)), is_return(arg_is_return) @@ -1778,7 +1779,7 @@ WhenStmt::WhenStmt(IntrusivePtr arg_cond, WhenStmt::~WhenStmt() = default; -IntrusivePtr WhenStmt::Exec(Frame* f, stmt_flow_type& flow) const +ValPtr WhenStmt::Exec(Frame* f, stmt_flow_type& flow) const { RegisterAccess(); flow = FLOW_NEXT; diff --git a/src/Stmt.h b/src/Stmt.h index dc744c9b4b..881a042836 100644 --- a/src/Stmt.h +++ b/src/Stmt.h @@ -14,7 +14,8 @@ #include "TraverseTypes.h" class CompositeHash; -class Frame; + +ZEEK_FORWARD_DECLARE_NAMESPACED(Frame, zeek::detail); namespace zeek::detail { @@ -23,15 +24,21 @@ class ForStmt; class EventExpr; class ListExpr; -class Stmt : public BroObj { +using EventExprPtr = zeek::IntrusivePtr; +using ListExprPtr = zeek::IntrusivePtr; + +class Stmt; +using StmtPtr = zeek::IntrusivePtr; + +class Stmt : public Obj { public: BroStmtTag Tag() const { return tag; } ~Stmt() override; - virtual IntrusivePtr Exec(Frame* f, stmt_flow_type& flow) const = 0; + virtual ValPtr Exec(Frame* f, stmt_flow_type& flow) const = 0; - Stmt* Ref() { ::Ref(this); return this; } + Stmt* Ref() { zeek::Ref(this); return this; } bool SetLocationInfo(const Location* loc) override { return Stmt::SetLocationInfo(loc, loc); } @@ -80,17 +87,17 @@ public: TraversalCode Traverse(TraversalCallback* cb) const override; protected: - ExprListStmt(BroStmtTag t, IntrusivePtr arg_l); + ExprListStmt(BroStmtTag t, ListExprPtr arg_l); ~ExprListStmt() override; - IntrusivePtr Exec(Frame* f, stmt_flow_type& flow) const override; - virtual IntrusivePtr DoExec(std::vector> vals, - stmt_flow_type& flow) const = 0; + ValPtr Exec(Frame* f, stmt_flow_type& flow) const override; + virtual ValPtr DoExec(std::vector vals, + stmt_flow_type& flow) const = 0; void Describe(ODesc* d) const override; - IntrusivePtr l; + ListExprPtr l; }; class PrintStmt final : public ExprListStmt { @@ -99,16 +106,16 @@ public: explicit PrintStmt(L&& l) : ExprListStmt(STMT_PRINT, std::forward(l)) { } protected: - IntrusivePtr DoExec(std::vector> vals, - stmt_flow_type& flow) const override; + ValPtr DoExec(std::vector vals, + stmt_flow_type& flow) const override; }; class ExprStmt : public Stmt { public: - explicit ExprStmt(IntrusivePtr e); + explicit ExprStmt(ExprPtr e); ~ExprStmt() override; - IntrusivePtr Exec(Frame* f, stmt_flow_type& flow) const override; + ValPtr Exec(Frame* f, stmt_flow_type& flow) const override; const Expr* StmtExpr() const { return e.get(); } @@ -117,18 +124,18 @@ public: TraversalCode Traverse(TraversalCallback* cb) const override; protected: - ExprStmt(BroStmtTag t, IntrusivePtr e); + ExprStmt(BroStmtTag t, ExprPtr e); - virtual IntrusivePtr DoExec(Frame* f, Val* v, stmt_flow_type& flow) const; + virtual ValPtr DoExec(Frame* f, Val* v, stmt_flow_type& flow) const; bool IsPure() const override; - IntrusivePtr e; + ExprPtr e; }; class IfStmt final : public ExprStmt { public: - IfStmt(IntrusivePtr test, IntrusivePtr s1, IntrusivePtr s2); + IfStmt(ExprPtr test, StmtPtr s1, StmtPtr s2); ~IfStmt() override; const Stmt* TrueBranch() const { return s1.get(); } @@ -139,16 +146,16 @@ public: TraversalCode Traverse(TraversalCallback* cb) const override; protected: - IntrusivePtr DoExec(Frame* f, Val* v, stmt_flow_type& flow) const override; + ValPtr DoExec(Frame* f, Val* v, stmt_flow_type& flow) const override; bool IsPure() const override; - IntrusivePtr s1; - IntrusivePtr s2; + StmtPtr s1; + StmtPtr s2; }; -class Case final : public BroObj { +class Case final : public Obj { public: - Case(IntrusivePtr c, id_list* types, IntrusivePtr arg_s); + Case(ListExprPtr c, id_list* types, StmtPtr arg_s); ~Case() override; const ListExpr* ExprCases() const { return expr_cases.get(); } @@ -165,16 +172,16 @@ public: TraversalCode Traverse(TraversalCallback* cb) const; protected: - IntrusivePtr expr_cases; + ListExprPtr expr_cases; id_list* type_cases; - IntrusivePtr s; + StmtPtr s; }; -using case_list = PList; +using case_list = zeek::PList; class SwitchStmt final : public ExprStmt { public: - SwitchStmt(IntrusivePtr index, case_list* cases); + SwitchStmt(ExprPtr index, case_list* cases); ~SwitchStmt() override; const case_list* Cases() const { return cases; } @@ -184,7 +191,7 @@ public: TraversalCode Traverse(TraversalCallback* cb) const override; protected: - IntrusivePtr DoExec(Frame* f, Val* v, stmt_flow_type& flow) const override; + ValPtr DoExec(Frame* f, Val* v, stmt_flow_type& flow) const override; bool IsPure() const override; // Initialize composite hash and case label map. @@ -209,46 +216,46 @@ protected: case_list* cases; int default_case_idx; CompositeHash* comp_hash; - PDict case_label_value_map; + zeek::PDict case_label_value_map; std::vector> case_label_type_list; }; class AddStmt final : public ExprStmt { public: - explicit AddStmt(IntrusivePtr e); + explicit AddStmt(ExprPtr e); bool IsPure() const override; - IntrusivePtr Exec(Frame* f, stmt_flow_type& flow) const override; + ValPtr Exec(Frame* f, stmt_flow_type& flow) const override; TraversalCode Traverse(TraversalCallback* cb) const override; }; class DelStmt final : public ExprStmt { public: - explicit DelStmt(IntrusivePtr e); + explicit DelStmt(ExprPtr e); bool IsPure() const override; - IntrusivePtr Exec(Frame* f, stmt_flow_type& flow) const override; + ValPtr Exec(Frame* f, stmt_flow_type& flow) const override; TraversalCode Traverse(TraversalCallback* cb) const override; }; class EventStmt final : public ExprStmt { public: - explicit EventStmt(IntrusivePtr e); + explicit EventStmt(EventExprPtr e); - IntrusivePtr Exec(Frame* f, stmt_flow_type& flow) const override; + ValPtr Exec(Frame* f, stmt_flow_type& flow) const override; TraversalCode Traverse(TraversalCallback* cb) const override; protected: - IntrusivePtr event_expr; + EventExprPtr event_expr; }; class WhileStmt final : public Stmt { public: - WhileStmt(IntrusivePtr loop_condition, IntrusivePtr body); + WhileStmt(ExprPtr loop_condition, StmtPtr body); ~WhileStmt() override; bool IsPure() const override; @@ -258,20 +265,20 @@ public: TraversalCode Traverse(TraversalCallback* cb) const override; protected: - IntrusivePtr Exec(Frame* f, stmt_flow_type& flow) const override; + ValPtr Exec(Frame* f, stmt_flow_type& flow) const override; - IntrusivePtr loop_condition; - IntrusivePtr body; + ExprPtr loop_condition; + StmtPtr body; }; class ForStmt final : public ExprStmt { public: - ForStmt(id_list* loop_vars, IntrusivePtr loop_expr); + ForStmt(id_list* loop_vars, ExprPtr loop_expr); // Special constructor for key value for loop. - ForStmt(id_list* loop_vars, IntrusivePtr loop_expr, IntrusivePtr val_var); + ForStmt(id_list* loop_vars, ExprPtr loop_expr, IDPtr val_var); ~ForStmt() override; - void AddBody(IntrusivePtr arg_body) { body = std::move(arg_body); } + void AddBody(StmtPtr arg_body) { body = std::move(arg_body); } const id_list* LoopVar() const { return loop_vars; } const Expr* LoopExpr() const { return e.get(); } @@ -284,20 +291,20 @@ public: TraversalCode Traverse(TraversalCallback* cb) const override; protected: - IntrusivePtr DoExec(Frame* f, Val* v, stmt_flow_type& flow) const override; + ValPtr DoExec(Frame* f, Val* v, stmt_flow_type& flow) const override; id_list* loop_vars; - IntrusivePtr body; + StmtPtr body; // Stores the value variable being used for a key value for loop. // Always set to nullptr unless special constructor is called. - IntrusivePtr value_var; + IDPtr value_var; }; class NextStmt final : public Stmt { public: NextStmt() : Stmt(STMT_NEXT) { } - IntrusivePtr Exec(Frame* f, stmt_flow_type& flow) const override; + ValPtr Exec(Frame* f, stmt_flow_type& flow) const override; bool IsPure() const override; void Describe(ODesc* d) const override; @@ -311,7 +318,7 @@ class BreakStmt final : public Stmt { public: BreakStmt() : Stmt(STMT_BREAK) { } - IntrusivePtr Exec(Frame* f, stmt_flow_type& flow) const override; + ValPtr Exec(Frame* f, stmt_flow_type& flow) const override; bool IsPure() const override; void Describe(ODesc* d) const override; @@ -325,7 +332,7 @@ class FallthroughStmt final : public Stmt { public: FallthroughStmt() : Stmt(STMT_FALLTHROUGH) { } - IntrusivePtr Exec(Frame* f, stmt_flow_type& flow) const override; + ValPtr Exec(Frame* f, stmt_flow_type& flow) const override; bool IsPure() const override; void Describe(ODesc* d) const override; @@ -337,9 +344,9 @@ protected: class ReturnStmt final : public ExprStmt { public: - explicit ReturnStmt(IntrusivePtr e); + explicit ReturnStmt(ExprPtr e); - IntrusivePtr Exec(Frame* f, stmt_flow_type& flow) const override; + ValPtr Exec(Frame* f, stmt_flow_type& flow) const override; void Describe(ODesc* d) const override; }; @@ -349,7 +356,7 @@ public: StmtList(); ~StmtList() override; - IntrusivePtr Exec(Frame* f, stmt_flow_type& flow) const override; + ValPtr Exec(Frame* f, stmt_flow_type& flow) const override; const stmt_list& Stmts() const { return stmts; } stmt_list& Stmts() { return stmts; } @@ -369,7 +376,7 @@ public: EventBodyList() : StmtList() { topmost = false; tag = STMT_EVENT_BODY_LIST; } - IntrusivePtr Exec(Frame* f, stmt_flow_type& flow) const override; + ValPtr Exec(Frame* f, stmt_flow_type& flow) const override; void Describe(ODesc* d) const override; @@ -383,11 +390,11 @@ protected: class InitStmt final : public Stmt { public: - explicit InitStmt(std::vector> arg_inits); + explicit InitStmt(std::vector arg_inits); - IntrusivePtr Exec(Frame* f, stmt_flow_type& flow) const override; + ValPtr Exec(Frame* f, stmt_flow_type& flow) const override; - const std::vector>& Inits() const + const std::vector& Inits() const { return inits; } void Describe(ODesc* d) const override; @@ -395,14 +402,14 @@ public: TraversalCode Traverse(TraversalCallback* cb) const override; protected: - std::vector> inits; + std::vector inits; }; class NullStmt final : public Stmt { public: NullStmt() : Stmt(STMT_NULL) { } - IntrusivePtr Exec(Frame* f, stmt_flow_type& flow) const override; + ValPtr Exec(Frame* f, stmt_flow_type& flow) const override; bool IsPure() const override; void Describe(ODesc* d) const override; @@ -413,12 +420,12 @@ public: class WhenStmt final : public Stmt { public: // s2 is null if no timeout block given. - WhenStmt(IntrusivePtr cond, - IntrusivePtr s1, IntrusivePtr s2, - IntrusivePtr timeout, bool is_return); + WhenStmt(ExprPtr cond, + StmtPtr s1, StmtPtr s2, + ExprPtr timeout, bool is_return); ~WhenStmt() override; - IntrusivePtr Exec(Frame* f, stmt_flow_type& flow) const override; + ValPtr Exec(Frame* f, stmt_flow_type& flow) const override; bool IsPure() const override; const Expr* Cond() const { return cond.get(); } @@ -431,10 +438,10 @@ public: TraversalCode Traverse(TraversalCallback* cb) const override; protected: - IntrusivePtr cond; - IntrusivePtr s1; - IntrusivePtr s2; - IntrusivePtr timeout; + ExprPtr cond; + StmtPtr s1; + StmtPtr s2; + ExprPtr timeout; bool is_return; }; diff --git a/src/Tag.cc b/src/Tag.cc index cd2a93b7fb..315c7fc558 100644 --- a/src/Tag.cc +++ b/src/Tag.cc @@ -2,9 +2,8 @@ #include "Tag.h" #include "Val.h" -#include "IntrusivePtr.h" -Tag::Tag(const IntrusivePtr& etype, type_t arg_type, subtype_t arg_subtype) +Tag::Tag(const zeek::EnumTypePtr& etype, type_t arg_type, subtype_t arg_subtype) { assert(arg_type > 0); @@ -15,10 +14,10 @@ Tag::Tag(const IntrusivePtr& etype, type_t arg_type, subtype_t a } Tag::Tag(zeek::EnumType* etype, type_t arg_type, subtype_t arg_subtype) - : Tag({NewRef{}, etype}, arg_type, arg_subtype) + : Tag({zeek::NewRef{}, etype}, arg_type, arg_subtype) { } -Tag::Tag(IntrusivePtr arg_val) +Tag::Tag(zeek::EnumValPtr arg_val) { assert(arg_val); @@ -29,8 +28,8 @@ Tag::Tag(IntrusivePtr arg_val) subtype = (i >> 31) & 0xffffffff; } -Tag::Tag(EnumVal* arg_val) - : Tag({NewRef{}, arg_val}) +Tag::Tag(zeek::EnumVal* arg_val) + : Tag({zeek::NewRef{}, arg_val}) { } Tag::Tag(const Tag& other) @@ -73,7 +72,7 @@ Tag& Tag::operator=(const Tag&& other) noexcept return *this; } -const IntrusivePtr& Tag::AsVal(const IntrusivePtr& etype) const +const zeek::EnumValPtr& Tag::AsVal(const zeek::EnumTypePtr& etype) const { if ( ! val ) { @@ -84,9 +83,9 @@ const IntrusivePtr& Tag::AsVal(const IntrusivePtr& etyp return val; } -EnumVal* Tag::AsEnumVal(zeek::EnumType* etype) const +zeek::EnumVal* Tag::AsEnumVal(zeek::EnumType* etype) const { - return AsVal({NewRef{}, etype}).get(); + return AsVal({zeek::NewRef{}, etype}).get(); } std::string Tag::AsString() const diff --git a/src/Tag.h b/src/Tag.h index 763d14ef7a..bccc85a6cd 100644 --- a/src/Tag.h +++ b/src/Tag.h @@ -10,9 +10,14 @@ #include "IntrusivePtr.h" #include "util.h" -class EnumVal; +ZEEK_FORWARD_DECLARE_NAMESPACED(EnumVal, zeek); ZEEK_FORWARD_DECLARE_NAMESPACED(EnumType, zeek); +namespace zeek { +using EnumTypePtr = zeek::IntrusivePtr; +using EnumValPtr = zeek::IntrusivePtr; +} + /** * Class to identify an analyzer type. * @@ -116,10 +121,10 @@ protected: * * @param etype the script-layer enum type associated with the tag. */ - const IntrusivePtr& AsVal(const IntrusivePtr& etype) const; + const zeek::EnumValPtr& AsVal(const zeek::EnumTypePtr& etype) const; [[deprecated("Remove in v4.1. Use AsVal() instead.")]] - EnumVal* AsEnumVal(zeek::EnumType* etype) const; + zeek::EnumVal* AsEnumVal(zeek::EnumType* etype) const; /** * Constructor. @@ -132,9 +137,9 @@ protected: * @param subtype The sub type, which is left to an analyzer for * interpretation. By default it's set to zero. */ - Tag(const IntrusivePtr& etype, type_t type, subtype_t subtype = 0); + Tag(const zeek::EnumTypePtr& etype, type_t type, subtype_t subtype = 0); - [[deprecated("Remove in v4.1. Construct from IntrusivePtr& instead.")]] + [[deprecated("Remove in v4.1. Construct from zeek::IntrusivePtr& instead.")]] Tag(zeek::EnumType* etype, type_t type, subtype_t subtype = 0); /** @@ -142,13 +147,13 @@ protected: * * @param val An enum value of script type \c Analyzer::Tag. */ - explicit Tag(IntrusivePtr val); + explicit Tag(zeek::EnumValPtr val); - [[deprecated("Remove in v4.1. Construct from IntrusivePtr instead.")]] - explicit Tag(EnumVal* val); + [[deprecated("Remove in v4.1. Construct from zeek::IntrusivePtr instead.")]] + explicit Tag(zeek::EnumVal* val); private: type_t type; // Main type. subtype_t subtype; // Subtype. - mutable IntrusivePtr val; // Script-layer value. + mutable zeek::EnumValPtr val; // Script-layer value. }; diff --git a/src/Traverse.cc b/src/Traverse.cc index b9aa28b42d..71562dfee5 100644 --- a/src/Traverse.cc +++ b/src/Traverse.cc @@ -7,16 +7,16 @@ TraversalCode traverse_all(TraversalCallback* cb) { - if ( ! global_scope() ) + if ( ! zeek::detail::global_scope() ) return TC_CONTINUE; if ( ! stmts ) // May be null when parsing fails. return TC_CONTINUE; - cb->current_scope = global_scope(); + cb->current_scope = zeek::detail::global_scope(); - TraversalCode tc = global_scope()->Traverse(cb); + TraversalCode tc = zeek::detail::global_scope()->Traverse(cb); HANDLE_TC_STMT_PRE(tc); tc = stmts->Traverse(cb); diff --git a/src/Traverse.h b/src/Traverse.h index 2d3e13bfee..6cdd07f042 100644 --- a/src/Traverse.h +++ b/src/Traverse.h @@ -4,9 +4,8 @@ #include "TraverseTypes.h" -class Func; -class Scope; - +ZEEK_FORWARD_DECLARE_NAMESPACED(Func, zeek); +ZEEK_FORWARD_DECLARE_NAMESPACED(Scope, zeek::detail); ZEEK_FORWARD_DECLARE_NAMESPACED(Stmt, zeek::detail); ZEEK_FORWARD_DECLARE_NAMESPACED(Expr, zeek::detail); ZEEK_FORWARD_DECLARE_NAMESPACED(ID, zeek::detail); @@ -16,8 +15,8 @@ public: TraversalCallback() { current_scope = nullptr; } virtual ~TraversalCallback() {} - virtual TraversalCode PreFunction(const Func*) { return TC_CONTINUE; } - virtual TraversalCode PostFunction(const Func*) { return TC_CONTINUE; } + virtual TraversalCode PreFunction(const zeek::Func*) { return TC_CONTINUE; } + virtual TraversalCode PostFunction(const zeek::Func*) { return TC_CONTINUE; } virtual TraversalCode PreStmt(const zeek::detail::Stmt*) { return TC_CONTINUE; } virtual TraversalCode PostStmt(const zeek::detail::Stmt*) { return TC_CONTINUE; } @@ -34,7 +33,7 @@ public: virtual TraversalCode PreDecl(const zeek::detail::ID*) { return TC_CONTINUE; } virtual TraversalCode PostDecl(const zeek::detail::ID*) { return TC_CONTINUE; } - Scope* current_scope; + zeek::detail::Scope* current_scope; }; TraversalCode traverse_all(TraversalCallback* cb); diff --git a/src/Trigger.cc b/src/Trigger.cc index 084404de85..600a4aa84a 100644 --- a/src/Trigger.cc +++ b/src/Trigger.cc @@ -59,7 +59,7 @@ TraversalCode zeek::detail::trigger::TriggerTraversalCallback::PreExpr(const zee case EXPR_INDEX: { const auto* e = static_cast(expr); - BroObj::SuppressErrors no_errors; + Obj::SuppressErrors no_errors; try { @@ -151,7 +151,7 @@ Trigger::Trigger(zeek::detail::Expr* arg_cond, zeek::detail::Stmt* arg_body, arg_frame->SetDelayed(); } - IntrusivePtr timeout_val; + ValPtr timeout_val; if ( arg_timeout ) { @@ -262,9 +262,9 @@ bool Trigger::Eval() return false; } - f->SetTrigger({NewRef{}, this}); + f->SetTrigger({zeek::NewRef{}, this}); - IntrusivePtr v; + ValPtr v; try { @@ -348,8 +348,8 @@ void Trigger::Timeout() if ( timeout_stmts ) { stmt_flow_type flow; - IntrusivePtr f{AdoptRef{}, frame->Clone()}; - IntrusivePtr v; + FramePtr f{zeek::AdoptRef{}, frame->Clone()}; + ValPtr v; try { diff --git a/src/Trigger.h b/src/Trigger.h index 368238208c..549341440a 100644 --- a/src/Trigger.h +++ b/src/Trigger.h @@ -8,11 +8,12 @@ #include "Notifier.h" #include "iosource/IOSource.h" #include "util.h" +#include "IntrusivePtr.h" -class Frame; -class Val; class ODesc; +ZEEK_FORWARD_DECLARE_NAMESPACED(Val, zeek); +ZEEK_FORWARD_DECLARE_NAMESPACED(Frame, zeek::detail); ZEEK_FORWARD_DECLARE_NAMESPACED(Stmt, zeek::detail); ZEEK_FORWARD_DECLARE_NAMESPACED(Expr, zeek::detail); ZEEK_FORWARD_DECLARE_NAMESPACED(CallExpr, zeek::detail); @@ -26,7 +27,7 @@ namespace zeek::detail::trigger { class TriggerTimer; class TriggerTraversalCallback; -class Trigger final : public BroObj, public notifier::Receiver { +class Trigger final : public Obj, public notifier::Receiver { public: // Don't access Trigger objects; they take care of themselves after // instantiation. Note that if the condition is already true, the @@ -109,12 +110,14 @@ private: bool delayed; // true if a function call is currently being delayed bool disabled; - std::vector> objs; + std::vector> objs; using ValCache = std::map; ValCache cache; }; +using TriggerPtr = zeek::IntrusivePtr; + class Manager final : public iosource::IOSource { public: diff --git a/src/TunnelEncapsulation.cc b/src/TunnelEncapsulation.cc index 1b36a3f898..136f6d30b7 100644 --- a/src/TunnelEncapsulation.cc +++ b/src/TunnelEncapsulation.cc @@ -16,19 +16,19 @@ EncapsulatingConn::EncapsulatingConn(Connection* c, BifEnum::Tunnel::Type t) } } -IntrusivePtr EncapsulatingConn::ToVal() const +zeek::RecordValPtr EncapsulatingConn::ToVal() const { - auto rv = make_intrusive(zeek::BifType::Record::Tunnel::EncapsulatingConn); + auto rv = zeek::make_intrusive(zeek::BifType::Record::Tunnel::EncapsulatingConn); - auto id_val = make_intrusive(zeek::id::conn_id); - id_val->Assign(0, make_intrusive(src_addr)); - id_val->Assign(1, val_mgr->Port(ntohs(src_port), proto)); - id_val->Assign(2, make_intrusive(dst_addr)); - id_val->Assign(3, val_mgr->Port(ntohs(dst_port), proto)); + auto id_val = zeek::make_intrusive(zeek::id::conn_id); + id_val->Assign(0, zeek::make_intrusive(src_addr)); + id_val->Assign(1, zeek::val_mgr->Port(ntohs(src_port), proto)); + id_val->Assign(2, zeek::make_intrusive(dst_addr)); + id_val->Assign(3, zeek::val_mgr->Port(ntohs(dst_port), proto)); rv->Assign(0, std::move(id_val)); rv->Assign(1, zeek::BifType::Enum::Tunnel::Type->GetVal(type)); - rv->Assign(2, make_intrusive(uid.Base62("C").c_str())); + rv->Assign(2, zeek::make_intrusive(uid.Base62("C").c_str())); return rv; } diff --git a/src/TunnelEncapsulation.h b/src/TunnelEncapsulation.h index 048fcdddfd..13f6da8ef4 100644 --- a/src/TunnelEncapsulation.h +++ b/src/TunnelEncapsulation.h @@ -6,7 +6,6 @@ #include -#include "IntrusivePtr.h" #include "NetVar.h" #include "IPAddr.h" #include "ID.h" @@ -81,10 +80,10 @@ public: /** * Returns record value of type "EncapsulatingConn" representing the tunnel. */ - IntrusivePtr ToVal() const; + zeek::RecordValPtr ToVal() const; [[deprecated("Remove in v4.1. Use ToVal() instead.")]] - RecordVal* GetRecordVal() const + zeek::RecordVal* GetRecordVal() const { return ToVal().release(); } friend bool operator==(const EncapsulatingConn& ec1, @@ -196,9 +195,9 @@ public: * Get the value of type "EncapsulatingConnVector" represented by the * entire encapsulation chain. */ - IntrusivePtr ToVal() const + zeek::VectorValPtr ToVal() const { - auto vv = make_intrusive( + auto vv = zeek::make_intrusive( zeek::id::find_type("EncapsulatingConnVector")); if ( conns ) @@ -211,7 +210,7 @@ public: } [[deprecated("Remove in v4.1. Use ToVal() instead.")]] - VectorVal* GetVectorVal() const + zeek::VectorVal* GetVectorVal() const { return ToVal().release(); } friend bool operator==(const EncapsulationStack& e1, diff --git a/src/Type.cc b/src/Type.cc index 651712aaae..6a833ddb9e 100644 --- a/src/Type.cc +++ b/src/Type.cc @@ -196,7 +196,7 @@ TypeType* Type::AsTypeType() return (TypeType*) this; } -IntrusivePtr Type::ShallowClone() +TypePtr Type::ShallowClone() { switch ( tag ) { case TYPE_VOID: @@ -214,7 +214,7 @@ IntrusivePtr Type::ShallowClone() case TYPE_ADDR: case TYPE_SUBNET: case TYPE_ANY: - return make_intrusive(tag, base_type); + return zeek::make_intrusive(tag, base_type); default: reporter->InternalError("cloning illegal base Type"); @@ -236,7 +236,7 @@ int Type::MatchesIndex(zeek::detail::ListExpr* const index) const return DOES_NOT_MATCH_INDEX; } -const IntrusivePtr& Type::Yield() const +const TypePtr& Type::Yield() const { return Type::nil; } @@ -288,7 +288,7 @@ bool TypeList::AllMatch(const Type* t, bool is_init) const return true; } -void TypeList::Append(IntrusivePtr t) +void TypeList::Append(TypePtr t) { if ( pure_type && ! same_type(t, pure_type) ) reporter->InternalError("pure type-list violation"); @@ -297,7 +297,7 @@ void TypeList::Append(IntrusivePtr t) types.emplace_back(std::move(t)); } -void TypeList::AppendEvenIfNotPure(IntrusivePtr t) +void TypeList::AppendEvenIfNotPure(TypePtr t) { if ( pure_type && ! same_type(t, pure_type) ) pure_type = nullptr; @@ -442,7 +442,7 @@ bool IndexType::IsSubNetIndex() const return false; } -TableType::TableType(IntrusivePtr ind, IntrusivePtr yield) +TableType::TableType(TypeListPtr ind, TypePtr yield) : IndexType(TYPE_TABLE, std::move(ind), std::move(yield)) { if ( ! indices ) @@ -469,9 +469,9 @@ TableType::TableType(IntrusivePtr ind, IntrusivePtr yield) } } -IntrusivePtr TableType::ShallowClone() +TypePtr TableType::ShallowClone() { - return make_intrusive(indices, yield_type); + return zeek::make_intrusive(indices, yield_type); } bool TableType::IsUnspecifiedTable() const @@ -480,7 +480,7 @@ bool TableType::IsUnspecifiedTable() const return indices->GetTypes().empty(); } -SetType::SetType(IntrusivePtr ind, IntrusivePtr arg_elements) +SetType::SetType(TypeListPtr ind, zeek::detail::ListExprPtr arg_elements) : TableType(std::move(ind), nullptr), elements(std::move(arg_elements)) { if ( elements ) @@ -503,8 +503,8 @@ SetType::SetType(IntrusivePtr ind, IntrusivePtr ft{NewRef{}, flatten_type(tl[0].get())}; - indices = make_intrusive(ft); + TypePtr ft{zeek::NewRef{}, flatten_type(tl[0].get())}; + indices = zeek::make_intrusive(ft); indices->Append(std::move(ft)); } @@ -521,24 +521,24 @@ SetType::SetType(IntrusivePtr ind, IntrusivePtr(t); + indices = zeek::make_intrusive(t); indices->Append(std::move(t)); } } } } -IntrusivePtr SetType::ShallowClone() +TypePtr SetType::ShallowClone() { - return make_intrusive(indices, elements); + return zeek::make_intrusive(indices, elements); } SetType::~SetType() = default; -FuncType::FuncType(IntrusivePtr arg_args, - IntrusivePtr arg_yield, FunctionFlavor arg_flavor) +FuncType::FuncType(RecordTypePtr arg_args, + TypePtr arg_yield, FunctionFlavor arg_flavor) : Type(TYPE_FUNC), args(std::move(arg_args)), - arg_types(make_intrusive()), yield(std::move(arg_yield)) + arg_types(zeek::make_intrusive()), yield(std::move(arg_yield)) { flavor = arg_flavor; @@ -566,9 +566,9 @@ FuncType::FuncType(IntrusivePtr arg_args, prototypes.emplace_back(Prototype{false, args, std::move(offsets)}); } -IntrusivePtr FuncType::ShallowClone() +TypePtr FuncType::ShallowClone() { - auto f = make_intrusive(); + auto f = zeek::make_intrusive(); f->args = args; f->arg_types = arg_types; f->yield = yield; @@ -606,16 +606,16 @@ int FuncType::MatchesIndex(zeek::detail::ListExpr* const index) const bool FuncType::CheckArgs(const type_list* args, bool is_init) const { - std::vector> as; + std::vector as; as.reserve(args->length()); for ( auto a : *args ) - as.emplace_back(NewRef{}, a); + as.emplace_back(zeek::NewRef{}, a); return CheckArgs(as, is_init); } -bool FuncType::CheckArgs(const std::vector>& args, +bool FuncType::CheckArgs(const std::vector& args, bool is_init) const { const auto& my_args = arg_types->GetTypes(); @@ -734,8 +734,7 @@ std::optional FuncType::FindPrototype(const RecordType& arg return {}; } -TypeDecl::TypeDecl(const char* i, IntrusivePtr t, - IntrusivePtr arg_attrs) +TypeDecl::TypeDecl(const char* i, TypePtr t, zeek::detail::AttributesPtr arg_attrs) : type(std::move(t)), attrs(std::move(arg_attrs)), id(i) @@ -783,12 +782,12 @@ RecordType::RecordType(type_decl_list* arg_types) : Type(TYPE_RECORD) // in this case the clone is actually not so shallow, since // it gets modified by everyone. -IntrusivePtr RecordType::ShallowClone() +TypePtr RecordType::ShallowClone() { auto pass = new type_decl_list(); for ( const auto& type : *types ) pass->push_back(new TypeDecl(*type)); - return make_intrusive(pass); + return zeek::make_intrusive(pass); } RecordType::~RecordType() @@ -807,7 +806,7 @@ bool RecordType::HasField(const char* field) const return FieldOffset(field) >= 0; } -IntrusivePtr RecordType::FieldDefault(int field) const +ValPtr RecordType::FieldDefault(int field) const { const TypeDecl* td = FieldDecl(field); @@ -919,31 +918,31 @@ static string container_type_name(const Type* ft) return s; } -IntrusivePtr RecordType::GetRecordFieldsVal(const RecordVal* rv) const +TableValPtr RecordType::GetRecordFieldsVal(const RecordVal* rv) const { static auto record_field = zeek::id::find_type("record_field"); static auto record_field_table = zeek::id::find_type("record_field_table"); - auto rval = make_intrusive(record_field_table); + auto rval = zeek::make_intrusive(record_field_table); for ( int i = 0; i < NumFields(); ++i ) { const auto& ft = GetFieldType(i); const TypeDecl* fd = FieldDecl(i); - IntrusivePtr fv; + ValPtr fv; if ( rv ) fv = rv->GetField(i); bool logged = (fd->attrs && fd->GetAttr(zeek::detail::ATTR_LOG) != nullptr); - auto nr = make_intrusive(record_field); + auto nr = zeek::make_intrusive(record_field); string s = container_type_name(ft.get()); - nr->Assign(0, make_intrusive(s)); - nr->Assign(1, val_mgr->Bool(logged)); + nr->Assign(0, zeek::make_intrusive(s)); + nr->Assign(1, zeek::val_mgr->Bool(logged)); nr->Assign(2, std::move(fv)); nr->Assign(3, FieldDefault(i)); - auto field_name = make_intrusive(FieldName(i)); + auto field_name = zeek::make_intrusive(FieldName(i)); rval->Assign(std::move(field_name), std::move(nr)); } @@ -970,9 +969,9 @@ const char* RecordType::AddFields(const type_decl_list& others, if ( add_log_attr ) { if ( ! td->attrs ) - td->attrs = make_intrusive(td->type, true, false); + td->attrs = zeek::make_intrusive(td->type, true, false); - td->attrs->AddAttr(make_intrusive(zeek::detail::ATTR_LOG)); + td->attrs->AddAttr(zeek::make_intrusive(zeek::detail::ATTR_LOG)); } types->push_back(td); @@ -1153,7 +1152,7 @@ void SubNetType::Describe(ODesc* d) const d->Add(int(Tag())); } -FileType::FileType(IntrusivePtr yield_type) +FileType::FileType(TypePtr yield_type) : Type(TYPE_FILE), yield(std::move(yield_type)) { } @@ -1208,12 +1207,12 @@ EnumType::EnumType(const EnumType* e) SetName(e->GetName()); } -IntrusivePtr EnumType::ShallowClone() +TypePtr EnumType::ShallowClone() { if ( counter == 0 ) - return make_intrusive(GetName()); + return zeek::make_intrusive(GetName()); - return make_intrusive(this); + return zeek::make_intrusive(this); } EnumType::~EnumType() = default; @@ -1257,16 +1256,16 @@ void EnumType::CheckAndAddName(const string& module_name, const char* name, return; } - auto id = lookup_ID(name, module_name.c_str()); + auto id = zeek::detail::lookup_ID(name, module_name.c_str()); if ( ! id ) { - id = install_ID(name, module_name.c_str(), true, is_export); - id->SetType({NewRef{}, this}); + id = zeek::detail::install_ID(name, module_name.c_str(), true, is_export); + id->SetType({zeek::NewRef{}, this}); id->SetEnumConst(); if ( deprecation ) - id->MakeDeprecated({NewRef{}, deprecation}); + id->MakeDeprecated({zeek::NewRef{}, deprecation}); zeekygen_mgr->Identifier(std::move(id)); } @@ -1289,7 +1288,7 @@ void EnumType::CheckAndAddName(const string& module_name, const char* name, AddNameInternal(module_name, name, val, is_export); if ( vals.find(val) == vals.end() ) - vals[val] = make_intrusive(IntrusivePtr{NewRef{}, this}, val); + vals[val] = zeek::make_intrusive(zeek::IntrusivePtr{zeek::NewRef{}, this}, val); set types = Type::GetAliases(GetName()); set::const_iterator it; @@ -1338,13 +1337,13 @@ EnumType::enum_name_list EnumType::Names() const return n; } -const IntrusivePtr& EnumType::GetVal(bro_int_t i) +const EnumValPtr& EnumType::GetVal(bro_int_t i) { auto it = vals.find(i); if ( it == vals.end() ) { - auto ev = make_intrusive(IntrusivePtr{NewRef{}, this}, i); + auto ev = zeek::make_intrusive(zeek::IntrusivePtr{zeek::NewRef{}, this}, i); return vals.emplace(i, std::move(ev)).first->second; } @@ -1428,19 +1427,19 @@ void EnumType::DescribeReST(ODesc* d, bool roles_only) const } } -VectorType::VectorType(IntrusivePtr element_type) +VectorType::VectorType(TypePtr element_type) : Type(TYPE_VECTOR), yield_type(std::move(element_type)) { } -IntrusivePtr VectorType::ShallowClone() +TypePtr VectorType::ShallowClone() { - return make_intrusive(yield_type); + return zeek::make_intrusive(yield_type); } VectorType::~VectorType() = default; -const IntrusivePtr& VectorType::Yield() const +const TypePtr& VectorType::Yield() const { // Work around the fact that we use void internally to mark a vector // as being unspecified. When looking at its yield type, we need to @@ -1809,8 +1808,8 @@ TypeTag max_type(TypeTag t1, TypeTag t2) } } -IntrusivePtr merge_types(const IntrusivePtr& arg_t1, - const IntrusivePtr& arg_t2) +TypePtr merge_types(const TypePtr& arg_t1, + const TypePtr& arg_t2) { auto t1 = arg_t1.get(); auto t2 = arg_t2.get(); @@ -1859,7 +1858,7 @@ IntrusivePtr merge_types(const IntrusivePtr& arg_t1, // Doing a lookup here as a roundabout way of ref-ing t1, without // changing the function params which has t1 as const and also // (potentially) avoiding a pitfall mentioned earlier about clones. - const auto& id = global_scope()->Find(t1->GetName()); + const auto& id = zeek::detail::global_scope()->Find(t1->GetName()); if ( id && id->IsType() && id->GetType()->Tag() == TYPE_ENUM ) // It should make most sense to return the real type here rather @@ -1883,7 +1882,7 @@ IntrusivePtr merge_types(const IntrusivePtr& arg_t1, const auto& tl1 = it1->GetIndexTypes(); const auto& tl2 = it2->GetIndexTypes(); - IntrusivePtr tl3; + TypeListPtr tl3; if ( tl1.size() != tl2.size() ) { @@ -1891,7 +1890,7 @@ IntrusivePtr merge_types(const IntrusivePtr& arg_t1, return nullptr; } - tl3 = make_intrusive(); + tl3 = zeek::make_intrusive(); for ( auto i = 0u; i < tl1.size(); ++i ) { @@ -1904,7 +1903,7 @@ IntrusivePtr merge_types(const IntrusivePtr& arg_t1, const auto& y1 = t1->Yield(); const auto& y2 = t2->Yield(); - IntrusivePtr y3; + TypePtr y3; if ( y1 || y2 ) { @@ -1920,9 +1919,9 @@ IntrusivePtr merge_types(const IntrusivePtr& arg_t1, } if ( t1->IsSet() ) - return make_intrusive(std::move(tl3), nullptr); + return zeek::make_intrusive(std::move(tl3), nullptr); else - return make_intrusive(std::move(tl3), std::move(y3)); + return zeek::make_intrusive(std::move(tl3), std::move(y3)); } case TYPE_FUNC: @@ -1935,12 +1934,12 @@ IntrusivePtr merge_types(const IntrusivePtr& arg_t1, const FuncType* ft1 = (const FuncType*) t1; const FuncType* ft2 = (const FuncType*) t1; - auto args = cast_intrusive(merge_types(ft1->Params(), + auto args = zeek::cast_intrusive(merge_types(ft1->Params(), ft2->Params())); auto yield = t1->Yield() ? merge_types(t1->Yield(), t2->Yield()) : nullptr; - return make_intrusive(std::move(args), std::move(yield), + return zeek::make_intrusive(std::move(args), std::move(yield), ft1->Flavor()); } @@ -1970,7 +1969,7 @@ IntrusivePtr merge_types(const IntrusivePtr& arg_t1, tdl3->push_back(new TypeDecl(copy_string(td1->id), std::move(tdl3_i))); } - return make_intrusive(tdl3); + return zeek::make_intrusive(tdl3); } case TYPE_LIST: @@ -2013,7 +2012,7 @@ IntrusivePtr merge_types(const IntrusivePtr& arg_t1, return nullptr; } - auto tl3 = make_intrusive(); + auto tl3 = zeek::make_intrusive(); for ( auto i = 0u; i < l1.size(); ++i ) tl3->Append(merge_types(l1[i], l2[i])); @@ -2028,7 +2027,7 @@ IntrusivePtr merge_types(const IntrusivePtr& arg_t1, return nullptr; } - return make_intrusive(merge_types(t1->Yield(), t2->Yield())); + return zeek::make_intrusive(merge_types(t1->Yield(), t2->Yield())); case TYPE_FILE: if ( ! same_type(t1->Yield(), t2->Yield()) ) @@ -2037,7 +2036,7 @@ IntrusivePtr merge_types(const IntrusivePtr& arg_t1, return nullptr; } - return make_intrusive(merge_types(t1->Yield(), t2->Yield())); + return zeek::make_intrusive(merge_types(t1->Yield(), t2->Yield())); case TYPE_UNION: reporter->InternalError("union type in merge_types()"); @@ -2049,7 +2048,7 @@ IntrusivePtr merge_types(const IntrusivePtr& arg_t1, } } -IntrusivePtr merge_type_list(zeek::detail::ListExpr* elements) +TypePtr merge_type_list(zeek::detail::ListExpr* elements) { TypeList* tl_type = elements->GetType()->AsTypeList(); const auto& tl = tl_type->GetTypes(); @@ -2094,7 +2093,7 @@ static Type* reduce_type(Type* t) return t; } -IntrusivePtr init_type(zeek::detail::Expr* init) +TypePtr init_type(zeek::detail::Expr* init) { if ( init->Tag() != zeek::detail::EXPR_LIST ) { @@ -2133,7 +2132,7 @@ IntrusivePtr init_type(zeek::detail::Expr* init) auto t = e0->InitType(); if ( t ) - t = {NewRef{}, reduce_type(t.get())}; + t = {zeek::NewRef{}, reduce_type(t.get())}; if ( ! t ) return nullptr; @@ -2141,10 +2140,10 @@ IntrusivePtr init_type(zeek::detail::Expr* init) for ( int i = 1; t && i < el.length(); ++i ) { auto el_t = el[i]->InitType(); - IntrusivePtr ti; + TypePtr ti; if ( el_t ) - ti = {NewRef{}, reduce_type(el_t.get())}; + ti = {zeek::NewRef{}, reduce_type(el_t.get())}; if ( ! ti ) return nullptr; @@ -2169,12 +2168,12 @@ IntrusivePtr init_type(zeek::detail::Expr* init) // it one, as that's what's required for creating a set type. if ( t->Tag() != TYPE_LIST ) { - auto tl = make_intrusive(t); + auto tl = zeek::make_intrusive(t); tl->Append(std::move(t)); t = std::move(tl); } - return make_intrusive(cast_intrusive(std::move(t)), + return zeek::make_intrusive(zeek::cast_intrusive(std::move(t)), nullptr); } @@ -2193,16 +2192,16 @@ bool is_atomic_type(const Type& t) } } -const IntrusivePtr& base_type(zeek::TypeTag tag) +const TypePtr& base_type(zeek::TypeTag tag) { - static IntrusivePtr base_types[NUM_TYPES]; + static TypePtr base_types[NUM_TYPES]; // We could check here that "tag" actually corresponds to a basic type. if ( ! base_types[tag] ) { - base_types[tag] = make_intrusive(tag, true); + base_types[tag] = zeek::make_intrusive(tag, true); // Give the base types a pseudo-location for easier identification. - Location l(type_name(tag), 0, 0, 0, 0); + zeek::detail::Location l(type_name(tag), 0, 0, 0, 0); base_types[tag]->SetLocationInfo(&l); } diff --git a/src/Type.h b/src/Type.h index bec4017d26..b5d58a633c 100644 --- a/src/Type.h +++ b/src/Type.h @@ -14,13 +14,23 @@ #include #include -class EnumVal; -class TableVal; - +ZEEK_FORWARD_DECLARE_NAMESPACED(Val, zeek); +ZEEK_FORWARD_DECLARE_NAMESPACED(EnumVal, zeek); +ZEEK_FORWARD_DECLARE_NAMESPACED(TableVal, zeek); ZEEK_FORWARD_DECLARE_NAMESPACED(Expr, zeek::detail); ZEEK_FORWARD_DECLARE_NAMESPACED(ListExpr, zeek::detail); ZEEK_FORWARD_DECLARE_NAMESPACED(Attributes, zeek::detail); +namespace zeek { +using ValPtr = zeek::IntrusivePtr; +using EnumValPtr = zeek::IntrusivePtr; +using TableValPtr = zeek::IntrusivePtr; + +namespace detail { +using ListExprPtr = zeek::IntrusivePtr; +} +} + namespace zeek { // BRO types. @@ -127,6 +137,7 @@ constexpr InternalTypeTag to_internal_type_tag(TypeTag tag) noexcept return TYPE_INTERNAL_VOID; } +class Type; class TypeList; class TableType; class SetType; @@ -137,14 +148,28 @@ class EnumType; class VectorType; class TypeType; class OpaqueType; +class FileType; + +using TypePtr = zeek::IntrusivePtr; +using TypeListPtr = zeek::IntrusivePtr; +using TableTypePtr = zeek::IntrusivePtr; +using SetTypePtr = zeek::IntrusivePtr; +using RecordTypePtr = zeek::IntrusivePtr; +using SubNetTypePtr = zeek::IntrusivePtr; +using FuncTypePtr = zeek::IntrusivePtr; +using EnumTypePtr = zeek::IntrusivePtr; +using VectorTypePtr = zeek::IntrusivePtr; +using TypeTypePtr = zeek::IntrusivePtr; +using OpaqueTypePtr = zeek::IntrusivePtr; +using FileTypePtr = zeek::IntrusivePtr; constexpr int DOES_NOT_MATCH_INDEX = 0; constexpr int MATCHES_INDEX_SCALAR = 1; constexpr int MATCHES_INDEX_VECTOR = 2; -class Type : public BroObj { +class Type : public Obj { public: - static inline const IntrusivePtr nil; + static inline const TypePtr nil; explicit Type(zeek::TypeTag tag, bool base_type = false); @@ -156,7 +181,7 @@ public: // Clone operations will mostly be implemented in the derived classes; // in addition cloning will be limited to classes that can be reached by // the script-level. - virtual IntrusivePtr ShallowClone(); + virtual TypePtr ShallowClone(); TypeTag Tag() const { return tag; } InternalTypeTag InternalType() const { return internal_tag; } @@ -176,7 +201,7 @@ public: // Returns the type yielded by this type. For example, if // this type is a table[string] of port, then returns the "port" // type. Returns nil if this is not an index type. - virtual const IntrusivePtr& Yield() const; + virtual const TypePtr& Yield() const; [[deprecated("Remove in v4.1. Use Yield() instead.")]] virtual Type* YieldType() @@ -234,7 +259,7 @@ public: return tag == TYPE_TABLE && Yield(); } - Type* Ref() { ::Ref(this); return this; } + Type* Ref() { zeek::Ref(this); return this; } void Describe(ODesc* d) const override; virtual void DescribeReST(ODesc* d, bool roles_only = false) const; @@ -269,7 +294,7 @@ private: class TypeList final : public Type { public: - explicit TypeList(IntrusivePtr arg_pure_type = nullptr) + explicit TypeList(TypePtr arg_pure_type = nullptr) : Type(TYPE_LIST), pure_type(std::move(arg_pure_type)) { } @@ -280,14 +305,14 @@ public: const type_list* Types() const { return &types_list; } - const std::vector>& GetTypes() const + const std::vector& GetTypes() const { return types; } bool IsPure() const { return pure_type != nullptr; } // Returns the underlying pure type, or nil if the list // is not pure or is empty. - const IntrusivePtr& GetPureType() const + const TypePtr& GetPureType() const { return pure_type; } [[deprecated("Remove in v4.1. Use GetPureType() instead.")]] @@ -299,19 +324,19 @@ public: // is_init is true, then the matching is done in the context // of an initialization. bool AllMatch(const Type* t, bool is_init) const; - bool AllMatch(const IntrusivePtr& t, bool is_init) const + bool AllMatch(const TypePtr& t, bool is_init) const { return AllMatch(t.get(), is_init); } - void Append(IntrusivePtr t); - void AppendEvenIfNotPure(IntrusivePtr t); + void Append(TypePtr t); + void AppendEvenIfNotPure(TypePtr t); void Describe(ODesc* d) const override; unsigned int MemoryAllocation() const override; protected: - IntrusivePtr pure_type; - std::vector> types; + TypePtr pure_type; + std::vector types; // Remove in v4.1. This is used by Types(), which is deprecated. type_list types_list; @@ -322,7 +347,7 @@ public: int MatchesIndex(zeek::detail::ListExpr* index) const override; - const IntrusivePtr& GetIndices() const + const TypeListPtr& GetIndices() const { return indices; } [[deprecated("Remove in v4.1. Use GetIndices().")]] @@ -337,10 +362,10 @@ public: #pragma GCC diagnostic pop } - const std::vector>& GetIndexTypes() const + const std::vector& GetIndexTypes() const { return indices->GetTypes(); } - const IntrusivePtr& Yield() const override + const TypePtr& Yield() const override { return yield_type; } void Describe(ODesc* d) const override; @@ -350,8 +375,8 @@ public: bool IsSubNetIndex() const; protected: - IndexType(TypeTag t, IntrusivePtr arg_indices, - IntrusivePtr arg_yield_type) + IndexType(TypeTag t, TypeListPtr arg_indices, + TypePtr arg_yield_type) : Type(t), indices(std::move(arg_indices)), yield_type(std::move(arg_yield_type)) { @@ -359,15 +384,15 @@ protected: ~IndexType() override = default; - IntrusivePtr indices; - IntrusivePtr yield_type; + TypeListPtr indices; + TypePtr yield_type; }; class TableType : public IndexType { public: - TableType(IntrusivePtr ind, IntrusivePtr yield); + TableType(TypeListPtr ind, TypePtr yield); - IntrusivePtr ShallowClone() override; + TypePtr ShallowClone() override; // Returns true if this table type is "unspecified", which is // what one gets using an empty "set()" or "table()" constructor. @@ -376,24 +401,24 @@ public: class SetType final : public TableType { public: - SetType(IntrusivePtr ind, IntrusivePtr arg_elements); + SetType(TypeListPtr ind, zeek::detail::ListExprPtr arg_elements); ~SetType() override; - IntrusivePtr ShallowClone() override; + TypePtr ShallowClone() override; [[deprecated("Remove in v4.1. Use Elements() isntead.")]] zeek::detail::ListExpr* SetElements() const { return elements.get(); } - const IntrusivePtr& Elements() const + const zeek::detail::ListExprPtr& Elements() const { return elements; } protected: - IntrusivePtr elements; + zeek::detail::ListExprPtr elements; }; class FuncType final : public Type { public: - static inline const IntrusivePtr nil; + static inline const FuncTypePtr nil; /** * Prototype is only currently used for events and hooks which declare @@ -402,27 +427,27 @@ public: */ struct Prototype { bool deprecated; - IntrusivePtr args; + RecordTypePtr args; std::map offsets; }; - FuncType(IntrusivePtr args, IntrusivePtr yield, + FuncType(RecordTypePtr args, TypePtr yield, FunctionFlavor f); - IntrusivePtr ShallowClone() override; + TypePtr ShallowClone() override; ~FuncType() override; [[deprecated("Remove in v4.1. Use Params().")]] RecordType* Args() const { return args.get(); } - const IntrusivePtr& Params() const + const RecordTypePtr& Params() const { return args; } - const IntrusivePtr& Yield() const override + const TypePtr& Yield() const override { return yield; } - void SetYieldType(IntrusivePtr arg_yield) { yield = std::move(arg_yield); } + void SetYieldType(TypePtr arg_yield) { yield = std::move(arg_yield); } FunctionFlavor Flavor() const { return flavor; } std::string FlavorString() const; @@ -432,13 +457,13 @@ public: int MatchesIndex(zeek::detail::ListExpr* index) const override; bool CheckArgs(const type_list* args, bool is_init = false) const; - bool CheckArgs(const std::vector>& args, + bool CheckArgs(const std::vector& args, bool is_init = false) const; [[deprecated("Remove in v4.1. Use ParamList().")]] TypeList* ArgTypes() const { return arg_types.get(); } - const IntrusivePtr& ParamList() const + const TypeListPtr& ParamList() const { return arg_types; } void Describe(ODesc* d) const override; @@ -461,27 +486,27 @@ public: { return prototypes; } protected: - friend IntrusivePtr make_intrusive(); + friend FuncTypePtr zeek::make_intrusive(); FuncType() : Type(TYPE_FUNC) { flavor = FUNC_FLAVOR_FUNCTION; } - IntrusivePtr args; - IntrusivePtr arg_types; - IntrusivePtr yield; + RecordTypePtr args; + TypeListPtr arg_types; + TypePtr yield; FunctionFlavor flavor; std::vector prototypes; }; class TypeType final : public Type { public: - explicit TypeType(IntrusivePtr t) : zeek::Type(TYPE_TYPE), type(std::move(t)) {} - IntrusivePtr ShallowClone() override { return make_intrusive(type); } + explicit TypeType(TypePtr t) : zeek::Type(TYPE_TYPE), type(std::move(t)) {} + TypePtr ShallowClone() override { return zeek::make_intrusive(type); } - const IntrusivePtr& GetType() const + const TypePtr& GetType() const { return type; } template - IntrusivePtr GetType() const - { return cast_intrusive(type); } + zeek::IntrusivePtr GetType() const + { return zeek::cast_intrusive(type); } [[deprecated("Remove in v4.1. Use GetType().")]] zeek::Type* Type() { return type.get(); } @@ -489,33 +514,32 @@ public: const zeek::Type* Type() const { return type.get(); } protected: - IntrusivePtr type; + TypePtr type; }; class TypeDecl final { public: TypeDecl() = default; - TypeDecl(const char* i, IntrusivePtr t, - IntrusivePtr attrs = nullptr); + TypeDecl(const char* i, TypePtr t, zeek::detail::AttributesPtr attrs = nullptr); TypeDecl(const TypeDecl& other); ~TypeDecl(); - const IntrusivePtr& GetAttr(zeek::detail::AttrTag a) const + const zeek::detail::AttrPtr& GetAttr(zeek::detail::AttrTag a) const { return attrs ? attrs->Find(a) : zeek::detail::Attr::nil; } void DescribeReST(ODesc* d, bool roles_only = false) const; - IntrusivePtr type; - IntrusivePtr attrs; + TypePtr type; + zeek::detail::AttributesPtr attrs; const char* id = nullptr; }; -using type_decl_list = PList; +using type_decl_list = zeek::PList; class RecordType final : public Type { public: explicit RecordType(type_decl_list* types); - IntrusivePtr ShallowClone() override; + TypePtr ShallowClone() override; ~RecordType() override; @@ -536,7 +560,7 @@ public: * Looks up a field by name and returns its type. No check for invalid * field name is performed. */ - const IntrusivePtr& GetFieldType(const char* field_name) const + const TypePtr& GetFieldType(const char* field_name) const { return GetFieldType(FieldOffset(field_name)); } /** @@ -544,14 +568,14 @@ public: * No check for invalid field name is performed. */ template - IntrusivePtr GetFieldType(const char* field_name) const - { return cast_intrusive(GetFieldType(field_name)); } + zeek::IntrusivePtr GetFieldType(const char* field_name) const + { return zeek::cast_intrusive(GetFieldType(field_name)); } /** * Looks up a field by its index and returns its type. No check for * invalid field offset is performed. */ - const IntrusivePtr& GetFieldType(int field_index) const + const TypePtr& GetFieldType(int field_index) const { return (*types)[field_index]->type; } /** @@ -559,10 +583,10 @@ public: * No check for invalid field offset is performed. */ template - IntrusivePtr GetFieldType(int field_index) const - { return cast_intrusive((*types)[field_index]->type); } + zeek::IntrusivePtr GetFieldType(int field_index) const + { return zeek::cast_intrusive((*types)[field_index]->type); } - IntrusivePtr FieldDefault(int field) const; + zeek::ValPtr FieldDefault(int field) const; // A field's offset is its position in the type_decl_list, // starting at 0. Returns negative if the field doesn't exist. @@ -584,7 +608,7 @@ public: * @param rv an optional record value, if given the values of * all fields will be provided in the returned table. */ - IntrusivePtr GetRecordFieldsVal(const RecordVal* rv = nullptr) const; + zeek::TableValPtr GetRecordFieldsVal(const zeek::RecordVal* rv = nullptr) const; // Returns null if all is ok, otherwise a pointer to an error message. const char* AddFields(const type_decl_list& types, @@ -624,23 +648,23 @@ public: class FileType final : public Type { public: - explicit FileType(IntrusivePtr yield_type); - IntrusivePtr ShallowClone() override { return make_intrusive(yield); } + explicit FileType(TypePtr yield_type); + TypePtr ShallowClone() override { return zeek::make_intrusive(yield); } ~FileType() override; - const IntrusivePtr& Yield() const override + const TypePtr& Yield() const override { return yield; } void Describe(ODesc* d) const override; protected: - IntrusivePtr yield; + TypePtr yield; }; class OpaqueType final : public Type { public: explicit OpaqueType(const std::string& name); - IntrusivePtr ShallowClone() override { return make_intrusive(name); } + TypePtr ShallowClone() override { return zeek::make_intrusive(name); } ~OpaqueType() override { }; const std::string& Name() const { return name; } @@ -660,7 +684,7 @@ public: explicit EnumType(const EnumType* e); explicit EnumType(const std::string& arg_name); - IntrusivePtr ShallowClone() override; + TypePtr ShallowClone() override; ~EnumType() override; // The value of this name is next internal counter value, starting @@ -682,7 +706,7 @@ public: void DescribeReST(ODesc* d, bool roles_only = false) const override; - const IntrusivePtr& GetVal(bro_int_t i); + const zeek::EnumValPtr& GetVal(bro_int_t i); protected: void AddNameInternal(const std::string& module_name, @@ -695,7 +719,7 @@ protected: typedef std::map NameMap; NameMap names; - using ValMap = std::unordered_map>; + using ValMap = std::unordered_map; ValMap vals; // The counter is initialized to 0 and incremented on every implicit @@ -709,11 +733,11 @@ protected: class VectorType final : public Type { public: - explicit VectorType(IntrusivePtr t); - IntrusivePtr ShallowClone() override; + explicit VectorType(TypePtr t); + TypePtr ShallowClone() override; ~VectorType() override; - const IntrusivePtr& Yield() const override; + const TypePtr& Yield() const override; int MatchesIndex(zeek::detail::ListExpr* index) const override; @@ -725,7 +749,7 @@ public: void DescribeReST(ODesc* d, bool roles_only = false) const override; protected: - IntrusivePtr yield_type; + TypePtr yield_type; }; // True if the two types are equivalent. If is_init is true then the test is @@ -733,16 +757,16 @@ protected: // true then for record types the field names have to match, too. extern bool same_type(const Type& t1, const Type& t2, bool is_init=false, bool match_record_field_names=true); -inline bool same_type(const IntrusivePtr& t1, const IntrusivePtr& t2, +inline bool same_type(const TypePtr& t1, const TypePtr& t2, bool is_init=false, bool match_record_field_names=true) { return same_type(*t1, *t2, is_init, match_record_field_names); } inline bool same_type(const Type* t1, const Type* t2, bool is_init=false, bool match_record_field_names=true) { return same_type(*t1, *t2, is_init, match_record_field_names); } -inline bool same_type(const IntrusivePtr& t1, const Type* t2, +inline bool same_type(const TypePtr& t1, const Type* t2, bool is_init=false, bool match_record_field_names=true) { return same_type(*t1, *t2, is_init, match_record_field_names); } -inline bool same_type(const Type* t1, const IntrusivePtr& t2, +inline bool same_type(const Type* t1, const TypePtr& t2, bool is_init=false, bool match_record_field_names=true) { return same_type(*t1, *t2, is_init, match_record_field_names); } @@ -765,22 +789,21 @@ extern TypeTag max_type(TypeTag t1, TypeTag t2); // Given two types, returns the "merge", in which promotable types // are promoted to the maximum of the two. Returns nil (and generates // an error message) if the types are incompatible. -IntrusivePtr merge_types(const IntrusivePtr& t1, - const IntrusivePtr& t2); +TypePtr merge_types(const TypePtr& t1, const TypePtr& t2); // Given a list of expressions, returns a (ref'd) type reflecting // a merged type consistent across all of them, or nil if this // cannot be done. -IntrusivePtr merge_type_list(zeek::detail::ListExpr* elements); +TypePtr merge_type_list(zeek::detail::ListExpr* elements); // Given an expression, infer its type when used for an initialization. -IntrusivePtr init_type(zeek::detail::Expr* init); +TypePtr init_type(zeek::detail::Expr* init); // Returns true if argument is an atomic type. bool is_atomic_type(const Type& t); inline bool is_atomic_type(const Type* t) { return is_atomic_type(*t); } -inline bool is_atomic_type(const IntrusivePtr& t) +inline bool is_atomic_type(const TypePtr& t) { return is_atomic_type(*t); } // True if the given type tag corresponds to type that can be assigned to. @@ -837,10 +860,10 @@ inline bool BothString(TypeTag t1, TypeTag t2) { return (IsString(t1) && IsStrin inline bool EitherError(TypeTag t1, TypeTag t2) { return (IsErrorType(t1) || IsErrorType(t2)); } // Returns the basic (non-parameterized) type with the given type. -const IntrusivePtr& base_type(zeek::TypeTag tag); +const TypePtr& base_type(zeek::TypeTag tag); // Returns the basic error type. -inline const IntrusivePtr& error_type() { return base_type(TYPE_ERROR); } +inline const TypePtr& error_type() { return base_type(TYPE_ERROR); } } // namespace zeek @@ -850,16 +873,16 @@ inline const IntrusivePtr& error_type() { return base_type(TYP inline zeek::Type* base_type_no_ref(zeek::TypeTag tag) { return zeek::base_type(tag).get(); } -extern IntrusivePtr md5_type; -extern IntrusivePtr sha1_type; -extern IntrusivePtr sha256_type; -extern IntrusivePtr entropy_type; -extern IntrusivePtr cardinality_type; -extern IntrusivePtr topk_type; -extern IntrusivePtr bloomfilter_type; -extern IntrusivePtr x509_opaque_type; -extern IntrusivePtr ocsp_resp_opaque_type; -extern IntrusivePtr paraglob_type; +extern zeek::OpaqueTypePtr md5_type; +extern zeek::OpaqueTypePtr sha1_type; +extern zeek::OpaqueTypePtr sha256_type; +extern zeek::OpaqueTypePtr entropy_type; +extern zeek::OpaqueTypePtr cardinality_type; +extern zeek::OpaqueTypePtr topk_type; +extern zeek::OpaqueTypePtr bloomfilter_type; +extern zeek::OpaqueTypePtr x509_opaque_type; +extern zeek::OpaqueTypePtr ocsp_resp_opaque_type; +extern zeek::OpaqueTypePtr paraglob_type; using BroType [[deprecated("Remove in v4.1. Use zeek::Type instead.")]] = zeek::Type; using TypeList [[deprecated("Remove in v4.1. Use zeek::TypeList instead.")]] = zeek::TypeList; diff --git a/src/Val.cc b/src/Val.cc index cb461dacfd..37360464c0 100644 --- a/src/Val.cc +++ b/src/Val.cc @@ -17,7 +17,7 @@ #include #include "Attr.h" -#include "BroString.h" +#include "ZeekString.h" #include "CompHash.h" #include "Dict.h" #include "Net.h" @@ -42,17 +42,19 @@ using namespace std; -Val::Val(Func* f) : Val({NewRef{}, f}) +namespace zeek { + +Val::Val(zeek::Func* f) : Val({NewRef{}, f}) {} -Val::Val(IntrusivePtr f) +Val::Val(zeek::FuncPtr f) : val(f.release()), type(val.func_val->GetType()) {} -static const IntrusivePtr& GetStringFileType() noexcept +static const FileTypePtr& GetStringFileType() noexcept { - static IntrusivePtr string_file_type - = make_intrusive(zeek::base_type(zeek::TYPE_STRING)); + static auto string_file_type + = make_intrusive(base_type(TYPE_STRING)); return string_file_type; } @@ -60,21 +62,21 @@ static const IntrusivePtr& GetStringFileType() noexcept Val::Val(BroFile* f) : Val({AdoptRef{}, f}) {} -Val::Val(IntrusivePtr f) +Val::Val(BroFilePtr f) : val(f.release()), type(GetStringFileType()) { - assert(val.file_val->GetType()->Tag() == zeek::TYPE_STRING); + assert(val.file_val->GetType()->Tag() == TYPE_STRING); } Val::~Val() { - if ( type->InternalType() == zeek::TYPE_INTERNAL_STRING ) + if ( type->InternalType() == TYPE_INTERNAL_STRING ) delete val.string_val; - else if ( type->Tag() == zeek::TYPE_FUNC ) + else if ( type->Tag() == TYPE_FUNC ) Unref(val.func_val); - else if ( type->Tag() == zeek::TYPE_FILE ) + else if ( type->Tag() == TYPE_FILE ) Unref(val.file_val); #ifdef DEBUG @@ -112,19 +114,19 @@ CONVERTERS(zeek::TYPE_VECTOR, VectorVal*, Val::AsVectorVal) CONVERTERS(zeek::TYPE_ENUM, EnumVal*, Val::AsEnumVal) CONVERTERS(zeek::TYPE_OPAQUE, OpaqueVal*, Val::AsOpaqueVal) -IntrusivePtr Val::CloneState::NewClone(Val* src, IntrusivePtr dst) +ValPtr Val::CloneState::NewClone(Val* src, ValPtr dst) { clones.insert(std::make_pair(src, dst.get())); return dst; } -IntrusivePtr Val::Clone() +ValPtr Val::Clone() { Val::CloneState state; return Clone(&state); } -IntrusivePtr Val::Clone(CloneState* state) +ValPtr Val::Clone(CloneState* state) { auto i = state->clones.find(this); @@ -139,22 +141,22 @@ IntrusivePtr Val::Clone(CloneState* state) return c; } -IntrusivePtr Val::DoClone(CloneState* state) +ValPtr Val::DoClone(CloneState* state) { switch ( type->InternalType() ) { - case zeek::TYPE_INTERNAL_INT: - case zeek::TYPE_INTERNAL_UNSIGNED: - case zeek::TYPE_INTERNAL_DOUBLE: + case TYPE_INTERNAL_INT: + case TYPE_INTERNAL_UNSIGNED: + case TYPE_INTERNAL_DOUBLE: // Immutable. return {NewRef{}, this}; - case zeek::TYPE_INTERNAL_OTHER: + case TYPE_INTERNAL_OTHER: // Derived classes are responsible for this. Exception: // Functions and files. There aren't any derived classes. - if ( type->Tag() == zeek::TYPE_FUNC ) - return make_intrusive(AsFunc()->DoClone()); + if ( type->Tag() == TYPE_FUNC ) + return make_intrusive(AsFunc()->DoClone()); - if ( type->Tag() == zeek::TYPE_FILE ) + if ( type->Tag() == TYPE_FILE ) { // I think we can just ref the file here - it is unclear what else // to do. In the case of cached files, I think this is equivalent @@ -169,7 +171,7 @@ IntrusivePtr Val::DoClone(CloneState* state) return {NewRef{}, this}; } - if ( type->Tag() == zeek::TYPE_TYPE ) + if ( type->Tag() == TYPE_TYPE ) // These are immutable, essentially. return {NewRef{}, this}; @@ -183,18 +185,18 @@ IntrusivePtr Val::DoClone(CloneState* state) return nullptr; } -IntrusivePtr Val::AsFuncPtr() const +zeek::FuncPtr Val::AsFuncPtr() const { - CHECK_TAG(type->Tag(), zeek::TYPE_FUNC, "Val::Func", zeek::type_name) + CHECK_TAG(type->Tag(), TYPE_FUNC, "Val::Func", type_name) return {NewRef{}, val.func_val}; } bool Val::IsZero() const { switch ( type->InternalType() ) { - case zeek::TYPE_INTERNAL_INT: return val.int_val == 0; - case zeek::TYPE_INTERNAL_UNSIGNED: return val.uint_val == 0; - case zeek::TYPE_INTERNAL_DOUBLE: return val.double_val == 0.0; + case TYPE_INTERNAL_INT: return val.int_val == 0; + case TYPE_INTERNAL_UNSIGNED: return val.uint_val == 0; + case TYPE_INTERNAL_DOUBLE: return val.double_val == 0.0; default: return false; } @@ -203,9 +205,9 @@ bool Val::IsZero() const bool Val::IsOne() const { switch ( type->InternalType() ) { - case zeek::TYPE_INTERNAL_INT: return val.int_val == 1; - case zeek::TYPE_INTERNAL_UNSIGNED: return val.uint_val == 1; - case zeek::TYPE_INTERNAL_DOUBLE: return val.double_val == 1.0; + case TYPE_INTERNAL_INT: return val.int_val == 1; + case TYPE_INTERNAL_UNSIGNED: return val.uint_val == 1; + case TYPE_INTERNAL_DOUBLE: return val.double_val == 1.0; default: return false; } @@ -213,9 +215,9 @@ bool Val::IsOne() const bro_int_t Val::InternalInt() const { - if ( type->InternalType() == zeek::TYPE_INTERNAL_INT ) + if ( type->InternalType() == TYPE_INTERNAL_INT ) return val.int_val; - else if ( type->InternalType() == zeek::TYPE_INTERNAL_UNSIGNED ) + else if ( type->InternalType() == TYPE_INTERNAL_UNSIGNED ) // ### should check here for overflow return static_cast(val.uint_val); else @@ -226,7 +228,7 @@ bro_int_t Val::InternalInt() const bro_uint_t Val::InternalUnsigned() const { - if ( type->InternalType() == zeek::TYPE_INTERNAL_UNSIGNED ) + if ( type->InternalType() == TYPE_INTERNAL_UNSIGNED ) return val.uint_val; else InternalWarning("bad request for InternalUnsigned"); @@ -236,7 +238,7 @@ bro_uint_t Val::InternalUnsigned() const double Val::InternalDouble() const { - if ( type->InternalType() == zeek::TYPE_INTERNAL_DOUBLE ) + if ( type->InternalType() == TYPE_INTERNAL_DOUBLE ) return val.double_val; else InternalWarning("bad request for InternalDouble"); @@ -246,11 +248,11 @@ double Val::InternalDouble() const bro_int_t Val::CoerceToInt() const { - if ( type->InternalType() == zeek::TYPE_INTERNAL_INT ) + if ( type->InternalType() == TYPE_INTERNAL_INT ) return val.int_val; - else if ( type->InternalType() == zeek::TYPE_INTERNAL_UNSIGNED ) + else if ( type->InternalType() == TYPE_INTERNAL_UNSIGNED ) return static_cast(val.uint_val); - else if ( type->InternalType() == zeek::TYPE_INTERNAL_DOUBLE ) + else if ( type->InternalType() == TYPE_INTERNAL_DOUBLE ) return static_cast(val.double_val); else InternalWarning("bad request for CoerceToInt"); @@ -260,11 +262,11 @@ bro_int_t Val::CoerceToInt() const bro_uint_t Val::CoerceToUnsigned() const { - if ( type->InternalType() == zeek::TYPE_INTERNAL_UNSIGNED ) + if ( type->InternalType() == TYPE_INTERNAL_UNSIGNED ) return val.uint_val; - else if ( type->InternalType() == zeek::TYPE_INTERNAL_INT ) + else if ( type->InternalType() == TYPE_INTERNAL_INT ) return static_cast(val.int_val); - else if ( type->InternalType() == zeek::TYPE_INTERNAL_DOUBLE ) + else if ( type->InternalType() == TYPE_INTERNAL_DOUBLE ) return static_cast(val.double_val); else InternalWarning("bad request for CoerceToUnsigned"); @@ -274,11 +276,11 @@ bro_uint_t Val::CoerceToUnsigned() const double Val::CoerceToDouble() const { - if ( type->InternalType() == zeek::TYPE_INTERNAL_DOUBLE ) + if ( type->InternalType() == TYPE_INTERNAL_DOUBLE ) return val.double_val; - else if ( type->InternalType() == zeek::TYPE_INTERNAL_INT ) + else if ( type->InternalType() == TYPE_INTERNAL_INT ) return static_cast(val.int_val); - else if ( type->InternalType() == zeek::TYPE_INTERNAL_UNSIGNED ) + else if ( type->InternalType() == TYPE_INTERNAL_UNSIGNED ) return static_cast(val.uint_val); else InternalWarning("bad request for CoerceToDouble"); @@ -286,36 +288,36 @@ double Val::CoerceToDouble() const return 0.0; } -IntrusivePtr Val::SizeVal() const +ValPtr Val::SizeVal() const { switch ( type->InternalType() ) { - case zeek::TYPE_INTERNAL_INT: + case TYPE_INTERNAL_INT: // Return abs value. However abs() only works on ints and llabs // doesn't work on Mac OS X 10.5. So we do it by hand if ( val.int_val < 0 ) - return val_mgr->Count(-val.int_val); + return zeek::val_mgr->Count(-val.int_val); else - return val_mgr->Count(val.int_val); + return zeek::val_mgr->Count(val.int_val); - case zeek::TYPE_INTERNAL_UNSIGNED: - return val_mgr->Count(val.uint_val); + case TYPE_INTERNAL_UNSIGNED: + return zeek::val_mgr->Count(val.uint_val); - case zeek::TYPE_INTERNAL_DOUBLE: - return make_intrusive(fabs(val.double_val)); + case TYPE_INTERNAL_DOUBLE: + return make_intrusive(fabs(val.double_val)); - case zeek::TYPE_INTERNAL_OTHER: - if ( type->Tag() == zeek::TYPE_FUNC ) - return val_mgr->Count(val.func_val->GetType()->ParamList()->GetTypes().size()); + case TYPE_INTERNAL_OTHER: + if ( type->Tag() == TYPE_FUNC ) + return zeek::val_mgr->Count(val.func_val->GetType()->ParamList()->GetTypes().size()); - if ( type->Tag() == zeek::TYPE_FILE ) - return make_intrusive(val.file_val->Size()); + if ( type->Tag() == TYPE_FILE ) + return make_intrusive(val.file_val->Size()); break; default: break; } - return val_mgr->Count(0); + return zeek::val_mgr->Count(0); } unsigned int Val::MemoryAllocation() const @@ -353,36 +355,36 @@ void Val::DescribeReST(ODesc* d) const void Val::ValDescribe(ODesc* d) const { - if ( d->IsReadable() && type->Tag() == zeek::TYPE_BOOL ) + if ( d->IsReadable() && type->Tag() == TYPE_BOOL ) { d->Add(CoerceToInt() ? "T" : "F"); return; } switch ( type->InternalType() ) { - case zeek::TYPE_INTERNAL_INT: d->Add(val.int_val); break; - case zeek::TYPE_INTERNAL_UNSIGNED: d->Add(val.uint_val); break; - case zeek::TYPE_INTERNAL_DOUBLE: d->Add(val.double_val); break; - case zeek::TYPE_INTERNAL_STRING: d->AddBytes(val.string_val); break; - case zeek::TYPE_INTERNAL_ADDR: d->Add(val.addr_val->AsString().c_str()); break; + case TYPE_INTERNAL_INT: d->Add(val.int_val); break; + case TYPE_INTERNAL_UNSIGNED: d->Add(val.uint_val); break; + case TYPE_INTERNAL_DOUBLE: d->Add(val.double_val); break; + case TYPE_INTERNAL_STRING: d->AddBytes(val.string_val); break; + case TYPE_INTERNAL_ADDR: d->Add(val.addr_val->AsString().c_str()); break; - case zeek::TYPE_INTERNAL_SUBNET: + case TYPE_INTERNAL_SUBNET: d->Add(val.subnet_val->AsString().c_str()); break; - case zeek::TYPE_INTERNAL_ERROR: d->AddCS("error"); break; - case zeek::TYPE_INTERNAL_OTHER: - if ( type->Tag() == zeek::TYPE_FUNC ) + case TYPE_INTERNAL_ERROR: d->AddCS("error"); break; + case TYPE_INTERNAL_OTHER: + if ( type->Tag() == TYPE_FUNC ) AsFunc()->Describe(d); - else if ( type->Tag() == zeek::TYPE_FILE ) + else if ( type->Tag() == TYPE_FILE ) AsFile()->Describe(d); - else if ( type->Tag() == zeek::TYPE_TYPE ) + else if ( type->Tag() == TYPE_TYPE ) d->Add(type->AsTypeType()->GetType()->GetName()); else d->Add(""); break; - case zeek::TYPE_INTERNAL_VOID: + case TYPE_INTERNAL_VOID: d->Add(""); break; @@ -396,7 +398,7 @@ void Val::ValDescribe(ODesc* d) const void Val::ValDescribeReST(ODesc* d) const { switch ( type->InternalType() ) { - case zeek::TYPE_INTERNAL_OTHER: + case TYPE_INTERNAL_OTHER: Describe(d); break; @@ -409,12 +411,12 @@ void Val::ValDescribeReST(ODesc* d) const #ifdef DEBUG -zeek::detail::ID* Val::GetID() const +detail::ID* Val::GetID() const { - return bound_id ? global_scope()->Find(bound_id).get() : nullptr; + return bound_id ? zeek::detail::global_scope()->Find(bound_id).get() : nullptr; } -void Val::SetID(zeek::detail::ID* id) +void Val::SetID(detail::ID* id) { delete [] bound_id; bound_id = id ? copy_string(id->Name()) : nullptr; @@ -428,42 +430,42 @@ bool Val::WouldOverflow(const zeek::Type* from_type, const zeek::Type* to_type, else if ( same_type(to_type, from_type) ) return false; - if ( to_type->InternalType() == zeek::TYPE_INTERNAL_DOUBLE ) + if ( to_type->InternalType() == TYPE_INTERNAL_DOUBLE ) return false; - else if ( to_type->InternalType() == zeek::TYPE_INTERNAL_UNSIGNED ) + else if ( to_type->InternalType() == TYPE_INTERNAL_UNSIGNED ) { - if ( from_type->InternalType() == zeek::TYPE_INTERNAL_DOUBLE ) + if ( from_type->InternalType() == TYPE_INTERNAL_DOUBLE ) return (val->InternalDouble() < 0.0 || val->InternalDouble() > static_cast(UINT64_MAX)); - else if ( from_type->InternalType() == zeek::TYPE_INTERNAL_INT ) + else if ( from_type->InternalType() == TYPE_INTERNAL_INT ) return (val->InternalInt() < 0); } - else if ( to_type->InternalType() == zeek::TYPE_INTERNAL_INT ) + else if ( to_type->InternalType() == TYPE_INTERNAL_INT ) { - if ( from_type->InternalType() == zeek::TYPE_INTERNAL_DOUBLE ) + if ( from_type->InternalType() == TYPE_INTERNAL_DOUBLE ) return (val->InternalDouble() < static_cast(INT64_MIN) || val->InternalDouble() > static_cast(INT64_MAX)); - else if ( from_type->InternalType() == zeek::TYPE_INTERNAL_UNSIGNED ) + else if ( from_type->InternalType() == TYPE_INTERNAL_UNSIGNED ) return (val->InternalUnsigned() > INT64_MAX); } return false; } -IntrusivePtr Val::GetRecordFields() +TableValPtr Val::GetRecordFields() { - static auto record_field_table = zeek::id::find_type("record_field_table"); + static auto record_field_table = id::find_type("record_field_table"); auto t = GetType().get(); - if ( t->Tag() != zeek::TYPE_RECORD && t->Tag() != zeek::TYPE_TYPE ) + if ( t->Tag() != TYPE_RECORD && t->Tag() != TYPE_TYPE ) { reporter->Error("non-record value/type passed to record_fields"); - return make_intrusive(record_field_table); + return make_intrusive(record_field_table); } - zeek::RecordType* rt = nullptr; + RecordType* rt = nullptr; RecordVal* rv = nullptr; - if ( t->Tag() == zeek::TYPE_RECORD ) + if ( t->Tag() == TYPE_RECORD ) { rt = t->AsRecordType(); rv = AsRecordVal(); @@ -472,10 +474,10 @@ IntrusivePtr Val::GetRecordFields() { t = t->AsTypeType()->GetType().get(); - if ( t->Tag() != zeek::TYPE_RECORD ) + if ( t->Tag() != TYPE_RECORD ) { reporter->Error("non-record value/type passed to record_fields"); - return make_intrusive(record_field_table); + return make_intrusive(record_field_table); } rt = t->AsRecordType(); @@ -501,31 +503,31 @@ static void BuildJSON(threading::formatter::JSON::NullDoubleWriter& writer, Val* switch ( val->GetType()->Tag() ) { - case zeek::TYPE_BOOL: + case TYPE_BOOL: writer.Bool(val->AsBool()); break; - case zeek::TYPE_INT: + case TYPE_INT: writer.Int64(val->AsInt()); break; - case zeek::TYPE_COUNT: + case TYPE_COUNT: writer.Uint64(val->AsCount()); break; - case zeek::TYPE_COUNTER: + case TYPE_COUNTER: writer.Uint64(val->AsCounter()); break; - case zeek::TYPE_TIME: + case TYPE_TIME: writer.Double(val->AsTime()); break; - case zeek::TYPE_DOUBLE: + case TYPE_DOUBLE: writer.Double(val->AsDouble()); break; - case zeek::TYPE_PORT: + case TYPE_PORT: { auto* pval = val->AsPortVal(); writer.StartObject(); @@ -537,10 +539,10 @@ static void BuildJSON(threading::formatter::JSON::NullDoubleWriter& writer, Val* break; } - case zeek::TYPE_PATTERN: - case zeek::TYPE_INTERVAL: - case zeek::TYPE_ADDR: - case zeek::TYPE_SUBNET: + case TYPE_PATTERN: + case TYPE_INTERVAL: + case TYPE_ADDR: + case TYPE_SUBNET: { ODesc d; d.SetStyle(RAW_STYLE); @@ -549,10 +551,10 @@ static void BuildJSON(threading::formatter::JSON::NullDoubleWriter& writer, Val* break; } - case zeek::TYPE_FILE: - case zeek::TYPE_FUNC: - case zeek::TYPE_ENUM: - case zeek::TYPE_STRING: + case TYPE_FILE: + case TYPE_FUNC: + case TYPE_ENUM: + case TYPE_STRING: { ODesc d; d.SetStyle(RAW_STYLE); @@ -561,7 +563,7 @@ static void BuildJSON(threading::formatter::JSON::NullDoubleWriter& writer, Val* break; } - case zeek::TYPE_TABLE: + case TYPE_TABLE: { auto* table = val->AsTable(); auto* tval = val->AsTableVal(); @@ -607,7 +609,7 @@ static void BuildJSON(threading::formatter::JSON::NullDoubleWriter& writer, Val* break; } - case zeek::TYPE_RECORD: + case TYPE_RECORD: { writer.StartObject(); @@ -618,15 +620,15 @@ static void BuildJSON(threading::formatter::JSON::NullDoubleWriter& writer, Val* { auto value = rval->GetFieldOrDefault(i); - if ( value && ( ! only_loggable || rt->FieldHasAttr(i, zeek::detail::ATTR_LOG) ) ) + if ( value && ( ! only_loggable || rt->FieldHasAttr(i, detail::ATTR_LOG) ) ) { string key_str; auto field_name = rt->FieldName(i); if ( re && re->MatchAnywhere(field_name) != 0 ) { - auto blank = make_intrusive(""); - auto fn_val = make_intrusive(field_name); + auto blank = make_intrusive(""); + auto fn_val = make_intrusive(field_name); const auto& bs = *blank->AsString(); auto key_val = fn_val->Replace(re, bs, false); key_str = key_val->ToStdString(); @@ -642,7 +644,7 @@ static void BuildJSON(threading::formatter::JSON::NullDoubleWriter& writer, Val* break; } - case zeek::TYPE_LIST: + case TYPE_LIST: { writer.StartArray(); @@ -655,7 +657,7 @@ static void BuildJSON(threading::formatter::JSON::NullDoubleWriter& writer, Val* break; } - case zeek::TYPE_VECTOR: + case TYPE_VECTOR: { writer.StartArray(); @@ -668,7 +670,7 @@ static void BuildJSON(threading::formatter::JSON::NullDoubleWriter& writer, Val* break; } - case zeek::TYPE_OPAQUE: + case TYPE_OPAQUE: { writer.StartObject(); @@ -686,14 +688,14 @@ static void BuildJSON(threading::formatter::JSON::NullDoubleWriter& writer, Val* } } -IntrusivePtr Val::ToJSON(bool only_loggable, RE_Matcher* re) +StringValPtr Val::ToJSON(bool only_loggable, RE_Matcher* re) { rapidjson::StringBuffer buffer; threading::formatter::JSON::NullDoubleWriter writer(buffer); BuildJSON(writer, this, only_loggable, re, ""); - return make_intrusive(buffer.GetString()); + return make_intrusive(buffer.GetString()); } void IntervalVal::ValDescribe(ODesc* d) const @@ -769,9 +771,9 @@ void IntervalVal::ValDescribe(ODesc* d) const } } -IntrusivePtr PortVal::SizeVal() const +ValPtr PortVal::SizeVal() const { - return val_mgr->Int(val.uint_val); + return zeek::val_mgr->Int(val.uint_val); } uint32_t PortVal::Mask(uint32_t port_num, TransportProto port_type) @@ -805,7 +807,7 @@ uint32_t PortVal::Mask(uint32_t port_num, TransportProto port_type) return port_num; } -PortVal::PortVal(uint32_t p) : Val(bro_uint_t(p), zeek::TYPE_PORT) +PortVal::PortVal(uint32_t p) : Val(bro_uint_t(p), TYPE_PORT) { } @@ -850,13 +852,13 @@ void PortVal::ValDescribe(ODesc* d) const d->Add(Protocol()); } -IntrusivePtr PortVal::DoClone(CloneState* state) +ValPtr PortVal::DoClone(CloneState* state) { // Immutable. return {NewRef{}, this}; } -AddrVal::AddrVal(const char* text) : Val(new IPAddr(text), zeek::TYPE_ADDR) +AddrVal::AddrVal(const char* text) : Val(new IPAddr(text), TYPE_ADDR) { } @@ -864,16 +866,16 @@ AddrVal::AddrVal(const std::string& text) : AddrVal(text.c_str()) { } -AddrVal::AddrVal(uint32_t addr) : Val(new IPAddr(IPv4, &addr, IPAddr::Network), zeek::TYPE_ADDR) +AddrVal::AddrVal(uint32_t addr) : Val(new IPAddr(IPv4, &addr, IPAddr::Network), TYPE_ADDR) { // ### perhaps do gethostbyaddr here? } -AddrVal::AddrVal(const uint32_t addr[4]) : Val(new IPAddr(IPv6, addr, IPAddr::Network), zeek::TYPE_ADDR) +AddrVal::AddrVal(const uint32_t addr[4]) : Val(new IPAddr(IPv6, addr, IPAddr::Network), TYPE_ADDR) { } -AddrVal::AddrVal(const IPAddr& addr) : Val(new IPAddr(addr), zeek::TYPE_ADDR) +AddrVal::AddrVal(const IPAddr& addr) : Val(new IPAddr(addr), TYPE_ADDR) { } @@ -887,27 +889,27 @@ unsigned int AddrVal::MemoryAllocation() const return padded_sizeof(*this) + val.addr_val->MemoryAllocation(); } -IntrusivePtr AddrVal::SizeVal() const +ValPtr AddrVal::SizeVal() const { if ( val.addr_val->GetFamily() == IPv4 ) - return val_mgr->Count(32); + return zeek::val_mgr->Count(32); else - return val_mgr->Count(128); + return zeek::val_mgr->Count(128); } -IntrusivePtr AddrVal::DoClone(CloneState* state) +ValPtr AddrVal::DoClone(CloneState* state) { // Immutable. return {NewRef{}, this}; } -SubNetVal::SubNetVal(const char* text) : Val(new IPPrefix(), zeek::TYPE_SUBNET) +SubNetVal::SubNetVal(const char* text) : Val(new IPPrefix(), TYPE_SUBNET) { if ( ! IPPrefix::ConvertString(text, val.subnet_val) ) reporter->Error("Bad string in SubNetVal ctor: %s", text); } -SubNetVal::SubNetVal(const char* text, int width) : Val(new IPPrefix(text, width), zeek::TYPE_SUBNET) +SubNetVal::SubNetVal(const char* text, int width) : Val(new IPPrefix(text, width), TYPE_SUBNET) { } @@ -919,11 +921,11 @@ SubNetVal::SubNetVal(const uint32_t* addr, int width) : SubNetVal(IPAddr{IPv6, a { } -SubNetVal::SubNetVal(const IPAddr& addr, int width) : Val(new IPPrefix(addr, width), zeek::TYPE_SUBNET) +SubNetVal::SubNetVal(const IPAddr& addr, int width) : Val(new IPPrefix(addr, width), TYPE_SUBNET) { } -SubNetVal::SubNetVal(const IPPrefix& prefix) : Val(new IPPrefix(prefix), zeek::TYPE_SUBNET) +SubNetVal::SubNetVal(const IPPrefix& prefix) : Val(new IPPrefix(prefix), TYPE_SUBNET) { } @@ -947,10 +949,10 @@ unsigned int SubNetVal::MemoryAllocation() const return padded_sizeof(*this) + val.subnet_val->MemoryAllocation(); } -IntrusivePtr SubNetVal::SizeVal() const +ValPtr SubNetVal::SizeVal() const { int retained = 128 - val.subnet_val->LengthIPv6(); - return make_intrusive(pow(2.0, double(retained))); + return make_intrusive(pow(2.0, double(retained))); } void SubNetVal::ValDescribe(ODesc* d) const @@ -992,23 +994,23 @@ bool SubNetVal::Contains(const IPAddr& addr) const return val.subnet_val->Contains(addr); } -IntrusivePtr SubNetVal::DoClone(CloneState* state) +ValPtr SubNetVal::DoClone(CloneState* state) { // Immutable. return {NewRef{}, this}; } -StringVal::StringVal(BroString* s) : Val(s, zeek::TYPE_STRING) +StringVal::StringVal(String* s) : Val(s, TYPE_STRING) { } // The following adds a NUL at the end. StringVal::StringVal(int length, const char* s) - : StringVal(new BroString(reinterpret_cast(s), length, true)) + : StringVal(new String(reinterpret_cast(s), length, true)) { } -StringVal::StringVal(const char* s) : StringVal(new BroString(s)) +StringVal::StringVal(const char* s) : StringVal(new String(s)) { } @@ -1016,9 +1018,9 @@ StringVal::StringVal(const string& s) : StringVal(s.length(), s.data()) { } -IntrusivePtr StringVal::SizeVal() const +ValPtr StringVal::SizeVal() const { - return val_mgr->Count(val.string_val->Len()); + return zeek::val_mgr->Count(val.string_val->Len()); } int StringVal::Len() @@ -1063,8 +1065,8 @@ unsigned int StringVal::MemoryAllocation() const return padded_sizeof(*this) + val.string_val->MemoryAllocation(); } -IntrusivePtr StringVal::Replace(RE_Matcher* re, - const BroString& repl, bool do_all) +StringValPtr StringVal::Replace( + RE_Matcher* re, const String& repl, bool do_all) { const u_char* s = Bytes(); int offset = 0; @@ -1145,21 +1147,21 @@ IntrusivePtr StringVal::Replace(RE_Matcher* re, // the NUL. r[0] = '\0'; - return make_intrusive(new BroString(true, result, r - result)); + return make_intrusive(new String(true, result, r - result)); } -IntrusivePtr StringVal::DoClone(CloneState* state) +ValPtr StringVal::DoClone(CloneState* state) { // We could likely treat this type as immutable and return a reference // instead of creating a new copy, but we first need to be careful and // audit whether anything internal actually does mutate it. - return state->NewClone(this, make_intrusive( - new BroString((u_char*) val.string_val->Bytes(), - val.string_val->Len(), true))); + return state->NewClone(this, make_intrusive( + new String((u_char*) val.string_val->Bytes(), + val.string_val->Len(), true))); } PatternVal::PatternVal(RE_Matcher* re) - : Val(zeek::base_type(zeek::TYPE_PATTERN)) + : Val(base_type(TYPE_PATTERN)) { val.re_val = re; } @@ -1171,7 +1173,7 @@ PatternVal::~PatternVal() bool PatternVal::AddTo(Val* v, bool /* is_first_init */) const { - if ( v->GetType()->Tag() != zeek::TYPE_PATTERN ) + if ( v->GetType()->Tag() != TYPE_PATTERN ) { v->Error("not a pattern"); return false; @@ -1206,7 +1208,7 @@ unsigned int PatternVal::MemoryAllocation() const return padded_sizeof(*this) + val.re_val->MemoryAllocation(); } -IntrusivePtr PatternVal::DoClone(CloneState* state) +ValPtr PatternVal::DoClone(CloneState* state) { // We could likely treat this type as immutable and return a reference // instead of creating a new copy, but we first need to be careful and @@ -1214,11 +1216,11 @@ IntrusivePtr PatternVal::DoClone(CloneState* state) auto re = new RE_Matcher(val.re_val->PatternText(), val.re_val->AnywherePatternText()); re->Compile(); - return state->NewClone(this, make_intrusive(re)); + return state->NewClone(this, make_intrusive(re)); } -ListVal::ListVal(zeek::TypeTag t) - : Val(make_intrusive(t == zeek::TYPE_ANY ? nullptr : zeek::base_type(t))) +ListVal::ListVal(TypeTag t) + : Val(make_intrusive(t == TYPE_ANY ? nullptr : base_type(t))) { tag = t; } @@ -1227,14 +1229,14 @@ ListVal::~ListVal() { } -IntrusivePtr ListVal::SizeVal() const +ValPtr ListVal::SizeVal() const { - return val_mgr->Count(vals.size()); + return zeek::val_mgr->Count(vals.size()); } RE_Matcher* ListVal::BuildRE() const { - if ( tag != zeek::TYPE_STRING ) + if ( tag != TYPE_STRING ) Internal("non-string list in ListVal::IncludedInString"); RE_Matcher* re = new RE_Matcher(); @@ -1247,7 +1249,7 @@ RE_Matcher* ListVal::BuildRE() const return re; } -void ListVal::Append(IntrusivePtr v) +void ListVal::Append(ValPtr v) { if ( type->AsTypeList()->IsPure() ) { @@ -1265,16 +1267,16 @@ void ListVal::Append(Val* v) Append({AdoptRef{}, v}); } -IntrusivePtr ListVal::ToSetVal() const +TableValPtr ListVal::ToSetVal() const { - if ( tag == zeek::TYPE_ANY ) + if ( tag == TYPE_ANY ) Internal("conversion of heterogeneous list to set"); const auto& pt = type->AsTypeList()->GetPureType(); - auto set_index = make_intrusive(pt); - set_index->Append(zeek::base_type(tag)); - auto s = make_intrusive(std::move(set_index), nullptr); - auto t = make_intrusive(std::move(s)); + auto set_index = make_intrusive(pt); + set_index->Append(base_type(tag)); + auto s = make_intrusive(std::move(set_index), nullptr); + auto t = make_intrusive(std::move(s)); for ( const auto& val : vals ) t->Assign(val, nullptr); @@ -1312,9 +1314,9 @@ void ListVal::Describe(ODesc* d) const } } -IntrusivePtr ListVal::DoClone(CloneState* state) +ValPtr ListVal::DoClone(CloneState* state) { - auto lv = make_intrusive(tag); + auto lv = make_intrusive(tag); lv->vals.reserve(vals.size()); state->NewClone(this, lv); @@ -1366,13 +1368,13 @@ static void table_entry_val_delete_func(void* val) delete tv; } -static void find_nested_record_types(const IntrusivePtr& t, std::set* found) +static void find_nested_record_types(const TypePtr& t, std::set* found) { if ( ! t ) return; switch ( t->Tag() ) { - case zeek::TYPE_RECORD: + case TYPE_RECORD: { auto rt = t->AsRecordType(); found->emplace(rt); @@ -1381,24 +1383,24 @@ static void find_nested_record_types(const IntrusivePtr& t, std::set find_nested_record_types(rt->FieldDecl(i)->type, found); } return; - case zeek::TYPE_TABLE: + case TYPE_TABLE: find_nested_record_types(t->AsTableType()->GetIndices(), found); find_nested_record_types(t->AsTableType()->Yield(), found); return; - case zeek::TYPE_LIST: + case TYPE_LIST: { for ( const auto& type : t->AsTypeList()->GetTypes() ) find_nested_record_types(type, found); } return; - case zeek::TYPE_FUNC: + case TYPE_FUNC: find_nested_record_types(t->AsFuncType()->Params(), found); find_nested_record_types(t->AsFuncType()->Yield(), found); return; - case zeek::TYPE_VECTOR: + case TYPE_VECTOR: find_nested_record_types(t->AsVectorType()->Yield(), found); return; - case zeek::TYPE_TYPE: + case TYPE_TYPE: find_nested_record_types(t->AsTypeType()->GetType(), found); return; default: @@ -1406,7 +1408,7 @@ static void find_nested_record_types(const IntrusivePtr& t, std::set } } -TableVal::TableVal(IntrusivePtr t, IntrusivePtr a) : Val(t) +TableVal::TableVal(TableTypePtr t, detail::AttributesPtr a) : Val(t) { Init(std::move(t)); SetAttrs(std::move(a)); @@ -1416,7 +1418,7 @@ TableVal::TableVal(IntrusivePtr t, IntrusivePtrGetIndexTypes() ) { - std::set found; + std::set found; // TODO: this likely doesn't have to be repeated for each new TableVal, // can remember the resulting dependencies per TableType find_nested_record_types(t, &found); @@ -1426,7 +1428,7 @@ TableVal::TableVal(IntrusivePtr t, IntrusivePtr t) +void TableVal::Init(TableTypePtr t) { table_type = std::move(t); expire_func = nullptr; @@ -1441,7 +1443,7 @@ void TableVal::Init(IntrusivePtr t) subnets = nullptr; table_hash = new CompositeHash(table_type->GetIndices()); - val.table_val = new PDict; + val.table_val = new PDict; val.table_val->SetDeleteFunc(table_entry_val_delete_func); } @@ -1459,7 +1461,7 @@ void TableVal::RemoveAll() { // Here we take the brute force approach. delete AsTable(); - val.table_val = new PDict; + val.table_val = new PDict; val.table_val->SetDeleteFunc(table_entry_val_delete_func); } @@ -1473,10 +1475,10 @@ int TableVal::RecursiveSize() const int n = AsTable()->Length(); if ( GetType()->IsSet() || - GetType()->AsTableType()->Yield()->Tag() != zeek::TYPE_TABLE ) + GetType()->AsTableType()->Yield()->Tag() != TYPE_TABLE ) return n; - PDict* v = val.table_val; + PDict* v = val.table_val; IterCookie* c = v->InitForIteration(); TableEntryVal* tv; @@ -1489,29 +1491,29 @@ int TableVal::RecursiveSize() const return n; } -void TableVal::SetAttrs(IntrusivePtr a) +void TableVal::SetAttrs(detail::AttributesPtr a) { attrs = std::move(a); if ( ! attrs ) return; - CheckExpireAttr(zeek::detail::ATTR_EXPIRE_READ); - CheckExpireAttr(zeek::detail::ATTR_EXPIRE_WRITE); - CheckExpireAttr(zeek::detail::ATTR_EXPIRE_CREATE); + CheckExpireAttr(detail::ATTR_EXPIRE_READ); + CheckExpireAttr(detail::ATTR_EXPIRE_WRITE); + CheckExpireAttr(detail::ATTR_EXPIRE_CREATE); - const auto& ef = attrs->Find(zeek::detail::ATTR_EXPIRE_FUNC); + const auto& ef = attrs->Find(detail::ATTR_EXPIRE_FUNC); if ( ef ) expire_func = ef->GetExpr(); - const auto& cf = attrs->Find(zeek::detail::ATTR_ON_CHANGE); + const auto& cf = attrs->Find(detail::ATTR_ON_CHANGE); if ( cf ) change_func = cf->GetExpr(); } -void TableVal::CheckExpireAttr(zeek::detail::AttrTag at) +void TableVal::CheckExpireAttr(detail::AttrTag at) { const auto& a = attrs->Find(at); @@ -1519,7 +1521,7 @@ void TableVal::CheckExpireAttr(zeek::detail::AttrTag at) { expire_time = a->GetExpr(); - if ( expire_time->GetType()->Tag() != zeek::TYPE_INTERVAL ) + if ( expire_time->GetType()->Tag() != TYPE_INTERVAL ) { if ( ! expire_time->IsError() ) expire_time->SetError("expiration interval has wrong type"); @@ -1537,7 +1539,7 @@ void TableVal::CheckExpireAttr(zeek::detail::AttrTag at) } } -bool TableVal::Assign(IntrusivePtr index, IntrusivePtr new_val) +bool TableVal::Assign(ValPtr index, ValPtr new_val) { auto k = MakeHashKey(*index); @@ -1555,8 +1557,8 @@ bool TableVal::Assign(Val* index, Val* new_val) return Assign({NewRef{}, index}, {AdoptRef{}, new_val}); } -bool TableVal::Assign(IntrusivePtr index, std::unique_ptr k, - IntrusivePtr new_val) +bool TableVal::Assign(ValPtr index, std::unique_ptr k, + ValPtr new_val) { bool is_set = table_type->IsSet(); @@ -1584,7 +1586,7 @@ bool TableVal::Assign(IntrusivePtr index, std::unique_ptr k, } // Keep old expiration time if necessary. - if ( old_entry_val && attrs && attrs->Find(zeek::detail::ATTR_EXPIRE_CREATE) ) + if ( old_entry_val && attrs && attrs->Find(detail::ATTR_EXPIRE_CREATE) ) new_entry_val->SetExpireAccess(old_entry_val->ExpireAccessTime()); Modified(); @@ -1606,9 +1608,9 @@ bool TableVal::Assign(Val* index, HashKey* k, Val* new_val) return Assign({NewRef{}, index}, std::unique_ptr{k}, {AdoptRef{}, new_val}); } -IntrusivePtr TableVal::SizeVal() const +ValPtr TableVal::SizeVal() const { - return val_mgr->Count(Size()); + return zeek::val_mgr->Count(Size()); } bool TableVal::AddTo(Val* val, bool is_first_init) const @@ -1618,7 +1620,7 @@ bool TableVal::AddTo(Val* val, bool is_first_init) const bool TableVal::AddTo(Val* val, bool is_first_init, bool propagate_ops) const { - if ( val->GetType()->Tag() != zeek::TYPE_TABLE ) + if ( val->GetType()->Tag() != TYPE_TABLE ) { val->Error("not a table"); return false; @@ -1632,7 +1634,7 @@ bool TableVal::AddTo(Val* val, bool is_first_init, bool propagate_ops) const return false; } - const PDict* tbl = AsTable(); + const PDict* tbl = AsTable(); IterCookie* c = tbl->InitForIteration(); HashKey* k; @@ -1666,7 +1668,7 @@ bool TableVal::AddTo(Val* val, bool is_first_init, bool propagate_ops) const bool TableVal::RemoveFrom(Val* val) const { - if ( val->GetType()->Tag() != zeek::TYPE_TABLE ) + if ( val->GetType()->Tag() != TYPE_TABLE ) { val->Error("not a table"); return false; @@ -1680,7 +1682,7 @@ bool TableVal::RemoveFrom(Val* val) const return false; } - const PDict* tbl = AsTable(); + const PDict* tbl = AsTable(); IterCookie* c = tbl->InitForIteration(); HashKey* k; @@ -1698,18 +1700,18 @@ bool TableVal::RemoveFrom(Val* val) const return true; } -IntrusivePtr TableVal::Intersection(const TableVal& tv) const +TableValPtr TableVal::Intersection(const TableVal& tv) const { - auto result = make_intrusive(table_type); + auto result = make_intrusive(table_type); - const PDict* t0 = AsTable(); - const PDict* t1 = tv.AsTable(); - PDict* t2 = result->AsNonConstTable(); + const PDict* t0 = AsTable(); + const PDict* t1 = tv.AsTable(); + PDict* t2 = result->AsNonConstTable(); // Figure out which is smaller; assign it to t1. if ( t1->Length() > t0->Length() ) { // Swap. - const PDict* tmp = t1; + const PDict* tmp = t1; t1 = t0; t0 = tmp; } @@ -1731,8 +1733,8 @@ IntrusivePtr TableVal::Intersection(const TableVal& tv) const bool TableVal::EqualTo(const TableVal& tv) const { - const PDict* t0 = AsTable(); - const PDict* t1 = tv.AsTable(); + const PDict* t0 = AsTable(); + const PDict* t1 = tv.AsTable(); if ( t0->Length() != t1->Length() ) return false; @@ -1758,8 +1760,8 @@ bool TableVal::EqualTo(const TableVal& tv) const bool TableVal::IsSubsetOf(const TableVal& tv) const { - const PDict* t0 = AsTable(); - const PDict* t1 = tv.AsTable(); + const PDict* t0 = AsTable(); + const PDict* t1 = tv.AsTable(); if ( t0->Length() > t1->Length() ) return false; @@ -1783,7 +1785,7 @@ bool TableVal::IsSubsetOf(const TableVal& tv) const return true; } -bool TableVal::ExpandAndInit(IntrusivePtr index, IntrusivePtr new_val) +bool TableVal::ExpandAndInit(ValPtr index, ValPtr new_val) { const auto& index_type = index->GetType(); @@ -1793,12 +1795,12 @@ bool TableVal::ExpandAndInit(IntrusivePtr index, IntrusivePtr new_val) return ExpandAndInit(std::move(index), std::move(new_val)); } - if ( index_type->Tag() != zeek::TYPE_LIST ) + if ( index_type->Tag() != TYPE_LIST ) // Nothing to expand. return CheckAndAssign(std::move(index), std::move(new_val)); ListVal* iv = index->AsListVal(); - if ( iv->BaseTag() != zeek::TYPE_ANY ) + if ( iv->BaseTag() != TYPE_ANY ) { if ( table_type->GetIndices()->GetTypes().size() != 1 ) reporter->InternalError("bad singleton list index"); @@ -1822,7 +1824,7 @@ bool TableVal::ExpandAndInit(IntrusivePtr index, IntrusivePtr new_val) // then we could optimize here. const auto& t = v->GetType(); - if ( t->IsSet() || t->Tag() == zeek::TYPE_LIST ) + if ( t->IsSet() || t->Tag() == TYPE_LIST ) break; } @@ -1835,9 +1837,9 @@ bool TableVal::ExpandAndInit(IntrusivePtr index, IntrusivePtr new_val) } -IntrusivePtr TableVal::Default(const IntrusivePtr& index) +ValPtr TableVal::Default(const ValPtr& index) { - const auto& def_attr = GetAttr(zeek::detail::ATTR_DEFAULT); + const auto& def_attr = GetAttr(detail::ATTR_DEFAULT); if ( ! def_attr ) return nullptr; @@ -1847,13 +1849,13 @@ IntrusivePtr TableVal::Default(const IntrusivePtr& index) const auto& ytype = GetType()->Yield(); const auto& dtype = def_attr->GetExpr()->GetType(); - if ( dtype->Tag() == zeek::TYPE_RECORD && ytype->Tag() == zeek::TYPE_RECORD && + if ( dtype->Tag() == TYPE_RECORD && ytype->Tag() == TYPE_RECORD && ! same_type(dtype, ytype) && record_promotion_compatible(dtype->AsRecordType(), ytype->AsRecordType()) ) { - auto rt = cast_intrusive(ytype); - auto coerce = make_intrusive( + auto rt = cast_intrusive(ytype); + auto coerce = make_intrusive( def_attr->GetExpr(), std::move(rt)); def_val = coerce->Eval(nullptr); @@ -1869,7 +1871,7 @@ IntrusivePtr TableVal::Default(const IntrusivePtr& index) return nullptr; } - if ( def_val->GetType()->Tag() != zeek::TYPE_FUNC || + if ( def_val->GetType()->Tag() != TYPE_FUNC || same_type(def_val->GetType(), GetType()->Yield()) ) { if ( def_attr->GetExpr()->IsConst() ) @@ -1886,10 +1888,10 @@ IntrusivePtr TableVal::Default(const IntrusivePtr& index) return nullptr; } - const Func* f = def_val->AsFunc(); - zeek::Args vl; + const zeek::Func* f = def_val->AsFunc(); + Args vl; - if ( index->GetType()->Tag() == zeek::TYPE_LIST ) + if ( index->GetType()->Tag() == TYPE_LIST ) { auto lv = index->AsListVal(); vl.reserve(lv->Length()); @@ -1900,7 +1902,7 @@ IntrusivePtr TableVal::Default(const IntrusivePtr& index) else vl.emplace_back(index); - IntrusivePtr result; + ValPtr result; try { @@ -1919,26 +1921,26 @@ IntrusivePtr TableVal::Default(const IntrusivePtr& index) return result; } -const IntrusivePtr& TableVal::Find(const IntrusivePtr& index) +const ValPtr& TableVal::Find(const ValPtr& index) { if ( subnets ) { TableEntryVal* v = (TableEntryVal*) subnets->Lookup(index.get()); if ( v ) { - if ( attrs && attrs->Find(zeek::detail::ATTR_EXPIRE_READ) ) + if ( attrs && attrs->Find(detail::ATTR_EXPIRE_READ) ) v->SetExpireAccess(network_time); if ( v->GetVal() ) return v->GetVal(); - return val_mgr->True(); + return zeek::val_mgr->True(); } return Val::nil; } - const PDict* tbl = AsTable(); + const PDict* tbl = AsTable(); if ( tbl->Length() > 0 ) { @@ -1950,13 +1952,13 @@ const IntrusivePtr& TableVal::Find(const IntrusivePtr& index) if ( v ) { - if ( attrs && attrs->Find(zeek::detail::ATTR_EXPIRE_READ) ) + if ( attrs && attrs->Find(detail::ATTR_EXPIRE_READ) ) v->SetExpireAccess(network_time); if ( v->GetVal() ) return v->GetVal(); - return val_mgr->True(); + return zeek::val_mgr->True(); } } } @@ -1964,7 +1966,7 @@ const IntrusivePtr& TableVal::Find(const IntrusivePtr& index) return Val::nil; } -IntrusivePtr TableVal::FindOrDefault(const IntrusivePtr& index) +ValPtr TableVal::FindOrDefault(const ValPtr& index) { if ( auto rval = Find(index) ) return rval; @@ -1974,9 +1976,9 @@ IntrusivePtr TableVal::FindOrDefault(const IntrusivePtr& index) Val* TableVal::Lookup(Val* index, bool use_default_val) { - static IntrusivePtr last_default; + static ValPtr last_default; last_default = nullptr; - IntrusivePtr idx{NewRef{}, index}; + ValPtr idx{NewRef{}, index}; if ( const auto& rval = Find(idx) ) return rval.get(); @@ -1988,31 +1990,31 @@ Val* TableVal::Lookup(Val* index, bool use_default_val) return last_default.get(); } -IntrusivePtr TableVal::LookupSubnets(const SubNetVal* search) +VectorValPtr TableVal::LookupSubnets(const SubNetVal* search) { if ( ! subnets ) reporter->InternalError("LookupSubnets called on wrong table type"); - auto result = make_intrusive(zeek::id::find_type("subnet_vec")); + auto result = make_intrusive(id::find_type("subnet_vec")); auto matches = subnets->FindAll(search); for ( auto element : matches ) - result->Assign(result->Size(), make_intrusive(get<0>(element))); + result->Assign(result->Size(), make_intrusive(get<0>(element))); return result; } -IntrusivePtr TableVal::LookupSubnetValues(const SubNetVal* search) +TableValPtr TableVal::LookupSubnetValues(const SubNetVal* search) { if ( ! subnets ) reporter->InternalError("LookupSubnetValues called on wrong table type"); - auto nt = make_intrusive(this->GetType()); + auto nt = make_intrusive(this->GetType()); auto matches = subnets->FindAll(search); for ( auto element : matches ) { - auto s = make_intrusive(get<0>(element)); + auto s = make_intrusive(get<0>(element)); TableEntryVal* entry = reinterpret_cast(get<1>(element)); if ( entry && entry->GetVal() ) @@ -2022,7 +2024,7 @@ IntrusivePtr TableVal::LookupSubnetValues(const SubNetVal* search) if ( entry ) { - if ( attrs && attrs->Find(zeek::detail::ATTR_EXPIRE_READ) ) + if ( attrs && attrs->Find(detail::ATTR_EXPIRE_READ) ) entry->SetExpireAccess(network_time); } } @@ -2054,13 +2056,13 @@ bool TableVal::UpdateTimestamp(Val* index) return true; } -IntrusivePtr TableVal::RecreateIndex(const HashKey& k) const +ListValPtr TableVal::RecreateIndex(const HashKey& k) const { return table_hash->RecoverVals(k); } void TableVal::CallChangeFunc(const Val* index, - const IntrusivePtr& old_value, + const ValPtr& old_value, OnChangeType tpe) { if ( ! change_func || ! index || in_change_func ) @@ -2078,32 +2080,32 @@ void TableVal::CallChangeFunc(const Val* index, return; } - if ( thefunc->GetType()->Tag() != zeek::TYPE_FUNC ) + if ( thefunc->GetType()->Tag() != TYPE_FUNC ) { thefunc->Error("not a function"); return; } - const Func* f = thefunc->AsFunc(); + const zeek::Func* f = thefunc->AsFunc(); auto lv = index->AsListVal(); - zeek::Args vl; + Args vl; vl.reserve(2 + lv->Length() + table_type->IsTable()); vl.emplace_back(NewRef{}, this); switch ( tpe ) { case ELEMENT_NEW: - vl.emplace_back(zeek::BifType::Enum::TableChange->GetVal(BifEnum::TableChange::TABLE_ELEMENT_NEW)); + vl.emplace_back(BifType::Enum::TableChange->GetVal(BifEnum::TableChange::TABLE_ELEMENT_NEW)); break; case ELEMENT_CHANGED: - vl.emplace_back(zeek::BifType::Enum::TableChange->GetVal(BifEnum::TableChange::TABLE_ELEMENT_CHANGED)); + vl.emplace_back(BifType::Enum::TableChange->GetVal(BifEnum::TableChange::TABLE_ELEMENT_CHANGED)); break; case ELEMENT_REMOVED: - vl.emplace_back(zeek::BifType::Enum::TableChange->GetVal(BifEnum::TableChange::TABLE_ELEMENT_REMOVED)); + vl.emplace_back(BifType::Enum::TableChange->GetVal(BifEnum::TableChange::TABLE_ELEMENT_REMOVED)); break; case ELEMENT_EXPIRED: - vl.emplace_back(zeek::BifType::Enum::TableChange->GetVal(BifEnum::TableChange::TABLE_ELEMENT_EXPIRED)); + vl.emplace_back(BifType::Enum::TableChange->GetVal(BifEnum::TableChange::TABLE_ELEMENT_EXPIRED)); } for ( const auto& v : lv->Vals() ) @@ -2122,11 +2124,11 @@ void TableVal::CallChangeFunc(const Val* index, in_change_func = false; } -IntrusivePtr TableVal::Remove(const Val& index) +ValPtr TableVal::Remove(const Val& index) { auto k = MakeHashKey(index); TableEntryVal* v = k ? AsNonConstTable()->RemoveEntry(k.get()) : nullptr; - IntrusivePtr va; + ValPtr va; if ( v ) va = v->GetVal() ? v->GetVal() : IntrusivePtr{NewRef{}, this}; @@ -2144,10 +2146,10 @@ IntrusivePtr TableVal::Remove(const Val& index) return va; } -IntrusivePtr TableVal::Remove(const HashKey& k) +ValPtr TableVal::Remove(const HashKey& k) { TableEntryVal* v = AsNonConstTable()->RemoveEntry(k); - IntrusivePtr va; + ValPtr va; if ( v ) va = v->GetVal() ? v->GetVal() : IntrusivePtr{NewRef{}, this}; @@ -2173,11 +2175,11 @@ IntrusivePtr TableVal::Remove(const HashKey& k) return va; } -IntrusivePtr TableVal::ToListVal(zeek::TypeTag t) const +ListValPtr TableVal::ToListVal(TypeTag t) const { - auto l = make_intrusive(t); + auto l = make_intrusive(t); - const PDict* tbl = AsTable(); + const PDict* tbl = AsTable(); IterCookie* c = tbl->InitForIteration(); HashKey* k; @@ -2185,7 +2187,7 @@ IntrusivePtr TableVal::ToListVal(zeek::TypeTag t) const { auto index = table_hash->RecoverVals(*k); - if ( t == zeek::TYPE_ANY ) + if ( t == TYPE_ANY ) l->Append(std::move(index)); else { @@ -2202,12 +2204,12 @@ IntrusivePtr TableVal::ToListVal(zeek::TypeTag t) const return l; } -ListVal* TableVal::ConvertToList(zeek::TypeTag t) const +ListVal* TableVal::ConvertToList(TypeTag t) const { return ToListVal().release(); } -IntrusivePtr TableVal::ToPureListVal() const +ListValPtr TableVal::ToPureListVal() const { const auto& tl = table_type->GetIndices()->GetTypes(); if ( tl.size() != 1 ) @@ -2224,14 +2226,14 @@ ListVal* TableVal::ConvertToPureList() const return ToPureListVal().release(); } -const IntrusivePtr& TableVal::GetAttr(zeek::detail::AttrTag t) const +const detail::AttrPtr& TableVal::GetAttr(detail::AttrTag t) const { - return attrs ? attrs->Find(t) : zeek::detail::Attr::nil; + return attrs ? attrs->Find(t) : detail::Attr::nil; } void TableVal::Describe(ODesc* d) const { - const PDict* tbl = AsTable(); + const PDict* tbl = AsTable(); int n = tbl->Length(); if ( d->IsBinary() || d->IsPortable() ) @@ -2315,17 +2317,17 @@ void TableVal::Describe(ODesc* d) const } } -bool TableVal::ExpandCompoundAndInit(ListVal* lv, int k, IntrusivePtr new_val) +bool TableVal::ExpandCompoundAndInit(ListVal* lv, int k, ValPtr new_val) { Val* ind_k_v = lv->Idx(k).get(); auto ind_k = ind_k_v->GetType()->IsSet() ? ind_k_v->AsTableVal()->ToListVal() : - IntrusivePtr{NewRef{}, ind_k_v->AsListVal()}; + ListValPtr{NewRef{}, ind_k_v->AsListVal()}; for ( int i = 0; i < ind_k->Length(); ++i ) { const auto& ind_k_i = ind_k->Idx(i); - auto expd = make_intrusive(zeek::TYPE_ANY); + auto expd = make_intrusive(TYPE_ANY); for ( auto j = 0; j < lv->Length(); ++j ) { @@ -2344,7 +2346,7 @@ bool TableVal::ExpandCompoundAndInit(ListVal* lv, int k, IntrusivePtr new_v return true; } -bool TableVal::CheckAndAssign(IntrusivePtr index, IntrusivePtr new_val) +bool TableVal::CheckAndAssign(ValPtr index, ValPtr new_val) { Val* v = nullptr; if ( subnets ) @@ -2359,13 +2361,13 @@ bool TableVal::CheckAndAssign(IntrusivePtr index, IntrusivePtr new_val return Assign(std::move(index), std::move(new_val)); } -void TableVal::InitDefaultFunc(Frame* f) +void TableVal::InitDefaultFunc(zeek::detail::Frame* f) { // Value aready initialized. if ( def_val ) return; - const auto& def_attr = GetAttr(zeek::detail::ATTR_DEFAULT); + const auto& def_attr = GetAttr(detail::ATTR_DEFAULT); if ( ! def_attr ) return; @@ -2373,7 +2375,7 @@ void TableVal::InitDefaultFunc(Frame* f) const auto& ytype = GetType()->Yield(); const auto& dtype = def_attr->GetExpr()->GetType(); - if ( dtype->Tag() == zeek::TYPE_RECORD && ytype->Tag() == zeek::TYPE_RECORD && + if ( dtype->Tag() == TYPE_RECORD && ytype->Tag() == TYPE_RECORD && ! same_type(dtype, ytype) && record_promotion_compatible(dtype->AsRecordType(), ytype->AsRecordType()) ) @@ -2393,7 +2395,7 @@ void TableVal::DoExpire(double t) if ( ! type ) return; // FIX ME ### - PDict* tbl = AsNonConstTable(); + PDict* tbl = AsNonConstTable(); double timeout = GetExpireTime(); @@ -2427,7 +2429,7 @@ void TableVal::DoExpire(double t) else if ( v->ExpireAccessTime() + timeout < t ) { - IntrusivePtr idx = nullptr; + ListValPtr idx = nullptr; if ( expire_func ) { @@ -2521,7 +2523,7 @@ double TableVal::GetExpireTime() return -1; } -double TableVal::CallExpireFunc(IntrusivePtr idx) +double TableVal::CallExpireFunc(ListValPtr idx) { if ( ! expire_func ) return 0; @@ -2536,18 +2538,18 @@ double TableVal::CallExpireFunc(IntrusivePtr idx) // Will have been reported already. return 0; - if ( vf->GetType()->Tag() != zeek::TYPE_FUNC ) + if ( vf->GetType()->Tag() != TYPE_FUNC ) { vf->Error("not a function"); return 0; } - const Func* f = vf->AsFunc(); - zeek::Args vl; + const zeek::Func* f = vf->AsFunc(); + Args vl; const auto& func_args = f->GetType()->ParamList()->GetTypes(); // backwards compatibility with idx: any idiom - bool any_idiom = func_args.size() == 2 && func_args.back()->Tag() == zeek::TYPE_ANY; + bool any_idiom = func_args.size() == 2 && func_args.back()->Tag() == TYPE_ANY; if ( ! any_idiom ) { @@ -2584,12 +2586,12 @@ double TableVal::CallExpireFunc(IntrusivePtr idx) return secs; } -IntrusivePtr TableVal::DoClone(CloneState* state) +ValPtr TableVal::DoClone(CloneState* state) { - auto tv = make_intrusive(table_type); + auto tv = make_intrusive(table_type); state->NewClone(this, tv); - const PDict* tbl = AsTable(); + const PDict* tbl = AsTable(); IterCookie* cookie = tbl->InitForIteration(); HashKey* key; @@ -2633,7 +2635,7 @@ unsigned int TableVal::MemoryAllocation() const { unsigned int size = 0; - PDict* v = val.table_val; + PDict* v = val.table_val; IterCookie* c = v->InitForIteration(); TableEntryVal* tv; @@ -2656,7 +2658,7 @@ std::unique_ptr TableVal::MakeHashKey(const Val& index) const return table_hash->MakeHashKey(index, true); } -void TableVal::SaveParseTimeTableState(zeek::RecordType* rt) +void TableVal::SaveParseTimeTableState(RecordType* rt) { auto it = parse_time_table_record_dependencies.find(rt); @@ -2684,7 +2686,7 @@ void TableVal::DoneParsing() TableVal::ParseTimeTableState TableVal::DumpTableState() { - const PDict* tbl = AsTable(); + const PDict* tbl = AsTable(); IterCookie* cookie = tbl->InitForIteration(); HashKey* key; @@ -2717,16 +2719,16 @@ TableVal::TableRecordDependencies TableVal::parse_time_table_record_dependencies RecordVal::RecordTypeValMap RecordVal::parse_time_records; -RecordVal::RecordVal(zeek::RecordType* t, bool init_fields) +RecordVal::RecordVal(RecordType* t, bool init_fields) : RecordVal({NewRef{}, t}, init_fields) {} -RecordVal::RecordVal(IntrusivePtr t, bool init_fields) : Val(std::move(t)) +RecordVal::RecordVal(RecordTypePtr t, bool init_fields) : Val(std::move(t)) { origin = nullptr; auto rt = GetType()->AsRecordType(); int n = rt->NumFields(); - auto vl = val.record_val = new std::vector>; + auto vl = val.record_val = new std::vector; vl->reserve(n); if ( is_parsing ) @@ -2739,34 +2741,34 @@ RecordVal::RecordVal(IntrusivePtr t, bool init_fields) : Val(s // by default). for ( int i = 0; i < n; ++i ) { - zeek::detail::Attributes* a = rt->FieldDecl(i)->attrs.get(); - zeek::detail::Attr* def_attr = a ? a->Find(zeek::detail::ATTR_DEFAULT).get() : nullptr; + detail::Attributes* a = rt->FieldDecl(i)->attrs.get(); + detail::Attr* def_attr = a ? a->Find(detail::ATTR_DEFAULT).get() : nullptr; auto def = def_attr ? def_attr->GetExpr()->Eval(nullptr) : nullptr; const auto& type = rt->FieldDecl(i)->type; - if ( def && type->Tag() == zeek::TYPE_RECORD && - def->GetType()->Tag() == zeek::TYPE_RECORD && + if ( def && type->Tag() == TYPE_RECORD && + def->GetType()->Tag() == TYPE_RECORD && ! same_type(def->GetType(), type) ) { - auto tmp = def->AsRecordVal()->CoerceTo(cast_intrusive(type)); + auto tmp = def->AsRecordVal()->CoerceTo(cast_intrusive(type)); if ( tmp ) def = std::move(tmp); } - if ( ! def && ! (a && a->Find(zeek::detail::ATTR_OPTIONAL)) ) + if ( ! def && ! (a && a->Find(detail::ATTR_OPTIONAL)) ) { - zeek::TypeTag tag = type->Tag(); + TypeTag tag = type->Tag(); - if ( tag == zeek::TYPE_RECORD ) - def = make_intrusive(cast_intrusive(type)); + if ( tag == TYPE_RECORD ) + def = make_intrusive(cast_intrusive(type)); - else if ( tag == zeek::TYPE_TABLE ) - def = make_intrusive(IntrusivePtr{NewRef{}, type->AsTableType()}, - IntrusivePtr{NewRef{}, a}); + else if ( tag == TYPE_TABLE ) + def = make_intrusive(IntrusivePtr{NewRef{}, type->AsTableType()}, + IntrusivePtr{NewRef{}, a}); - else if ( tag == zeek::TYPE_VECTOR ) - def = make_intrusive(cast_intrusive(type)); + else if ( tag == TYPE_VECTOR ) + def = make_intrusive(cast_intrusive(type)); } vl->emplace_back(std::move(def)); @@ -2778,12 +2780,12 @@ RecordVal::~RecordVal() delete AsNonConstRecord(); } -IntrusivePtr RecordVal::SizeVal() const +ValPtr RecordVal::SizeVal() const { - return val_mgr->Count(GetType()->AsRecordType()->NumFields()); + return zeek::val_mgr->Count(GetType()->AsRecordType()->NumFields()); } -void RecordVal::Assign(int field, IntrusivePtr new_val) +void RecordVal::Assign(int field, ValPtr new_val) { (*AsNonConstRecord())[field] = std::move(new_val); Modified(); @@ -2794,7 +2796,7 @@ void RecordVal::Assign(int field, Val* new_val) Assign(field, {AdoptRef{}, new_val}); } -IntrusivePtr RecordVal::GetFieldOrDefault(int field) const +ValPtr RecordVal::GetFieldOrDefault(int field) const { const auto& val = (*AsRecord())[field]; @@ -2804,7 +2806,7 @@ IntrusivePtr RecordVal::GetFieldOrDefault(int field) const return GetType()->AsRecordType()->FieldDefault(field); } -void RecordVal::ResizeParseTimeRecords(zeek::RecordType* rt) +void RecordVal::ResizeParseTimeRecords(RecordType* rt) { auto it = parse_time_records.find(rt); @@ -2834,7 +2836,7 @@ void RecordVal::DoneParsing() parse_time_records.clear(); } -const IntrusivePtr& RecordVal::GetField(const char* field) const +const ValPtr& RecordVal::GetField(const char* field) const { int idx = GetType()->AsRecordType()->FieldOffset(field); @@ -2844,7 +2846,7 @@ const IntrusivePtr& RecordVal::GetField(const char* field) const return GetField(idx); } -IntrusivePtr RecordVal::GetFieldOrDefault(const char* field) const +ValPtr RecordVal::GetFieldOrDefault(const char* field) const { int idx = GetType()->AsRecordType()->FieldOffset(field); @@ -2854,18 +2856,18 @@ IntrusivePtr RecordVal::GetFieldOrDefault(const char* field) const return GetFieldOrDefault(idx); } -IntrusivePtr RecordVal::CoerceTo(IntrusivePtr t, - IntrusivePtr aggr, - bool allow_orphaning) const +RecordValPtr RecordVal::CoerceTo(RecordTypePtr t, + RecordValPtr aggr, + bool allow_orphaning) const { if ( ! record_promotion_compatible(t.get(), GetType()->AsRecordType()) ) return nullptr; if ( ! aggr ) - aggr = make_intrusive(std::move(t)); + aggr = make_intrusive(std::move(t)); - zeek::RecordType* ar_t = aggr->GetType()->AsRecordType(); - const zeek::RecordType* rv_t = GetType()->AsRecordType(); + RecordType* ar_t = aggr->GetType()->AsRecordType(); + const RecordType* rv_t = GetType()->AsRecordType(); int i; for ( i = 0; i < rv_t->NumFields(); ++i ) @@ -2893,11 +2895,11 @@ IntrusivePtr RecordVal::CoerceTo(IntrusivePtr t, const auto& ft = ar_t->GetFieldType(t_i); - if ( ft->Tag() == zeek::TYPE_RECORD && ! same_type(ft, v->GetType()) ) + if ( ft->Tag() == TYPE_RECORD && ! same_type(ft, v->GetType()) ) { - auto rhs = make_intrusive(v); - auto e = make_intrusive(std::move(rhs), - cast_intrusive(ft)); + auto rhs = make_intrusive(v); + auto e = make_intrusive( + std::move(rhs), cast_intrusive(ft)); aggr->Assign(t_i, e->Eval(nullptr)); continue; } @@ -2907,7 +2909,7 @@ IntrusivePtr RecordVal::CoerceTo(IntrusivePtr t, for ( i = 0; i < ar_t->NumFields(); ++i ) if ( ! aggr->GetField(i) && - ! ar_t->FieldDecl(i)->GetAttr(zeek::detail::ATTR_OPTIONAL) ) + ! ar_t->FieldDecl(i)->GetAttr(detail::ATTR_OPTIONAL) ) { char buf[512]; snprintf(buf, sizeof(buf), @@ -2918,8 +2920,7 @@ IntrusivePtr RecordVal::CoerceTo(IntrusivePtr t, return aggr; } -IntrusivePtr RecordVal::CoerceTo(IntrusivePtr t, - bool allow_orphaning) +RecordValPtr RecordVal::CoerceTo(RecordTypePtr t, bool allow_orphaning) { if ( same_type(GetType(), t) ) return {NewRef{}, this}; @@ -2927,7 +2928,7 @@ IntrusivePtr RecordVal::CoerceTo(IntrusivePtr t, return CoerceTo(std::move(t), nullptr, allow_orphaning); } -IntrusivePtr RecordVal::GetRecordFieldsVal() const +TableValPtr RecordVal::GetRecordFieldsVal() const { return GetType()->AsRecordType()->GetRecordFieldsVal(this); } @@ -2999,14 +3000,14 @@ void RecordVal::DescribeReST(ODesc* d) const d->Add("}"); } -IntrusivePtr RecordVal::DoClone(CloneState* state) +ValPtr RecordVal::DoClone(CloneState* state) { // We set origin to 0 here. Origin only seems to be used for exactly one // purpose - to find the connection record that is associated with a // record. As we cannot guarantee that it will ber zeroed out at the // approproate time (as it seems to be guaranteed for the original record) // we don't touch it. - auto rv = make_intrusive(GetType(), false); + auto rv = make_intrusive(GetType(), false); rv->origin = nullptr; state->NewClone(this, rv); @@ -3030,14 +3031,14 @@ unsigned int RecordVal::MemoryAllocation() const size += v->MemoryAllocation(); } - size += pad_size(vl.capacity() * sizeof(IntrusivePtr)); + size += pad_size(vl.capacity() * sizeof(ValPtr)); size += padded_sizeof(vl); return size + padded_sizeof(*this); } -IntrusivePtr EnumVal::SizeVal() const +ValPtr EnumVal::SizeVal() const { - return val_mgr->Int(val.int_val); + return zeek::val_mgr->Int(val.int_val); } void EnumVal::ValDescribe(ODesc* d) const @@ -3050,18 +3051,18 @@ void EnumVal::ValDescribe(ODesc* d) const d->Add(ename); } -IntrusivePtr EnumVal::DoClone(CloneState* state) +ValPtr EnumVal::DoClone(CloneState* state) { // Immutable. return {NewRef{}, this}; } -VectorVal::VectorVal(zeek::VectorType* t) : VectorVal({NewRef{}, t}) +VectorVal::VectorVal(VectorType* t) : VectorVal({NewRef{}, t}) { } -VectorVal::VectorVal(IntrusivePtr t) : Val(std::move(t)) +VectorVal::VectorVal(VectorTypePtr t) : Val(std::move(t)) { - val.vector_val = new vector>(); + val.vector_val = new vector(); } VectorVal::~VectorVal() @@ -3069,12 +3070,12 @@ VectorVal::~VectorVal() delete val.vector_val; } -IntrusivePtr VectorVal::SizeVal() const +ValPtr VectorVal::SizeVal() const { - return val_mgr->Count(uint32_t(val.vector_val->size())); + return zeek::val_mgr->Count(uint32_t(val.vector_val->size())); } -bool VectorVal::Assign(unsigned int index, IntrusivePtr element) +bool VectorVal::Assign(unsigned int index, ValPtr element) { if ( element && ! same_type(element->GetType(), GetType()->AsVectorType()->Yield(), false) ) @@ -3090,7 +3091,7 @@ bool VectorVal::Assign(unsigned int index, IntrusivePtr element) } bool VectorVal::AssignRepeat(unsigned int index, unsigned int how_many, - IntrusivePtr element) + ValPtr element) { ResizeAtLeast(index + how_many); @@ -3101,7 +3102,7 @@ bool VectorVal::AssignRepeat(unsigned int index, unsigned int how_many, return true; } -bool VectorVal::Insert(unsigned int index, IntrusivePtr element) +bool VectorVal::Insert(unsigned int index, ValPtr element) { if ( element && ! same_type(element->GetType(), GetType()->AsVectorType()->Yield(), false) ) @@ -3109,7 +3110,7 @@ bool VectorVal::Insert(unsigned int index, IntrusivePtr element) return false; } - vector>::iterator it; + vector::iterator it; if ( index < val.vector_val->size() ) it = std::next(val.vector_val->begin(), index); @@ -3136,7 +3137,7 @@ bool VectorVal::Remove(unsigned int index) bool VectorVal::AddTo(Val* val, bool /* is_first_init */) const { - if ( val->GetType()->Tag() != zeek::TYPE_VECTOR ) + if ( val->GetType()->Tag() != TYPE_VECTOR ) { val->Error("not a vector"); return false; @@ -3158,7 +3159,7 @@ bool VectorVal::AddTo(Val* val, bool /* is_first_init */) const return true; } -const IntrusivePtr& VectorVal::At(unsigned int index) const +const ValPtr& VectorVal::At(unsigned int index) const { if ( index >= val.vector_val->size() ) return Val::nil; @@ -3183,9 +3184,9 @@ unsigned int VectorVal::ResizeAtLeast(unsigned int new_num_elements) return Resize(new_num_elements); } -IntrusivePtr VectorVal::DoClone(CloneState* state) +ValPtr VectorVal::DoClone(CloneState* state) { - auto vv = make_intrusive(GetType()); + auto vv = make_intrusive(GetType()); vv->val.vector_val->reserve(val.vector_val->size()); state->NewClone(this, vv); @@ -3217,26 +3218,27 @@ void VectorVal::ValDescribe(ODesc* d) const d->Add("]"); } -IntrusivePtr check_and_promote(IntrusivePtr v, const zeek::Type* t, - bool is_init, - const Location* expr_location) +ValPtr check_and_promote(ValPtr v, + const Type* t, + bool is_init, + const zeek::detail::Location* expr_location) { if ( ! v ) return nullptr; - zeek::Type* vt = flatten_type(v->GetType().get()); + Type* vt = flatten_type(v->GetType().get()); t = flatten_type(t); - zeek::TypeTag t_tag = t->Tag(); - zeek::TypeTag v_tag = vt->Tag(); + TypeTag t_tag = t->Tag(); + TypeTag v_tag = vt->Tag(); // More thought definitely needs to go into this. - if ( t_tag == zeek::TYPE_ANY || v_tag == zeek::TYPE_ANY ) + if ( t_tag == TYPE_ANY || v_tag == TYPE_ANY ) return v; - if ( ! zeek::EitherArithmetic(t_tag, v_tag) || + if ( ! EitherArithmetic(t_tag, v_tag) || /* allow sets as initializers */ - (is_init && v_tag == zeek::TYPE_TABLE) ) + (is_init && v_tag == TYPE_TABLE) ) { if ( same_type(t, vt, is_init) ) return v; @@ -3245,10 +3247,10 @@ IntrusivePtr check_and_promote(IntrusivePtr v, const zeek::Type* t, return nullptr; } - if ( ! zeek::BothArithmetic(t_tag, v_tag) && - (! zeek::IsArithmetic(v_tag) || t_tag != zeek::TYPE_TIME || ! v->IsZero()) ) + if ( ! BothArithmetic(t_tag, v_tag) && + (! IsArithmetic(v_tag) || t_tag != TYPE_TIME || ! v->IsZero()) ) { - if ( t_tag == zeek::TYPE_LIST || v_tag == zeek::TYPE_LIST ) + if ( t_tag == TYPE_LIST || v_tag == TYPE_LIST ) t->Error("list mixed with scalar", v.get(), false, expr_location); else t->Error("arithmetic mixed with non-arithmetic", v.get(), false, expr_location); @@ -3258,9 +3260,9 @@ IntrusivePtr check_and_promote(IntrusivePtr v, const zeek::Type* t, if ( v_tag == t_tag ) return v; - if ( t_tag != zeek::TYPE_TIME && ! zeek::BothArithmetic(t_tag, v_tag) ) + if ( t_tag != TYPE_TIME && ! BothArithmetic(t_tag, v_tag) ) { - zeek::TypeTag mt = zeek::max_type(t_tag, v_tag); + TypeTag mt = max_type(t_tag, v_tag); if ( mt != t_tag ) { t->Error("over-promotion of arithmetic value", v.get(), false, expr_location); @@ -3269,24 +3271,24 @@ IntrusivePtr check_and_promote(IntrusivePtr v, const zeek::Type* t, } // Need to promote v to type t. - zeek::InternalTypeTag it = t->InternalType(); - zeek::InternalTypeTag vit = vt->InternalType(); + InternalTypeTag it = t->InternalType(); + InternalTypeTag vit = vt->InternalType(); if ( it == vit ) // Already has the right internal type. return v; - IntrusivePtr promoted_v; + ValPtr promoted_v; switch ( it ) { - case zeek::TYPE_INTERNAL_INT: - if ( ( vit == zeek::TYPE_INTERNAL_UNSIGNED || vit == zeek::TYPE_INTERNAL_DOUBLE ) && Val::WouldOverflow(vt, t, v.get()) ) + case TYPE_INTERNAL_INT: + if ( ( vit == TYPE_INTERNAL_UNSIGNED || vit == TYPE_INTERNAL_DOUBLE ) && Val::WouldOverflow(vt, t, v.get()) ) { t->Error("overflow promoting from unsigned/double to signed arithmetic value", v.get(), false, expr_location); return nullptr; } - else if ( t_tag == zeek::TYPE_INT ) - promoted_v = val_mgr->Int(v->CoerceToInt()); + else if ( t_tag == TYPE_INT ) + promoted_v = zeek::val_mgr->Int(v->CoerceToInt()); else // enum { reporter->InternalError("bad internal type in check_and_promote()"); @@ -3295,14 +3297,14 @@ IntrusivePtr check_and_promote(IntrusivePtr v, const zeek::Type* t, break; - case zeek::TYPE_INTERNAL_UNSIGNED: - if ( ( vit == zeek::TYPE_INTERNAL_DOUBLE || vit == zeek::TYPE_INTERNAL_INT) && Val::WouldOverflow(vt, t, v.get()) ) + case TYPE_INTERNAL_UNSIGNED: + if ( ( vit == TYPE_INTERNAL_DOUBLE || vit == TYPE_INTERNAL_INT) && Val::WouldOverflow(vt, t, v.get()) ) { t->Error("overflow promoting from signed/double to unsigned arithmetic value", v.get(), false, expr_location); return nullptr; } - else if ( t_tag == zeek::TYPE_COUNT || t_tag == zeek::TYPE_COUNTER ) - promoted_v = val_mgr->Count(v->CoerceToUnsigned()); + else if ( t_tag == TYPE_COUNT || t_tag == TYPE_COUNTER ) + promoted_v = zeek::val_mgr->Count(v->CoerceToUnsigned()); else // port { reporter->InternalError("bad internal type in check_and_promote()"); @@ -3311,16 +3313,16 @@ IntrusivePtr check_and_promote(IntrusivePtr v, const zeek::Type* t, break; - case zeek::TYPE_INTERNAL_DOUBLE: + case TYPE_INTERNAL_DOUBLE: switch ( t_tag ) { - case zeek::TYPE_DOUBLE: - promoted_v = make_intrusive(v->CoerceToDouble()); + case TYPE_DOUBLE: + promoted_v = make_intrusive(v->CoerceToDouble()); break; - case zeek::TYPE_INTERVAL: - promoted_v = make_intrusive(v->CoerceToDouble()); + case TYPE_INTERVAL: + promoted_v = make_intrusive(v->CoerceToDouble()); break; - case zeek::TYPE_TIME: - promoted_v = make_intrusive(v->CoerceToDouble()); + case TYPE_TIME: + promoted_v = make_intrusive(v->CoerceToDouble()); break; default: reporter->InternalError("bad internal type in check_and_promote()"); @@ -3355,17 +3357,17 @@ bool same_atomic_val(const Val* v1, const Val* v2) return false; switch ( v1->GetType()->InternalType() ) { - case zeek::TYPE_INTERNAL_INT: + case TYPE_INTERNAL_INT: return v1->InternalInt() == v2->InternalInt(); - case zeek::TYPE_INTERNAL_UNSIGNED: + case TYPE_INTERNAL_UNSIGNED: return v1->InternalUnsigned() == v2->InternalUnsigned(); - case zeek::TYPE_INTERNAL_DOUBLE: + case TYPE_INTERNAL_DOUBLE: return v1->InternalDouble() == v2->InternalDouble(); - case zeek::TYPE_INTERNAL_STRING: + case TYPE_INTERNAL_STRING: return Bstr_eq(v1->AsString(), v2->AsString()); - case zeek::TYPE_INTERNAL_ADDR: + case TYPE_INTERNAL_ADDR: return v1->AsAddr() == v2->AsAddr(); - case zeek::TYPE_INTERNAL_SUBNET: + case TYPE_INTERNAL_SUBNET: return v1->AsSubNet() == v2->AsSubNet(); default: @@ -3393,7 +3395,7 @@ void describe_vals(const val_list* vals, ODesc* d, int offset) } } -void describe_vals(const std::vector>& vals, +void describe_vals(const std::vector& vals, ODesc* d, size_t offset) { if ( ! d->IsReadable() ) @@ -3421,7 +3423,7 @@ void delete_vals(val_list* vals) } } -IntrusivePtr cast_value_to_type(Val* v, zeek::Type* t) +ValPtr cast_value_to_type(Val* v, Type* t) { // Note: when changing this function, adapt all three of // cast_value_to_type()/can_cast_value_to_type()/can_cast_value_to_type(). @@ -3447,7 +3449,7 @@ IntrusivePtr cast_value_to_type(Val* v, zeek::Type* t) return nullptr; } -bool can_cast_value_to_type(const Val* v, zeek::Type* t) +bool can_cast_value_to_type(const Val* v, Type* t) { // Note: when changing this function, adapt all three of // cast_value_to_type()/can_cast_value_to_type()/can_cast_value_to_type(). @@ -3473,7 +3475,7 @@ bool can_cast_value_to_type(const Val* v, zeek::Type* t) return false; } -bool can_cast_value_to_type(const zeek::Type* s, zeek::Type* t) +bool can_cast_value_to_type(const Type* s, Type* t) { // Note: when changing this function, adapt all three of // cast_value_to_type()/can_cast_value_to_type()/can_cast_value_to_type(). @@ -3492,24 +3494,24 @@ bool can_cast_value_to_type(const zeek::Type* s, zeek::Type* t) return false; } -IntrusivePtr Val::MakeBool(bool b) +ValPtr Val::MakeBool(bool b) { - return IntrusivePtr{AdoptRef{}, new Val(bro_int_t(b), zeek::TYPE_BOOL)}; + return IntrusivePtr{AdoptRef{}, new Val(bro_int_t(b), TYPE_BOOL)}; } -IntrusivePtr Val::MakeInt(bro_int_t i) +ValPtr Val::MakeInt(bro_int_t i) { - return IntrusivePtr{AdoptRef{}, new Val(i, zeek::TYPE_INT)}; + return IntrusivePtr{AdoptRef{}, new Val(i, TYPE_INT)}; } -IntrusivePtr Val::MakeCount(bro_uint_t u) +ValPtr Val::MakeCount(bro_uint_t u) { - return IntrusivePtr{AdoptRef{}, new Val(u, zeek::TYPE_COUNT)}; + return IntrusivePtr{AdoptRef{}, new Val(u, TYPE_COUNT)}; } ValManager::ValManager() { - empty_string = make_intrusive(""); + empty_string = make_intrusive(""); b_false = Val::MakeBool(false); b_true = Val::MakeBool(true); @@ -3534,7 +3536,7 @@ StringVal* ValManager::GetEmptyString() const return empty_string->Ref()->AsStringVal(); } -const IntrusivePtr& ValManager::Port(uint32_t port_num, TransportProto port_type) const +const PortValPtr& ValManager::Port(uint32_t port_num, TransportProto port_type) const { if ( port_num >= 65536 ) { @@ -3550,7 +3552,7 @@ PortVal* ValManager::GetPort(uint32_t port_num, TransportProto port_type) const return Port(port_num, port_type)->Ref()->AsPortVal(); } -const IntrusivePtr& ValManager::Port(uint32_t port_num) const +const PortValPtr& ValManager::Port(uint32_t port_num) const { auto mask = port_num & PORT_SPACE_MASK; port_num &= ~PORT_SPACE_MASK; @@ -3569,3 +3571,5 @@ PortVal* ValManager::GetPort(uint32_t port_num) const { return Port(port_num)->Ref()->AsPortVal(); } + +} diff --git a/src/Val.h b/src/Val.h index bf7868168b..822fbb1ec7 100644 --- a/src/Val.h +++ b/src/Val.h @@ -25,20 +25,41 @@ #define UDP_PORT_MASK 0x20000 #define ICMP_PORT_MASK 0x30000 +namespace zeek { template class PDict; -class IterCookie; +class String; +}; +template using PDict [[deprecated("Remove in v4.1. Use zeek::PDict instead.")]] = zeek::PDict; +using BroString [[deprecated("Remove in v4.1. Use zeek::String instead.")]] = zeek::String; + +ZEEK_FORWARD_DECLARE_NAMESPACED(IterCookie, zeek); +ZEEK_FORWARD_DECLARE_NAMESPACED(Frame, zeek::detail); +ZEEK_FORWARD_DECLARE_NAMESPACED(Func, zeek); + +namespace zeek::detail { class ScriptFunc; } +using BroFunc [[deprecated("Remove in v4.1. Use zeek::detail::ScriptFunc instead.")]] = zeek::detail::ScriptFunc; -class Val; -class BroString; -class BroFunc; -class Func; class BroFile; class PrefixTable; +class IPAddr; +class IPPrefix; +class StateAccess; +class RE_Matcher; +class CompositeHash; +class HashKey; + +extern double bro_start_network_time; + +namespace zeek { + +using FuncPtr = zeek::IntrusivePtr; +using BroFilePtr = zeek::IntrusivePtr; + +class Val; class PortVal; class AddrVal; class SubNetVal; - class IntervalVal; class PatternVal; class TableVal; @@ -47,17 +68,18 @@ class ListVal; class StringVal; class EnumVal; class OpaqueVal; - -class IPAddr; -class IPPrefix; - -class StateAccess; - class VectorVal; - class TableEntryVal; -class RE_Matcher; +using AddrValPtr = zeek::IntrusivePtr; +using EnumValPtr = zeek::IntrusivePtr; +using ListValPtr = zeek::IntrusivePtr; +using PortValPtr = zeek::IntrusivePtr; +using RecordValPtr = zeek::IntrusivePtr; +using StringValPtr = zeek::IntrusivePtr; +using TableValPtr = zeek::IntrusivePtr; +using ValPtr = zeek::IntrusivePtr; +using VectorValPtr = zeek::IntrusivePtr; union BroValUnion { // Used for bool, int, enum. @@ -75,13 +97,13 @@ union BroValUnion { // Used for double, time, interval. double double_val; - BroString* string_val; - Func* func_val; + String* string_val; + zeek::Func* func_val; BroFile* file_val; RE_Matcher* re_val; - PDict* table_val; - std::vector>* record_val; - std::vector>* vector_val; + zeek::PDict* table_val; + std::vector* record_val; + std::vector* vector_val; BroValUnion() = default; @@ -100,10 +122,10 @@ union BroValUnion { constexpr BroValUnion(double value) noexcept : double_val(value) {} - constexpr BroValUnion(BroString* value) noexcept + constexpr BroValUnion(String* value) noexcept : string_val(value) {} - constexpr BroValUnion(Func* value) noexcept + constexpr BroValUnion(zeek::Func* value) noexcept : func_val(value) {} constexpr BroValUnion(BroFile* value) noexcept @@ -112,13 +134,13 @@ union BroValUnion { constexpr BroValUnion(RE_Matcher* value) noexcept : re_val(value) {} - constexpr BroValUnion(PDict* value) noexcept + constexpr BroValUnion(zeek::PDict* value) noexcept : table_val(value) {} }; -class Val : public BroObj { +class Val : public Obj { public: - static inline const IntrusivePtr nil; + static inline const ValPtr nil; [[deprecated("Remove in v4.1. Use IntervalVal(), TimeVal(), or DoubleVal() constructors.")]] Val(double d, zeek::TypeTag t) @@ -126,22 +148,22 @@ public: {} [[deprecated("Remove in v4.1. Construct from IntrusivePtr instead.")]] - explicit Val(Func* f); - explicit Val(IntrusivePtr f); + explicit Val(zeek::Func* f); + explicit Val(zeek::FuncPtr f); [[deprecated("Remove in v4.1. Construct from IntrusivePtr instead.")]] explicit Val(BroFile* f); // Note, the file will be closed after this Val is destructed if there's // no other remaining references. - explicit Val(IntrusivePtr f); + explicit Val(BroFilePtr f); // Extra arg to differentiate from protected version. - Val(IntrusivePtr t, bool type_type) - : type(make_intrusive(std::move(t))) + Val(zeek::TypePtr t, bool type_type) + : type(zeek::make_intrusive(std::move(t))) {} [[deprecated("Remove in v4.1. Construct from IntrusivePtr instead.")]] - Val(zeek::Type* t, bool type_type) : Val({NewRef{}, t}, type_type) + Val(zeek::Type* t, bool type_type) : Val({zeek::NewRef{}, t}, type_type) {} Val() @@ -150,8 +172,8 @@ public: ~Val() override; - Val* Ref() { ::Ref(this); return this; } - IntrusivePtr Clone(); + Val* Ref() { zeek::Ref(this); return this; } + ValPtr Clone(); bool IsZero() const; bool IsOne() const; @@ -166,7 +188,7 @@ public: // Returns a new Val with the "size" of this Val. What constitutes // size depends on the Val's type. - virtual IntrusivePtr SizeVal() const; + virtual ValPtr SizeVal() const; // Bytes in total value object. virtual unsigned int MemoryAllocation() const; @@ -185,12 +207,12 @@ public: [[deprecated("Remove in v4.1. Use GetType().")]] const zeek::Type* Type() const { return type.get(); } - const IntrusivePtr& GetType() const + const zeek::TypePtr& GetType() const { return type; } template - IntrusivePtr GetType() const - { return cast_intrusive(type); } + zeek::IntrusivePtr GetType() const + { return zeek::cast_intrusive(type); } #define CONST_ACCESSOR(tag, ctype, accessor, name) \ const ctype name() const \ @@ -215,13 +237,13 @@ public: CONST_ACCESSOR2(zeek::TYPE_TIME, double, double_val, AsTime) CONST_ACCESSOR2(zeek::TYPE_INTERVAL, double, double_val, AsInterval) CONST_ACCESSOR2(zeek::TYPE_ENUM, int, int_val, AsEnum) - CONST_ACCESSOR(zeek::TYPE_STRING, BroString*, string_val, AsString) - CONST_ACCESSOR(zeek::TYPE_FUNC, Func*, func_val, AsFunc) - CONST_ACCESSOR(zeek::TYPE_TABLE, PDict*, table_val, AsTable) - CONST_ACCESSOR(zeek::TYPE_RECORD, std::vector>*, record_val, AsRecord) + CONST_ACCESSOR(zeek::TYPE_STRING, String*, string_val, AsString) + CONST_ACCESSOR(zeek::TYPE_FUNC, zeek::Func*, func_val, AsFunc) + CONST_ACCESSOR(zeek::TYPE_TABLE, zeek::PDict*, table_val, AsTable) + CONST_ACCESSOR(zeek::TYPE_RECORD, std::vector*, record_val, AsRecord) CONST_ACCESSOR(zeek::TYPE_FILE, BroFile*, file_val, AsFile) CONST_ACCESSOR(zeek::TYPE_PATTERN, RE_Matcher*, re_val, AsPattern) - CONST_ACCESSOR(zeek::TYPE_VECTOR, std::vector>*, vector_val, AsVector) + CONST_ACCESSOR(zeek::TYPE_VECTOR, std::vector*, vector_val, AsVector) const IPPrefix& AsSubNet() const { @@ -251,13 +273,13 @@ public: // Accessors for mutable values are called AsNonConst* and // are protected to avoid external state changes. - // ACCESSOR(zeek::TYPE_STRING, BroString*, string_val, AsString) - ACCESSOR(zeek::TYPE_FUNC, Func*, func_val, AsFunc) + // ACCESSOR(zeek::TYPE_STRING, String*, string_val, AsString) + ACCESSOR(zeek::TYPE_FUNC, zeek::Func*, func_val, AsFunc) ACCESSOR(zeek::TYPE_FILE, BroFile*, file_val, AsFile) ACCESSOR(zeek::TYPE_PATTERN, RE_Matcher*, re_val, AsPattern) - ACCESSOR(zeek::TYPE_VECTOR, std::vector>*, vector_val, AsVector) + ACCESSOR(zeek::TYPE_VECTOR, std::vector*, vector_val, AsVector) - IntrusivePtr AsFuncPtr() const; + zeek::FuncPtr AsFuncPtr() const; const IPPrefix& AsSubNet() { @@ -327,9 +349,9 @@ public: static bool WouldOverflow(const zeek::Type* from_type, const zeek::Type* to_type, const Val* val); - IntrusivePtr GetRecordFields(); + TableValPtr GetRecordFields(); - IntrusivePtr ToJSON(bool only_loggable=false, RE_Matcher* re=nullptr); + StringValPtr ToJSON(bool only_loggable=false, RE_Matcher* re=nullptr); protected: @@ -343,9 +365,9 @@ protected: virtual void ValDescribe(ODesc* d) const; virtual void ValDescribeReST(ODesc* d) const; - static IntrusivePtr MakeBool(bool b); - static IntrusivePtr MakeInt(bro_int_t i); - static IntrusivePtr MakeCount(bro_uint_t u); + static ValPtr MakeBool(bool b); + static ValPtr MakeInt(bro_int_t i); + static ValPtr MakeCount(bro_uint_t u); template Val(V&& v, zeek::TypeTag t) noexcept @@ -353,32 +375,32 @@ protected: {} template - Val(V&& v, IntrusivePtr t) noexcept + Val(V&& v, zeek::TypePtr t) noexcept : val(std::forward(v)), type(std::move(t)) {} - explicit Val(IntrusivePtr t) noexcept + explicit Val(zeek::TypePtr t) noexcept : type(std::move(t)) {} - ACCESSOR(zeek::TYPE_TABLE, PDict*, table_val, AsNonConstTable) - ACCESSOR(zeek::TYPE_RECORD, std::vector>*, record_val, AsNonConstRecord) + ACCESSOR(zeek::TYPE_TABLE, zeek::PDict*, table_val, AsNonConstTable) + ACCESSOR(zeek::TYPE_RECORD, std::vector*, record_val, AsNonConstRecord) // For internal use by the Val::Clone() methods. struct CloneState { // Caches a cloned value for later reuse during the same // cloning operation. For recursive types, call this *before* // descending down. - IntrusivePtr NewClone(Val* src, IntrusivePtr dst); + ValPtr NewClone(Val* src, ValPtr dst); std::unordered_map clones; }; - IntrusivePtr Clone(CloneState* state); - virtual IntrusivePtr DoClone(CloneState* state); + ValPtr Clone(CloneState* state); + virtual ValPtr DoClone(CloneState* state); BroValUnion val; - IntrusivePtr type; + zeek::TypePtr type; #ifdef DEBUG // For debugging, we keep the name of the ID to which a Val is bound. @@ -400,79 +422,79 @@ public: ValManager(); - [[deprecated("Remove in v4.1. Use val_mgr->True() instead.")]] + [[deprecated("Remove in v4.1. Use zeek::val_mgr->True() instead.")]] inline Val* GetTrue() const { return b_true->Ref(); } - inline const IntrusivePtr& True() const + inline const ValPtr& True() const { return b_true; } - [[deprecated("Remove in v4.1. Use val_mgr->False() instead.")]] + [[deprecated("Remove in v4.1. Use zeek::val_mgr->False() instead.")]] inline Val* GetFalse() const { return b_false->Ref(); } - inline const IntrusivePtr& False() const + inline const ValPtr& False() const { return b_false; } - [[deprecated("Remove in v4.1. Use val_mgr->Bool() instead.")]] + [[deprecated("Remove in v4.1. Use zeek::val_mgr->Bool() instead.")]] inline Val* GetBool(bool b) const { return b ? b_true->Ref() : b_false->Ref(); } - inline const IntrusivePtr& Bool(bool b) const + inline const ValPtr& Bool(bool b) const { return b ? b_true : b_false; } - [[deprecated("Remove in v4.1. Use val_mgr->Int() instead.")]] + [[deprecated("Remove in v4.1. Use zeek::val_mgr->Int() instead.")]] inline Val* GetInt(int64_t i) const { return i < PREALLOCATED_INT_LOWEST || i > PREALLOCATED_INT_HIGHEST ? Val::MakeInt(i).release() : ints[i - PREALLOCATED_INT_LOWEST]->Ref(); } - inline IntrusivePtr Int(int64_t i) const + inline ValPtr Int(int64_t i) const { return i < PREALLOCATED_INT_LOWEST || i > PREALLOCATED_INT_HIGHEST ? Val::MakeInt(i) : ints[i - PREALLOCATED_INT_LOWEST]; } - [[deprecated("Remove in v4.1. Use val_mgr->Count() instead.")]] + [[deprecated("Remove in v4.1. Use zeek::val_mgr->Count() instead.")]] inline Val* GetCount(uint64_t i) const { return i >= PREALLOCATED_COUNTS ? Val::MakeCount(i).release() : counts[i]->Ref(); } - inline IntrusivePtr Count(uint64_t i) const + inline ValPtr Count(uint64_t i) const { return i >= PREALLOCATED_COUNTS ? Val::MakeCount(i) : counts[i]; } - [[deprecated("Remove in v4.1. Use val_mgr->EmptyString() instead.")]] + [[deprecated("Remove in v4.1. Use zeek::val_mgr->EmptyString() instead.")]] StringVal* GetEmptyString() const; - inline const IntrusivePtr& EmptyString() const + inline const StringValPtr& EmptyString() const { return empty_string; } // Port number given in host order. - [[deprecated("Remove in v4.1. Use val_mgr->Port() instead.")]] + [[deprecated("Remove in v4.1. Use zeek::val_mgr->Port() instead.")]] PortVal* GetPort(uint32_t port_num, TransportProto port_type) const; // Port number given in host order. - const IntrusivePtr& Port(uint32_t port_num, TransportProto port_type) const; + const PortValPtr& Port(uint32_t port_num, TransportProto port_type) const; // Host-order port number already masked with port space protocol mask. - [[deprecated("Remove in v4.1. Use val_mgr->Port() instead.")]] + [[deprecated("Remove in v4.1. Use zeek::val_mgr->Port() instead.")]] PortVal* GetPort(uint32_t port_num) const; // Host-order port number already masked with port space protocol mask. - const IntrusivePtr& Port(uint32_t port_num) const; + const PortValPtr& Port(uint32_t port_num) const; private: - std::array, 65536>, NUM_PORT_SPACES> ports; - std::array, PREALLOCATED_COUNTS> counts; - std::array, PREALLOCATED_INTS> ints; - IntrusivePtr empty_string; - IntrusivePtr b_true; - IntrusivePtr b_false; + std::array, NUM_PORT_SPACES> ports; + std::array counts; + std::array ints; + StringValPtr empty_string; + ValPtr b_true; + ValPtr b_false; }; extern ValManager* val_mgr; @@ -510,7 +532,7 @@ public: class PortVal final : public Val { public: - IntrusivePtr SizeVal() const override; + ValPtr SizeVal() const override; // Returns the port number in host order (not including the mask). uint32_t Port() const; @@ -541,7 +563,7 @@ protected: PortVal(uint32_t p); void ValDescribe(ODesc* d) const override; - IntrusivePtr DoClone(CloneState* state) override; + ValPtr DoClone(CloneState* state) override; }; class AddrVal final : public Val { @@ -550,7 +572,7 @@ public: explicit AddrVal(const std::string& text); ~AddrVal() override; - IntrusivePtr SizeVal() const override; + ValPtr SizeVal() const override; // Constructor for address already in network order. explicit AddrVal(uint32_t addr); // IPv4. @@ -560,7 +582,7 @@ public: unsigned int MemoryAllocation() const override; protected: - IntrusivePtr DoClone(CloneState* state) override; + ValPtr DoClone(CloneState* state) override; }; class SubNetVal final : public Val { @@ -573,7 +595,7 @@ public: explicit SubNetVal(const IPPrefix& prefix); ~SubNetVal() override; - IntrusivePtr SizeVal() const override; + ValPtr SizeVal() const override; const IPAddr& Prefix() const; int Width() const; @@ -585,17 +607,17 @@ public: protected: void ValDescribe(ODesc* d) const override; - IntrusivePtr DoClone(CloneState* state) override; + ValPtr DoClone(CloneState* state) override; }; class StringVal final : public Val { public: - explicit StringVal(BroString* s); + explicit StringVal(String* s); explicit StringVal(const char* s); explicit StringVal(const std::string& s); StringVal(int length, const char* s); - IntrusivePtr SizeVal() const override; + ValPtr SizeVal() const override; int Len(); const u_char* Bytes(); @@ -603,7 +625,7 @@ public: // Note that one needs to de-allocate the return value of // ExpandedString() to avoid a memory leak. - // char* ExpandedString(int format = BroString::EXPANDED_STRING) + // char* ExpandedString(int format = String::EXPANDED_STRING) // { return AsString()->ExpandedString(format); } std::string ToStdString() const; @@ -611,8 +633,8 @@ public: unsigned int MemoryAllocation() const override; - IntrusivePtr Replace(RE_Matcher* re, const BroString& repl, - bool do_all); + StringValPtr Replace(RE_Matcher* re, const String& repl, + bool do_all); [[deprecated("Remove in v4.1. Use Replace().")]] Val* Substitute(RE_Matcher* re, StringVal* repl, bool do_all) @@ -620,7 +642,7 @@ public: protected: void ValDescribe(ODesc* d) const override; - IntrusivePtr DoClone(CloneState* state) override; + ValPtr DoClone(CloneState* state) override; }; class PatternVal final : public Val { @@ -636,7 +658,7 @@ public: protected: void ValDescribe(ODesc* d) const override; - IntrusivePtr DoClone(CloneState* state) override; + ValPtr DoClone(CloneState* state) override; }; // ListVals are mainly used to index tables that have more than one @@ -649,11 +671,11 @@ public: zeek::TypeTag BaseTag() const { return tag; } - IntrusivePtr SizeVal() const override; + ValPtr SizeVal() const override; int Length() const { return vals.size(); } - const IntrusivePtr& Idx(size_t i) const { return vals[i]; } + const ValPtr& Idx(size_t i) const { return vals[i]; } [[deprecated("Remove in v4.1. Use Idx() instead")]] Val* Index(const int n) { return vals[n].get(); } @@ -674,35 +696,33 @@ public: * Appends a value to the list. * @param v the value to append. */ - void Append(IntrusivePtr v); + void Append(ValPtr v); [[deprecated("Remove in v4.1. Use Append(IntrusivePtr) instead.")]] void Append(Val* v); // Returns a Set representation of the list (which must be homogeneous). - IntrusivePtr ToSetVal() const; + TableValPtr ToSetVal() const; [[deprecated("Remove in v4.1. Use ToSetVal() instead.")]] TableVal* ConvertToSet() const; - const std::vector>& Vals() const { return vals; } + const std::vector& Vals() const { return vals; } void Describe(ODesc* d) const override; unsigned int MemoryAllocation() const override; protected: - IntrusivePtr DoClone(CloneState* state) override; + ValPtr DoClone(CloneState* state) override; - std::vector> vals; + std::vector vals; zeek::TypeTag tag; }; -extern double bro_start_network_time; - class TableEntryVal { public: - explicit TableEntryVal(IntrusivePtr v) + explicit TableEntryVal(ValPtr v) : val(std::move(v)) { expire_access_time = @@ -714,7 +734,7 @@ public: [[deprecated("Remove in v4.1. Use GetVal().")]] Val* Value() { return val.get(); } - const IntrusivePtr& GetVal() const + const ValPtr& GetVal() const { return val; } // Returns/sets time of last expiration relevant access to this value. @@ -726,7 +746,8 @@ public: protected: friend class TableVal; - IntrusivePtr val; + ValPtr val; + // The next entry stores seconds since Bro's start. We use ints here // to save a few bytes, as we do not need a high resolution for these // anyway. @@ -746,17 +767,13 @@ protected: TableVal* table; }; -class CompositeHash; -class HashKey; -class Frame; - class TableVal final : public Val, public notifier::Modifiable { public: - explicit TableVal(IntrusivePtr t, IntrusivePtr attrs = nullptr); + explicit TableVal(zeek::TableTypePtr t, zeek::detail::AttributesPtr attrs = nullptr); [[deprecated("Remove in v4.1. Construct from IntrusivePtrs instead.")]] explicit TableVal(zeek::TableType* t, zeek::detail::Attributes* attrs = nullptr) - : TableVal({NewRef{}, t}, {NewRef{}, attrs}) + : TableVal({zeek::NewRef{}, t}, {zeek::NewRef{}, attrs}) {} ~TableVal() override; @@ -769,7 +786,7 @@ public: * must be nullptr. * @return True if the assignment type-checked. */ - bool Assign(IntrusivePtr index, IntrusivePtr new_val); + bool Assign(ValPtr index, ValPtr new_val); /** * Assigns a value at an associated index in the table (or in the @@ -781,8 +798,8 @@ public: * must be nullptr. * @return True if the assignment type-checked. */ - bool Assign(IntrusivePtr index, std::unique_ptr k, - IntrusivePtr new_val); + bool Assign(ValPtr index, std::unique_ptr k, + ValPtr new_val); // Returns true if the assignment typechecked, false if not. The // methods take ownership of new_val, but not of the index. If we're @@ -795,7 +812,7 @@ public: [[deprecated("Remove in v4.1. Use IntrusivePtr overload instead.")]] bool Assign(Val* index, HashKey* k, Val* new_val); - IntrusivePtr SizeVal() const override; + ValPtr SizeVal() const override; // Add the entire contents of the table to the given value, // which must also be a TableVal. @@ -823,7 +840,7 @@ public: * @param v The intersecting table. * @return The intersection of this table and the given one. */ - IntrusivePtr Intersection(const TableVal& v) const; + TableValPtr Intersection(const TableVal& v) const; [[deprecated("Remove in v4.1. Use Intersection() instead.")]] TableVal* Intersect(const TableVal* v) const @@ -849,7 +866,7 @@ public: // Expands any lists in the index into multiple initializations. // Returns true if the initializations typecheck, false if not. - bool ExpandAndInit(IntrusivePtr index, IntrusivePtr new_val); + bool ExpandAndInit(ValPtr index, ValPtr new_val); /** * Finds an index in the table and returns its associated value. @@ -860,7 +877,7 @@ public: * non-existent index (nullptr), but otherwise has no meaning in relation * to the set's contents. */ - const IntrusivePtr& Find(const IntrusivePtr& index); + const ValPtr& Find(const ValPtr& index); /** * Finds an index in the table and returns its associated value or else @@ -870,7 +887,7 @@ public: * exist, instead returns the &default value. If there's no &default * attribute, then nullptr is still returned for non-existent index. */ - IntrusivePtr FindOrDefault(const IntrusivePtr& index); + ValPtr FindOrDefault(const ValPtr& index); // Returns the element's value if it exists in the table, // nil otherwise. Note, "index" is not const because we @@ -881,12 +898,12 @@ public: // For a table[subnet]/set[subnet], return all subnets that cover // the given subnet. // Causes an internal error if called for any other kind of table. - IntrusivePtr LookupSubnets(const SubNetVal* s); + VectorValPtr LookupSubnets(const SubNetVal* s); // For a set[subnet]/table[subnet], return a new table that only contains // entries that cover the given subnet. // Causes an internal error if called for any other kind of table. - IntrusivePtr LookupSubnetValues(const SubNetVal* s); + TableValPtr LookupSubnetValues(const SubNetVal* s); // Sets the timestamp for the given index to network time. // Returns false if index does not exist. @@ -895,7 +912,7 @@ public: /** * @return The index corresponding to the given HashKey. */ - IntrusivePtr RecreateIndex(const HashKey& k) const; + ListValPtr RecreateIndex(const HashKey& k) const; [[deprecated("Remove in v4.1. Use RecreateIndex().")]] ListVal* RecoverIndex(const HashKey* k) const @@ -909,14 +926,14 @@ public: * value is returned to differentiate it from non-existent index (nullptr), * but otherwise has no meaning in relation to the set's contents. */ - IntrusivePtr Remove(const Val& index); + ValPtr Remove(const Val& index); /** * Same as Remove(const Val&), but uses a precomputed hash key. * @param k The hash key to lookup. * @return Same as Remove(const Val&). */ - IntrusivePtr Remove(const HashKey& k); + ValPtr Remove(const HashKey& k); [[deprecated("Remove in v4.1. Use Remove().")]] Val* Delete(const Val* index) @@ -927,25 +944,25 @@ public: { return Remove(*k).release(); } // Returns a ListVal representation of the table (which must be a set). - IntrusivePtr ToListVal(zeek::TypeTag t = zeek::TYPE_ANY) const; + ListValPtr ToListVal(zeek::TypeTag t = zeek::TYPE_ANY) const; // Returns a ListVal representation of the table (which must be a set // with non-composite index type). - IntrusivePtr ToPureListVal() const; + ListValPtr ToPureListVal() const; [[deprecated("Remove in v4.1. Use ToListVal() instead.")]] ListVal* ConvertToList(zeek::TypeTag t=zeek::TYPE_ANY) const; [[deprecated("Remove in v4.1. Use ToPureListVal() instead.")]] ListVal* ConvertToPureList() const; // must be single index type - void SetAttrs(IntrusivePtr attrs); + void SetAttrs(zeek::detail::AttributesPtr attrs); - const IntrusivePtr& GetAttr(zeek::detail::AttrTag t) const; + const zeek::detail::AttrPtr& GetAttr(zeek::detail::AttrTag t) const; [[deprecated("Remove in v4.1. Use GetAttrs().")]] zeek::detail::Attributes* Attrs() { return attrs.get(); } - const IntrusivePtr& GetAttrs() const + const zeek::detail::AttributesPtr& GetAttrs() const { return attrs; } // Returns the size of the table. @@ -965,7 +982,7 @@ public: // If the &default attribute is not a function, or the functon has // already been initialized, this does nothing. Otherwise, evaluates // the function in the frame allowing it to capture its closure. - void InitDefaultFunc(Frame* f); + void InitDefaultFunc(zeek::detail::Frame* f); unsigned int MemoryAllocation() const override; @@ -1001,22 +1018,22 @@ public: static void DoneParsing(); protected: - void Init(IntrusivePtr t); + void Init(zeek::TableTypePtr t); - using TableRecordDependencies = std::unordered_map>>; + using TableRecordDependencies = std::unordered_map>; - using ParseTimeTableState = std::vector, IntrusivePtr>>; + using ParseTimeTableState = std::vector>; using ParseTimeTableStates = std::unordered_map; ParseTimeTableState DumpTableState(); void RebuildTable(ParseTimeTableState ptts); void CheckExpireAttr(zeek::detail::AttrTag at); - bool ExpandCompoundAndInit(ListVal* lv, int k, IntrusivePtr new_val); - bool CheckAndAssign(IntrusivePtr index, IntrusivePtr new_val); + bool ExpandCompoundAndInit(ListVal* lv, int k, ValPtr new_val); + bool CheckAndAssign(ValPtr index, ValPtr new_val); // Calculates default value for index. Returns nullptr if none. - IntrusivePtr Default(const IntrusivePtr& index); + ValPtr Default(const ValPtr& index); // Returns true if item expiration is enabled. bool ExpirationEnabled() { return expire_time != nullptr; } @@ -1027,27 +1044,27 @@ protected: double GetExpireTime(); // Calls &expire_func and returns its return interval; - double CallExpireFunc(IntrusivePtr idx); + double CallExpireFunc(ListValPtr idx); // Enum for the different kinds of changes an &on_change handler can see enum OnChangeType { ELEMENT_NEW, ELEMENT_CHANGED, ELEMENT_REMOVED, ELEMENT_EXPIRED }; // Calls &change_func. Does not take ownership of values. (Refs if needed). - void CallChangeFunc(const Val* index, const IntrusivePtr& old_value, + void CallChangeFunc(const Val* index, const ValPtr& old_value, OnChangeType tpe); - IntrusivePtr DoClone(CloneState* state) override; + ValPtr DoClone(CloneState* state) override; - IntrusivePtr table_type; + zeek::TableTypePtr table_type; CompositeHash* table_hash; - IntrusivePtr attrs; - IntrusivePtr expire_time; - IntrusivePtr expire_func; + zeek::detail::AttributesPtr attrs; + zeek::detail::ExprPtr expire_time; + zeek::detail::ExprPtr expire_func; TableValTimer* timer; IterCookie* expire_cookie; PrefixTable* subnets; - IntrusivePtr def_val; - IntrusivePtr change_func; + ValPtr def_val; + zeek::detail::ExprPtr change_func; // prevent recursion of change functions bool in_change_func = false; @@ -1059,18 +1076,18 @@ class RecordVal final : public Val, public notifier::Modifiable { public: [[deprecated("Remove in v4.1. Construct from IntrusivePtr instead.")]] explicit RecordVal(zeek::RecordType* t, bool init_fields = true); - explicit RecordVal(IntrusivePtr t, bool init_fields = true); + explicit RecordVal(zeek::RecordTypePtr t, bool init_fields = true); ~RecordVal() override; - IntrusivePtr SizeVal() const override; + ValPtr SizeVal() const override; /** * Assign a value to a record field. * @param field The field index to assign. * @param new_val The value to assign. */ - void Assign(int field, IntrusivePtr new_val); + void Assign(int field, ValPtr new_val); /** * Assign a value of type @c T to a record field, as constructed from @@ -1081,13 +1098,13 @@ public: */ template void Assign(int field, Ts&&... args) - { Assign(field, make_intrusive(std::forward(args)...)); } + { Assign(field, zeek::make_intrusive(std::forward(args)...)); } [[deprecated("Remove in v4.1. Assign an IntrusivePtr instead.")]] void Assign(int field, Val* new_val); // Note: the following nullptr method can also go upon removing the above. void Assign(int field, std::nullptr_t) - { Assign(field, IntrusivePtr{}); } + { Assign(field, ValPtr{}); } [[deprecated("Remove in v4.1. Use GetField().")]] Val* Lookup(int field) const // Does not Ref() value. @@ -1098,7 +1115,7 @@ public: * @param field The field index to retrieve. * @return The value at the given field index. */ - const IntrusivePtr& GetField(int field) const + const ValPtr& GetField(int field) const { return (*AsRecord())[field]; } /** @@ -1107,8 +1124,8 @@ public: * @return The value at the given field index cast to type @c T. */ template - IntrusivePtr GetField(int field) const - { return cast_intrusive(GetField(field)); } + zeek::IntrusivePtr GetField(int field) const + { return zeek::cast_intrusive(GetField(field)); } /** * Returns the value of a given field index if it's previously been @@ -1118,7 +1135,7 @@ public: * @return The value at the given field index or the default value if * the field hasn't been assigned yet. */ - IntrusivePtr GetFieldOrDefault(int field) const; + ValPtr GetFieldOrDefault(int field) const; [[deprecated("Remove in v4.1. Use GetFieldOrDefault().")]] Val* LookupWithDefault(int field) const @@ -1130,7 +1147,7 @@ public: * @return The value of the given field. If no such field name exists, * a fatal error occurs. */ - const IntrusivePtr& GetField(const char* field) const; + const ValPtr& GetField(const char* field) const; /** * Returns the value of a given field name as cast to type @c T. @@ -1139,8 +1156,8 @@ public: * field name exists, a fatal error occurs. */ template - IntrusivePtr GetField(const char* field) const - { return cast_intrusive(GetField(field)); } + zeek::IntrusivePtr GetField(const char* field) const + { return zeek::cast_intrusive(GetField(field)); } /** * Returns the value of a given field name if it's previously been @@ -1151,7 +1168,7 @@ public: * if the field hasn't been assigned yet. If no such field name exists, * a fatal error occurs. */ - IntrusivePtr GetFieldOrDefault(const char* field) const; + ValPtr GetFieldOrDefault(const char* field) const; /** * Returns the value of a given field name or its default value @@ -1161,8 +1178,8 @@ public: * type @c T. If no such field name exists, a fatal error occurs. */ template - IntrusivePtr GetFieldOrDefault(const char* field) const - { return cast_intrusive(GetField(field)); } + zeek::IntrusivePtr GetFieldOrDefault(const char* field) const + { return zeek::cast_intrusive(GetField(field)); } /** * Looks up the value of a field by field name. If the field doesn't @@ -1181,12 +1198,12 @@ public: /** * Returns a "record_field_table" value for introspection purposes. */ - IntrusivePtr GetRecordFieldsVal() const; + TableValPtr GetRecordFieldsVal() const; - // This is an experiment to associate a BroObj within the + // This is an experiment to associate a Obj within the // event engine to a record value in bro script. - void SetOrigin(BroObj* o) { origin = o; } - BroObj* GetOrigin() const { return origin; } + void SetOrigin(Obj* o) { origin = o; } + Obj* GetOrigin() const { return origin; } // Returns a new value representing the value coerced to the given // type. If coercion is not possible, returns 0. The non-const @@ -1199,11 +1216,11 @@ public: // // The *allow_orphaning* parameter allows for a record to be demoted // down to a record type that contains less fields. - IntrusivePtr CoerceTo(IntrusivePtr other, - IntrusivePtr aggr, - bool allow_orphaning = false) const; - IntrusivePtr CoerceTo(IntrusivePtr other, - bool allow_orphaning = false); + RecordValPtr CoerceTo(zeek::RecordTypePtr other, + RecordValPtr aggr, + bool allow_orphaning = false) const; + RecordValPtr CoerceTo(zeek::RecordTypePtr other, + bool allow_orphaning = false); unsigned int MemoryAllocation() const override; void DescribeReST(ODesc* d) const override; @@ -1218,30 +1235,30 @@ public: static void DoneParsing(); protected: - IntrusivePtr DoClone(CloneState* state) override; + ValPtr DoClone(CloneState* state) override; - BroObj* origin; + Obj* origin; - using RecordTypeValMap = std::unordered_map>>; + using RecordTypeValMap = std::unordered_map>; static RecordTypeValMap parse_time_records; }; class EnumVal final : public Val { public: - IntrusivePtr SizeVal() const override; + ValPtr SizeVal() const override; protected: friend class Val; friend class zeek::EnumType; template - friend IntrusivePtr make_intrusive(Ts&&... args); + friend zeek::IntrusivePtr zeek::make_intrusive(Ts&&... args); - EnumVal(IntrusivePtr t, int i) : Val(bro_int_t(i), std::move(t)) + EnumVal(zeek::EnumTypePtr t, int i) : Val(bro_int_t(i), std::move(t)) {} void ValDescribe(ODesc* d) const override; - IntrusivePtr DoClone(CloneState* state) override; + ValPtr DoClone(CloneState* state) override; }; @@ -1249,10 +1266,10 @@ class VectorVal final : public Val, public notifier::Modifiable { public: [[deprecated("Remove in v4.1. Construct from IntrusivePtr instead.")]] explicit VectorVal(zeek::VectorType* t); - explicit VectorVal(IntrusivePtr t); + explicit VectorVal(zeek::VectorTypePtr t); ~VectorVal() override; - IntrusivePtr SizeVal() const override; + ValPtr SizeVal() const override; /** * Assigns an element to a given vector index. @@ -1261,22 +1278,22 @@ public: * @return True if the element was successfully assigned, or false if * the element was the wrong type. */ - bool Assign(unsigned int index, IntrusivePtr element); + bool Assign(unsigned int index, ValPtr element); // Note: does NOT Ref() the element! Remember to do so unless // the element was just created and thus has refcount 1. [[deprecated("Remove in v4.1. Assign an IntrusivePtr instead.")]] bool Assign(unsigned int index, Val* element) - { return Assign(index, {AdoptRef{}, element}); } + { return Assign(index, {zeek::AdoptRef{}, element}); } // Note: the following nullptr method can also go upon removing the above. void Assign(unsigned int index, std::nullptr_t) - { Assign(index, IntrusivePtr{}); } + { Assign(index, ValPtr{}); } [[deprecated("Remove in v4.1. Assign using integer index and IntrusivePtr element.")]] bool Assign(Val* index, Val* element) { return Assign(index->AsListVal()->Idx(0)->CoerceToUnsigned(), - {AdoptRef{}, element}); + {zeek::AdoptRef{}, element}); } /** @@ -1287,11 +1304,11 @@ public: * the element was the wrong type. */ bool AssignRepeat(unsigned int index, unsigned int how_many, - IntrusivePtr element); + ValPtr element); [[deprecated("Remove in v4.1. Assign an IntrusivePtr instead.")]] bool AssignRepeat(unsigned int index, unsigned int how_many, Val* element) - { return AssignRepeat(index, how_many, {NewRef{}, element}); } + { return AssignRepeat(index, how_many, {zeek::NewRef{}, element}); } // Add this value to the given value (if appropriate). // Returns true if succcessful. @@ -1303,7 +1320,7 @@ public: * @return The element at the given index or nullptr if the index * does not exist (it's greater than or equal to vector's current size). */ - const IntrusivePtr& At(unsigned int index) const; + const ValPtr& At(unsigned int index) const; [[deprecated("Remove in v4.1. Use At().")]] Val* Lookup(unsigned int index) const @@ -1335,44 +1352,44 @@ public: * @return True if the element was inserted or false if the element was * the wrong type. */ - bool Insert(unsigned int index, IntrusivePtr element); + bool Insert(unsigned int index, ValPtr element); [[deprecated("Remove in v4.1. Insert an IntrusivePtr instead.")]] bool Insert(unsigned int index, Val* element) - { return Insert(index, {AdoptRef{}, element}); } + { return Insert(index, {zeek::AdoptRef{}, element}); } // Removes an element at a specific position. bool Remove(unsigned int index); protected: void ValDescribe(ODesc* d) const override; - IntrusivePtr DoClone(CloneState* state) override; + ValPtr DoClone(CloneState* state) override; }; // Checks the given value for consistency with the given type. If an // exact match, returns it. If promotable, returns the promoted version. // If not a match, generates an error message and return nil. If is_init is // true, then the checking is done in the context of an initialization. -extern IntrusivePtr check_and_promote(IntrusivePtr v, - const zeek::Type* t, bool is_init, - const Location* expr_location = nullptr); +extern ValPtr check_and_promote( + ValPtr v, const zeek::Type* t, bool is_init, + const zeek::detail::Location* expr_location = nullptr); extern bool same_val(const Val* v1, const Val* v2); extern bool same_atomic_val(const Val* v1, const Val* v2); extern bool is_atomic_val(const Val* v); extern void describe_vals(const val_list* vals, ODesc* d, int offset=0); -extern void describe_vals(const std::vector>& vals, +extern void describe_vals(const std::vector& vals, ODesc* d, size_t offset = 0); extern void delete_vals(val_list* vals); // True if the given Val* has a vector type. inline bool is_vector(Val* v) { return v->GetType()->Tag() == zeek::TYPE_VECTOR; } -inline bool is_vector(const IntrusivePtr& v) { return is_vector(v.get()); } +inline bool is_vector(const ValPtr& v) { return is_vector(v.get()); } // Returns v casted to type T if the type supports that. Returns null if not. // // Note: This implements the script-level cast operator. -extern IntrusivePtr cast_value_to_type(Val* v, zeek::Type* t); +extern ValPtr cast_value_to_type(Val* v, zeek::Type* t); // Returns true if v can be casted to type T. If so, check_and_cast() will // succeed as well. @@ -1385,3 +1402,26 @@ extern bool can_cast_value_to_type(const Val* v, zeek::Type* t); // However, even this function returns true, casting may still fail for a // specific instance later. extern bool can_cast_value_to_type(const zeek::Type* s, zeek::Type* t); + +} + +using Val [[deprecated("Remove in v4.1. Use zeek::Val instead.")]] = zeek::Val; +using PortVal [[deprecated("Remove in v4.1. Use zeek::PortVal instead.")]] = zeek::PortVal; +using AddrVal [[deprecated("Remove in v4.1. Use zeek::AddrVal instead.")]] = zeek::AddrVal; +using SubNetVal [[deprecated("Remove in v4.1. Use zeek::SubNetVal instead.")]] = zeek::SubNetVal; +using PatternVal [[deprecated("Remove in v4.1. Use zeek::PatternVal instead.")]] = zeek::PatternVal; +using TableVal [[deprecated("Remove in v4.1. Use zeek::TableVal instead.")]] = zeek::TableVal; +using TableValTimer [[deprecated("Remove in v4.1. Use zeek::TableVal instead.")]] = zeek::TableValTimer; +using RecordVal [[deprecated("Remove in v4.1. Use zeek::RecordVal instead.")]] = zeek::RecordVal; +using ListVal [[deprecated("Remove in v4.1. Use zeek::ListVal instead.")]] = zeek::ListVal; +using StringVal [[deprecated("Remove in v4.1. Use zeek::StringVal instead.")]] = zeek::StringVal; +using EnumVal [[deprecated("Remove in v4.1. Use zeek::EnumVal instead.")]] = zeek::EnumVal; +using VectorVal [[deprecated("Remove in v4.1. Use zeek::VectorVal instead.")]] = zeek::VectorVal; +using TableEntryVal [[deprecated("Remove in v4.1. Use zeek::TableEntryVal instead.")]] = zeek::TableEntryVal; +using TimeVal [[deprecated("Remove in v4.1. Use zeek::TimeVal instead.")]] = zeek::TimeVal; +using DoubleVal [[deprecated("Remove in v4.1. Use zeek::DoubleVal instead.")]] = zeek::DoubleVal; +using IntervalVal [[deprecated("Remove in v4.1. Use zeek::IntervalVal instead.")]] = zeek::IntervalVal; +using ValManager [[deprecated("Remove in v4.1. Use zeek::ValManager instead.")]] = zeek::ValManager; + +// Alias for zeek::val_mgr. +extern zeek::ValManager*& val_mgr [[deprecated("Remove in v4.1. Use zeek::val_mgr instead.")]]; diff --git a/src/Var.cc b/src/Var.cc index 6bed3934a4..baa4c0dae7 100644 --- a/src/Var.cc +++ b/src/Var.cc @@ -19,8 +19,9 @@ using namespace zeek::detail; -static IntrusivePtr init_val(zeek::detail::Expr* init, const zeek::Type* t, - IntrusivePtr aggr) +static zeek::ValPtr init_val(zeek::detail::Expr* init, + const zeek::Type* t, + zeek::ValPtr aggr) { try { @@ -32,9 +33,9 @@ static IntrusivePtr init_val(zeek::detail::Expr* init, const zeek::Type* t, } } -static bool add_prototype(const IntrusivePtr& id, zeek::Type* t, - std::vector>* attrs, - const IntrusivePtr& init) +static bool add_prototype(const zeek::detail::IDPtr& id, zeek::Type* t, + std::vector* attrs, + const zeek::detail::ExprPtr& init) { if ( ! zeek::IsFunc(id->GetType()->Tag()) ) return false; @@ -110,10 +111,10 @@ static bool add_prototype(const IntrusivePtr& id, zeek::Type* return true; } -static void make_var(const IntrusivePtr& id, IntrusivePtr t, +static void make_var(const zeek::detail::IDPtr& id, zeek::TypePtr t, zeek::detail::InitClass c, - IntrusivePtr init, - std::unique_ptr>> attr, + zeek::detail::ExprPtr init, + std::unique_ptr> attr, decl_type dt, bool do_init) { @@ -121,7 +122,7 @@ static void make_var(const IntrusivePtr& id, IntrusivePtrIsRedefinable() || (! init && attr && ! zeek::IsFunc(id->GetType()->Tag())) ) { - BroObj* redef_obj = init ? (BroObj*) init.get() : (BroObj*) t.get(); + zeek::Obj* redef_obj = init ? (zeek::Obj*) init.get() : (zeek::Obj*) t.get(); if ( dt != VAR_REDEF ) id->Warn("redefinition requires \"redef\"", redef_obj, true); } @@ -202,7 +203,7 @@ static void make_var(const IntrusivePtr& id, IntrusivePtrSetType(t); if ( attr ) - id->AddAttrs(make_intrusive(std::move(*attr), t, false, id->IsGlobal())); + id->AddAttrs(zeek::make_intrusive(std::move(*attr), t, false, id->IsGlobal())); if ( init ) { @@ -243,26 +244,27 @@ static void make_var(const IntrusivePtr& id, IntrusivePtr aggr; + zeek::ValPtr aggr; if ( t->Tag() == zeek::TYPE_RECORD ) { - aggr = make_intrusive(cast_intrusive(t)); + aggr = zeek::make_intrusive(zeek::cast_intrusive(t)); if ( init && t ) // Have an initialization and type is not deduced. - init = make_intrusive(std::move(init), - IntrusivePtr{NewRef{}, t->AsRecordType()}); + init = zeek::make_intrusive( + std::move(init), + zeek::IntrusivePtr{zeek::NewRef{}, t->AsRecordType()}); } else if ( t->Tag() == zeek::TYPE_TABLE ) - aggr = make_intrusive(cast_intrusive(t), + aggr = zeek::make_intrusive(zeek::cast_intrusive(t), id->GetAttrs()); else if ( t->Tag() == zeek::TYPE_VECTOR ) - aggr = make_intrusive(cast_intrusive(t)); + aggr = zeek::make_intrusive(zeek::cast_intrusive(t)); - IntrusivePtr v; + zeek::ValPtr v; if ( init ) { @@ -304,24 +306,27 @@ static void make_var(const IntrusivePtr& id, IntrusivePtr> inits; - auto f = make_intrusive(id, nullptr, inits, 0, 0); - id->SetVal(make_intrusive(std::move(f))); + std::vector inits; + auto f = zeek::make_intrusive(id, nullptr, inits, 0, 0); + id->SetVal(zeek::make_intrusive(std::move(f))); } } -void add_global(const IntrusivePtr& id, IntrusivePtr t, - zeek::detail::InitClass c, IntrusivePtr init, - std::unique_ptr>> attr, - decl_type dt) +void add_global( + const zeek::detail::IDPtr& id, + zeek::TypePtr t, + zeek::detail::InitClass c, zeek::detail::ExprPtr init, + std::unique_ptr> attr, + decl_type dt) { make_var(id, std::move(t), c, std::move(init), std::move(attr), dt, true); } -IntrusivePtr add_local(IntrusivePtr id, IntrusivePtr t, - zeek::detail::InitClass c, IntrusivePtr init, - std::unique_ptr>> attr, - decl_type dt) +zeek::detail::StmtPtr add_local( + zeek::detail::IDPtr id, zeek::TypePtr t, + zeek::detail::InitClass c, zeek::detail::ExprPtr init, + std::unique_ptr> attr, + decl_type dt) { make_var(id, std::move(t), c, init, std::move(attr), dt, false); @@ -331,41 +336,42 @@ IntrusivePtr add_local(IntrusivePtr id, In id->Error("can't use += / -= for initializations of local variables"); // copy Location to the stack, because AssignExpr may free "init" - const Location location = init->GetLocationInfo() ? - *init->GetLocationInfo() : no_location; + const zeek::detail::Location location = init->GetLocationInfo() ? + *init->GetLocationInfo() : zeek::detail::no_location; - auto name_expr = make_intrusive(id, dt == VAR_CONST); - auto assign_expr = make_intrusive(std::move(name_expr), + auto name_expr = zeek::make_intrusive(id, dt == VAR_CONST); + auto assign_expr = zeek::make_intrusive(std::move(name_expr), std::move(init), 0, nullptr, id->GetAttrs()); - auto stmt = make_intrusive(std::move(assign_expr)); + auto stmt = zeek::make_intrusive(std::move(assign_expr)); stmt->SetLocationInfo(&location); return stmt; } else { - current_scope()->AddInit(std::move(id)); - return make_intrusive(); + zeek::detail::current_scope()->AddInit(std::move(id)); + return zeek::make_intrusive(); } } -extern IntrusivePtr add_and_assign_local(IntrusivePtr id, - IntrusivePtr init, - IntrusivePtr val) +extern zeek::detail::ExprPtr add_and_assign_local( + zeek::detail::IDPtr id, + zeek::detail::ExprPtr init, + zeek::ValPtr val) { make_var(id, nullptr, zeek::detail::INIT_FULL, init, nullptr, VAR_REGULAR, false); - auto name_expr = make_intrusive(std::move(id)); - return make_intrusive(std::move(name_expr), std::move(init), - false, std::move(val)); + auto name_expr = zeek::make_intrusive(std::move(id)); + return zeek::make_intrusive( + std::move(name_expr), std::move(init), false, std::move(val)); } -void add_type(zeek::detail::ID* id, IntrusivePtr t, - std::unique_ptr>> attr) +void add_type(zeek::detail::ID* id, zeek::TypePtr t, + std::unique_ptr> attr) { std::string new_type_name = id->Name(); std::string old_type_name = t->GetName(); - IntrusivePtr tnew; + zeek::TypePtr tnew; if ( (t->Tag() == zeek::TYPE_RECORD || t->Tag() == zeek::TYPE_ENUM) && old_type_name.empty() ) @@ -386,7 +392,7 @@ void add_type(zeek::detail::ID* id, IntrusivePtr t, id->MakeType(); if ( attr ) - id->SetAttrs(make_intrusive(std::move(*attr), tnew, false, false)); + id->SetAttrs(zeek::make_intrusive(std::move(*attr), tnew, false, false)); } static void transfer_arg_defaults(zeek::RecordType* args, zeek::RecordType* recv) @@ -403,10 +409,10 @@ static void transfer_arg_defaults(zeek::RecordType* args, zeek::RecordType* recv if ( ! recv_i->attrs ) { - std::vector> a{def}; - recv_i->attrs = make_intrusive(std::move(a), - recv_i->type, - true, false); + std::vector a{def}; + recv_i->attrs = zeek::make_intrusive(std::move(a), + recv_i->type, + true, false); } else if ( ! recv_i->attrs->Find(zeek::detail::ATTR_DEFAULT) ) @@ -414,7 +420,7 @@ static void transfer_arg_defaults(zeek::RecordType* args, zeek::RecordType* recv } } -static zeek::detail::Attr* find_attr(const std::vector>* al, +static zeek::detail::Attr* find_attr(const std::vector* al, zeek::detail::AttrTag tag) { if ( ! al ) @@ -462,10 +468,10 @@ static bool canonical_arg_types_match(const zeek::FuncType* decl, const zeek::Fu return true; } -void begin_func(IntrusivePtr id, const char* module_name, +void begin_func(zeek::detail::IDPtr id, const char* module_name, zeek::FunctionFlavor flavor, bool is_redef, - IntrusivePtr t, - std::unique_ptr>> attrs) + zeek::FuncTypePtr t, + std::unique_ptr> attrs) { if ( flavor == zeek::FUNC_FLAVOR_EVENT ) { @@ -562,7 +568,7 @@ void begin_func(IntrusivePtr id, const char* module_name, else id->SetType(t); - push_scope(std::move(id), std::move(attrs)); + zeek::detail::push_scope(std::move(id), std::move(attrs)); const auto& args = t->Params(); int num_args = args->NumFields(); @@ -570,26 +576,26 @@ void begin_func(IntrusivePtr id, const char* module_name, for ( int i = 0; i < num_args; ++i ) { zeek::TypeDecl* arg_i = args->FieldDecl(i); - auto arg_id = lookup_ID(arg_i->id, module_name); + auto arg_id = zeek::detail::lookup_ID(arg_i->id, module_name); if ( arg_id && ! arg_id->IsGlobal() ) arg_id->Error("argument name used twice"); - arg_id = install_ID(arg_i->id, module_name, false, false); + arg_id = zeek::detail::install_ID(arg_i->id, module_name, false, false); arg_id->SetType(arg_i->type); if ( prototype ) arg_id->SetOffset(prototype->offsets[i]); } - if ( zeek::detail::Attr* depr_attr = find_attr(current_scope()->Attrs().get(), + if ( zeek::detail::Attr* depr_attr = find_attr(zeek::detail::current_scope()->Attrs().get(), zeek::detail::ATTR_DEPRECATED) ) - current_scope()->GetID()->MakeDeprecated(depr_attr->GetExpr()); + zeek::detail::current_scope()->GetID()->MakeDeprecated(depr_attr->GetExpr()); } class OuterIDBindingFinder : public TraversalCallback { public: - OuterIDBindingFinder(Scope* s) + OuterIDBindingFinder(zeek::detail::Scope* s) { scopes.emplace_back(s); } @@ -597,7 +603,7 @@ public: TraversalCode PreExpr(const zeek::detail::Expr*) override; TraversalCode PostExpr(const zeek::detail::Expr*) override; - std::vector scopes; + std::vector scopes; std::vector outer_id_references; }; @@ -636,9 +642,10 @@ TraversalCode OuterIDBindingFinder::PostExpr(const zeek::detail::Expr* expr) return TC_CONTINUE; } -void end_func(IntrusivePtr body) +void end_func(zeek::detail::StmtPtr body) { - auto ingredients = std::make_unique(pop_scope(), std::move(body)); + auto ingredients = std::make_unique(zeek::detail::pop_scope(), + std::move(body)); if ( ingredients->id->HasVal() ) ingredients->id->GetVal()->AsFunc()->AddBody( @@ -648,14 +655,14 @@ void end_func(IntrusivePtr body) ingredients->priority); else { - auto f = make_intrusive( + auto f = zeek::make_intrusive( ingredients->id, ingredients->body, ingredients->inits, ingredients->frame_size, ingredients->priority); - ingredients->id->SetVal(make_intrusive(std::move(f))); + ingredients->id->SetVal(zeek::make_intrusive(std::move(f))); ingredients->id->SetConst(); } @@ -666,12 +673,12 @@ void end_func(IntrusivePtr body) ingredients.release(); } -Val* internal_val(const char* name) +zeek::Val* internal_val(const char* name) { return zeek::id::find_val(name).get(); } -id_list gather_outer_ids(Scope* scope, zeek::detail::Stmt* body) +id_list gather_outer_ids(zeek::detail::Scope* scope, zeek::detail::Stmt* body) { OuterIDBindingFinder cb(scope); body->Traverse(&cb); @@ -691,20 +698,20 @@ id_list gather_outer_ids(Scope* scope, zeek::detail::Stmt* body) return idl; } -Val* internal_const_val(const char* name) +zeek::Val* internal_const_val(const char* name) { return zeek::id::find_const(name).get(); } -Val* opt_internal_val(const char* name) +zeek::Val* opt_internal_val(const char* name) { - const auto& id = lookup_ID(name, GLOBAL_MODULE_NAME); + const auto& id = zeek::detail::lookup_ID(name, GLOBAL_MODULE_NAME); return id ? id->GetVal().get() : nullptr; } double opt_internal_double(const char* name) { - const auto& id = lookup_ID(name, GLOBAL_MODULE_NAME); + const auto& id = zeek::detail::lookup_ID(name, GLOBAL_MODULE_NAME); if ( ! id ) return 0.0; const auto& v = id->GetVal(); return v ? v->InternalDouble() : 0.0; @@ -712,7 +719,7 @@ double opt_internal_double(const char* name) bro_int_t opt_internal_int(const char* name) { - const auto& id = lookup_ID(name, GLOBAL_MODULE_NAME); + const auto& id = zeek::detail::lookup_ID(name, GLOBAL_MODULE_NAME); if ( ! id ) return 0; const auto& v = id->GetVal(); return v ? v->InternalInt() : 0; @@ -720,44 +727,44 @@ bro_int_t opt_internal_int(const char* name) bro_uint_t opt_internal_unsigned(const char* name) { - const auto& id = lookup_ID(name, GLOBAL_MODULE_NAME); + const auto& id = zeek::detail::lookup_ID(name, GLOBAL_MODULE_NAME); if ( ! id ) return 0; const auto& v = id->GetVal(); return v ? v->InternalUnsigned() : 0; } -StringVal* opt_internal_string(const char* name) +zeek::StringVal* opt_internal_string(const char* name) { - const auto& id = lookup_ID(name, GLOBAL_MODULE_NAME); + const auto& id = zeek::detail::lookup_ID(name, GLOBAL_MODULE_NAME); if ( ! id ) return nullptr; const auto& v = id->GetVal(); return v ? v->AsStringVal() : nullptr; } -TableVal* opt_internal_table(const char* name) +zeek::TableVal* opt_internal_table(const char* name) { - const auto& id = lookup_ID(name, GLOBAL_MODULE_NAME); + const auto& id = zeek::detail::lookup_ID(name, GLOBAL_MODULE_NAME); if ( ! id ) return nullptr; const auto& v = id->GetVal(); return v ? v->AsTableVal() : nullptr; } -ListVal* internal_list_val(const char* name) +zeek::ListVal* internal_list_val(const char* name) { - const auto& id = lookup_ID(name, GLOBAL_MODULE_NAME); + const auto& id = zeek::detail::lookup_ID(name, GLOBAL_MODULE_NAME); if ( ! id ) return nullptr; - Val* v = id->GetVal().get(); + zeek::Val* v = id->GetVal().get(); if ( v ) { if ( v->GetType()->Tag() == zeek::TYPE_LIST ) - return (ListVal*) v; + return (zeek::ListVal*) v; else if ( v->GetType()->IsSet() ) { - TableVal* tv = v->AsTableVal(); + zeek::TableVal* tv = v->AsTableVal(); auto lv = tv->ToPureListVal(); return lv.release(); } @@ -774,7 +781,7 @@ zeek::Type* internal_type(const char* name) return zeek::id::find_type(name).get(); } -Func* internal_func(const char* name) +zeek::Func* internal_func(const char* name) { const auto& v = zeek::id::find_val(name); diff --git a/src/Var.h b/src/Var.h index da1adb8a1b..25278c7b8c 100644 --- a/src/Var.h +++ b/src/Var.h @@ -6,57 +6,63 @@ #include "ID.h" #include "Type.h" -class Scope; class EventHandlerPtr; -class StringVal; -class TableVal; -class ListVal; +ZEEK_FORWARD_DECLARE_NAMESPACED(StringVal, zeek); +ZEEK_FORWARD_DECLARE_NAMESPACED(TableVal, zeek); +ZEEK_FORWARD_DECLARE_NAMESPACED(ListVal, zeek); ZEEK_FORWARD_DECLARE_NAMESPACED(FuncType, zeek); ZEEK_FORWARD_DECLARE_NAMESPACED(Stmt, zeek::detail); ZEEK_FORWARD_DECLARE_NAMESPACED(Expr, zeek::detail); +ZEEK_FORWARD_DECLARE_NAMESPACED(Scope, zeek::detail); + +namespace zeek::detail { +using StmtPtr = zeek::IntrusivePtr; +} typedef enum { VAR_REGULAR, VAR_CONST, VAR_REDEF, VAR_OPTION, } decl_type; -extern void add_global(const IntrusivePtr& id, - IntrusivePtr t, +extern void add_global(const zeek::detail::IDPtr& id, + zeek::TypePtr t, zeek::detail::InitClass c, - IntrusivePtr init, - std::unique_ptr>> attr, + zeek::detail::ExprPtr init, + std::unique_ptr> attr, decl_type dt); -extern IntrusivePtr add_local(IntrusivePtr id, - IntrusivePtr t, - zeek::detail::InitClass c, - IntrusivePtr init, - std::unique_ptr>> attr, - decl_type dt); +extern zeek::detail::StmtPtr add_local( + zeek::detail::IDPtr id, + zeek::TypePtr t, + zeek::detail::InitClass c, + zeek::detail::ExprPtr init, + std::unique_ptr> attr, + decl_type dt); -extern IntrusivePtr add_and_assign_local(IntrusivePtr id, - IntrusivePtr init, - IntrusivePtr val = nullptr); +extern zeek::detail::ExprPtr add_and_assign_local( + zeek::detail::IDPtr id, + zeek::detail::ExprPtr init, + zeek::ValPtr val = nullptr); -extern void add_type(zeek::detail::ID* id, IntrusivePtr t, - std::unique_ptr>> attr); +extern void add_type(zeek::detail::ID* id, zeek::TypePtr t, + std::unique_ptr> attr); -extern void begin_func(IntrusivePtr id, const char* module_name, +extern void begin_func(zeek::detail::IDPtr id, const char* module_name, zeek::FunctionFlavor flavor, bool is_redef, - IntrusivePtr t, - std::unique_ptr>> attrs = nullptr); + zeek::FuncTypePtr t, + std::unique_ptr> attrs = nullptr); -extern void end_func(IntrusivePtr body); +extern void end_func(zeek::detail::StmtPtr body); // Gather all IDs referenced inside a body that aren't part of a given scope. -extern id_list gather_outer_ids(Scope* scope, zeek::detail::Stmt* body); +extern id_list gather_outer_ids(zeek::detail::Scope* scope, zeek::detail::Stmt* body); [[deprecated("Remove in v4.1. Use zeek::id::find_val().")]] -extern Val* internal_val(const char* name); +extern zeek::Val* internal_val(const char* name); [[deprecated("Remove in v4.1. Use zeek::id::find_const().")]] -extern Val* internal_const_val(const char* name); // internal error if not const +extern zeek::Val* internal_const_val(const char* name); // internal error if not const [[deprecated("Remove in v4.1. Use zeek::id::find() or zeek::id::find_val().")]] -extern Val* opt_internal_val(const char* name); // returns nil if not defined +extern zeek::Val* opt_internal_val(const char* name); // returns nil if not defined [[deprecated("Remove in v4.1. Use zeek::id::find() or zeek::id::find_val().")]] extern double opt_internal_double(const char* name); @@ -68,19 +74,19 @@ extern bro_int_t opt_internal_int(const char* name); extern bro_uint_t opt_internal_unsigned(const char* name); [[deprecated("Remove in v4.1. Use zeek::id::find() or zeek::id::find_val().")]] -extern StringVal* opt_internal_string(const char* name); +extern zeek::StringVal* opt_internal_string(const char* name); [[deprecated("Remove in v4.1. Use zeek::id::find() or zeek::id::find_val().")]] -extern TableVal* opt_internal_table(const char* name); // nil if not defined +extern zeek::TableVal* opt_internal_table(const char* name); // nil if not defined [[deprecated("Remove in v4.1. Use zeek::id::find(), zeek::id::find_val(), and/or TableVal::ToPureListVal().")]] -extern ListVal* internal_list_val(const char* name); +extern zeek::ListVal* internal_list_val(const char* name); [[deprecated("Remove in v4.1. Use zeek::id::find_type().")]] extern zeek::Type* internal_type(const char* name); [[deprecated("Remove in v4.1. Use zeek::id::find_func().")]] -extern Func* internal_func(const char* name); +extern zeek::Func* internal_func(const char* name); [[deprecated("Remove in v4.1. Use event_registry->Register().")]] extern EventHandlerPtr internal_handler(const char* name); diff --git a/src/ZeekArgs.cc b/src/ZeekArgs.cc index e9c4b36412..3f480427ef 100644 --- a/src/ZeekArgs.cc +++ b/src/ZeekArgs.cc @@ -1,5 +1,4 @@ #include "ZeekArgs.h" -#include "IntrusivePtr.h" #include "Val.h" zeek::Args zeek::val_list_to_args(const val_list& vl) @@ -8,8 +7,7 @@ zeek::Args zeek::val_list_to_args(const val_list& vl) rval.reserve(vl.length()); for ( auto& v : vl ) - rval.emplace_back(AdoptRef{}, v); + rval.emplace_back(zeek::AdoptRef{}, v); return rval; } - diff --git a/src/ZeekArgs.h b/src/ZeekArgs.h index fbde15965c..6c54947de8 100644 --- a/src/ZeekArgs.h +++ b/src/ZeekArgs.h @@ -2,16 +2,15 @@ #pragma once +#include #include "BroList.h" -#include - -class Val; -template class IntrusivePtr; +ZEEK_FORWARD_DECLARE_NAMESPACED(Val, zeek); namespace zeek { -using Args = std::vector>; +template class IntrusivePtr; +using Args = std::vector>; /** * Converts a legacy-style argument list for use in modern Zeek function diff --git a/src/BroString.cc b/src/ZeekString.cc similarity index 71% rename from src/BroString.cc rename to src/ZeekString.cc index 2cd5059cc8..e03ff5b797 100644 --- a/src/BroString.cc +++ b/src/ZeekString.cc @@ -1,7 +1,7 @@ // See the file "COPYING" in the main distribution directory for copyright. #include "zeek-config.h" -#include "BroString.h" +#include "ZeekString.h" #include #include @@ -18,15 +18,17 @@ #define DEBUG_STR(msg) #endif -const int BroString::EXPANDED_STRING; -const int BroString::BRO_STRING_LITERAL; +namespace zeek { + +constexpr int String::EXPANDED_STRING; +constexpr int String::BRO_STRING_LITERAL; // This constructor forces the user to specify arg_final_NUL. When str // is a *normal* NUL-terminated string, make arg_n == strlen(str) and // arg_final_NUL == 1; when str is a sequence of n bytes, make // arg_final_NUL == 0. -BroString::BroString(bool arg_final_NUL, byte_vec str, int arg_n) +String::String(bool arg_final_NUL, byte_vec str, int arg_n) { b = str; n = arg_n; @@ -34,27 +36,27 @@ BroString::BroString(bool arg_final_NUL, byte_vec str, int arg_n) use_free_to_delete = false; } -BroString::BroString(const u_char* str, int arg_n, bool add_NUL) : BroString() +String::String(const u_char* str, int arg_n, bool add_NUL) : String() { Set(str, arg_n, add_NUL); } -BroString::BroString(const char* str) : BroString() +String::String(const char* str) : String() { Set(str); } -BroString::BroString(const std::string &str) : BroString() +String::String(const std::string &str) : String() { Set(str); } -BroString::BroString(const BroString& bs) : BroString() +String::String(const String& bs) : String() { *this = bs; } -BroString::BroString() +String::String() { b = nullptr; n = 0; @@ -62,7 +64,7 @@ BroString::BroString() use_free_to_delete = false; } -void BroString::Reset() +void String::Reset() { if ( use_free_to_delete ) free(b); @@ -75,7 +77,7 @@ void BroString::Reset() use_free_to_delete = false; } -const BroString& BroString::operator=(const BroString &bs) +const String& String::operator=(const String &bs) { Reset(); n = bs.n; @@ -89,17 +91,17 @@ const BroString& BroString::operator=(const BroString &bs) return *this; } -bool BroString::operator==(const BroString &bs) const +bool String::operator==(const String &bs) const { return Bstr_eq(this, &bs); } -bool BroString::operator<(const BroString &bs) const +bool String::operator<(const String &bs) const { return Bstr_cmp(this, &bs) < 0; } -void BroString::Adopt(byte_vec bytes, int len) +void String::Adopt(byte_vec bytes, int len) { Reset(); @@ -111,7 +113,7 @@ void BroString::Adopt(byte_vec bytes, int len) n = len - final_NUL; } -void BroString::Set(const u_char* str, int len, bool add_NUL) +void String::Set(const u_char* str, int len, bool add_NUL) { Reset(); @@ -126,7 +128,7 @@ void BroString::Set(const u_char* str, int len, bool add_NUL) use_free_to_delete = false; } -void BroString::Set(const char* str) +void String::Set(const char* str) { Reset(); @@ -137,7 +139,7 @@ void BroString::Set(const char* str) use_free_to_delete = false; } -void BroString::Set(const std::string& str) +void String::Set(const std::string& str) { Reset(); @@ -148,12 +150,12 @@ void BroString::Set(const std::string& str) use_free_to_delete = false; } -void BroString::Set(const BroString& str) +void String::Set(const String& str) { *this = str; } -const char* BroString::CheckString() const +const char* String::CheckString() const { void *nulTerm; if ( n == 0 ) @@ -176,7 +178,7 @@ const char* BroString::CheckString() const return (const char*) b; } -char* BroString::Render(int format, int* len) const +char* String::Render(int format, int* len) const { // Maxmimum character expansion is as \xHH, so a factor of 4. char* s = new char[n*4 + 1]; // +1 is for final '\0' @@ -234,7 +236,7 @@ char* BroString::Render(int format, int* len) const return s; } -std::ostream& BroString::Render(std::ostream &os, int format) const +std::ostream& String::Render(std::ostream &os, int format) const { char* tmp = Render(format); os << tmp; @@ -242,9 +244,9 @@ std::ostream& BroString::Render(std::ostream &os, int format) const return os; } -std::istream& BroString::Read(std::istream &is, int format) +std::istream& String::Read(std::istream &is, int format) { - if ( (format & BroString::ESC_SER) ) + if ( (format & String::ESC_SER) ) { int len; is >> len; // Get the length of the string @@ -268,19 +270,19 @@ std::istream& BroString::Read(std::istream &is, int format) return is; } -void BroString::ToUpper() +void String::ToUpper() { for ( int i = 0; i < n; ++i ) if ( islower(b[i]) ) b[i] = toupper(b[i]); } -unsigned int BroString::MemoryAllocation() const +unsigned int String::MemoryAllocation() const { return padded_sizeof(*this) + pad_size(n + final_NUL); } -BroString* BroString::GetSubstring(int start, int len) const +String* String::GetSubstring(int start, int len) const { // This code used to live in zeek.bif's sub_bytes() routine. if ( start < 0 || start > n ) @@ -289,15 +291,15 @@ BroString* BroString::GetSubstring(int start, int len) const if ( len < 0 || len > n - start ) len = n - start; - return new BroString(&b[start], len, true); + return new String(&b[start], len, true); } -int BroString::FindSubstring(const BroString* s) const +int String::FindSubstring(const String* s) const { return strstr_n(n, b, s->Len(), s->Bytes()); } -BroString::Vec* BroString::Split(const BroString::IdxVec& indices) const +String::Vec* String::Split(const String::IdxVec& indices) const { unsigned int i; @@ -338,22 +340,22 @@ BroString::Vec* BroString::Split(const BroString::IdxVec& indices) const return result; } -VectorVal* BroString:: VecToPolicy(Vec* vec) +zeek::VectorVal* String:: VecToPolicy(Vec* vec) { - auto result = make_intrusive(zeek::id::string_vec); + auto result = zeek::make_intrusive(zeek::id::string_vec); for ( unsigned int i = 0; i < vec->size(); ++i ) { - BroString* string = (*vec)[i]; - auto val = make_intrusive(string->Len(), - (const char*) string->Bytes()); + String* string = (*vec)[i]; + auto val = zeek::make_intrusive(string->Len(), + (const char*) string->Bytes()); result->Assign(i+1, std::move(val)); } return result.release(); } -BroString::Vec* BroString::VecFromPolicy(VectorVal* vec) +String::Vec* String::VecFromPolicy(zeek::VectorVal* vec) { Vec* result = new Vec(); @@ -364,18 +366,18 @@ BroString::Vec* BroString::VecFromPolicy(VectorVal* vec) if ( ! v ) continue; - BroString* string = new BroString(*(v->AsString())); + String* string = new String(*(v->AsString())); result->push_back(string); } return result; } -char* BroString::VecToString(const Vec* vec) +char* String::VecToString(const Vec* vec) { std::string result("["); - for ( BroString::VecCIt it = vec->begin(); it != vec->end(); ++it ) + for ( String::VecCIt it = vec->begin(); it != vec->end(); ++it ) { result += (*it)->CheckString(); result += ","; @@ -386,22 +388,22 @@ char* BroString::VecToString(const Vec* vec) return strdup(result.c_str()); } -bool BroStringLenCmp::operator()(BroString * const& bst1, - BroString * const& bst2) +bool StringLenCmp::operator()(String * const& bst1, + String * const& bst2) { return _increasing ? (bst1->Len() < bst2->Len()) : (bst1->Len() > bst2->Len()); } -std::ostream& operator<<(std::ostream& os, const BroString& bs) +std::ostream& operator<<(std::ostream& os, const String& bs) { - char* tmp = bs.Render(BroString::EXPANDED_STRING); + char* tmp = bs.Render(String::EXPANDED_STRING); os << tmp; delete [] tmp; return os; } -int Bstr_eq(const BroString* s1, const BroString* s2) +int Bstr_eq(const String* s1, const String* s2) { if ( s1->Len() != s2->Len() ) return 0; @@ -409,7 +411,7 @@ int Bstr_eq(const BroString* s1, const BroString* s2) return memcmp(s1->Bytes(), s2->Bytes(), s1->Len()) == 0; } -int Bstr_cmp(const BroString* s1, const BroString* s2) +int Bstr_cmp(const String* s1, const String* s2) { int n = std::min(s1->Len(), s2->Len()); int cmp = memcmp(s1->Bytes(), s2->Bytes(), n); @@ -425,7 +427,7 @@ int Bstr_cmp(const BroString* s1, const BroString* s2) return 1; } -BroString* concatenate(std::vector& v) +String* concatenate(std::vector& v) { int n = v.size(); int len = 0; @@ -444,10 +446,10 @@ BroString* concatenate(std::vector& v) *b = '\0'; - return new BroString(true, (byte_vec) data, len); + return new String(true, (byte_vec) data, len); } -BroString* concatenate(BroString::CVec& v) +String* concatenate(String::CVec& v) { int n = v.size(); int len = 0; @@ -465,22 +467,24 @@ BroString* concatenate(BroString::CVec& v) } *b = '\0'; - return new BroString(true, (byte_vec) data, len); + return new String(true, (byte_vec) data, len); } -BroString* concatenate(BroString::Vec& v) +String* concatenate(String::Vec& v) { - BroString::CVec cv; + String::CVec cv; - for ( BroString::VecIt it = v.begin(); it != v.end(); ++it ) + for ( String::VecIt it = v.begin(); it != v.end(); ++it ) cv.push_back(*it); return concatenate(cv); } -void delete_strings(std::vector& v) +void delete_strings(std::vector& v) { for ( unsigned int i = 0; i < v.size(); ++i ) delete v[i]; v.clear(); } + +} // namespace zeek diff --git a/src/ZeekString.h b/src/ZeekString.h new file mode 100644 index 0000000000..0b0ab3db60 --- /dev/null +++ b/src/ZeekString.h @@ -0,0 +1,195 @@ +// See the file "COPYING" in the main distribution directory for copyright. + +#pragma once + +#include "zeek-config.h" + +#include +#include +#include + +#include + +// Forward declaration, for helper functions that convert (sub)string vectors +// to and from policy-level representations. +// +ZEEK_FORWARD_DECLARE_NAMESPACED(VectorVal, zeek); + +namespace zeek { + +typedef u_char* byte_vec; + +class String { +public: + typedef std::vector Vec; + typedef Vec::iterator VecIt; + typedef Vec::const_iterator VecCIt; + + typedef std::vector CVec; + typedef Vec::iterator CVecIt; + typedef Vec::const_iterator CVecCIt; + + // IdxVecs are vectors of indices of characters in a string. + typedef std::vector IdxVec; + typedef IdxVec::iterator IdxVecIt; + typedef IdxVec::const_iterator IdxVecCIt; + + // Constructors creating internal copies of the data passed in. + String(const u_char* str, int arg_n, bool add_NUL); + explicit String(const char* str); + explicit String(const std::string& str); + String(const String& bs); + + // Constructor that takes owernship of the vector passed in. + String(bool arg_final_NUL, byte_vec str, int arg_n); + + String(); + ~String() { Reset(); } + + const String& operator=(const String& bs); + bool operator==(const String& bs) const; + bool operator<(const String& bs) const; + + byte_vec Bytes() const { return b; } + int Len() const { return n; } + + // Releases the string's current contents, if any, and + // adopts the byte vector of given length. The string will + // manage the memory occupied by the string afterwards. + // + void Adopt(byte_vec bytes, int len); + + // Various flavors of methods that release the string's + // current contents, if any, and then set the string's + // contents to a copy of the string given by the arguments. + // + void Set(const u_char* str, int len, bool add_NUL=true); + void Set(const char* str); + void Set(const std::string& str); + void Set(const String &str); + + void SetUseFreeToDelete(int use_it) + { use_free_to_delete = use_it; } + + const char* CheckString() const; + + enum render_style { + ESC_NONE = 0, + ESC_ESC = (1 << 1), // '\' -> "\\" + ESC_QUOT = (1 << 2), // '"' -> "\"", ''' -> "\'" + ESC_HEX = (1 << 3), // Not in [32, 126]? -> "\xXX" + ESC_DOT = (1 << 4), // Not in [32, 126]? -> "." + + // For serialization: ' ' + ESC_SER = (1 << 7), + }; + + static constexpr int EXPANDED_STRING = // the original style + ESC_HEX; + + static constexpr int BRO_STRING_LITERAL = // as in a Bro string literal + ESC_ESC | ESC_QUOT | ESC_HEX; + + // Renders a string into a newly allocated character array that + // you have to delete[]. You can combine the render styles given + // above to achieve the representation you desire. If you pass a + // pointer to an integer as the final argument, you'll receive the + // entire length of the resulting char* in it. + // + // Note that you need to delete[] the resulting string. + // + char* Render(int format = EXPANDED_STRING, int* len = nullptr) const; + + // Similar to the above, but useful for output streams. + // Also more useful for debugging purposes since no deallocation + // is required on your part here. + // + std::ostream& Render(std::ostream& os, int format = ESC_SER) const; + + // Reads a string from an input stream. Unless you use a render + // style combination that uses ESC_SER, note that the streams + // will consider whitespace as a field delimiter. + // + std::istream& Read(std::istream& is, int format = ESC_SER); + + // XXX Fix redundancy: strings.bif implements both to_lower + // XXX and to_upper; the latter doesn't use String::ToUpper(). + void ToUpper(); + + unsigned int MemoryAllocation() const; + + // Returns new string containing the substring of this string, + // starting at @start >= 0 for going up to @length elements, + // A negative @length means "until end of string". Other invalid + // values result in a return value of 0. + // + String* GetSubstring(int start, int length) const; + + // Returns the start index of s in this string, counting from 0. + // If s is not found, -1 is returned. + // + int FindSubstring(const String* s) const; + + // Splits the string into substrings, taking all the indices in + // the given vector as cutting points. The vector does not need + // to be sorted, and can have multiple entries. Out-of-bounds + // indices are ignored. All returned strings are newly allocated. + // + Vec* Split(const IdxVec& indices) const; + + // Helper functions for vectors: + static zeek::VectorVal* VecToPolicy(Vec* vec); + static Vec* VecFromPolicy(zeek::VectorVal* vec); + static char* VecToString(const Vec* vec); + +protected: + void Reset(); + + byte_vec b; + int n; + bool final_NUL; // whether we have added a final NUL + bool use_free_to_delete; // free() vs. operator delete +}; + +// A comparison class that sorts pointers to String's according to +// the length of the pointed-to strings. Sort order can be specified +// through the constructor. +// +class StringLenCmp { +public: + explicit StringLenCmp(bool increasing = true) { _increasing = increasing; } + bool operator()(String*const& bst1, String*const& bst2); + + private: + unsigned int _increasing; +}; + +// Default output stream operator, using rendering mode EXPANDED_STRING. +std::ostream& operator<<(std::ostream& os, const String& bs); + +extern int Bstr_eq(const String* s1, const String* s2); +extern int Bstr_cmp(const String* s1, const String* s2); + +// A data_chunk_t specifies a length-delimited constant string. It is +// often used for substrings of other String's to avoid memory copy, +// which would be necessary if String were used. Unlike String, +// the string should not be deallocated on destruction. +// +// "BroConstString" might be a better name here. + +struct data_chunk_t { + int length; + const char* data; +}; + +extern String* concatenate(std::vector& v); +extern String* concatenate(String::Vec& v); +extern String* concatenate(String::CVec& v); +extern void delete_strings(std::vector& v); + +} // namespace zeek + +using BroString [[deprecated("Remove in v4.1. Use zeek::String instead.")]] = zeek::String; +using BroStringLenCmp [[deprecated("Remove in v4.1. Use zeek::StringLenCmp instead.")]] = zeek::StringLenCmp; +using byte_vec [[deprecated("Remove in v4.1. Use zeek::byte_vec instead.")]] = zeek::byte_vec; +using data_chunk_t [[deprecated("Remove in v4.1. Use zeek::data_chunk_t instead.")]] = zeek::data_chunk_t; diff --git a/src/analyzer/Analyzer.cc b/src/analyzer/Analyzer.cc index 76bad9c789..7971ea9eb6 100644 --- a/src/analyzer/Analyzer.cc +++ b/src/analyzer/Analyzer.cc @@ -7,7 +7,7 @@ #include "binpac.h" #include "analyzer/protocol/pia/PIA.h" -#include "../BroString.h" +#include "../ZeekString.h" #include "../Event.h" namespace analyzer { @@ -702,7 +702,7 @@ void Analyzer::ProtocolConfirmation(Tag arg_tag) return; const auto& tval = arg_tag ? arg_tag.AsVal() : tag.AsVal(); - mgr.Enqueue(protocol_confirmation, ConnVal(), tval, val_mgr->Count(id)); + mgr.Enqueue(protocol_confirmation, ConnVal(), tval, zeek::val_mgr->Count(id)); } void Analyzer::ProtocolViolation(const char* reason, const char* data, int len) @@ -710,21 +710,21 @@ void Analyzer::ProtocolViolation(const char* reason, const char* data, int len) if ( ! protocol_violation ) return; - IntrusivePtr r; + zeek::StringValPtr r; if ( data && len ) { const char *tmp = copy_string(reason); - r = make_intrusive(fmt("%s [%s%s]", tmp, - fmt_bytes(data, min(40, len)), - len > 40 ? "..." : "")); + r = zeek::make_intrusive(fmt("%s [%s%s]", tmp, + fmt_bytes(data, min(40, len)), + len > 40 ? "..." : "")); delete [] tmp; } else - r = make_intrusive(reason); + r = zeek::make_intrusive(reason); const auto& tval = tag.AsVal(); - mgr.Enqueue(protocol_violation, ConnVal(), tval, val_mgr->Count(id), std::move(r)); + mgr.Enqueue(protocol_violation, ConnVal(), tval, zeek::val_mgr->Count(id), std::move(r)); } void Analyzer::AddTimer(analyzer_timer_func timer, double t, @@ -783,18 +783,18 @@ unsigned int Analyzer::MemoryAllocation() const return mem; } -void Analyzer::UpdateConnVal(RecordVal *conn_val) +void Analyzer::UpdateConnVal(zeek::RecordVal *conn_val) { LOOP_OVER_CHILDREN(i) (*i)->UpdateConnVal(conn_val); } -RecordVal* Analyzer::BuildConnVal() +zeek::RecordVal* Analyzer::BuildConnVal() { return conn->ConnVal()->Ref()->AsRecordVal(); } -const IntrusivePtr& Analyzer::ConnVal() +const zeek::RecordValPtr& Analyzer::ConnVal() { return conn->ConnVal(); } @@ -804,10 +804,10 @@ void Analyzer::Event(EventHandlerPtr f, const char* name) conn->Event(f, this, name); } -void Analyzer::Event(EventHandlerPtr f, Val* v1, Val* v2) +void Analyzer::Event(EventHandlerPtr f, zeek::Val* v1, zeek::Val* v2) { - IntrusivePtr val1{AdoptRef{}, v1}; - IntrusivePtr val2{AdoptRef{}, v2}; + zeek::IntrusivePtr val1{zeek::AdoptRef{}, v1}; + zeek::IntrusivePtr val2{zeek::AdoptRef{}, v2}; if ( f ) conn->EnqueueEvent(f, this, conn->ConnVal(), std::move(val1), std::move(val2)); @@ -926,12 +926,12 @@ void TransportLayerAnalyzer::Done() } void TransportLayerAnalyzer::SetContentsFile(unsigned int /* direction */, - IntrusivePtr /* f */) + BroFilePtr /* f */) { reporter->Error("analyzer type does not support writing to a contents file"); } -IntrusivePtr TransportLayerAnalyzer::GetContentsFile(unsigned int /* direction */) const +BroFilePtr TransportLayerAnalyzer::GetContentsFile(unsigned int /* direction */) const { reporter->Error("analyzer type does not support writing to a contents file"); return nullptr; @@ -941,8 +941,8 @@ void TransportLayerAnalyzer::PacketContents(const u_char* data, int len) { if ( packet_contents && len > 0 ) { - BroString* cbs = new BroString(data, len, true); - auto contents = make_intrusive(cbs); + zeek::String* cbs = new zeek::String(data, len, true); + auto contents = zeek::make_intrusive(cbs); EnqueueConnEvent(packet_contents, ConnVal(), std::move(contents)); } } diff --git a/src/analyzer/Analyzer.h b/src/analyzer/Analyzer.h index 76ef088633..99ab5f3a20 100644 --- a/src/analyzer/Analyzer.h +++ b/src/analyzer/Analyzer.h @@ -17,10 +17,16 @@ #include "../IntrusivePtr.h" class BroFile; +using BroFilePtr = zeek::IntrusivePtr; + class Rule; class Connection; class IP_Hdr; +namespace zeek { +using RecordValPtr = zeek::IntrusivePtr; +} + namespace analyzer { namespace tcp { class TCP_ApplicationAnalyzer; } @@ -543,20 +549,20 @@ public: * * @param conn_val The connenction value being updated. */ - virtual void UpdateConnVal(RecordVal *conn_val); + virtual void UpdateConnVal(zeek::RecordVal *conn_val); /** * Convenience function that forwards directly to * Connection::BuildConnVal(). */ [[deprecated("Remove in v4.1. Use ConnVal() instead.")]] - RecordVal* BuildConnVal(); + zeek::RecordVal* BuildConnVal(); /** * Convenience function that forwards directly to * Connection::ConnVal(). */ - const IntrusivePtr& ConnVal(); + const zeek::RecordValPtr& ConnVal(); /** * Convenience function that forwards directly to the corresponding @@ -569,7 +575,7 @@ public: * Connection::Event(). */ [[deprecated("Remove in v4.1. Use EnqueueConnEvent() instead (note it doesn't automatically ad the connection argument).")]] - void Event(EventHandlerPtr f, Val* v1, Val* v2 = nullptr); + void Event(EventHandlerPtr f, zeek::Val* v1, zeek::Val* v2 = nullptr); /** * Convenience function that forwards directly to @@ -603,8 +609,8 @@ public: */ template std::enable_if_t< - std::is_convertible_v< - std::tuple_element_t<0, std::tuple>, IntrusivePtr>> + std::is_convertible_v< + std::tuple_element_t<0, std::tuple>, zeek::ValPtr>> EnqueueConnEvent(EventHandlerPtr h, Args&&... args) { return EnqueueConnEvent(h, zeek::Args{std::forward(args)...}); } @@ -911,7 +917,7 @@ public: * @param f The file to record to. * */ - virtual void SetContentsFile(unsigned int direction, IntrusivePtr f); + virtual void SetContentsFile(unsigned int direction, BroFilePtr f); /** * Returns an associated contents file, if any. This must only be @@ -921,7 +927,7 @@ public: * @param direction One of the CONTENTS_* constants indicating which * direction the query is for. */ - virtual IntrusivePtr GetContentsFile(unsigned int direction) const; + virtual BroFilePtr GetContentsFile(unsigned int direction) const; /** * Associates a PIA with this analyzer. A PIA takes the diff --git a/src/analyzer/Manager.cc b/src/analyzer/Manager.cc index 343641d99c..6f19d07246 100644 --- a/src/analyzer/Manager.cc +++ b/src/analyzer/Manager.cc @@ -90,7 +90,7 @@ void Manager::InitPreScript() void Manager::InitPostScript() { - const auto& id = global_scope()->Find("Tunnel::vxlan_ports"); + const auto& id = zeek::detail::global_scope()->Find("Tunnel::vxlan_ports"); if ( ! (id && id->GetVal()) ) reporter->FatalError("Tunnel::vxlan_ports not defined"); @@ -154,7 +154,7 @@ bool Manager::EnableAnalyzer(const Tag& tag) return true; } -bool Manager::EnableAnalyzer(EnumVal* val) +bool Manager::EnableAnalyzer(zeek::EnumVal* val) { Component* p = Lookup(val); @@ -180,7 +180,7 @@ bool Manager::DisableAnalyzer(const Tag& tag) return true; } -bool Manager::DisableAnalyzer(EnumVal* val) +bool Manager::DisableAnalyzer(zeek::EnumVal* val) { Component* p = Lookup(val); @@ -220,7 +220,7 @@ bool Manager::IsEnabled(const Tag& tag) return p->Enabled(); } -bool Manager::IsEnabled(EnumVal* val) +bool Manager::IsEnabled(zeek::EnumVal* val) { Component* p = Lookup(val); @@ -231,7 +231,7 @@ bool Manager::IsEnabled(EnumVal* val) } -bool Manager::RegisterAnalyzerForPort(EnumVal* val, PortVal* port) +bool Manager::RegisterAnalyzerForPort(zeek::EnumVal* val, zeek::PortVal* port) { Component* p = Lookup(val); @@ -241,7 +241,7 @@ bool Manager::RegisterAnalyzerForPort(EnumVal* val, PortVal* port) return RegisterAnalyzerForPort(p->Tag(), port->PortType(), port->Port()); } -bool Manager::UnregisterAnalyzerForPort(EnumVal* val, PortVal* port) +bool Manager::UnregisterAnalyzerForPort(zeek::EnumVal* val, zeek::PortVal* port) { Component* p = Lookup(val); @@ -353,7 +353,7 @@ Manager::tag_set* Manager::LookupPort(TransportProto proto, uint32_t port, bool return l; } -Manager::tag_set* Manager::LookupPort(PortVal* val, bool add_if_not_found) +Manager::tag_set* Manager::LookupPort(zeek::PortVal* val, bool add_if_not_found) { return LookupPort(val->PortType(), val->Port(), add_if_not_found); } @@ -438,9 +438,9 @@ bool Manager::BuildInitialAnalyzerTree(Connection* conn) if ( tcp_contents && ! reass ) { - static auto tcp_content_delivery_ports_orig = zeek::id::find_val("tcp_content_delivery_ports_orig"); - static auto tcp_content_delivery_ports_resp = zeek::id::find_val("tcp_content_delivery_ports_resp"); - const auto& dport = val_mgr->Port(ntohs(conn->RespPort()), TRANSPORT_TCP); + static auto tcp_content_delivery_ports_orig = zeek::id::find_val("tcp_content_delivery_ports_orig"); + static auto tcp_content_delivery_ports_resp = zeek::id::find_val("tcp_content_delivery_ports_resp"); + const auto& dport = zeek::val_mgr->Port(ntohs(conn->RespPort()), TRANSPORT_TCP); if ( ! reass ) reass = (bool)tcp_content_delivery_ports_orig->FindOrDefault(dport); @@ -462,8 +462,8 @@ bool Manager::BuildInitialAnalyzerTree(Connection* conn) uint16_t resp_port = ntohs(conn->RespPort()); if ( resp_port == 22 || resp_port == 23 || resp_port == 513 ) { - static auto stp_skip_src = zeek::id::find_val("stp_skip_src"); - auto src = make_intrusive(conn->OrigAddr()); + static auto stp_skip_src = zeek::id::find_val("stp_skip_src"); + auto src = zeek::make_intrusive(conn->OrigAddr()); if ( ! stp_skip_src->FindOrDefault(src) ) tcp->AddChildAnalyzer(new stepping_stone::SteppingStone_Analyzer(conn), false); @@ -573,10 +573,10 @@ void Manager::ScheduleAnalyzer(const IPAddr& orig, const IPAddr& resp, ScheduleAnalyzer(orig, resp, resp_p, proto, tag, timeout); } -void Manager::ScheduleAnalyzer(const IPAddr& orig, const IPAddr& resp, PortVal* resp_p, - Val* analyzer, double timeout) +void Manager::ScheduleAnalyzer(const IPAddr& orig, const IPAddr& resp, zeek::PortVal* resp_p, + zeek::Val* analyzer, double timeout) { - IntrusivePtr ev{NewRef{}, analyzer->AsEnumVal()}; + zeek::EnumValPtr ev{zeek::NewRef{}, analyzer->AsEnumVal()}; return ScheduleAnalyzer(orig, resp, resp_p->Port(), resp_p->PortType(), Tag(std::move(ev)), timeout); } diff --git a/src/analyzer/Manager.h b/src/analyzer/Manager.h index 123851016d..147534c692 100644 --- a/src/analyzer/Manager.h +++ b/src/analyzer/Manager.h @@ -101,7 +101,7 @@ public: * * @return True if successful. */ - bool EnableAnalyzer(EnumVal* tag); + bool EnableAnalyzer(zeek::EnumVal* tag); /** * Enables an analyzer type. Disabled analyzers will not be @@ -122,7 +122,7 @@ public: * * @return True if successful. */ - bool DisableAnalyzer(EnumVal* tag); + bool DisableAnalyzer(zeek::EnumVal* tag); /** * Disables all currently registered analyzers. @@ -150,7 +150,7 @@ public: * @param tag The analyzer's tag as an enum of script type \c * Analyzer::Tag. */ - bool IsEnabled(EnumVal* tag); + bool IsEnabled(zeek::EnumVal* tag); /** * Registers a well-known port for an analyzer. Once registered, @@ -164,7 +164,7 @@ public: * * @return True if successful. */ - bool RegisterAnalyzerForPort(EnumVal* tag, PortVal* port); + bool RegisterAnalyzerForPort(zeek::EnumVal* tag, zeek::PortVal* port); /** * Registers a well-known port for an analyzer. Once registered, @@ -193,7 +193,7 @@ public: * registered for the analyzer). * */ - bool UnregisterAnalyzerForPort(EnumVal* tag, PortVal* port); + bool UnregisterAnalyzerForPort(zeek::EnumVal* tag, zeek::PortVal* port); /** * Unregisters a well-known port for an anlyzers. @@ -269,7 +269,7 @@ public: * schedule this analyzer. Must be non-zero. */ void ScheduleAnalyzer(const IPAddr& orig, const IPAddr& resp, uint16_t resp_p, - TransportProto proto, const Tag& analyzer, double timeout); + TransportProto proto, const Tag& analyzer, double timeout); /** * Schedules a particular analyzer for an upcoming connection. Once @@ -293,8 +293,8 @@ public: * schedule this analyzer. Must be non-zero. */ void ScheduleAnalyzer(const IPAddr& orig, const IPAddr& resp, uint16_t resp_p, - TransportProto proto, const char* analyzer, - double timeout); + TransportProto proto, const char* analyzer, + double timeout); /** * Searched for analyzers scheduled to be attached to a given connection @@ -311,7 +311,8 @@ public: * * @return True if at least one scheduled analyzer was found. */ - bool ApplyScheduledAnalyzers(Connection* conn, bool init_and_event = true, TransportLayerAnalyzer* parent = nullptr); + bool ApplyScheduledAnalyzers(Connection* conn, bool init_and_event = true, + TransportLayerAnalyzer* parent = nullptr); /** * Schedules a particular analyzer for an upcoming connection. Once @@ -332,8 +333,8 @@ public: * @param timeout An interval after which to timeout the request to * schedule this analyzer. Must be non-zero. */ - void ScheduleAnalyzer(const IPAddr& orig, const IPAddr& resp, PortVal* resp_p, - Val* analyzer, double timeout); + void ScheduleAnalyzer(const IPAddr& orig, const IPAddr& resp, zeek::PortVal* resp_p, + zeek::Val* analyzer, double timeout); /** * @return the UDP port numbers to be associated with VXLAN traffic. @@ -346,7 +347,7 @@ private: using tag_set = std::set; using analyzer_map_by_port = std::map; - tag_set* LookupPort(PortVal* val, bool add_if_not_found); + tag_set* LookupPort(zeek::PortVal* val, bool add_if_not_found); tag_set* LookupPort(TransportProto proto, uint32_t port, bool add_if_not_found); tag_set GetScheduled(const Connection* conn); diff --git a/src/analyzer/Tag.cc b/src/analyzer/Tag.cc index 228668e15d..5af0adfaf7 100644 --- a/src/analyzer/Tag.cc +++ b/src/analyzer/Tag.cc @@ -16,20 +16,20 @@ analyzer::Tag& analyzer::Tag::operator=(const analyzer::Tag& other) return *this; } -const IntrusivePtr& analyzer::Tag::AsVal() const +const zeek::EnumValPtr& analyzer::Tag::AsVal() const { return ::Tag::AsVal(analyzer_mgr->GetTagType()); } -EnumVal* analyzer::Tag::AsEnumVal() const +zeek::EnumVal* analyzer::Tag::AsEnumVal() const { return AsVal().get(); } -analyzer::Tag::Tag(IntrusivePtr val) +analyzer::Tag::Tag(zeek::EnumValPtr val) : ::Tag(std::move(val)) { } -analyzer::Tag::Tag(EnumVal* val) - : ::Tag({NewRef{}, val}) +analyzer::Tag::Tag(zeek::EnumVal* val) + : ::Tag({zeek::NewRef{}, val}) { } diff --git a/src/analyzer/Tag.h b/src/analyzer/Tag.h index 18eaf2fdf6..ce968f1a06 100644 --- a/src/analyzer/Tag.h +++ b/src/analyzer/Tag.h @@ -1,3 +1,4 @@ + // See the file "COPYING" in the main distribution directory for copyright. #pragma once @@ -5,7 +6,7 @@ #include "zeek-config.h" #include "../Tag.h" -class EnumVal; +ZEEK_FORWARD_DECLARE_NAMESPACED(EnumVal, zeek); namespace zeek::plugin { template class TaggedComponent; @@ -89,10 +90,10 @@ public: * * @param etype the script-layer enum type associated with the tag. */ - const IntrusivePtr& AsVal() const; + const zeek::EnumValPtr& AsVal() const; [[deprecated("Remove in v4.1. Use AsVal() instead.")]] - EnumVal* AsEnumVal() const; + zeek::EnumVal* AsEnumVal() const; static const Tag Error; @@ -118,10 +119,10 @@ protected: * * @param val An enum value of script type \c Analyzer::Tag. */ - explicit Tag(IntrusivePtr val); + explicit Tag(zeek::EnumValPtr val); [[deprecated("Remove in v4.1. Construct from IntrusivePtr instead")]] - explicit Tag(EnumVal* val); + explicit Tag(zeek::EnumVal* val); }; } diff --git a/src/analyzer/analyzer.bif b/src/analyzer/analyzer.bif index 849b75d693..058e0acc7b 100644 --- a/src/analyzer/analyzer.bif +++ b/src/analyzer/analyzer.bif @@ -11,13 +11,13 @@ module Analyzer; function Analyzer::__enable_analyzer%(id: Analyzer::Tag%) : bool %{ bool result = analyzer_mgr->EnableAnalyzer(id->AsEnumVal()); - return val_mgr->Bool(result); + return zeek::val_mgr->Bool(result); %} function Analyzer::__disable_analyzer%(id: Analyzer::Tag%) : bool %{ bool result = analyzer_mgr->DisableAnalyzer(id->AsEnumVal()); - return val_mgr->Bool(result); + return zeek::val_mgr->Bool(result); %} function Analyzer::__disable_all_analyzers%(%) : any @@ -29,20 +29,20 @@ function Analyzer::__disable_all_analyzers%(%) : any function Analyzer::__register_for_port%(id: Analyzer::Tag, p: port%) : bool %{ bool result = analyzer_mgr->RegisterAnalyzerForPort(id->AsEnumVal(), p); - return val_mgr->Bool(result); + return zeek::val_mgr->Bool(result); %} function Analyzer::__schedule_analyzer%(orig: addr, resp: addr, resp_p: port, analyzer: Analyzer::Tag, tout: interval%) : bool %{ analyzer_mgr->ScheduleAnalyzer(orig->AsAddr(), resp->AsAddr(), resp_p, analyzer->AsEnumVal(), tout); - return val_mgr->True(); + return zeek::val_mgr->True(); %} function __name%(atype: Analyzer::Tag%) : string %{ - const auto& n = analyzer_mgr->GetComponentName(IntrusivePtr{NewRef{}, atype->AsEnumVal()}); - return make_intrusive(n); + const auto& n = analyzer_mgr->GetComponentName(zeek::IntrusivePtr{zeek::NewRef{}, atype->AsEnumVal()}); + return zeek::make_intrusive(n); %} function __tag%(name: string%) : Analyzer::Tag diff --git a/src/analyzer/protocol/arp/ARP.cc b/src/analyzer/protocol/arp/ARP.cc index 4d8b83b8b8..73b7fe96a6 100644 --- a/src/analyzer/protocol/arp/ARP.cc +++ b/src/analyzer/protocol/arp/ARP.cc @@ -196,7 +196,7 @@ void ARP_Analyzer::BadARP(const struct arp_pkthdr* hdr, const char* msg) ToEthAddrStr((const u_char*) ar_sha(hdr)), ToAddrVal(ar_tpa(hdr)), ToEthAddrStr((const u_char*) ar_tha(hdr)), - make_intrusive(msg) + zeek::make_intrusive(msg) ); } @@ -223,22 +223,22 @@ void ARP_Analyzer::RREvent(EventHandlerPtr e, ); } -AddrVal* ARP_Analyzer::ConstructAddrVal(const void* addr) +zeek::AddrVal* ARP_Analyzer::ConstructAddrVal(const void* addr) { return ToAddrVal(addr).release(); } -IntrusivePtr ARP_Analyzer::ToAddrVal(const void* addr) +zeek::AddrValPtr ARP_Analyzer::ToAddrVal(const void* addr) { // ### For now, we only handle IPv4 addresses. - return make_intrusive(*(const uint32_t*) addr); + return zeek::make_intrusive(*(const uint32_t*) addr); } -StringVal* ARP_Analyzer::EthAddrToStr(const u_char* addr) +zeek::StringVal* ARP_Analyzer::EthAddrToStr(const u_char* addr) { return ToEthAddrStr(addr).release(); } -IntrusivePtr ARP_Analyzer::ToEthAddrStr(const u_char* addr) +zeek::StringValPtr ARP_Analyzer::ToEthAddrStr(const u_char* addr) { char buf[1024]; snprintf(buf, sizeof(buf), "%02x:%02x:%02x:%02x:%02x:%02x", addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]); - return make_intrusive(buf); + return zeek::make_intrusive(buf); } diff --git a/src/analyzer/protocol/arp/ARP.h b/src/analyzer/protocol/arp/ARP.h index d1de7de01f..9198003975 100644 --- a/src/analyzer/protocol/arp/ARP.h +++ b/src/analyzer/protocol/arp/ARP.h @@ -30,9 +30,9 @@ extern "C" { #include } -namespace analyzer { namespace arp { +namespace analyzer::arp { -class ARP_Analyzer : public BroObj { +class ARP_Analyzer : public zeek::Obj { public: ARP_Analyzer(); ~ARP_Analyzer() override; @@ -47,14 +47,14 @@ public: protected: [[deprecated("Remove in v4.1. Use ToAddrVal().")]] - AddrVal* ConstructAddrVal(const void* addr); + zeek::AddrVal* ConstructAddrVal(const void* addr); [[deprecated("Remove in v4.1. Use ToEthAddrStr().")]] - StringVal* EthAddrToStr(const u_char* addr); + zeek::StringVal* EthAddrToStr(const u_char* addr); - IntrusivePtr ToAddrVal(const void* addr); - IntrusivePtr ToEthAddrStr(const u_char* addr); + zeek::AddrValPtr ToAddrVal(const void* addr); + zeek::StringValPtr ToEthAddrStr(const u_char* addr); void BadARP(const struct arp_pkthdr* hdr, const char* string); void Corrupted(const char* string); }; -} } // namespace analyzer::* +} // namespace analyzer::arp diff --git a/src/analyzer/protocol/asn1/asn1.pac b/src/analyzer/protocol/asn1/asn1.pac index 4e87e11c1a..484ed27db7 100644 --- a/src/analyzer/protocol/asn1/asn1.pac +++ b/src/analyzer/protocol/asn1/asn1.pac @@ -3,12 +3,12 @@ %} %header{ - IntrusivePtr asn1_integer_to_val(const ASN1Encoding* i, zeek::TypeTag t); - IntrusivePtr asn1_integer_to_val(const ASN1Integer* i, zeek::TypeTag t); - IntrusivePtr asn1_oid_to_val(const ASN1Encoding* oid); - IntrusivePtr asn1_oid_to_val(const ASN1ObjectIdentifier* oid); - IntrusivePtr asn1_octet_string_to_val(const ASN1Encoding* s); - IntrusivePtr asn1_octet_string_to_val(const ASN1OctetString* s); + zeek::ValPtr asn1_integer_to_val(const ASN1Encoding* i, zeek::TypeTag t); + zeek::ValPtr asn1_integer_to_val(const ASN1Integer* i, zeek::TypeTag t); + zeek::StringValPtr asn1_oid_to_val(const ASN1Encoding* oid); + zeek::StringValPtr asn1_oid_to_val(const ASN1ObjectIdentifier* oid); + zeek::StringValPtr asn1_octet_string_to_val(const ASN1Encoding* s); + zeek::StringValPtr asn1_octet_string_to_val(const ASN1OctetString* s); %} ############################## ASN.1 Encodings @@ -102,35 +102,35 @@ function binary_to_int64(bs: bytestring): int64 %code{ -IntrusivePtr asn1_integer_to_val(const ASN1Integer* i, zeek::TypeTag t) +zeek::ValPtr asn1_integer_to_val(const ASN1Integer* i, zeek::TypeTag t) { return asn1_integer_to_val(i->encoding(), t); } -IntrusivePtr asn1_integer_to_val(const ASN1Encoding* i, zeek::TypeTag t) +zeek::ValPtr asn1_integer_to_val(const ASN1Encoding* i, zeek::TypeTag t) { auto v = binary_to_int64(i->content()); switch ( t ) { case zeek::TYPE_BOOL: - return val_mgr->Bool(v); + return zeek::val_mgr->Bool(v); case zeek::TYPE_INT: - return val_mgr->Int(v); + return zeek::val_mgr->Int(v); case zeek::TYPE_COUNT: case zeek::TYPE_COUNTER: - return val_mgr->Count(v); + return zeek::val_mgr->Count(v); default: reporter->Error("bad asn1_integer_to_val tag: %s", zeek::type_name(t)); - return val_mgr->Count(v); + return zeek::val_mgr->Count(v); } } -IntrusivePtr asn1_oid_to_val(const ASN1ObjectIdentifier* oid) +zeek::StringValPtr asn1_oid_to_val(const ASN1ObjectIdentifier* oid) { return asn1_oid_to_val(oid->encoding()); } -IntrusivePtr asn1_oid_to_val(const ASN1Encoding* oid) +zeek::StringValPtr asn1_oid_to_val(const ASN1Encoding* oid) { vector oid_components; vector > subidentifiers; @@ -152,7 +152,7 @@ IntrusivePtr asn1_oid_to_val(const ASN1Encoding* oid) if ( ! subidentifier.empty() || subidentifiers.size() < 1 ) // Underflow. - return val_mgr->EmptyString(); + return zeek::val_mgr->EmptyString(); for ( size_t i = 0; i < subidentifiers.size(); ++i ) { @@ -191,17 +191,17 @@ IntrusivePtr asn1_oid_to_val(const ASN1Encoding* oid) } } - return make_intrusive(rval); + return zeek::make_intrusive(rval); } -IntrusivePtr asn1_octet_string_to_val(const ASN1OctetString* s) +zeek::StringValPtr asn1_octet_string_to_val(const ASN1OctetString* s) { return asn1_octet_string_to_val(s->encoding()); } -IntrusivePtr asn1_octet_string_to_val(const ASN1Encoding* s) +zeek::StringValPtr asn1_octet_string_to_val(const ASN1Encoding* s) { bytestring const& bs = s->content(); - return make_intrusive(bs.length(), reinterpret_cast(bs.data())); + return zeek::make_intrusive(bs.length(), reinterpret_cast(bs.data())); } %} diff --git a/src/analyzer/protocol/bittorrent/BitTorrent.cc b/src/analyzer/protocol/bittorrent/BitTorrent.cc index bfc9e6be51..c479248220 100644 --- a/src/analyzer/protocol/bittorrent/BitTorrent.cc +++ b/src/analyzer/protocol/bittorrent/BitTorrent.cc @@ -120,8 +120,7 @@ void BitTorrent_Analyzer::DeliverWeird(const char* msg, bool orig) { if ( bittorrent_peer_weird ) EnqueueConnEvent(bittorrent_peer_weird, - ConnVal(), - val_mgr->Bool(orig), - make_intrusive(msg) - ); + ConnVal(), + zeek::val_mgr->Bool(orig), + zeek::make_intrusive(msg)); } diff --git a/src/analyzer/protocol/bittorrent/BitTorrentTracker.cc b/src/analyzer/protocol/bittorrent/BitTorrentTracker.cc index c73644991a..d79ed0763b 100644 --- a/src/analyzer/protocol/bittorrent/BitTorrentTracker.cc +++ b/src/analyzer/protocol/bittorrent/BitTorrentTracker.cc @@ -15,11 +15,11 @@ using namespace analyzer::bittorrent; -static IntrusivePtr bt_tracker_headers; -static IntrusivePtr bittorrent_peer; -static IntrusivePtr bittorrent_peer_set; -static IntrusivePtr bittorrent_benc_value; -static IntrusivePtr bittorrent_benc_dir; +static zeek::TableTypePtr bt_tracker_headers; +static zeek::RecordTypePtr bittorrent_peer; +static zeek::TableTypePtr bittorrent_peer_set; +static zeek::RecordTypePtr bittorrent_benc_value; +static zeek::TableTypePtr bittorrent_benc_dir; BitTorrentTracker_Analyzer::BitTorrentTracker_Analyzer(Connection* c) : tcp::TCP_ApplicationAnalyzer("BITTORRENTTRACKER", c) @@ -45,7 +45,7 @@ BitTorrentTracker_Analyzer::BitTorrentTracker_Analyzer(Connection* c) req_buf_pos = req_buf; req_buf_len = 0; req_val_uri = nullptr; - req_val_headers = new TableVal(bt_tracker_headers); + req_val_headers = new zeek::TableVal(bt_tracker_headers); res_state = BTT_RES_STATUS; res_allow_blank_line = false; @@ -53,9 +53,9 @@ BitTorrentTracker_Analyzer::BitTorrentTracker_Analyzer(Connection* c) res_buf_pos = res_buf; res_buf_len = 0; res_status = 0; - res_val_headers = new TableVal(bt_tracker_headers); - res_val_peers = new TableVal(bittorrent_peer_set); - res_val_benc = new TableVal(bittorrent_benc_dir); + res_val_headers = new zeek::TableVal(bt_tracker_headers); + res_val_peers = new zeek::TableVal(bittorrent_peer_set); + res_val_benc = new zeek::TableVal(bittorrent_benc_dir); InitBencParser(); @@ -136,7 +136,7 @@ void BitTorrentTracker_Analyzer::ClientRequest(int len, const u_char* data) req_buf_len -= (req_buf_pos - req_buf); memmove(req_buf, req_buf_pos, req_buf_len); req_buf_pos = req_buf; - req_val_headers = new TableVal(bt_tracker_headers); + req_val_headers = new zeek::TableVal(bt_tracker_headers); } } } @@ -198,9 +198,9 @@ void BitTorrentTracker_Analyzer::ServerReply(int len, const u_char* data) res_buf_pos = res_buf; res_status = 0; - res_val_headers = new TableVal(bt_tracker_headers); - res_val_peers = new TableVal(bittorrent_peer_set); - res_val_benc = new TableVal(bittorrent_benc_dir); + res_val_headers = new zeek::TableVal(bt_tracker_headers); + res_val_peers = new zeek::TableVal(bittorrent_peer_set); + res_val_benc = new zeek::TableVal(bittorrent_benc_dir); InitBencParser(); } @@ -247,8 +247,8 @@ void BitTorrentTracker_Analyzer::DeliverWeird(const char* msg, bool orig) if ( bt_tracker_weird ) EnqueueConnEvent(bt_tracker_weird, ConnVal(), - val_mgr->Bool(orig), - make_intrusive(msg) + zeek::val_mgr->Bool(orig), + zeek::make_intrusive(msg) ); } @@ -338,7 +338,7 @@ bool BitTorrentTracker_Analyzer::ParseRequest(char* line) void BitTorrentTracker_Analyzer::RequestGet(char* uri) { - req_val_uri = new StringVal(uri); + req_val_uri = new zeek::StringVal(uri); } void BitTorrentTracker_Analyzer::EmitRequest(void) @@ -347,9 +347,9 @@ void BitTorrentTracker_Analyzer::EmitRequest(void) if ( bt_tracker_request ) EnqueueConnEvent(bt_tracker_request, - ConnVal(), - IntrusivePtr{AdoptRef{}, req_val_uri}, - IntrusivePtr{AdoptRef{}, req_val_headers} + ConnVal(), + zeek::IntrusivePtr{zeek::AdoptRef{}, req_val_uri}, + zeek::IntrusivePtr{zeek::AdoptRef{}, req_val_headers} ); req_val_uri = nullptr; @@ -400,10 +400,11 @@ bool BitTorrentTracker_Analyzer::ParseResponse(char* line) if ( res_status != 200 ) { if ( bt_tracker_response_not_ok ) - EnqueueConnEvent(bt_tracker_response_not_ok, + EnqueueConnEvent( + bt_tracker_response_not_ok, ConnVal(), - val_mgr->Count(res_status), - IntrusivePtr{AdoptRef{}, res_val_headers} + zeek::val_mgr->Count(res_status), + zeek::IntrusivePtr{zeek::AdoptRef{}, res_val_headers} ); res_val_headers = nullptr; res_buf_pos = res_buf + res_buf_len; @@ -455,8 +456,8 @@ void BitTorrentTracker_Analyzer::ParseHeader(char* name, char* value, } #ifdef BTTRACKER_STORE_HEADERS - StringVal* name_ = new StringVal(name); - StringVal* value_ = new StringVal(value); + zeek::StringVal* name_ = new zeek::StringVal(name); + zeek::StringVal* value_ = new zeek::StringVal(value); (is_request ? req_val_headers : res_val_headers)->Assign(name_, value_); Unref(name_); @@ -477,17 +478,17 @@ void BitTorrentTracker_Analyzer::ResponseBenc(int name_len, char* name, uint32_t ad = extract_uint32((u_char*) value); uint16_t pt = ntohs((value[4] << 8) | value[5]); - auto peer = make_intrusive(bittorrent_peer); - peer->Assign(0, make_intrusive(ad)); - peer->Assign(1, val_mgr->Port(pt, TRANSPORT_TCP)); + auto peer = zeek::make_intrusive(bittorrent_peer); + peer->Assign(0, zeek::make_intrusive(ad)); + peer->Assign(1, zeek::val_mgr->Port(pt, TRANSPORT_TCP)); res_val_peers->Assign(std::move(peer), nullptr); } } else { - auto name_ = make_intrusive(name_len, name); - auto benc_value = make_intrusive(bittorrent_benc_value); - benc_value->Assign(type, make_intrusive(value_len, value)); + auto name_ = zeek::make_intrusive(name_len, name); + auto benc_value = zeek::make_intrusive(bittorrent_benc_value); + benc_value->Assign(type, zeek::make_intrusive(value_len, value)); res_val_benc->Assign(std::move(name_), std::move(benc_value)); } } @@ -495,10 +496,10 @@ void BitTorrentTracker_Analyzer::ResponseBenc(int name_len, char* name, void BitTorrentTracker_Analyzer::ResponseBenc(int name_len, char* name, enum btt_benc_types type, bro_int_t value) { - auto benc_value = make_intrusive(bittorrent_benc_value); - auto name_ = make_intrusive(name_len, name); + auto benc_value = zeek::make_intrusive(bittorrent_benc_value); + auto name_ = zeek::make_intrusive(name_len, name); - benc_value->Assign(type, val_mgr->Int(value)); + benc_value->Assign(type, zeek::val_mgr->Int(value)); res_val_benc->Assign(std::move(name_), std::move(benc_value)); } @@ -782,11 +783,11 @@ void BitTorrentTracker_Analyzer::EmitResponse(void) if ( bt_tracker_response ) EnqueueConnEvent(bt_tracker_response, - ConnVal(), - val_mgr->Count(res_status), - IntrusivePtr{AdoptRef{}, res_val_headers}, - IntrusivePtr{AdoptRef{}, res_val_peers}, - IntrusivePtr{AdoptRef{}, res_val_benc} + ConnVal(), + zeek::val_mgr->Count(res_status), + zeek::IntrusivePtr{zeek::AdoptRef{}, res_val_headers}, + zeek::IntrusivePtr{zeek::AdoptRef{}, res_val_peers}, + zeek::IntrusivePtr{zeek::AdoptRef{}, res_val_benc} ); res_val_headers = nullptr; diff --git a/src/analyzer/protocol/bittorrent/BitTorrentTracker.h b/src/analyzer/protocol/bittorrent/BitTorrentTracker.h index 5fbaba7a15..f737a13c8a 100644 --- a/src/analyzer/protocol/bittorrent/BitTorrentTracker.h +++ b/src/analyzer/protocol/bittorrent/BitTorrentTracker.h @@ -6,7 +6,7 @@ #define BTTRACKER_BUF 2048 -class StringVal; +ZEEK_FORWARD_DECLARE_NAMESPACED(StringVal, zeek); namespace analyzer { namespace bittorrent { @@ -92,8 +92,8 @@ protected: char req_buf[BTTRACKER_BUF]; char* req_buf_pos; unsigned int req_buf_len; - StringVal* req_val_uri; - TableVal* req_val_headers; + zeek::StringVal* req_val_uri; + zeek::TableVal* req_val_headers; // Response. enum btt_states res_state; @@ -102,9 +102,9 @@ protected: char* res_buf_pos; unsigned int res_buf_len; bro_uint_t res_status; - TableVal* res_val_headers; - TableVal* res_val_peers; - TableVal* res_val_benc; + zeek::TableVal* res_val_headers; + zeek::TableVal* res_val_peers; + zeek::TableVal* res_val_benc; std::vector benc_stack; std::vector benc_count; diff --git a/src/analyzer/protocol/bittorrent/bittorrent-analyzer.pac b/src/analyzer/protocol/bittorrent/bittorrent-analyzer.pac index f6dbb95dda..456fbeaaa5 100644 --- a/src/analyzer/protocol/bittorrent/bittorrent-analyzer.pac +++ b/src/analyzer/protocol/bittorrent/bittorrent-analyzer.pac @@ -221,7 +221,7 @@ flow BitTorrent_Flow(is_orig: bool) { connection()->bro_analyzer(), connection()->bro_analyzer()->Conn(), is_orig(), - val_mgr->Port(listen_port, TRANSPORT_TCP)); + zeek::val_mgr->Port(listen_port, TRANSPORT_TCP)); } return true; diff --git a/src/analyzer/protocol/conn-size/ConnSize.cc b/src/analyzer/protocol/conn-size/ConnSize.cc index f356f39e3f..f71cfb4528 100644 --- a/src/analyzer/protocol/conn-size/ConnSize.cc +++ b/src/analyzer/protocol/conn-size/ConnSize.cc @@ -52,8 +52,8 @@ void ConnSize_Analyzer::ThresholdEvent(EventHandlerPtr f, uint64_t threshold, bo EnqueueConnEvent(f, ConnVal(), - val_mgr->Count(threshold), - val_mgr->Bool(is_orig) + zeek::val_mgr->Count(threshold), + zeek::val_mgr->Bool(is_orig) ); } @@ -94,8 +94,8 @@ void ConnSize_Analyzer::CheckThresholds(bool is_orig) { EnqueueConnEvent(conn_duration_threshold_crossed, ConnVal(), - make_intrusive(duration_thresh), - val_mgr->Bool(is_orig) + zeek::make_intrusive(duration_thresh), + zeek::val_mgr->Bool(is_orig) ); duration_thresh = 0; } @@ -167,11 +167,11 @@ void ConnSize_Analyzer::SetDurationThreshold(double duration) CheckThresholds(true); } -void ConnSize_Analyzer::UpdateConnVal(RecordVal *conn_val) +void ConnSize_Analyzer::UpdateConnVal(zeek::RecordVal *conn_val) { // RecordType *connection_type is decleared in NetVar.h - RecordVal* orig_endp = conn_val->GetField("orig")->AsRecordVal(); - RecordVal* resp_endp = conn_val->GetField("resp")->AsRecordVal(); + zeek::RecordVal* orig_endp = conn_val->GetField("orig")->AsRecordVal(); + zeek::RecordVal* resp_endp = conn_val->GetField("resp")->AsRecordVal(); // endpoint is the RecordType from NetVar.h int pktidx = zeek::id::endpoint->FieldOffset("num_pkts"); @@ -183,10 +183,10 @@ void ConnSize_Analyzer::UpdateConnVal(RecordVal *conn_val) if ( bytesidx < 0 ) reporter->InternalError("'endpoint' record missing 'num_bytes_ip' field"); - orig_endp->Assign(pktidx, val_mgr->Count(orig_pkts)); - orig_endp->Assign(bytesidx, val_mgr->Count(orig_bytes)); - resp_endp->Assign(pktidx, val_mgr->Count(resp_pkts)); - resp_endp->Assign(bytesidx, val_mgr->Count(resp_bytes)); + orig_endp->Assign(pktidx, zeek::val_mgr->Count(orig_pkts)); + orig_endp->Assign(bytesidx, zeek::val_mgr->Count(orig_bytes)); + resp_endp->Assign(pktidx, zeek::val_mgr->Count(resp_pkts)); + resp_endp->Assign(bytesidx, zeek::val_mgr->Count(resp_bytes)); Analyzer::UpdateConnVal(conn_val); } diff --git a/src/analyzer/protocol/conn-size/ConnSize.h b/src/analyzer/protocol/conn-size/ConnSize.h index 241e67877a..a6360440a4 100644 --- a/src/analyzer/protocol/conn-size/ConnSize.h +++ b/src/analyzer/protocol/conn-size/ConnSize.h @@ -17,7 +17,7 @@ public: void Done() override; // from Analyzer.h - void UpdateConnVal(RecordVal *conn_val) override; + void UpdateConnVal(zeek::RecordVal *conn_val) override; void FlipRoles() override; void SetByteAndPacketThreshold(uint64_t threshold, bool bytes, bool orig); @@ -50,4 +50,4 @@ protected: double duration_thresh; }; -} } // namespace analyzer::* +} } // namespace analyzer::* diff --git a/src/analyzer/protocol/conn-size/functions.bif b/src/analyzer/protocol/conn-size/functions.bif index 9c2a506a99..e0e6e1c31f 100644 --- a/src/analyzer/protocol/conn-size/functions.bif +++ b/src/analyzer/protocol/conn-size/functions.bif @@ -3,7 +3,7 @@ #include "Reporter.h" #include "Sessions.h" -static analyzer::Analyzer* GetConnsizeAnalyzer(Val* cid) +static analyzer::Analyzer* GetConnsizeAnalyzer(zeek::Val* cid) { Connection* c = sessions->FindConnection(cid); if ( ! c ) @@ -35,11 +35,11 @@ function set_current_conn_bytes_threshold%(cid: conn_id, threshold: count, is_or %{ analyzer::Analyzer* a = GetConnsizeAnalyzer(cid); if ( ! a ) - return val_mgr->False(); + return zeek::val_mgr->False(); static_cast(a)->SetByteAndPacketThreshold(threshold, true, is_orig); - return val_mgr->True(); + return zeek::val_mgr->True(); %} ## Sets a threshold for connection packets, overwtiting any potential old thresholds. @@ -59,11 +59,11 @@ function set_current_conn_packets_threshold%(cid: conn_id, threshold: count, is_ %{ analyzer::Analyzer* a = GetConnsizeAnalyzer(cid); if ( ! a ) - return val_mgr->False(); + return zeek::val_mgr->False(); static_cast(a)->SetByteAndPacketThreshold(threshold, false, is_orig); - return val_mgr->True(); + return zeek::val_mgr->True(); %} ## Sets the current duration threshold for connection, overwriting any potential old @@ -81,11 +81,11 @@ function set_current_conn_duration_threshold%(cid: conn_id, threshold: interval% %{ analyzer::Analyzer* a = GetConnsizeAnalyzer(cid); if ( ! a ) - return val_mgr->False(); + return zeek::val_mgr->False(); static_cast(a)->SetDurationThreshold(threshold); - return val_mgr->True(); + return zeek::val_mgr->True(); %} # Gets the current byte threshold size for a connection. @@ -103,9 +103,9 @@ function get_current_conn_bytes_threshold%(cid: conn_id, is_orig: bool%): count %{ analyzer::Analyzer* a = GetConnsizeAnalyzer(cid); if ( ! a ) - return val_mgr->Count(0); + return zeek::val_mgr->Count(0); - return val_mgr->Count(static_cast(a)->GetByteAndPacketThreshold(true, is_orig)); + return zeek::val_mgr->Count(static_cast(a)->GetByteAndPacketThreshold(true, is_orig)); %} ## Gets the current packet threshold size for a connection. @@ -122,9 +122,9 @@ function get_current_conn_packets_threshold%(cid: conn_id, is_orig: bool%): coun %{ analyzer::Analyzer* a = GetConnsizeAnalyzer(cid); if ( ! a ) - return val_mgr->Count(0); + return zeek::val_mgr->Count(0); - return val_mgr->Count(static_cast(a)->GetByteAndPacketThreshold(false, is_orig)); + return zeek::val_mgr->Count(static_cast(a)->GetByteAndPacketThreshold(false, is_orig)); %} ## Gets the current duration threshold size for a connection. @@ -139,7 +139,7 @@ function get_current_conn_duration_threshold%(cid: conn_id%): interval %{ analyzer::Analyzer* a = GetConnsizeAnalyzer(cid); if ( ! a ) - return make_intrusive(0.0); + return zeek::make_intrusive(0.0); - return make_intrusive(static_cast(a)->GetDurationThreshold()); + return zeek::make_intrusive(static_cast(a)->GetDurationThreshold()); %} diff --git a/src/analyzer/protocol/dce-rpc/dce_rpc-analyzer.pac b/src/analyzer/protocol/dce-rpc/dce_rpc-analyzer.pac index c6bdbd3ab8..eaddc49381 100644 --- a/src/analyzer/protocol/dce-rpc/dce_rpc-analyzer.pac +++ b/src/analyzer/protocol/dce-rpc/dce_rpc-analyzer.pac @@ -83,14 +83,14 @@ refine connection DCE_RPC_Conn += { %{ if ( dce_rpc_bind_ack ) { - IntrusivePtr sec_addr; + zeek::StringValPtr sec_addr; // Remove the null from the end of the string if it's there. if ( ${bind.sec_addr}.length() > 0 && *(${bind.sec_addr}.begin() + ${bind.sec_addr}.length()) == 0 ) - sec_addr = make_intrusive(${bind.sec_addr}.length()-1, (const char*) ${bind.sec_addr}.begin()); + sec_addr = zeek::make_intrusive(${bind.sec_addr}.length()-1, (const char*) ${bind.sec_addr}.begin()); else - sec_addr = make_intrusive(${bind.sec_addr}.length(), (const char*) ${bind.sec_addr}.begin()); + sec_addr = zeek::make_intrusive(${bind.sec_addr}.length(), (const char*) ${bind.sec_addr}.begin()); zeek::BifEvent::enqueue_dce_rpc_bind_ack(bro_analyzer(), bro_analyzer()->Conn(), @@ -175,4 +175,3 @@ refine typeattr DCE_RPC_Request += &let { refine typeattr DCE_RPC_Response += &let { proc = $context.connection.process_dce_rpc_response(this); }; - diff --git a/src/analyzer/protocol/dhcp/dhcp-analyzer.pac b/src/analyzer/protocol/dhcp/dhcp-analyzer.pac index 1228322d39..fe6c893971 100644 --- a/src/analyzer/protocol/dhcp/dhcp-analyzer.pac +++ b/src/analyzer/protocol/dhcp/dhcp-analyzer.pac @@ -1,8 +1,8 @@ refine flow DHCP_Flow += { %member{ - IntrusivePtr options; - IntrusivePtr all_options; + zeek::RecordValPtr options; + zeek::VectorValPtr all_options; %} %init{ @@ -19,8 +19,8 @@ refine flow DHCP_Flow += { %{ if ( ! options ) { - options = make_intrusive(zeek::BifType::Record::DHCP::Options); - all_options = make_intrusive(zeek::id::index_vec); + options = zeek::make_intrusive(zeek::BifType::Record::DHCP::Options); + all_options = zeek::make_intrusive(zeek::id::index_vec); options->Assign(0, all_options); } @@ -32,7 +32,7 @@ refine flow DHCP_Flow += { init_options(); if ( code != 255 ) - all_options->Assign(all_options->Size(), val_mgr->Count(code)); + all_options->Assign(all_options->Size(), zeek::val_mgr->Count(code)); return true; %} @@ -53,17 +53,17 @@ refine flow DHCP_Flow += { std::string mac_str = fmt_mac(${msg.chaddr}.data(), ${msg.chaddr}.length()); double secs = static_cast(${msg.secs}); - auto dhcp_msg_val = make_intrusive(zeek::BifType::Record::DHCP::Msg); - dhcp_msg_val->Assign(0, val_mgr->Count(${msg.op})); - dhcp_msg_val->Assign(1, val_mgr->Count(${msg.type})); - dhcp_msg_val->Assign(2, val_mgr->Count(${msg.xid})); - dhcp_msg_val->Assign(3, make_intrusive(secs)); - dhcp_msg_val->Assign(4, val_mgr->Count(${msg.flags})); - dhcp_msg_val->Assign(5, make_intrusive(htonl(${msg.ciaddr}))); - dhcp_msg_val->Assign(6, make_intrusive(htonl(${msg.yiaddr}))); - dhcp_msg_val->Assign(7, make_intrusive(htonl(${msg.siaddr}))); - dhcp_msg_val->Assign(8, make_intrusive(htonl(${msg.giaddr}))); - dhcp_msg_val->Assign(9, make_intrusive(mac_str)); + auto dhcp_msg_val = zeek::make_intrusive(zeek::BifType::Record::DHCP::Msg); + dhcp_msg_val->Assign(0, zeek::val_mgr->Count(${msg.op})); + dhcp_msg_val->Assign(1, zeek::val_mgr->Count(${msg.type})); + dhcp_msg_val->Assign(2, zeek::val_mgr->Count(${msg.xid})); + dhcp_msg_val->Assign(3, zeek::make_intrusive(secs)); + dhcp_msg_val->Assign(4, zeek::val_mgr->Count(${msg.flags})); + dhcp_msg_val->Assign(5, zeek::make_intrusive(htonl(${msg.ciaddr}))); + dhcp_msg_val->Assign(6, zeek::make_intrusive(htonl(${msg.yiaddr}))); + dhcp_msg_val->Assign(7, zeek::make_intrusive(htonl(${msg.siaddr}))); + dhcp_msg_val->Assign(8, zeek::make_intrusive(htonl(${msg.giaddr}))); + dhcp_msg_val->Assign(9, zeek::make_intrusive(mac_str)); int last_non_null = 0; @@ -74,7 +74,7 @@ refine flow DHCP_Flow += { } if ( last_non_null > 0 ) - dhcp_msg_val->Assign(10, make_intrusive(last_non_null + 1, + dhcp_msg_val->Assign(10, zeek::make_intrusive(last_non_null + 1, reinterpret_cast(${msg.sname}.begin()))); last_non_null = 0; @@ -86,7 +86,7 @@ refine flow DHCP_Flow += { } if ( last_non_null > 0 ) - dhcp_msg_val->Assign(11, make_intrusive(last_non_null + 1, + dhcp_msg_val->Assign(11, zeek::make_intrusive(last_non_null + 1, reinterpret_cast(${msg.file_n}.begin()))); init_options(); diff --git a/src/analyzer/protocol/dhcp/dhcp-options.pac b/src/analyzer/protocol/dhcp/dhcp-options.pac index b572f297b3..34351c3700 100644 --- a/src/analyzer/protocol/dhcp/dhcp-options.pac +++ b/src/analyzer/protocol/dhcp/dhcp-options.pac @@ -11,7 +11,7 @@ refine casetype OptionValue += { refine flow DHCP_Flow += { function process_subnet_option(v: OptionValue): bool %{ - ${context.flow}->options->Assign(1, make_intrusive(htonl(${v.subnet}))); + ${context.flow}->options->Assign(1, zeek::make_intrusive(htonl(${v.subnet}))); return true; %} }; @@ -34,7 +34,7 @@ refine casetype OptionValue += { refine flow DHCP_Flow += { function process_time_offset_option(v: OptionValue): bool %{ - ${context.flow}->options->Assign(25, val_mgr->Int(${v.time_offset})); + ${context.flow}->options->Assign(25, zeek::val_mgr->Int(${v.time_offset})); return true; %} }; @@ -57,14 +57,14 @@ refine casetype OptionValue += { refine flow DHCP_Flow += { function process_router_option(v: OptionValue): bool %{ - auto router_list = make_intrusive(zeek::BifType::Vector::DHCP::Addrs); + auto router_list = zeek::make_intrusive(zeek::BifType::Vector::DHCP::Addrs); int num_routers = ${v.router_list}->size(); vector* rlist = ${v.router_list}; for ( int i = 0; i < num_routers; ++i ) { uint32 raddr = (*rlist)[i]; - router_list->Assign(i, make_intrusive(htonl(raddr))); + router_list->Assign(i, zeek::make_intrusive(htonl(raddr))); } ${context.flow}->options->Assign(2, std::move(router_list)); @@ -91,14 +91,14 @@ refine casetype OptionValue += { refine flow DHCP_Flow += { function process_timeserver_option(v: OptionValue): bool %{ - auto timeserver_list = make_intrusive(zeek::BifType::Vector::DHCP::Addrs); + auto timeserver_list = zeek::make_intrusive(zeek::BifType::Vector::DHCP::Addrs); int num_servers = ${v.timeserver_list}->size(); vector* rlist = ${v.timeserver_list}; for ( int i = 0; i < num_servers; ++i ) { uint32 raddr = (*rlist)[i]; - timeserver_list->Assign(i, make_intrusive(htonl(raddr))); + timeserver_list->Assign(i, zeek::make_intrusive(htonl(raddr))); } ${context.flow}->options->Assign(26, std::move(timeserver_list)); @@ -125,14 +125,14 @@ refine casetype OptionValue += { refine flow DHCP_Flow += { function process_nameserver_option(v: OptionValue): bool %{ - auto nameserver_list = make_intrusive(zeek::BifType::Vector::DHCP::Addrs); + auto nameserver_list = zeek::make_intrusive(zeek::BifType::Vector::DHCP::Addrs); int num_servers = ${v.nameserver_list}->size(); vector* rlist = ${v.nameserver_list}; for ( int i = 0; i < num_servers; ++i ) { uint32 raddr = (*rlist)[i]; - nameserver_list->Assign(i, make_intrusive(htonl(raddr))); + nameserver_list->Assign(i, zeek::make_intrusive(htonl(raddr))); } ${context.flow}->options->Assign(27, std::move(nameserver_list)); @@ -159,14 +159,14 @@ refine casetype OptionValue += { refine flow DHCP_Flow += { function process_dns_server_option(v: OptionValue): bool %{ - auto server_list = make_intrusive(zeek::BifType::Vector::DHCP::Addrs); + auto server_list = zeek::make_intrusive(zeek::BifType::Vector::DHCP::Addrs); int num_servers = ${v.dns_server_list}->size(); vector* rlist = ${v.dns_server_list}; for ( int i = 0; i < num_servers; ++i ) { uint32 raddr = (*rlist)[i]; - server_list->Assign(i, make_intrusive(htonl(raddr))); + server_list->Assign(i, zeek::make_intrusive(htonl(raddr))); } ${context.flow}->options->Assign(3, std::move(server_list)); @@ -192,7 +192,7 @@ refine casetype OptionValue += { refine flow DHCP_Flow += { function process_host_name_option(v: OptionValue): bool %{ - ${context.flow}->options->Assign(4, make_intrusive(${v.host_name}.length(), + ${context.flow}->options->Assign(4, zeek::make_intrusive(${v.host_name}.length(), reinterpret_cast(${v.host_name}.begin()))); return true; @@ -225,7 +225,7 @@ refine flow DHCP_Flow += { last_non_null = i; } - ${context.flow}->options->Assign(5, make_intrusive(last_non_null == 0 ? 0 : last_non_null + 1, + ${context.flow}->options->Assign(5, zeek::make_intrusive(last_non_null == 0 ? 0 : last_non_null + 1, reinterpret_cast(${v.domain_name}.begin()))); return true; @@ -250,7 +250,7 @@ refine casetype OptionValue += { refine flow DHCP_Flow += { function process_forwarding_option(v: OptionValue): bool %{ - ${context.flow}->options->Assign(6, val_mgr->Bool(${v.forwarding} == 0 ? false : true)); + ${context.flow}->options->Assign(6, zeek::val_mgr->Bool(${v.forwarding} == 0 ? false : true)); return true; %} @@ -274,7 +274,7 @@ refine casetype OptionValue += { refine flow DHCP_Flow += { function process_broadcast_address_option(v: OptionValue): bool %{ - ${context.flow}->options->Assign(7, make_intrusive(htonl(${v.broadcast_address}))); + ${context.flow}->options->Assign(7, zeek::make_intrusive(htonl(${v.broadcast_address}))); return true; %} @@ -298,14 +298,14 @@ refine casetype OptionValue += { refine flow DHCP_Flow += { function process_ntpserver_option(v: OptionValue): bool %{ - auto ntpserver_list = make_intrusive(zeek::BifType::Vector::DHCP::Addrs); + auto ntpserver_list = zeek::make_intrusive(zeek::BifType::Vector::DHCP::Addrs); int num_servers = ${v.ntpserver_list}->size(); vector* rlist = ${v.ntpserver_list}; for ( int i = 0; i < num_servers; ++i ) { uint32 raddr = (*rlist)[i]; - ntpserver_list->Assign(i, make_intrusive(htonl(raddr))); + ntpserver_list->Assign(i, zeek::make_intrusive(htonl(raddr))); } ${context.flow}->options->Assign(28, std::move(ntpserver_list)); @@ -331,7 +331,7 @@ refine casetype OptionValue += { refine flow DHCP_Flow += { function process_vendor_specific_option(v: OptionValue): bool %{ - ${context.flow}->options->Assign(8, make_intrusive(${v.vendor_specific}.length(), + ${context.flow}->options->Assign(8, zeek::make_intrusive(${v.vendor_specific}.length(), reinterpret_cast(${v.vendor_specific}.begin()))); return true; @@ -356,14 +356,14 @@ refine casetype OptionValue += { refine flow DHCP_Flow += { function process_nbns_option(v: OptionValue): bool %{ - auto server_list = make_intrusive(zeek::BifType::Vector::DHCP::Addrs); + auto server_list = zeek::make_intrusive(zeek::BifType::Vector::DHCP::Addrs); int num_servers = ${v.nbns}->size(); vector* rlist = ${v.nbns}; for ( int i = 0; i < num_servers; ++i ) { uint32 raddr = (*rlist)[i]; - server_list->Assign(i, make_intrusive(htonl(raddr))); + server_list->Assign(i, zeek::make_intrusive(htonl(raddr))); } ${context.flow}->options->Assign(9, std::move(server_list)); @@ -389,7 +389,7 @@ refine casetype OptionValue += { refine flow DHCP_Flow += { function process_addr_request_option(v: OptionValue): bool %{ - ${context.flow}->options->Assign(10, make_intrusive(htonl(${v.addr_request}))); + ${context.flow}->options->Assign(10, zeek::make_intrusive(htonl(${v.addr_request}))); return true; %} @@ -414,7 +414,7 @@ refine flow DHCP_Flow += { function process_lease_option(v: OptionValue): bool %{ double lease = static_cast(${v.lease}); - ${context.flow}->options->Assign(11, make_intrusive(lease)); + ${context.flow}->options->Assign(11, zeek::make_intrusive(lease)); return true; %} @@ -438,7 +438,7 @@ refine casetype OptionValue += { refine flow DHCP_Flow += { function process_serv_id_option(v: OptionValue): bool %{ - ${context.flow}->options->Assign(12, make_intrusive(htonl(${v.serv_addr}))); + ${context.flow}->options->Assign(12, zeek::make_intrusive(htonl(${v.serv_addr}))); return true; %} @@ -462,14 +462,14 @@ refine casetype OptionValue += { refine flow DHCP_Flow += { function process_par_req_list_option(v: OptionValue): bool %{ - auto params = make_intrusive(zeek::id::index_vec); + auto params = zeek::make_intrusive(zeek::id::index_vec); int num_parms = ${v.par_req_list}->size(); vector* plist = ${v.par_req_list}; for ( int i = 0; i < num_parms; ++i ) { uint8 param = (*plist)[i]; - params->Assign(i, val_mgr->Count(param)); + params->Assign(i, zeek::val_mgr->Count(param)); } ${context.flow}->options->Assign(13, std::move(params)); @@ -496,7 +496,7 @@ refine casetype OptionValue += { refine flow DHCP_Flow += { function process_message_option(v: OptionValue): bool %{ - ${context.flow}->options->Assign(14, make_intrusive(${v.message}.length(), + ${context.flow}->options->Assign(14, zeek::make_intrusive(${v.message}.length(), reinterpret_cast(${v.message}.begin()))); return true; @@ -521,7 +521,7 @@ refine casetype OptionValue += { refine flow DHCP_Flow += { function process_max_message_size_option(v: OptionValue): bool %{ - ${context.flow}->options->Assign(15, val_mgr->Count(${v.max_msg_size})); + ${context.flow}->options->Assign(15, zeek::val_mgr->Count(${v.max_msg_size})); return true; %} @@ -546,7 +546,7 @@ refine flow DHCP_Flow += { function process_renewal_time_option(v: OptionValue): bool %{ double renewal_time = static_cast(${v.renewal_time}); - ${context.flow}->options->Assign(16, make_intrusive(renewal_time)); + ${context.flow}->options->Assign(16, zeek::make_intrusive(renewal_time)); return true; %} @@ -571,7 +571,7 @@ refine flow DHCP_Flow += { function process_rebinding_time_option(v: OptionValue): bool %{ double rebinding_time = static_cast(${v.rebinding_time}); - ${context.flow}->options->Assign(17, make_intrusive(rebinding_time)); + ${context.flow}->options->Assign(17, zeek::make_intrusive(rebinding_time)); return true; %} @@ -595,7 +595,7 @@ refine casetype OptionValue += { refine flow DHCP_Flow += { function process_vendor_class_option(v: OptionValue): bool %{ - ${context.flow}->options->Assign(18, make_intrusive(${v.vendor_class}.length(), + ${context.flow}->options->Assign(18, zeek::make_intrusive(${v.vendor_class}.length(), reinterpret_cast(${v.vendor_class}.begin()))); return true; @@ -625,16 +625,16 @@ refine casetype OptionValue += { refine flow DHCP_Flow += { function process_client_id_option(v: OptionValue): bool %{ - auto client_id = make_intrusive(zeek::BifType::Record::DHCP::ClientID); - client_id->Assign(0, val_mgr->Count(${v.client_id.hwtype})); - IntrusivePtr sv; + auto client_id = zeek::make_intrusive(zeek::BifType::Record::DHCP::ClientID); + client_id->Assign(0, zeek::val_mgr->Count(${v.client_id.hwtype})); + zeek::StringValPtr sv; if ( ${v.client_id.hwtype} == 0 ) - sv = make_intrusive(${v.client_id.hwaddr}.length(), - (const char*)${v.client_id.hwaddr}.begin()); + sv = zeek::make_intrusive(${v.client_id.hwaddr}.length(), + (const char*)${v.client_id.hwaddr}.begin()); else - sv = make_intrusive(fmt_mac(${v.client_id.hwaddr}.begin(), - ${v.client_id.hwaddr}.length())); + sv = zeek::make_intrusive(fmt_mac(${v.client_id.hwaddr}.begin(), + ${v.client_id.hwaddr}.length())); client_id->Assign(1, std::move(sv)); @@ -662,7 +662,7 @@ refine casetype OptionValue += { refine flow DHCP_Flow += { function process_user_class_option(v: OptionValue): bool %{ - ${context.flow}->options->Assign(20, make_intrusive(${v.user_class}.length(), + ${context.flow}->options->Assign(20, zeek::make_intrusive(${v.user_class}.length(), reinterpret_cast(${v.user_class}.begin()))); return true; @@ -694,12 +694,12 @@ refine casetype OptionValue += { refine flow DHCP_Flow += { function process_client_fqdn_option(v: OptionValue): bool %{ - auto client_fqdn = make_intrusive(zeek::BifType::Record::DHCP::ClientFQDN); - client_fqdn->Assign(0, val_mgr->Count(${v.client_fqdn.flags})); - client_fqdn->Assign(1, val_mgr->Count(${v.client_fqdn.rcode1})); - client_fqdn->Assign(2, val_mgr->Count(${v.client_fqdn.rcode2})); + auto client_fqdn = zeek::make_intrusive(zeek::BifType::Record::DHCP::ClientFQDN); + client_fqdn->Assign(0, zeek::val_mgr->Count(${v.client_fqdn.flags})); + client_fqdn->Assign(1, zeek::val_mgr->Count(${v.client_fqdn.rcode1})); + client_fqdn->Assign(2, zeek::val_mgr->Count(${v.client_fqdn.rcode2})); const char* domain_name = reinterpret_cast(${v.client_fqdn.domain_name}.begin()); - client_fqdn->Assign(3, make_intrusive(${v.client_fqdn.domain_name}.length(), domain_name)); + client_fqdn->Assign(3, zeek::make_intrusive(${v.client_fqdn.domain_name}.length(), domain_name)); ${context.flow}->options->Assign(21, std::move(client_fqdn)); @@ -752,15 +752,15 @@ refine flow DHCP_Flow += { function process_relay_agent_inf_option(v: OptionValue): bool %{ - auto relay_agent_sub_opt = make_intrusive(zeek::BifType::Vector::DHCP::SubOpts); + auto relay_agent_sub_opt = zeek::make_intrusive(zeek::BifType::Vector::DHCP::SubOpts); uint16 i = 0; for ( auto ptrsubopt = ${v.relay_agent_inf}->begin(); ptrsubopt != ${v.relay_agent_inf}->end(); ++ptrsubopt ) { - auto r = make_intrusive(zeek::BifType::Record::DHCP::SubOpt); - r->Assign(0, val_mgr->Count((*ptrsubopt)->code())); + auto r = zeek::make_intrusive(zeek::BifType::Record::DHCP::SubOpt); + r->Assign(0, zeek::val_mgr->Count((*ptrsubopt)->code())); r->Assign(1, to_stringval((*ptrsubopt)->value())); relay_agent_sub_opt->Assign(i, std::move(r)); @@ -790,7 +790,7 @@ refine casetype OptionValue += { refine flow DHCP_Flow += { function process_auto_config_option(v: OptionValue): bool %{ - ${context.flow}->options->Assign(23, val_mgr->Bool(${v.auto_config} == 0 ? false : true)); + ${context.flow}->options->Assign(23, zeek::val_mgr->Bool(${v.auto_config} == 0 ? false : true)); return true; %} @@ -818,7 +818,7 @@ refine flow DHCP_Flow += { if ( string_len == 0 ) { - ${context.flow}->options->Assign(24, make_intrusive(0, "")); + ${context.flow}->options->Assign(24, zeek::make_intrusive(0, "")); return true; } @@ -830,7 +830,7 @@ refine flow DHCP_Flow += { if ( has_newline ) --string_len; - ${context.flow}->options->Assign(24, make_intrusive(string_len, + ${context.flow}->options->Assign(24, zeek::make_intrusive(string_len, reinterpret_cast(${v.auto_proxy_config}.begin()))); return true; @@ -840,5 +840,3 @@ refine flow DHCP_Flow += { refine typeattr Option += &let { proc_auto_proxy_config_option = $context.flow.process_auto_proxy_config_option(info.value) &if(code==AUTO_PROXY_CONFIG_OPTION); }; - - diff --git a/src/analyzer/protocol/dns/DNS.cc b/src/analyzer/protocol/dns/DNS.cc index 1551c9ba4a..09458db5f9 100644 --- a/src/analyzer/protocol/dns/DNS.cc +++ b/src/analyzer/protocol/dns/DNS.cc @@ -9,7 +9,7 @@ #include #include -#include "BroString.h" +#include "ZeekString.h" #include "NetVar.h" #include "Sessions.h" #include "Event.h" @@ -50,9 +50,9 @@ void DNS_Interpreter::ParseMessage(const u_char* data, int len, int is_query) if ( dns_message ) analyzer->EnqueueConnEvent(dns_message, analyzer->ConnVal(), - val_mgr->Bool(is_query), + zeek::val_mgr->Bool(is_query), msg.BuildHdrVal(), - val_mgr->Count(len) + zeek::val_mgr->Count(len) ); // There is a great deal of non-DNS traffic that runs on port 53. @@ -89,9 +89,9 @@ void DNS_Interpreter::ParseMessage(const u_char* data, int len, int is_query) int skip_addl = dns_skip_all_addl; if ( msg.ancount > 0 ) { // We did an answer, so can potentially skip auth/addl. - static auto dns_skip_auth = zeek::id::find_val("dns_skip_auth"); - static auto dns_skip_addl = zeek::id::find_val("dns_skip_addl"); - auto server = make_intrusive(analyzer->Conn()->RespAddr()); + static auto dns_skip_auth = zeek::id::find_val("dns_skip_auth"); + static auto dns_skip_addl = zeek::id::find_val("dns_skip_addl"); + auto server = zeek::make_intrusive(analyzer->Conn()->RespAddr()); skip_auth = skip_auth || msg.nscount == 0 || dns_skip_auth->FindOrDefault(server); @@ -196,14 +196,14 @@ bool DNS_Interpreter::ParseQuestion(DNS_MsgInfo* msg, if ( dns_event && ! msg->skip_event ) { - BroString* original_name = new BroString(name, name_end - name, true); + zeek::String* original_name = new zeek::String(name, name_end - name, true); // Downcase the Name to normalize it for ( u_char* np = name; np < name_end; ++np ) if ( isupper(*np) ) *np = tolower(*np); - BroString* question_name = new BroString(name, name_end - name, true); + zeek::String* question_name = new zeek::String(name, name_end - name, true); SendReplyOrRejectEvent(msg, dns_event, data, len, question_name, original_name); } @@ -238,7 +238,7 @@ bool DNS_Interpreter::ParseAnswer(DNS_MsgInfo* msg, // Note that the exact meaning of some of these fields will be // re-interpreted by other, more adventurous RR types. - msg->query_name = make_intrusive(new BroString(name, name_end - name, true)); + msg->query_name = zeek::make_intrusive(new zeek::String(name, name_end - name, true)); msg->atype = RR_Type(ExtractShort(data, len)); msg->aclass = ExtractShort(data, len); msg->ttl = ExtractLong(data, len); @@ -562,7 +562,7 @@ bool DNS_Interpreter::ParseRR_Name(DNS_MsgInfo* msg, analyzer->ConnVal(), msg->BuildHdrVal(), msg->BuildAnswerVal(), - make_intrusive(new BroString(name, name_end - name, true)) + zeek::make_intrusive(new zeek::String(name, name_end - name, true)) ); return true; @@ -603,14 +603,14 @@ bool DNS_Interpreter::ParseRR_SOA(DNS_MsgInfo* msg, if ( dns_SOA_reply && ! msg->skip_event ) { static auto dns_soa = zeek::id::find_type("dns_soa"); - auto r = make_intrusive(dns_soa); - r->Assign(0, make_intrusive(new BroString(mname, mname_end - mname, true))); - r->Assign(1, make_intrusive(new BroString(rname, rname_end - rname, true))); - r->Assign(2, val_mgr->Count(serial)); - r->Assign(3, make_intrusive(double(refresh), Seconds)); - r->Assign(4, make_intrusive(double(retry), Seconds)); - r->Assign(5, make_intrusive(double(expire), Seconds)); - r->Assign(6, make_intrusive(double(minimum), Seconds)); + auto r = zeek::make_intrusive(dns_soa); + r->Assign(0, zeek::make_intrusive(new zeek::String(mname, mname_end - mname, true))); + r->Assign(1, zeek::make_intrusive(new zeek::String(rname, rname_end - rname, true))); + r->Assign(2, zeek::val_mgr->Count(serial)); + r->Assign(3, zeek::make_intrusive(double(refresh), Seconds)); + r->Assign(4, zeek::make_intrusive(double(retry), Seconds)); + r->Assign(5, zeek::make_intrusive(double(expire), Seconds)); + r->Assign(6, zeek::make_intrusive(double(minimum), Seconds)); analyzer->EnqueueConnEvent(dns_SOA_reply, analyzer->ConnVal(), @@ -646,8 +646,8 @@ bool DNS_Interpreter::ParseRR_MX(DNS_MsgInfo* msg, analyzer->ConnVal(), msg->BuildHdrVal(), msg->BuildAnswerVal(), - make_intrusive(new BroString(name, name_end - name, true)), - val_mgr->Count(preference) + zeek::make_intrusive(new zeek::String(name, name_end - name, true)), + zeek::val_mgr->Count(preference) ); return true; @@ -687,10 +687,10 @@ bool DNS_Interpreter::ParseRR_SRV(DNS_MsgInfo* msg, analyzer->ConnVal(), msg->BuildHdrVal(), msg->BuildAnswerVal(), - make_intrusive(new BroString(name, name_end - name, true)), - val_mgr->Count(priority), - val_mgr->Count(weight), - val_mgr->Count(port) + zeek::make_intrusive(new zeek::String(name, name_end - name, true)), + zeek::val_mgr->Count(priority), + zeek::val_mgr->Count(weight), + zeek::val_mgr->Count(port) ); return true; @@ -723,23 +723,23 @@ bool DNS_Interpreter::ParseRR_EDNS(DNS_MsgInfo* msg, } void DNS_Interpreter::ExtractOctets(const u_char*& data, int& len, - BroString** p) + zeek::String** p) { uint16_t dlen = ExtractShort(data, len); dlen = min(len, static_cast(dlen)); if ( p ) - *p = new BroString(data, dlen, false); + *p = new zeek::String(data, dlen, false); data += dlen; len -= dlen; } -BroString* DNS_Interpreter::ExtractStream(const u_char*& data, int& len, int l) +zeek::String* DNS_Interpreter::ExtractStream(const u_char*& data, int& len, int l) { l = max(l, 0); int dlen = min(len, l); // Len in bytes of the algorithm use - auto rval = new BroString(data, dlen, false); + auto rval = new zeek::String(data, dlen, false); data += dlen; len -= dlen; @@ -763,7 +763,7 @@ bool DNS_Interpreter::ParseRR_TSIG(DNS_MsgInfo* msg, uint32_t sign_time_sec = ExtractLong(data, len); unsigned int sign_time_msec = ExtractShort(data, len); unsigned int fudge = ExtractShort(data, len); - BroString* request_MAC; + zeek::String* request_MAC; ExtractOctets(data, len, dns_TSIG_addl ? &request_MAC : nullptr); unsigned int orig_id = ExtractShort(data, len); unsigned int rr_error = ExtractShort(data, len); @@ -773,7 +773,7 @@ bool DNS_Interpreter::ParseRR_TSIG(DNS_MsgInfo* msg, { TSIG_DATA tsig; tsig.alg_name = - new BroString(alg_name, alg_name_end - alg_name, true); + new zeek::String(alg_name, alg_name_end - alg_name, true); tsig.sig = request_MAC; tsig.time_s = sign_time_sec; tsig.time_ms = sign_time_msec; @@ -827,7 +827,7 @@ bool DNS_Interpreter::ParseRR_RRSIG(DNS_MsgInfo* msg, int sig_len = rdlength - ((data - data_start) + 18); DNSSEC_Algo dsa = DNSSEC_Algo(algo); - BroString* sign = ExtractStream(data, len, sig_len); + zeek::String* sign = ExtractStream(data, len, sig_len); switch ( dsa ) { case RSA_MD5: @@ -879,7 +879,7 @@ bool DNS_Interpreter::ParseRR_RRSIG(DNS_MsgInfo* msg, rrsig.sig_exp = sign_exp; rrsig.sig_incep = sign_incp; rrsig.key_tag = key_tag; - rrsig.signer_name = new BroString(name, name_end - name, true); + rrsig.signer_name = new zeek::String(name, name_end - name, true); rrsig.signature = sign; analyzer->EnqueueConnEvent(dns_RRSIG, @@ -914,7 +914,7 @@ bool DNS_Interpreter::ParseRR_DNSKEY(DNS_MsgInfo* msg, unsigned int dalgorithm = proto_algo & 0xff; DNSSEC_Algo dsa = DNSSEC_Algo(dalgorithm); //Evaluating the size of remaining bytes for Public Key - BroString* key = ExtractStream(data, len, rdlength - 4); + zeek::String* key = ExtractStream(data, len, rdlength - 4); // flags bit 7: zone key // flags bit 8: revoked @@ -1009,7 +1009,7 @@ bool DNS_Interpreter::ParseRR_NSEC(DNS_MsgInfo* msg, int typebitmaps_len = rdlength - (data - data_start); - auto char_strings = make_intrusive(zeek::id::string_vec); + auto char_strings = zeek::make_intrusive(zeek::id::string_vec); while ( typebitmaps_len > 0 && len > 0 ) { @@ -1023,8 +1023,8 @@ bool DNS_Interpreter::ParseRR_NSEC(DNS_MsgInfo* msg, break; } - BroString* bitmap = ExtractStream(data, len, bmlen); - char_strings->Assign(char_strings->Size(), make_intrusive(bitmap)); + zeek::String* bitmap = ExtractStream(data, len, bmlen); + char_strings->Assign(char_strings->Size(), zeek::make_intrusive(bitmap)); typebitmaps_len = typebitmaps_len - (2 + bmlen); } @@ -1033,7 +1033,7 @@ bool DNS_Interpreter::ParseRR_NSEC(DNS_MsgInfo* msg, analyzer->ConnVal(), msg->BuildHdrVal(), msg->BuildAnswerVal(), - make_intrusive(new BroString(name, name_end - name, true)), + zeek::make_intrusive(new zeek::String(name, name_end - name, true)), std::move(char_strings) ); @@ -1084,7 +1084,7 @@ bool DNS_Interpreter::ParseRR_NSEC3(DNS_MsgInfo* msg, int typebitmaps_len = rdlength - (data - data_start); - auto char_strings = make_intrusive(zeek::id::string_vec); + auto char_strings = zeek::make_intrusive(zeek::id::string_vec); while ( typebitmaps_len > 0 && len > 0 ) { @@ -1098,8 +1098,8 @@ bool DNS_Interpreter::ParseRR_NSEC3(DNS_MsgInfo* msg, break; } - BroString* bitmap = ExtractStream(data, len, bmlen); - char_strings->Assign(char_strings->Size(), make_intrusive(bitmap)); + zeek::String* bitmap = ExtractStream(data, len, bmlen); + char_strings->Assign(char_strings->Size(), zeek::make_intrusive(bitmap)); typebitmaps_len = typebitmaps_len - (2 + bmlen); } @@ -1146,7 +1146,7 @@ bool DNS_Interpreter::ParseRR_DS(DNS_MsgInfo* msg, unsigned int ds_algo = (ds_algo_dtype >> 8) & 0xff; unsigned int ds_dtype = ds_algo_dtype & 0xff; DNSSEC_Digest ds_digest_type = DNSSEC_Digest(ds_dtype); - BroString* ds_digest = ExtractStream(data, len, rdlength - 4); + zeek::String* ds_digest = ExtractStream(data, len, rdlength - 4); switch ( ds_digest_type ) { case SHA1: @@ -1200,7 +1200,7 @@ bool DNS_Interpreter::ParseRR_A(DNS_MsgInfo* msg, analyzer->ConnVal(), msg->BuildHdrVal(), msg->BuildAnswerVal(), - make_intrusive(htonl(addr)) + zeek::make_intrusive(htonl(addr)) ); return true; @@ -1236,7 +1236,7 @@ bool DNS_Interpreter::ParseRR_AAAA(DNS_MsgInfo* msg, analyzer->ConnVal(), msg->BuildHdrVal(), msg->BuildAnswerVal(), - make_intrusive(addr) + zeek::make_intrusive(addr) ); return true; @@ -1260,7 +1260,7 @@ bool DNS_Interpreter::ParseRR_HINFO(DNS_MsgInfo* msg, return true; } -static IntrusivePtr +static zeek::StringValPtr extract_char_string(analyzer::Analyzer* analyzer, const u_char*& data, int& len, int& rdlen) { @@ -1279,7 +1279,7 @@ extract_char_string(analyzer::Analyzer* analyzer, return nullptr; } - auto rval = make_intrusive(str_size, reinterpret_cast(data)); + auto rval = zeek::make_intrusive(str_size, reinterpret_cast(data)); rdlen -= str_size; len -= str_size; @@ -1299,8 +1299,8 @@ bool DNS_Interpreter::ParseRR_TXT(DNS_MsgInfo* msg, return true; } - auto char_strings = make_intrusive(zeek::id::string_vec); - IntrusivePtr char_string; + auto char_strings = zeek::make_intrusive(zeek::id::string_vec); + zeek::StringValPtr char_string; while ( (char_string = extract_char_string(analyzer, data, len, rdlength)) ) char_strings->Assign(char_strings->Size(), std::move(char_string)); @@ -1327,8 +1327,8 @@ bool DNS_Interpreter::ParseRR_SPF(DNS_MsgInfo* msg, return true; } - auto char_strings = make_intrusive(zeek::id::string_vec); - IntrusivePtr char_string; + auto char_strings = zeek::make_intrusive(zeek::id::string_vec); + zeek::StringValPtr char_string; while ( (char_string = extract_char_string(analyzer, data, len, rdlength)) ) char_strings->Assign(char_strings->Size(), std::move(char_string)); @@ -1364,11 +1364,11 @@ bool DNS_Interpreter::ParseRR_CAA(DNS_MsgInfo* msg, analyzer->Weird("DNS_CAA_char_str_past_rdlen"); return false; } - BroString* tag = new BroString(data, tagLen, true); + zeek::String* tag = new zeek::String(data, tagLen, true); len -= tagLen; data += tagLen; rdlength -= tagLen; - BroString* value = new BroString(data, rdlength, false); + zeek::String* value = new zeek::String(data, rdlength, false); len -= value->Len(); data += value->Len(); @@ -1379,9 +1379,9 @@ bool DNS_Interpreter::ParseRR_CAA(DNS_MsgInfo* msg, analyzer->ConnVal(), msg->BuildHdrVal(), msg->BuildAnswerVal(), - val_mgr->Count(flags), - make_intrusive(tag), - make_intrusive(value) + zeek::val_mgr->Count(flags), + zeek::make_intrusive(tag), + zeek::make_intrusive(value) ); else { @@ -1396,8 +1396,8 @@ bool DNS_Interpreter::ParseRR_CAA(DNS_MsgInfo* msg, void DNS_Interpreter::SendReplyOrRejectEvent(DNS_MsgInfo* msg, EventHandlerPtr event, const u_char*& data, int& len, - BroString* question_name, - BroString* original_name) + zeek::String* question_name, + zeek::String* original_name) { RR_Type qtype = RR_Type(ExtractShort(data, len)); int qclass = ExtractShort(data, len); @@ -1407,10 +1407,10 @@ void DNS_Interpreter::SendReplyOrRejectEvent(DNS_MsgInfo* msg, analyzer->EnqueueConnEvent(event, analyzer->ConnVal(), msg->BuildHdrVal(), - make_intrusive(question_name), - val_mgr->Count(qtype), - val_mgr->Count(qclass), - make_intrusive(original_name) + zeek::make_intrusive(question_name), + zeek::val_mgr->Count(qtype), + zeek::val_mgr->Count(qclass), + zeek::make_intrusive(original_name) ); } @@ -1446,57 +1446,57 @@ DNS_MsgInfo::DNS_MsgInfo(DNS_RawMsgHdr* hdr, int arg_is_query) skip_event = 0; } -IntrusivePtr DNS_MsgInfo::BuildHdrVal() +zeek::RecordValPtr DNS_MsgInfo::BuildHdrVal() { static auto dns_msg = zeek::id::find_type("dns_msg"); - auto r = make_intrusive(dns_msg); + auto r = zeek::make_intrusive(dns_msg); - r->Assign(0, val_mgr->Count(id)); - r->Assign(1, val_mgr->Count(opcode)); - r->Assign(2, val_mgr->Count(rcode)); - r->Assign(3, val_mgr->Bool(QR)); - r->Assign(4, val_mgr->Bool(AA)); - r->Assign(5, val_mgr->Bool(TC)); - r->Assign(6, val_mgr->Bool(RD)); - r->Assign(7, val_mgr->Bool(RA)); - r->Assign(8, val_mgr->Count(Z)); - r->Assign(9, val_mgr->Count(qdcount)); - r->Assign(10, val_mgr->Count(ancount)); - r->Assign(11, val_mgr->Count(nscount)); - r->Assign(12, val_mgr->Count(arcount)); + r->Assign(0, zeek::val_mgr->Count(id)); + r->Assign(1, zeek::val_mgr->Count(opcode)); + r->Assign(2, zeek::val_mgr->Count(rcode)); + r->Assign(3, zeek::val_mgr->Bool(QR)); + r->Assign(4, zeek::val_mgr->Bool(AA)); + r->Assign(5, zeek::val_mgr->Bool(TC)); + r->Assign(6, zeek::val_mgr->Bool(RD)); + r->Assign(7, zeek::val_mgr->Bool(RA)); + r->Assign(8, zeek::val_mgr->Count(Z)); + r->Assign(9, zeek::val_mgr->Count(qdcount)); + r->Assign(10, zeek::val_mgr->Count(ancount)); + r->Assign(11, zeek::val_mgr->Count(nscount)); + r->Assign(12, zeek::val_mgr->Count(arcount)); return r; } -IntrusivePtr DNS_MsgInfo::BuildAnswerVal() +zeek::RecordValPtr DNS_MsgInfo::BuildAnswerVal() { static auto dns_answer = zeek::id::find_type("dns_answer"); - auto r = make_intrusive(dns_answer); + auto r = zeek::make_intrusive(dns_answer); - r->Assign(0, val_mgr->Count(int(answer_type))); + r->Assign(0, zeek::val_mgr->Count(int(answer_type))); r->Assign(1, query_name); - r->Assign(2, val_mgr->Count(atype)); - r->Assign(3, val_mgr->Count(aclass)); - r->Assign(4, make_intrusive(double(ttl), Seconds)); + r->Assign(2, zeek::val_mgr->Count(atype)); + r->Assign(3, zeek::val_mgr->Count(aclass)); + r->Assign(4, zeek::make_intrusive(double(ttl), Seconds)); return r; } -IntrusivePtr DNS_MsgInfo::BuildEDNS_Val() +zeek::RecordValPtr DNS_MsgInfo::BuildEDNS_Val() { // We have to treat the additional record type in EDNS differently // than a regular resource record. static auto dns_edns_additional = zeek::id::find_type("dns_edns_additional"); - auto r = make_intrusive(dns_edns_additional); + auto r = zeek::make_intrusive(dns_edns_additional); - r->Assign(0, val_mgr->Count(int(answer_type))); + r->Assign(0, zeek::val_mgr->Count(int(answer_type))); r->Assign(1, query_name); // type = 0x29 or 41 = EDNS - r->Assign(2, val_mgr->Count(atype)); + r->Assign(2, zeek::val_mgr->Count(atype)); // sender's UDP payload size, per RFC 2671 4.3 - r->Assign(3, val_mgr->Count(aclass)); + r->Assign(3, zeek::val_mgr->Count(aclass)); // Need to break the TTL field into three components: // initial: [------------- ttl (32) ---------------------] @@ -1509,104 +1509,104 @@ IntrusivePtr DNS_MsgInfo::BuildEDNS_Val() unsigned int return_error = (ercode << 8) | rcode; - r->Assign(4, val_mgr->Count(return_error)); - r->Assign(5, val_mgr->Count(version)); - r->Assign(6, val_mgr->Count(z)); - r->Assign(7, make_intrusive(double(ttl), Seconds)); - r->Assign(8, val_mgr->Count(is_query)); + r->Assign(4, zeek::val_mgr->Count(return_error)); + r->Assign(5, zeek::val_mgr->Count(version)); + r->Assign(6, zeek::val_mgr->Count(z)); + r->Assign(7, zeek::make_intrusive(double(ttl), Seconds)); + r->Assign(8, zeek::val_mgr->Count(is_query)); return r; } -IntrusivePtr DNS_MsgInfo::BuildTSIG_Val(struct TSIG_DATA* tsig) +zeek::RecordValPtr DNS_MsgInfo::BuildTSIG_Val(struct TSIG_DATA* tsig) { static auto dns_tsig_additional = zeek::id::find_type("dns_tsig_additional"); - auto r = make_intrusive(dns_tsig_additional); + auto r = zeek::make_intrusive(dns_tsig_additional); double rtime = tsig->time_s + tsig->time_ms / 1000.0; - // r->Assign(0, val_mgr->Count(int(answer_type))); + // r->Assign(0, zeek::val_mgr->Count(int(answer_type))); r->Assign(0, query_name); - r->Assign(1, val_mgr->Count(int(answer_type))); - r->Assign(2, make_intrusive(tsig->alg_name)); - r->Assign(3, make_intrusive(tsig->sig)); - r->Assign(4, make_intrusive(rtime)); - r->Assign(5, make_intrusive(double(tsig->fudge))); - r->Assign(6, val_mgr->Count(tsig->orig_id)); - r->Assign(7, val_mgr->Count(tsig->rr_error)); - r->Assign(8, val_mgr->Count(is_query)); + r->Assign(1, zeek::val_mgr->Count(int(answer_type))); + r->Assign(2, zeek::make_intrusive(tsig->alg_name)); + r->Assign(3, zeek::make_intrusive(tsig->sig)); + r->Assign(4, zeek::make_intrusive(rtime)); + r->Assign(5, zeek::make_intrusive(double(tsig->fudge))); + r->Assign(6, zeek::val_mgr->Count(tsig->orig_id)); + r->Assign(7, zeek::val_mgr->Count(tsig->rr_error)); + r->Assign(8, zeek::val_mgr->Count(is_query)); return r; } -IntrusivePtr DNS_MsgInfo::BuildRRSIG_Val(RRSIG_DATA* rrsig) +zeek::RecordValPtr DNS_MsgInfo::BuildRRSIG_Val(RRSIG_DATA* rrsig) { static auto dns_rrsig_rr = zeek::id::find_type("dns_rrsig_rr"); - auto r = make_intrusive(dns_rrsig_rr); + auto r = zeek::make_intrusive(dns_rrsig_rr); r->Assign(0, query_name); - r->Assign(1, val_mgr->Count(int(answer_type))); - r->Assign(2, val_mgr->Count(rrsig->type_covered)); - r->Assign(3, val_mgr->Count(rrsig->algorithm)); - r->Assign(4, val_mgr->Count(rrsig->labels)); - r->Assign(5, make_intrusive(double(rrsig->orig_ttl), Seconds)); - r->Assign(6, make_intrusive(double(rrsig->sig_exp))); - r->Assign(7, make_intrusive(double(rrsig->sig_incep))); - r->Assign(8, val_mgr->Count(rrsig->key_tag)); - r->Assign(9, make_intrusive(rrsig->signer_name)); - r->Assign(10, make_intrusive(rrsig->signature)); - r->Assign(11, val_mgr->Count(is_query)); + r->Assign(1, zeek::val_mgr->Count(int(answer_type))); + r->Assign(2, zeek::val_mgr->Count(rrsig->type_covered)); + r->Assign(3, zeek::val_mgr->Count(rrsig->algorithm)); + r->Assign(4, zeek::val_mgr->Count(rrsig->labels)); + r->Assign(5, zeek::make_intrusive(double(rrsig->orig_ttl), Seconds)); + r->Assign(6, zeek::make_intrusive(double(rrsig->sig_exp))); + r->Assign(7, zeek::make_intrusive(double(rrsig->sig_incep))); + r->Assign(8, zeek::val_mgr->Count(rrsig->key_tag)); + r->Assign(9, zeek::make_intrusive(rrsig->signer_name)); + r->Assign(10, zeek::make_intrusive(rrsig->signature)); + r->Assign(11, zeek::val_mgr->Count(is_query)); return r; } -IntrusivePtr DNS_MsgInfo::BuildDNSKEY_Val(DNSKEY_DATA* dnskey) +zeek::RecordValPtr DNS_MsgInfo::BuildDNSKEY_Val(DNSKEY_DATA* dnskey) { static auto dns_dnskey_rr = zeek::id::find_type("dns_dnskey_rr"); - auto r = make_intrusive(dns_dnskey_rr); + auto r = zeek::make_intrusive(dns_dnskey_rr); r->Assign(0, query_name); - r->Assign(1, val_mgr->Count(int(answer_type))); - r->Assign(2, val_mgr->Count(dnskey->dflags)); - r->Assign(3, val_mgr->Count(dnskey->dprotocol)); - r->Assign(4, val_mgr->Count(dnskey->dalgorithm)); - r->Assign(5, make_intrusive(dnskey->public_key)); - r->Assign(6, val_mgr->Count(is_query)); + r->Assign(1, zeek::val_mgr->Count(int(answer_type))); + r->Assign(2, zeek::val_mgr->Count(dnskey->dflags)); + r->Assign(3, zeek::val_mgr->Count(dnskey->dprotocol)); + r->Assign(4, zeek::val_mgr->Count(dnskey->dalgorithm)); + r->Assign(5, zeek::make_intrusive(dnskey->public_key)); + r->Assign(6, zeek::val_mgr->Count(is_query)); return r; } -IntrusivePtr DNS_MsgInfo::BuildNSEC3_Val(NSEC3_DATA* nsec3) +zeek::RecordValPtr DNS_MsgInfo::BuildNSEC3_Val(NSEC3_DATA* nsec3) { static auto dns_nsec3_rr = zeek::id::find_type("dns_nsec3_rr"); - auto r = make_intrusive(dns_nsec3_rr); + auto r = zeek::make_intrusive(dns_nsec3_rr); r->Assign(0, query_name); - r->Assign(1, val_mgr->Count(int(answer_type))); - r->Assign(2, val_mgr->Count(nsec3->nsec_flags)); - r->Assign(3, val_mgr->Count(nsec3->nsec_hash_algo)); - r->Assign(4, val_mgr->Count(nsec3->nsec_iter)); - r->Assign(5, val_mgr->Count(nsec3->nsec_salt_len)); - r->Assign(6, make_intrusive(nsec3->nsec_salt)); - r->Assign(7, val_mgr->Count(nsec3->nsec_hlen)); - r->Assign(8, make_intrusive(nsec3->nsec_hash)); + r->Assign(1, zeek::val_mgr->Count(int(answer_type))); + r->Assign(2, zeek::val_mgr->Count(nsec3->nsec_flags)); + r->Assign(3, zeek::val_mgr->Count(nsec3->nsec_hash_algo)); + r->Assign(4, zeek::val_mgr->Count(nsec3->nsec_iter)); + r->Assign(5, zeek::val_mgr->Count(nsec3->nsec_salt_len)); + r->Assign(6, zeek::make_intrusive(nsec3->nsec_salt)); + r->Assign(7, zeek::val_mgr->Count(nsec3->nsec_hlen)); + r->Assign(8, zeek::make_intrusive(nsec3->nsec_hash)); r->Assign(9, std::move(nsec3->bitmaps)); - r->Assign(10, val_mgr->Count(is_query)); + r->Assign(10, zeek::val_mgr->Count(is_query)); return r; } -IntrusivePtr DNS_MsgInfo::BuildDS_Val(DS_DATA* ds) +zeek::RecordValPtr DNS_MsgInfo::BuildDS_Val(DS_DATA* ds) { static auto dns_ds_rr = zeek::id::find_type("dns_ds_rr"); - auto r = make_intrusive(dns_ds_rr); + auto r = zeek::make_intrusive(dns_ds_rr); r->Assign(0, query_name); - r->Assign(1, val_mgr->Count(int(answer_type))); - r->Assign(2, val_mgr->Count(ds->key_tag)); - r->Assign(3, val_mgr->Count(ds->algorithm)); - r->Assign(4, val_mgr->Count(ds->digest_type)); - r->Assign(5, make_intrusive(ds->digest_val)); - r->Assign(6, val_mgr->Count(is_query)); + r->Assign(1, zeek::val_mgr->Count(int(answer_type))); + r->Assign(2, zeek::val_mgr->Count(ds->key_tag)); + r->Assign(3, zeek::val_mgr->Count(ds->algorithm)); + r->Assign(4, zeek::val_mgr->Count(ds->digest_type)); + r->Assign(5, zeek::make_intrusive(ds->digest_val)); + r->Assign(6, zeek::val_mgr->Count(is_query)); return r; } diff --git a/src/analyzer/protocol/dns/DNS.h b/src/analyzer/protocol/dns/DNS.h index 040a1c000d..73a882a985 100644 --- a/src/analyzer/protocol/dns/DNS.h +++ b/src/analyzer/protocol/dns/DNS.h @@ -129,10 +129,10 @@ struct EDNS_ADDITIONAL { // size }; struct TSIG_DATA { - BroString* alg_name; + zeek::String* alg_name; unsigned long time_s; unsigned short time_ms; - BroString* sig; + zeek::String* sig; unsigned short fudge; unsigned short orig_id; unsigned short rr_error; @@ -146,15 +146,15 @@ struct RRSIG_DATA { unsigned long sig_exp; // 32 unsigned long sig_incep; // 32 unsigned short key_tag; //16 - BroString* signer_name; - BroString* signature; + zeek::String* signer_name; + zeek::String* signature; }; struct DNSKEY_DATA { unsigned short dflags; // 16 : ExtractShort(data, len) unsigned short dalgorithm; // 8 unsigned short dprotocol; // 8 - BroString* public_key; // Variable lenght Public Key + zeek::String* public_key; // Variable lenght Public Key }; struct NSEC3_DATA { @@ -162,31 +162,31 @@ struct NSEC3_DATA { unsigned short nsec_hash_algo; unsigned short nsec_iter; unsigned short nsec_salt_len; - BroString* nsec_salt; + zeek::String* nsec_salt; unsigned short nsec_hlen; - BroString* nsec_hash; - IntrusivePtr bitmaps; + zeek::String* nsec_hash; + zeek::VectorValPtr bitmaps; }; struct DS_DATA { unsigned short key_tag; // 16 : ExtractShort(data, len) unsigned short algorithm; // 8 unsigned short digest_type; // 8 - BroString* digest_val; // Variable lenght Digest of DNSKEY RR + zeek::String* digest_val; // Variable lenght Digest of DNSKEY RR }; class DNS_MsgInfo { public: DNS_MsgInfo(DNS_RawMsgHdr* hdr, int is_query); - IntrusivePtr BuildHdrVal(); - IntrusivePtr BuildAnswerVal(); - IntrusivePtr BuildEDNS_Val(); - IntrusivePtr BuildTSIG_Val(struct TSIG_DATA*); - IntrusivePtr BuildRRSIG_Val(struct RRSIG_DATA*); - IntrusivePtr BuildDNSKEY_Val(struct DNSKEY_DATA*); - IntrusivePtr BuildNSEC3_Val(struct NSEC3_DATA*); - IntrusivePtr BuildDS_Val(struct DS_DATA*); + zeek::RecordValPtr BuildHdrVal(); + zeek::RecordValPtr BuildAnswerVal(); + zeek::RecordValPtr BuildEDNS_Val(); + zeek::RecordValPtr BuildTSIG_Val(struct TSIG_DATA*); + zeek::RecordValPtr BuildRRSIG_Val(struct RRSIG_DATA*); + zeek::RecordValPtr BuildDNSKEY_Val(struct DNSKEY_DATA*); + zeek::RecordValPtr BuildNSEC3_Val(struct NSEC3_DATA*); + zeek::RecordValPtr BuildDS_Val(struct DS_DATA*); int id; int opcode; ///< query type, see DNS_Opcode @@ -203,7 +203,7 @@ public: int arcount; ///< number of additional RRs int is_query; ///< whether it came from the session initiator - IntrusivePtr query_name; + zeek::StringValPtr query_name; RR_Type atype; int aclass; ///< normally = 1, inet uint32_t ttl; @@ -249,9 +249,9 @@ protected: uint16_t ExtractShort(const u_char*& data, int& len); uint32_t ExtractLong(const u_char*& data, int& len); - void ExtractOctets(const u_char*& data, int& len, BroString** p); + void ExtractOctets(const u_char*& data, int& len, zeek::String** p); - BroString* ExtractStream(const u_char*& data, int& len, int sig_len); + zeek::String* ExtractStream(const u_char*& data, int& len, int sig_len); bool ParseRR_Name(DNS_MsgInfo* msg, const u_char*& data, int& len, int rdlength, @@ -308,7 +308,8 @@ protected: const u_char* msg_start); void SendReplyOrRejectEvent(DNS_MsgInfo* msg, EventHandlerPtr event, const u_char*& data, int& len, - BroString* question_name, BroString* original_name); + zeek::String* question_name, + zeek::String* original_name); analyzer::Analyzer* analyzer; bool first_message; diff --git a/src/analyzer/protocol/file/File.cc b/src/analyzer/protocol/file/File.cc index 7bb91df028..9a313e3883 100644 --- a/src/analyzer/protocol/file/File.cc +++ b/src/analyzer/protocol/file/File.cc @@ -79,10 +79,11 @@ void File_Analyzer::Identify() : *(matches.begin()->second.begin()); if ( file_transferred ) - EnqueueConnEvent(file_transferred, + EnqueueConnEvent( + file_transferred, ConnVal(), - make_intrusive(buffer_len, buffer), - make_intrusive(""), - make_intrusive(match) + zeek::make_intrusive(buffer_len, buffer), + zeek::make_intrusive(""), + zeek::make_intrusive(match) ); } diff --git a/src/analyzer/protocol/finger/Finger.cc b/src/analyzer/protocol/finger/Finger.cc index 2d96eabe1a..28a4ea8236 100644 --- a/src/analyzer/protocol/finger/Finger.cc +++ b/src/analyzer/protocol/finger/Finger.cc @@ -69,9 +69,9 @@ void Finger_Analyzer::DeliverStream(int length, const u_char* data, bool is_orig if ( finger_request ) EnqueueConnEvent(finger_request, ConnVal(), - val_mgr->Bool(long_cnt), - make_intrusive(at - line, line), - make_intrusive(end_of_line - host, host) + zeek::val_mgr->Bool(long_cnt), + zeek::make_intrusive(at - line, line), + zeek::make_intrusive(end_of_line - host, host) ); Conn()->Match(Rule::FINGER, (const u_char *) line, @@ -87,7 +87,7 @@ void Finger_Analyzer::DeliverStream(int length, const u_char* data, bool is_orig EnqueueConnEvent(finger_reply, ConnVal(), - make_intrusive(end_of_line - line, line) + zeek::make_intrusive(end_of_line - line, line) ); } } diff --git a/src/analyzer/protocol/ftp/FTP.cc b/src/analyzer/protocol/ftp/FTP.cc index 9fcaaf3d73..f62b9a43f2 100644 --- a/src/analyzer/protocol/ftp/FTP.cc +++ b/src/analyzer/protocol/ftp/FTP.cc @@ -5,7 +5,7 @@ #include -#include "BroString.h" +#include "ZeekString.h" #include "NetVar.h" #include "Event.h" #include "Base64.h" @@ -82,7 +82,7 @@ void FTP_Analyzer::DeliverStream(int length, const u_char* data, bool orig) { int cmd_len; const char* cmd; - StringVal* cmd_str; + zeek::StringVal* cmd_str; line = skip_whitespace(line, end_of_line); get_word(end_of_line - line, line, cmd_len, cmd); @@ -91,15 +91,15 @@ void FTP_Analyzer::DeliverStream(int length, const u_char* data, bool orig) if ( cmd_len == 0 ) { // Weird("FTP command missing", end_of_line - orig_line, orig_line); - cmd_str = new StringVal(""); + cmd_str = new zeek::StringVal(""); } else - cmd_str = (new StringVal(cmd_len, cmd))->ToUpper(); + cmd_str = (new zeek::StringVal(cmd_len, cmd))->ToUpper(); vl = { ConnVal(), - IntrusivePtr{AdoptRef{}, cmd_str}, - make_intrusive(end_of_line - line, line), + zeek::IntrusivePtr{zeek::AdoptRef{}, cmd_str}, + zeek::make_intrusive(end_of_line - line, line), }; f = ftp_request; @@ -177,9 +177,9 @@ void FTP_Analyzer::DeliverStream(int length, const u_char* data, bool orig) vl = { ConnVal(), - val_mgr->Count(reply_code), - make_intrusive(end_of_line - line, line), - val_mgr->Bool(cont_resp) + zeek::val_mgr->Count(reply_code), + zeek::make_intrusive(end_of_line - line, line), + zeek::val_mgr->Bool(cont_resp) }; f = ftp_reply; @@ -204,7 +204,7 @@ void FTP_ADAT_Analyzer::DeliverStream(int len, const u_char* data, bool orig) const char* line = (const char*) data; const char* end_of_line = line + len; - BroString* decoded_adat = nullptr; + zeek::String* decoded_adat = nullptr; if ( orig ) { @@ -216,7 +216,7 @@ void FTP_ADAT_Analyzer::DeliverStream(int len, const u_char* data, bool orig) if ( strncmp(cmd, "ADAT", cmd_len) == 0 ) { line = skip_whitespace(line + cmd_len, end_of_line); - StringVal encoded(end_of_line - line, line); + zeek::StringVal encoded(end_of_line - line, line); decoded_adat = decode_base64(encoded.AsString(), nullptr, Conn()); if ( first_token ) @@ -291,7 +291,7 @@ void FTP_ADAT_Analyzer::DeliverStream(int len, const u_char* data, bool orig) if ( end_of_line - line >= 5 && strncmp(line, "ADAT=", 5) == 0 ) { line += 5; - StringVal encoded(end_of_line - line, line); + zeek::StringVal encoded(end_of_line - line, line); decoded_adat = decode_base64(encoded.AsString(), nullptr, Conn()); } diff --git a/src/analyzer/protocol/ftp/functions.bif b/src/analyzer/protocol/ftp/functions.bif index 204481b575..7bf05a049b 100644 --- a/src/analyzer/protocol/ftp/functions.bif +++ b/src/analyzer/protocol/ftp/functions.bif @@ -4,9 +4,9 @@ type ftp_port: record; %%{ #include "Reporter.h" -static IntrusivePtr parse_port(const char* line) +static zeek::ValPtr parse_port(const char* line) { - auto r = make_intrusive(zeek::BifType::Record::ftp_port); + auto r = zeek::make_intrusive(zeek::BifType::Record::ftp_port); int bytes[6]; if ( line && sscanf(line, "%d,%d,%d,%d,%d,%d", @@ -33,23 +33,23 @@ static IntrusivePtr parse_port(const char* line) good = 0; } - r->Assign(0, make_intrusive(htonl(addr))); - r->Assign(1, val_mgr->Port(port, TRANSPORT_TCP)); - r->Assign(2, val_mgr->Bool(good)); + r->Assign(0, zeek::make_intrusive(htonl(addr))); + r->Assign(1, zeek::val_mgr->Port(port, TRANSPORT_TCP)); + r->Assign(2, zeek::val_mgr->Bool(good)); } else { - r->Assign(0, make_intrusive(uint32_t(0))); - r->Assign(1, val_mgr->Port(0, TRANSPORT_TCP)); - r->Assign(2, val_mgr->False()); + r->Assign(0, zeek::make_intrusive(uint32_t(0))); + r->Assign(1, zeek::val_mgr->Port(0, TRANSPORT_TCP)); + r->Assign(2, zeek::val_mgr->False()); } return r; } -static IntrusivePtr parse_eftp(const char* line) +static zeek::ValPtr parse_eftp(const char* line) { - auto r = make_intrusive(zeek::BifType::Record::ftp_port); + auto r = zeek::make_intrusive(zeek::BifType::Record::ftp_port); int net_proto = 0; // currently not used IPAddr addr; // unspecified IPv6 address (all 128 bits zero) @@ -109,9 +109,9 @@ static IntrusivePtr parse_eftp(const char* line) } - r->Assign(0, make_intrusive(addr)); - r->Assign(1, val_mgr->Port(port, TRANSPORT_TCP)); - r->Assign(2, val_mgr->Bool(good)); + r->Assign(0, zeek::make_intrusive(addr)); + r->Assign(1, zeek::val_mgr->Port(port, TRANSPORT_TCP)); + r->Assign(2, zeek::val_mgr->Bool(good)); return r; } @@ -206,15 +206,15 @@ function fmt_ftp_port%(a: addr, p: port%): string { uint32_t a = ntohl(addr[0]); uint32_t pn = p->Port(); - return make_intrusive(fmt("%d,%d,%d,%d,%d,%d", - a >> 24, (a >> 16) & 0xff, - (a >> 8) & 0xff, a & 0xff, - pn >> 8, pn & 0xff)); + return zeek::make_intrusive(fmt("%d,%d,%d,%d,%d,%d", + a >> 24, (a >> 16) & 0xff, + (a >> 8) & 0xff, a & 0xff, + pn >> 8, pn & 0xff)); } else { - builtin_error("conversion of non-IPv4 address in fmt_ftp_port", - @ARG@[0]); - return val_mgr->EmptyString(); + zeek::emit_builtin_error("conversion of non-IPv4 address in fmt_ftp_port", + @ARG@[0]); + return zeek::val_mgr->EmptyString(); } %} diff --git a/src/analyzer/protocol/gnutella/Gnutella.cc b/src/analyzer/protocol/gnutella/Gnutella.cc index 6b2d487c9a..089beaa3f9 100644 --- a/src/analyzer/protocol/gnutella/Gnutella.cc +++ b/src/analyzer/protocol/gnutella/Gnutella.cc @@ -72,11 +72,10 @@ void Gnutella_Analyzer::Done() { if ( ! p->msg_sent && p->msg_pos ) EnqueueConnEvent(gnutella_partial_binary_msg, - ConnVal(), - make_intrusive(p->msg), - val_mgr->Bool((i == 0)), - val_mgr->Count(p->msg_pos) - ); + ConnVal(), + zeek::make_intrusive(p->msg), + zeek::val_mgr->Bool((i == 0)), + zeek::val_mgr->Count(p->msg_pos)); else if ( ! p->msg_sent && p->payload_left ) SendEvents(p, (i == 0)); @@ -177,10 +176,9 @@ void Gnutella_Analyzer::DeliverLines(int len, const u_char* data, bool orig) { if ( gnutella_text_msg ) EnqueueConnEvent(gnutella_text_msg, - ConnVal(), - val_mgr->Bool(orig), - make_intrusive(ms->headers.data()) - ); + ConnVal(), + zeek::val_mgr->Bool(orig), + zeek::make_intrusive(ms->headers.data())); ms->headers = ""; state |= new_state; @@ -215,17 +213,16 @@ void Gnutella_Analyzer::SendEvents(GnutellaMsgState* p, bool is_orig) if ( gnutella_binary_msg ) EnqueueConnEvent(gnutella_binary_msg, - ConnVal(), - val_mgr->Bool(is_orig), - val_mgr->Count(p->msg_type), - val_mgr->Count(p->msg_ttl), - val_mgr->Count(p->msg_hops), - val_mgr->Count(p->msg_len), - make_intrusive(p->payload), - val_mgr->Count(p->payload_len), - val_mgr->Bool((p->payload_len < std::min(p->msg_len, (unsigned int)GNUTELLA_MAX_PAYLOAD))), - val_mgr->Bool((p->payload_left == 0)) - ); + ConnVal(), + zeek::val_mgr->Bool(is_orig), + zeek::val_mgr->Count(p->msg_type), + zeek::val_mgr->Count(p->msg_ttl), + zeek::val_mgr->Count(p->msg_hops), + zeek::val_mgr->Count(p->msg_len), + zeek::make_intrusive(p->payload), + zeek::val_mgr->Count(p->payload_len), + zeek::val_mgr->Bool((p->payload_len < std::min(p->msg_len, (unsigned int)GNUTELLA_MAX_PAYLOAD))), + zeek::val_mgr->Bool((p->payload_left == 0))); } diff --git a/src/analyzer/protocol/gtpv1/gtpv1-analyzer.pac b/src/analyzer/protocol/gtpv1/gtpv1-analyzer.pac index 00eae1b5f1..d49578ef2f 100644 --- a/src/analyzer/protocol/gtpv1/gtpv1-analyzer.pac +++ b/src/analyzer/protocol/gtpv1/gtpv1-analyzer.pac @@ -1,93 +1,93 @@ %extern{ #include "Sessions.h" -#include "BroString.h" +#include "ZeekString.h" %} %code{ -IntrusivePtr BuildGTPv1Hdr(const GTPv1_Header* pdu) +zeek::RecordValPtr BuildGTPv1Hdr(const GTPv1_Header* pdu) { - auto rv = make_intrusive(zeek::BifType::Record::gtpv1_hdr); + auto rv = zeek::make_intrusive(zeek::BifType::Record::gtpv1_hdr); - rv->Assign(0, val_mgr->Count(pdu->version())); - rv->Assign(1, val_mgr->Bool(pdu->pt_flag())); - rv->Assign(2, val_mgr->Bool(pdu->rsv())); - rv->Assign(3, val_mgr->Bool(pdu->e_flag())); - rv->Assign(4, val_mgr->Bool(pdu->s_flag())); - rv->Assign(5, val_mgr->Bool(pdu->pn_flag())); - rv->Assign(6, val_mgr->Count(pdu->msg_type())); - rv->Assign(7, val_mgr->Count(pdu->length())); - rv->Assign(8, val_mgr->Count(pdu->teid())); + rv->Assign(0, zeek::val_mgr->Count(pdu->version())); + rv->Assign(1, zeek::val_mgr->Bool(pdu->pt_flag())); + rv->Assign(2, zeek::val_mgr->Bool(pdu->rsv())); + rv->Assign(3, zeek::val_mgr->Bool(pdu->e_flag())); + rv->Assign(4, zeek::val_mgr->Bool(pdu->s_flag())); + rv->Assign(5, zeek::val_mgr->Bool(pdu->pn_flag())); + rv->Assign(6, zeek::val_mgr->Count(pdu->msg_type())); + rv->Assign(7, zeek::val_mgr->Count(pdu->length())); + rv->Assign(8, zeek::val_mgr->Count(pdu->teid())); if ( pdu->has_opt() ) { - rv->Assign(9, val_mgr->Count(pdu->opt_hdr()->seq())); - rv->Assign(10, val_mgr->Count(pdu->opt_hdr()->n_pdu())); - rv->Assign(11, val_mgr->Count(pdu->opt_hdr()->next_type())); + rv->Assign(9, zeek::val_mgr->Count(pdu->opt_hdr()->seq())); + rv->Assign(10, zeek::val_mgr->Count(pdu->opt_hdr()->n_pdu())); + rv->Assign(11, zeek::val_mgr->Count(pdu->opt_hdr()->next_type())); } return rv; } -static IntrusivePtr BuildIMSI(const InformationElement* ie) +static zeek::ValPtr BuildIMSI(const InformationElement* ie) { - return val_mgr->Count(ie->imsi()->value()); + return zeek::val_mgr->Count(ie->imsi()->value()); } -static IntrusivePtr BuildRAI(const InformationElement* ie) +static zeek::ValPtr BuildRAI(const InformationElement* ie) { - auto ev = make_intrusive(zeek::BifType::Record::gtp_rai); - ev->Assign(0, val_mgr->Count(ie->rai()->mcc())); - ev->Assign(1, val_mgr->Count(ie->rai()->mnc())); - ev->Assign(2, val_mgr->Count(ie->rai()->lac())); - ev->Assign(3, val_mgr->Count(ie->rai()->rac())); + auto ev = zeek::make_intrusive(zeek::BifType::Record::gtp_rai); + ev->Assign(0, zeek::val_mgr->Count(ie->rai()->mcc())); + ev->Assign(1, zeek::val_mgr->Count(ie->rai()->mnc())); + ev->Assign(2, zeek::val_mgr->Count(ie->rai()->lac())); + ev->Assign(3, zeek::val_mgr->Count(ie->rai()->rac())); return ev; } -static IntrusivePtr BuildRecovery(const InformationElement* ie) +static zeek::ValPtr BuildRecovery(const InformationElement* ie) { - return val_mgr->Count(ie->recovery()->restart_counter()); + return zeek::val_mgr->Count(ie->recovery()->restart_counter()); } -static IntrusivePtr BuildSelectionMode(const InformationElement* ie) +static zeek::ValPtr BuildSelectionMode(const InformationElement* ie) { - return val_mgr->Count(ie->selection_mode()->mode()); + return zeek::val_mgr->Count(ie->selection_mode()->mode()); } -static IntrusivePtr BuildTEID1(const InformationElement* ie) +static zeek::ValPtr BuildTEID1(const InformationElement* ie) { - return val_mgr->Count(ie->teid1()->value()); + return zeek::val_mgr->Count(ie->teid1()->value()); } -static IntrusivePtr BuildTEID_ControlPlane(const InformationElement* ie) +static zeek::ValPtr BuildTEID_ControlPlane(const InformationElement* ie) { - return val_mgr->Count(ie->teidcp()->value()); + return zeek::val_mgr->Count(ie->teidcp()->value()); } -static IntrusivePtr BuildNSAPI(const InformationElement* ie) +static zeek::ValPtr BuildNSAPI(const InformationElement* ie) { - return val_mgr->Count(ie->nsapi()->nsapi()); + return zeek::val_mgr->Count(ie->nsapi()->nsapi()); } -static IntrusivePtr BuildChargingCharacteristics(const InformationElement* ie) +static zeek::ValPtr BuildChargingCharacteristics(const InformationElement* ie) { - return val_mgr->Count(ie->charging_characteristics()->value()); + return zeek::val_mgr->Count(ie->charging_characteristics()->value()); } -static IntrusivePtr BuildTraceReference(const InformationElement* ie) +static zeek::ValPtr BuildTraceReference(const InformationElement* ie) { - return val_mgr->Count(ie->trace_reference()->value()); + return zeek::val_mgr->Count(ie->trace_reference()->value()); } -static IntrusivePtr BuildTraceType(const InformationElement* ie) +static zeek::ValPtr BuildTraceType(const InformationElement* ie) { - return val_mgr->Count(ie->trace_type()->value()); + return zeek::val_mgr->Count(ie->trace_type()->value()); } -IntrusivePtr BuildEndUserAddr(const InformationElement* ie) +zeek::ValPtr BuildEndUserAddr(const InformationElement* ie) { - auto ev = make_intrusive(zeek::BifType::Record::gtp_end_user_addr); - ev->Assign(0, val_mgr->Count(ie->end_user_addr()->pdp_type_org())); - ev->Assign(1, val_mgr->Count(ie->end_user_addr()->pdp_type_num())); + auto ev = zeek::make_intrusive(zeek::BifType::Record::gtp_end_user_addr); + ev->Assign(0, zeek::val_mgr->Count(ie->end_user_addr()->pdp_type_org())); + ev->Assign(1, zeek::val_mgr->Count(ie->end_user_addr()->pdp_type_num())); int len = ie->end_user_addr()->pdp_addr().length(); @@ -97,16 +97,16 @@ IntrusivePtr BuildEndUserAddr(const InformationElement* ie) switch ( ie->end_user_addr()->pdp_type_num() ) { case 0x21: - ev->Assign(2, make_intrusive( + ev->Assign(2, zeek::make_intrusive( IPAddr(IPv4, (const uint32*) d, IPAddr::Network))); break; case 0x57: - ev->Assign(2, make_intrusive( + ev->Assign(2, zeek::make_intrusive( IPAddr(IPv6, (const uint32*) d, IPAddr::Network))); break; default: - ev->Assign(3, make_intrusive( - new BroString((const u_char*) d, len, false))); + ev->Assign(3, zeek::make_intrusive( + new zeek::String((const u_char*) d, len, false))); break; } } @@ -114,130 +114,130 @@ IntrusivePtr BuildEndUserAddr(const InformationElement* ie) return ev; } -IntrusivePtr BuildAccessPointName(const InformationElement* ie) +zeek::ValPtr BuildAccessPointName(const InformationElement* ie) { - BroString* bs = new BroString((const u_char*) ie->ap_name()->value().data(), - ie->ap_name()->value().length(), false); - return make_intrusive(bs); + zeek::String* bs = new zeek::String((const u_char*) ie->ap_name()->value().data(), + ie->ap_name()->value().length(), false); + return zeek::make_intrusive(bs); } -IntrusivePtr BuildProtoConfigOptions(const InformationElement* ie) +zeek::ValPtr BuildProtoConfigOptions(const InformationElement* ie) { const u_char* d = (const u_char*) ie->proto_config_opts()->value().data(); int len = ie->proto_config_opts()->value().length(); - return make_intrusive(new BroString(d, len, false)); + return zeek::make_intrusive(new zeek::String(d, len, false)); } -IntrusivePtr BuildGSN_Addr(const InformationElement* ie) +zeek::ValPtr BuildGSN_Addr(const InformationElement* ie) { - auto ev = make_intrusive(zeek::BifType::Record::gtp_gsn_addr); + auto ev = zeek::make_intrusive(zeek::BifType::Record::gtp_gsn_addr); int len = ie->gsn_addr()->value().length(); const uint8* d = ie->gsn_addr()->value().data(); if ( len == 4 ) - ev->Assign(0, make_intrusive( + ev->Assign(0, zeek::make_intrusive( IPAddr(IPv4, (const uint32*) d, IPAddr::Network))); else if ( len == 16 ) - ev->Assign(0, make_intrusive( + ev->Assign(0, zeek::make_intrusive( IPAddr(IPv6, (const uint32*) d, IPAddr::Network))); else - ev->Assign(1, make_intrusive(new BroString((const u_char*) d, len, false))); + ev->Assign(1, zeek::make_intrusive(new zeek::String((const u_char*) d, len, false))); return ev; } -IntrusivePtr BuildMSISDN(const InformationElement* ie) +zeek::ValPtr BuildMSISDN(const InformationElement* ie) { const u_char* d = (const u_char*) ie->msisdn()->value().data(); int len = ie->msisdn()->value().length(); - return make_intrusive(new BroString(d, len, false)); + return zeek::make_intrusive(new zeek::String(d, len, false)); } -IntrusivePtr BuildQoS_Profile(const InformationElement* ie) +zeek::ValPtr BuildQoS_Profile(const InformationElement* ie) { - auto ev = make_intrusive(zeek::BifType::Record::gtp_qos_profile); + auto ev = zeek::make_intrusive(zeek::BifType::Record::gtp_qos_profile); const u_char* d = (const u_char*) ie->qos_profile()->data().data(); int len = ie->qos_profile()->data().length(); - ev->Assign(0, val_mgr->Count(ie->qos_profile()->alloc_retention_priority())); - ev->Assign(1, make_intrusive(new BroString(d, len, false))); + ev->Assign(0, zeek::val_mgr->Count(ie->qos_profile()->alloc_retention_priority())); + ev->Assign(1, zeek::make_intrusive(new zeek::String(d, len, false))); return ev; } -IntrusivePtr BuildTrafficFlowTemplate(const InformationElement* ie) +zeek::ValPtr BuildTrafficFlowTemplate(const InformationElement* ie) { const uint8* d = ie->traffic_flow_template()->value().data(); int len = ie->traffic_flow_template()->value().length(); - return make_intrusive(new BroString((const u_char*) d, len, false)); + return zeek::make_intrusive(new zeek::String((const u_char*) d, len, false)); } -IntrusivePtr BuildTriggerID(const InformationElement* ie) +zeek::ValPtr BuildTriggerID(const InformationElement* ie) { const uint8* d = ie->trigger_id()->value().data(); int len = ie->trigger_id()->value().length(); - return make_intrusive(new BroString((const u_char*) d, len, false)); + return zeek::make_intrusive(new zeek::String((const u_char*) d, len, false)); } -IntrusivePtr BuildOMC_ID(const InformationElement* ie) +zeek::ValPtr BuildOMC_ID(const InformationElement* ie) { const uint8* d = ie->omc_id()->value().data(); int len = ie->omc_id()->value().length(); - return make_intrusive(new BroString((const u_char*) d, len, false)); + return zeek::make_intrusive(new zeek::String((const u_char*) d, len, false)); } -IntrusivePtr BuildPrivateExt(const InformationElement* ie) +zeek::ValPtr BuildPrivateExt(const InformationElement* ie) { - auto ev = make_intrusive(zeek::BifType::Record::gtp_private_extension); + auto ev = zeek::make_intrusive(zeek::BifType::Record::gtp_private_extension); const uint8* d = ie->private_ext()->value().data(); int len = ie->private_ext()->value().length(); - ev->Assign(0, val_mgr->Count(ie->private_ext()->id())); - ev->Assign(1, make_intrusive(new BroString((const u_char*) d, len, false))); + ev->Assign(0, zeek::val_mgr->Count(ie->private_ext()->id())); + ev->Assign(1, zeek::make_intrusive(new zeek::String((const u_char*) d, len, false))); return ev; } -static IntrusivePtr BuildCause(const InformationElement* ie) +static zeek::ValPtr BuildCause(const InformationElement* ie) { - return val_mgr->Count(ie->cause()->value()); + return zeek::val_mgr->Count(ie->cause()->value()); } -static IntrusivePtr BuildReorderReq(const InformationElement* ie) +static zeek::ValPtr BuildReorderReq(const InformationElement* ie) { - return val_mgr->Bool(ie->reorder_req()->req()); + return zeek::val_mgr->Bool(ie->reorder_req()->req()); } -static IntrusivePtr BuildChargingID(const InformationElement* ie) +static zeek::ValPtr BuildChargingID(const InformationElement* ie) { - return val_mgr->Count(ie->charging_id()->value());; + return zeek::val_mgr->Count(ie->charging_id()->value());; } -IntrusivePtr BuildChargingGatewayAddr(const InformationElement* ie) +zeek::ValPtr BuildChargingGatewayAddr(const InformationElement* ie) { const uint8* d = ie->charging_gateway_addr()->value().data(); int len = ie->charging_gateway_addr()->value().length(); if ( len == 4 ) - return make_intrusive(IPAddr(IPv4, (const uint32*) d, IPAddr::Network)); + return zeek::make_intrusive(IPAddr(IPv4, (const uint32*) d, IPAddr::Network)); else if ( len == 16 ) - return make_intrusive(IPAddr(IPv6, (const uint32*) d, IPAddr::Network)); + return zeek::make_intrusive(IPAddr(IPv6, (const uint32*) d, IPAddr::Network)); else return nullptr; } -static IntrusivePtr BuildTeardownInd(const InformationElement* ie) +static zeek::ValPtr BuildTeardownInd(const InformationElement* ie) { - return val_mgr->Bool(ie->teardown_ind()->ind()); + return zeek::val_mgr->Bool(ie->teardown_ind()->ind()); } void CreatePDP_Request(const BroAnalyzer& a, const GTPv1_Header* pdu) { if ( ! ::gtpv1_create_pdp_ctx_request ) return; - auto rv = make_intrusive( + auto rv = zeek::make_intrusive( zeek::BifType::Record::gtp_create_pdp_ctx_request_elements); const vector * v = pdu->create_pdp_ctx_request(); @@ -337,7 +337,7 @@ void CreatePDP_Response(const BroAnalyzer& a, const GTPv1_Header* pdu) if ( ! ::gtpv1_create_pdp_ctx_response ) return; - auto rv = make_intrusive( + auto rv = zeek::make_intrusive( zeek::BifType::Record::gtp_create_pdp_ctx_response_elements); const vector * v = pdu->create_pdp_ctx_response(); @@ -406,7 +406,7 @@ void UpdatePDP_Request(const BroAnalyzer& a, const GTPv1_Header* pdu) if ( ! ::gtpv1_update_pdp_ctx_request ) return; - auto rv = make_intrusive( + auto rv = zeek::make_intrusive( zeek::BifType::Record::gtp_update_pdp_ctx_request_elements); const vector * v = pdu->update_pdp_ctx_request(); @@ -484,7 +484,7 @@ void UpdatePDP_Response(const BroAnalyzer& a, const GTPv1_Header* pdu) if ( ! ::gtpv1_update_pdp_ctx_response ) return; - auto rv = make_intrusive( + auto rv = zeek::make_intrusive( zeek::BifType::Record::gtp_update_pdp_ctx_response_elements); const vector * v = pdu->update_pdp_ctx_response(); @@ -544,7 +544,7 @@ void DeletePDP_Request(const BroAnalyzer& a, const GTPv1_Header* pdu) if ( ! ::gtpv1_delete_pdp_ctx_request ) return; - auto rv = make_intrusive( + auto rv = zeek::make_intrusive( zeek::BifType::Record::gtp_delete_pdp_ctx_request_elements); const vector * v = pdu->delete_pdp_ctx_request(); @@ -578,7 +578,7 @@ void DeletePDP_Response(const BroAnalyzer& a, const GTPv1_Header* pdu) if ( ! ::gtpv1_delete_pdp_ctx_response ) return; - auto rv = make_intrusive( + auto rv = zeek::make_intrusive( zeek::BifType::Record::gtp_delete_pdp_ctx_response_elements); const vector * v = pdu->delete_pdp_ctx_response(); @@ -760,7 +760,7 @@ flow GTPv1_Flow(is_orig: bool) if ( ::gtpv1_g_pdu_packet ) zeek::BifEvent::enqueue_gtpv1_g_pdu_packet(a, c, BuildGTPv1Hdr(pdu), - inner->ToPktHdrVal()); + inner->ToPktHdrVal()); EncapsulatingConn ec(c, BifEnum::Tunnel::GTPv1); diff --git a/src/analyzer/protocol/http/HTTP.cc b/src/analyzer/protocol/http/HTTP.cc index a4e4d2befe..13af97f264 100644 --- a/src/analyzer/protocol/http/HTTP.cc +++ b/src/analyzer/protocol/http/HTTP.cc @@ -361,7 +361,7 @@ void HTTP_Entity::SubmitHeader(mime::MIME_Header* h) { if ( mime::istrequal(h->get_name(), "content-length") ) { - data_chunk_t vt = h->get_value_token(); + zeek::data_chunk_t vt = h->get_value_token(); if ( ! mime::is_null_data_chunk(vt) ) { int64_t n; @@ -388,7 +388,7 @@ void HTTP_Entity::SubmitHeader(mime::MIME_Header* h) else if ( mime::istrequal(h->get_name(), "content-range") && http_message->MyHTTP_Analyzer()->HTTP_ReplyCode() == 206 ) { - data_chunk_t vt = h->get_value_token(); + zeek::data_chunk_t vt = h->get_value_token(); string byte_unit(vt.data, vt.length); vt = h->get_value_after_token(); string byte_range(vt.data, vt.length); @@ -479,7 +479,7 @@ void HTTP_Entity::SubmitHeader(mime::MIME_Header* h) else // reply_ongoing http_version = http_message->analyzer->GetReplyVersionNumber(); - data_chunk_t vt = h->get_value_token(); + zeek::data_chunk_t vt = h->get_value_token(); if ( mime::istrequal(vt, "chunked") && http_version == HTTP_Analyzer::HTTP_VersionNumber{1, 1} ) chunked_transfer_state = BEFORE_CHUNK; @@ -487,7 +487,7 @@ void HTTP_Entity::SubmitHeader(mime::MIME_Header* h) else if ( mime::istrequal(h->get_name(), "content-encoding") ) { - data_chunk_t vt = h->get_value_token(); + zeek::data_chunk_t vt = h->get_value_token(); if ( mime::istrequal(vt, "gzip") || mime::istrequal(vt, "x-gzip") ) encoding = GZIP; if ( mime::istrequal(vt, "deflate") ) @@ -613,17 +613,17 @@ HTTP_Message::~HTTP_Message() delete [] entity_data_buffer; } -IntrusivePtr HTTP_Message::BuildMessageStat(bool interrupted, const char* msg) +zeek::RecordValPtr HTTP_Message::BuildMessageStat(bool interrupted, const char* msg) { static auto http_message_stat = zeek::id::find_type("http_message_stat"); - auto stat = make_intrusive(http_message_stat); + auto stat = zeek::make_intrusive(http_message_stat); int field = 0; - stat->Assign(field++, make_intrusive(start_time)); - stat->Assign(field++, val_mgr->Bool(interrupted)); - stat->Assign(field++, make_intrusive(msg)); - stat->Assign(field++, val_mgr->Count(body_length)); - stat->Assign(field++, val_mgr->Count(content_gap_length)); - stat->Assign(field++, val_mgr->Count(header_length)); + stat->Assign(field++, zeek::make_intrusive(start_time)); + stat->Assign(field++, zeek::val_mgr->Bool(interrupted)); + stat->Assign(field++, zeek::make_intrusive(msg)); + stat->Assign(field++, zeek::val_mgr->Count(body_length)); + stat->Assign(field++, zeek::val_mgr->Count(content_gap_length)); + stat->Assign(field++, zeek::val_mgr->Count(header_length)); return stat; } @@ -652,7 +652,7 @@ void HTTP_Message::Done(bool interrupted, const char* detail) if ( http_message_done ) GetAnalyzer()->EnqueueConnEvent(http_message_done, analyzer->ConnVal(), - val_mgr->Bool(is_orig), + zeek::val_mgr->Bool(is_orig), BuildMessageStat(interrupted, detail) ); @@ -683,7 +683,7 @@ void HTTP_Message::BeginEntity(mime::MIME_Entity* entity) if ( http_begin_entity ) analyzer->EnqueueConnEvent(http_begin_entity, analyzer->ConnVal(), - val_mgr->Bool(is_orig) + zeek::val_mgr->Bool(is_orig) ); } @@ -698,7 +698,7 @@ void HTTP_Message::EndEntity(mime::MIME_Entity* entity) if ( http_end_entity ) analyzer->EnqueueConnEvent(http_end_entity, analyzer->ConnVal(), - val_mgr->Bool(is_orig) + zeek::val_mgr->Bool(is_orig) ); current_entity = (HTTP_Entity*) entity->Parent(); @@ -737,14 +737,14 @@ void HTTP_Message::SubmitAllHeaders(mime::MIME_HeaderList& hlist) if ( http_all_headers ) analyzer->EnqueueConnEvent(http_all_headers, analyzer->ConnVal(), - val_mgr->Bool(is_orig), + zeek::val_mgr->Bool(is_orig), ToHeaderTable(hlist) ); if ( http_content_type ) analyzer->EnqueueConnEvent(http_content_type, analyzer->ConnVal(), - val_mgr->Bool(is_orig), + zeek::val_mgr->Bool(is_orig), current_entity->GetContentType(), current_entity->GetContentSubType() ); @@ -762,7 +762,7 @@ void HTTP_Message::SubmitData(int len, const char* buf) { if ( http_entity_data ) MyHTTP_Analyzer()->HTTP_EntityData(is_orig, - new BroString(reinterpret_cast(buf), len, false)); + new zeek::String(reinterpret_cast(buf), len, false)); } bool HTTP_Message::RequestBuffer(int* plen, char** pbuf) @@ -1153,11 +1153,11 @@ void HTTP_Analyzer::GenStats() if ( http_stats ) { static auto http_stats_rec = zeek::id::find_type("http_stats_rec"); - auto r = make_intrusive(http_stats_rec); - r->Assign(0, val_mgr->Count(num_requests)); - r->Assign(1, val_mgr->Count(num_replies)); - r->Assign(2, make_intrusive(request_version.ToDouble())); - r->Assign(3, make_intrusive(reply_version.ToDouble())); + auto r = zeek::make_intrusive(http_stats_rec); + r->Assign(0, zeek::val_mgr->Count(num_requests)); + r->Assign(1, zeek::val_mgr->Count(num_replies)); + r->Assign(2, zeek::make_intrusive(request_version.ToDouble())); + r->Assign(3, zeek::make_intrusive(reply_version.ToDouble())); // DEBUG_MSG("%.6f http_stats\n", network_time); EnqueueConnEvent(http_stats, ConnVal(), std::move(r)); @@ -1242,7 +1242,7 @@ int HTTP_Analyzer::HTTP_RequestLine(const char* line, const char* end_of_line) return -1; } - request_method = make_intrusive(end_of_method - line, line); + request_method = zeek::make_intrusive(end_of_method - line, line); Conn()->Match(Rule::HTTP_REQUEST, (const u_char*) unescaped_URI->AsString()->Bytes(), @@ -1312,8 +1312,8 @@ bool HTTP_Analyzer::ParseRequest(const char* line, const char* end_of_line) // NormalizeURI(line, end_of_uri); - request_URI = make_intrusive(end_of_uri - line, line); - unescaped_URI = make_intrusive( + request_URI = zeek::make_intrusive(end_of_uri - line, line); + unescaped_URI = zeek::make_intrusive( unescape_URI((const u_char*) line, (const u_char*) end_of_uri, this)); return true; @@ -1352,30 +1352,30 @@ void HTTP_Analyzer::SetVersion(HTTP_VersionNumber* version, HTTP_VersionNumber n void HTTP_Analyzer::HTTP_Event(const char* category, const char* detail) { - HTTP_Event(category, make_intrusive(detail)); + HTTP_Event(category, zeek::make_intrusive(detail)); } -void HTTP_Analyzer::HTTP_Event(const char* category, IntrusivePtr detail) +void HTTP_Analyzer::HTTP_Event(const char* category, zeek::StringValPtr detail) { if ( http_event ) // DEBUG_MSG("%.6f http_event\n", network_time); EnqueueConnEvent(http_event, ConnVal(), - make_intrusive(category), + zeek::make_intrusive(category), std::move(detail)); } -IntrusivePtr -HTTP_Analyzer::TruncateURI(const IntrusivePtr& uri) +zeek::StringValPtr +HTTP_Analyzer::TruncateURI(const zeek::StringValPtr& uri) { - const BroString* str = uri->AsString(); + const zeek::String* str = uri->AsString(); if ( truncate_http_URI >= 0 && str->Len() > truncate_http_URI ) { u_char* s = new u_char[truncate_http_URI + 4]; memcpy(s, str->Bytes(), truncate_http_URI); memcpy(s + truncate_http_URI, "...", 4); - return make_intrusive(new BroString(true, s, truncate_http_URI+3)); + return zeek::make_intrusive(new zeek::String(true, s, truncate_http_URI+3)); } else return uri; @@ -1398,7 +1398,7 @@ void HTTP_Analyzer::HTTP_Request() request_method, TruncateURI(request_URI), TruncateURI(unescaped_URI), - make_intrusive(fmt("%.1f", request_version.ToDouble())) + zeek::make_intrusive(fmt("%.1f", request_version.ToDouble())) ); } @@ -1407,11 +1407,11 @@ void HTTP_Analyzer::HTTP_Reply() if ( http_reply ) EnqueueConnEvent(http_reply, ConnVal(), - make_intrusive(fmt("%.1f", reply_version.ToDouble())), - val_mgr->Count(reply_code), + zeek::make_intrusive(fmt("%.1f", reply_version.ToDouble())), + zeek::val_mgr->Count(reply_code), reply_reason_phrase ? reply_reason_phrase : - make_intrusive("") + zeek::make_intrusive("") ); else reply_reason_phrase = nullptr; @@ -1473,7 +1473,7 @@ void HTTP_Analyzer::ReplyMade(bool interrupted, const char* msg) if ( http_connection_upgrade ) EnqueueConnEvent(http_connection_upgrade, ConnVal(), - make_intrusive(upgrade_protocol) + zeek::make_intrusive(upgrade_protocol) ); } @@ -1487,7 +1487,7 @@ void HTTP_Analyzer::ReplyMade(bool interrupted, const char* msg) reply_state = EXPECT_REPLY_LINE; } -void HTTP_Analyzer::RequestClash(Val* /* clash_val */) +void HTTP_Analyzer::RequestClash(zeek::Val* /* clash_val */) { Weird("multiple_HTTP_request_elements"); @@ -1495,7 +1495,7 @@ void HTTP_Analyzer::RequestClash(Val* /* clash_val */) RequestMade(true, "request clash"); } -const BroString* HTTP_Analyzer::UnansweredRequestMethod() +const zeek::String* HTTP_Analyzer::UnansweredRequestMethod() { return unanswered_requests.empty() ? nullptr : unanswered_requests.front()->AsString(); } @@ -1551,7 +1551,7 @@ int HTTP_Analyzer::HTTP_ReplyLine(const char* line, const char* end_of_line) rest = skip_whitespace(rest, end_of_line); reply_reason_phrase = - make_intrusive(end_of_line - rest, (const char *) rest); + zeek::make_intrusive(end_of_line - rest, (const char *) rest); return 1; } @@ -1579,7 +1579,7 @@ int HTTP_Analyzer::ExpectReplyMessageBody() // MUST NOT include a message-body. All other responses do include a // message-body, although it MAY be of zero length. - const BroString* method = UnansweredRequestMethod(); + const zeek::String* method = UnansweredRequestMethod(); if ( method && strncasecmp((const char*) (method->Bytes()), "HEAD", method->Len()) == 0 ) return HTTP_BODY_NOT_EXPECTED; @@ -1622,8 +1622,8 @@ void HTTP_Analyzer::HTTP_Header(bool is_orig, mime::MIME_Header* h) is_orig ? Rule::HTTP_REQUEST_HEADER : Rule::HTTP_REPLY_HEADER; - data_chunk_t hd_name = h->get_name(); - data_chunk_t hd_value = h->get_value(); + zeek::data_chunk_t hd_name = h->get_name(); + zeek::data_chunk_t hd_value = h->get_value(); Conn()->Match(rule, (const u_char*) hd_name.data, hd_name.length, is_orig, true, false, true); @@ -1640,7 +1640,7 @@ void HTTP_Analyzer::HTTP_Header(bool is_orig, mime::MIME_Header* h) EnqueueConnEvent(http_header, ConnVal(), - val_mgr->Bool(is_orig), + zeek::val_mgr->Bool(is_orig), mime::to_string_val(h->get_name()), std::move(upper_hn), mime::to_string_val(h->get_value()) @@ -1648,14 +1648,14 @@ void HTTP_Analyzer::HTTP_Header(bool is_orig, mime::MIME_Header* h) } } -void HTTP_Analyzer::HTTP_EntityData(bool is_orig, BroString* entity_data) +void HTTP_Analyzer::HTTP_EntityData(bool is_orig, zeek::String* entity_data) { if ( http_entity_data ) EnqueueConnEvent(http_entity_data, ConnVal(), - val_mgr->Bool(is_orig), - val_mgr->Count(entity_data->Len()), - make_intrusive(entity_data) + zeek::val_mgr->Bool(is_orig), + zeek::val_mgr->Count(entity_data->Len()), + zeek::make_intrusive(entity_data) ); else delete entity_data; @@ -1711,11 +1711,11 @@ void analyzer::http::escape_URI_char(unsigned char ch, unsigned char*& p) *p++ = encode_hex(ch & 0xf); } -BroString* analyzer::http::unescape_URI(const u_char* line, const u_char* line_end, - analyzer::Analyzer* analyzer) +zeek::String* analyzer::http::unescape_URI(const u_char* line, const u_char* line_end, + analyzer::Analyzer* analyzer) { - byte_vec decoded_URI = new u_char[line_end - line + 1]; - byte_vec URI_p = decoded_URI; + zeek::byte_vec decoded_URI = new u_char[line_end - line + 1]; + zeek::byte_vec URI_p = decoded_URI; while ( line < line_end ) { @@ -1807,5 +1807,5 @@ BroString* analyzer::http::unescape_URI(const u_char* line, const u_char* line_e URI_p[0] = 0; - return new BroString(true, decoded_URI, URI_p - decoded_URI); + return new zeek::String(true, decoded_URI, URI_p - decoded_URI); } diff --git a/src/analyzer/protocol/http/HTTP.h b/src/analyzer/protocol/http/HTTP.h index 63ddfbbb7c..5d243be1d6 100644 --- a/src/analyzer/protocol/http/HTTP.h +++ b/src/analyzer/protocol/http/HTTP.h @@ -145,7 +145,7 @@ protected: HTTP_Entity* current_entity; - IntrusivePtr BuildMessageStat(bool interrupted, const char* msg); + zeek::RecordValPtr BuildMessageStat(bool interrupted, const char* msg); }; class HTTP_Analyzer final : public tcp::TCP_ApplicationAnalyzer { @@ -153,10 +153,10 @@ public: HTTP_Analyzer(Connection* conn); void HTTP_Header(bool is_orig, mime::MIME_Header* h); - void HTTP_EntityData(bool is_orig, BroString* entity_data); + void HTTP_EntityData(bool is_orig, zeek::String* entity_data); void HTTP_MessageDone(bool is_orig, HTTP_Message* message); void HTTP_Event(const char* category, const char* detail); - void HTTP_Event(const char* category, IntrusivePtr detail); + void HTTP_Event(const char* category, zeek::StringValPtr detail); void SkipEntityData(bool is_orig); @@ -230,14 +230,14 @@ protected: void RequestMade(bool interrupted, const char* msg); void ReplyMade(bool interrupted, const char* msg); - void RequestClash(Val* clash_val); + void RequestClash(zeek::Val* clash_val); - const BroString* UnansweredRequestMethod(); + const zeek::String* UnansweredRequestMethod(); int HTTP_ReplyCode(const char* code_str); int ExpectReplyMessageBody(); - IntrusivePtr TruncateURI(const IntrusivePtr& uri); + zeek::StringValPtr TruncateURI(const zeek::StringValPtr& uri); int request_state, reply_state; int num_requests, num_replies; @@ -257,19 +257,19 @@ protected: // in a reply. std::string upgrade_protocol; - IntrusivePtr request_method; + zeek::StringValPtr request_method; // request_URI is in the original form (may contain '%' // sequences). - IntrusivePtr request_URI; + zeek::StringValPtr request_URI; // unescaped_URI does not contain escaped sequences. - IntrusivePtr unescaped_URI; + zeek::StringValPtr unescaped_URI; - std::queue> unanswered_requests; + std::queue unanswered_requests; int reply_code; - IntrusivePtr reply_reason_phrase; + zeek::StringValPtr reply_reason_phrase; tcp::ContentLine_Analyzer* content_line_orig; tcp::ContentLine_Analyzer* content_line_resp; @@ -281,7 +281,7 @@ protected: extern bool is_reserved_URI_char(unsigned char ch); extern bool is_unreserved_URI_char(unsigned char ch); extern void escape_URI_char(unsigned char ch, unsigned char*& p); -extern BroString* unescape_URI(const u_char* line, const u_char* line_end, - analyzer::Analyzer* analyzer); +extern zeek::String* unescape_URI(const u_char* line, const u_char* line_end, + analyzer::Analyzer* analyzer); } } // namespace analyzer::* diff --git a/src/analyzer/protocol/http/functions.bif b/src/analyzer/protocol/http/functions.bif index c8c9f2e976..3b950e26fc 100644 --- a/src/analyzer/protocol/http/functions.bif +++ b/src/analyzer/protocol/http/functions.bif @@ -52,5 +52,5 @@ function unescape_URI%(URI: string%): string const u_char* line = URI->Bytes(); const u_char* const line_end = line + URI->Len(); - return make_intrusive(analyzer::http::unescape_URI(line, line_end, 0)); + return zeek::make_intrusive(analyzer::http::unescape_URI(line, line_end, 0)); %} diff --git a/src/analyzer/protocol/icmp/ICMP.cc b/src/analyzer/protocol/icmp/ICMP.cc index c1677c315b..fa6997d206 100644 --- a/src/analyzer/protocol/icmp/ICMP.cc +++ b/src/analyzer/protocol/icmp/ICMP.cc @@ -209,32 +209,31 @@ void ICMP_Analyzer::ICMP_Sent(const struct icmp* icmpp, int len, int caplen, if ( icmp_sent_payload ) { - BroString* payload = new BroString(data, std::min(len, caplen), false); + zeek::String* payload = new zeek::String(data, std::min(len, caplen), false); EnqueueConnEvent(icmp_sent_payload, ConnVal(), BuildICMPVal(icmpp, len, icmpv6, ip_hdr), - make_intrusive(payload) + zeek::make_intrusive(payload) ); } } -IntrusivePtr -ICMP_Analyzer::BuildICMPVal(const struct icmp* icmpp, int len, - int icmpv6, const IP_Hdr* ip_hdr) +zeek::RecordValPtr ICMP_Analyzer::BuildICMPVal(const struct icmp* icmpp, int len, + int icmpv6, const IP_Hdr* ip_hdr) { if ( ! icmp_conn_val ) { static auto icmp_conn = zeek::id::find_type("icmp_conn"); - icmp_conn_val = make_intrusive(icmp_conn); + icmp_conn_val = zeek::make_intrusive(icmp_conn); - icmp_conn_val->Assign(0, make_intrusive(Conn()->OrigAddr())); - icmp_conn_val->Assign(1, make_intrusive(Conn()->RespAddr())); - icmp_conn_val->Assign(2, val_mgr->Count(icmpp->icmp_type)); - icmp_conn_val->Assign(3, val_mgr->Count(icmpp->icmp_code)); - icmp_conn_val->Assign(4, val_mgr->Count(len)); - icmp_conn_val->Assign(5, val_mgr->Count(ip_hdr->TTL())); - icmp_conn_val->Assign(6, val_mgr->Bool(icmpv6)); + icmp_conn_val->Assign(0, zeek::make_intrusive(Conn()->OrigAddr())); + icmp_conn_val->Assign(1, zeek::make_intrusive(Conn()->RespAddr())); + icmp_conn_val->Assign(2, zeek::val_mgr->Count(icmpp->icmp_type)); + icmp_conn_val->Assign(3, zeek::val_mgr->Count(icmpp->icmp_code)); + icmp_conn_val->Assign(4, zeek::val_mgr->Count(len)); + icmp_conn_val->Assign(5, zeek::val_mgr->Count(ip_hdr->TTL())); + icmp_conn_val->Assign(6, zeek::val_mgr->Bool(icmpv6)); } return icmp_conn_val; @@ -305,7 +304,7 @@ TransportProto ICMP_Analyzer::GetContextProtocol(const IP_Hdr* ip_hdr, uint32_t* return proto; } -IntrusivePtr ICMP_Analyzer::ExtractICMP4Context(int len, const u_char*& data) +zeek::RecordValPtr ICMP_Analyzer::ExtractICMP4Context(int len, const u_char*& data) { const IP_Hdr ip_hdr_data((const struct ip*) data, false); const IP_Hdr* ip_hdr = &ip_hdr_data; @@ -352,27 +351,27 @@ IntrusivePtr ICMP_Analyzer::ExtractICMP4Context(int len, const u_char } static auto icmp_context = zeek::id::find_type("icmp_context"); - auto iprec = make_intrusive(icmp_context); - auto id_val = make_intrusive(zeek::id::conn_id); + auto iprec = zeek::make_intrusive(icmp_context); + auto id_val = zeek::make_intrusive(zeek::id::conn_id); - id_val->Assign(0, make_intrusive(src_addr)); - id_val->Assign(1, val_mgr->Port(src_port, proto)); - id_val->Assign(2, make_intrusive(dst_addr)); - id_val->Assign(3, val_mgr->Port(dst_port, proto)); + id_val->Assign(0, zeek::make_intrusive(src_addr)); + id_val->Assign(1, zeek::val_mgr->Port(src_port, proto)); + id_val->Assign(2, zeek::make_intrusive(dst_addr)); + id_val->Assign(3, zeek::val_mgr->Port(dst_port, proto)); iprec->Assign(0, std::move(id_val)); - iprec->Assign(1, val_mgr->Count(ip_len)); - iprec->Assign(2, val_mgr->Count(proto)); - iprec->Assign(3, val_mgr->Count(frag_offset)); - iprec->Assign(4, val_mgr->Bool(bad_hdr_len)); - iprec->Assign(5, val_mgr->Bool(bad_checksum)); - iprec->Assign(6, val_mgr->Bool(MF)); - iprec->Assign(7, val_mgr->Bool(DF)); + iprec->Assign(1, zeek::val_mgr->Count(ip_len)); + iprec->Assign(2, zeek::val_mgr->Count(proto)); + iprec->Assign(3, zeek::val_mgr->Count(frag_offset)); + iprec->Assign(4, zeek::val_mgr->Bool(bad_hdr_len)); + iprec->Assign(5, zeek::val_mgr->Bool(bad_checksum)); + iprec->Assign(6, zeek::val_mgr->Bool(MF)); + iprec->Assign(7, zeek::val_mgr->Bool(DF)); return iprec; } -IntrusivePtr ICMP_Analyzer::ExtractICMP6Context(int len, const u_char*& data) +zeek::RecordValPtr ICMP_Analyzer::ExtractICMP6Context(int len, const u_char*& data) { int DF = 0, MF = 0, bad_hdr_len = 0; TransportProto proto = TRANSPORT_UNKNOWN; @@ -412,23 +411,23 @@ IntrusivePtr ICMP_Analyzer::ExtractICMP6Context(int len, const u_char } static auto icmp_context = zeek::id::find_type("icmp_context"); - auto iprec = make_intrusive(icmp_context); - auto id_val = make_intrusive(zeek::id::conn_id); + auto iprec = zeek::make_intrusive(icmp_context); + auto id_val = zeek::make_intrusive(zeek::id::conn_id); - id_val->Assign(0, make_intrusive(src_addr)); - id_val->Assign(1, val_mgr->Port(src_port, proto)); - id_val->Assign(2, make_intrusive(dst_addr)); - id_val->Assign(3, val_mgr->Port(dst_port, proto)); + id_val->Assign(0, zeek::make_intrusive(src_addr)); + id_val->Assign(1, zeek::val_mgr->Port(src_port, proto)); + id_val->Assign(2, zeek::make_intrusive(dst_addr)); + id_val->Assign(3, zeek::val_mgr->Port(dst_port, proto)); iprec->Assign(0, std::move(id_val)); - iprec->Assign(1, val_mgr->Count(ip_len)); - iprec->Assign(2, val_mgr->Count(proto)); - iprec->Assign(3, val_mgr->Count(frag_offset)); - iprec->Assign(4, val_mgr->Bool(bad_hdr_len)); + iprec->Assign(1, zeek::val_mgr->Count(ip_len)); + iprec->Assign(2, zeek::val_mgr->Count(proto)); + iprec->Assign(3, zeek::val_mgr->Count(frag_offset)); + iprec->Assign(4, zeek::val_mgr->Bool(bad_hdr_len)); // bad_checksum is always false since IPv6 layer doesn't have a checksum. - iprec->Assign(5, val_mgr->False()); - iprec->Assign(6, val_mgr->Bool(MF)); - iprec->Assign(7, val_mgr->Bool(DF)); + iprec->Assign(5, zeek::val_mgr->False()); + iprec->Assign(6, zeek::val_mgr->Bool(MF)); + iprec->Assign(7, zeek::val_mgr->Bool(DF)); return iprec; } @@ -457,7 +456,7 @@ void ICMP_Analyzer::Describe(ODesc* d) const d->Add(Conn()->RespAddr()); } -void ICMP_Analyzer::UpdateConnVal(RecordVal *conn_val) +void ICMP_Analyzer::UpdateConnVal(zeek::RecordVal *conn_val) { const auto& orig_endp = conn_val->GetField("orig"); const auto& resp_endp = conn_val->GetField("resp"); @@ -469,7 +468,7 @@ void ICMP_Analyzer::UpdateConnVal(RecordVal *conn_val) Analyzer::UpdateConnVal(conn_val); } -void ICMP_Analyzer::UpdateEndpointVal(const IntrusivePtr& endp_arg, bool is_orig) +void ICMP_Analyzer::UpdateEndpointVal(const zeek::ValPtr& endp_arg, bool is_orig) { Conn()->EnableStatusUpdateTimer(); @@ -478,14 +477,14 @@ void ICMP_Analyzer::UpdateEndpointVal(const IntrusivePtr& endp_arg, bool is if ( size < 0 ) { - endp->Assign(0, val_mgr->Count(0)); - endp->Assign(1, val_mgr->Count(int(ICMP_INACTIVE))); + endp->Assign(0, zeek::val_mgr->Count(0)); + endp->Assign(1, zeek::val_mgr->Count(int(ICMP_INACTIVE))); } else { - endp->Assign(0, val_mgr->Count(size)); - endp->Assign(1, val_mgr->Count(int(ICMP_ACTIVE))); + endp->Assign(0, zeek::val_mgr->Count(size)); + endp->Assign(1, zeek::val_mgr->Count(int(ICMP_ACTIVE))); } } @@ -516,14 +515,14 @@ void ICMP_Analyzer::Echo(double t, const struct icmp* icmpp, int len, int iid = ntohs(icmpp->icmp_hun.ih_idseq.icd_id); int iseq = ntohs(icmpp->icmp_hun.ih_idseq.icd_seq); - BroString* payload = new BroString(data, caplen, false); + zeek::String* payload = new zeek::String(data, caplen, false); EnqueueConnEvent(f, ConnVal(), BuildICMPVal(icmpp, len, ip_hdr->NextProto() != IPPROTO_ICMP, ip_hdr), - val_mgr->Count(iid), - val_mgr->Count(iseq), - make_intrusive(payload) + zeek::val_mgr->Count(iid), + zeek::val_mgr->Count(iseq), + zeek::make_intrusive(payload) ); } @@ -549,16 +548,16 @@ void ICMP_Analyzer::RouterAdvert(double t, const struct icmp* icmpp, int len, EnqueueConnEvent(f, ConnVal(), BuildICMPVal(icmpp, len, 1, ip_hdr), - val_mgr->Count(icmpp->icmp_num_addrs), // Cur Hop Limit - val_mgr->Bool(icmpp->icmp_wpa & 0x80), // Managed - val_mgr->Bool(icmpp->icmp_wpa & 0x40), // Other - val_mgr->Bool(icmpp->icmp_wpa & 0x20), // Home Agent - val_mgr->Count((icmpp->icmp_wpa & 0x18)>>3), // Pref - val_mgr->Bool(icmpp->icmp_wpa & 0x04), // Proxy - val_mgr->Count(icmpp->icmp_wpa & 0x02), // Reserved - make_intrusive((double)ntohs(icmpp->icmp_lifetime), Seconds), - make_intrusive((double)ntohl(reachable), Milliseconds), - make_intrusive((double)ntohl(retrans), Milliseconds), + zeek::val_mgr->Count(icmpp->icmp_num_addrs), // Cur Hop Limit + zeek::val_mgr->Bool(icmpp->icmp_wpa & 0x80), // Managed + zeek::val_mgr->Bool(icmpp->icmp_wpa & 0x40), // Other + zeek::val_mgr->Bool(icmpp->icmp_wpa & 0x20), // Home Agent + zeek::val_mgr->Count((icmpp->icmp_wpa & 0x18)>>3), // Pref + zeek::val_mgr->Bool(icmpp->icmp_wpa & 0x04), // Proxy + zeek::val_mgr->Count(icmpp->icmp_wpa & 0x02), // Reserved + zeek::make_intrusive((double)ntohs(icmpp->icmp_lifetime), Seconds), + zeek::make_intrusive((double)ntohl(reachable), Milliseconds), + zeek::make_intrusive((double)ntohl(retrans), Milliseconds), BuildNDOptionsVal(caplen - opt_offset, data + opt_offset) ); } @@ -582,10 +581,10 @@ void ICMP_Analyzer::NeighborAdvert(double t, const struct icmp* icmpp, int len, EnqueueConnEvent(f, ConnVal(), BuildICMPVal(icmpp, len, 1, ip_hdr), - val_mgr->Bool(icmpp->icmp_num_addrs & 0x80), // Router - val_mgr->Bool(icmpp->icmp_num_addrs & 0x40), // Solicited - val_mgr->Bool(icmpp->icmp_num_addrs & 0x20), // Override - make_intrusive(tgtaddr), + zeek::val_mgr->Bool(icmpp->icmp_num_addrs & 0x80), // Router + zeek::val_mgr->Bool(icmpp->icmp_num_addrs & 0x40), // Solicited + zeek::val_mgr->Bool(icmpp->icmp_num_addrs & 0x20), // Override + zeek::make_intrusive(tgtaddr), BuildNDOptionsVal(caplen - opt_offset, data + opt_offset) ); } @@ -609,7 +608,7 @@ void ICMP_Analyzer::NeighborSolicit(double t, const struct icmp* icmpp, int len, EnqueueConnEvent(f, ConnVal(), BuildICMPVal(icmpp, len, 1, ip_hdr), - make_intrusive(tgtaddr), + zeek::make_intrusive(tgtaddr), BuildNDOptionsVal(caplen - opt_offset, data + opt_offset) ); } @@ -636,8 +635,8 @@ void ICMP_Analyzer::Redirect(double t, const struct icmp* icmpp, int len, EnqueueConnEvent(f, ConnVal(), BuildICMPVal(icmpp, len, 1, ip_hdr), - make_intrusive(tgtaddr), - make_intrusive(dstaddr), + zeek::make_intrusive(tgtaddr), + zeek::make_intrusive(dstaddr), BuildNDOptionsVal(caplen - opt_offset, data + opt_offset) ); } @@ -679,7 +678,7 @@ void ICMP_Analyzer::Context4(double t, const struct icmp* icmpp, EnqueueConnEvent(f, ConnVal(), BuildICMPVal(icmpp, len, 0, ip_hdr), - val_mgr->Count(icmpp->icmp_code), + zeek::val_mgr->Count(icmpp->icmp_code), ExtractICMP4Context(caplen, data) ); } @@ -717,17 +716,17 @@ void ICMP_Analyzer::Context6(double t, const struct icmp* icmpp, EnqueueConnEvent(f, ConnVal(), BuildICMPVal(icmpp, len, 1, ip_hdr), - val_mgr->Count(icmpp->icmp_code), + zeek::val_mgr->Count(icmpp->icmp_code), ExtractICMP6Context(caplen, data) ); } -IntrusivePtr ICMP_Analyzer::BuildNDOptionsVal(int caplen, const u_char* data) +zeek::VectorValPtr ICMP_Analyzer::BuildNDOptionsVal(int caplen, const u_char* data) { static auto icmp6_nd_option_type = zeek::id::find_type("icmp6_nd_option"); static auto icmp6_nd_prefix_info_type = zeek::id::find_type("icmp6_nd_prefix_info"); - auto vv = make_intrusive( + auto vv = zeek::make_intrusive( zeek::id::find_type("icmp6_nd_options")); while ( caplen > 0 ) @@ -748,9 +747,9 @@ IntrusivePtr ICMP_Analyzer::BuildNDOptionsVal(int caplen, const u_cha break; } - auto rv = make_intrusive(icmp6_nd_option_type); - rv->Assign(0, val_mgr->Count(type)); - rv->Assign(1, val_mgr->Count(length)); + auto rv = zeek::make_intrusive(icmp6_nd_option_type); + rv->Assign(0, zeek::val_mgr->Count(type)); + rv->Assign(1, zeek::val_mgr->Count(length)); // Adjust length to be in units of bytes, exclude type/length fields. length = length * 8 - 2; @@ -768,8 +767,8 @@ IntrusivePtr ICMP_Analyzer::BuildNDOptionsVal(int caplen, const u_cha { if ( caplen >= length ) { - BroString* link_addr = new BroString(data, length, false); - rv->Assign(2, make_intrusive(link_addr)); + zeek::String* link_addr = new zeek::String(data, length, false); + rv->Assign(2, zeek::make_intrusive(link_addr)); } else set_payload_field = true; @@ -782,19 +781,19 @@ IntrusivePtr ICMP_Analyzer::BuildNDOptionsVal(int caplen, const u_cha { if ( caplen >= 30 ) { - auto info = make_intrusive(icmp6_nd_prefix_info_type); + auto info = zeek::make_intrusive(icmp6_nd_prefix_info_type); uint8_t prefix_len = *((const uint8_t*)(data)); bool L_flag = (*((const uint8_t*)(data + 1)) & 0x80) != 0; bool A_flag = (*((const uint8_t*)(data + 1)) & 0x40) != 0; uint32_t valid_life = *((const uint32_t*)(data + 2)); uint32_t prefer_life = *((const uint32_t*)(data + 6)); in6_addr prefix = *((const in6_addr*)(data + 14)); - info->Assign(0, val_mgr->Count(prefix_len)); - info->Assign(1, val_mgr->Bool(L_flag)); - info->Assign(2, val_mgr->Bool(A_flag)); - info->Assign(3, make_intrusive((double)ntohl(valid_life), Seconds)); - info->Assign(4, make_intrusive((double)ntohl(prefer_life), Seconds)); - info->Assign(5, make_intrusive(IPAddr(prefix))); + info->Assign(0, zeek::val_mgr->Count(prefix_len)); + info->Assign(1, zeek::val_mgr->Bool(L_flag)); + info->Assign(2, zeek::val_mgr->Bool(A_flag)); + info->Assign(3, zeek::make_intrusive((double)ntohl(valid_life), Seconds)); + info->Assign(4, zeek::make_intrusive((double)ntohl(prefer_life), Seconds)); + info->Assign(5, zeek::make_intrusive(IPAddr(prefix))); rv->Assign(3, std::move(info)); } @@ -822,7 +821,7 @@ IntrusivePtr ICMP_Analyzer::BuildNDOptionsVal(int caplen, const u_cha // MTU option { if ( caplen >= 6 ) - rv->Assign(5, val_mgr->Count(ntohl(*((const uint32_t*)(data + 2))))); + rv->Assign(5, zeek::val_mgr->Count(ntohl(*((const uint32_t*)(data + 2))))); else set_payload_field = true; @@ -838,8 +837,8 @@ IntrusivePtr ICMP_Analyzer::BuildNDOptionsVal(int caplen, const u_cha if ( set_payload_field ) { - BroString* payload = new BroString(data, std::min((int)length, caplen), false); - rv->Assign(6, make_intrusive(payload)); + zeek::String* payload = new zeek::String(data, std::min((int)length, caplen), false); + rv->Assign(6, zeek::make_intrusive(payload)); } data += length; diff --git a/src/analyzer/protocol/icmp/ICMP.h b/src/analyzer/protocol/icmp/ICMP.h index 74ecb3a322..2e62d477bb 100644 --- a/src/analyzer/protocol/icmp/ICMP.h +++ b/src/analyzer/protocol/icmp/ICMP.h @@ -6,7 +6,10 @@ #include "analyzer/Analyzer.h" #include "net_util.h" -class VectorVal; +ZEEK_FORWARD_DECLARE_NAMESPACED(VectorVal, zeek); +namespace zeek { +using VectorValPtr = zeek::IntrusivePtr; +} namespace analyzer { namespace icmp { @@ -21,7 +24,7 @@ class ICMP_Analyzer final : public analyzer::TransportLayerAnalyzer { public: explicit ICMP_Analyzer(Connection* conn); - void UpdateConnVal(RecordVal *conn_val) override; + void UpdateConnVal(zeek::RecordVal *conn_val) override; static analyzer::Analyzer* Instantiate(Connection* conn) { return new ICMP_Analyzer(conn); } @@ -29,7 +32,7 @@ public: protected: void Done() override; void DeliverPacket(int len, const u_char* data, bool orig, - uint64_t seq, const IP_Hdr* ip, int caplen) override; + uint64_t seq, const IP_Hdr* ip, int caplen) override; bool IsReuse(double t, const u_char* pkt) override; unsigned int MemoryAllocation() const override; @@ -51,32 +54,32 @@ protected: void Describe(ODesc* d) const; - IntrusivePtr BuildICMPVal(const struct icmp* icmpp, int len, - int icmpv6, const IP_Hdr* ip_hdr); + zeek::RecordValPtr BuildICMPVal(const struct icmp* icmpp, int len, + int icmpv6, const IP_Hdr* ip_hdr); void NextICMP4(double t, const struct icmp* icmpp, int len, int caplen, - const u_char*& data, const IP_Hdr* ip_hdr ); + const u_char*& data, const IP_Hdr* ip_hdr ); - IntrusivePtr ExtractICMP4Context(int len, const u_char*& data); + zeek::RecordValPtr ExtractICMP4Context(int len, const u_char*& data); void Context4(double t, const struct icmp* icmpp, int len, int caplen, - const u_char*& data, const IP_Hdr* ip_hdr); + const u_char*& data, const IP_Hdr* ip_hdr); TransportProto GetContextProtocol(const IP_Hdr* ip_hdr, uint32_t* src_port, - uint32_t* dst_port); + uint32_t* dst_port); void NextICMP6(double t, const struct icmp* icmpp, int len, int caplen, - const u_char*& data, const IP_Hdr* ip_hdr ); + const u_char*& data, const IP_Hdr* ip_hdr ); - IntrusivePtr ExtractICMP6Context(int len, const u_char*& data); + zeek::RecordValPtr ExtractICMP6Context(int len, const u_char*& data); void Context6(double t, const struct icmp* icmpp, int len, int caplen, - const u_char*& data, const IP_Hdr* ip_hdr); + const u_char*& data, const IP_Hdr* ip_hdr); // RFC 4861 Neighbor Discover message options - IntrusivePtr BuildNDOptionsVal(int caplen, const u_char* data); + zeek::VectorValPtr BuildNDOptionsVal(int caplen, const u_char* data); - IntrusivePtr icmp_conn_val; + zeek::RecordValPtr icmp_conn_val; int type; int code; int request_len, reply_len; @@ -84,7 +87,7 @@ protected: RuleMatcherState matcher_state; private: - void UpdateEndpointVal(const IntrusivePtr& endp, bool is_orig); + void UpdateEndpointVal(const zeek::ValPtr& endp, bool is_orig); }; // Returns the counterpart type to the given type (e.g., the counterpart diff --git a/src/analyzer/protocol/ident/Ident.cc b/src/analyzer/protocol/ident/Ident.cc index 8db6e4185f..bf1cb9073a 100644 --- a/src/analyzer/protocol/ident/Ident.cc +++ b/src/analyzer/protocol/ident/Ident.cc @@ -4,7 +4,7 @@ #include -#include "BroString.h" +#include "ZeekString.h" #include "NetVar.h" #include "Ident.h" #include "Event.h" @@ -80,14 +80,14 @@ void Ident_Analyzer::DeliverStream(int length, const u_char* data, bool is_orig) if ( line != end_of_line ) { - BroString s((const u_char*)orig_line, length, true); + zeek::String s((const u_char*)orig_line, length, true); Weird("ident_request_addendum", s.CheckString()); } EnqueueConnEvent(ident_request, ConnVal(), - val_mgr->Port(local_port, TRANSPORT_TCP), - val_mgr->Port(remote_port, TRANSPORT_TCP) + zeek::val_mgr->Port(local_port, TRANSPORT_TCP), + zeek::val_mgr->Port(remote_port, TRANSPORT_TCP) ); did_deliver = true; @@ -147,9 +147,9 @@ void Ident_Analyzer::DeliverStream(int length, const u_char* data, bool is_orig) if ( ident_error ) EnqueueConnEvent(ident_error, ConnVal(), - val_mgr->Port(local_port, TRANSPORT_TCP), - val_mgr->Port(remote_port, TRANSPORT_TCP), - make_intrusive(end_of_line - line, line) + zeek::val_mgr->Port(local_port, TRANSPORT_TCP), + zeek::val_mgr->Port(remote_port, TRANSPORT_TCP), + zeek::make_intrusive(end_of_line - line, line) ); } @@ -172,18 +172,18 @@ void Ident_Analyzer::DeliverStream(int length, const u_char* data, bool is_orig) while ( --sys_end > sys_type && isspace(*sys_end) ) ; - BroString* sys_type_s = - new BroString((const u_char*) sys_type, - sys_end - sys_type + 1, true); + zeek::String* sys_type_s = + new zeek::String((const u_char*) sys_type, + sys_end - sys_type + 1, true); line = skip_whitespace(colon + 1, end_of_line); EnqueueConnEvent(ident_reply, ConnVal(), - val_mgr->Port(local_port, TRANSPORT_TCP), - val_mgr->Port(remote_port, TRANSPORT_TCP), - make_intrusive(end_of_line - line, line), - make_intrusive(sys_type_s) + zeek::val_mgr->Port(local_port, TRANSPORT_TCP), + zeek::val_mgr->Port(remote_port, TRANSPORT_TCP), + zeek::make_intrusive(end_of_line - line, line), + zeek::make_intrusive(sys_type_s) ); } } @@ -242,7 +242,7 @@ const char* Ident_Analyzer::ParsePort(const char* line, const char* end_of_line, void Ident_Analyzer::BadRequest(int length, const char* line) { - BroString s((const u_char*)line, length, true); + zeek::String s((const u_char*)line, length, true); Weird("bad_ident_request", s.CheckString()); } @@ -250,7 +250,7 @@ void Ident_Analyzer::BadReply(int length, const char* line) { if ( ! did_bad_reply ) { - BroString s((const u_char*)line, length, true); + zeek::String s((const u_char*)line, length, true); Weird("bad_ident_reply", s.CheckString()); did_bad_reply = true; } diff --git a/src/analyzer/protocol/imap/imap-analyzer.pac b/src/analyzer/protocol/imap/imap-analyzer.pac index 677e3789ec..196af72e98 100644 --- a/src/analyzer/protocol/imap/imap-analyzer.pac +++ b/src/analyzer/protocol/imap/imap-analyzer.pac @@ -59,12 +59,12 @@ refine connection IMAP_Conn += { if ( ! imap_capabilities ) return true; - auto capv = make_intrusive(zeek::id::string_vec); + auto capv = zeek::make_intrusive(zeek::id::string_vec); for ( unsigned int i = 0; i< capabilities->size(); i++ ) { const bytestring& capability = (*capabilities)[i]->cap(); - capv->Assign(i, make_intrusive(capability.length(), (const char*)capability.data())); + capv->Assign(i, zeek::make_intrusive(capability.length(), (const char*)capability.data())); } zeek::BifEvent::enqueue_imap_capabilities(bro_analyzer(), bro_analyzer()->Conn(), std::move(capv)); diff --git a/src/analyzer/protocol/irc/IRC.cc b/src/analyzer/protocol/irc/IRC.cc index 4c1e817a99..dea201c7f1 100644 --- a/src/analyzer/protocol/irc/IRC.cc +++ b/src/analyzer/protocol/irc/IRC.cc @@ -237,12 +237,11 @@ void IRC_Analyzer::DeliverStream(int length, const u_char* line, bool orig) } EnqueueConnEvent(irc_network_info, - ConnVal(), - val_mgr->Bool(orig), - val_mgr->Int(users), - val_mgr->Int(services), - val_mgr->Int(servers) - ); + ConnVal(), + zeek::val_mgr->Bool(orig), + zeek::val_mgr->Int(users), + zeek::val_mgr->Int(services), + zeek::val_mgr->Int(servers)); } break; @@ -273,23 +272,22 @@ void IRC_Analyzer::DeliverStream(int length, const u_char* line, bool orig) if ( parts.size() > 0 && parts[0][0] == ':' ) parts[0] = parts[0].substr(1); - auto set = make_intrusive(zeek::id::string_set); + auto set = zeek::make_intrusive(zeek::id::string_set); for ( unsigned int i = 0; i < parts.size(); ++i ) { if ( parts[i][0] == '@' ) parts[i] = parts[i].substr(1); - auto idx = make_intrusive(parts[i].c_str()); + auto idx = zeek::make_intrusive(parts[i].c_str()); set->Assign(std::move(idx), nullptr); } EnqueueConnEvent(irc_names_info, - ConnVal(), - val_mgr->Bool(orig), - make_intrusive(type.c_str()), - make_intrusive(channel.c_str()), - std::move(set) - ); + ConnVal(), + zeek::val_mgr->Bool(orig), + zeek::make_intrusive(type.c_str()), + zeek::make_intrusive(channel.c_str()), + std::move(set)); } break; @@ -318,12 +316,11 @@ void IRC_Analyzer::DeliverStream(int length, const u_char* line, bool orig) } EnqueueConnEvent(irc_server_info, - ConnVal(), - val_mgr->Bool(orig), - val_mgr->Int(users), - val_mgr->Int(services), - val_mgr->Int(servers) - ); + ConnVal(), + zeek::val_mgr->Bool(orig), + zeek::val_mgr->Int(users), + zeek::val_mgr->Int(services), + zeek::val_mgr->Int(servers)); } break; @@ -340,10 +337,9 @@ void IRC_Analyzer::DeliverStream(int length, const u_char* line, bool orig) channels = atoi(parts[i - 1].c_str()); EnqueueConnEvent(irc_channel_info, - ConnVal(), - val_mgr->Bool(orig), - val_mgr->Int(channels) - ); + ConnVal(), + zeek::val_mgr->Bool(orig), + zeek::val_mgr->Int(channels)); } break; @@ -372,11 +368,10 @@ void IRC_Analyzer::DeliverStream(int length, const u_char* line, bool orig) } EnqueueConnEvent(irc_global_users, - ConnVal(), - val_mgr->Bool(orig), - make_intrusive(eop - prefix, prefix), - make_intrusive(++msg) - ); + ConnVal(), + zeek::val_mgr->Bool(orig), + zeek::make_intrusive(eop - prefix, prefix), + zeek::make_intrusive(++msg)); break; } @@ -399,10 +394,10 @@ void IRC_Analyzer::DeliverStream(int length, const u_char* line, bool orig) zeek::Args vl; vl.reserve(6); vl.emplace_back(ConnVal()); - vl.emplace_back(val_mgr->Bool(orig)); - vl.emplace_back(make_intrusive(parts[0].c_str())); - vl.emplace_back(make_intrusive(parts[1].c_str())); - vl.emplace_back(make_intrusive(parts[2].c_str())); + vl.emplace_back(zeek::val_mgr->Bool(orig)); + vl.emplace_back(zeek::make_intrusive(parts[0].c_str())); + vl.emplace_back(zeek::make_intrusive(parts[1].c_str())); + vl.emplace_back(zeek::make_intrusive(parts[2].c_str())); parts.erase(parts.begin(), parts.begin() + 4); @@ -413,7 +408,7 @@ void IRC_Analyzer::DeliverStream(int length, const u_char* line, bool orig) if ( real_name[0] == ':' ) real_name = real_name.substr(1); - vl.emplace_back(make_intrusive(real_name.c_str())); + vl.emplace_back(zeek::make_intrusive(real_name.c_str())); EnqueueConnEvent(irc_whois_user_line, std::move(vl)); } @@ -437,10 +432,9 @@ void IRC_Analyzer::DeliverStream(int length, const u_char* line, bool orig) } EnqueueConnEvent(irc_whois_operator_line, - ConnVal(), - val_mgr->Bool(orig), - make_intrusive(parts[0].c_str()) - ); + ConnVal(), + zeek::val_mgr->Bool(orig), + zeek::make_intrusive(parts[0].c_str())); } break; @@ -466,20 +460,19 @@ void IRC_Analyzer::DeliverStream(int length, const u_char* line, bool orig) if ( parts.size() > 0 && parts[0][0] == ':' ) parts[0] = parts[0].substr(1); - auto set = make_intrusive(zeek::id::string_set); + auto set = zeek::make_intrusive(zeek::id::string_set); for ( unsigned int i = 0; i < parts.size(); ++i ) { - auto idx = make_intrusive(parts[i].c_str()); + auto idx = zeek::make_intrusive(parts[i].c_str()); set->Assign(std::move(idx), nullptr); } EnqueueConnEvent(irc_whois_channel_line, - ConnVal(), - val_mgr->Bool(orig), - make_intrusive(nick.c_str()), - std::move(set) - ); + ConnVal(), + zeek::val_mgr->Bool(orig), + zeek::make_intrusive(nick.c_str()), + std::move(set)); } break; @@ -506,11 +499,10 @@ void IRC_Analyzer::DeliverStream(int length, const u_char* line, bool orig) ++t; EnqueueConnEvent(irc_channel_topic, - ConnVal(), - val_mgr->Bool(orig), - make_intrusive(parts[1].c_str()), - make_intrusive(t) - ); + ConnVal(), + zeek::val_mgr->Bool(orig), + zeek::make_intrusive(parts[1].c_str()), + zeek::make_intrusive(t)); } else { @@ -540,18 +532,17 @@ void IRC_Analyzer::DeliverStream(int length, const u_char* line, bool orig) parts[7] = parts[7].substr(1); EnqueueConnEvent(irc_who_line, - ConnVal(), - val_mgr->Bool(orig), - make_intrusive(parts[0].c_str()), - make_intrusive(parts[1].c_str()), - make_intrusive(parts[2].c_str()), - make_intrusive(parts[3].c_str()), - make_intrusive(parts[4].c_str()), - make_intrusive(parts[5].c_str()), - make_intrusive(parts[6].c_str()), - val_mgr->Int(atoi(parts[7].c_str())), - make_intrusive(parts[8].c_str()) - ); + ConnVal(), + zeek::val_mgr->Bool(orig), + zeek::make_intrusive(parts[0].c_str()), + zeek::make_intrusive(parts[1].c_str()), + zeek::make_intrusive(parts[2].c_str()), + zeek::make_intrusive(parts[3].c_str()), + zeek::make_intrusive(parts[4].c_str()), + zeek::make_intrusive(parts[5].c_str()), + zeek::make_intrusive(parts[6].c_str()), + zeek::val_mgr->Int(atoi(parts[7].c_str())), + zeek::make_intrusive(parts[8].c_str())); } break; @@ -562,9 +553,8 @@ void IRC_Analyzer::DeliverStream(int length, const u_char* line, bool orig) case 436: if ( irc_invalid_nick ) EnqueueConnEvent(irc_invalid_nick, - ConnVal(), - val_mgr->Bool(orig) - ); + ConnVal(), + zeek::val_mgr->Bool(orig)); break; // Operator responses. @@ -572,10 +562,9 @@ void IRC_Analyzer::DeliverStream(int length, const u_char* line, bool orig) case 491: // user is not operator if ( irc_oper_response ) EnqueueConnEvent(irc_oper_response, - ConnVal(), - val_mgr->Bool(orig), - val_mgr->Bool(code == 381) - ); + ConnVal(), + zeek::val_mgr->Bool(orig), + zeek::val_mgr->Bool(code == 381)); break; case 670: @@ -587,12 +576,11 @@ void IRC_Analyzer::DeliverStream(int length, const u_char* line, bool orig) default: if ( irc_reply ) EnqueueConnEvent(irc_reply, - ConnVal(), - val_mgr->Bool(orig), - make_intrusive(prefix.c_str()), - val_mgr->Count(code), - make_intrusive(params.c_str()) - ); + ConnVal(), + zeek::val_mgr->Bool(orig), + zeek::make_intrusive(prefix.c_str()), + zeek::val_mgr->Count(code), + zeek::make_intrusive(params.c_str())); break; } return; @@ -658,27 +646,27 @@ void IRC_Analyzer::DeliverStream(int length, const u_char* line, bool orig) if ( irc_dcc_message ) EnqueueConnEvent(irc_dcc_message, - ConnVal(), - val_mgr->Bool(orig), - make_intrusive(prefix.c_str()), - make_intrusive(target.c_str()), - make_intrusive(parts[1].c_str()), - make_intrusive(parts[2].c_str()), - make_intrusive(htonl(raw_ip)), - val_mgr->Count(atoi(parts[4].c_str())), - parts.size() >= 6 ? val_mgr->Count(atoi(parts[5].c_str())) : val_mgr->Count(0) - ); + ConnVal(), + zeek::val_mgr->Bool(orig), + zeek::make_intrusive(prefix.c_str()), + zeek::make_intrusive(target.c_str()), + zeek::make_intrusive(parts[1].c_str()), + zeek::make_intrusive(parts[2].c_str()), + zeek::make_intrusive(htonl(raw_ip)), + zeek::val_mgr->Count(atoi(parts[4].c_str())), + parts.size() >= 6 ? zeek::val_mgr->Count(atoi(parts[5].c_str())) : zeek::val_mgr->Count(0) + ); } else { if ( irc_privmsg_message ) EnqueueConnEvent(irc_privmsg_message, - ConnVal(), - val_mgr->Bool(orig), - make_intrusive(prefix.c_str()), - make_intrusive(target.c_str()), - make_intrusive(message.c_str()) + ConnVal(), + zeek::val_mgr->Bool(orig), + zeek::make_intrusive(prefix.c_str()), + zeek::make_intrusive(target.c_str()), + zeek::make_intrusive(message.c_str()) ); } } @@ -699,11 +687,11 @@ void IRC_Analyzer::DeliverStream(int length, const u_char* line, bool orig) message = message.substr(1); EnqueueConnEvent(irc_notice_message, - ConnVal(), - val_mgr->Bool(orig), - make_intrusive(prefix.c_str()), - make_intrusive(target.c_str()), - make_intrusive(message.c_str()) + ConnVal(), + zeek::val_mgr->Bool(orig), + zeek::make_intrusive(prefix.c_str()), + zeek::make_intrusive(target.c_str()), + zeek::make_intrusive(message.c_str()) ); } @@ -723,11 +711,11 @@ void IRC_Analyzer::DeliverStream(int length, const u_char* line, bool orig) message = message.substr(1); EnqueueConnEvent(irc_squery_message, - ConnVal(), - val_mgr->Bool(orig), - make_intrusive(prefix.c_str()), - make_intrusive(target.c_str()), - make_intrusive(message.c_str()) + ConnVal(), + zeek::val_mgr->Bool(orig), + zeek::make_intrusive(prefix.c_str()), + zeek::make_intrusive(target.c_str()), + zeek::make_intrusive(message.c_str()) ); } @@ -738,19 +726,19 @@ void IRC_Analyzer::DeliverStream(int length, const u_char* line, bool orig) zeek::Args vl; vl.reserve(6); vl.emplace_back(ConnVal()); - vl.emplace_back(val_mgr->Bool(orig)); + vl.emplace_back(zeek::val_mgr->Bool(orig)); if ( parts.size() > 0 ) - vl.emplace_back(make_intrusive(parts[0].c_str())); - else vl.emplace_back(val_mgr->EmptyString()); + vl.emplace_back(zeek::make_intrusive(parts[0].c_str())); + else vl.emplace_back(zeek::val_mgr->EmptyString()); if ( parts.size() > 1 ) - vl.emplace_back(make_intrusive(parts[1].c_str())); - else vl.emplace_back(val_mgr->EmptyString()); + vl.emplace_back(zeek::make_intrusive(parts[1].c_str())); + else vl.emplace_back(zeek::val_mgr->EmptyString()); if ( parts.size() > 2 ) - vl.emplace_back(make_intrusive(parts[2].c_str())); - else vl.emplace_back(val_mgr->EmptyString()); + vl.emplace_back(zeek::make_intrusive(parts[2].c_str())); + else vl.emplace_back(zeek::val_mgr->EmptyString()); string realname; for ( unsigned int i = 3; i < parts.size(); i++ ) @@ -761,7 +749,7 @@ void IRC_Analyzer::DeliverStream(int length, const u_char* line, bool orig) } const char* name = realname.c_str(); - vl.emplace_back(make_intrusive(*name == ':' ? name + 1 : name)); + vl.emplace_back(zeek::make_intrusive(*name == ':' ? name + 1 : name)); EnqueueConnEvent(irc_user_message, std::move(vl)); } @@ -772,10 +760,10 @@ void IRC_Analyzer::DeliverStream(int length, const u_char* line, bool orig) vector parts = SplitWords(params, ' '); if ( parts.size() == 2 ) EnqueueConnEvent(irc_oper_message, - ConnVal(), - val_mgr->Bool(orig), - make_intrusive(parts[0].c_str()), - make_intrusive(parts[1].c_str()) + ConnVal(), + zeek::val_mgr->Bool(orig), + zeek::make_intrusive(parts[0].c_str()), + zeek::make_intrusive(parts[1].c_str()) ); else @@ -795,10 +783,10 @@ void IRC_Analyzer::DeliverStream(int length, const u_char* line, bool orig) zeek::Args vl; vl.reserve(6); vl.emplace_back(ConnVal()); - vl.emplace_back(val_mgr->Bool(orig)); - vl.emplace_back(make_intrusive(prefix.c_str())); - vl.emplace_back(make_intrusive(parts[0].c_str())); - vl.emplace_back(make_intrusive(parts[1].c_str())); + vl.emplace_back(zeek::val_mgr->Bool(orig)); + vl.emplace_back(zeek::make_intrusive(prefix.c_str())); + vl.emplace_back(zeek::make_intrusive(parts[0].c_str())); + vl.emplace_back(zeek::make_intrusive(parts[1].c_str())); if ( parts.size() > 2 ) { @@ -809,10 +797,10 @@ void IRC_Analyzer::DeliverStream(int length, const u_char* line, bool orig) if ( comment[0] == ':' ) comment = comment.substr(1); - vl.emplace_back(make_intrusive(comment.c_str())); + vl.emplace_back(zeek::make_intrusive(comment.c_str())); } else - vl.emplace_back(val_mgr->EmptyString()); + vl.emplace_back(zeek::val_mgr->EmptyString()); EnqueueConnEvent(irc_kick_message, std::move(vl)); } @@ -838,7 +826,7 @@ void IRC_Analyzer::DeliverStream(int length, const u_char* line, bool orig) nickname = prefix.substr(0, pos); } - auto list = make_intrusive(irc_join_list); + auto list = zeek::make_intrusive(irc_join_list); vector channels = SplitWords(parts[0], ','); vector passwords; @@ -849,21 +837,21 @@ void IRC_Analyzer::DeliverStream(int length, const u_char* line, bool orig) string empty_string = ""; for ( unsigned int i = 0; i < channels.size(); ++i ) { - auto info = make_intrusive(irc_join_info); - info->Assign(0, make_intrusive(nickname.c_str())); - info->Assign(1, make_intrusive(channels[i].c_str())); + auto info = zeek::make_intrusive(irc_join_info); + info->Assign(0, zeek::make_intrusive(nickname.c_str())); + info->Assign(1, zeek::make_intrusive(channels[i].c_str())); if ( i < passwords.size() ) - info->Assign(2, make_intrusive(passwords[i].c_str())); + info->Assign(2, zeek::make_intrusive(passwords[i].c_str())); else - info->Assign(2, make_intrusive(empty_string.c_str())); + info->Assign(2, zeek::make_intrusive(empty_string.c_str())); // User mode. - info->Assign(3, make_intrusive(empty_string.c_str())); + info->Assign(3, zeek::make_intrusive(empty_string.c_str())); list->Assign(std::move(info), nullptr); } EnqueueConnEvent(irc_join_message, ConnVal(), - val_mgr->Bool(orig), + zeek::val_mgr->Bool(orig), std::move(list) ); } @@ -882,13 +870,13 @@ void IRC_Analyzer::DeliverStream(int length, const u_char* line, bool orig) parts[1] = parts[1].substr(1); vector users = SplitWords(parts[1], ','); - auto list = make_intrusive(irc_join_list); + auto list = zeek::make_intrusive(irc_join_list); string empty_string = ""; for ( unsigned int i = 0; i < users.size(); ++i ) { - auto info = make_intrusive(irc_join_info); + auto info = zeek::make_intrusive(irc_join_info); string nick = users[i]; string mode = "none"; @@ -912,18 +900,18 @@ void IRC_Analyzer::DeliverStream(int length, const u_char* line, bool orig) mode = "voice"; } - info->Assign(0, make_intrusive(nick.c_str())); - info->Assign(1, make_intrusive(channel.c_str())); + info->Assign(0, zeek::make_intrusive(nick.c_str())); + info->Assign(1, zeek::make_intrusive(channel.c_str())); // Password: - info->Assign(2, make_intrusive(empty_string.c_str())); + info->Assign(2, zeek::make_intrusive(empty_string.c_str())); // User mode: - info->Assign(3, make_intrusive(mode.c_str())); + info->Assign(3, zeek::make_intrusive(mode.c_str())); list->Assign(std::move(info), nullptr); } EnqueueConnEvent(irc_join_message, ConnVal(), - val_mgr->Bool(orig), + zeek::val_mgr->Bool(orig), std::move(list) ); } @@ -952,20 +940,20 @@ void IRC_Analyzer::DeliverStream(int length, const u_char* line, bool orig) nick = nick.substr(0, pos); vector channelList = SplitWords(channels, ','); - auto set = make_intrusive(zeek::id::string_set); + auto set = zeek::make_intrusive(zeek::id::string_set); for ( unsigned int i = 0; i < channelList.size(); ++i ) { - auto idx = make_intrusive(channelList[i].c_str()); + auto idx = zeek::make_intrusive(channelList[i].c_str()); set->Assign(std::move(idx), nullptr); } EnqueueConnEvent(irc_part_message, - ConnVal(), - val_mgr->Bool(orig), - make_intrusive(nick.c_str()), - std::move(set), - make_intrusive(message.c_str()) + ConnVal(), + zeek::val_mgr->Bool(orig), + zeek::make_intrusive(nick.c_str()), + std::move(set), + zeek::make_intrusive(message.c_str()) ); } @@ -984,10 +972,10 @@ void IRC_Analyzer::DeliverStream(int length, const u_char* line, bool orig) } EnqueueConnEvent(irc_quit_message, - ConnVal(), - val_mgr->Bool(orig), - make_intrusive(nickname.c_str()), - make_intrusive(message.c_str()) + ConnVal(), + zeek::val_mgr->Bool(orig), + zeek::make_intrusive(nickname.c_str()), + zeek::make_intrusive(message.c_str()) ); } @@ -998,10 +986,10 @@ void IRC_Analyzer::DeliverStream(int length, const u_char* line, bool orig) nick = nick.substr(1); EnqueueConnEvent(irc_nick_message, - ConnVal(), - val_mgr->Bool(orig), - make_intrusive(prefix.c_str()), - make_intrusive(nick.c_str()) + ConnVal(), + zeek::val_mgr->Bool(orig), + zeek::make_intrusive(prefix.c_str()), + zeek::make_intrusive(nick.c_str()) ); } @@ -1023,12 +1011,12 @@ void IRC_Analyzer::DeliverStream(int length, const u_char* line, bool orig) parts[0] = parts[0].substr(1); EnqueueConnEvent(irc_who_message, - ConnVal(), - val_mgr->Bool(orig), - parts.size() > 0 ? - make_intrusive(parts[0].c_str()) : - val_mgr->EmptyString(), - val_mgr->Bool(oper) + ConnVal(), + zeek::val_mgr->Bool(orig), + parts.size() > 0 ? + zeek::make_intrusive(parts[0].c_str()) : + zeek::val_mgr->EmptyString(), + zeek::val_mgr->Bool(oper) ); } @@ -1053,10 +1041,10 @@ void IRC_Analyzer::DeliverStream(int length, const u_char* line, bool orig) users = parts[0]; EnqueueConnEvent(irc_whois_message, - ConnVal(), - val_mgr->Bool(orig), - make_intrusive(server.c_str()), - make_intrusive(users.c_str()) + ConnVal(), + zeek::val_mgr->Bool(orig), + zeek::make_intrusive(server.c_str()), + zeek::make_intrusive(users.c_str()) ); } @@ -1066,10 +1054,10 @@ void IRC_Analyzer::DeliverStream(int length, const u_char* line, bool orig) params = params.substr(1); EnqueueConnEvent(irc_error_message, - ConnVal(), - val_mgr->Bool(orig), - make_intrusive(prefix.c_str()), - make_intrusive(params.c_str()) + ConnVal(), + zeek::val_mgr->Bool(orig), + zeek::make_intrusive(prefix.c_str()), + zeek::make_intrusive(params.c_str()) ); } @@ -1082,11 +1070,11 @@ void IRC_Analyzer::DeliverStream(int length, const u_char* line, bool orig) parts[1] = parts[1].substr(1); EnqueueConnEvent(irc_invite_message, - ConnVal(), - val_mgr->Bool(orig), - make_intrusive(prefix.c_str()), - make_intrusive(parts[0].c_str()), - make_intrusive(parts[1].c_str()) + ConnVal(), + zeek::val_mgr->Bool(orig), + zeek::make_intrusive(prefix.c_str()), + zeek::make_intrusive(parts[0].c_str()), + zeek::make_intrusive(parts[1].c_str()) ); } else @@ -1097,10 +1085,10 @@ void IRC_Analyzer::DeliverStream(int length, const u_char* line, bool orig) { if ( params.size() > 0 ) EnqueueConnEvent(irc_mode_message, - ConnVal(), - val_mgr->Bool(orig), - make_intrusive(prefix.c_str()), - make_intrusive(params.c_str()) + ConnVal(), + zeek::val_mgr->Bool(orig), + zeek::make_intrusive(prefix.c_str()), + zeek::make_intrusive(params.c_str()) ); else @@ -1110,9 +1098,9 @@ void IRC_Analyzer::DeliverStream(int length, const u_char* line, bool orig) else if ( irc_password_message && command == "PASS" ) { EnqueueConnEvent(irc_password_message, - ConnVal(), - val_mgr->Bool(orig), - make_intrusive(params.c_str()) + ConnVal(), + zeek::val_mgr->Bool(orig), + zeek::make_intrusive(params.c_str()) ); } @@ -1132,11 +1120,11 @@ void IRC_Analyzer::DeliverStream(int length, const u_char* line, bool orig) } EnqueueConnEvent(irc_squit_message, - ConnVal(), - val_mgr->Bool(orig), - make_intrusive(prefix.c_str()), - make_intrusive(server.c_str()), - make_intrusive(message.c_str()) + ConnVal(), + zeek::val_mgr->Bool(orig), + zeek::make_intrusive(prefix.c_str()), + zeek::make_intrusive(server.c_str()), + zeek::make_intrusive(message.c_str()) ); } @@ -1146,11 +1134,11 @@ void IRC_Analyzer::DeliverStream(int length, const u_char* line, bool orig) if ( irc_request ) { EnqueueConnEvent(irc_request, - ConnVal(), - val_mgr->Bool(orig), - make_intrusive(prefix.c_str()), - make_intrusive(command.c_str()), - make_intrusive(params.c_str()) + ConnVal(), + zeek::val_mgr->Bool(orig), + zeek::make_intrusive(prefix.c_str()), + zeek::make_intrusive(command.c_str()), + zeek::make_intrusive(params.c_str()) ); } } @@ -1160,11 +1148,11 @@ void IRC_Analyzer::DeliverStream(int length, const u_char* line, bool orig) if ( irc_message ) { EnqueueConnEvent(irc_message, - ConnVal(), - val_mgr->Bool(orig), - make_intrusive(prefix.c_str()), - make_intrusive(command.c_str()), - make_intrusive(params.c_str()) + ConnVal(), + zeek::val_mgr->Bool(orig), + zeek::make_intrusive(prefix.c_str()), + zeek::make_intrusive(command.c_str()), + zeek::make_intrusive(params.c_str()) ); } } diff --git a/src/analyzer/protocol/krb/KRB.cc b/src/analyzer/protocol/krb/KRB.cc index 5d66d7942a..7d57acb530 100644 --- a/src/analyzer/protocol/krb/KRB.cc +++ b/src/analyzer/protocol/krb/KRB.cc @@ -87,23 +87,23 @@ void KRB_Analyzer::DeliverPacket(int len, const u_char* data, bool orig, } } -IntrusivePtr KRB_Analyzer::GetAuthenticationInfo(const BroString* principal, - const BroString* ciphertext, - const bro_uint_t enctype) +zeek::StringValPtr KRB_Analyzer::GetAuthenticationInfo(const zeek::String* principal, + const zeek::String* ciphertext, + const bro_uint_t enctype) { #ifdef USE_KRB5 if ( !krb_available ) return nullptr; - BroString delim("/"); + zeek::String delim("/"); int pos = principal->FindSubstring(&delim); if ( pos == -1 ) { reporter->Warning("KRB: Couldn't parse principal (%s)", principal->CheckString()); return nullptr; } - std::unique_ptr service = unique_ptr(principal->GetSubstring(0, pos)); - std::unique_ptr hostname = unique_ptr(principal->GetSubstring(pos + 1, -1)); + std::unique_ptr service = unique_ptr(principal->GetSubstring(0, pos)); + std::unique_ptr hostname = unique_ptr(principal->GetSubstring(pos + 1, -1)); if ( !service || !hostname ) { reporter->Warning("KRB: Couldn't parse principal (%s)", principal->CheckString()); @@ -147,7 +147,7 @@ IntrusivePtr KRB_Analyzer::GetAuthenticationInfo(const BroString* pri return nullptr; } - auto ret = make_intrusive(cp); + auto ret = zeek::make_intrusive(cp); krb5_free_unparsed_name(krb_context, cp); krb5_free_ticket(krb_context, tkt); diff --git a/src/analyzer/protocol/krb/KRB.h b/src/analyzer/protocol/krb/KRB.h index a34ccbe4b4..ff463b9f15 100644 --- a/src/analyzer/protocol/krb/KRB.h +++ b/src/analyzer/protocol/krb/KRB.h @@ -25,9 +25,9 @@ public: static analyzer::Analyzer* Instantiate(Connection* conn) { return new KRB_Analyzer(conn); } - IntrusivePtr GetAuthenticationInfo(const BroString* principal, - const BroString* ciphertext, - const bro_uint_t enctype); + zeek::StringValPtr GetAuthenticationInfo(const zeek::String* principal, + const zeek::String* ciphertext, + const bro_uint_t enctype); protected: diff --git a/src/analyzer/protocol/krb/KRB_TCP.h b/src/analyzer/protocol/krb/KRB_TCP.h index 7cc1a83a5d..6c534d192c 100644 --- a/src/analyzer/protocol/krb/KRB_TCP.h +++ b/src/analyzer/protocol/krb/KRB_TCP.h @@ -21,10 +21,10 @@ public: // Overriden from tcp::TCP_ApplicationAnalyzer. void EndpointEOF(bool is_orig) override; - IntrusivePtr GetAuthenticationInfo(const BroString* principal, - const BroString* ciphertext, - const bro_uint_t enctype) - { return val_mgr->EmptyString(); } + zeek::StringValPtr GetAuthenticationInfo(const zeek::String* principal, + const zeek::String* ciphertext, + const bro_uint_t enctype) + { return zeek::val_mgr->EmptyString(); } static analyzer::Analyzer* Instantiate(Connection* conn) { return new KRB_Analyzer(conn); } diff --git a/src/analyzer/protocol/krb/krb-analyzer.pac b/src/analyzer/protocol/krb/krb-analyzer.pac index 3d19ef2777..94883b353b 100644 --- a/src/analyzer/protocol/krb/krb-analyzer.pac +++ b/src/analyzer/protocol/krb/krb-analyzer.pac @@ -1,35 +1,35 @@ %header{ -IntrusivePtr proc_krb_kdc_options(const KRB_KDC_Options* opts); -IntrusivePtr proc_krb_kdc_req_arguments(KRB_KDC_REQ* msg, const BroAnalyzer bro_analyzer); +zeek::RecordValPtr proc_krb_kdc_options(const KRB_KDC_Options* opts); +zeek::RecordValPtr proc_krb_kdc_req_arguments(KRB_KDC_REQ* msg, const BroAnalyzer bro_analyzer); -bool proc_error_arguments(RecordVal* rv, const std::vector* args, int64 error_code); +bool proc_error_arguments(zeek::RecordVal* rv, const std::vector* args, int64 error_code); %} %code{ -IntrusivePtr proc_krb_kdc_options(const KRB_KDC_Options* opts) +zeek::RecordValPtr proc_krb_kdc_options(const KRB_KDC_Options* opts) { - auto rv = make_intrusive(zeek::BifType::Record::KRB::KDC_Options); + auto rv = zeek::make_intrusive(zeek::BifType::Record::KRB::KDC_Options); - rv->Assign(0, val_mgr->Bool(opts->forwardable())); - rv->Assign(1, val_mgr->Bool(opts->forwarded())); - rv->Assign(2, val_mgr->Bool(opts->proxiable())); - rv->Assign(3, val_mgr->Bool(opts->proxy())); - rv->Assign(4, val_mgr->Bool(opts->allow_postdate())); - rv->Assign(5, val_mgr->Bool(opts->postdated())); - rv->Assign(6, val_mgr->Bool(opts->renewable())); - rv->Assign(7, val_mgr->Bool(opts->opt_hardware_auth())); - rv->Assign(8, val_mgr->Bool(opts->disable_transited_check())); - rv->Assign(9, val_mgr->Bool(opts->renewable_ok())); - rv->Assign(10, val_mgr->Bool(opts->enc_tkt_in_skey())); - rv->Assign(11, val_mgr->Bool(opts->renew())); - rv->Assign(12, val_mgr->Bool(opts->validate())); + rv->Assign(0, zeek::val_mgr->Bool(opts->forwardable())); + rv->Assign(1, zeek::val_mgr->Bool(opts->forwarded())); + rv->Assign(2, zeek::val_mgr->Bool(opts->proxiable())); + rv->Assign(3, zeek::val_mgr->Bool(opts->proxy())); + rv->Assign(4, zeek::val_mgr->Bool(opts->allow_postdate())); + rv->Assign(5, zeek::val_mgr->Bool(opts->postdated())); + rv->Assign(6, zeek::val_mgr->Bool(opts->renewable())); + rv->Assign(7, zeek::val_mgr->Bool(opts->opt_hardware_auth())); + rv->Assign(8, zeek::val_mgr->Bool(opts->disable_transited_check())); + rv->Assign(9, zeek::val_mgr->Bool(opts->renewable_ok())); + rv->Assign(10, zeek::val_mgr->Bool(opts->enc_tkt_in_skey())); + rv->Assign(11, zeek::val_mgr->Bool(opts->renew())); + rv->Assign(12, zeek::val_mgr->Bool(opts->validate())); return rv; } -IntrusivePtr proc_krb_kdc_req_arguments(KRB_KDC_REQ* msg, const BroAnalyzer bro_analyzer) +zeek::RecordValPtr proc_krb_kdc_req_arguments(KRB_KDC_REQ* msg, const BroAnalyzer bro_analyzer) { - auto rv = make_intrusive(zeek::BifType::Record::KRB::KDC_Request); + auto rv = zeek::make_intrusive(zeek::BifType::Record::KRB::KDC_Request); rv->Assign(0, asn1_integer_to_val(msg->pvno()->data(), zeek::TYPE_COUNT)); rv->Assign(1, asn1_integer_to_val(msg->msg_type()->data(), zeek::TYPE_COUNT)); @@ -93,7 +93,7 @@ IntrusivePtr proc_krb_kdc_req_arguments(KRB_KDC_REQ* msg, const BroAn } -bool proc_error_arguments(RecordVal* rv, const std::vector* args, int64 error_code ) +bool proc_error_arguments(zeek::RecordVal* rv, const std::vector* args, int64 error_code ) { uint ctime_i = 0, stime_i = 0; int64 ctime_usecs = 0, stime_usecs = 0; @@ -201,9 +201,9 @@ refine connection KRB_Conn += { %{ bro_analyzer()->ProtocolConfirmation(); auto msg_type = binary_to_int64(${msg.msg_type.data.content}); - auto make_arg = [this, msg]() -> IntrusivePtr + auto make_arg = [this, msg]() -> zeek::RecordValPtr { - auto rv = make_intrusive(zeek::BifType::Record::KRB::KDC_Response); + auto rv = zeek::make_intrusive(zeek::BifType::Record::KRB::KDC_Response); rv->Assign(0, asn1_integer_to_val(${msg.pvno.data}, zeek::TYPE_COUNT)); rv->Assign(1, asn1_integer_to_val(${msg.msg_type.data}, zeek::TYPE_COUNT)); @@ -244,7 +244,7 @@ refine connection KRB_Conn += { bro_analyzer()->ProtocolConfirmation(); if ( krb_error ) { - auto rv = make_intrusive(zeek::BifType::Record::KRB::Error_Msg); + auto rv = zeek::make_intrusive(zeek::BifType::Record::KRB::Error_Msg); proc_error_arguments(rv.get(), ${msg.args1}, 0); rv->Assign(4, asn1_integer_to_val(${msg.error_code}, zeek::TYPE_COUNT)); proc_error_arguments(rv.get(), ${msg.args2}, binary_to_int64(${msg.error_code.encoding.content})); @@ -258,9 +258,9 @@ refine connection KRB_Conn += { bro_analyzer()->ProtocolConfirmation(); if ( krb_ap_request ) { - auto rv = make_intrusive(zeek::BifType::Record::KRB::AP_Options); - rv->Assign(0, val_mgr->Bool(${msg.ap_options.use_session_key})); - rv->Assign(1, val_mgr->Bool(${msg.ap_options.mutual_required})); + auto rv = zeek::make_intrusive(zeek::BifType::Record::KRB::AP_Options); + rv->Assign(0, zeek::val_mgr->Bool(${msg.ap_options.use_session_key})); + rv->Assign(1, zeek::val_mgr->Bool(${msg.ap_options.mutual_required})); auto rvticket = proc_ticket(${msg.ticket}); auto authenticationinfo = bro_analyzer()->GetAuthenticationInfo(rvticket->GetField(2)->AsString(), rvticket->GetField(4)->AsString(), rvticket->GetField(3)->AsCount()); @@ -289,7 +289,7 @@ refine connection KRB_Conn += { bro_analyzer()->ProtocolConfirmation(); if ( krb_safe ) { - auto rv = make_intrusive(zeek::BifType::Record::KRB::SAFE_Msg); + auto rv = zeek::make_intrusive(zeek::BifType::Record::KRB::SAFE_Msg); rv->Assign(0, asn1_integer_to_val(${msg.pvno.data}, zeek::TYPE_COUNT)); rv->Assign(1, asn1_integer_to_val(${msg.msg_type.data}, zeek::TYPE_COUNT)); diff --git a/src/analyzer/protocol/krb/krb-asn1.pac b/src/analyzer/protocol/krb/krb-asn1.pac index 5619ca285f..34c2d928a0 100644 --- a/src/analyzer/protocol/krb/krb-asn1.pac +++ b/src/analyzer/protocol/krb/krb-asn1.pac @@ -2,20 +2,20 @@ %include ../asn1/asn1.pac %header{ - IntrusivePtr GetTimeFromAsn1(const KRB_Time* atime, int64 usecs); - IntrusivePtr GetTimeFromAsn1(StringVal* atime, int64 usecs); + zeek::ValPtr GetTimeFromAsn1(const KRB_Time* atime, int64 usecs); + zeek::ValPtr GetTimeFromAsn1(zeek::StringVal* atime, int64 usecs); %} %code{ -IntrusivePtr GetTimeFromAsn1(const KRB_Time* atime, int64 usecs) +zeek::ValPtr GetTimeFromAsn1(const KRB_Time* atime, int64 usecs) { auto atime_bytestring = to_stringval(atime->time()); auto result = GetTimeFromAsn1(atime_bytestring.get(), usecs); return result; } -IntrusivePtr GetTimeFromAsn1(StringVal* atime, int64 usecs) +zeek::ValPtr GetTimeFromAsn1(zeek::StringVal* atime, int64 usecs) { time_t lResult = 0; @@ -51,7 +51,7 @@ IntrusivePtr GetTimeFromAsn1(StringVal* atime, int64 usecs) if ( !lResult ) lResult = 0; - return make_intrusive(double(lResult + double(usecs/100000.0))); + return zeek::make_intrusive(double(lResult + double(usecs/100000.0))); } %} diff --git a/src/analyzer/protocol/krb/krb-padata.pac b/src/analyzer/protocol/krb/krb-padata.pac index 003fb43e7b..78f811638a 100644 --- a/src/analyzer/protocol/krb/krb-padata.pac +++ b/src/analyzer/protocol/krb/krb-padata.pac @@ -7,13 +7,13 @@ %} %header{ -IntrusivePtr proc_padata(const KRB_PA_Data_Sequence* data, const BroAnalyzer bro_analyzer, bool is_error); +zeek::VectorValPtr proc_padata(const KRB_PA_Data_Sequence* data, const BroAnalyzer bro_analyzer, bool is_error); %} %code{ -IntrusivePtr proc_padata(const KRB_PA_Data_Sequence* data, const BroAnalyzer bro_analyzer, bool is_error) +zeek::VectorValPtr proc_padata(const KRB_PA_Data_Sequence* data, const BroAnalyzer bro_analyzer, bool is_error) { - auto vv = make_intrusive(zeek::id::find_type("KRB::Type_Value_Vector")); + auto vv = zeek::make_intrusive(zeek::id::find_type("KRB::Type_Value_Vector")); if ( ! data->data()->has_padata() ) return vv; @@ -36,24 +36,24 @@ IntrusivePtr proc_padata(const KRB_PA_Data_Sequence* data, const BroA break; case PA_PW_SALT: { - auto type_val = make_intrusive(zeek::BifType::Record::KRB::Type_Value); - type_val->Assign(0, val_mgr->Count(element->data_type())); + auto type_val = zeek::make_intrusive(zeek::BifType::Record::KRB::Type_Value); + type_val->Assign(0, zeek::val_mgr->Count(element->data_type())); type_val->Assign(1, to_stringval(element->pa_data_element()->pa_pw_salt()->encoding()->content())); vv->Assign(vv->Size(), std::move(type_val)); break; } case PA_ENCTYPE_INFO: { - auto type_val = make_intrusive(zeek::BifType::Record::KRB::Type_Value); - type_val->Assign(0, val_mgr->Count(element->data_type())); + auto type_val = zeek::make_intrusive(zeek::BifType::Record::KRB::Type_Value); + type_val->Assign(0, zeek::val_mgr->Count(element->data_type())); type_val->Assign(1, to_stringval(element->pa_data_element()->pf_enctype_info()->salt())); vv->Assign(vv->Size(), std::move(type_val)); break; } case PA_ENCTYPE_INFO2: { - auto type_val = make_intrusive(zeek::BifType::Record::KRB::Type_Value); - type_val->Assign(0, val_mgr->Count(element->data_type())); + auto type_val = zeek::make_intrusive(zeek::BifType::Record::KRB::Type_Value); + type_val->Assign(0, zeek::val_mgr->Count(element->data_type())); type_val->Assign(1, to_stringval(element->pa_data_element()->pf_enctype_info2()->salt())); vv->Assign(vv->Size(), std::move(type_val)); break; @@ -110,8 +110,8 @@ IntrusivePtr proc_padata(const KRB_PA_Data_Sequence* data, const BroA { if ( ! is_error && element->pa_data_element()->unknown()->meta()->length() > 0 ) { - auto type_val = make_intrusive(zeek::BifType::Record::KRB::Type_Value); - type_val->Assign(0, val_mgr->Count(element->data_type())); + auto type_val = zeek::make_intrusive(zeek::BifType::Record::KRB::Type_Value); + type_val->Assign(0, zeek::val_mgr->Count(element->data_type())); type_val->Assign(1, to_stringval(element->pa_data_element()->unknown()->content())); vv->Assign(vv->Size(), std::move(type_val)); } diff --git a/src/analyzer/protocol/krb/krb-types.pac b/src/analyzer/protocol/krb/krb-types.pac index f9c3e24d84..1e2f44e259 100644 --- a/src/analyzer/protocol/krb/krb-types.pac +++ b/src/analyzer/protocol/krb/krb-types.pac @@ -1,41 +1,41 @@ # Fundamental KRB types %header{ -IntrusivePtr GetStringFromPrincipalName(const KRB_Principal_Name* pname); +zeek::ValPtr GetStringFromPrincipalName(const KRB_Principal_Name* pname); -IntrusivePtr proc_cipher_list(const Array* list); +zeek::VectorValPtr proc_cipher_list(const Array* list); -IntrusivePtr proc_host_address_list(const BroAnalyzer a, const KRB_Host_Addresses* list); -IntrusivePtr proc_host_address(const BroAnalyzer a, const KRB_Host_Address* addr); +zeek::VectorValPtr proc_host_address_list(const BroAnalyzer a, const KRB_Host_Addresses* list); +zeek::RecordValPtr proc_host_address(const BroAnalyzer a, const KRB_Host_Address* addr); -IntrusivePtr proc_tickets(const KRB_Ticket_Sequence* list); -IntrusivePtr proc_ticket(const KRB_Ticket* ticket); +zeek::VectorValPtr proc_tickets(const KRB_Ticket_Sequence* list); +zeek::RecordValPtr proc_ticket(const KRB_Ticket* ticket); %} %code{ -IntrusivePtr GetStringFromPrincipalName(const KRB_Principal_Name* pname) +zeek::ValPtr GetStringFromPrincipalName(const KRB_Principal_Name* pname) { if ( pname->data()->size() == 1 ) return to_stringval(pname->data()[0][0]->encoding()->content()); if ( pname->data()->size() == 2 ) - return make_intrusive(fmt("%s/%s", (char *) pname->data()[0][0]->encoding()->content().begin(), (char *)pname->data()[0][1]->encoding()->content().begin())); + return zeek::make_intrusive(fmt("%s/%s", (char *) pname->data()[0][0]->encoding()->content().begin(), (char *)pname->data()[0][1]->encoding()->content().begin())); if ( pname->data()->size() == 3 ) // if the name-string has a third value, this will just append it, else this will return unknown as the principal name - return make_intrusive(fmt("%s/%s/%s", (char *) pname->data()[0][0]->encoding()->content().begin(), (char *)pname->data()[0][1]->encoding()->content().begin(), (char *)pname->data()[0][2]->encoding()->content().begin())); + return zeek::make_intrusive(fmt("%s/%s/%s", (char *) pname->data()[0][0]->encoding()->content().begin(), (char *)pname->data()[0][1]->encoding()->content().begin(), (char *)pname->data()[0][2]->encoding()->content().begin())); - return make_intrusive("unknown"); + return zeek::make_intrusive("unknown"); } -IntrusivePtr proc_cipher_list(const Array* list) +zeek::VectorValPtr proc_cipher_list(const Array* list) { - auto ciphers = make_intrusive(zeek::id::index_vec); + auto ciphers = zeek::make_intrusive(zeek::id::index_vec); for ( uint i = 0; i < list->data()->size(); ++i ) ciphers->Assign(ciphers->Size(), asn1_integer_to_val((*list->data())[i], zeek::TYPE_COUNT)); return ciphers; } -IntrusivePtr proc_host_address_list(const BroAnalyzer a, const KRB_Host_Addresses* list) +zeek::VectorValPtr proc_host_address_list(const BroAnalyzer a, const KRB_Host_Addresses* list) { - auto addrs = make_intrusive(zeek::id::find_type("KRB::Host_Address_Vector")); + auto addrs = zeek::make_intrusive(zeek::id::find_type("KRB::Host_Address_Vector")); for ( uint i = 0; i < list->addresses()->size(); ++i ) { @@ -45,9 +45,9 @@ IntrusivePtr proc_host_address_list(const BroAnalyzer a, const KRB_Ho return addrs; } -IntrusivePtr proc_host_address(const BroAnalyzer a, const KRB_Host_Address* addr) +zeek::RecordValPtr proc_host_address(const BroAnalyzer a, const KRB_Host_Address* addr) { - auto rv = make_intrusive(zeek::BifType::Record::KRB::Host_Address); + auto rv = zeek::make_intrusive(zeek::BifType::Record::KRB::Host_Address); const auto& addr_bytes = addr->address()->data()->content(); switch ( binary_to_int64(addr->addr_type()->encoding()->content()) ) @@ -61,7 +61,7 @@ IntrusivePtr proc_host_address(const BroAnalyzer a, const KRB_Host_Ad } auto bytes = reinterpret_cast(addr_bytes.data()); - rv->Assign(0, make_intrusive(IPAddr(IPv4, bytes, IPAddr::Network))); + rv->Assign(0, zeek::make_intrusive(IPAddr(IPv4, bytes, IPAddr::Network))); return rv; } case 24: @@ -73,7 +73,7 @@ IntrusivePtr proc_host_address(const BroAnalyzer a, const KRB_Host_Ad } auto bytes = reinterpret_cast(addr_bytes.data()); - rv->Assign(0, make_intrusive(IPAddr(IPv6, bytes, IPAddr::Network))); + rv->Assign(0, zeek::make_intrusive(IPAddr(IPv6, bytes, IPAddr::Network))); return rv; } case 20: @@ -85,16 +85,16 @@ IntrusivePtr proc_host_address(const BroAnalyzer a, const KRB_Host_Ad break; } - auto unk = make_intrusive(zeek::BifType::Record::KRB::Type_Value); + auto unk = zeek::make_intrusive(zeek::BifType::Record::KRB::Type_Value); unk->Assign(0, asn1_integer_to_val(addr->addr_type(), zeek::TYPE_COUNT)); unk->Assign(1, to_stringval(addr_bytes)); rv->Assign(2, std::move(unk)); return rv; } -IntrusivePtr proc_tickets(const KRB_Ticket_Sequence* list) +zeek::VectorValPtr proc_tickets(const KRB_Ticket_Sequence* list) { - auto tickets = make_intrusive(zeek::id::find_type("KRB::Ticket_Vector")); + auto tickets = zeek::make_intrusive(zeek::id::find_type("KRB::Ticket_Vector")); for ( uint i = 0; i < list->tickets()->size(); ++i ) { @@ -105,9 +105,9 @@ IntrusivePtr proc_tickets(const KRB_Ticket_Sequence* list) return tickets; } -IntrusivePtr proc_ticket(const KRB_Ticket* ticket) +zeek::RecordValPtr proc_ticket(const KRB_Ticket* ticket) { - auto rv = make_intrusive(zeek::BifType::Record::KRB::Ticket); + auto rv = zeek::make_intrusive(zeek::BifType::Record::KRB::Ticket); rv->Assign(0, asn1_integer_to_val(ticket->tkt_vno()->data(), zeek::TYPE_COUNT)); rv->Assign(1, to_stringval(ticket->realm()->data()->content())); diff --git a/src/analyzer/protocol/login/Login.cc b/src/analyzer/protocol/login/Login.cc index 63d9c12541..2b5bbf3105 100644 --- a/src/analyzer/protocol/login/Login.cc +++ b/src/analyzer/protocol/login/Login.cc @@ -6,7 +6,7 @@ #include #include -#include "BroString.h" +#include "ZeekString.h" #include "NetVar.h" #include "RE.h" #include "Reporter.h" @@ -25,7 +25,7 @@ static RE_Matcher* re_login_failure_msgs; static RE_Matcher* re_login_success_msgs; static RE_Matcher* re_login_timeouts; -static RE_Matcher* init_RE(ListVal* l); +static RE_Matcher* init_RE(zeek::ListVal* l); Login_Analyzer::Login_Analyzer(const char* name, Connection* conn) : tcp::TCP_ApplicationAnalyzer(name, conn), user_text() @@ -45,13 +45,13 @@ Login_Analyzer::Login_Analyzer(const char* name, Connection* conn) if ( ! re_skip_authentication ) { - IntrusivePtr skip_authentication = zeek::id::find_val("skip_authentication")->AsTableVal()->ToPureListVal(); - IntrusivePtr direct_login_prompts = zeek::id::find_val("direct_login_prompts")->AsTableVal()->ToPureListVal(); - IntrusivePtr login_prompts = zeek::id::find_val("login_prompts")->AsTableVal()->ToPureListVal(); - IntrusivePtr login_non_failure_msgs = zeek::id::find_val("login_non_failure_msgs")->AsTableVal()->ToPureListVal(); - IntrusivePtr login_failure_msgs = zeek::id::find_val("login_failure_msgs")->AsTableVal()->ToPureListVal(); - IntrusivePtr login_success_msgs = zeek::id::find_val("login_success_msgs")->AsTableVal()->ToPureListVal(); - IntrusivePtr login_timeouts = zeek::id::find_val("login_timeouts")->AsTableVal()->ToPureListVal(); + zeek::ListValPtr skip_authentication = zeek::id::find_val("skip_authentication")->AsTableVal()->ToPureListVal(); + zeek::ListValPtr direct_login_prompts = zeek::id::find_val("direct_login_prompts")->AsTableVal()->ToPureListVal(); + zeek::ListValPtr login_prompts = zeek::id::find_val("login_prompts")->AsTableVal()->ToPureListVal(); + zeek::ListValPtr login_non_failure_msgs = zeek::id::find_val("login_non_failure_msgs")->AsTableVal()->ToPureListVal(); + zeek::ListValPtr login_failure_msgs = zeek::id::find_val("login_failure_msgs")->AsTableVal()->ToPureListVal(); + zeek::ListValPtr login_success_msgs = zeek::id::find_val("login_success_msgs")->AsTableVal()->ToPureListVal(); + zeek::ListValPtr login_timeouts = zeek::id::find_val("login_timeouts")->AsTableVal()->ToPureListVal(); #ifdef USE_PERFTOOLS_DEBUG HeapLeakChecker::Disabler disabler; @@ -327,8 +327,8 @@ void Login_Analyzer::SetEnv(bool orig, char* name, char* val) { if ( username ) { - const BroString* u = username->AsString(); - const byte_vec ub = u->Bytes(); + const zeek::String* u = username->AsString(); + const zeek::byte_vec ub = u->Bytes(); const char* us = (const char*) ub; if ( ! streq(val, us) ) Confused("multiple_USERs", val); @@ -336,25 +336,25 @@ void Login_Analyzer::SetEnv(bool orig, char* name, char* val) } // "val" gets copied here. - username = new StringVal(val); + username = new zeek::StringVal(val); } else if ( login_terminal && streq(name, "TERM") ) EnqueueConnEvent(login_terminal, ConnVal(), - make_intrusive(val) + zeek::make_intrusive(val) ); else if ( login_display && streq(name, "DISPLAY") ) EnqueueConnEvent(login_display, ConnVal(), - make_intrusive(val) + zeek::make_intrusive(val) ); else if ( login_prompt && streq(name, "TTYPROMPT") ) EnqueueConnEvent(login_prompt, ConnVal(), - make_intrusive(val) + zeek::make_intrusive(val) ); } @@ -389,7 +389,7 @@ void Login_Analyzer::LoginEvent(EventHandlerPtr f, const char* line, if ( no_user_okay ) { Unref(username); - username = new StringVal(""); + username = new zeek::StringVal(""); } else @@ -414,7 +414,7 @@ void Login_Analyzer::LoginEvent(EventHandlerPtr f, const char* line, if ( no_user_okay ) { Unref(username); - username = new StringVal(""); + username = new zeek::StringVal(""); } else @@ -425,16 +425,16 @@ void Login_Analyzer::LoginEvent(EventHandlerPtr f, const char* line, } } - Val* password = HaveTypeahead() ? - PopUserTextVal() : new StringVal(""); + zeek::Val* password = HaveTypeahead() ? + PopUserTextVal() : new zeek::StringVal(""); EnqueueConnEvent(f, ConnVal(), - IntrusivePtr{NewRef{}, username}, - client_name ? IntrusivePtr{NewRef{}, client_name} - : val_mgr->EmptyString(), - IntrusivePtr{AdoptRef{}, password}, - make_intrusive(line) + zeek::IntrusivePtr{zeek::NewRef{}, username}, + client_name ? zeek::IntrusivePtr{zeek::NewRef{}, client_name} + : zeek::val_mgr->EmptyString(), + zeek::IntrusivePtr{zeek::AdoptRef{}, password}, + zeek::make_intrusive(line) ); } @@ -453,7 +453,7 @@ void Login_Analyzer::LineEvent(EventHandlerPtr f, const char* line) EnqueueConnEvent(f, ConnVal(), - make_intrusive(line) + zeek::make_intrusive(line) ); } @@ -465,8 +465,8 @@ void Login_Analyzer::Confused(const char* msg, const char* line) if ( login_confused ) EnqueueConnEvent(login_confused, ConnVal(), - make_intrusive(msg), - make_intrusive(line) + zeek::make_intrusive(msg), + zeek::make_intrusive(line) ); if ( login_confused_text ) @@ -489,7 +489,7 @@ void Login_Analyzer::ConfusionText(const char* line) if ( login_confused_text ) EnqueueConnEvent(login_confused_text, ConnVal(), - make_intrusive(line) + zeek::make_intrusive(line) ); } @@ -595,14 +595,14 @@ char* Login_Analyzer::PopUserText() return s; } -Val* Login_Analyzer::PopUserTextVal() +zeek::Val* Login_Analyzer::PopUserTextVal() { char* s = PopUserText(); if ( s ) - return new StringVal(new BroString(true, byte_vec(s), strlen(s))); + return new zeek::StringVal(new zeek::String(true, zeek::byte_vec(s), strlen(s))); else - return val_mgr->EmptyString()->Ref(); + return zeek::val_mgr->EmptyString()->Ref(); } bool Login_Analyzer::MatchesTypeahead(const char* line) const @@ -625,7 +625,7 @@ void Login_Analyzer::FlushEmptyTypeahead() delete [] PopUserText(); } -RE_Matcher* init_RE(ListVal* l) +RE_Matcher* init_RE(zeek::ListVal* l) { RE_Matcher* re = l->BuildRE(); if ( re ) diff --git a/src/analyzer/protocol/login/Login.h b/src/analyzer/protocol/login/Login.h index 6398725ec0..20072f95b6 100644 --- a/src/analyzer/protocol/login/Login.h +++ b/src/analyzer/protocol/login/Login.h @@ -56,7 +56,7 @@ protected: void AddUserText(const char* line); // complains on overflow char* PeekUserText(); // internal warning on underflow char* PopUserText(); // internal warning on underflow - Val* PopUserTextVal(); + zeek::Val* PopUserTextVal(); bool MatchesTypeahead(const char* line) const; bool HaveTypeahead() const { return num_user_text > 0; } @@ -69,8 +69,8 @@ protected: int user_text_first, user_text_last; // indices into user_text int num_user_text; // number of entries in user_text - Val* username; // last username reported - Val* client_name; // rlogin client name (or nil if none) + zeek::Val* username; // last username reported + zeek::Val* client_name; // rlogin client name (or nil if none) login_state state; int lines_scanned; diff --git a/src/analyzer/protocol/login/NVT.cc b/src/analyzer/protocol/login/NVT.cc index 230c09ba16..52922e58a7 100644 --- a/src/analyzer/protocol/login/NVT.cc +++ b/src/analyzer/protocol/login/NVT.cc @@ -5,7 +5,7 @@ #include -#include "BroString.h" +#include "ZeekString.h" #include "NetVar.h" #include "Event.h" #include "Reporter.h" @@ -461,7 +461,7 @@ void NVT_Analyzer::SetTerminal(const u_char* terminal, int len) if ( login_terminal ) EnqueueConnEvent(login_terminal, ConnVal(), - make_intrusive(new BroString(terminal, len, false)) + zeek::make_intrusive(new zeek::String(terminal, len, false)) ); } diff --git a/src/analyzer/protocol/login/RSH.cc b/src/analyzer/protocol/login/RSH.cc index 3827cbd2f8..a34889bb5c 100644 --- a/src/analyzer/protocol/login/RSH.cc +++ b/src/analyzer/protocol/login/RSH.cc @@ -175,24 +175,24 @@ void Rsh_Analyzer::DeliverStream(int len, const u_char* data, bool orig) vl.emplace_back(ConnVal()); if ( client_name ) - vl.emplace_back(NewRef{}, client_name); + vl.emplace_back(zeek::NewRef{}, client_name); else - vl.emplace_back(make_intrusive("")); + vl.emplace_back(zeek::make_intrusive("")); if ( username ) - vl.emplace_back(NewRef{}, username); + vl.emplace_back(zeek::NewRef{}, username); else - vl.emplace_back(make_intrusive("")); + vl.emplace_back(zeek::make_intrusive("")); - vl.emplace_back(make_intrusive(line)); + vl.emplace_back(zeek::make_intrusive(line)); if ( orig ) { if ( contents_orig->RshSaveState() == RSH_SERVER_USER_NAME ) // First input - vl.emplace_back(val_mgr->True()); + vl.emplace_back(zeek::val_mgr->True()); else - vl.emplace_back(val_mgr->False()); + vl.emplace_back(zeek::val_mgr->False()); EnqueueConnEvent(rsh_request, std::move(vl)); } @@ -209,7 +209,7 @@ void Rsh_Analyzer::ClientUserName(const char* s) return; } - client_name = new StringVal(s); + client_name = new zeek::StringVal(s); } void Rsh_Analyzer::ServerUserName(const char* s) @@ -221,5 +221,5 @@ void Rsh_Analyzer::ServerUserName(const char* s) return; } - username = new StringVal(s); + username = new zeek::StringVal(s); } diff --git a/src/analyzer/protocol/login/Rlogin.cc b/src/analyzer/protocol/login/Rlogin.cc index f2dd23f2ab..dfb868c621 100644 --- a/src/analyzer/protocol/login/Rlogin.cc +++ b/src/analyzer/protocol/login/Rlogin.cc @@ -132,7 +132,7 @@ void Contents_Rlogin_Analyzer::DoDeliver(int len, const u_char* data) } } else - { + { // Unknown control, or we're confused. // Put back what we've consumed. unsigned char buf[64]; @@ -231,7 +231,7 @@ void Rlogin_Analyzer::ClientUserName(const char* s) return; } - client_name = new StringVal(s); + client_name = new zeek::StringVal(s); } void Rlogin_Analyzer::ServerUserName(const char* s) @@ -246,6 +246,6 @@ void Rlogin_Analyzer::TerminalType(const char* s) if ( login_terminal ) EnqueueConnEvent(login_terminal, ConnVal(), - make_intrusive(s) + zeek::make_intrusive(s) ); } diff --git a/src/analyzer/protocol/login/functions.bif b/src/analyzer/protocol/login/functions.bif index 676f81409c..0abfeabdb2 100644 --- a/src/analyzer/protocol/login/functions.bif +++ b/src/analyzer/protocol/login/functions.bif @@ -28,13 +28,13 @@ function get_login_state%(cid: conn_id%): count %{ Connection* c = sessions->FindConnection(cid); if ( ! c ) - return val_mgr->False(); + return zeek::val_mgr->False(); analyzer::Analyzer* la = c->FindAnalyzer("Login"); if ( ! la ) - return val_mgr->False(); + return zeek::val_mgr->False(); - return val_mgr->Count(int(static_cast(la)->LoginState())); + return zeek::val_mgr->Count(int(static_cast(la)->LoginState())); %} ## Sets the login state of a connection with a login analyzer. @@ -52,12 +52,12 @@ function set_login_state%(cid: conn_id, new_state: count%): bool %{ Connection* c = sessions->FindConnection(cid); if ( ! c ) - return val_mgr->False(); + return zeek::val_mgr->False(); analyzer::Analyzer* la = c->FindAnalyzer("Login"); if ( ! la ) - return val_mgr->False(); + return zeek::val_mgr->False(); static_cast(la)->SetLoginState(analyzer::login::login_state(new_state)); - return val_mgr->True(); + return zeek::val_mgr->True(); %} diff --git a/src/analyzer/protocol/mime/MIME.cc b/src/analyzer/protocol/mime/MIME.cc index 377d272bfa..75ead71f8d 100644 --- a/src/analyzer/protocol/mime/MIME.cc +++ b/src/analyzer/protocol/mime/MIME.cc @@ -21,7 +21,7 @@ namespace analyzer { namespace mime { -static const data_chunk_t null_data_chunk = { 0, nullptr }; +static const zeek::data_chunk_t null_data_chunk = { 0, nullptr }; int mime_header_only = 0; int mime_decode_data = 1; @@ -98,7 +98,7 @@ static const char* MIMEContentEncodingName[] = { nullptr, }; -bool is_null_data_chunk(data_chunk_t b) +bool is_null_data_chunk(zeek::data_chunk_t b) { return b.data == nullptr; } @@ -108,39 +108,39 @@ bool is_lws(char ch) return ch == 9 || ch == 32; } -StringVal* new_string_val(int length, const char* data) +zeek::StringVal* new_string_val(int length, const char* data) { return to_string_val(length, data).release(); } -StringVal* new_string_val(const char* data, const char* end_of_data) +zeek::StringVal* new_string_val(const char* data, const char* end_of_data) { return to_string_val(data, end_of_data).release(); } -StringVal* new_string_val(const data_chunk_t buf) +zeek::StringVal* new_string_val(const zeek::data_chunk_t buf) { return to_string_val(buf).release(); } -IntrusivePtr to_string_val(int length, const char* data) +zeek::StringValPtr to_string_val(int length, const char* data) { - return make_intrusive(length, data); + return zeek::make_intrusive(length, data); } -IntrusivePtr to_string_val(const char* data, const char* end_of_data) +zeek::StringValPtr to_string_val(const char* data, const char* end_of_data) { - return make_intrusive(end_of_data - data, data); + return zeek::make_intrusive(end_of_data - data, data); } -IntrusivePtr to_string_val(const data_chunk_t buf) +zeek::StringValPtr to_string_val(const zeek::data_chunk_t buf) { return to_string_val(buf.length, buf.data); } -static data_chunk_t get_data_chunk(BroString* s) +static zeek::data_chunk_t get_data_chunk(zeek::String* s) { - data_chunk_t b; + zeek::data_chunk_t b; b.length = s->Len(); b.data = (const char*) s->Bytes(); return b; } -int fputs(data_chunk_t b, FILE* fp) +int fputs(zeek::data_chunk_t b, FILE* fp) { for ( int i = 0; i < b.length; ++i ) if ( fputc(b.data[i], fp) == EOF ) @@ -155,7 +155,7 @@ void MIME_Mail::Undelivered(int len) is_orig, cur_entity_id); } -bool istrequal(data_chunk_t s, const char* t) +bool istrequal(zeek::data_chunk_t s, const char* t) { int len = strlen(t); @@ -233,7 +233,7 @@ int MIME_skip_lws_comments(int len, const char* data) return len; } -int MIME_get_field_name(int len, const char* data, data_chunk_t* name) +int MIME_get_field_name(int len, const char* data, zeek::data_chunk_t* name) { int i = MIME_skip_lws_comments(len, data); while ( i < len ) @@ -281,7 +281,7 @@ static bool MIME_is_token_char (char ch, bool is_boundary = false) // See RFC 2045, page 12. // A token is composed of characters that are not SPACE, CTLs or tspecials -int MIME_get_token(int len, const char* data, data_chunk_t* token, +int MIME_get_token(int len, const char* data, zeek::data_chunk_t* token, bool is_boundary) { int i = 0; @@ -313,7 +313,7 @@ int MIME_get_token(int len, const char* data, data_chunk_t* token, return -1; } -int MIME_get_slash_token_pair(int len, const char* data, data_chunk_t* first, data_chunk_t* second) +int MIME_get_slash_token_pair(int len, const char* data, zeek::data_chunk_t* first, zeek::data_chunk_t* second) { int offset; const char* data_start = data; @@ -353,7 +353,7 @@ int MIME_get_slash_token_pair(int len, const char* data, data_chunk_t* first, da } // See RFC 2822, page 13. -int MIME_get_quoted_string(int len, const char* data, data_chunk_t* str) +int MIME_get_quoted_string(int len, const char* data, zeek::data_chunk_t* str) { int offset = MIME_skip_lws_comments(len, data); @@ -380,7 +380,7 @@ int MIME_get_quoted_string(int len, const char* data, data_chunk_t* str) return -1; } -int MIME_get_value(int len, const char* data, BroString*& buf, bool is_boundary) +int MIME_get_value(int len, const char* data, zeek::String*& buf, bool is_boundary) { int offset = 0; @@ -392,7 +392,7 @@ int MIME_get_value(int len, const char* data, BroString*& buf, bool is_boundary) if ( len > 0 && *data == '"' ) { - data_chunk_t str; + zeek::data_chunk_t str; int end = MIME_get_quoted_string(len, data, &str); if ( end < 0 ) return -1; @@ -403,12 +403,12 @@ int MIME_get_value(int len, const char* data, BroString*& buf, bool is_boundary) else { - data_chunk_t str; + zeek::data_chunk_t str; int end = MIME_get_token(len, data, &str, is_boundary); if ( end < 0 ) return -1; - buf = new BroString((const u_char*)str.data, str.length, true); + buf = new zeek::String((const u_char*)str.data, str.length, true); return offset + end; } } @@ -416,7 +416,7 @@ int MIME_get_value(int len, const char* data, BroString*& buf, bool is_boundary) // Decode each quoted-pair: a '\' followed by a character by the // quoted character. The decoded string is returned. -BroString* MIME_decode_quoted_pairs(data_chunk_t buf) +zeek::String* MIME_decode_quoted_pairs(zeek::data_chunk_t buf) { const char* data = buf.data; char* dest = new char[buf.length+1]; @@ -436,7 +436,7 @@ BroString* MIME_decode_quoted_pairs(data_chunk_t buf) dest[j++] = data[i]; dest[j] = 0; - return new BroString(true, (byte_vec) dest, j); + return new zeek::String(true, (zeek::byte_vec) dest, j); } @@ -457,10 +457,10 @@ MIME_Multiline::~MIME_Multiline() void MIME_Multiline::append(int len, const char* data) { - buffer.push_back(new BroString((const u_char*) data, len, true)); + buffer.push_back(new zeek::String((const u_char*) data, len, true)); } -BroString* MIME_Multiline::get_concatenated_line() +zeek::String* MIME_Multiline::get_concatenated_line() { if ( buffer.empty() ) return nullptr; @@ -477,7 +477,7 @@ MIME_Header::MIME_Header(MIME_Multiline* hl) lines = hl; name = value = value_token = rest_value = null_data_chunk; - BroString* s = hl->get_concatenated_line(); + zeek::String* s = hl->get_concatenated_line(); int len = s->Len(); const char* data = (const char*) s->Bytes(); @@ -523,7 +523,7 @@ int MIME_Header::get_first_token() } } -data_chunk_t MIME_Header::get_value_token() +zeek::data_chunk_t MIME_Header::get_value_token() { if ( ! is_null_data_chunk(value_token) ) return value_token; @@ -531,7 +531,7 @@ data_chunk_t MIME_Header::get_value_token() return value_token; } -data_chunk_t MIME_Header::get_value_after_token() +zeek::data_chunk_t MIME_Header::get_value_after_token() { if ( ! is_null_data_chunk(rest_value) ) return rest_value; @@ -560,8 +560,8 @@ void MIME_Entity::init() need_to_parse_parameters = 0; - content_type_str = make_intrusive("TEXT"); - content_subtype_str = make_intrusive("PLAIN"); + content_type_str = zeek::make_intrusive("TEXT"); + content_subtype_str = zeek::make_intrusive("PLAIN"); content_encoding_str = nullptr; multipart_boundary = nullptr; @@ -764,7 +764,7 @@ void MIME_Entity::FinishHeader() delete h; } -int MIME_Entity::LookupMIMEHeaderName(data_chunk_t name) +int MIME_Entity::LookupMIMEHeaderName(zeek::data_chunk_t name) { // A linear lookup should be fine for now. // header names are case-insensitive (RFC 822, 2822, 2045). @@ -795,11 +795,11 @@ void MIME_Entity::ParseMIMEHeader(MIME_Header* h) bool MIME_Entity::ParseContentTypeField(MIME_Header* h) { - data_chunk_t val = h->get_value(); + zeek::data_chunk_t val = h->get_value(); int len = val.length; const char* data = val.data; - data_chunk_t ty, subty; + zeek::data_chunk_t ty, subty; int offset; offset = MIME_get_slash_token_pair(len, data, &ty, &subty); @@ -811,9 +811,9 @@ bool MIME_Entity::ParseContentTypeField(MIME_Header* h) data += offset; len -= offset; - content_type_str = make_intrusive(ty.length, ty.data); + content_type_str = zeek::make_intrusive(ty.length, ty.data); content_type_str->ToUpper(); - content_subtype_str = make_intrusive(subty.length, subty.data); + content_subtype_str = zeek::make_intrusive(subty.length, subty.data); content_subtype_str->ToUpper(); ParseContentType(ty, subty); @@ -834,7 +834,7 @@ bool MIME_Entity::ParseContentTypeField(MIME_Header* h) bool MIME_Entity::ParseContentEncodingField(MIME_Header* h) { - data_chunk_t enc; + zeek::data_chunk_t enc; enc = h->get_value_token(); if ( is_null_data_chunk(enc) ) @@ -844,12 +844,12 @@ bool MIME_Entity::ParseContentEncodingField(MIME_Header* h) } delete content_encoding_str; - content_encoding_str = new BroString((const u_char*)enc.data, enc.length, true); + content_encoding_str = new zeek::String((const u_char*)enc.data, enc.length, true); ParseContentEncoding(enc); if ( need_to_parse_parameters ) { - data_chunk_t val = h->get_value_after_token(); + zeek::data_chunk_t val = h->get_value_after_token(); if ( ! is_null_data_chunk(val) ) ParseFieldParameters(val.length, val.data); } @@ -859,7 +859,7 @@ bool MIME_Entity::ParseContentEncodingField(MIME_Header* h) bool MIME_Entity::ParseFieldParameters(int len, const char* data) { - data_chunk_t attr; + zeek::data_chunk_t attr; while ( true ) { @@ -892,7 +892,7 @@ bool MIME_Entity::ParseFieldParameters(int len, const char* data) data += offset; len -= offset; - BroString* val = nullptr; + zeek::String* val = nullptr; if ( current_field_type == MIME_CONTENT_TYPE && content_type == CONTENT_TYPE_MULTIPART && @@ -908,9 +908,9 @@ bool MIME_Entity::ParseFieldParameters(int len, const char* data) continue; } - data_chunk_t vd = get_data_chunk(val); + zeek::data_chunk_t vd = get_data_chunk(val); delete multipart_boundary; - multipart_boundary = new BroString((const u_char*)vd.data, + multipart_boundary = new zeek::String((const u_char*)vd.data, vd.length, true); } else @@ -932,7 +932,7 @@ bool MIME_Entity::ParseFieldParameters(int len, const char* data) return true; } -void MIME_Entity::ParseContentType(data_chunk_t type, data_chunk_t sub_type) +void MIME_Entity::ParseContentType(zeek::data_chunk_t type, zeek::data_chunk_t sub_type) { int i; for ( i = 0; MIMEContentTypeName[i]; ++i ) @@ -959,7 +959,7 @@ void MIME_Entity::ParseContentType(data_chunk_t type, data_chunk_t sub_type) } } -void MIME_Entity::ParseContentEncoding(data_chunk_t encoding_mechanism) +void MIME_Entity::ParseContentEncoding(zeek::data_chunk_t encoding_mechanism) { int i; for ( i = 0; MIMEContentEncodingName[i]; ++i ) @@ -983,7 +983,7 @@ int MIME_Entity::CheckBoundaryDelimiter(int len, const char* data) { len -= 2; data += 2; - data_chunk_t delim = get_data_chunk(multipart_boundary); + zeek::data_chunk_t delim = get_data_chunk(multipart_boundary); int i; for ( i = 0; i < len && i < delim.length; ++i ) @@ -1298,13 +1298,13 @@ void MIME_Entity::DebugPrintHeaders() #endif } -RecordVal* MIME_Message::BuildHeaderVal(MIME_Header* h) +zeek::RecordVal* MIME_Message::BuildHeaderVal(MIME_Header* h) { return ToHeaderVal(h).release(); } -IntrusivePtr MIME_Message::ToHeaderVal(MIME_Header* h) +zeek::RecordValPtr MIME_Message::ToHeaderVal(MIME_Header* h) { static auto mime_header_rec = zeek::id::find_type("mime_header_rec"); - auto header_record = make_intrusive(mime_header_rec); + auto header_record = zeek::make_intrusive(mime_header_rec); header_record->Assign(0, to_string_val(h->get_name())); auto upper_hn = to_string_val(h->get_name()); upper_hn->ToUpper(); @@ -1313,17 +1313,17 @@ IntrusivePtr MIME_Message::ToHeaderVal(MIME_Header* h) return header_record; } -TableVal* MIME_Message::BuildHeaderTable(MIME_HeaderList& hlist) +zeek::TableVal* MIME_Message::BuildHeaderTable(MIME_HeaderList& hlist) { return ToHeaderTable(hlist).release(); } -IntrusivePtr MIME_Message::ToHeaderTable(MIME_HeaderList& hlist) +zeek::TableValPtr MIME_Message::ToHeaderTable(MIME_HeaderList& hlist) { static auto mime_header_list = zeek::id::find_type("mime_header_list"); - auto t = make_intrusive(mime_header_list); + auto t = zeek::make_intrusive(mime_header_list); for ( unsigned int i = 0; i < hlist.size(); ++i ) { - auto index = val_mgr->Count(i + 1); // index starting from 1 + auto index = zeek::val_mgr->Count(i + 1); // index starting from 1 MIME_Header* h = hlist[i]; t->Assign(std::move(index), ToHeaderVal(h)); } @@ -1352,7 +1352,7 @@ MIME_Mail::MIME_Mail(analyzer::Analyzer* mail_analyzer, bool orig, int buf_size) length = max_chunk_length; buffer_start = data_start = 0; - data_buffer = new BroString(true, new u_char[length+1], length); + data_buffer = new zeek::String(true, new u_char[length+1], length); if ( mime_content_hash ) { @@ -1382,8 +1382,8 @@ void MIME_Mail::Done() analyzer->EnqueueConnEvent(mime_content_hash, analyzer->ConnVal(), - val_mgr->Count(content_hash_length), - make_intrusive(new BroString(true, digest, 16)) + zeek::val_mgr->Count(content_hash_length), + zeek::make_intrusive(new zeek::String(true, digest, 16)) ); } @@ -1418,12 +1418,12 @@ void MIME_Mail::EndEntity(MIME_Entity* /* entity */) { if ( mime_entity_data ) { - BroString* s = concatenate(entity_content); + zeek::String* s = concatenate(entity_content); analyzer->EnqueueConnEvent(mime_entity_data, analyzer->ConnVal(), - val_mgr->Count(s->Len()), - make_intrusive(s) + zeek::val_mgr->Count(s->Len()), + zeek::make_intrusive(s) ); if ( ! mime_all_data ) @@ -1474,7 +1474,7 @@ void MIME_Mail::SubmitData(int len, const char* buf) if ( mime_entity_data || mime_all_data ) { - BroString* s = new BroString((const u_char*) buf, len, false); + zeek::String* s = new zeek::String((const u_char*) buf, len, false); if ( mime_entity_data ) entity_content.push_back(s); @@ -1489,8 +1489,8 @@ void MIME_Mail::SubmitData(int len, const char* buf) analyzer->EnqueueConnEvent(mime_segment_data, analyzer->ConnVal(), - val_mgr->Count(data_len), - make_intrusive(data_len, data) + zeek::val_mgr->Count(data_len), + zeek::make_intrusive(data_len, data) ); } @@ -1531,13 +1531,13 @@ void MIME_Mail::SubmitAllData() { if ( mime_all_data ) { - BroString* s = concatenate(all_content); + zeek::String* s = concatenate(all_content); delete_strings(all_content); analyzer->EnqueueConnEvent(mime_all_data, analyzer->ConnVal(), - val_mgr->Count(s->Len()), - make_intrusive(s) + zeek::val_mgr->Count(s->Len()), + zeek::make_intrusive(s) ); } } @@ -1564,7 +1564,7 @@ void MIME_Mail::SubmitEvent(int event_type, const char* detail) if ( mime_event ) analyzer->EnqueueConnEvent(mime_event, analyzer->ConnVal(), - make_intrusive(category), - make_intrusive(detail) + zeek::make_intrusive(category), + zeek::make_intrusive(detail) ); } diff --git a/src/analyzer/protocol/mime/MIME.h b/src/analyzer/protocol/mime/MIME.h index bfea4ef6a2..5511ceae3d 100644 --- a/src/analyzer/protocol/mime/MIME.h +++ b/src/analyzer/protocol/mime/MIME.h @@ -6,14 +6,19 @@ #include #include -#include "BroString.h" +#include "ZeekString.h" #include "Reporter.h" #include "analyzer/Analyzer.h" -class TableVal; -class StringVal; +ZEEK_FORWARD_DECLARE_NAMESPACED(TableVal, zeek); +ZEEK_FORWARD_DECLARE_NAMESPACED(StringVal, zeek); class Base64Converter; +namespace zeek { +using TableValPtr = zeek::IntrusivePtr; +using StringValPtr = zeek::IntrusivePtr; +} + namespace analyzer { namespace mime { // MIME: Multipurpose Internet Mail Extensions @@ -58,11 +63,11 @@ public: ~MIME_Multiline(); void append(int len, const char* data); - BroString* get_concatenated_line(); + zeek::String* get_concatenated_line(); protected: - std::vector buffer; - BroString* line; + std::vector buffer; + zeek::String* line; }; class MIME_Header { @@ -70,19 +75,19 @@ public: explicit MIME_Header(MIME_Multiline* hl); ~MIME_Header(); - data_chunk_t get_name() const { return name; } - data_chunk_t get_value() const { return value; } + zeek::data_chunk_t get_name() const { return name; } + zeek::data_chunk_t get_value() const { return value; } - data_chunk_t get_value_token(); - data_chunk_t get_value_after_token(); + zeek::data_chunk_t get_value_token(); + zeek::data_chunk_t get_value_after_token(); protected: int get_first_token(); MIME_Multiline* lines; - data_chunk_t name; - data_chunk_t value; - data_chunk_t value_token, rest_value; + zeek::data_chunk_t name; + zeek::data_chunk_t value; + zeek::data_chunk_t value_token, rest_value; }; @@ -99,11 +104,11 @@ public: MIME_Entity* Parent() const { return parent; } int MIMEContentType() const { return content_type; } [[deprecated("Remove in v4.1. Use GetContentType().")]] - StringVal* ContentType() const { return content_type_str.get(); } + zeek::StringVal* ContentType() const { return content_type_str.get(); } [[deprecated("Remove in v4.1. Use GetContentSubType().")]] - StringVal* ContentSubType() const { return content_subtype_str.get(); } - const IntrusivePtr& GetContentType() const { return content_type_str; } - const IntrusivePtr& GetContentSubType() const { return content_subtype_str; } + zeek::StringVal* ContentSubType() const { return content_subtype_str.get(); } + const zeek::StringValPtr& GetContentType() const { return content_type_str; } + const zeek::StringValPtr& GetContentSubType() const { return content_subtype_str; } int ContentTransferEncoding() const { return content_encoding; } protected: @@ -115,13 +120,13 @@ protected: void FinishHeader(); void ParseMIMEHeader(MIME_Header* h); - int LookupMIMEHeaderName(data_chunk_t name); + int LookupMIMEHeaderName(zeek::data_chunk_t name); bool ParseContentTypeField(MIME_Header* h); bool ParseContentEncodingField(MIME_Header* h); bool ParseFieldParameters(int len, const char* data); - void ParseContentType(data_chunk_t type, data_chunk_t sub_type); - void ParseContentEncoding(data_chunk_t encoding_mechanism); + void ParseContentType(zeek::data_chunk_t type, zeek::data_chunk_t sub_type); + void ParseContentEncoding(zeek::data_chunk_t encoding_mechanism); void BeginBody(); void NewDataLine(int len, const char* data, bool trailing_CRLF); @@ -159,10 +164,10 @@ protected: int current_field_type; int need_to_parse_parameters; - IntrusivePtr content_type_str; - IntrusivePtr content_subtype_str; - BroString* content_encoding_str; - BroString* multipart_boundary; + zeek::StringValPtr content_type_str; + zeek::StringValPtr content_subtype_str; + zeek::String* content_encoding_str; + zeek::String* multipart_boundary; int content_type, content_subtype, content_encoding; @@ -231,12 +236,12 @@ protected: bool finished; [[deprecated("Remove in v4.1. Use ToHeaderVal().")]] - RecordVal* BuildHeaderVal(MIME_Header* h); + zeek::RecordVal* BuildHeaderVal(MIME_Header* h); [[deprecated("Remove in v4.1. Use ToHeaderTable().")]] - TableVal* BuildHeaderTable(MIME_HeaderList& hlist); + zeek::TableVal* BuildHeaderTable(MIME_HeaderList& hlist); - IntrusivePtr ToHeaderVal(MIME_Header* h); - IntrusivePtr ToHeaderTable(MIME_HeaderList& hlist); + zeek::RecordValPtr ToHeaderVal(MIME_Header* h); + zeek::TableValPtr ToHeaderTable(MIME_HeaderList& hlist); }; class MIME_Mail final : public MIME_Message { @@ -264,40 +269,39 @@ protected: int compute_content_hash; int content_hash_length; EVP_MD_CTX* md5_hash; - std::vector entity_content; - std::vector all_content; + std::vector entity_content; + std::vector all_content; - BroString* data_buffer; + zeek::String* data_buffer; uint64_t cur_entity_len; std::string cur_entity_id; }; - -extern bool is_null_data_chunk(data_chunk_t b); +extern bool is_null_data_chunk(zeek::data_chunk_t b); [[deprecated("Remove in v4.1. Use analyzer::mime::to_string_val().")]] -extern StringVal* new_string_val(int length, const char* data); +extern zeek::StringVal* new_string_val(int length, const char* data); [[deprecated("Remove in v4.1. Use analyzer::mime::to_string_val().")]] -extern StringVal* new_string_val(const char* data, const char* end_of_data); +extern zeek::StringVal* new_string_val(const char* data, const char* end_of_data); [[deprecated("Remove in v4.1. Use analyzer::mime::to_string_val().")]] -extern StringVal* new_string_val(const data_chunk_t buf); -extern IntrusivePtr to_string_val(int length, const char* data); -extern IntrusivePtr to_string_val(const char* data, const char* end_of_data); -extern IntrusivePtr to_string_val(const data_chunk_t buf); -extern int fputs(data_chunk_t b, FILE* fp); -extern bool istrequal(data_chunk_t s, const char* t); +extern zeek::StringVal* new_string_val(const zeek::data_chunk_t buf); +extern zeek::StringValPtr to_string_val(int length, const char* data); +extern zeek::StringValPtr to_string_val(const char* data, const char* end_of_data); +extern zeek::StringValPtr to_string_val(const zeek::data_chunk_t buf); +extern int fputs(zeek::data_chunk_t b, FILE* fp); +extern bool istrequal(zeek::data_chunk_t s, const char* t); extern bool is_lws(char ch); extern bool MIME_is_field_name_char(char ch); extern int MIME_count_leading_lws(int len, const char* data); extern int MIME_count_trailing_lws(int len, const char* data); extern int MIME_skip_comments(int len, const char* data); extern int MIME_skip_lws_comments(int len, const char* data); -extern int MIME_get_token(int len, const char* data, data_chunk_t* token, +extern int MIME_get_token(int len, const char* data, zeek::data_chunk_t* token, bool is_boundary = false); -extern int MIME_get_slash_token_pair(int len, const char* data, data_chunk_t* first, data_chunk_t* second); -extern int MIME_get_value(int len, const char* data, BroString*& buf, +extern int MIME_get_slash_token_pair(int len, const char* data, zeek::data_chunk_t* first, zeek::data_chunk_t* second); +extern int MIME_get_value(int len, const char* data, zeek::String*& buf, bool is_boundary = false); -extern int MIME_get_field_name(int len, const char* data, data_chunk_t* name); -extern BroString* MIME_decode_quoted_pairs(data_chunk_t buf); +extern int MIME_get_field_name(int len, const char* data, zeek::data_chunk_t* name); +extern zeek::String* MIME_decode_quoted_pairs(zeek::data_chunk_t buf); } } // namespace analyzer::* diff --git a/src/analyzer/protocol/modbus/modbus-analyzer.pac b/src/analyzer/protocol/modbus/modbus-analyzer.pac index 06271c82e6..13117ffbb6 100644 --- a/src/analyzer/protocol/modbus/modbus-analyzer.pac +++ b/src/analyzer/protocol/modbus/modbus-analyzer.pac @@ -8,39 +8,39 @@ # %header{ - IntrusivePtr bytestring_to_coils(const bytestring& coils, uint quantity); - IntrusivePtr HeaderToVal(ModbusTCP_TransportHeader* header); - IntrusivePtr create_vector_of_count(); + zeek::VectorValPtr bytestring_to_coils(const bytestring& coils, uint quantity); + zeek::RecordValPtr HeaderToVal(ModbusTCP_TransportHeader* header); + zeek::VectorValPtr create_vector_of_count(); %} %code{ - IntrusivePtr bytestring_to_coils(const bytestring& coils, uint quantity) + zeek::VectorValPtr bytestring_to_coils(const bytestring& coils, uint quantity) { - auto modbus_coils = make_intrusive(zeek::BifType::Vector::ModbusCoils); + auto modbus_coils = zeek::make_intrusive(zeek::BifType::Vector::ModbusCoils); for ( uint i = 0; i < quantity; i++ ) { char currentCoil = (coils[i/8] >> (i % 8)) % 2; - modbus_coils->Assign(i, val_mgr->Bool(currentCoil)); + modbus_coils->Assign(i, zeek::val_mgr->Bool(currentCoil)); } return modbus_coils; } - IntrusivePtr HeaderToVal(ModbusTCP_TransportHeader* header) + zeek::RecordValPtr HeaderToVal(ModbusTCP_TransportHeader* header) { - auto modbus_header = make_intrusive(zeek::BifType::Record::ModbusHeaders); - modbus_header->Assign(0, val_mgr->Count(header->tid())); - modbus_header->Assign(1, val_mgr->Count(header->pid())); - modbus_header->Assign(2, val_mgr->Count(header->uid())); - modbus_header->Assign(3, val_mgr->Count(header->fc())); + auto modbus_header = zeek::make_intrusive(zeek::BifType::Record::ModbusHeaders); + modbus_header->Assign(0, zeek::val_mgr->Count(header->tid())); + modbus_header->Assign(1, zeek::val_mgr->Count(header->pid())); + modbus_header->Assign(2, zeek::val_mgr->Count(header->uid())); + modbus_header->Assign(3, zeek::val_mgr->Count(header->fc())); return modbus_header; } - IntrusivePtr create_vector_of_count() + zeek::VectorValPtr create_vector_of_count() { - auto vt = make_intrusive(zeek::base_type(zeek::TYPE_COUNT)); - auto vv = make_intrusive(std::move(vt)); + auto vt = zeek::make_intrusive(zeek::base_type(zeek::TYPE_COUNT)); + auto vv = zeek::make_intrusive(std::move(vt)); return vv; } @@ -209,11 +209,11 @@ refine flow ModbusTCP_Flow += { if ( ::modbus_read_holding_registers_response ) { - auto t = make_intrusive(zeek::BifType::Vector::ModbusRegisters); + auto t = zeek::make_intrusive(zeek::BifType::Vector::ModbusRegisters); for ( unsigned int i=0; i < ${message.registers}->size(); ++i ) { - auto r = val_mgr->Count(${message.registers[i]}); + auto r = zeek::val_mgr->Count(${message.registers[i]}); t->Assign(i, r); } @@ -253,11 +253,11 @@ refine flow ModbusTCP_Flow += { if ( ::modbus_read_input_registers_response ) { - auto t = make_intrusive(zeek::BifType::Vector::ModbusRegisters); + auto t = zeek::make_intrusive(zeek::BifType::Vector::ModbusRegisters); for ( unsigned int i=0; i < (${message.registers})->size(); ++i ) { - auto r = val_mgr->Count(${message.registers[i]}); + auto r = zeek::val_mgr->Count(${message.registers[i]}); t->Assign(i, r); } @@ -397,11 +397,11 @@ refine flow ModbusTCP_Flow += { if ( ::modbus_write_multiple_registers_request ) { - auto t = make_intrusive(zeek::BifType::Vector::ModbusRegisters); + auto t = zeek::make_intrusive(zeek::BifType::Vector::ModbusRegisters); for ( unsigned int i = 0; i < (${message.registers}->size()); ++i ) { - auto r = val_mgr->Count(${message.registers[i]}); + auto r = zeek::val_mgr->Count(${message.registers[i]}); t->Assign(i, r); } @@ -437,13 +437,13 @@ refine flow ModbusTCP_Flow += { //auto t = create_vector_of_count(); //for ( unsigned int i = 0; i < (${message.references}->size()); ++i ) // { - // auto r = val_mgr->Count((${message.references[i].ref_type})); + // auto r = zeek::val_mgr->Count((${message.references[i].ref_type})); // t->Assign(i, r); // - // auto k = val_mgr->Count((${message.references[i].file_num})); + // auto k = zeek::val_mgr->Count((${message.references[i].file_num})); // t->Assign(i, k); // - // auto l = val_mgr->Count((${message.references[i].record_num})); + // auto l = zeek::val_mgr->Count((${message.references[i].record_num})); // t->Assign(i, l); // } @@ -464,7 +464,7 @@ refine flow ModbusTCP_Flow += { //for ( unsigned int i = 0; i < ${message.references}->size(); ++i ) // { // //TODO: work the reference type in here somewhere - // auto r = val_mgr->Count(${message.references[i].record_data})); + // auto r = zeek::val_mgr->Count(${message.references[i].record_data})); // t->Assign(i, r); // } @@ -484,18 +484,18 @@ refine flow ModbusTCP_Flow += { //auto t = create_vector_of_count(); //for ( unsigned int i = 0; i < (${message.references}->size()); ++i ) // { - // auto r = val_mgr->Count((${message.references[i].ref_type})); + // auto r = zeek::val_mgr->Count((${message.references[i].ref_type})); // t->Assign(i, r); // - // auto k = val_mgr->Count((${message.references[i].file_num})); + // auto k = zeek::val_mgr->Count((${message.references[i].file_num})); // t->Assign(i, k); // - // auto n = val_mgr->Count((${message.references[i].record_num})); + // auto n = zeek::val_mgr->Count((${message.references[i].record_num})); // t->Assign(i, n); // // for ( unsigned int j = 0; j < (${message.references[i].register_value}->size()); ++j ) // { - // k = val_mgr->Count((${message.references[i].register_value[j]})); + // k = zeek::val_mgr->Count((${message.references[i].register_value[j]})); // t->Assign(i, k); // } // } @@ -517,18 +517,18 @@ refine flow ModbusTCP_Flow += { //auto t = create_vector_of_count(); //for ( unsigned int i = 0; i < (${messages.references}->size()); ++i ) // { - // auto r = val_mgr->Count((${message.references[i].ref_type})); + // auto r = zeek::val_mgr->Count((${message.references[i].ref_type})); // t->Assign(i, r); // - // auto f = val_mgr->Count((${message.references[i].file_num})); + // auto f = zeek::val_mgr->Count((${message.references[i].file_num})); // t->Assign(i, f); // - // auto rn = val_mgr->Count((${message.references[i].record_num})); + // auto rn = zeek::val_mgr->Count((${message.references[i].record_num})); // t->Assign(i, rn); // // for ( unsigned int j = 0; j<(${message.references[i].register_value}->size()); ++j ) // { - // auto k = val_mgr->Count((${message.references[i].register_value[j]})); + // auto k = zeek::val_mgr->Count((${message.references[i].register_value[j]})); // t->Assign(i, k); // } @@ -582,11 +582,11 @@ refine flow ModbusTCP_Flow += { if ( ::modbus_read_write_multiple_registers_request ) { - auto t = make_intrusive(zeek::BifType::Vector::ModbusRegisters); + auto t = zeek::make_intrusive(zeek::BifType::Vector::ModbusRegisters); for ( unsigned int i = 0; i < ${message.write_register_values}->size(); ++i ) { - auto r = val_mgr->Count(${message.write_register_values[i]}); + auto r = zeek::val_mgr->Count(${message.write_register_values[i]}); t->Assign(i, r); } @@ -614,11 +614,11 @@ refine flow ModbusTCP_Flow += { if ( ::modbus_read_write_multiple_registers_response ) { - auto t = make_intrusive(zeek::BifType::Vector::ModbusRegisters); + auto t = zeek::make_intrusive(zeek::BifType::Vector::ModbusRegisters); for ( unsigned int i = 0; i < ${message.registers}->size(); ++i ) { - auto r = val_mgr->Count(${message.registers[i]}); + auto r = zeek::val_mgr->Count(${message.registers[i]}); t->Assign(i, r); } @@ -662,7 +662,7 @@ refine flow ModbusTCP_Flow += { for ( unsigned int i = 0; i < (${message.register_data})->size(); ++i ) { - auto r = val_mgr->Count(${message.register_data[i]}); + auto r = zeek::val_mgr->Count(${message.register_data[i]}); t->Assign(i, r); } diff --git a/src/analyzer/protocol/mqtt/commands/connack.pac b/src/analyzer/protocol/mqtt/commands/connack.pac index c2954efa8a..ae7619ba3b 100644 --- a/src/analyzer/protocol/mqtt/commands/connack.pac +++ b/src/analyzer/protocol/mqtt/commands/connack.pac @@ -15,9 +15,9 @@ refine flow MQTT_Flow += { %{ if ( mqtt_connack ) { - auto m = make_intrusive(zeek::BifType::Record::MQTT::ConnectAckMsg); - m->Assign(0, val_mgr->Count(${msg.return_code})); - m->Assign(1, val_mgr->Bool(${msg.session_present})); + auto m = zeek::make_intrusive(zeek::BifType::Record::MQTT::ConnectAckMsg); + m->Assign(0, zeek::val_mgr->Count(${msg.return_code})); + m->Assign(1, zeek::val_mgr->Bool(${msg.session_present})); zeek::BifEvent::enqueue_mqtt_connack(connection()->bro_analyzer(), connection()->bro_analyzer()->Conn(), std::move(m)); diff --git a/src/analyzer/protocol/mqtt/commands/connect.pac b/src/analyzer/protocol/mqtt/commands/connect.pac index 407313cc8a..84fddf0eb3 100644 --- a/src/analyzer/protocol/mqtt/commands/connect.pac +++ b/src/analyzer/protocol/mqtt/commands/connect.pac @@ -44,34 +44,34 @@ refine flow MQTT_Flow += { %{ if ( mqtt_connect ) { - auto m = make_intrusive(zeek::BifType::Record::MQTT::ConnectMsg); - m->Assign(0, make_intrusive(${msg.protocol_name.str}.length(), + auto m = zeek::make_intrusive(zeek::BifType::Record::MQTT::ConnectMsg); + m->Assign(0, zeek::make_intrusive(${msg.protocol_name.str}.length(), reinterpret_cast(${msg.protocol_name.str}.begin()))); - m->Assign(1, val_mgr->Count(${msg.protocol_version})); - m->Assign(2, make_intrusive(${msg.client_id.str}.length(), + m->Assign(1, zeek::val_mgr->Count(${msg.protocol_version})); + m->Assign(2, zeek::make_intrusive(${msg.client_id.str}.length(), reinterpret_cast(${msg.client_id.str}.begin()))); - m->Assign(3, make_intrusive(double(${msg.keep_alive}), Seconds)); + m->Assign(3, zeek::make_intrusive(double(${msg.keep_alive}), Seconds)); - m->Assign(4, val_mgr->Bool(${msg.clean_session})); - m->Assign(5, val_mgr->Bool(${msg.will_retain})); - m->Assign(6, val_mgr->Count(${msg.will_qos})); + m->Assign(4, zeek::val_mgr->Bool(${msg.clean_session})); + m->Assign(5, zeek::val_mgr->Bool(${msg.will_retain})); + m->Assign(6, zeek::val_mgr->Count(${msg.will_qos})); if ( ${msg.will_flag} ) { - m->Assign(7, make_intrusive(${msg.will.topic.str}.length(), + m->Assign(7, zeek::make_intrusive(${msg.will.topic.str}.length(), reinterpret_cast(${msg.will.topic.str}.begin()))); - m->Assign(8, make_intrusive(${msg.will.msg.str}.length(), + m->Assign(8, zeek::make_intrusive(${msg.will.msg.str}.length(), reinterpret_cast(${msg.will.msg.str}.begin()))); } if ( ${msg.username} ) { - m->Assign(9, make_intrusive(${msg.uname.str}.length(), + m->Assign(9, zeek::make_intrusive(${msg.uname.str}.length(), reinterpret_cast(${msg.uname.str}.begin()))); } if ( ${msg.password} ) { - m->Assign(10, make_intrusive(${msg.pass.str}.length(), + m->Assign(10, zeek::make_intrusive(${msg.pass.str}.length(), reinterpret_cast(${msg.pass.str}.begin()))); } diff --git a/src/analyzer/protocol/mqtt/commands/publish.pac b/src/analyzer/protocol/mqtt/commands/publish.pac index cd7ceef2b3..9ca39273c7 100644 --- a/src/analyzer/protocol/mqtt/commands/publish.pac +++ b/src/analyzer/protocol/mqtt/commands/publish.pac @@ -23,11 +23,11 @@ refine flow MQTT_Flow += { %{ if ( mqtt_publish ) { - auto m = make_intrusive(zeek::BifType::Record::MQTT::PublishMsg); - m->Assign(0, val_mgr->Bool(${msg.dup})); - m->Assign(1, val_mgr->Count(${msg.qos})); - m->Assign(2, val_mgr->Bool(${msg.retain})); - m->Assign(3, ${msg.topic.str}.length(), + auto m = zeek::make_intrusive(zeek::BifType::Record::MQTT::PublishMsg); + m->Assign(0, zeek::val_mgr->Bool(${msg.dup})); + m->Assign(1, zeek::val_mgr->Count(${msg.qos})); + m->Assign(2, zeek::val_mgr->Bool(${msg.retain})); + m->Assign(3, ${msg.topic.str}.length(), reinterpret_cast(${msg.topic.str}.begin())); auto len = ${msg.payload}.length(); @@ -37,10 +37,10 @@ refine flow MQTT_Flow += { if ( len > static_cast(max) ) len = max; - m->Assign(4, len, + m->Assign(4, len, reinterpret_cast(${msg.payload}.begin())); - m->Assign(5, val_mgr->Count(${msg.payload}.length())); + m->Assign(5, zeek::val_mgr->Count(${msg.payload}.length())); zeek::BifEvent::enqueue_mqtt_publish(connection()->bro_analyzer(), connection()->bro_analyzer()->Conn(), diff --git a/src/analyzer/protocol/mqtt/commands/subscribe.pac b/src/analyzer/protocol/mqtt/commands/subscribe.pac index 755101b41f..bf52a3f29d 100644 --- a/src/analyzer/protocol/mqtt/commands/subscribe.pac +++ b/src/analyzer/protocol/mqtt/commands/subscribe.pac @@ -19,14 +19,14 @@ refine flow MQTT_Flow += { %{ if ( mqtt_subscribe ) { - auto topics = make_intrusive(zeek::id::string_vec); - auto qos_levels = make_intrusive(zeek::id::index_vec); + auto topics = zeek::make_intrusive(zeek::id::string_vec); + auto qos_levels = zeek::make_intrusive(zeek::id::index_vec); for ( auto topic: *${msg.topics} ) { - auto subscribe_topic = make_intrusive(${topic.name.str}.length(), + auto subscribe_topic = zeek::make_intrusive(${topic.name.str}.length(), reinterpret_cast(${topic.name.str}.begin())); - auto qos = val_mgr->Count(${topic.requested_QoS}); + auto qos = zeek::val_mgr->Count(${topic.requested_QoS}); topics->Assign(topics->Size(), std::move(subscribe_topic)); qos_levels->Assign(qos_levels->Size(), std::move(qos)); } diff --git a/src/analyzer/protocol/mqtt/commands/unsubscribe.pac b/src/analyzer/protocol/mqtt/commands/unsubscribe.pac index 944e005c7b..f9363efebd 100644 --- a/src/analyzer/protocol/mqtt/commands/unsubscribe.pac +++ b/src/analyzer/protocol/mqtt/commands/unsubscribe.pac @@ -14,11 +14,11 @@ refine flow MQTT_Flow += { %{ if ( mqtt_unsubscribe ) { - auto topics = make_intrusive(zeek::id::string_vec); + auto topics = zeek::make_intrusive(zeek::id::string_vec); for ( auto topic: *${msg.topics} ) { - auto unsubscribe_topic = make_intrusive(${topic.str}.length(), + auto unsubscribe_topic = zeek::make_intrusive(${topic.str}.length(), reinterpret_cast(${topic.str}.begin())); topics->Assign(topics->Size(), std::move(unsubscribe_topic)); } diff --git a/src/analyzer/protocol/mysql/mysql-analyzer.pac b/src/analyzer/protocol/mysql/mysql-analyzer.pac index 8c94ecdec6..f019cbcf39 100644 --- a/src/analyzer/protocol/mysql/mysql-analyzer.pac +++ b/src/analyzer/protocol/mysql/mysql-analyzer.pac @@ -8,11 +8,11 @@ refine flow MySQL_Flow += { if ( ${msg.version} == 10 ) zeek::BifEvent::enqueue_mysql_server_version(connection()->bro_analyzer(), connection()->bro_analyzer()->Conn(), - make_intrusive(c_str(${msg.handshake10.server_version}))); + zeek::make_intrusive(c_str(${msg.handshake10.server_version}))); if ( ${msg.version} == 9 ) zeek::BifEvent::enqueue_mysql_server_version(connection()->bro_analyzer(), connection()->bro_analyzer()->Conn(), - make_intrusive(c_str(${msg.handshake9.server_version}))); + zeek::make_intrusive(c_str(${msg.handshake9.server_version}))); } return true; %} @@ -27,11 +27,11 @@ refine flow MySQL_Flow += { if ( ${msg.version} == 10 ) zeek::BifEvent::enqueue_mysql_handshake(connection()->bro_analyzer(), connection()->bro_analyzer()->Conn(), - make_intrusive(c_str(${msg.v10_response.username}))); + zeek::make_intrusive(c_str(${msg.v10_response.username}))); if ( ${msg.version} == 9 ) zeek::BifEvent::enqueue_mysql_handshake(connection()->bro_analyzer(), connection()->bro_analyzer()->Conn(), - make_intrusive(c_str(${msg.v9_response.username}))); + zeek::make_intrusive(c_str(${msg.v9_response.username}))); } return true; %} @@ -83,11 +83,11 @@ refine flow MySQL_Flow += { return true; auto vt = zeek::id::string_vec; - auto vv = make_intrusive(std::move(vt)); + auto vv = zeek::make_intrusive(std::move(vt)); auto& bstring = ${msg.row.first_field.val}; auto ptr = reinterpret_cast(bstring.data()); - vv->Assign(vv->Size(), make_intrusive(bstring.length(), ptr)); + vv->Assign(vv->Size(), zeek::make_intrusive(bstring.length(), ptr)); auto& fields = *${msg.row.fields}; @@ -95,7 +95,7 @@ refine flow MySQL_Flow += { { auto& bstring = f->val(); auto ptr = reinterpret_cast(bstring.data()); - vv->Assign(vv->Size(), make_intrusive(bstring.length(), ptr)); + vv->Assign(vv->Size(), zeek::make_intrusive(bstring.length(), ptr)); } zeek::BifEvent::enqueue_mysql_result_row(connection()->bro_analyzer(), diff --git a/src/analyzer/protocol/ncp/NCP.cc b/src/analyzer/protocol/ncp/NCP.cc index 180d1164c9..615503870a 100644 --- a/src/analyzer/protocol/ncp/NCP.cc +++ b/src/analyzer/protocol/ncp/NCP.cc @@ -64,18 +64,18 @@ void NCP_Session::DeliverFrame(const binpac::NCP::ncp_frame* frame) if ( frame->is_orig() ) analyzer->EnqueueConnEvent(f, analyzer->ConnVal(), - val_mgr->Count(frame->frame_type()), - val_mgr->Count(frame->body_length()), - val_mgr->Count(req_func) + zeek::val_mgr->Count(frame->frame_type()), + zeek::val_mgr->Count(frame->body_length()), + zeek::val_mgr->Count(req_func) ); else analyzer->EnqueueConnEvent(f, analyzer->ConnVal(), - val_mgr->Count(frame->frame_type()), - val_mgr->Count(frame->body_length()), - val_mgr->Count(req_frame_type), - val_mgr->Count(req_func), - val_mgr->Count(frame->reply()->completion_code()) + zeek::val_mgr->Count(frame->frame_type()), + zeek::val_mgr->Count(frame->body_length()), + zeek::val_mgr->Count(req_frame_type), + zeek::val_mgr->Count(req_func), + zeek::val_mgr->Count(frame->reply()->completion_code()) ); } } diff --git a/src/analyzer/protocol/netbios/NetbiosSSN.cc b/src/analyzer/protocol/netbios/NetbiosSSN.cc index 2fa240b752..08d4fdc8a2 100644 --- a/src/analyzer/protocol/netbios/NetbiosSSN.cc +++ b/src/analyzer/protocol/netbios/NetbiosSSN.cc @@ -5,7 +5,7 @@ #include -#include "BroString.h" +#include "ZeekString.h" #include "NetVar.h" #include "Sessions.h" #include "Event.h" @@ -61,9 +61,9 @@ void NetbiosSSN_Interpreter::ParseMessage(unsigned int type, unsigned int flags, if ( netbios_session_message ) analyzer->EnqueueConnEvent(netbios_session_message, analyzer->ConnVal(), - val_mgr->Bool(is_query), - val_mgr->Count(type), - val_mgr->Count(len) + zeek::val_mgr->Bool(is_query), + zeek::val_mgr->Count(type), + zeek::val_mgr->Count(len) ); switch ( type ) { @@ -125,11 +125,11 @@ void NetbiosSSN_Interpreter::ParseBroadcast(const u_char* data, int len, // FIND THE NUL-TERMINATED NAME STRINGS HERE! // Not sure what's in them, so we don't keep them currently. - BroString* srcname = new BroString((char*) data); + zeek::String* srcname = new zeek::String((char*) data); data += srcname->Len()+1; len -= srcname->Len(); - BroString* dstname = new BroString((char*) data); + zeek::String* dstname = new zeek::String((char*) data); data += dstname->Len()+1; len -= dstname->Len(); @@ -322,15 +322,13 @@ void NetbiosSSN_Interpreter::Event(EventHandlerPtr event, const u_char* data, if ( is_orig >= 0 ) analyzer->EnqueueConnEvent(event, - analyzer->ConnVal(), - val_mgr->Bool(is_orig), - make_intrusive(new BroString(data, len, false)) - ); + analyzer->ConnVal(), + zeek::val_mgr->Bool(is_orig), + zeek::make_intrusive(new zeek::String(data, len, false))); else analyzer->EnqueueConnEvent(event, - analyzer->ConnVal(), - make_intrusive(new BroString(data, len, false)) - ); + analyzer->ConnVal(), + zeek::make_intrusive(new zeek::String(data, len, false))); } diff --git a/src/analyzer/protocol/netbios/functions.bif b/src/analyzer/protocol/netbios/functions.bif index f4c145a9ae..255a007de5 100644 --- a/src/analyzer/protocol/netbios/functions.bif +++ b/src/analyzer/protocol/netbios/functions.bif @@ -34,7 +34,7 @@ function decode_netbios_name%(name: string%): string break; } - return make_intrusive(i, result); + return zeek::make_intrusive(i, result); %} ## Converts a NetBIOS name type to its corresponding numeric value. @@ -49,5 +49,5 @@ function decode_netbios_name_type%(name: string%): count %{ const u_char* s = name->Bytes(); char return_val = ((toupper(s[30]) - 'A') << 4) + (toupper(s[31]) - 'A'); - return val_mgr->Count(return_val); + return zeek::val_mgr->Count(return_val); %} diff --git a/src/analyzer/protocol/ntlm/ntlm-analyzer.pac b/src/analyzer/protocol/ntlm/ntlm-analyzer.pac index 7b4f38e288..8071fa1f5d 100644 --- a/src/analyzer/protocol/ntlm/ntlm-analyzer.pac +++ b/src/analyzer/protocol/ntlm/ntlm-analyzer.pac @@ -1,58 +1,58 @@ %header{ - IntrusivePtr filetime2brotime(uint64_t ts); - IntrusivePtr build_version_record(NTLM_Version* val); - IntrusivePtr build_negotiate_flag_record(NTLM_Negotiate_Flags* val); + zeek::ValPtr filetime2brotime(uint64_t ts); + zeek::RecordValPtr build_version_record(NTLM_Version* val); + zeek::RecordValPtr build_negotiate_flag_record(NTLM_Negotiate_Flags* val); %} %code{ // This is replicated from the SMB analyzer. :( - IntrusivePtr filetime2brotime(uint64_t ts) + zeek::ValPtr filetime2brotime(uint64_t ts) { double secs = (ts / 10000000.0); // Bro can't support times back to the 1600's // so we subtract a lot of seconds. - auto bro_ts = make_intrusive(secs - 11644473600.0); + auto bro_ts = zeek::make_intrusive(secs - 11644473600.0); return bro_ts; } - IntrusivePtr build_version_record(NTLM_Version* val) + zeek::RecordValPtr build_version_record(NTLM_Version* val) { - auto result = make_intrusive(zeek::BifType::Record::NTLM::Version); - result->Assign(0, val_mgr->Count(${val.major_version})); - result->Assign(1, val_mgr->Count(${val.minor_version})); - result->Assign(2, val_mgr->Count(${val.build_number})); - result->Assign(3, val_mgr->Count(${val.ntlm_revision})); + auto result = zeek::make_intrusive(zeek::BifType::Record::NTLM::Version); + result->Assign(0, zeek::val_mgr->Count(${val.major_version})); + result->Assign(1, zeek::val_mgr->Count(${val.minor_version})); + result->Assign(2, zeek::val_mgr->Count(${val.build_number})); + result->Assign(3, zeek::val_mgr->Count(${val.ntlm_revision})); return result; } - IntrusivePtr build_negotiate_flag_record(NTLM_Negotiate_Flags* val) + zeek::RecordValPtr build_negotiate_flag_record(NTLM_Negotiate_Flags* val) { - auto flags = make_intrusive(zeek::BifType::Record::NTLM::NegotiateFlags); - flags->Assign(0, val_mgr->Bool(${val.negotiate_56})); - flags->Assign(1, val_mgr->Bool(${val.negotiate_key_exch})); - flags->Assign(2, val_mgr->Bool(${val.negotiate_128})); - flags->Assign(3, val_mgr->Bool(${val.negotiate_version})); - flags->Assign(4, val_mgr->Bool(${val.negotiate_target_info})); - flags->Assign(5, val_mgr->Bool(${val.request_non_nt_session_key})); - flags->Assign(6, val_mgr->Bool(${val.negotiate_identify})); - flags->Assign(7, val_mgr->Bool(${val.negotiate_extended_sessionsecurity})); - flags->Assign(8, val_mgr->Bool(${val.target_type_server})); - flags->Assign(9, val_mgr->Bool(${val.target_type_domain})); - flags->Assign(10, val_mgr->Bool(${val.negotiate_always_sign})); - flags->Assign(11, val_mgr->Bool(${val.negotiate_oem_workstation_supplied})); - flags->Assign(12, val_mgr->Bool(${val.negotiate_oem_domain_supplied})); - flags->Assign(13, val_mgr->Bool(${val.negotiate_anonymous_connection})); - flags->Assign(14, val_mgr->Bool(${val.negotiate_ntlm})); - flags->Assign(15, val_mgr->Bool(${val.negotiate_lm_key})); - flags->Assign(16, val_mgr->Bool(${val.negotiate_datagram})); - flags->Assign(17, val_mgr->Bool(${val.negotiate_seal})); - flags->Assign(18, val_mgr->Bool(${val.negotiate_sign})); - flags->Assign(19, val_mgr->Bool(${val.request_target})); - flags->Assign(20, val_mgr->Bool(${val.negotiate_oem})); - flags->Assign(21, val_mgr->Bool(${val.negotiate_unicode})); + auto flags = zeek::make_intrusive(zeek::BifType::Record::NTLM::NegotiateFlags); + flags->Assign(0, zeek::val_mgr->Bool(${val.negotiate_56})); + flags->Assign(1, zeek::val_mgr->Bool(${val.negotiate_key_exch})); + flags->Assign(2, zeek::val_mgr->Bool(${val.negotiate_128})); + flags->Assign(3, zeek::val_mgr->Bool(${val.negotiate_version})); + flags->Assign(4, zeek::val_mgr->Bool(${val.negotiate_target_info})); + flags->Assign(5, zeek::val_mgr->Bool(${val.request_non_nt_session_key})); + flags->Assign(6, zeek::val_mgr->Bool(${val.negotiate_identify})); + flags->Assign(7, zeek::val_mgr->Bool(${val.negotiate_extended_sessionsecurity})); + flags->Assign(8, zeek::val_mgr->Bool(${val.target_type_server})); + flags->Assign(9, zeek::val_mgr->Bool(${val.target_type_domain})); + flags->Assign(10, zeek::val_mgr->Bool(${val.negotiate_always_sign})); + flags->Assign(11, zeek::val_mgr->Bool(${val.negotiate_oem_workstation_supplied})); + flags->Assign(12, zeek::val_mgr->Bool(${val.negotiate_oem_domain_supplied})); + flags->Assign(13, zeek::val_mgr->Bool(${val.negotiate_anonymous_connection})); + flags->Assign(14, zeek::val_mgr->Bool(${val.negotiate_ntlm})); + flags->Assign(15, zeek::val_mgr->Bool(${val.negotiate_lm_key})); + flags->Assign(16, zeek::val_mgr->Bool(${val.negotiate_datagram})); + flags->Assign(17, zeek::val_mgr->Bool(${val.negotiate_seal})); + flags->Assign(18, zeek::val_mgr->Bool(${val.negotiate_sign})); + flags->Assign(19, zeek::val_mgr->Bool(${val.request_target})); + flags->Assign(20, zeek::val_mgr->Bool(${val.negotiate_oem})); + flags->Assign(21, zeek::val_mgr->Bool(${val.negotiate_unicode})); return flags; } @@ -62,7 +62,7 @@ refine connection NTLM_Conn += { function build_av_record(val: NTLM_AV_Pair_Sequence, len: uint16): BroVal %{ - RecordVal* result = new RecordVal(zeek::BifType::Record::NTLM::AVs); + zeek::RecordVal* result = new zeek::RecordVal(zeek::BifType::Record::NTLM::AVs); for ( uint i = 0; ; i++ ) { if ( i >= ${val.pairs}->size() ) @@ -96,13 +96,13 @@ refine connection NTLM_Conn += { result->Assign(4, utf16_to_utf8_val(bro_analyzer()->Conn(), ${val.pairs[i].dns_tree_name.data})); break; case 6: - result->Assign(5, val_mgr->Bool(${val.pairs[i].constrained_auth})); + result->Assign(5, zeek::val_mgr->Bool(${val.pairs[i].constrained_auth})); break; case 7: result->Assign(6, filetime2brotime(${val.pairs[i].timestamp})); break; case 8: - result->Assign(7, val_mgr->Count(${val.pairs[i].single_host.machine_id})); + result->Assign(7, zeek::val_mgr->Count(${val.pairs[i].single_host.machine_id})); break; case 9: result->Assign(8, utf16_to_utf8_val(bro_analyzer()->Conn(), ${val.pairs[i].target_name.data})); @@ -117,7 +117,7 @@ refine connection NTLM_Conn += { if ( ! ntlm_negotiate ) return true; - auto result = make_intrusive(zeek::BifType::Record::NTLM::Negotiate); + auto result = zeek::make_intrusive(zeek::BifType::Record::NTLM::Negotiate); result->Assign(0, build_negotiate_flag_record(${val.flags})); if ( ${val}->has_domain_name() ) @@ -141,7 +141,7 @@ refine connection NTLM_Conn += { if ( ! ntlm_challenge ) return true; - auto result = make_intrusive(zeek::BifType::Record::NTLM::Challenge); + auto result = zeek::make_intrusive(zeek::BifType::Record::NTLM::Challenge); result->Assign(0, build_negotiate_flag_record(${val.flags})); if ( ${val}->has_target_name() ) @@ -151,7 +151,7 @@ refine connection NTLM_Conn += { result->Assign(2, build_version_record(${val.version})); if ( ${val}->has_target_info() ) - result->Assign(3, {AdoptRef{}, build_av_record(${val.target_info}, ${val.target_info_fields.length})}); + result->Assign(3, {zeek::AdoptRef{}, build_av_record(${val.target_info}, ${val.target_info_fields.length})}); zeek::BifEvent::enqueue_ntlm_challenge(bro_analyzer(), bro_analyzer()->Conn(), @@ -165,7 +165,7 @@ refine connection NTLM_Conn += { if ( ! ntlm_authenticate ) return true; - auto result = make_intrusive(zeek::BifType::Record::NTLM::Authenticate); + auto result = zeek::make_intrusive(zeek::BifType::Record::NTLM::Authenticate); result->Assign(0, build_negotiate_flag_record(${val.flags})); if ( ${val}->has_domain_name() > 0 ) diff --git a/src/analyzer/protocol/ntp/ntp-analyzer.pac b/src/analyzer/protocol/ntp/ntp-analyzer.pac index 1e08505da4..f7a3b2dc90 100644 --- a/src/analyzer/protocol/ntp/ntp-analyzer.pac +++ b/src/analyzer/protocol/ntp/ntp-analyzer.pac @@ -8,37 +8,37 @@ %} %header{ - IntrusivePtr proc_ntp_short(const NTP_Short_Time* t); - IntrusivePtr proc_ntp_timestamp(const NTP_Time* t); - IntrusivePtr BuildNTPStdMsg(NTP_std_msg* nsm); - IntrusivePtr BuildNTPControlMsg(NTP_control_msg* ncm); - IntrusivePtr BuildNTPMode7Msg(NTP_mode7_msg* m7); + zeek::ValPtr proc_ntp_short(const NTP_Short_Time* t); + zeek::ValPtr proc_ntp_timestamp(const NTP_Time* t); + zeek::RecordValPtr BuildNTPStdMsg(NTP_std_msg* nsm); + zeek::RecordValPtr BuildNTPControlMsg(NTP_control_msg* ncm); + zeek::RecordValPtr BuildNTPMode7Msg(NTP_mode7_msg* m7); %} %code{ - IntrusivePtr proc_ntp_short(const NTP_Short_Time* t) + zeek::ValPtr proc_ntp_short(const NTP_Short_Time* t) { if ( t->seconds() == 0 && t->fractions() == 0 ) - return make_intrusive(0.0); - return make_intrusive(t->seconds() + t->fractions()*FRAC_16); + return zeek::make_intrusive(0.0); + return zeek::make_intrusive(t->seconds() + t->fractions()*FRAC_16); } - IntrusivePtr proc_ntp_timestamp(const NTP_Time* t) + zeek::ValPtr proc_ntp_timestamp(const NTP_Time* t) { if ( t->seconds() == 0 && t->fractions() == 0) - return make_intrusive(0.0); - return make_intrusive(EPOCH_OFFSET + t->seconds() + t->fractions()*FRAC_32); + return zeek::make_intrusive(0.0); + return zeek::make_intrusive(EPOCH_OFFSET + t->seconds() + t->fractions()*FRAC_32); } // This builds the standard msg record - IntrusivePtr BuildNTPStdMsg(NTP_std_msg* nsm) + zeek::RecordValPtr BuildNTPStdMsg(NTP_std_msg* nsm) { - auto rv = make_intrusive(zeek::BifType::Record::NTP::StandardMessage); + auto rv = zeek::make_intrusive(zeek::BifType::Record::NTP::StandardMessage); - rv->Assign(0, val_mgr->Count(${nsm.stratum})); - rv->Assign(1, make_intrusive(pow(2, ${nsm.poll}))); - rv->Assign(2, make_intrusive(pow(2, ${nsm.precision}))); + rv->Assign(0, zeek::val_mgr->Count(${nsm.stratum})); + rv->Assign(1, zeek::make_intrusive(pow(2, ${nsm.poll}))); + rv->Assign(2, zeek::make_intrusive(pow(2, ${nsm.precision}))); rv->Assign(3, proc_ntp_short(${nsm.root_delay})); rv->Assign(4, proc_ntp_short(${nsm.root_dispersion})); @@ -54,7 +54,7 @@ default: { const uint8* d = ${nsm.reference_id}.data(); - rv->Assign(7, make_intrusive(IPAddr(IPv4, (const uint32*) d, IPAddr::Network))); + rv->Assign(7, zeek::make_intrusive(IPAddr(IPv4, (const uint32*) d, IPAddr::Network))); } break; } @@ -66,43 +66,43 @@ if ( ${nsm.mac_len} == 20 ) { - rv->Assign(12, val_mgr->Count(${nsm.mac.key_id})); + rv->Assign(12, zeek::val_mgr->Count(${nsm.mac.key_id})); rv->Assign(13, to_stringval(${nsm.mac.digest})); } else if ( ${nsm.mac_len} == 24 ) { - rv->Assign(12, val_mgr->Count(${nsm.mac_ext.key_id})); + rv->Assign(12, zeek::val_mgr->Count(${nsm.mac_ext.key_id})); rv->Assign(13, to_stringval(${nsm.mac_ext.digest})); } if ( ${nsm.has_exts} ) { // TODO: add extension fields - rv->Assign(14, val_mgr->Count((uint32) ${nsm.exts}->size())); + rv->Assign(14, zeek::val_mgr->Count((uint32) ${nsm.exts}->size())); } return rv; } // This builds the control msg record - IntrusivePtr BuildNTPControlMsg(NTP_control_msg* ncm) + zeek::RecordValPtr BuildNTPControlMsg(NTP_control_msg* ncm) { - auto rv = make_intrusive(zeek::BifType::Record::NTP::ControlMessage); + auto rv = zeek::make_intrusive(zeek::BifType::Record::NTP::ControlMessage); - rv->Assign(0, val_mgr->Count(${ncm.OpCode})); - rv->Assign(1, val_mgr->Bool(${ncm.R})); - rv->Assign(2, val_mgr->Bool(${ncm.E})); - rv->Assign(3, val_mgr->Bool(${ncm.M})); - rv->Assign(4, val_mgr->Count(${ncm.sequence})); - rv->Assign(5, val_mgr->Count(${ncm.status})); - rv->Assign(6, val_mgr->Count(${ncm.association_id})); + rv->Assign(0, zeek::val_mgr->Count(${ncm.OpCode})); + rv->Assign(1, zeek::val_mgr->Bool(${ncm.R})); + rv->Assign(2, zeek::val_mgr->Bool(${ncm.E})); + rv->Assign(3, zeek::val_mgr->Bool(${ncm.M})); + rv->Assign(4, zeek::val_mgr->Count(${ncm.sequence})); + rv->Assign(5, zeek::val_mgr->Count(${ncm.status})); + rv->Assign(6, zeek::val_mgr->Count(${ncm.association_id})); if ( ${ncm.c} > 0 ) rv->Assign(7, to_stringval(${ncm.data})); if ( ${ncm.has_control_mac} ) { - rv->Assign(8, val_mgr->Count(${ncm.mac.key_id})); + rv->Assign(8, zeek::val_mgr->Count(${ncm.mac.key_id})); rv->Assign(9, to_stringval(${ncm.mac.crypto_checksum})); } @@ -110,15 +110,15 @@ } // This builds the mode7 msg record - IntrusivePtr BuildNTPMode7Msg(NTP_mode7_msg* m7) + zeek::RecordValPtr BuildNTPMode7Msg(NTP_mode7_msg* m7) { - auto rv = make_intrusive(zeek::BifType::Record::NTP::Mode7Message); + auto rv = zeek::make_intrusive(zeek::BifType::Record::NTP::Mode7Message); - rv->Assign(0, val_mgr->Count(${m7.request_code})); - rv->Assign(1, val_mgr->Bool(${m7.auth_bit})); - rv->Assign(2, val_mgr->Count(${m7.sequence})); - rv->Assign(3, val_mgr->Count(${m7.implementation})); - rv->Assign(4, val_mgr->Count(${m7.error_code})); + rv->Assign(0, zeek::val_mgr->Count(${m7.request_code})); + rv->Assign(1, zeek::val_mgr->Bool(${m7.auth_bit})); + rv->Assign(2, zeek::val_mgr->Count(${m7.sequence})); + rv->Assign(3, zeek::val_mgr->Count(${m7.implementation})); + rv->Assign(4, zeek::val_mgr->Count(${m7.error_code})); if ( ${m7.data_len} > 0 ) rv->Assign(5, to_stringval(${m7.data})); @@ -138,9 +138,9 @@ refine flow NTP_Flow += { if ( ! ntp_message ) return false; - auto rv = make_intrusive(zeek::BifType::Record::NTP::Message); - rv->Assign(0, val_mgr->Count(${msg.version})); - rv->Assign(1, val_mgr->Count(${msg.mode})); + auto rv = zeek::make_intrusive(zeek::BifType::Record::NTP::Message); + rv->Assign(0, zeek::val_mgr->Count(${msg.version})); + rv->Assign(1, zeek::val_mgr->Count(${msg.mode})); // The standard record if ( ${msg.mode} >=1 && ${msg.mode} <= 5 ) diff --git a/src/analyzer/protocol/pop3/POP3.cc b/src/analyzer/protocol/pop3/POP3.cc index b73c2532ad..c1e6c0f690 100644 --- a/src/analyzer/protocol/pop3/POP3.cc +++ b/src/analyzer/protocol/pop3/POP3.cc @@ -78,7 +78,7 @@ void POP3_Analyzer::DeliverStream(int len, const u_char* data, bool orig) if ( (TCP() && TCP()->IsPartial()) ) return; - BroString terminated_string(data, len, true); + zeek::String terminated_string(data, len, true); if ( orig ) ProcessRequest(len, (char*) terminated_string.Bytes()); @@ -135,8 +135,8 @@ void POP3_Analyzer::ProcessRequest(int length, const char* line) { ++authLines; - BroString encoded(line); - BroString* decoded = decode_base64(&encoded, nullptr, Conn()); + zeek::String encoded(line); + zeek::String* decoded = decode_base64(&encoded, nullptr, Conn()); if ( ! decoded ) { @@ -920,12 +920,12 @@ void POP3_Analyzer::POP3Event(EventHandlerPtr event, bool is_orig, vl.reserve(2 + (bool)arg1 + (bool)arg2); vl.emplace_back(ConnVal()); - vl.emplace_back(val_mgr->Bool(is_orig)); + vl.emplace_back(zeek::val_mgr->Bool(is_orig)); if ( arg1 ) - vl.emplace_back(make_intrusive(arg1)); + vl.emplace_back(zeek::make_intrusive(arg1)); if ( arg2 ) - vl.emplace_back(make_intrusive(arg2)); + vl.emplace_back(zeek::make_intrusive(arg2)); EnqueueConnEvent(event, std::move(vl)); } diff --git a/src/analyzer/protocol/radius/radius-analyzer.pac b/src/analyzer/protocol/radius/radius-analyzer.pac index 02c500e676..e47f2748d6 100644 --- a/src/analyzer/protocol/radius/radius-analyzer.pac +++ b/src/analyzer/protocol/radius/radius-analyzer.pac @@ -7,32 +7,32 @@ refine flow RADIUS_Flow += { if ( ! radius_message ) return false; - auto result = make_intrusive(zeek::BifType::Record::RADIUS::Message); - result->Assign(0, val_mgr->Count(${msg.code})); - result->Assign(1, val_mgr->Count(${msg.trans_id})); + auto result = zeek::make_intrusive(zeek::BifType::Record::RADIUS::Message); + result->Assign(0, zeek::val_mgr->Count(${msg.code})); + result->Assign(1, zeek::val_mgr->Count(${msg.trans_id})); result->Assign(2, to_stringval(${msg.authenticator})); if ( ${msg.attributes}->size() ) { - auto attributes = make_intrusive(zeek::BifType::Table::RADIUS::Attributes); + auto attributes = zeek::make_intrusive(zeek::BifType::Table::RADIUS::Attributes); for ( uint i = 0; i < ${msg.attributes}->size(); ++i ) { - auto index = val_mgr->Count(${msg.attributes[i].code}); + auto index = zeek::val_mgr->Count(${msg.attributes[i].code}); // Do we already have a vector of attributes for this type? auto current = attributes->FindOrDefault(index); - IntrusivePtr val = to_stringval(${msg.attributes[i].value}); + zeek::ValPtr val = to_stringval(${msg.attributes[i].value}); if ( current ) { - VectorVal* vcurrent = current->AsVectorVal(); + zeek::VectorVal* vcurrent = current->AsVectorVal(); vcurrent->Assign(vcurrent->Size(), std::move(val)); } else { - auto attribute_list = make_intrusive(zeek::BifType::Vector::RADIUS::AttributeList); + auto attribute_list = zeek::make_intrusive(zeek::BifType::Vector::RADIUS::AttributeList); attribute_list->Assign((unsigned int)0, std::move(val)); attributes->Assign(std::move(index), std::move(attribute_list)); } diff --git a/src/analyzer/protocol/rdp/rdp-analyzer.pac b/src/analyzer/protocol/rdp/rdp-analyzer.pac index 4f1f9ef39a..db267cd66d 100644 --- a/src/analyzer/protocol/rdp/rdp-analyzer.pac +++ b/src/analyzer/protocol/rdp/rdp-analyzer.pac @@ -64,36 +64,36 @@ refine flow RDP_Flow += { if ( rdp_client_core_data ) { - auto ec_flags = make_intrusive(zeek::BifType::Record::RDP::EarlyCapabilityFlags); - ec_flags->Assign(0, val_mgr->Bool(${ccore.SUPPORT_ERRINFO_PDU})); - ec_flags->Assign(1, val_mgr->Bool(${ccore.WANT_32BPP_SESSION})); - ec_flags->Assign(2, val_mgr->Bool(${ccore.SUPPORT_STATUSINFO_PDU})); - ec_flags->Assign(3, val_mgr->Bool(${ccore.STRONG_ASYMMETRIC_KEYS})); - ec_flags->Assign(4, val_mgr->Bool(${ccore.SUPPORT_MONITOR_LAYOUT_PDU})); - ec_flags->Assign(5, val_mgr->Bool(${ccore.SUPPORT_NETCHAR_AUTODETECT})); - ec_flags->Assign(6, val_mgr->Bool(${ccore.SUPPORT_DYNVC_GFX_PROTOCOL})); - ec_flags->Assign(7, val_mgr->Bool(${ccore.SUPPORT_DYNAMIC_TIME_ZONE})); - ec_flags->Assign(8, val_mgr->Bool(${ccore.SUPPORT_HEARTBEAT_PDU})); + auto ec_flags = zeek::make_intrusive(zeek::BifType::Record::RDP::EarlyCapabilityFlags); + ec_flags->Assign(0, zeek::val_mgr->Bool(${ccore.SUPPORT_ERRINFO_PDU})); + ec_flags->Assign(1, zeek::val_mgr->Bool(${ccore.WANT_32BPP_SESSION})); + ec_flags->Assign(2, zeek::val_mgr->Bool(${ccore.SUPPORT_STATUSINFO_PDU})); + ec_flags->Assign(3, zeek::val_mgr->Bool(${ccore.STRONG_ASYMMETRIC_KEYS})); + ec_flags->Assign(4, zeek::val_mgr->Bool(${ccore.SUPPORT_MONITOR_LAYOUT_PDU})); + ec_flags->Assign(5, zeek::val_mgr->Bool(${ccore.SUPPORT_NETCHAR_AUTODETECT})); + ec_flags->Assign(6, zeek::val_mgr->Bool(${ccore.SUPPORT_DYNVC_GFX_PROTOCOL})); + ec_flags->Assign(7, zeek::val_mgr->Bool(${ccore.SUPPORT_DYNAMIC_TIME_ZONE})); + ec_flags->Assign(8, zeek::val_mgr->Bool(${ccore.SUPPORT_HEARTBEAT_PDU})); - auto ccd = make_intrusive(zeek::BifType::Record::RDP::ClientCoreData); - ccd->Assign(0, val_mgr->Count(${ccore.version_major})); - ccd->Assign(1, val_mgr->Count(${ccore.version_minor})); - ccd->Assign(2, val_mgr->Count(${ccore.desktop_width})); - ccd->Assign(3, val_mgr->Count(${ccore.desktop_height})); - ccd->Assign(4, val_mgr->Count(${ccore.color_depth})); - ccd->Assign(5, val_mgr->Count(${ccore.sas_sequence})); - ccd->Assign(6, val_mgr->Count(${ccore.keyboard_layout})); - ccd->Assign(7, val_mgr->Count(${ccore.client_build})); + auto ccd = zeek::make_intrusive(zeek::BifType::Record::RDP::ClientCoreData); + ccd->Assign(0, zeek::val_mgr->Count(${ccore.version_major})); + ccd->Assign(1, zeek::val_mgr->Count(${ccore.version_minor})); + ccd->Assign(2, zeek::val_mgr->Count(${ccore.desktop_width})); + ccd->Assign(3, zeek::val_mgr->Count(${ccore.desktop_height})); + ccd->Assign(4, zeek::val_mgr->Count(${ccore.color_depth})); + ccd->Assign(5, zeek::val_mgr->Count(${ccore.sas_sequence})); + ccd->Assign(6, zeek::val_mgr->Count(${ccore.keyboard_layout})); + ccd->Assign(7, zeek::val_mgr->Count(${ccore.client_build})); ccd->Assign(8, utf16_to_utf8_val(connection()->bro_analyzer()->Conn(), ${ccore.client_name})); - ccd->Assign(9, val_mgr->Count(${ccore.keyboard_type})); - ccd->Assign(10, val_mgr->Count(${ccore.keyboard_sub})); - ccd->Assign(11, val_mgr->Count(${ccore.keyboard_function_key})); + ccd->Assign(9, zeek::val_mgr->Count(${ccore.keyboard_type})); + ccd->Assign(10, zeek::val_mgr->Count(${ccore.keyboard_sub})); + ccd->Assign(11, zeek::val_mgr->Count(${ccore.keyboard_function_key})); ccd->Assign(12, utf16_to_utf8_val(connection()->bro_analyzer()->Conn(), ${ccore.ime_file_name})); - ccd->Assign(13, val_mgr->Count(${ccore.post_beta2_color_depth})); - ccd->Assign(14, val_mgr->Count(${ccore.client_product_id})); - ccd->Assign(15, val_mgr->Count(${ccore.serial_number})); - ccd->Assign(16, val_mgr->Count(${ccore.high_color_depth})); - ccd->Assign(17, val_mgr->Count(${ccore.supported_color_depths})); + ccd->Assign(13, zeek::val_mgr->Count(${ccore.post_beta2_color_depth})); + ccd->Assign(14, zeek::val_mgr->Count(${ccore.client_product_id})); + ccd->Assign(15, zeek::val_mgr->Count(${ccore.serial_number})); + ccd->Assign(16, zeek::val_mgr->Count(${ccore.high_color_depth})); + ccd->Assign(17, zeek::val_mgr->Count(${ccore.supported_color_depths})); ccd->Assign(18, std::move(ec_flags)); ccd->Assign(19, utf16_to_utf8_val(connection()->bro_analyzer()->Conn(), ${ccore.dig_product_id})); @@ -110,9 +110,9 @@ refine flow RDP_Flow += { if ( ! rdp_client_security_data ) return false; - auto csd = make_intrusive(zeek::BifType::Record::RDP::ClientSecurityData); - csd->Assign(0, val_mgr->Count(${csec.encryption_methods})); - csd->Assign(1, val_mgr->Count(${csec.ext_encryption_methods})); + auto csd = zeek::make_intrusive(zeek::BifType::Record::RDP::ClientSecurityData); + csd->Assign(0, zeek::val_mgr->Count(${csec.encryption_methods})); + csd->Assign(1, zeek::val_mgr->Count(${csec.ext_encryption_methods})); zeek::BifEvent::enqueue_rdp_client_security_data(connection()->bro_analyzer(), connection()->bro_analyzer()->Conn(), @@ -127,26 +127,26 @@ refine flow RDP_Flow += { if ( ${cnetwork.channel_def_array}->size() ) { - auto channels = make_intrusive(zeek::BifType::Vector::RDP::ClientChannelList); + auto channels = zeek::make_intrusive(zeek::BifType::Vector::RDP::ClientChannelList); for ( uint i = 0; i < ${cnetwork.channel_def_array}->size(); ++i ) { - auto channel_def = make_intrusive(zeek::BifType::Record::RDP::ClientChannelDef); + auto channel_def = zeek::make_intrusive(zeek::BifType::Record::RDP::ClientChannelDef); channel_def->Assign(0, to_stringval(${cnetwork.channel_def_array[i].name})); - channel_def->Assign(1, val_mgr->Count(${cnetwork.channel_def_array[i].options})); + channel_def->Assign(1, zeek::val_mgr->Count(${cnetwork.channel_def_array[i].options})); - channel_def->Assign(2, val_mgr->Bool(${cnetwork.channel_def_array[i].CHANNEL_OPTION_INITIALIZED})); - channel_def->Assign(3, val_mgr->Bool(${cnetwork.channel_def_array[i].CHANNEL_OPTION_ENCRYPT_RDP})); - channel_def->Assign(4, val_mgr->Bool(${cnetwork.channel_def_array[i].CHANNEL_OPTION_ENCRYPT_SC})); - channel_def->Assign(5, val_mgr->Bool(${cnetwork.channel_def_array[i].CHANNEL_OPTION_ENCRYPT_CS})); - channel_def->Assign(6, val_mgr->Bool(${cnetwork.channel_def_array[i].CHANNEL_OPTION_PRI_HIGH})); - channel_def->Assign(7, val_mgr->Bool(${cnetwork.channel_def_array[i].CHANNEL_OPTION_PRI_MED})); - channel_def->Assign(8, val_mgr->Bool(${cnetwork.channel_def_array[i].CHANNEL_OPTION_PRI_LOW})); - channel_def->Assign(9, val_mgr->Bool(${cnetwork.channel_def_array[i].CHANNEL_OPTION_COMPRESS_RDP})); - channel_def->Assign(10, val_mgr->Bool(${cnetwork.channel_def_array[i].CHANNEL_OPTION_COMPRESS})); - channel_def->Assign(11, val_mgr->Bool(${cnetwork.channel_def_array[i].CHANNEL_OPTION_SHOW_PROTOCOL})); - channel_def->Assign(12, val_mgr->Bool(${cnetwork.channel_def_array[i].REMOTE_CONTROL_PERSISTENT})); + channel_def->Assign(2, zeek::val_mgr->Bool(${cnetwork.channel_def_array[i].CHANNEL_OPTION_INITIALIZED})); + channel_def->Assign(3, zeek::val_mgr->Bool(${cnetwork.channel_def_array[i].CHANNEL_OPTION_ENCRYPT_RDP})); + channel_def->Assign(4, zeek::val_mgr->Bool(${cnetwork.channel_def_array[i].CHANNEL_OPTION_ENCRYPT_SC})); + channel_def->Assign(5, zeek::val_mgr->Bool(${cnetwork.channel_def_array[i].CHANNEL_OPTION_ENCRYPT_CS})); + channel_def->Assign(6, zeek::val_mgr->Bool(${cnetwork.channel_def_array[i].CHANNEL_OPTION_PRI_HIGH})); + channel_def->Assign(7, zeek::val_mgr->Bool(${cnetwork.channel_def_array[i].CHANNEL_OPTION_PRI_MED})); + channel_def->Assign(8, zeek::val_mgr->Bool(${cnetwork.channel_def_array[i].CHANNEL_OPTION_PRI_LOW})); + channel_def->Assign(9, zeek::val_mgr->Bool(${cnetwork.channel_def_array[i].CHANNEL_OPTION_COMPRESS_RDP})); + channel_def->Assign(10, zeek::val_mgr->Bool(${cnetwork.channel_def_array[i].CHANNEL_OPTION_COMPRESS})); + channel_def->Assign(11, zeek::val_mgr->Bool(${cnetwork.channel_def_array[i].CHANNEL_OPTION_SHOW_PROTOCOL})); + channel_def->Assign(12, zeek::val_mgr->Bool(${cnetwork.channel_def_array[i].REMOTE_CONTROL_PERSISTENT})); channels->Assign(channels->Size(), std::move(channel_def)); } @@ -164,13 +164,13 @@ refine flow RDP_Flow += { if ( ! rdp_client_cluster_data ) return false; - auto ccld = make_intrusive(zeek::BifType::Record::RDP::ClientClusterData); - ccld->Assign(0, val_mgr->Count(${ccluster.flags})); - ccld->Assign(1, val_mgr->Count(${ccluster.redir_session_id})); - ccld->Assign(2, val_mgr->Bool(${ccluster.REDIRECTION_SUPPORTED})); - ccld->Assign(3, val_mgr->Count(${ccluster.SERVER_SESSION_REDIRECTION_VERSION_MASK})); - ccld->Assign(4, val_mgr->Bool(${ccluster.REDIRECTED_SESSIONID_FIELD_VALID})); - ccld->Assign(5, val_mgr->Bool(${ccluster.REDIRECTED_SMARTCARD})); + auto ccld = zeek::make_intrusive(zeek::BifType::Record::RDP::ClientClusterData); + ccld->Assign(0, zeek::val_mgr->Count(${ccluster.flags})); + ccld->Assign(1, zeek::val_mgr->Count(${ccluster.redir_session_id})); + ccld->Assign(2, zeek::val_mgr->Bool(${ccluster.REDIRECTION_SUPPORTED})); + ccld->Assign(3, zeek::val_mgr->Count(${ccluster.SERVER_SESSION_REDIRECTION_VERSION_MASK})); + ccld->Assign(4, zeek::val_mgr->Bool(${ccluster.REDIRECTED_SESSIONID_FIELD_VALID})); + ccld->Assign(5, zeek::val_mgr->Bool(${ccluster.REDIRECTED_SMARTCARD})); zeek::BifEvent::enqueue_rdp_client_cluster_data(connection()->bro_analyzer(), connection()->bro_analyzer()->Conn(), @@ -269,4 +269,3 @@ refine typeattr Server_Certificate += &let { refine typeattr X509_Cert_Data += &let { proc: bool = $context.flow.proc_x509_cert_data(this); }; - diff --git a/src/analyzer/protocol/rfb/rfb-analyzer.pac b/src/analyzer/protocol/rfb/rfb-analyzer.pac index b3e99e1af2..36bf163ce4 100644 --- a/src/analyzer/protocol/rfb/rfb-analyzer.pac +++ b/src/analyzer/protocol/rfb/rfb-analyzer.pac @@ -52,7 +52,7 @@ refine flow RFB_Flow += { auto name_ptr = &((*vec_ptr)[0]); zeek::BifEvent::enqueue_rfb_server_parameters( connection()->bro_analyzer(), connection()->bro_analyzer()->Conn(), - make_intrusive(${msg.name}->size(), (const char*)name_ptr), + zeek::make_intrusive(${msg.name}->size(), (const char*)name_ptr), ${msg.width}, ${msg.height}); } diff --git a/src/analyzer/protocol/rpc/MOUNT.cc b/src/analyzer/protocol/rpc/MOUNT.cc index 2e9d2d46bd..9bab07d5bf 100644 --- a/src/analyzer/protocol/rpc/MOUNT.cc +++ b/src/analyzer/protocol/rpc/MOUNT.cc @@ -6,7 +6,7 @@ #include #include -#include "BroString.h" +#include "ZeekString.h" #include "NetVar.h" #include "XDR.h" #include "Event.h" @@ -22,7 +22,7 @@ bool MOUNT_Interp::RPC_BuildCall(RPC_CallInfo* c, const u_char*& buf, int& n) uint32_t proc = c->Proc(); // The call arguments, depends on the call type obviously ... - IntrusivePtr callarg; + zeek::RecordValPtr callarg; switch ( proc ) { case BifEnum::MOUNT3::PROC_NULL: @@ -69,7 +69,7 @@ bool MOUNT_Interp::RPC_BuildReply(RPC_CallInfo* c, BifEnum::rpc_status rpc_statu double last_time, int reply_len) { EventHandlerPtr event = nullptr; - IntrusivePtr reply; + zeek::ValPtr reply; BifEnum::MOUNT3::status_t mount_status = BifEnum::MOUNT3::MNT3_OK; bool rpc_success = ( rpc_status == BifEnum::RPC_SUCCESS ); @@ -177,40 +177,40 @@ zeek::Args MOUNT_Interp::event_common_vl(RPC_CallInfo *c, zeek::Args vl; vl.reserve(2 + extra_elements); vl.emplace_back(analyzer->ConnVal()); - auto auxgids = make_intrusive(zeek::id::index_vec); + auto auxgids = zeek::make_intrusive(zeek::id::index_vec); for (size_t i = 0; i < c->AuxGIDs().size(); ++i) { - auxgids->Assign(i, val_mgr->Count(c->AuxGIDs()[i])); + auxgids->Assign(i, zeek::val_mgr->Count(c->AuxGIDs()[i])); } - auto info = make_intrusive(zeek::BifType::Record::MOUNT3::info_t); + auto info = zeek::make_intrusive(zeek::BifType::Record::MOUNT3::info_t); info->Assign(0, zeek::BifType::Enum::rpc_status->GetVal(rpc_status)); info->Assign(1, zeek::BifType::Enum::MOUNT3::status_t->GetVal(mount_status)); - info->Assign(2, make_intrusive(c->StartTime())); - info->Assign(3, make_intrusive(c->LastTime() - c->StartTime())); - info->Assign(4, val_mgr->Count(c->RPCLen())); - info->Assign(5, make_intrusive(rep_start_time)); - info->Assign(6, make_intrusive(rep_last_time - rep_start_time)); - info->Assign(7, val_mgr->Count(reply_len)); - info->Assign(8, val_mgr->Count(c->Uid())); - info->Assign(9, val_mgr->Count(c->Gid())); - info->Assign(10, val_mgr->Count(c->Stamp())); - info->Assign(11, make_intrusive(c->MachineName())); + info->Assign(2, zeek::make_intrusive(c->StartTime())); + info->Assign(3, zeek::make_intrusive(c->LastTime() - c->StartTime())); + info->Assign(4, zeek::val_mgr->Count(c->RPCLen())); + info->Assign(5, zeek::make_intrusive(rep_start_time)); + info->Assign(6, zeek::make_intrusive(rep_last_time - rep_start_time)); + info->Assign(7, zeek::val_mgr->Count(reply_len)); + info->Assign(8, zeek::val_mgr->Count(c->Uid())); + info->Assign(9, zeek::val_mgr->Count(c->Gid())); + info->Assign(10, zeek::val_mgr->Count(c->Stamp())); + info->Assign(11, zeek::make_intrusive(c->MachineName())); info->Assign(12, std::move(auxgids)); vl.emplace_back(std::move(info)); return vl; } -IntrusivePtr MOUNT_Interp::mount3_auth_flavor(const u_char*& buf, int& n) +zeek::EnumValPtr MOUNT_Interp::mount3_auth_flavor(const u_char*& buf, int& n) { BifEnum::MOUNT3::auth_flavor_t t = (BifEnum::MOUNT3::auth_flavor_t)extract_XDR_uint32(buf, n); auto rval = zeek::BifType::Enum::MOUNT3::auth_flavor_t->GetVal(t); return rval; } -IntrusivePtr MOUNT_Interp::mount3_fh(const u_char*& buf, int& n) +zeek::StringValPtr MOUNT_Interp::mount3_fh(const u_char*& buf, int& n) { int fh_n; const u_char* fh = extract_XDR_opaque(buf, n, fh_n, 64); @@ -218,10 +218,10 @@ IntrusivePtr MOUNT_Interp::mount3_fh(const u_char*& buf, int& n) if ( ! fh ) return nullptr; - return make_intrusive(new BroString(fh, fh_n, false)); + return zeek::make_intrusive(new zeek::String(fh, fh_n, false)); } -IntrusivePtr MOUNT_Interp::mount3_filename(const u_char*& buf, int& n) +zeek::StringValPtr MOUNT_Interp::mount3_filename(const u_char*& buf, int& n) { int name_len; const u_char* name = extract_XDR_opaque(buf, n, name_len); @@ -229,20 +229,20 @@ IntrusivePtr MOUNT_Interp::mount3_filename(const u_char*& buf, int& n if ( ! name ) return nullptr; - return make_intrusive(new BroString(name, name_len, false)); + return zeek::make_intrusive(new zeek::String(name, name_len, false)); } -IntrusivePtr MOUNT_Interp::mount3_dirmntargs(const u_char*& buf, int& n) +zeek::RecordValPtr MOUNT_Interp::mount3_dirmntargs(const u_char*& buf, int& n) { - auto dirmntargs = make_intrusive(zeek::BifType::Record::MOUNT3::dirmntargs_t); + auto dirmntargs = zeek::make_intrusive(zeek::BifType::Record::MOUNT3::dirmntargs_t); dirmntargs->Assign(0, mount3_filename(buf, n)); return dirmntargs; } -IntrusivePtr MOUNT_Interp::mount3_mnt_reply(const u_char*& buf, int& n, - BifEnum::MOUNT3::status_t status) +zeek::RecordValPtr MOUNT_Interp::mount3_mnt_reply(const u_char*& buf, int& n, + BifEnum::MOUNT3::status_t status) { - auto rep = make_intrusive(zeek::BifType::Record::MOUNT3::mnt_reply_t); + auto rep = zeek::make_intrusive(zeek::BifType::Record::MOUNT3::mnt_reply_t); if ( status == BifEnum::MOUNT3::MNT3_OK ) { @@ -258,8 +258,8 @@ IntrusivePtr MOUNT_Interp::mount3_mnt_reply(const u_char*& buf, int& auth_flavors_count = max_auth_flavors; } - auto enum_vector = make_intrusive(zeek::base_type(zeek::TYPE_ENUM)); - auto auth_flavors = make_intrusive(std::move(enum_vector)); + auto enum_vector = zeek::make_intrusive(zeek::base_type(zeek::TYPE_ENUM)); + auto auth_flavors = zeek::make_intrusive(std::move(enum_vector)); for ( auto i = 0u; i < auth_flavors_count; ++i ) auth_flavors->Assign(auth_flavors->Size(), diff --git a/src/analyzer/protocol/rpc/MOUNT.h b/src/analyzer/protocol/rpc/MOUNT.h index 0409db7404..888cc5b47e 100644 --- a/src/analyzer/protocol/rpc/MOUNT.h +++ b/src/analyzer/protocol/rpc/MOUNT.h @@ -29,12 +29,12 @@ protected: // to 0. However, the methods might still return an allocated Val * ! // So, you might want to Unref() the Val if buf is 0. Method names // are based on the type names of RFC 1813. - IntrusivePtr mount3_auth_flavor(const u_char*& buf, int& n); - IntrusivePtr mount3_fh(const u_char*& buf, int& n); - IntrusivePtr mount3_dirmntargs(const u_char*&buf, int &n); - IntrusivePtr mount3_filename(const u_char*& buf, int& n); + zeek::EnumValPtr mount3_auth_flavor(const u_char*& buf, int& n); + zeek::StringValPtr mount3_fh(const u_char*& buf, int& n); + zeek::RecordValPtr mount3_dirmntargs(const u_char*&buf, int &n); + zeek::StringValPtr mount3_filename(const u_char*& buf, int& n); - IntrusivePtr mount3_mnt_reply(const u_char*& buf, int& n, BifEnum::MOUNT3::status_t status); + zeek::RecordValPtr mount3_mnt_reply(const u_char*& buf, int& n, BifEnum::MOUNT3::status_t status); }; class MOUNT_Analyzer : public RPC_Analyzer { diff --git a/src/analyzer/protocol/rpc/NFS.cc b/src/analyzer/protocol/rpc/NFS.cc index 97a66f5461..f6c6015162 100644 --- a/src/analyzer/protocol/rpc/NFS.cc +++ b/src/analyzer/protocol/rpc/NFS.cc @@ -6,7 +6,7 @@ #include #include -#include "BroString.h" +#include "ZeekString.h" #include "NetVar.h" #include "XDR.h" #include "Event.h" @@ -22,7 +22,7 @@ bool NFS_Interp::RPC_BuildCall(RPC_CallInfo* c, const u_char*& buf, int& n) uint32_t proc = c->Proc(); // The call arguments, depends on the call type obviously ... - IntrusivePtr callarg; + zeek::ValPtr callarg; switch ( proc ) { case BifEnum::NFS3::PROC_NULL: @@ -124,7 +124,7 @@ bool NFS_Interp::RPC_BuildReply(RPC_CallInfo* c, BifEnum::rpc_status rpc_status, double last_time, int reply_len) { EventHandlerPtr event = nullptr; - IntrusivePtr reply; + zeek::ValPtr reply; BifEnum::NFS3::status_t nfs_status = BifEnum::NFS3::NFS3ERR_OK; bool rpc_success = ( rpc_status == BifEnum::RPC_SUCCESS ); @@ -278,7 +278,7 @@ bool NFS_Interp::RPC_BuildReply(RPC_CallInfo* c, BifEnum::rpc_status rpc_status, return true; } -IntrusivePtr NFS_Interp::nfs3_file_data(const u_char*& buf, int& n, uint64_t offset, int size) +zeek::StringValPtr NFS_Interp::nfs3_file_data(const u_char*& buf, int& n, uint64_t offset, int size) { int data_n; @@ -297,7 +297,7 @@ IntrusivePtr NFS_Interp::nfs3_file_data(const u_char*& buf, int& n, u data_n = std::min(data_n, int(zeek::BifConst::NFS3::return_data_max)); if ( data && data_n > 0 ) - return make_intrusive(new BroString(data, data_n, false)); + return zeek::make_intrusive(new zeek::String(data, data_n, false)); return nullptr; } @@ -312,31 +312,31 @@ zeek::Args NFS_Interp::event_common_vl(RPC_CallInfo *c, BifEnum::rpc_status rpc_ zeek::Args vl; vl.reserve(2 + extra_elements); vl.emplace_back(analyzer->ConnVal()); - auto auxgids = make_intrusive(zeek::id::index_vec); + auto auxgids = zeek::make_intrusive(zeek::id::index_vec); for ( size_t i = 0; i < c->AuxGIDs().size(); ++i ) - auxgids->Assign(i, val_mgr->Count(c->AuxGIDs()[i])); + auxgids->Assign(i, zeek::val_mgr->Count(c->AuxGIDs()[i])); - auto info = make_intrusive(zeek::BifType::Record::NFS3::info_t); + auto info = zeek::make_intrusive(zeek::BifType::Record::NFS3::info_t); info->Assign(0, zeek::BifType::Enum::rpc_status->GetVal(rpc_status)); info->Assign(1, zeek::BifType::Enum::NFS3::status_t->GetVal(nfs_status)); - info->Assign(2, make_intrusive(c->StartTime())); - info->Assign(3, make_intrusive(c->LastTime()-c->StartTime())); - info->Assign(4, val_mgr->Count(c->RPCLen())); - info->Assign(5, make_intrusive(rep_start_time)); - info->Assign(6, make_intrusive(rep_last_time-rep_start_time)); - info->Assign(7, val_mgr->Count(reply_len)); - info->Assign(8, val_mgr->Count(c->Uid())); - info->Assign(9, val_mgr->Count(c->Gid())); - info->Assign(10, val_mgr->Count(c->Stamp())); - info->Assign(11, make_intrusive(c->MachineName())); + info->Assign(2, zeek::make_intrusive(c->StartTime())); + info->Assign(3, zeek::make_intrusive(c->LastTime()-c->StartTime())); + info->Assign(4, zeek::val_mgr->Count(c->RPCLen())); + info->Assign(5, zeek::make_intrusive(rep_start_time)); + info->Assign(6, zeek::make_intrusive(rep_last_time-rep_start_time)); + info->Assign(7, zeek::val_mgr->Count(reply_len)); + info->Assign(8, zeek::val_mgr->Count(c->Uid())); + info->Assign(9, zeek::val_mgr->Count(c->Gid())); + info->Assign(10, zeek::val_mgr->Count(c->Stamp())); + info->Assign(11, zeek::make_intrusive(c->MachineName())); info->Assign(12, std::move(auxgids)); vl.emplace_back(std::move(info)); return vl; } -IntrusivePtr NFS_Interp::nfs3_fh(const u_char*& buf, int& n) +zeek::StringValPtr NFS_Interp::nfs3_fh(const u_char*& buf, int& n) { int fh_n; const u_char* fh = extract_XDR_opaque(buf, n, fh_n, 64); @@ -344,13 +344,13 @@ IntrusivePtr NFS_Interp::nfs3_fh(const u_char*& buf, int& n) if ( ! fh ) return nullptr; - return make_intrusive(new BroString(fh, fh_n, false)); + return zeek::make_intrusive(new zeek::String(fh, fh_n, false)); } -IntrusivePtr NFS_Interp::nfs3_sattr(const u_char*& buf, int& n) +zeek::RecordValPtr NFS_Interp::nfs3_sattr(const u_char*& buf, int& n) { - auto attrs = make_intrusive(zeek::BifType::Record::NFS3::sattr_t); + auto attrs = zeek::make_intrusive(zeek::BifType::Record::NFS3::sattr_t); attrs->Assign(0, nullptr); // mode int mode_set_it = extract_XDR_uint32(buf, n); @@ -379,9 +379,9 @@ IntrusivePtr NFS_Interp::nfs3_sattr(const u_char*& buf, int& n) return attrs; } -IntrusivePtr NFS_Interp::nfs3_sattr_reply(const u_char*& buf, int& n, BifEnum::NFS3::status_t status) +zeek::RecordValPtr NFS_Interp::nfs3_sattr_reply(const u_char*& buf, int& n, BifEnum::NFS3::status_t status) { - auto rep = make_intrusive(zeek::BifType::Record::NFS3::sattr_reply_t); + auto rep = zeek::make_intrusive(zeek::BifType::Record::NFS3::sattr_reply_t); if ( status == BifEnum::NFS3::NFS3ERR_OK ) { @@ -397,9 +397,9 @@ IntrusivePtr NFS_Interp::nfs3_sattr_reply(const u_char*& buf, int& n, return rep; } -IntrusivePtr NFS_Interp::nfs3_fattr(const u_char*& buf, int& n) +zeek::RecordValPtr NFS_Interp::nfs3_fattr(const u_char*& buf, int& n) { - auto attrs = make_intrusive(zeek::BifType::Record::NFS3::fattr_t); + auto attrs = zeek::make_intrusive(zeek::BifType::Record::NFS3::fattr_t); attrs->Assign(0, nfs3_ftype(buf, n)); // file type attrs->Assign(1, ExtractUint32(buf, n)); // mode @@ -419,23 +419,23 @@ IntrusivePtr NFS_Interp::nfs3_fattr(const u_char*& buf, int& n) return attrs; } -IntrusivePtr NFS_Interp::nfs3_time_how(const u_char*& buf, int& n) +zeek::EnumValPtr NFS_Interp::nfs3_time_how(const u_char*& buf, int& n) { BifEnum::NFS3::time_how_t t = (BifEnum::NFS3::time_how_t)extract_XDR_uint32(buf, n); auto rval = zeek::BifType::Enum::NFS3::time_how_t->GetVal(t); return rval; } -IntrusivePtr NFS_Interp::nfs3_ftype(const u_char*& buf, int& n) +zeek::EnumValPtr NFS_Interp::nfs3_ftype(const u_char*& buf, int& n) { BifEnum::NFS3::file_type_t t = (BifEnum::NFS3::file_type_t)extract_XDR_uint32(buf, n); auto rval = zeek::BifType::Enum::NFS3::file_type_t->GetVal(t); return rval; } -IntrusivePtr NFS_Interp::nfs3_wcc_attr(const u_char*& buf, int& n) +zeek::RecordValPtr NFS_Interp::nfs3_wcc_attr(const u_char*& buf, int& n) { - auto attrs = make_intrusive(zeek::BifType::Record::NFS3::wcc_attr_t); + auto attrs = zeek::make_intrusive(zeek::BifType::Record::NFS3::wcc_attr_t); attrs->Assign(0, ExtractUint64(buf, n)); // size attrs->Assign(1, ExtractTime(buf, n)); // mtime @@ -444,7 +444,7 @@ IntrusivePtr NFS_Interp::nfs3_wcc_attr(const u_char*& buf, int& n) return attrs; } -IntrusivePtr NFS_Interp::nfs3_filename(const u_char*& buf, int& n) +zeek::StringValPtr NFS_Interp::nfs3_filename(const u_char*& buf, int& n) { int name_len; const u_char* name = extract_XDR_opaque(buf, n, name_len); @@ -452,12 +452,12 @@ IntrusivePtr NFS_Interp::nfs3_filename(const u_char*& buf, int& n) if ( ! name ) return nullptr; - return make_intrusive(new BroString(name, name_len, false)); + return zeek::make_intrusive(new zeek::String(name, name_len, false)); } -IntrusivePtr NFS_Interp::nfs3_diropargs(const u_char*& buf, int& n) +zeek::RecordValPtr NFS_Interp::nfs3_diropargs(const u_char*& buf, int& n) { - auto diropargs = make_intrusive(zeek::BifType::Record::NFS3::diropargs_t); + auto diropargs = zeek::make_intrusive(zeek::BifType::Record::NFS3::diropargs_t); diropargs->Assign(0, nfs3_fh(buf, n)); diropargs->Assign(1, nfs3_filename(buf, n)); @@ -465,9 +465,9 @@ IntrusivePtr NFS_Interp::nfs3_diropargs(const u_char*& buf, int& n) return diropargs; } -IntrusivePtr NFS_Interp::nfs3_symlinkdata(const u_char*& buf, int& n) +zeek::RecordValPtr NFS_Interp::nfs3_symlinkdata(const u_char*& buf, int& n) { - auto symlinkdata = make_intrusive(zeek::BifType::Record::NFS3::symlinkdata_t); + auto symlinkdata = zeek::make_intrusive(zeek::BifType::Record::NFS3::symlinkdata_t); symlinkdata->Assign(0, nfs3_sattr(buf, n)); symlinkdata->Assign(1, nfs3_nfspath(buf, n)); @@ -475,9 +475,9 @@ IntrusivePtr NFS_Interp::nfs3_symlinkdata(const u_char*& buf, int& n) return symlinkdata; } -IntrusivePtr NFS_Interp::nfs3_renameopargs(const u_char*& buf, int& n) +zeek::RecordValPtr NFS_Interp::nfs3_renameopargs(const u_char*& buf, int& n) { - auto renameopargs = make_intrusive(zeek::BifType::Record::NFS3::renameopargs_t); + auto renameopargs = zeek::make_intrusive(zeek::BifType::Record::NFS3::renameopargs_t); renameopargs->Assign(0, nfs3_fh(buf, n)); renameopargs->Assign(1, nfs3_filename(buf, n)); @@ -487,7 +487,7 @@ IntrusivePtr NFS_Interp::nfs3_renameopargs(const u_char*& buf, int& n return renameopargs; } -IntrusivePtr NFS_Interp::nfs3_post_op_attr(const u_char*& buf, int& n) +zeek::RecordValPtr NFS_Interp::nfs3_post_op_attr(const u_char*& buf, int& n) { int have_attrs = extract_XDR_uint32(buf, n); @@ -497,7 +497,7 @@ IntrusivePtr NFS_Interp::nfs3_post_op_attr(const u_char*& buf, int& n return nullptr; } -IntrusivePtr NFS_Interp::nfs3_post_op_fh(const u_char*& buf, int& n) +zeek::StringValPtr NFS_Interp::nfs3_post_op_fh(const u_char*& buf, int& n) { int have_fh = extract_XDR_uint32(buf, n); @@ -507,7 +507,7 @@ IntrusivePtr NFS_Interp::nfs3_post_op_fh(const u_char*& buf, int& n) return nullptr; } -IntrusivePtr NFS_Interp::nfs3_pre_op_attr(const u_char*& buf, int& n) +zeek::RecordValPtr NFS_Interp::nfs3_pre_op_attr(const u_char*& buf, int& n) { int have_attrs = extract_XDR_uint32(buf, n); @@ -516,16 +516,16 @@ IntrusivePtr NFS_Interp::nfs3_pre_op_attr(const u_char*& buf, int& n) return nullptr; } -IntrusivePtr NFS_Interp::nfs3_stable_how(const u_char*& buf, int& n) +zeek::EnumValPtr NFS_Interp::nfs3_stable_how(const u_char*& buf, int& n) { BifEnum::NFS3::stable_how_t stable = (BifEnum::NFS3::stable_how_t)extract_XDR_uint32(buf, n); auto rval = zeek::BifType::Enum::NFS3::stable_how_t->GetVal(stable); return rval; } -IntrusivePtr NFS_Interp::nfs3_lookup_reply(const u_char*& buf, int& n, BifEnum::NFS3::status_t status) +zeek::RecordValPtr NFS_Interp::nfs3_lookup_reply(const u_char*& buf, int& n, BifEnum::NFS3::status_t status) { - auto rep = make_intrusive(zeek::BifType::Record::NFS3::lookup_reply_t); + auto rep = zeek::make_intrusive(zeek::BifType::Record::NFS3::lookup_reply_t); if ( status == BifEnum::NFS3::NFS3ERR_OK ) { @@ -542,9 +542,9 @@ IntrusivePtr NFS_Interp::nfs3_lookup_reply(const u_char*& buf, int& n return rep; } -IntrusivePtr NFS_Interp::nfs3_readargs(const u_char*& buf, int& n) +zeek::RecordValPtr NFS_Interp::nfs3_readargs(const u_char*& buf, int& n) { - auto readargs = make_intrusive(zeek::BifType::Record::NFS3::readargs_t); + auto readargs = zeek::make_intrusive(zeek::BifType::Record::NFS3::readargs_t); readargs->Assign(0, nfs3_fh(buf, n)); readargs->Assign(1, ExtractUint64(buf, n)); // offset @@ -553,10 +553,10 @@ IntrusivePtr NFS_Interp::nfs3_readargs(const u_char*& buf, int& n) return readargs; } -IntrusivePtr NFS_Interp::nfs3_read_reply(const u_char*& buf, int& n, BifEnum::NFS3::status_t status, +zeek::RecordValPtr NFS_Interp::nfs3_read_reply(const u_char*& buf, int& n, BifEnum::NFS3::status_t status, bro_uint_t offset) { - auto rep = make_intrusive(zeek::BifType::Record::NFS3::read_reply_t); + auto rep = zeek::make_intrusive(zeek::BifType::Record::NFS3::read_reply_t); if (status == BifEnum::NFS3::NFS3ERR_OK) { @@ -564,7 +564,7 @@ IntrusivePtr NFS_Interp::nfs3_read_reply(const u_char*& buf, int& n, rep->Assign(0, nfs3_post_op_attr(buf, n)); bytes_read = extract_XDR_uint32(buf, n); - rep->Assign(1, val_mgr->Count(bytes_read)); + rep->Assign(1, zeek::val_mgr->Count(bytes_read)); rep->Assign(2, ExtractBool(buf, n)); rep->Assign(3, nfs3_file_data(buf, n, offset, bytes_read)); } @@ -576,9 +576,9 @@ IntrusivePtr NFS_Interp::nfs3_read_reply(const u_char*& buf, int& n, return rep; } -IntrusivePtr NFS_Interp::nfs3_readlink_reply(const u_char*& buf, int& n, BifEnum::NFS3::status_t status) +zeek::RecordValPtr NFS_Interp::nfs3_readlink_reply(const u_char*& buf, int& n, BifEnum::NFS3::status_t status) { - auto rep = make_intrusive(zeek::BifType::Record::NFS3::readlink_reply_t); + auto rep = zeek::make_intrusive(zeek::BifType::Record::NFS3::readlink_reply_t); if (status == BifEnum::NFS3::NFS3ERR_OK) { @@ -593,9 +593,9 @@ IntrusivePtr NFS_Interp::nfs3_readlink_reply(const u_char*& buf, int& return rep; } -IntrusivePtr NFS_Interp::nfs3_link_reply(const u_char*& buf, int& n, BifEnum::NFS3::status_t status) +zeek::RecordValPtr NFS_Interp::nfs3_link_reply(const u_char*& buf, int& n, BifEnum::NFS3::status_t status) { - auto rep = make_intrusive(zeek::BifType::Record::NFS3::link_reply_t); + auto rep = zeek::make_intrusive(zeek::BifType::Record::NFS3::link_reply_t); if ( status == BifEnum::NFS3::NFS3ERR_OK ) { @@ -609,9 +609,9 @@ IntrusivePtr NFS_Interp::nfs3_link_reply(const u_char*& buf, int& n, return rep; } -IntrusivePtr NFS_Interp::nfs3_symlinkargs(const u_char*& buf, int& n) +zeek::RecordValPtr NFS_Interp::nfs3_symlinkargs(const u_char*& buf, int& n) { - auto symlinkargs = make_intrusive(zeek::BifType::Record::NFS3::symlinkargs_t); + auto symlinkargs = zeek::make_intrusive(zeek::BifType::Record::NFS3::symlinkargs_t); symlinkargs->Assign(0, nfs3_diropargs(buf, n)); symlinkargs->Assign(1, nfs3_symlinkdata(buf, n)); @@ -619,9 +619,9 @@ IntrusivePtr NFS_Interp::nfs3_symlinkargs(const u_char*& buf, int& n) return symlinkargs; } -IntrusivePtr NFS_Interp::nfs3_sattrargs(const u_char*& buf, int& n) +zeek::RecordValPtr NFS_Interp::nfs3_sattrargs(const u_char*& buf, int& n) { - auto sattrargs = make_intrusive(zeek::BifType::Record::NFS3::sattrargs_t); + auto sattrargs = zeek::make_intrusive(zeek::BifType::Record::NFS3::sattrargs_t); sattrargs->Assign(0, nfs3_fh(buf, n)); sattrargs->Assign(1, nfs3_sattr(buf, n)); @@ -629,9 +629,9 @@ IntrusivePtr NFS_Interp::nfs3_sattrargs(const u_char*& buf, int& n) return sattrargs; } -IntrusivePtr NFS_Interp::nfs3_linkargs(const u_char*& buf, int& n) +zeek::RecordValPtr NFS_Interp::nfs3_linkargs(const u_char*& buf, int& n) { - auto linkargs = make_intrusive(zeek::BifType::Record::NFS3::linkargs_t); + auto linkargs = zeek::make_intrusive(zeek::BifType::Record::NFS3::linkargs_t); linkargs->Assign(0, nfs3_fh(buf, n)); linkargs->Assign(1, nfs3_diropargs(buf, n)); @@ -639,17 +639,17 @@ IntrusivePtr NFS_Interp::nfs3_linkargs(const u_char*& buf, int& n) return linkargs; } -IntrusivePtr NFS_Interp::nfs3_writeargs(const u_char*& buf, int& n) +zeek::RecordValPtr NFS_Interp::nfs3_writeargs(const u_char*& buf, int& n) { uint32_t bytes; uint64_t offset; - auto writeargs = make_intrusive(zeek::BifType::Record::NFS3::writeargs_t); + auto writeargs = zeek::make_intrusive(zeek::BifType::Record::NFS3::writeargs_t); writeargs->Assign(0, nfs3_fh(buf, n)); offset = extract_XDR_uint64(buf, n); - writeargs->Assign(1, val_mgr->Count(offset)); // offset + writeargs->Assign(1, zeek::val_mgr->Count(offset)); // offset bytes = extract_XDR_uint32(buf, n); - writeargs->Assign(2, val_mgr->Count(bytes)); // size + writeargs->Assign(2, zeek::val_mgr->Count(bytes)); // size writeargs->Assign(3, nfs3_stable_how(buf, n)); writeargs->Assign(4, nfs3_file_data(buf, n, offset, bytes)); @@ -657,9 +657,9 @@ IntrusivePtr NFS_Interp::nfs3_writeargs(const u_char*& buf, int& n) return writeargs; } -IntrusivePtr NFS_Interp::nfs3_write_reply(const u_char*& buf, int& n, BifEnum::NFS3::status_t status) +zeek::RecordValPtr NFS_Interp::nfs3_write_reply(const u_char*& buf, int& n, BifEnum::NFS3::status_t status) { - auto rep = make_intrusive(zeek::BifType::Record::NFS3::write_reply_t); + auto rep = zeek::make_intrusive(zeek::BifType::Record::NFS3::write_reply_t); if ( status == BifEnum::NFS3::NFS3ERR_OK ) { @@ -682,9 +682,9 @@ IntrusivePtr NFS_Interp::nfs3_write_reply(const u_char*& buf, int& n, return rep; } -IntrusivePtr NFS_Interp::nfs3_newobj_reply(const u_char*& buf, int& n, BifEnum::NFS3::status_t status) +zeek::RecordValPtr NFS_Interp::nfs3_newobj_reply(const u_char*& buf, int& n, BifEnum::NFS3::status_t status) { - auto rep = make_intrusive(zeek::BifType::Record::NFS3::newobj_reply_t); + auto rep = zeek::make_intrusive(zeek::BifType::Record::NFS3::newobj_reply_t); if (status == BifEnum::NFS3::NFS3ERR_OK) { @@ -706,9 +706,9 @@ IntrusivePtr NFS_Interp::nfs3_newobj_reply(const u_char*& buf, int& n return rep; } -IntrusivePtr NFS_Interp::nfs3_delobj_reply(const u_char*& buf, int& n) +zeek::RecordValPtr NFS_Interp::nfs3_delobj_reply(const u_char*& buf, int& n) { - auto rep = make_intrusive(zeek::BifType::Record::NFS3::delobj_reply_t); + auto rep = zeek::make_intrusive(zeek::BifType::Record::NFS3::delobj_reply_t); // wcc_data rep->Assign(0, nfs3_pre_op_attr(buf, n)); @@ -717,9 +717,9 @@ IntrusivePtr NFS_Interp::nfs3_delobj_reply(const u_char*& buf, int& n return rep; } -IntrusivePtr NFS_Interp::nfs3_renameobj_reply(const u_char*& buf, int& n) +zeek::RecordValPtr NFS_Interp::nfs3_renameobj_reply(const u_char*& buf, int& n) { - auto rep = make_intrusive(zeek::BifType::Record::NFS3::renameobj_reply_t); + auto rep = zeek::make_intrusive(zeek::BifType::Record::NFS3::renameobj_reply_t); // wcc_data rep->Assign(0, nfs3_pre_op_attr(buf, n)); @@ -730,11 +730,11 @@ IntrusivePtr NFS_Interp::nfs3_renameobj_reply(const u_char*& buf, int return rep; } -IntrusivePtr NFS_Interp::nfs3_readdirargs(bool isplus, const u_char*& buf, int&n) +zeek::RecordValPtr NFS_Interp::nfs3_readdirargs(bool isplus, const u_char*& buf, int&n) { - auto args = make_intrusive(zeek::BifType::Record::NFS3::readdirargs_t); + auto args = zeek::make_intrusive(zeek::BifType::Record::NFS3::readdirargs_t); - args->Assign(0, val_mgr->Bool(isplus)); + args->Assign(0, zeek::val_mgr->Bool(isplus)); args->Assign(1, nfs3_fh(buf, n)); args->Assign(2, ExtractUint64(buf,n)); // cookie args->Assign(3, ExtractUint64(buf,n)); // cookieverf @@ -746,17 +746,17 @@ IntrusivePtr NFS_Interp::nfs3_readdirargs(bool isplus, const u_char*& return args; } -IntrusivePtr NFS_Interp::nfs3_readdir_reply(bool isplus, const u_char*& buf, +zeek::RecordValPtr NFS_Interp::nfs3_readdir_reply(bool isplus, const u_char*& buf, int&n, BifEnum::NFS3::status_t status) { - auto rep = make_intrusive(zeek::BifType::Record::NFS3::readdir_reply_t); + auto rep = zeek::make_intrusive(zeek::BifType::Record::NFS3::readdir_reply_t); - rep->Assign(0, val_mgr->Bool(isplus)); + rep->Assign(0, zeek::val_mgr->Bool(isplus)); if ( status == BifEnum::NFS3::NFS3ERR_OK ) { unsigned pos; - auto entries = make_intrusive(zeek::BifType::Vector::NFS3::direntry_vec_t); + auto entries = zeek::make_intrusive(zeek::BifType::Vector::NFS3::direntry_vec_t); rep->Assign(1, nfs3_post_op_attr(buf,n)); // dir_attr rep->Assign(2, ExtractUint64(buf,n)); // cookieverf @@ -765,7 +765,7 @@ IntrusivePtr NFS_Interp::nfs3_readdir_reply(bool isplus, const u_char while ( extract_XDR_uint32(buf,n) ) { - auto entry = make_intrusive(zeek::BifType::Record::NFS3::direntry_t); + auto entry = zeek::make_intrusive(zeek::BifType::Record::NFS3::direntry_t); entry->Assign(0, ExtractUint64(buf,n)); // fileid entry->Assign(1, nfs3_filename(buf,n)); // fname entry->Assign(2, ExtractUint64(buf,n)); // cookie @@ -791,29 +791,29 @@ IntrusivePtr NFS_Interp::nfs3_readdir_reply(bool isplus, const u_char return rep; } -IntrusivePtr NFS_Interp::ExtractUint32(const u_char*& buf, int& n) +zeek::ValPtr NFS_Interp::ExtractUint32(const u_char*& buf, int& n) { - return val_mgr->Count(extract_XDR_uint32(buf, n)); + return zeek::val_mgr->Count(extract_XDR_uint32(buf, n)); } -IntrusivePtr NFS_Interp::ExtractUint64(const u_char*& buf, int& n) +zeek::ValPtr NFS_Interp::ExtractUint64(const u_char*& buf, int& n) { - return val_mgr->Count(extract_XDR_uint64(buf, n)); + return zeek::val_mgr->Count(extract_XDR_uint64(buf, n)); } -IntrusivePtr NFS_Interp::ExtractTime(const u_char*& buf, int& n) +zeek::ValPtr NFS_Interp::ExtractTime(const u_char*& buf, int& n) { - return make_intrusive(extract_XDR_time(buf, n)); + return zeek::make_intrusive(extract_XDR_time(buf, n)); } -IntrusivePtr NFS_Interp::ExtractInterval(const u_char*& buf, int& n) +zeek::ValPtr NFS_Interp::ExtractInterval(const u_char*& buf, int& n) { - return make_intrusive(double(extract_XDR_uint32(buf, n)), 1.0); + return zeek::make_intrusive(double(extract_XDR_uint32(buf, n)), 1.0); } -IntrusivePtr NFS_Interp::ExtractBool(const u_char*& buf, int& n) +zeek::ValPtr NFS_Interp::ExtractBool(const u_char*& buf, int& n) { - return val_mgr->Bool(extract_XDR_uint32(buf, n)); + return zeek::val_mgr->Bool(extract_XDR_uint32(buf, n)); } diff --git a/src/analyzer/protocol/rpc/NFS.h b/src/analyzer/protocol/rpc/NFS.h index 9d5942878e..c8b160e276 100644 --- a/src/analyzer/protocol/rpc/NFS.h +++ b/src/analyzer/protocol/rpc/NFS.h @@ -30,53 +30,53 @@ protected: // to 0. However, the methods might still return an allocated Val * ! // So, you might want to Unref() the Val if buf is 0. Method names // are based on the type names of RFC 1813. - IntrusivePtr nfs3_fh(const u_char*& buf, int& n); - IntrusivePtr nfs3_fattr(const u_char*& buf, int& n); - IntrusivePtr nfs3_sattr(const u_char*& buf, int& n); - IntrusivePtr nfs3_ftype(const u_char*& buf, int& n); - IntrusivePtr nfs3_time_how(const u_char*& buf, int& n); - IntrusivePtr nfs3_wcc_attr(const u_char*& buf, int& n); - IntrusivePtr nfs3_diropargs(const u_char*&buf, int &n); - IntrusivePtr nfs3_symlinkdata(const u_char*& buf, int& n); - IntrusivePtr nfs3_renameopargs(const u_char*&buf, int &n); - IntrusivePtr nfs3_filename(const u_char*& buf, int& n); - IntrusivePtr nfs3_linkargs(const u_char*& buf, int& n); - IntrusivePtr nfs3_symlinkargs(const u_char*& buf, int& n); - IntrusivePtr nfs3_sattrargs(const u_char*& buf, int& n); - IntrusivePtr nfs3_nfspath(const u_char*& buf, int& n) + zeek::StringValPtr nfs3_fh(const u_char*& buf, int& n); + zeek::RecordValPtr nfs3_fattr(const u_char*& buf, int& n); + zeek::RecordValPtr nfs3_sattr(const u_char*& buf, int& n); + zeek::EnumValPtr nfs3_ftype(const u_char*& buf, int& n); + zeek::EnumValPtr nfs3_time_how(const u_char*& buf, int& n); + zeek::RecordValPtr nfs3_wcc_attr(const u_char*& buf, int& n); + zeek::RecordValPtr nfs3_diropargs(const u_char*&buf, int &n); + zeek::RecordValPtr nfs3_symlinkdata(const u_char*& buf, int& n); + zeek::RecordValPtr nfs3_renameopargs(const u_char*&buf, int &n); + zeek::StringValPtr nfs3_filename(const u_char*& buf, int& n); + zeek::RecordValPtr nfs3_linkargs(const u_char*& buf, int& n); + zeek::RecordValPtr nfs3_symlinkargs(const u_char*& buf, int& n); + zeek::RecordValPtr nfs3_sattrargs(const u_char*& buf, int& n); + zeek::StringValPtr nfs3_nfspath(const u_char*& buf, int& n) { return nfs3_filename(buf,n); } - IntrusivePtr nfs3_post_op_attr(const u_char*&buf, int &n); // Return 0 or an fattr - IntrusivePtr nfs3_pre_op_attr(const u_char*&buf, int &n); // Return 0 or an wcc_attr - IntrusivePtr nfs3_sattr_reply(const u_char*& buf, int& n, BifEnum::NFS3::status_t status); - IntrusivePtr nfs3_lookup_reply(const u_char*& buf, int& n, BifEnum::NFS3::status_t status); - IntrusivePtr nfs3_readargs(const u_char*& buf, int& n); - IntrusivePtr nfs3_read_reply(const u_char*& buf, int& n, BifEnum::NFS3::status_t status, bro_uint_t offset); - IntrusivePtr nfs3_readlink_reply(const u_char*& buf, int& n, BifEnum::NFS3::status_t status); - IntrusivePtr nfs3_link_reply(const u_char*& buf, int& n, BifEnum::NFS3::status_t status); - IntrusivePtr nfs3_writeargs(const u_char*& buf, int& n); - IntrusivePtr nfs3_stable_how(const u_char*& buf, int& n); - IntrusivePtr nfs3_write_reply(const u_char*& buf, int& n, BifEnum::NFS3::status_t status); - IntrusivePtr nfs3_newobj_reply(const u_char*& buf, int&n, BifEnum::NFS3::status_t status); - IntrusivePtr nfs3_delobj_reply(const u_char*& buf, int& n); - IntrusivePtr nfs3_renameobj_reply(const u_char*& buf, int& n); - IntrusivePtr nfs3_post_op_fh(const u_char*& buf, int& n); - IntrusivePtr nfs3_readdirargs(bool isplus, const u_char*& buf, int&n); - IntrusivePtr nfs3_readdir_reply(bool isplus, const u_char*& buf, int&n, BifEnum::NFS3::status_t status); + zeek::RecordValPtr nfs3_post_op_attr(const u_char*&buf, int &n); // Return 0 or an fattr + zeek::RecordValPtr nfs3_pre_op_attr(const u_char*&buf, int &n); // Return 0 or an wcc_attr + zeek::RecordValPtr nfs3_sattr_reply(const u_char*& buf, int& n, BifEnum::NFS3::status_t status); + zeek::RecordValPtr nfs3_lookup_reply(const u_char*& buf, int& n, BifEnum::NFS3::status_t status); + zeek::RecordValPtr nfs3_readargs(const u_char*& buf, int& n); + zeek::RecordValPtr nfs3_read_reply(const u_char*& buf, int& n, BifEnum::NFS3::status_t status, bro_uint_t offset); + zeek::RecordValPtr nfs3_readlink_reply(const u_char*& buf, int& n, BifEnum::NFS3::status_t status); + zeek::RecordValPtr nfs3_link_reply(const u_char*& buf, int& n, BifEnum::NFS3::status_t status); + zeek::RecordValPtr nfs3_writeargs(const u_char*& buf, int& n); + zeek::EnumValPtr nfs3_stable_how(const u_char*& buf, int& n); + zeek::RecordValPtr nfs3_write_reply(const u_char*& buf, int& n, BifEnum::NFS3::status_t status); + zeek::RecordValPtr nfs3_newobj_reply(const u_char*& buf, int&n, BifEnum::NFS3::status_t status); + zeek::RecordValPtr nfs3_delobj_reply(const u_char*& buf, int& n); + zeek::RecordValPtr nfs3_renameobj_reply(const u_char*& buf, int& n); + zeek::StringValPtr nfs3_post_op_fh(const u_char*& buf, int& n); + zeek::RecordValPtr nfs3_readdirargs(bool isplus, const u_char*& buf, int&n); + zeek::RecordValPtr nfs3_readdir_reply(bool isplus, const u_char*& buf, int&n, BifEnum::NFS3::status_t status); // Consumes the file data in the RPC message. Depending on NFS::return_data* consts // in bro.init returns NULL or the data as string val: // * offset is the offset of the read/write call // * size is the amount of bytes read (or requested to be written), - IntrusivePtr nfs3_file_data(const u_char*& buf, int& n, uint64_t offset, int size); + zeek::StringValPtr nfs3_file_data(const u_char*& buf, int& n, uint64_t offset, int size); - IntrusivePtr ExtractUint32(const u_char*& buf, int& n); - IntrusivePtr ExtractUint64(const u_char*& buf, int& n); - IntrusivePtr ExtractTime(const u_char*& buf, int& n); - IntrusivePtr ExtractInterval(const u_char*& buf, int& n); - IntrusivePtr ExtractBool(const u_char*& buf, int& n); + zeek::ValPtr ExtractUint32(const u_char*& buf, int& n); + zeek::ValPtr ExtractUint64(const u_char*& buf, int& n); + zeek::ValPtr ExtractTime(const u_char*& buf, int& n); + zeek::ValPtr ExtractInterval(const u_char*& buf, int& n); + zeek::ValPtr ExtractBool(const u_char*& buf, int& n); }; class NFS_Analyzer : public RPC_Analyzer { diff --git a/src/analyzer/protocol/rpc/Portmap.cc b/src/analyzer/protocol/rpc/Portmap.cc index e69bb9d487..4927cb7505 100644 --- a/src/analyzer/protocol/rpc/Portmap.cc +++ b/src/analyzer/protocol/rpc/Portmap.cc @@ -79,7 +79,7 @@ bool PortmapperInterp::RPC_BuildReply(RPC_CallInfo* c, BifEnum::rpc_status statu int reply_len) { EventHandlerPtr event; - IntrusivePtr reply; + zeek::ValPtr reply; int success = (status == BifEnum::RPC_SUCCESS); switch ( c->Proc() ) { @@ -94,7 +94,7 @@ bool PortmapperInterp::RPC_BuildReply(RPC_CallInfo* c, BifEnum::rpc_status statu if ( ! buf ) return false; - reply = val_mgr->Bool(status); + reply = zeek::val_mgr->Bool(status); event = pm_request_set; } else @@ -109,7 +109,7 @@ bool PortmapperInterp::RPC_BuildReply(RPC_CallInfo* c, BifEnum::rpc_status statu if ( ! buf ) return false; - reply = val_mgr->Bool(status); + reply = zeek::val_mgr->Bool(status); event = pm_request_unset; } else @@ -124,9 +124,9 @@ bool PortmapperInterp::RPC_BuildReply(RPC_CallInfo* c, BifEnum::rpc_status statu if ( ! buf ) return false; - RecordVal* rv = c->RequestVal()->AsRecordVal(); + zeek::RecordVal* rv = c->RequestVal()->AsRecordVal(); const auto& is_tcp = rv->GetField(2); - reply = val_mgr->Port(CheckPort(port), is_tcp->IsOne() ? + reply = zeek::val_mgr->Port(CheckPort(port), is_tcp->IsOne() ? TRANSPORT_TCP : TRANSPORT_UDP); event = pm_request_getport; } @@ -139,7 +139,7 @@ bool PortmapperInterp::RPC_BuildReply(RPC_CallInfo* c, BifEnum::rpc_status statu if ( success ) { static auto pm_mappings = zeek::id::find_type("pm_mappings"); - auto mappings = make_intrusive(pm_mappings); + auto mappings = zeek::make_intrusive(pm_mappings); uint32_t nmap = 0; // Each call in the loop test pulls the next "opted" @@ -150,7 +150,7 @@ bool PortmapperInterp::RPC_BuildReply(RPC_CallInfo* c, BifEnum::rpc_status statu if ( ! m ) break; - auto index = val_mgr->Count(++nmap); + auto index = zeek::val_mgr->Count(++nmap); mappings->Assign(std::move(index), std::move(m)); } @@ -174,7 +174,7 @@ bool PortmapperInterp::RPC_BuildReply(RPC_CallInfo* c, BifEnum::rpc_status statu if ( ! opaque_reply ) return false; - reply = val_mgr->Port(CheckPort(port), TRANSPORT_UDP); + reply = zeek::val_mgr->Port(CheckPort(port), TRANSPORT_UDP); event = pm_request_callit; } else @@ -189,17 +189,17 @@ bool PortmapperInterp::RPC_BuildReply(RPC_CallInfo* c, BifEnum::rpc_status statu return true; } -IntrusivePtr PortmapperInterp::ExtractMapping(const u_char*& buf, int& len) +zeek::ValPtr PortmapperInterp::ExtractMapping(const u_char*& buf, int& len) { static auto pm_mapping = zeek::id::find_type("pm_mapping"); - auto mapping = make_intrusive(pm_mapping); + auto mapping = zeek::make_intrusive(pm_mapping); - mapping->Assign(0, val_mgr->Count(extract_XDR_uint32(buf, len))); - mapping->Assign(1, val_mgr->Count(extract_XDR_uint32(buf, len))); + mapping->Assign(0, zeek::val_mgr->Count(extract_XDR_uint32(buf, len))); + mapping->Assign(1, zeek::val_mgr->Count(extract_XDR_uint32(buf, len))); bool is_tcp = extract_XDR_uint32(buf, len) == IPPROTO_TCP; uint32_t port = extract_XDR_uint32(buf, len); - mapping->Assign(2, val_mgr->Port(CheckPort(port), is_tcp ? TRANSPORT_TCP : TRANSPORT_UDP)); + mapping->Assign(2, zeek::val_mgr->Port(CheckPort(port), is_tcp ? TRANSPORT_TCP : TRANSPORT_UDP)); if ( ! buf ) return nullptr; @@ -207,16 +207,16 @@ IntrusivePtr PortmapperInterp::ExtractMapping(const u_char*& buf, int& len) return mapping; } -IntrusivePtr PortmapperInterp::ExtractPortRequest(const u_char*& buf, int& len) +zeek::ValPtr PortmapperInterp::ExtractPortRequest(const u_char*& buf, int& len) { static auto pm_port_request = zeek::id::find_type("pm_port_request"); - auto pr = make_intrusive(pm_port_request); + auto pr = zeek::make_intrusive(pm_port_request); - pr->Assign(0, val_mgr->Count(extract_XDR_uint32(buf, len))); - pr->Assign(1, val_mgr->Count(extract_XDR_uint32(buf, len))); + pr->Assign(0, zeek::val_mgr->Count(extract_XDR_uint32(buf, len))); + pr->Assign(1, zeek::val_mgr->Count(extract_XDR_uint32(buf, len))); bool is_tcp = extract_XDR_uint32(buf, len) == IPPROTO_TCP; - pr->Assign(2, val_mgr->Bool(is_tcp)); + pr->Assign(2, zeek::val_mgr->Bool(is_tcp)); (void) extract_XDR_uint32(buf, len); // consume the bogus port if ( ! buf ) @@ -225,18 +225,18 @@ IntrusivePtr PortmapperInterp::ExtractPortRequest(const u_char*& buf, int& return pr; } -IntrusivePtr PortmapperInterp::ExtractCallItRequest(const u_char*& buf, int& len) +zeek::ValPtr PortmapperInterp::ExtractCallItRequest(const u_char*& buf, int& len) { static auto pm_callit_request = zeek::id::find_type("pm_callit_request"); - auto c = make_intrusive(pm_callit_request); + auto c = zeek::make_intrusive(pm_callit_request); - c->Assign(0, val_mgr->Count(extract_XDR_uint32(buf, len))); - c->Assign(1, val_mgr->Count(extract_XDR_uint32(buf, len))); - c->Assign(2, val_mgr->Count(extract_XDR_uint32(buf, len))); + c->Assign(0, zeek::val_mgr->Count(extract_XDR_uint32(buf, len))); + c->Assign(1, zeek::val_mgr->Count(extract_XDR_uint32(buf, len))); + c->Assign(2, zeek::val_mgr->Count(extract_XDR_uint32(buf, len))); int arg_n; (void) extract_XDR_opaque(buf, len, arg_n); - c->Assign(3, val_mgr->Count(arg_n)); + c->Assign(3, zeek::val_mgr->Count(arg_n)); if ( ! buf ) return nullptr; @@ -252,7 +252,7 @@ uint32_t PortmapperInterp::CheckPort(uint32_t port) { analyzer->EnqueueConnEvent(pm_bad_port, analyzer->ConnVal(), - val_mgr->Count(port) + zeek::val_mgr->Count(port) ); } @@ -262,7 +262,7 @@ uint32_t PortmapperInterp::CheckPort(uint32_t port) return port; } -void PortmapperInterp::Event(EventHandlerPtr f, IntrusivePtr request, BifEnum::rpc_status status, IntrusivePtr reply) +void PortmapperInterp::Event(EventHandlerPtr f, zeek::ValPtr request, BifEnum::rpc_status status, zeek::ValPtr reply) { if ( ! f ) return; diff --git a/src/analyzer/protocol/rpc/Portmap.h b/src/analyzer/protocol/rpc/Portmap.h index 9879976c28..309f310d06 100644 --- a/src/analyzer/protocol/rpc/Portmap.h +++ b/src/analyzer/protocol/rpc/Portmap.h @@ -17,11 +17,11 @@ protected: double last_time, int reply_len) override; uint32_t CheckPort(uint32_t port); - void Event(EventHandlerPtr f, IntrusivePtr request, BifEnum::rpc_status status, IntrusivePtr reply); + void Event(EventHandlerPtr f, zeek::ValPtr request, BifEnum::rpc_status status, zeek::ValPtr reply); - IntrusivePtr ExtractMapping(const u_char*& buf, int& len); - IntrusivePtr ExtractPortRequest(const u_char*& buf, int& len); - IntrusivePtr ExtractCallItRequest(const u_char*& buf, int& len); + zeek::ValPtr ExtractMapping(const u_char*& buf, int& len); + zeek::ValPtr ExtractPortRequest(const u_char*& buf, int& len); + zeek::ValPtr ExtractCallItRequest(const u_char*& buf, int& len); }; class Portmapper_Analyzer : public RPC_Analyzer { diff --git a/src/analyzer/protocol/rpc/RPC.cc b/src/analyzer/protocol/rpc/RPC.cc index a891266d25..24df03dd81 100644 --- a/src/analyzer/protocol/rpc/RPC.cc +++ b/src/analyzer/protocol/rpc/RPC.cc @@ -338,13 +338,13 @@ void RPC_Interpreter::Event_RPC_Dialogue(RPC_CallInfo* c, BifEnum::rpc_status st if ( rpc_dialogue ) analyzer->EnqueueConnEvent(rpc_dialogue, analyzer->ConnVal(), - val_mgr->Count(c->Program()), - val_mgr->Count(c->Version()), - val_mgr->Count(c->Proc()), + zeek::val_mgr->Count(c->Program()), + zeek::val_mgr->Count(c->Version()), + zeek::val_mgr->Count(c->Proc()), zeek::BifType::Enum::rpc_status->GetVal(status), - make_intrusive(c->StartTime()), - val_mgr->Count(c->CallLen()), - val_mgr->Count(reply_len) + zeek::make_intrusive(c->StartTime()), + zeek::val_mgr->Count(c->CallLen()), + zeek::val_mgr->Count(reply_len) ); } @@ -353,11 +353,11 @@ void RPC_Interpreter::Event_RPC_Call(RPC_CallInfo* c) if ( rpc_call ) analyzer->EnqueueConnEvent(rpc_call, analyzer->ConnVal(), - val_mgr->Count(c->XID()), - val_mgr->Count(c->Program()), - val_mgr->Count(c->Version()), - val_mgr->Count(c->Proc()), - val_mgr->Count(c->CallLen()) + zeek::val_mgr->Count(c->XID()), + zeek::val_mgr->Count(c->Program()), + zeek::val_mgr->Count(c->Version()), + zeek::val_mgr->Count(c->Proc()), + zeek::val_mgr->Count(c->CallLen()) ); } @@ -366,9 +366,9 @@ void RPC_Interpreter::Event_RPC_Reply(uint32_t xid, BifEnum::rpc_status status, if ( rpc_reply ) analyzer->EnqueueConnEvent(rpc_reply, analyzer->ConnVal(), - val_mgr->Count(xid), + zeek::val_mgr->Count(xid), zeek::BifType::Enum::rpc_status->GetVal(status), - val_mgr->Count(reply_len) + zeek::val_mgr->Count(reply_len) ); } diff --git a/src/analyzer/protocol/rpc/RPC.h b/src/analyzer/protocol/rpc/RPC.h index 7d4a75bd8e..b54062c413 100644 --- a/src/analyzer/protocol/rpc/RPC.h +++ b/src/analyzer/protocol/rpc/RPC.h @@ -52,9 +52,9 @@ public: double last_time, int rpc_len); ~RPC_CallInfo(); - void AddVal(IntrusivePtr arg_v) { v = std::move(arg_v); } - const IntrusivePtr& RequestVal() const { return v; } - IntrusivePtr TakeRequestVal() { auto rv = std::move(v); return rv; } + void AddVal(zeek::ValPtr arg_v) { v = std::move(arg_v); } + const zeek::ValPtr& RequestVal() const { return v; } + zeek::ValPtr TakeRequestVal() { auto rv = std::move(v); return rv; } bool CompareRexmit(const u_char* buf, int n) const; @@ -95,7 +95,7 @@ protected: int header_len; // size of data before the arguments bool valid_call; // whether call was well-formed - IntrusivePtr v; // single (perhaps compound) value corresponding to call + zeek::ValPtr v; // single (perhaps compound) value corresponding to call }; class RPC_Interpreter { diff --git a/src/analyzer/protocol/sip/sip-analyzer.pac b/src/analyzer/protocol/sip/sip-analyzer.pac index 4a754dcd65..061e371c02 100644 --- a/src/analyzer/protocol/sip/sip-analyzer.pac +++ b/src/analyzer/protocol/sip/sip-analyzer.pac @@ -3,7 +3,7 @@ refine flow SIP_Flow += { %member{ int content_length; bool build_headers; - std::vector> headers; + std::vector headers; %} %init{ @@ -59,7 +59,7 @@ refine flow SIP_Flow += { if ( build_headers ) { - headers.push_back({AdoptRef{}, build_sip_header_val(name, value)}); + headers.push_back({zeek::AdoptRef{}, build_sip_header_val(name, value)}); } return true; @@ -68,11 +68,11 @@ refine flow SIP_Flow += { function build_sip_headers_val(): BroVal %{ static auto mime_header_list = zeek::id::find_type("mime_header_list"); - TableVal* t = new TableVal(mime_header_list); + auto* t = new zeek::TableVal(mime_header_list); for ( unsigned int i = 0; i < headers.size(); ++i ) { // index starting from 1 - auto index = val_mgr->Count(i + 1); + auto index = zeek::val_mgr->Count(i + 1); t->Assign(std::move(index), std::move(headers[i])); } @@ -84,7 +84,7 @@ refine flow SIP_Flow += { if ( sip_all_headers ) { zeek::BifEvent::enqueue_sip_all_headers(connection()->bro_analyzer(), connection()->bro_analyzer()->Conn(), - is_orig(), {AdoptRef{}, build_sip_headers_val()}); + is_orig(), {zeek::AdoptRef{}, build_sip_headers_val()}); } headers.clear(); @@ -103,18 +103,18 @@ refine flow SIP_Flow += { function build_sip_header_val(name: const_bytestring, value: const_bytestring): BroVal %{ static auto mime_header_rec = zeek::id::find_type("mime_header_rec"); - RecordVal* header_record = new RecordVal(mime_header_rec); - IntrusivePtr name_val; + auto* header_record = new zeek::RecordVal(mime_header_rec); + zeek::StringValPtr name_val; if ( name.length() > 0 ) { // Make it all uppercase. - name_val = make_intrusive(name.length(), (const char*) name.begin()); + name_val = zeek::make_intrusive(name.length(), (const char*) name.begin()); name_val->ToUpper(); } else { - name_val = val_mgr->EmptyString(); + name_val = zeek::val_mgr->EmptyString(); } header_record->Assign(0, name_val); diff --git a/src/analyzer/protocol/smb/smb-strings.pac b/src/analyzer/protocol/smb/smb-strings.pac index 2c7988b37c..3e6e8815ce 100644 --- a/src/analyzer/protocol/smb/smb-strings.pac +++ b/src/analyzer/protocol/smb/smb-strings.pac @@ -3,7 +3,7 @@ %} %code{ -IntrusivePtr binpac::SMB::SMB_Conn::uint8s_to_stringval(std::vector* data) +zeek::StringValPtr binpac::SMB::SMB_Conn::uint8s_to_stringval(std::vector* data) { int length = data->size(); auto buf = std::make_unique(length); @@ -15,7 +15,7 @@ IntrusivePtr binpac::SMB::SMB_Conn::uint8s_to_stringval(std::vectorConn(), bs); } -IntrusivePtr binpac::SMB::SMB_Conn::extract_string(SMB_string* s) +zeek::StringValPtr binpac::SMB::SMB_Conn::extract_string(SMB_string* s) { if ( s->unicode() == false ) { @@ -31,18 +31,18 @@ IntrusivePtr binpac::SMB::SMB_Conn::extract_string(SMB_string* s) if ( length > 0 && buf[length-1] == 0x00 ) length--; - return make_intrusive(length, buf.get()); + return zeek::make_intrusive(length, buf.get()); } else return uint8s_to_stringval(s->u()->s()); } -IntrusivePtr binpac::SMB::SMB_Conn::smb_string2stringval(SMB_string* s) +zeek::StringValPtr binpac::SMB::SMB_Conn::smb_string2stringval(SMB_string* s) { return extract_string(s); } -IntrusivePtr binpac::SMB::SMB_Conn::smb2_string2stringval(SMB2_string* s) +zeek::StringValPtr binpac::SMB::SMB_Conn::smb2_string2stringval(SMB2_string* s) { return uint8s_to_stringval(s->s()); } @@ -50,10 +50,10 @@ IntrusivePtr binpac::SMB::SMB_Conn::smb2_string2stringval(SMB2_string refine connection SMB_Conn += { %member{ - IntrusivePtr uint8s_to_stringval(std::vector* data); - IntrusivePtr extract_string(SMB_string* s); - IntrusivePtr smb_string2stringval(SMB_string* s); - IntrusivePtr smb2_string2stringval(SMB2_string* s); + zeek::StringValPtr uint8s_to_stringval(std::vector* data); + zeek::StringValPtr extract_string(SMB_string* s); + zeek::StringValPtr smb_string2stringval(SMB_string* s); + zeek::StringValPtr smb2_string2stringval(SMB2_string* s); SMB_unicode_string* me; %} diff --git a/src/analyzer/protocol/smb/smb-time.pac b/src/analyzer/protocol/smb/smb-time.pac index aa4d65bcb4..c658ec1ae1 100644 --- a/src/analyzer/protocol/smb/smb-time.pac +++ b/src/analyzer/protocol/smb/smb-time.pac @@ -1,21 +1,21 @@ %header{ -IntrusivePtr filetime2brotime(uint64_t ts); -IntrusivePtr time_from_lanman(SMB_time* t, SMB_date* d, uint16_t tz); +zeek::ValPtr filetime2brotime(uint64_t ts); +zeek::ValPtr time_from_lanman(SMB_time* t, SMB_date* d, uint16_t tz); -IntrusivePtr SMB_BuildMACTimes(uint64_t modify, uint64_t access, - uint64_t create, uint64_t change); +zeek::RecordValPtr SMB_BuildMACTimes(uint64_t modify, uint64_t access, + uint64_t create, uint64_t change); %} %code{ -IntrusivePtr filetime2brotime(uint64_t ts) +zeek::ValPtr filetime2brotime(uint64_t ts) { // Bro can't support times back to the 1600's // so we subtract a lot of seconds. double secs = (ts / 10000000.0L) - 11644473600.0L; - return make_intrusive(secs); + return zeek::make_intrusive(secs); } -IntrusivePtr time_from_lanman(SMB_time* t, SMB_date* d, uint16_t tz) +zeek::ValPtr time_from_lanman(SMB_time* t, SMB_date* d, uint16_t tz) { tm lTime; lTime.tm_sec = ${t.two_seconds} * 2; @@ -26,13 +26,13 @@ IntrusivePtr time_from_lanman(SMB_time* t, SMB_date* d, uint16_t tz) lTime.tm_year = 1980 + ${d.year}; lTime.tm_isdst = -1; double lResult = mktime(&lTime); - return make_intrusive(lResult + tz); + return zeek::make_intrusive(lResult + tz); } -IntrusivePtr SMB_BuildMACTimes(uint64_t modify, uint64_t access, - uint64_t create, uint64_t change) +zeek::RecordValPtr SMB_BuildMACTimes(uint64_t modify, uint64_t access, + uint64_t create, uint64_t change) { - auto r = make_intrusive(zeek::BifType::Record::SMB::MACTimes); + auto r = zeek::make_intrusive(zeek::BifType::Record::SMB::MACTimes); r->Assign(0, filetime2brotime(modify)); r->Assign(1, filetime2brotime(access)); r->Assign(2, filetime2brotime(create)); diff --git a/src/analyzer/protocol/smb/smb1-com-negotiate.pac b/src/analyzer/protocol/smb/smb1-com-negotiate.pac index 1a6ef0c3bd..4ade78c53e 100644 --- a/src/analyzer/protocol/smb/smb1-com-negotiate.pac +++ b/src/analyzer/protocol/smb/smb1-com-negotiate.pac @@ -15,7 +15,7 @@ refine connection SMB_Conn += { %{ if ( smb1_negotiate_request ) { - auto dialects = make_intrusive(zeek::id::string_vec); + auto dialects = zeek::make_intrusive(zeek::id::string_vec); for ( unsigned int i = 0; i < ${val.dialects}->size(); ++i ) { @@ -35,14 +35,14 @@ refine connection SMB_Conn += { %{ if ( smb1_negotiate_response ) { - auto response = make_intrusive(zeek::BifType::Record::SMB1::NegotiateResponse); + auto response = zeek::make_intrusive(zeek::BifType::Record::SMB1::NegotiateResponse); switch ( ${val.word_count} ) { case 0x01: { - auto core = make_intrusive(zeek::BifType::Record::SMB1::NegotiateResponseCore); - core->Assign(0, val_mgr->Count(${val.dialect_index})); + auto core = zeek::make_intrusive(zeek::BifType::Record::SMB1::NegotiateResponseCore); + core->Assign(0, zeek::val_mgr->Count(${val.dialect_index})); response->Assign(0, std::move(core)); } @@ -50,24 +50,24 @@ refine connection SMB_Conn += { case 0x0d: { - auto security = make_intrusive(zeek::BifType::Record::SMB1::NegotiateResponseSecurity); - security->Assign(0, val_mgr->Bool(${val.lanman.security_user_level})); - security->Assign(1, val_mgr->Bool(${val.lanman.security_challenge_response})); + auto security = zeek::make_intrusive(zeek::BifType::Record::SMB1::NegotiateResponseSecurity); + security->Assign(0, zeek::val_mgr->Bool(${val.lanman.security_user_level})); + security->Assign(1, zeek::val_mgr->Bool(${val.lanman.security_challenge_response})); - auto raw = make_intrusive(zeek::BifType::Record::SMB1::NegotiateRawMode); - raw->Assign(0, val_mgr->Bool(${val.lanman.raw_read_supported})); - raw->Assign(1, val_mgr->Bool(${val.lanman.raw_write_supported})); + auto raw = zeek::make_intrusive(zeek::BifType::Record::SMB1::NegotiateRawMode); + raw->Assign(0, zeek::val_mgr->Bool(${val.lanman.raw_read_supported})); + raw->Assign(1, zeek::val_mgr->Bool(${val.lanman.raw_write_supported})); - auto lanman = make_intrusive(zeek::BifType::Record::SMB1::NegotiateResponseLANMAN); - lanman->Assign(0, val_mgr->Count(${val.word_count})); - lanman->Assign(1, val_mgr->Count(${val.dialect_index})); + auto lanman = zeek::make_intrusive(zeek::BifType::Record::SMB1::NegotiateResponseLANMAN); + lanman->Assign(0, zeek::val_mgr->Count(${val.word_count})); + lanman->Assign(1, zeek::val_mgr->Count(${val.dialect_index})); lanman->Assign(2, std::move(security)); - lanman->Assign(3, val_mgr->Count(${val.lanman.max_buffer_size})); - lanman->Assign(4, val_mgr->Count(${val.lanman.max_mpx_count})); + lanman->Assign(3, zeek::val_mgr->Count(${val.lanman.max_buffer_size})); + lanman->Assign(4, zeek::val_mgr->Count(${val.lanman.max_mpx_count})); - lanman->Assign(5, val_mgr->Count(${val.lanman.max_number_vcs})); + lanman->Assign(5, zeek::val_mgr->Count(${val.lanman.max_number_vcs})); lanman->Assign(6, std::move(raw)); - lanman->Assign(7, val_mgr->Count(${val.lanman.session_key})); + lanman->Assign(7, zeek::val_mgr->Count(${val.lanman.session_key})); lanman->Assign(8, time_from_lanman(${val.lanman.server_time}, ${val.lanman.server_date}, ${val.lanman.server_tz})); lanman->Assign(9, to_stringval(${val.lanman.encryption_key})); @@ -79,45 +79,45 @@ refine connection SMB_Conn += { case 0x11: { - auto security = make_intrusive(zeek::BifType::Record::SMB1::NegotiateResponseSecurity); - security->Assign(0, val_mgr->Bool(${val.ntlm.security_user_level})); - security->Assign(1, val_mgr->Bool(${val.ntlm.security_challenge_response})); - security->Assign(2, val_mgr->Bool(${val.ntlm.security_signatures_enabled})); - security->Assign(3, val_mgr->Bool(${val.ntlm.security_signatures_required})); + auto security = zeek::make_intrusive(zeek::BifType::Record::SMB1::NegotiateResponseSecurity); + security->Assign(0, zeek::val_mgr->Bool(${val.ntlm.security_user_level})); + security->Assign(1, zeek::val_mgr->Bool(${val.ntlm.security_challenge_response})); + security->Assign(2, zeek::val_mgr->Bool(${val.ntlm.security_signatures_enabled})); + security->Assign(3, zeek::val_mgr->Bool(${val.ntlm.security_signatures_required})); - auto capabilities = make_intrusive(zeek::BifType::Record::SMB1::NegotiateCapabilities); - capabilities->Assign(0, val_mgr->Bool(${val.ntlm.capabilities_raw_mode})); - capabilities->Assign(1, val_mgr->Bool(${val.ntlm.capabilities_mpx_mode})); - capabilities->Assign(2, val_mgr->Bool(${val.ntlm.capabilities_unicode})); - capabilities->Assign(3, val_mgr->Bool(${val.ntlm.capabilities_large_files})); - capabilities->Assign(4, val_mgr->Bool(${val.ntlm.capabilities_nt_smbs})); + auto capabilities = zeek::make_intrusive(zeek::BifType::Record::SMB1::NegotiateCapabilities); + capabilities->Assign(0, zeek::val_mgr->Bool(${val.ntlm.capabilities_raw_mode})); + capabilities->Assign(1, zeek::val_mgr->Bool(${val.ntlm.capabilities_mpx_mode})); + capabilities->Assign(2, zeek::val_mgr->Bool(${val.ntlm.capabilities_unicode})); + capabilities->Assign(3, zeek::val_mgr->Bool(${val.ntlm.capabilities_large_files})); + capabilities->Assign(4, zeek::val_mgr->Bool(${val.ntlm.capabilities_nt_smbs})); - capabilities->Assign(5, val_mgr->Bool(${val.ntlm.capabilities_rpc_remote_apis})); - capabilities->Assign(6, val_mgr->Bool(${val.ntlm.capabilities_status32})); - capabilities->Assign(7, val_mgr->Bool(${val.ntlm.capabilities_level_2_oplocks})); - capabilities->Assign(8, val_mgr->Bool(${val.ntlm.capabilities_lock_and_read})); - capabilities->Assign(9, val_mgr->Bool(${val.ntlm.capabilities_nt_find})); + capabilities->Assign(5, zeek::val_mgr->Bool(${val.ntlm.capabilities_rpc_remote_apis})); + capabilities->Assign(6, zeek::val_mgr->Bool(${val.ntlm.capabilities_status32})); + capabilities->Assign(7, zeek::val_mgr->Bool(${val.ntlm.capabilities_level_2_oplocks})); + capabilities->Assign(8, zeek::val_mgr->Bool(${val.ntlm.capabilities_lock_and_read})); + capabilities->Assign(9, zeek::val_mgr->Bool(${val.ntlm.capabilities_nt_find})); - capabilities->Assign(10, val_mgr->Bool(${val.ntlm.capabilities_dfs})); - capabilities->Assign(11, val_mgr->Bool(${val.ntlm.capabilities_infolevel_passthru})); - capabilities->Assign(12, val_mgr->Bool(${val.ntlm.capabilities_large_readx})); - capabilities->Assign(13, val_mgr->Bool(${val.ntlm.capabilities_large_writex})); - capabilities->Assign(14, val_mgr->Bool(${val.ntlm.capabilities_unix})); + capabilities->Assign(10, zeek::val_mgr->Bool(${val.ntlm.capabilities_dfs})); + capabilities->Assign(11, zeek::val_mgr->Bool(${val.ntlm.capabilities_infolevel_passthru})); + capabilities->Assign(12, zeek::val_mgr->Bool(${val.ntlm.capabilities_large_readx})); + capabilities->Assign(13, zeek::val_mgr->Bool(${val.ntlm.capabilities_large_writex})); + capabilities->Assign(14, zeek::val_mgr->Bool(${val.ntlm.capabilities_unix})); - capabilities->Assign(15, val_mgr->Bool(${val.ntlm.capabilities_bulk_transfer})); - capabilities->Assign(16, val_mgr->Bool(${val.ntlm.capabilities_compressed_data})); - capabilities->Assign(17, val_mgr->Bool(${val.ntlm.capabilities_extended_security})); + capabilities->Assign(15, zeek::val_mgr->Bool(${val.ntlm.capabilities_bulk_transfer})); + capabilities->Assign(16, zeek::val_mgr->Bool(${val.ntlm.capabilities_compressed_data})); + capabilities->Assign(17, zeek::val_mgr->Bool(${val.ntlm.capabilities_extended_security})); - auto ntlm = make_intrusive(zeek::BifType::Record::SMB1::NegotiateResponseNTLM); - ntlm->Assign(0, val_mgr->Count(${val.word_count})); - ntlm->Assign(1, val_mgr->Count(${val.dialect_index})); + auto ntlm = zeek::make_intrusive(zeek::BifType::Record::SMB1::NegotiateResponseNTLM); + ntlm->Assign(0, zeek::val_mgr->Count(${val.word_count})); + ntlm->Assign(1, zeek::val_mgr->Count(${val.dialect_index})); ntlm->Assign(2, std::move(security)); - ntlm->Assign(3, val_mgr->Count(${val.ntlm.max_buffer_size})); - ntlm->Assign(4, val_mgr->Count(${val.ntlm.max_mpx_count})); + ntlm->Assign(3, zeek::val_mgr->Count(${val.ntlm.max_buffer_size})); + ntlm->Assign(4, zeek::val_mgr->Count(${val.ntlm.max_mpx_count})); - ntlm->Assign(5, val_mgr->Count(${val.ntlm.max_number_vcs})); - ntlm->Assign(6, val_mgr->Count(${val.ntlm.max_raw_size})); - ntlm->Assign(7, val_mgr->Count(${val.ntlm.session_key})); + ntlm->Assign(5, zeek::val_mgr->Count(${val.ntlm.max_number_vcs})); + ntlm->Assign(6, zeek::val_mgr->Count(${val.ntlm.max_raw_size})); + ntlm->Assign(7, zeek::val_mgr->Count(${val.ntlm.session_key})); ntlm->Assign(8, std::move(capabilities)); ntlm->Assign(9, filetime2brotime(${val.ntlm.server_time})); @@ -251,4 +251,3 @@ type SMB1_negotiate_ntlm_response(header: SMB_Header) = record { gssapi_proc : bool = $context.connection.forward_gssapi(security_blob, false) &if(capabilities_extended_security); }; - diff --git a/src/analyzer/protocol/smb/smb1-com-session-setup-andx.pac b/src/analyzer/protocol/smb/smb1-com-session-setup-andx.pac index ddc2c6ce3e..5eb97ce315 100644 --- a/src/analyzer/protocol/smb/smb1-com-session-setup-andx.pac +++ b/src/analyzer/protocol/smb/smb1-com-session-setup-andx.pac @@ -12,15 +12,15 @@ refine connection SMB_Conn += { %{ if ( smb1_session_setup_andx_request ) { - auto request = make_intrusive(zeek::BifType::Record::SMB1::SessionSetupAndXRequest); + auto request = zeek::make_intrusive(zeek::BifType::Record::SMB1::SessionSetupAndXRequest); - request->Assign(0, val_mgr->Count(${val.word_count})); + request->Assign(0, zeek::val_mgr->Count(${val.word_count})); switch ( ${val.word_count} ) { case 10: // pre NT LM 0.12 - request->Assign(1, val_mgr->Count(${val.lanman.max_buffer_size})); - request->Assign(2, val_mgr->Count(${val.lanman.max_mpx_count})); - request->Assign(3, val_mgr->Count(${val.lanman.vc_number})); - request->Assign(4, val_mgr->Count(${val.lanman.session_key})); + request->Assign(1, zeek::val_mgr->Count(${val.lanman.max_buffer_size})); + request->Assign(2, zeek::val_mgr->Count(${val.lanman.max_mpx_count})); + request->Assign(3, zeek::val_mgr->Count(${val.lanman.vc_number})); + request->Assign(4, zeek::val_mgr->Count(${val.lanman.session_key})); request->Assign(5, smb_string2stringval(${val.lanman.native_os})); request->Assign(6, smb_string2stringval(${val.lanman.native_lanman})); @@ -31,18 +31,18 @@ refine connection SMB_Conn += { break; case 12: // NT LM 0.12 with extended security { - auto capabilities = make_intrusive(zeek::BifType::Record::SMB1::SessionSetupAndXCapabilities); - capabilities->Assign(0, val_mgr->Bool(${val.ntlm_extended_security.capabilities.unicode})); - capabilities->Assign(1, val_mgr->Bool(${val.ntlm_extended_security.capabilities.large_files})); - capabilities->Assign(2, val_mgr->Bool(${val.ntlm_extended_security.capabilities.nt_smbs})); - capabilities->Assign(3, val_mgr->Bool(${val.ntlm_extended_security.capabilities.status32})); - capabilities->Assign(4, val_mgr->Bool(${val.ntlm_extended_security.capabilities.level_2_oplocks})); - capabilities->Assign(5, val_mgr->Bool(${val.ntlm_extended_security.capabilities.nt_find})); + auto capabilities = zeek::make_intrusive(zeek::BifType::Record::SMB1::SessionSetupAndXCapabilities); + capabilities->Assign(0, zeek::val_mgr->Bool(${val.ntlm_extended_security.capabilities.unicode})); + capabilities->Assign(1, zeek::val_mgr->Bool(${val.ntlm_extended_security.capabilities.large_files})); + capabilities->Assign(2, zeek::val_mgr->Bool(${val.ntlm_extended_security.capabilities.nt_smbs})); + capabilities->Assign(3, zeek::val_mgr->Bool(${val.ntlm_extended_security.capabilities.status32})); + capabilities->Assign(4, zeek::val_mgr->Bool(${val.ntlm_extended_security.capabilities.level_2_oplocks})); + capabilities->Assign(5, zeek::val_mgr->Bool(${val.ntlm_extended_security.capabilities.nt_find})); - request->Assign(1, val_mgr->Count(${val.ntlm_extended_security.max_buffer_size})); - request->Assign(2, val_mgr->Count(${val.ntlm_extended_security.max_mpx_count})); - request->Assign(3, val_mgr->Count(${val.ntlm_extended_security.vc_number})); - request->Assign(4, val_mgr->Count(${val.ntlm_extended_security.session_key})); + request->Assign(1, zeek::val_mgr->Count(${val.ntlm_extended_security.max_buffer_size})); + request->Assign(2, zeek::val_mgr->Count(${val.ntlm_extended_security.max_mpx_count})); + request->Assign(3, zeek::val_mgr->Count(${val.ntlm_extended_security.vc_number})); + request->Assign(4, zeek::val_mgr->Count(${val.ntlm_extended_security.session_key})); request->Assign(5, smb_string2stringval(${val.ntlm_extended_security.native_os})); request->Assign(6, smb_string2stringval(${val.ntlm_extended_security.native_lanman})); @@ -53,18 +53,18 @@ refine connection SMB_Conn += { case 13: // NT LM 0.12 without extended security { - auto capabilities = make_intrusive(zeek::BifType::Record::SMB1::SessionSetupAndXCapabilities); - capabilities->Assign(0, val_mgr->Bool(${val.ntlm_nonextended_security.capabilities.unicode})); - capabilities->Assign(1, val_mgr->Bool(${val.ntlm_nonextended_security.capabilities.large_files})); - capabilities->Assign(2, val_mgr->Bool(${val.ntlm_nonextended_security.capabilities.nt_smbs})); - capabilities->Assign(3, val_mgr->Bool(${val.ntlm_nonextended_security.capabilities.status32})); - capabilities->Assign(4, val_mgr->Bool(${val.ntlm_nonextended_security.capabilities.level_2_oplocks})); - capabilities->Assign(5, val_mgr->Bool(${val.ntlm_nonextended_security.capabilities.nt_find})); + auto capabilities = zeek::make_intrusive(zeek::BifType::Record::SMB1::SessionSetupAndXCapabilities); + capabilities->Assign(0, zeek::val_mgr->Bool(${val.ntlm_nonextended_security.capabilities.unicode})); + capabilities->Assign(1, zeek::val_mgr->Bool(${val.ntlm_nonextended_security.capabilities.large_files})); + capabilities->Assign(2, zeek::val_mgr->Bool(${val.ntlm_nonextended_security.capabilities.nt_smbs})); + capabilities->Assign(3, zeek::val_mgr->Bool(${val.ntlm_nonextended_security.capabilities.status32})); + capabilities->Assign(4, zeek::val_mgr->Bool(${val.ntlm_nonextended_security.capabilities.level_2_oplocks})); + capabilities->Assign(5, zeek::val_mgr->Bool(${val.ntlm_nonextended_security.capabilities.nt_find})); - request->Assign(1, val_mgr->Count(${val.ntlm_nonextended_security.max_buffer_size})); - request->Assign(2, val_mgr->Count(${val.ntlm_nonextended_security.max_mpx_count})); - request->Assign(3, val_mgr->Count(${val.ntlm_nonextended_security.vc_number})); - request->Assign(4, val_mgr->Count(${val.ntlm_nonextended_security.session_key})); + request->Assign(1, zeek::val_mgr->Count(${val.ntlm_nonextended_security.max_buffer_size})); + request->Assign(2, zeek::val_mgr->Count(${val.ntlm_nonextended_security.max_mpx_count})); + request->Assign(3, zeek::val_mgr->Count(${val.ntlm_nonextended_security.vc_number})); + request->Assign(4, zeek::val_mgr->Count(${val.ntlm_nonextended_security.session_key})); request->Assign(5, smb_string2stringval(${val.ntlm_nonextended_security.native_os})); request->Assign(6, smb_string2stringval(${val.ntlm_nonextended_security.native_lanman})); @@ -90,19 +90,19 @@ refine connection SMB_Conn += { %{ if ( smb1_session_setup_andx_response ) { - auto response = make_intrusive(zeek::BifType::Record::SMB1::SessionSetupAndXResponse); - response->Assign(0, val_mgr->Count(${val.word_count})); + auto response = zeek::make_intrusive(zeek::BifType::Record::SMB1::SessionSetupAndXResponse); + response->Assign(0, zeek::val_mgr->Count(${val.word_count})); switch ( ${val.word_count} ) { case 3: // pre NT LM 0.12 - response->Assign(1, val_mgr->Bool(${val.lanman.is_guest})); - response->Assign(2, ${val.lanman.byte_count} == 0 ? val_mgr->EmptyString() : smb_string2stringval(${val.lanman.native_os[0]})); - response->Assign(3, ${val.lanman.byte_count} == 0 ? val_mgr->EmptyString() : smb_string2stringval(${val.lanman.native_lanman[0]})); - response->Assign(4, ${val.lanman.byte_count} == 0 ? val_mgr->EmptyString() : smb_string2stringval(${val.lanman.primary_domain[0]})); + response->Assign(1, zeek::val_mgr->Bool(${val.lanman.is_guest})); + response->Assign(2, ${val.lanman.byte_count} == 0 ? zeek::val_mgr->EmptyString() : smb_string2stringval(${val.lanman.native_os[0]})); + response->Assign(3, ${val.lanman.byte_count} == 0 ? zeek::val_mgr->EmptyString() : smb_string2stringval(${val.lanman.native_lanman[0]})); + response->Assign(4, ${val.lanman.byte_count} == 0 ? zeek::val_mgr->EmptyString() : smb_string2stringval(${val.lanman.primary_domain[0]})); break; case 4: // NT LM 0.12 - response->Assign(1, val_mgr->Bool(${val.ntlm.is_guest})); + response->Assign(1, zeek::val_mgr->Bool(${val.ntlm.is_guest})); response->Assign(2, smb_string2stringval(${val.ntlm.native_os})); response->Assign(3, smb_string2stringval(${val.ntlm.native_lanman})); //response->Assign(4, smb_string2stringval(${val.ntlm.primary_domain})); diff --git a/src/analyzer/protocol/smb/smb1-com-transaction-secondary.pac b/src/analyzer/protocol/smb/smb1-com-transaction-secondary.pac index 321e1f9183..ba8d6a0af9 100644 --- a/src/analyzer/protocol/smb/smb1-com-transaction-secondary.pac +++ b/src/analyzer/protocol/smb/smb1-com-transaction-secondary.pac @@ -5,19 +5,19 @@ refine connection SMB_Conn += { if ( ! smb1_transaction_secondary_request ) return false; - auto args = make_intrusive(zeek::BifType::Record::SMB1::Trans_Sec_Args); - args->Assign(0, val_mgr->Count(${val.total_param_count})); - args->Assign(1, val_mgr->Count(${val.total_data_count})); - args->Assign(2, val_mgr->Count(${val.param_count})); - args->Assign(3, val_mgr->Count(${val.param_offset})); - args->Assign(4, val_mgr->Count(${val.param_displacement})); - args->Assign(5, val_mgr->Count(${val.data_count})); - args->Assign(6, val_mgr->Count(${val.data_offset})); - args->Assign(7, val_mgr->Count(${val.data_displacement})); + auto args = zeek::make_intrusive(zeek::BifType::Record::SMB1::Trans_Sec_Args); + args->Assign(0, zeek::val_mgr->Count(${val.total_param_count})); + args->Assign(1, zeek::val_mgr->Count(${val.total_data_count})); + args->Assign(2, zeek::val_mgr->Count(${val.param_count})); + args->Assign(3, zeek::val_mgr->Count(${val.param_offset})); + args->Assign(4, zeek::val_mgr->Count(${val.param_displacement})); + args->Assign(5, zeek::val_mgr->Count(${val.data_count})); + args->Assign(6, zeek::val_mgr->Count(${val.data_offset})); + args->Assign(7, zeek::val_mgr->Count(${val.data_displacement})); - auto parameters = make_intrusive(${val.parameters}.length(), + auto parameters = zeek::make_intrusive(${val.parameters}.length(), (const char*)${val.parameters}.data()); - IntrusivePtr payload_str; + zeek::StringValPtr payload_str; SMB1_transaction_data* payload = nullptr; if ( ${val.data_count} > 0 ) @@ -29,20 +29,20 @@ refine connection SMB_Conn += { { switch ( payload->trans_type() ) { case SMB_PIPE: - payload_str = make_intrusive(${val.data_count}, (const char*)${val.data.pipe_data}.data()); + payload_str = zeek::make_intrusive(${val.data_count}, (const char*)${val.data.pipe_data}.data()); break; case SMB_UNKNOWN: - payload_str = make_intrusive(${val.data_count}, (const char*)${val.data.unknown}.data()); + payload_str = zeek::make_intrusive(${val.data_count}, (const char*)${val.data.unknown}.data()); break; default: - payload_str = make_intrusive(${val.data_count}, (const char*)${val.data.data}.data()); + payload_str = zeek::make_intrusive(${val.data_count}, (const char*)${val.data.data}.data()); break; } } if ( ! payload_str ) { - payload_str = val_mgr->EmptyString(); + payload_str = zeek::val_mgr->EmptyString(); } zeek::BifEvent::enqueue_smb1_transaction_secondary_request(bro_analyzer(), diff --git a/src/analyzer/protocol/smb/smb1-com-transaction.pac b/src/analyzer/protocol/smb/smb1-com-transaction.pac index 221f8c5549..662f95e579 100644 --- a/src/analyzer/protocol/smb/smb1-com-transaction.pac +++ b/src/analyzer/protocol/smb/smb1-com-transaction.pac @@ -5,7 +5,7 @@ enum Trans_subcommands { }; %code{ - IntrusivePtr SMB_Conn::transaction_data_to_val(SMB1_transaction_data* payload) + zeek::StringValPtr SMB_Conn::transaction_data_to_val(SMB1_transaction_data* payload) { switch ( payload->trans_type() ) { case SMB_PIPE: @@ -17,7 +17,7 @@ enum Trans_subcommands { } assert(false); - return val_mgr->EmptyString(); + return zeek::val_mgr->EmptyString(); } %} @@ -26,7 +26,7 @@ refine connection SMB_Conn += { %member{ map is_file_a_pipe; - static IntrusivePtr transaction_data_to_val(SMB1_transaction_data* payload); + static zeek::StringValPtr transaction_data_to_val(SMB1_transaction_data* payload); %} function get_is_file_a_pipe(id: uint16): bool @@ -53,14 +53,14 @@ refine connection SMB_Conn += { if ( ! smb1_transaction_request ) return false; - auto parameters = make_intrusive(${val.parameters}.length(), - (const char*)${val.parameters}.data()); - IntrusivePtr payload_str; + auto parameters = zeek::make_intrusive(${val.parameters}.length(), + (const char*)${val.parameters}.data()); + zeek::StringValPtr payload_str; if ( ${val.data_count} > 0 ) payload_str = transaction_data_to_val(${val.data}); else - payload_str = val_mgr->EmptyString(); + payload_str = zeek::val_mgr->EmptyString(); zeek::BifEvent::enqueue_smb1_transaction_request(bro_analyzer(), bro_analyzer()->Conn(), @@ -78,14 +78,14 @@ refine connection SMB_Conn += { if ( ! smb1_transaction_response ) return false; - auto parameters = make_intrusive(${val.parameters}.length(), - (const char*)${val.parameters}.data()); - IntrusivePtr payload_str; + auto parameters = zeek::make_intrusive(${val.parameters}.length(), + (const char*)${val.parameters}.data()); + zeek::StringValPtr payload_str; if ( ${val.data_count} > 0 ) payload_str = transaction_data_to_val(${val.data[0]}); else - payload_str = val_mgr->EmptyString(); + payload_str = zeek::val_mgr->EmptyString(); zeek::BifEvent::enqueue_smb1_transaction_response(bro_analyzer(), bro_analyzer()->Conn(), diff --git a/src/analyzer/protocol/smb/smb1-com-transaction2-secondary.pac b/src/analyzer/protocol/smb/smb1-com-transaction2-secondary.pac index a3a65c8367..832092274c 100644 --- a/src/analyzer/protocol/smb/smb1-com-transaction2-secondary.pac +++ b/src/analyzer/protocol/smb/smb1-com-transaction2-secondary.pac @@ -5,19 +5,19 @@ refine connection SMB_Conn += { if ( ! smb1_transaction2_secondary_request ) return false; - auto args = make_intrusive(zeek::BifType::Record::SMB1::Trans2_Sec_Args); - args->Assign(0, val_mgr->Count(${val.total_param_count})); - args->Assign(1, val_mgr->Count(${val.total_data_count})); - args->Assign(2, val_mgr->Count(${val.param_count})); - args->Assign(3, val_mgr->Count(${val.param_offset})); - args->Assign(4, val_mgr->Count(${val.param_displacement})); - args->Assign(5, val_mgr->Count(${val.data_count})); - args->Assign(6, val_mgr->Count(${val.data_offset})); - args->Assign(7, val_mgr->Count(${val.data_displacement})); - args->Assign(8, val_mgr->Count(${val.FID})); + auto args = zeek::make_intrusive(zeek::BifType::Record::SMB1::Trans2_Sec_Args); + args->Assign(0, zeek::val_mgr->Count(${val.total_param_count})); + args->Assign(1, zeek::val_mgr->Count(${val.total_data_count})); + args->Assign(2, zeek::val_mgr->Count(${val.param_count})); + args->Assign(3, zeek::val_mgr->Count(${val.param_offset})); + args->Assign(4, zeek::val_mgr->Count(${val.param_displacement})); + args->Assign(5, zeek::val_mgr->Count(${val.data_count})); + args->Assign(6, zeek::val_mgr->Count(${val.data_offset})); + args->Assign(7, zeek::val_mgr->Count(${val.data_displacement})); + args->Assign(8, zeek::val_mgr->Count(${val.FID})); - auto parameters = make_intrusive(${val.parameters}.length(), (const char*)${val.parameters}.data()); - auto payload = make_intrusive(${val.data}.length(), (const char*)${val.data}.data()); + auto parameters = zeek::make_intrusive(${val.parameters}.length(), (const char*)${val.parameters}.data()); + auto payload = zeek::make_intrusive(${val.data}.length(), (const char*)${val.data}.data()); zeek::BifEvent::enqueue_smb1_transaction2_secondary_request(bro_analyzer(), bro_analyzer()->Conn(), diff --git a/src/analyzer/protocol/smb/smb1-com-transaction2.pac b/src/analyzer/protocol/smb/smb1-com-transaction2.pac index b13865d989..d831ea70ca 100644 --- a/src/analyzer/protocol/smb/smb1-com-transaction2.pac +++ b/src/analyzer/protocol/smb/smb1-com-transaction2.pac @@ -24,19 +24,19 @@ refine connection SMB_Conn += { %{ if ( smb1_transaction2_request ) { - auto args = make_intrusive(zeek::BifType::Record::SMB1::Trans2_Args); - args->Assign(0, val_mgr->Count(${val.total_param_count})); - args->Assign(1, val_mgr->Count(${val.total_data_count})); - args->Assign(2, val_mgr->Count(${val.max_param_count})); - args->Assign(3, val_mgr->Count(${val.max_data_count})); - args->Assign(4, val_mgr->Count(${val.max_setup_count})); - args->Assign(5, val_mgr->Count(${val.flags})); - args->Assign(6, val_mgr->Count(${val.timeout})); - args->Assign(7, val_mgr->Count(${val.param_count})); - args->Assign(8, val_mgr->Count(${val.param_offset})); - args->Assign(9, val_mgr->Count(${val.data_count})); - args->Assign(10, val_mgr->Count(${val.data_offset})); - args->Assign(11, val_mgr->Count(${val.setup_count})); + auto args = zeek::make_intrusive(zeek::BifType::Record::SMB1::Trans2_Args); + args->Assign(0, zeek::val_mgr->Count(${val.total_param_count})); + args->Assign(1, zeek::val_mgr->Count(${val.total_data_count})); + args->Assign(2, zeek::val_mgr->Count(${val.max_param_count})); + args->Assign(3, zeek::val_mgr->Count(${val.max_data_count})); + args->Assign(4, zeek::val_mgr->Count(${val.max_setup_count})); + args->Assign(5, zeek::val_mgr->Count(${val.flags})); + args->Assign(6, zeek::val_mgr->Count(${val.timeout})); + args->Assign(7, zeek::val_mgr->Count(${val.param_count})); + args->Assign(8, zeek::val_mgr->Count(${val.param_offset})); + args->Assign(9, zeek::val_mgr->Count(${val.data_count})); + args->Assign(10, zeek::val_mgr->Count(${val.data_offset})); + args->Assign(11, zeek::val_mgr->Count(${val.setup_count})); zeek::BifEvent::enqueue_smb1_transaction2_request(bro_analyzer(), bro_analyzer()->Conn(), @@ -131,17 +131,17 @@ refine connection SMB_Conn += { %{ if ( smb1_trans2_find_first2_request ) { - auto result = make_intrusive(zeek::BifType::Record::SMB1::Find_First2_Request_Args); - result->Assign(0, val_mgr->Count(${val.search_attrs})); - result->Assign(1, val_mgr->Count(${val.search_count})); - result->Assign(2, val_mgr->Count(${val.flags})); - result->Assign(3, val_mgr->Count(${val.info_level})); - result->Assign(4, val_mgr->Count(${val.search_storage_type})); + auto result = zeek::make_intrusive(zeek::BifType::Record::SMB1::Find_First2_Request_Args); + result->Assign(0, zeek::val_mgr->Count(${val.search_attrs})); + result->Assign(1, zeek::val_mgr->Count(${val.search_count})); + result->Assign(2, zeek::val_mgr->Count(${val.flags})); + result->Assign(3, zeek::val_mgr->Count(${val.info_level})); + result->Assign(4, zeek::val_mgr->Count(${val.search_storage_type})); result->Assign(5, smb_string2stringval(${val.file_name})); zeek::BifEvent::enqueue_smb1_trans2_find_first2_request(bro_analyzer(), - bro_analyzer()->Conn(), - SMBHeaderVal(header), - std::move(result)); + bro_analyzer()->Conn(), + SMBHeaderVal(header), + std::move(result)); } return true; diff --git a/src/analyzer/protocol/smb/smb1-com-tree-connect-andx.pac b/src/analyzer/protocol/smb/smb1-com-tree-connect-andx.pac index 914aef838b..14e11cf8cd 100644 --- a/src/analyzer/protocol/smb/smb1-com-tree-connect-andx.pac +++ b/src/analyzer/protocol/smb/smb1-com-tree-connect-andx.pac @@ -26,7 +26,7 @@ refine connection SMB_Conn += { std::move(service_string), ${val.byte_count} > ${val.service.a}->size() ? smb_string2stringval(${val.native_file_system[0]}) : - val_mgr->EmptyString()); + zeek::val_mgr->EmptyString()); return true; %} diff --git a/src/analyzer/protocol/smb/smb1-protocol.pac b/src/analyzer/protocol/smb/smb1-protocol.pac index 63e6d87e87..bd399ca183 100644 --- a/src/analyzer/protocol/smb/smb1-protocol.pac +++ b/src/analyzer/protocol/smb/smb1-protocol.pac @@ -3,13 +3,13 @@ %} %header{ - IntrusivePtr SMBHeaderVal(SMB_Header* hdr); + zeek::RecordValPtr SMBHeaderVal(SMB_Header* hdr); %} %code{ - IntrusivePtr SMBHeaderVal(SMB_Header* hdr) + zeek::RecordValPtr SMBHeaderVal(SMB_Header* hdr) { - auto r = make_intrusive(zeek::BifType::Record::SMB1::Header); + auto r = zeek::make_intrusive(zeek::BifType::Record::SMB1::Header); //unsigned int status = 0; // @@ -25,14 +25,14 @@ // { // do nothing // } - r->Assign(0, val_mgr->Count(${hdr.command})); - r->Assign(1, val_mgr->Count(${hdr.status})); - r->Assign(2, val_mgr->Count(${hdr.flags})); - r->Assign(3, val_mgr->Count(${hdr.flags2})); - r->Assign(4, val_mgr->Count(${hdr.tid})); - r->Assign(5, val_mgr->Count(${hdr.pid})); - r->Assign(6, val_mgr->Count(${hdr.uid})); - r->Assign(7, val_mgr->Count(${hdr.mid})); + r->Assign(0, zeek::val_mgr->Count(${hdr.command})); + r->Assign(1, zeek::val_mgr->Count(${hdr.status})); + r->Assign(2, zeek::val_mgr->Count(${hdr.flags})); + r->Assign(3, zeek::val_mgr->Count(${hdr.flags2})); + r->Assign(4, zeek::val_mgr->Count(${hdr.tid})); + r->Assign(5, zeek::val_mgr->Count(${hdr.pid})); + r->Assign(6, zeek::val_mgr->Count(${hdr.uid})); + r->Assign(7, zeek::val_mgr->Count(${hdr.mid})); return r; } diff --git a/src/analyzer/protocol/smb/smb2-com-close.pac b/src/analyzer/protocol/smb/smb2-com-close.pac index db6b24b9b4..103572544d 100644 --- a/src/analyzer/protocol/smb/smb2-com-close.pac +++ b/src/analyzer/protocol/smb/smb2-com-close.pac @@ -20,10 +20,10 @@ refine connection SMB_Conn += { %{ if ( smb2_close_response ) { - auto resp = make_intrusive(zeek::BifType::Record::SMB2::CloseResponse); + auto resp = zeek::make_intrusive(zeek::BifType::Record::SMB2::CloseResponse); - resp->Assign(0, val_mgr->Count(${val.alloc_size})); - resp->Assign(1, val_mgr->Count(${val.eof})); + resp->Assign(0, zeek::val_mgr->Count(${val.alloc_size})); + resp->Assign(1, zeek::val_mgr->Count(${val.eof})); resp->Assign(2, SMB_BuildMACTimes(${val.last_write_time}, ${val.last_access_time}, ${val.creation_time}, diff --git a/src/analyzer/protocol/smb/smb2-com-create.pac b/src/analyzer/protocol/smb/smb2-com-create.pac index ac9feb22f0..20cc31def8 100644 --- a/src/analyzer/protocol/smb/smb2-com-create.pac +++ b/src/analyzer/protocol/smb/smb2-com-create.pac @@ -16,10 +16,10 @@ refine connection SMB_Conn += { if ( smb2_create_request ) { - auto requestinfo = make_intrusive(zeek::BifType::Record::SMB2::CreateRequest); + auto requestinfo = zeek::make_intrusive(zeek::BifType::Record::SMB2::CreateRequest); requestinfo->Assign(0, std::move(filename)); - requestinfo->Assign(1, val_mgr->Count(${val.disposition})); - requestinfo->Assign(2, val_mgr->Count(${val.create_options})); + requestinfo->Assign(1, zeek::val_mgr->Count(${val.disposition})); + requestinfo->Assign(2, zeek::val_mgr->Count(${val.create_options})); zeek::BifEvent::enqueue_smb2_create_request(bro_analyzer(), bro_analyzer()->Conn(), BuildSMB2HeaderVal(h), @@ -33,19 +33,19 @@ refine connection SMB_Conn += { %{ if ( smb2_create_response ) { - auto responseinfo = make_intrusive(zeek::BifType::Record::SMB2::CreateResponse); + auto responseinfo = zeek::make_intrusive(zeek::BifType::Record::SMB2::CreateResponse); responseinfo->Assign(0, BuildSMB2GUID(${val.file_id})); - responseinfo->Assign(1, val_mgr->Count(${val.eof})); + responseinfo->Assign(1, zeek::val_mgr->Count(${val.eof})); responseinfo->Assign(2, SMB_BuildMACTimes(${val.last_write_time}, ${val.last_access_time}, ${val.creation_time}, ${val.change_time})); responseinfo->Assign(3, smb2_file_attrs_to_bro(${val.file_attrs})); - responseinfo->Assign(4, val_mgr->Count(${val.create_action})); + responseinfo->Assign(4, zeek::val_mgr->Count(${val.create_action})); zeek::BifEvent::enqueue_smb2_create_response(bro_analyzer(), bro_analyzer()->Conn(), BuildSMB2HeaderVal(h), - std::move(responseinfo)); + std::move(responseinfo)); } return true; diff --git a/src/analyzer/protocol/smb/smb2-com-negotiate.pac b/src/analyzer/protocol/smb/smb2-com-negotiate.pac index cc639088f2..d99fa6a869 100644 --- a/src/analyzer/protocol/smb/smb2-com-negotiate.pac +++ b/src/analyzer/protocol/smb/smb2-com-negotiate.pac @@ -22,10 +22,10 @@ refine connection SMB_Conn += { %{ if ( smb2_negotiate_request ) { - auto dialects = make_intrusive(zeek::id::index_vec); + auto dialects = zeek::make_intrusive(zeek::id::index_vec); for ( unsigned int i = 0; i < ${val.dialects}->size(); ++i ) - dialects->Assign(i, val_mgr->Count((*${val.dialects})[i])); + dialects->Assign(i, zeek::val_mgr->Count((*${val.dialects})[i])); zeek::BifEvent::enqueue_smb2_negotiate_request(bro_analyzer(), bro_analyzer()->Conn(), BuildSMB2HeaderVal(h), @@ -39,16 +39,16 @@ refine connection SMB_Conn += { %{ if ( smb2_negotiate_response ) { - auto nr = make_intrusive(zeek::BifType::Record::SMB2::NegotiateResponse); + auto nr = zeek::make_intrusive(zeek::BifType::Record::SMB2::NegotiateResponse); - nr->Assign(0, val_mgr->Count(${val.dialect_revision})); - nr->Assign(1, val_mgr->Count(${val.security_mode})); + nr->Assign(0, zeek::val_mgr->Count(${val.dialect_revision})); + nr->Assign(1, zeek::val_mgr->Count(${val.security_mode})); nr->Assign(2, BuildSMB2GUID(${val.server_guid})); nr->Assign(3, filetime2brotime(${val.system_time})); nr->Assign(4, filetime2brotime(${val.server_start_time})); - nr->Assign(5, val_mgr->Count(${val.negotiate_context_count})); + nr->Assign(5, zeek::val_mgr->Count(${val.negotiate_context_count})); - auto cv = make_intrusive(zeek::BifType::Vector::SMB2::NegotiateContextValues); + auto cv = zeek::make_intrusive(zeek::BifType::Vector::SMB2::NegotiateContextValues); if ( ${val.dialect_revision} == 0x0311 && ${val.negotiate_context_count} > 0 ) { @@ -61,8 +61,8 @@ refine connection SMB_Conn += { nr->Assign(6, std::move(cv)); zeek::BifEvent::enqueue_smb2_negotiate_response(bro_analyzer(), bro_analyzer()->Conn(), - BuildSMB2HeaderVal(h), - std::move(nr)); + BuildSMB2HeaderVal(h), + std::move(nr)); } return true; diff --git a/src/analyzer/protocol/smb/smb2-com-session-setup.pac b/src/analyzer/protocol/smb/smb2-com-session-setup.pac index 5b4b5f27e8..a052d1944f 100644 --- a/src/analyzer/protocol/smb/smb2-com-session-setup.pac +++ b/src/analyzer/protocol/smb/smb2-com-session-setup.pac @@ -4,8 +4,8 @@ refine connection SMB_Conn += { %{ if ( smb2_session_setup_request ) { - auto req = make_intrusive(zeek::BifType::Record::SMB2::SessionSetupRequest); - req->Assign(0, val_mgr->Count(${val.security_mode})); + auto req = zeek::make_intrusive(zeek::BifType::Record::SMB2::SessionSetupRequest); + req->Assign(0, zeek::val_mgr->Count(${val.security_mode})); zeek::BifEvent::enqueue_smb2_session_setup_request(bro_analyzer(), bro_analyzer()->Conn(), @@ -20,12 +20,12 @@ refine connection SMB_Conn += { %{ if ( smb2_session_setup_response ) { - auto flags = make_intrusive(zeek::BifType::Record::SMB2::SessionSetupFlags); - flags->Assign(0, val_mgr->Bool(${val.flag_guest})); - flags->Assign(1, val_mgr->Bool(${val.flag_anonymous})); - flags->Assign(2, val_mgr->Bool(${val.flag_encrypt})); + auto flags = zeek::make_intrusive(zeek::BifType::Record::SMB2::SessionSetupFlags); + flags->Assign(0, zeek::val_mgr->Bool(${val.flag_guest})); + flags->Assign(1, zeek::val_mgr->Bool(${val.flag_anonymous})); + flags->Assign(2, zeek::val_mgr->Bool(${val.flag_encrypt})); - auto resp = make_intrusive(zeek::BifType::Record::SMB2::SessionSetupResponse); + auto resp = zeek::make_intrusive(zeek::BifType::Record::SMB2::SessionSetupResponse); resp->Assign(0, std::move(flags)); zeek::BifEvent::enqueue_smb2_session_setup_response(bro_analyzer(), diff --git a/src/analyzer/protocol/smb/smb2-com-set-info.pac b/src/analyzer/protocol/smb/smb2-com-set-info.pac index a1c13e61b6..10e5899b2a 100644 --- a/src/analyzer/protocol/smb/smb2-com-set-info.pac +++ b/src/analyzer/protocol/smb/smb2-com-set-info.pac @@ -93,11 +93,11 @@ refine connection SMB_Conn += { %{ if ( smb2_file_fullea ) { - auto eas = make_intrusive(zeek::BifType::Vector::SMB2::FileEAs); + auto eas = zeek::make_intrusive(zeek::BifType::Vector::SMB2::FileEAs); for ( auto i = 0u; i < ${val.ea_vector}->size(); ++i ) { - auto r = make_intrusive(zeek::BifType::Record::SMB2::FileEA); + auto r = zeek::make_intrusive(zeek::BifType::Record::SMB2::FileEA); r->Assign(0, smb2_string2stringval(${val.ea_vector[i].ea_name})); r->Assign(1, smb2_string2stringval(${val.ea_vector[i].ea_value})); @@ -192,13 +192,13 @@ refine connection SMB_Conn += { %{ if ( smb2_file_fscontrol ) { - auto r = make_intrusive(zeek::BifType::Record::SMB2::Fscontrol); - r->Assign(0, val_mgr->Int(${val.free_space_start_filtering})); - r->Assign(1, val_mgr->Int(${val.free_space_start_threshold})); - r->Assign(2, val_mgr->Int(${val.free_space_stop_filtering})); - r->Assign(3, val_mgr->Count(${val.default_quota_threshold})); - r->Assign(4, val_mgr->Count(${val.default_quota_limit})); - r->Assign(5, val_mgr->Count(${val.file_system_control_flags})); + auto r = zeek::make_intrusive(zeek::BifType::Record::SMB2::Fscontrol); + r->Assign(0, zeek::val_mgr->Int(${val.free_space_start_filtering})); + r->Assign(1, zeek::val_mgr->Int(${val.free_space_start_threshold})); + r->Assign(2, zeek::val_mgr->Int(${val.free_space_stop_filtering})); + r->Assign(3, zeek::val_mgr->Count(${val.default_quota_threshold})); + r->Assign(4, zeek::val_mgr->Count(${val.default_quota_limit})); + r->Assign(5, zeek::val_mgr->Count(${val.file_system_control_flags})); zeek::BifEvent::enqueue_smb2_file_fscontrol(bro_analyzer(), bro_analyzer()->Conn(), @@ -268,7 +268,7 @@ type SMB2_file_fullea_info_element = record { flags : uint8; ea_name_length : uint8; ea_value_length : uint16; - ea_name : SMB2_string(ea_name_length); + ea_name : SMB2_string(ea_name_length); ea_value : SMB2_string(ea_value_length); pad_to_next : padding to next_entry_offset; } &let { @@ -276,7 +276,7 @@ type SMB2_file_fullea_info_element = record { }; type SMB2_file_fullea_info(sir: SMB2_set_info_request) = record { - ea_vector : SMB2_file_fullea_info_element[] &until($element.next_offset == 0); + ea_vector : SMB2_file_fullea_info_element[] &until($element.next_offset == 0); } &let { proc: bool = $context.connection.proc_smb2_set_info_request_file_fullea(this); }; diff --git a/src/analyzer/protocol/smb/smb2-com-transform-header.pac b/src/analyzer/protocol/smb/smb2-com-transform-header.pac index a261f58d42..e24c6d5ed8 100644 --- a/src/analyzer/protocol/smb/smb2-com-transform-header.pac +++ b/src/analyzer/protocol/smb/smb2-com-transform-header.pac @@ -4,12 +4,12 @@ refine connection SMB_Conn += { %{ if ( smb2_transform_header ) { - auto r = make_intrusive(zeek::BifType::Record::SMB2::Transform_header); + auto r = zeek::make_intrusive(zeek::BifType::Record::SMB2::Transform_header); r->Assign(0, to_stringval(${hdr.signature})); r->Assign(1, to_stringval(${hdr.nonce})); - r->Assign(2, val_mgr->Count(${hdr.orig_msg_size})); - r->Assign(3, val_mgr->Count(${hdr.flags})); - r->Assign(4, val_mgr->Count(${hdr.session_id})); + r->Assign(2, zeek::val_mgr->Count(${hdr.orig_msg_size})); + r->Assign(3, zeek::val_mgr->Count(${hdr.flags})); + r->Assign(4, zeek::val_mgr->Count(${hdr.session_id})); zeek::BifEvent::enqueue_smb2_transform_header(bro_analyzer(), bro_analyzer()->Conn(), diff --git a/src/analyzer/protocol/smb/smb2-com-tree-connect.pac b/src/analyzer/protocol/smb/smb2-com-tree-connect.pac index 63de3c1ccb..b89265506a 100644 --- a/src/analyzer/protocol/smb/smb2-com-tree-connect.pac +++ b/src/analyzer/protocol/smb/smb2-com-tree-connect.pac @@ -18,13 +18,13 @@ refine connection SMB_Conn += { if ( smb2_tree_connect_response ) { - auto resp = make_intrusive(zeek::BifType::Record::SMB2::TreeConnectResponse); - resp->Assign(0, val_mgr->Count(${val.share_type})); + auto resp = zeek::make_intrusive(zeek::BifType::Record::SMB2::TreeConnectResponse); + resp->Assign(0, zeek::val_mgr->Count(${val.share_type})); zeek::BifEvent::enqueue_smb2_tree_connect_response(bro_analyzer(), bro_analyzer()->Conn(), BuildSMB2HeaderVal(header), - std::move(resp)); + std::move(resp)); } return true; @@ -54,4 +54,3 @@ type SMB2_tree_connect_response(header: SMB2_Header) = record { } &let { proc: bool = $context.connection.proc_smb2_tree_connect_response(header, this); }; - diff --git a/src/analyzer/protocol/smb/smb2-protocol.pac b/src/analyzer/protocol/smb/smb2-protocol.pac index 3df04b354d..9f12838037 100644 --- a/src/analyzer/protocol/smb/smb2-protocol.pac +++ b/src/analyzer/protocol/smb/smb2-protocol.pac @@ -2,78 +2,78 @@ # http://msdn.microsoft.com/en-us/library/cc246497(v=PROT.13).aspx %header{ -IntrusivePtr BuildSMB2HeaderVal(SMB2_Header* hdr); -IntrusivePtr BuildSMB2GUID(SMB2_guid* file_id); -IntrusivePtr smb2_file_attrs_to_bro(SMB2_file_attributes* val); -IntrusivePtr BuildSMB2ContextVal(SMB3_negotiate_context_value* ncv); +zeek::RecordValPtr BuildSMB2HeaderVal(SMB2_Header* hdr); +zeek::RecordValPtr BuildSMB2GUID(SMB2_guid* file_id); +zeek::RecordValPtr smb2_file_attrs_to_bro(SMB2_file_attributes* val); +zeek::RecordValPtr BuildSMB2ContextVal(SMB3_negotiate_context_value* ncv); %} %code{ -IntrusivePtr BuildSMB2HeaderVal(SMB2_Header* hdr) +zeek::RecordValPtr BuildSMB2HeaderVal(SMB2_Header* hdr) { - auto r = make_intrusive(zeek::BifType::Record::SMB2::Header); - r->Assign(0, val_mgr->Count(${hdr.credit_charge})); - r->Assign(1, val_mgr->Count(${hdr.status})); - r->Assign(2, val_mgr->Count(${hdr.command})); - r->Assign(3, val_mgr->Count(${hdr.credits})); - r->Assign(4, val_mgr->Count(${hdr.flags})); - r->Assign(5, val_mgr->Count(${hdr.message_id})); - r->Assign(6, val_mgr->Count(${hdr.process_id})); - r->Assign(7, val_mgr->Count(${hdr.tree_id})); - r->Assign(8, val_mgr->Count(${hdr.session_id})); + auto r = zeek::make_intrusive(zeek::BifType::Record::SMB2::Header); + r->Assign(0, zeek::val_mgr->Count(${hdr.credit_charge})); + r->Assign(1, zeek::val_mgr->Count(${hdr.status})); + r->Assign(2, zeek::val_mgr->Count(${hdr.command})); + r->Assign(3, zeek::val_mgr->Count(${hdr.credits})); + r->Assign(4, zeek::val_mgr->Count(${hdr.flags})); + r->Assign(5, zeek::val_mgr->Count(${hdr.message_id})); + r->Assign(6, zeek::val_mgr->Count(${hdr.process_id})); + r->Assign(7, zeek::val_mgr->Count(${hdr.tree_id})); + r->Assign(8, zeek::val_mgr->Count(${hdr.session_id})); r->Assign(9, to_stringval(${hdr.signature})); return r; } -IntrusivePtr BuildSMB2GUID(SMB2_guid* file_id) +zeek::RecordValPtr BuildSMB2GUID(SMB2_guid* file_id) { - auto r = make_intrusive(zeek::BifType::Record::SMB2::GUID); - r->Assign(0, val_mgr->Count(${file_id.persistent})); - r->Assign(1, val_mgr->Count(${file_id._volatile})); + auto r = zeek::make_intrusive(zeek::BifType::Record::SMB2::GUID); + r->Assign(0, zeek::val_mgr->Count(${file_id.persistent})); + r->Assign(1, zeek::val_mgr->Count(${file_id._volatile})); return r; } -IntrusivePtr smb2_file_attrs_to_bro(SMB2_file_attributes* val) +zeek::RecordValPtr smb2_file_attrs_to_bro(SMB2_file_attributes* val) { - auto r = make_intrusive(zeek::BifType::Record::SMB2::FileAttrs); - r->Assign(0, val_mgr->Bool(${val.read_only})); - r->Assign(1, val_mgr->Bool(${val.hidden})); - r->Assign(2, val_mgr->Bool(${val.system})); - r->Assign(3, val_mgr->Bool(${val.directory})); - r->Assign(4, val_mgr->Bool(${val.archive})); - r->Assign(5, val_mgr->Bool(${val.normal})); - r->Assign(6, val_mgr->Bool(${val.temporary})); - r->Assign(7, val_mgr->Bool(${val.sparse_file})); - r->Assign(8, val_mgr->Bool(${val.reparse_point})); - r->Assign(9, val_mgr->Bool(${val.compressed})); - r->Assign(10, val_mgr->Bool(${val.offline})); - r->Assign(11, val_mgr->Bool(${val.not_content_indexed})); - r->Assign(12, val_mgr->Bool(${val.encrypted})); - r->Assign(13, val_mgr->Bool(${val.integrity_stream})); - r->Assign(14, val_mgr->Bool(${val.no_scrub_data})); + auto r = zeek::make_intrusive(zeek::BifType::Record::SMB2::FileAttrs); + r->Assign(0, zeek::val_mgr->Bool(${val.read_only})); + r->Assign(1, zeek::val_mgr->Bool(${val.hidden})); + r->Assign(2, zeek::val_mgr->Bool(${val.system})); + r->Assign(3, zeek::val_mgr->Bool(${val.directory})); + r->Assign(4, zeek::val_mgr->Bool(${val.archive})); + r->Assign(5, zeek::val_mgr->Bool(${val.normal})); + r->Assign(6, zeek::val_mgr->Bool(${val.temporary})); + r->Assign(7, zeek::val_mgr->Bool(${val.sparse_file})); + r->Assign(8, zeek::val_mgr->Bool(${val.reparse_point})); + r->Assign(9, zeek::val_mgr->Bool(${val.compressed})); + r->Assign(10, zeek::val_mgr->Bool(${val.offline})); + r->Assign(11, zeek::val_mgr->Bool(${val.not_content_indexed})); + r->Assign(12, zeek::val_mgr->Bool(${val.encrypted})); + r->Assign(13, zeek::val_mgr->Bool(${val.integrity_stream})); + r->Assign(14, zeek::val_mgr->Bool(${val.no_scrub_data})); return r; } -IntrusivePtr BuildSMB2ContextVal(SMB3_negotiate_context_value* ncv) +zeek::RecordValPtr BuildSMB2ContextVal(SMB3_negotiate_context_value* ncv) { - auto r = make_intrusive(zeek::BifType::Record::SMB2::NegotiateContextValue); + auto r = zeek::make_intrusive(zeek::BifType::Record::SMB2::NegotiateContextValue); - r->Assign(0, val_mgr->Count(${ncv.context_type})); - r->Assign(1, val_mgr->Count(${ncv.data_length})); + r->Assign(0, zeek::val_mgr->Count(${ncv.context_type})); + r->Assign(1, zeek::val_mgr->Count(${ncv.data_length})); switch ( ${ncv.context_type} ) { case SMB2_PREAUTH_INTEGRITY_CAPABILITIES: { - auto rpreauth = make_intrusive(zeek::BifType::Record::SMB2::PreAuthIntegrityCapabilities); - rpreauth->Assign(0, val_mgr->Count(${ncv.preauth_integrity_capabilities.hash_alg_count})); - rpreauth->Assign(1, val_mgr->Count(${ncv.preauth_integrity_capabilities.salt_length})); + auto rpreauth = zeek::make_intrusive(zeek::BifType::Record::SMB2::PreAuthIntegrityCapabilities); + rpreauth->Assign(0, zeek::val_mgr->Count(${ncv.preauth_integrity_capabilities.hash_alg_count})); + rpreauth->Assign(1, zeek::val_mgr->Count(${ncv.preauth_integrity_capabilities.salt_length})); - auto ha = make_intrusive(zeek::id::index_vec); + auto ha = zeek::make_intrusive(zeek::id::index_vec); for ( int i = 0; i < ${ncv.preauth_integrity_capabilities.hash_alg_count}; ++i ) { const auto& vec = *${ncv.preauth_integrity_capabilities.hash_alg}; - ha->Assign(i, val_mgr->Count(vec[i])); + ha->Assign(i, zeek::val_mgr->Count(vec[i])); } rpreauth->Assign(2, std::move(ha)); @@ -84,15 +84,15 @@ IntrusivePtr BuildSMB2ContextVal(SMB3_negotiate_context_value* ncv) case SMB2_ENCRYPTION_CAPABILITIES: { - auto rencr = make_intrusive(zeek::BifType::Record::SMB2::EncryptionCapabilities); - rencr->Assign(0, val_mgr->Count(${ncv.encryption_capabilities.cipher_count})); + auto rencr = zeek::make_intrusive(zeek::BifType::Record::SMB2::EncryptionCapabilities); + rencr->Assign(0, zeek::val_mgr->Count(${ncv.encryption_capabilities.cipher_count})); - auto c = make_intrusive(zeek::id::index_vec); + auto c = zeek::make_intrusive(zeek::id::index_vec); for ( int i = 0; i < ${ncv.encryption_capabilities.cipher_count}; ++i ) { const auto& vec = *${ncv.encryption_capabilities.ciphers}; - c->Assign(i, val_mgr->Count(vec[i])); + c->Assign(i, zeek::val_mgr->Count(vec[i])); } rencr->Assign(1, std::move(c)); @@ -102,15 +102,15 @@ IntrusivePtr BuildSMB2ContextVal(SMB3_negotiate_context_value* ncv) case SMB2_COMPRESSION_CAPABILITIES: { - auto rcomp = make_intrusive(zeek::BifType::Record::SMB2::CompressionCapabilities); - rcomp->Assign(0, val_mgr->Count(${ncv.compression_capabilities.alg_count})); + auto rcomp = zeek::make_intrusive(zeek::BifType::Record::SMB2::CompressionCapabilities); + rcomp->Assign(0, zeek::val_mgr->Count(${ncv.compression_capabilities.alg_count})); - auto c = make_intrusive(zeek::id::index_vec); + auto c = zeek::make_intrusive(zeek::id::index_vec); for ( int i = 0; i < ${ncv.compression_capabilities.alg_count}; ++i ) { const auto& vec = *${ncv.compression_capabilities.algs}; - c->Assign(i, val_mgr->Count(vec[i])); + c->Assign(i, zeek::val_mgr->Count(vec[i])); } rcomp->Assign(1, std::move(c)); diff --git a/src/analyzer/protocol/smtp/SMTP.cc b/src/analyzer/protocol/smtp/SMTP.cc index d3933f91c6..fbe584e2ae 100644 --- a/src/analyzer/protocol/smtp/SMTP.cc +++ b/src/analyzer/protocol/smtp/SMTP.cc @@ -183,7 +183,7 @@ void SMTP_Analyzer::ProcessLine(int length, const char* line, bool orig) delete line_after_gap; line_after_gap = - new BroString((const u_char *) line, length, true); + new zeek::String((const u_char *) line, length, true); } else if ( state == SMTP_IN_DATA && line[0] == '.' && length == 1 ) @@ -221,8 +221,8 @@ void SMTP_Analyzer::ProcessLine(int length, const char* line, bool orig) { EnqueueConnEvent(smtp_data, ConnVal(), - val_mgr->Bool(orig), - make_intrusive(data_len, line) + zeek::val_mgr->Bool(orig), + zeek::make_intrusive(data_len, line) ); } } @@ -351,11 +351,11 @@ void SMTP_Analyzer::ProcessLine(int length, const char* line, bool orig) EnqueueConnEvent(smtp_reply, ConnVal(), - val_mgr->Bool(orig), - val_mgr->Count(reply_code), - make_intrusive(cmd), - make_intrusive(end_of_line - line, line), - val_mgr->Bool((pending_reply > 0)) + zeek::val_mgr->Bool(orig), + zeek::val_mgr->Count(reply_code), + zeek::make_intrusive(cmd), + zeek::make_intrusive(end_of_line - line, line), + zeek::val_mgr->Bool((pending_reply > 0)) ); } } @@ -855,14 +855,14 @@ void SMTP_Analyzer::RequestEvent(int cmd_len, const char* cmd, if ( smtp_request ) { - auto cmd_arg = make_intrusive(cmd_len, cmd); + auto cmd_arg = zeek::make_intrusive(cmd_len, cmd); cmd_arg->ToUpper(); EnqueueConnEvent(smtp_request, ConnVal(), - val_mgr->Bool(orig_is_sender), + zeek::val_mgr->Bool(orig_is_sender), std::move(cmd_arg), - make_intrusive(arg_len, arg) + zeek::make_intrusive(arg_len, arg) ); } } @@ -881,9 +881,9 @@ void SMTP_Analyzer::Unexpected(bool is_sender, const char* msg, EnqueueConnEvent(smtp_unexpected, ConnVal(), - val_mgr->Bool(is_orig), - make_intrusive(msg), - make_intrusive(detail_len, detail) + zeek::val_mgr->Bool(is_orig), + zeek::make_intrusive(msg), + zeek::make_intrusive(detail_len, detail) ); } } diff --git a/src/analyzer/protocol/smtp/SMTP.h b/src/analyzer/protocol/smtp/SMTP.h index 4a1ffe96a5..edc17e7d20 100644 --- a/src/analyzer/protocol/smtp/SMTP.h +++ b/src/analyzer/protocol/smtp/SMTP.h @@ -84,7 +84,7 @@ protected: int pending_reply; // code assoc. w/ multi-line reply, or 0 std::list pending_cmd_q; // to support pipelining bool skip_data; // whether to skip message body - BroString* line_after_gap; // last line before the first reply + zeek::String* line_after_gap; // last line before the first reply // after a gap mime::MIME_Mail* mail; diff --git a/src/analyzer/protocol/snmp/snmp-analyzer.pac b/src/analyzer/protocol/snmp/snmp-analyzer.pac index 3b4af47cf5..162b7d1942 100644 --- a/src/analyzer/protocol/snmp/snmp-analyzer.pac +++ b/src/analyzer/protocol/snmp/snmp-analyzer.pac @@ -8,26 +8,26 @@ %} %header{ -IntrusivePtr network_address_to_val(const ASN1Encoding* na); -IntrusivePtr network_address_to_val(const NetworkAddress* na); -IntrusivePtr asn1_obj_to_val(const ASN1Encoding* obj); +zeek::AddrValPtr network_address_to_val(const ASN1Encoding* na); +zeek::AddrValPtr network_address_to_val(const NetworkAddress* na); +zeek::ValPtr asn1_obj_to_val(const ASN1Encoding* obj); -IntrusivePtr build_hdr(const Header* header); -IntrusivePtr build_hdrV3(const Header* header); -IntrusivePtr build_bindings(const VarBindList* vbl); -IntrusivePtr build_pdu(const CommonPDU* pdu); -IntrusivePtr build_trap_pdu(const TrapPDU* pdu); -IntrusivePtr build_bulk_pdu(const GetBulkRequestPDU* pdu); +zeek::RecordValPtr build_hdr(const Header* header); +zeek::RecordValPtr build_hdrV3(const Header* header); +zeek::VectorValPtr build_bindings(const VarBindList* vbl); +zeek::RecordValPtr build_pdu(const CommonPDU* pdu); +zeek::RecordValPtr build_trap_pdu(const TrapPDU* pdu); +zeek::RecordValPtr build_bulk_pdu(const GetBulkRequestPDU* pdu); %} %code{ -IntrusivePtr network_address_to_val(const NetworkAddress* na) +zeek::AddrValPtr network_address_to_val(const NetworkAddress* na) { return network_address_to_val(na->encoding()); } -IntrusivePtr network_address_to_val(const ASN1Encoding* na) +zeek::AddrValPtr network_address_to_val(const ASN1Encoding* na) { bytestring const& bs = na->content(); @@ -35,19 +35,19 @@ IntrusivePtr network_address_to_val(const ASN1Encoding* na) // but standards don't seem to currently make any provisions for IPv6, // so ignore anything that can't be IPv4. if ( bs.length() != 4 ) - return make_intrusive(IPAddr()); + return zeek::make_intrusive(IPAddr()); const u_char* data = reinterpret_cast(bs.data()); uint32 network_order = extract_uint32(data); - return make_intrusive(ntohl(network_order)); + return zeek::make_intrusive(ntohl(network_order)); } -IntrusivePtr asn1_obj_to_val(const ASN1Encoding* obj) +zeek::ValPtr asn1_obj_to_val(const ASN1Encoding* obj) { - IntrusivePtr rval = make_intrusive(zeek::BifType::Record::SNMP::ObjectValue); + zeek::RecordValPtr rval = zeek::make_intrusive(zeek::BifType::Record::SNMP::ObjectValue); uint8 tag = obj->meta()->tag(); - rval->Assign(0, val_mgr->Count(tag)); + rval->Assign(0, zeek::val_mgr->Count(tag)); switch ( tag ) { case VARBIND_UNSPECIFIED_TAG: @@ -85,20 +85,20 @@ IntrusivePtr asn1_obj_to_val(const ASN1Encoding* obj) return rval; } -IntrusivePtr time_ticks_to_val(const TimeTicks* tt) +zeek::ValPtr time_ticks_to_val(const TimeTicks* tt) { return asn1_integer_to_val(tt->asn1_integer(), zeek::TYPE_COUNT); } -IntrusivePtr build_hdr(const Header* header) +zeek::RecordValPtr build_hdr(const Header* header) { - auto rv = make_intrusive(zeek::BifType::Record::SNMP::Header); - rv->Assign(0, val_mgr->Count(header->version())); + auto rv = zeek::make_intrusive(zeek::BifType::Record::SNMP::Header); + rv->Assign(0, zeek::val_mgr->Count(header->version())); switch ( header->version() ) { case SNMPV1_TAG: { - auto v1 = make_intrusive(zeek::BifType::Record::SNMP::HeaderV1); + auto v1 = zeek::make_intrusive(zeek::BifType::Record::SNMP::HeaderV1); v1->Assign(0, asn1_octet_string_to_val(header->v1()->community())); rv->Assign(1, std::move(v1)); } @@ -106,7 +106,7 @@ IntrusivePtr build_hdr(const Header* header) case SNMPV2_TAG: { - auto v2 = make_intrusive(zeek::BifType::Record::SNMP::HeaderV2); + auto v2 = zeek::make_intrusive(zeek::BifType::Record::SNMP::HeaderV2); v2->Assign(0, asn1_octet_string_to_val(header->v2()->community())); rv->Assign(2, std::move(v2)); } @@ -122,9 +122,9 @@ IntrusivePtr build_hdr(const Header* header) return rv; } -IntrusivePtr build_hdrV3(const Header* header) +zeek::RecordValPtr build_hdrV3(const Header* header) { - auto v3 = make_intrusive(zeek::BifType::Record::SNMP::HeaderV3); + auto v3 = zeek::make_intrusive(zeek::BifType::Record::SNMP::HeaderV3); const v3Header* v3hdr = header->v3(); const v3HeaderData* global_data = v3hdr->global_data(); bytestring const& flags = global_data->flags()->encoding()->content(); @@ -132,17 +132,17 @@ IntrusivePtr build_hdrV3(const Header* header) v3->Assign(0, asn1_integer_to_val(global_data->id(), zeek::TYPE_COUNT)); v3->Assign(1, asn1_integer_to_val(global_data->max_size(), zeek::TYPE_COUNT)); - v3->Assign(2, val_mgr->Count(flags_byte)); - v3->Assign(3, val_mgr->Bool(flags_byte & 0x01)); - v3->Assign(4, val_mgr->Bool(flags_byte & 0x02)); - v3->Assign(5, val_mgr->Bool(flags_byte & 0x04)); + v3->Assign(2, zeek::val_mgr->Count(flags_byte)); + v3->Assign(3, zeek::val_mgr->Bool(flags_byte & 0x01)); + v3->Assign(4, zeek::val_mgr->Bool(flags_byte & 0x02)); + v3->Assign(5, zeek::val_mgr->Bool(flags_byte & 0x04)); v3->Assign(6, asn1_integer_to_val(global_data->security_model(), zeek::TYPE_COUNT)); v3->Assign(7, asn1_octet_string_to_val(v3hdr->security_parameters())); if ( v3hdr->next()->tag() == ASN1_SEQUENCE_TAG ) { const v3ScopedPDU* spdu = v3hdr->plaintext_pdu(); - auto rv = make_intrusive(zeek::BifType::Record::SNMP::ScopedPDU_Context); + auto rv = zeek::make_intrusive(zeek::BifType::Record::SNMP::ScopedPDU_Context); rv->Assign(0, asn1_octet_string_to_val(spdu->context_engine_id())); rv->Assign(1, asn1_octet_string_to_val(spdu->context_name())); v3->Assign(8, std::move(rv)); @@ -151,14 +151,14 @@ IntrusivePtr build_hdrV3(const Header* header) return v3; } -IntrusivePtr build_bindings(const VarBindList* vbl) +zeek::VectorValPtr build_bindings(const VarBindList* vbl) { - auto vv = make_intrusive(zeek::BifType::Vector::SNMP::Bindings); + auto vv = zeek::make_intrusive(zeek::BifType::Vector::SNMP::Bindings); for ( size_t i = 0; i < vbl->bindings()->size(); ++i ) { VarBind* vb = (*vbl->bindings())[i]; - auto binding = make_intrusive(zeek::BifType::Record::SNMP::Binding); + auto binding = zeek::make_intrusive(zeek::BifType::Record::SNMP::Binding); binding->Assign(0, asn1_oid_to_val(vb->name()->oid())); binding->Assign(1, asn1_obj_to_val(vb->value()->encoding())); vv->Assign(i, std::move(binding)); @@ -167,9 +167,9 @@ IntrusivePtr build_bindings(const VarBindList* vbl) return vv; } -IntrusivePtr build_pdu(const CommonPDU* pdu) +zeek::RecordValPtr build_pdu(const CommonPDU* pdu) { - auto rv = make_intrusive(zeek::BifType::Record::SNMP::PDU); + auto rv = zeek::make_intrusive(zeek::BifType::Record::SNMP::PDU); rv->Assign(0, asn1_integer_to_val(pdu->request_id(), zeek::TYPE_INT)); rv->Assign(1, asn1_integer_to_val(pdu->error_status(), zeek::TYPE_INT)); rv->Assign(2, asn1_integer_to_val(pdu->error_index(), zeek::TYPE_INT)); @@ -177,9 +177,9 @@ IntrusivePtr build_pdu(const CommonPDU* pdu) return rv; } -IntrusivePtr build_trap_pdu(const TrapPDU* pdu) +zeek::RecordValPtr build_trap_pdu(const TrapPDU* pdu) { - auto rv = make_intrusive(zeek::BifType::Record::SNMP::TrapPDU); + auto rv = zeek::make_intrusive(zeek::BifType::Record::SNMP::TrapPDU); rv->Assign(0, asn1_oid_to_val(pdu->enterprise())); rv->Assign(1, network_address_to_val(pdu->agent_addr())); rv->Assign(2, asn1_integer_to_val(pdu->generic_trap(), zeek::TYPE_INT)); @@ -189,9 +189,9 @@ IntrusivePtr build_trap_pdu(const TrapPDU* pdu) return rv; } -IntrusivePtr build_bulk_pdu(const GetBulkRequestPDU* pdu) +zeek::RecordValPtr build_bulk_pdu(const GetBulkRequestPDU* pdu) { - auto rv = make_intrusive(zeek::BifType::Record::SNMP::BulkPDU); + auto rv = zeek::make_intrusive(zeek::BifType::Record::SNMP::BulkPDU); rv->Assign(0, asn1_integer_to_val(pdu->request_id(), zeek::TYPE_INT)); rv->Assign(1, asn1_integer_to_val(pdu->non_repeaters(), zeek::TYPE_COUNT)); rv->Assign(2, asn1_integer_to_val(pdu->max_repititions(), zeek::TYPE_COUNT)); diff --git a/src/analyzer/protocol/socks/socks-analyzer.pac b/src/analyzer/protocol/socks/socks-analyzer.pac index 7c7932fb02..24eca37f08 100644 --- a/src/analyzer/protocol/socks/socks-analyzer.pac +++ b/src/analyzer/protocol/socks/socks-analyzer.pac @@ -1,10 +1,10 @@ %header{ -IntrusivePtr array_to_string(vector *a); +zeek::StringValPtr array_to_string(vector *a); %} %code{ -IntrusivePtr array_to_string(vector *a) +zeek::StringValPtr array_to_string(vector *a) { int len = a->size(); auto tmp = std::make_unique(len); @@ -14,7 +14,7 @@ IntrusivePtr array_to_string(vector *a) while ( len > 0 && tmp[len-1] == '\0' ) --len; - return make_intrusive(len, tmp.get()); + return zeek::make_intrusive(len, tmp.get()); } %} @@ -25,8 +25,8 @@ refine connection SOCKS_Conn += { if ( socks_request ) { static auto socks_address = zeek::id::find_type("SOCKS::Address"); - auto sa = make_intrusive(socks_address); - sa->Assign(0, make_intrusive(htonl(${request.addr}))); + auto sa = zeek::make_intrusive(socks_address); + sa->Assign(0, zeek::make_intrusive(htonl(${request.addr}))); if ( ${request.v4a} ) sa->Assign(1, array_to_string(${request.name})); @@ -36,7 +36,7 @@ refine connection SOCKS_Conn += { 4, ${request.command}, std::move(sa), - val_mgr->Port(${request.port}, TRANSPORT_TCP), + zeek::val_mgr->Port(${request.port}, TRANSPORT_TCP), array_to_string(${request.user})); } @@ -50,15 +50,15 @@ refine connection SOCKS_Conn += { if ( socks_reply ) { static auto socks_address = zeek::id::find_type("SOCKS::Address"); - auto sa = make_intrusive(socks_address); - sa->Assign(0, make_intrusive(htonl(${reply.addr}))); + auto sa = zeek::make_intrusive(socks_address); + sa->Assign(0, zeek::make_intrusive(htonl(${reply.addr}))); zeek::BifEvent::enqueue_socks_reply(bro_analyzer(), bro_analyzer()->Conn(), 4, ${reply.status}, std::move(sa), - val_mgr->Port(${reply.port}, TRANSPORT_TCP)); + zeek::val_mgr->Port(${reply.port}, TRANSPORT_TCP)); } bro_analyzer()->ProtocolConfirmation(); @@ -83,22 +83,22 @@ refine connection SOCKS_Conn += { } static auto socks_address = zeek::id::find_type("SOCKS::Address"); - auto sa = make_intrusive(socks_address); + auto sa = zeek::make_intrusive(socks_address); // This is dumb and there must be a better way (checking for presence of a field)... switch ( ${request.remote_name.addr_type} ) { case 1: - sa->Assign(0, make_intrusive(htonl(${request.remote_name.ipv4}))); + sa->Assign(0, zeek::make_intrusive(htonl(${request.remote_name.ipv4}))); break; case 3: - sa->Assign(1, make_intrusive(${request.remote_name.domain_name.name}.length(), + sa->Assign(1, zeek::make_intrusive(${request.remote_name.domain_name.name}.length(), (const char*) ${request.remote_name.domain_name.name}.data())); break; case 4: - sa->Assign(0, make_intrusive(IPAddr(IPv6, (const uint32_t*) ${request.remote_name.ipv6}, IPAddr::Network))); + sa->Assign(0, zeek::make_intrusive(IPAddr(IPv6, (const uint32_t*) ${request.remote_name.ipv6}, IPAddr::Network))); break; default: @@ -112,8 +112,8 @@ refine connection SOCKS_Conn += { 5, ${request.command}, std::move(sa), - val_mgr->Port(${request.port}, TRANSPORT_TCP), - val_mgr->EmptyString()); + zeek::val_mgr->Port(${request.port}, TRANSPORT_TCP), + zeek::val_mgr->EmptyString()); static_cast(bro_analyzer())->EndpointDone(true); @@ -123,22 +123,22 @@ refine connection SOCKS_Conn += { function socks5_reply(reply: SOCKS5_Reply): bool %{ static auto socks_address = zeek::id::find_type("SOCKS::Address"); - auto sa = make_intrusive(socks_address); + auto sa = zeek::make_intrusive(socks_address); // This is dumb and there must be a better way (checking for presence of a field)... switch ( ${reply.bound.addr_type} ) { case 1: - sa->Assign(0, make_intrusive(htonl(${reply.bound.ipv4}))); + sa->Assign(0, zeek::make_intrusive(htonl(${reply.bound.ipv4}))); break; case 3: - sa->Assign(1, make_intrusive(${reply.bound.domain_name.name}.length(), + sa->Assign(1, zeek::make_intrusive(${reply.bound.domain_name.name}.length(), (const char*) ${reply.bound.domain_name.name}.data())); break; case 4: - sa->Assign(0, make_intrusive(IPAddr(IPv6, (const uint32_t*) ${reply.bound.ipv6}, IPAddr::Network))); + sa->Assign(0, zeek::make_intrusive(IPAddr(IPv6, (const uint32_t*) ${reply.bound.ipv6}, IPAddr::Network))); break; default: @@ -152,7 +152,7 @@ refine connection SOCKS_Conn += { 5, ${reply.reply}, std::move(sa), - val_mgr->Port(${reply.port}, TRANSPORT_TCP)); + zeek::val_mgr->Port(${reply.port}, TRANSPORT_TCP)); bro_analyzer()->ProtocolConfirmation(); static_cast(bro_analyzer())->EndpointDone(false); @@ -164,8 +164,8 @@ refine connection SOCKS_Conn += { if ( ! socks_login_userpass_request ) return true; - auto user = make_intrusive(${request.username}.length(), (const char*) ${request.username}.begin()); - auto pass = make_intrusive(${request.password}.length(), (const char*) ${request.password}.begin()); + auto user = zeek::make_intrusive(${request.username}.length(), (const char*) ${request.username}.begin()); + auto pass = zeek::make_intrusive(${request.password}.length(), (const char*) ${request.password}.begin()); zeek::BifEvent::enqueue_socks_login_userpass_request(bro_analyzer(), bro_analyzer()->Conn(), diff --git a/src/analyzer/protocol/ssh/ssh-analyzer.pac b/src/analyzer/protocol/ssh/ssh-analyzer.pac index e3064e08a0..1a7529c993 100644 --- a/src/analyzer/protocol/ssh/ssh-analyzer.pac +++ b/src/analyzer/protocol/ssh/ssh-analyzer.pac @@ -5,14 +5,14 @@ %} %header{ -IntrusivePtr name_list_to_vector(const bytestring& nl); +zeek::VectorValPtr name_list_to_vector(const bytestring& nl); %} %code{ // Copied from IRC_Analyzer::SplitWords -IntrusivePtr name_list_to_vector(const bytestring& nl) +zeek::VectorValPtr name_list_to_vector(const bytestring& nl) { - auto vv = make_intrusive(zeek::id::string_vec); + auto vv = zeek::make_intrusive(zeek::id::string_vec); string name_list = std_str(nl); if ( name_list.size() < 1 ) @@ -32,7 +32,7 @@ IntrusivePtr name_list_to_vector(const bytestring& nl) { word = name_list.substr(start, split_pos - start); if ( word.size() > 0 && word[0] != ',' ) - vv->Assign(vv->Size(), make_intrusive(word)); + vv->Assign(vv->Size(), zeek::make_intrusive(word)); start = split_pos + 1; } @@ -41,7 +41,7 @@ IntrusivePtr name_list_to_vector(const bytestring& nl) if ( start < name_list.size() ) { word = name_list.substr(start, name_list.size() - start); - vv->Assign(vv->Size(), make_intrusive(word)); + vv->Assign(vv->Size(), zeek::make_intrusive(word)); } return vv; } @@ -70,28 +70,28 @@ refine flow SSH_Flow += { if ( ! ssh_capabilities ) return false; - auto result = make_intrusive(zeek::BifType::Record::SSH::Capabilities); + auto result = zeek::make_intrusive(zeek::BifType::Record::SSH::Capabilities); result->Assign(0, name_list_to_vector(${msg.kex_algorithms.val})); result->Assign(1, name_list_to_vector(${msg.server_host_key_algorithms.val})); - auto encryption_algs = make_intrusive(zeek::BifType::Record::SSH::Algorithm_Prefs); + auto encryption_algs = zeek::make_intrusive(zeek::BifType::Record::SSH::Algorithm_Prefs); encryption_algs->Assign(0, name_list_to_vector(${msg.encryption_algorithms_client_to_server.val})); encryption_algs->Assign(1, name_list_to_vector(${msg.encryption_algorithms_server_to_client.val})); result->Assign(2, std::move(encryption_algs)); - auto mac_algs = make_intrusive(zeek::BifType::Record::SSH::Algorithm_Prefs); + auto mac_algs = zeek::make_intrusive(zeek::BifType::Record::SSH::Algorithm_Prefs); mac_algs->Assign(0, name_list_to_vector(${msg.mac_algorithms_client_to_server.val})); mac_algs->Assign(1, name_list_to_vector(${msg.mac_algorithms_server_to_client.val})); result->Assign(3, std::move(mac_algs)); - auto compression_algs = make_intrusive(zeek::BifType::Record::SSH::Algorithm_Prefs); + auto compression_algs = zeek::make_intrusive(zeek::BifType::Record::SSH::Algorithm_Prefs); compression_algs->Assign(0, name_list_to_vector(${msg.compression_algorithms_client_to_server.val})); compression_algs->Assign(1, name_list_to_vector(${msg.compression_algorithms_server_to_client.val})); result->Assign(4, std::move(compression_algs)); if ( ${msg.languages_client_to_server.len} || ${msg.languages_server_to_client.len} ) { - auto languages = make_intrusive(zeek::BifType::Record::SSH::Algorithm_Prefs); + auto languages = zeek::make_intrusive(zeek::BifType::Record::SSH::Algorithm_Prefs); if ( ${msg.languages_client_to_server.len} ) languages->Assign(0, name_list_to_vector(${msg.languages_client_to_server.val})); if ( ${msg.languages_server_to_client.len} ) @@ -101,7 +101,7 @@ refine flow SSH_Flow += { } - result->Assign(6, val_mgr->Bool(!${msg.is_orig})); + result->Assign(6, zeek::val_mgr->Bool(!${msg.is_orig})); zeek::BifEvent::enqueue_ssh_capabilities(connection()->bro_analyzer(), connection()->bro_analyzer()->Conn(), to_stringval(${msg.cookie}), diff --git a/src/analyzer/protocol/ssh/ssh-protocol.pac b/src/analyzer/protocol/ssh/ssh-protocol.pac index 9b364601b8..56b65d25c0 100644 --- a/src/analyzer/protocol/ssh/ssh-protocol.pac +++ b/src/analyzer/protocol/ssh/ssh-protocol.pac @@ -1,7 +1,7 @@ %include consts.pac %extern{ -#include "BroString.h" +#include "ZeekString.h" %} # Common constructs across SSH1 and SSH2 diff --git a/src/analyzer/protocol/ssl/proc-client-hello.pac b/src/analyzer/protocol/ssl/proc-client-hello.pac index c98b0772c6..c879b6e29a 100644 --- a/src/analyzer/protocol/ssl/proc-client-hello.pac +++ b/src/analyzer/protocol/ssl/proc-client-hello.pac @@ -23,33 +23,32 @@ else std::transform(cipher_suites24->begin(), cipher_suites24->end(), std::back_inserter(cipher_suites), to_int()); - auto cipher_vec = make_intrusive(zeek::id::index_vec); + auto cipher_vec = zeek::make_intrusive(zeek::id::index_vec); for ( unsigned int i = 0; i < cipher_suites.size(); ++i ) { - auto ciph = val_mgr->Count(cipher_suites[i]); + auto ciph = zeek::val_mgr->Count(cipher_suites[i]); cipher_vec->Assign(i, ciph); } - auto comp_vec = make_intrusive(zeek::id::index_vec); + auto comp_vec = zeek::make_intrusive(zeek::id::index_vec); if ( compression_methods ) { for ( unsigned int i = 0; i < compression_methods->size(); ++i ) { - auto comp = val_mgr->Count((*compression_methods)[i]); + auto comp = zeek::val_mgr->Count((*compression_methods)[i]); comp_vec->Assign(i, comp); } } zeek::BifEvent::enqueue_ssl_client_hello(bro_analyzer(), bro_analyzer()->Conn(), version, record_version(), ts, - make_intrusive(client_random.length(), - (const char*) client_random.data()), - {AdoptRef{}, to_string_val(session_id)}, + zeek::make_intrusive(client_random.length(), + (const char*) client_random.data()), + {zeek::AdoptRef{}, to_string_val(session_id)}, std::move(cipher_vec), std::move(comp_vec)); } return true; %} - diff --git a/src/analyzer/protocol/ssl/proc-server-hello.pac b/src/analyzer/protocol/ssl/proc-server-hello.pac index 130ff1f9ca..f49eacbc68 100644 --- a/src/analyzer/protocol/ssl/proc-server-hello.pac +++ b/src/analyzer/protocol/ssl/proc-server-hello.pac @@ -28,9 +28,9 @@ zeek::BifEvent::enqueue_ssl_server_hello(bro_analyzer(), bro_analyzer()->Conn(), version, record_version(), ts, - make_intrusive(server_random.length(), - (const char*) server_random.data()), - {AdoptRef{}, to_string_val(session_id)}, + zeek::make_intrusive(server_random.length(), + (const char*) server_random.data()), + {zeek::AdoptRef{}, to_string_val(session_id)}, ciphers->size()==0 ? 0 : ciphers->at(0), comp_method); delete ciphers; @@ -38,4 +38,3 @@ return true; %} - diff --git a/src/analyzer/protocol/ssl/ssl-defs.pac b/src/analyzer/protocol/ssl/ssl-defs.pac index 6c2d6a0bfa..e13d6ca169 100644 --- a/src/analyzer/protocol/ssl/ssl-defs.pac +++ b/src/analyzer/protocol/ssl/ssl-defs.pac @@ -48,7 +48,7 @@ string orig_label(bool is_orig) extern type to_int; -function to_string_val(data : uint8[]) : StringVal +function to_string_val(data : uint8[]) : zeek::StringVal %{ char tmp[32]; memset(tmp, 0, sizeof(tmp)); @@ -60,7 +60,7 @@ function to_string_val(data : uint8[]) : StringVal tmp[i-1] = (*data)[i-1]; } - return new StringVal(32, tmp); + return new zeek::StringVal(32, tmp); %} function version_ok(vers : uint16) : bool diff --git a/src/analyzer/protocol/ssl/ssl-dtls-analyzer.pac b/src/analyzer/protocol/ssl/ssl-dtls-analyzer.pac index 47d664ef99..ae4a86b460 100644 --- a/src/analyzer/protocol/ssl/ssl-dtls-analyzer.pac +++ b/src/analyzer/protocol/ssl/ssl-dtls-analyzer.pac @@ -76,7 +76,7 @@ refine connection SSL_Conn += { if ( ssl_heartbeat ) zeek::BifEvent::enqueue_ssl_heartbeat(bro_analyzer(), bro_analyzer()->Conn(), ${rec.is_orig}, ${rec.length}, type, payload_length, - make_intrusive(data.length(), (const char*) data.data())); + zeek::make_intrusive(data.length(), (const char*) data.data())); return true; %} diff --git a/src/analyzer/protocol/ssl/tls-handshake-analyzer.pac b/src/analyzer/protocol/ssl/tls-handshake-analyzer.pac index e0ae9bdb5a..b19d9564b4 100644 --- a/src/analyzer/protocol/ssl/tls-handshake-analyzer.pac +++ b/src/analyzer/protocol/ssl/tls-handshake-analyzer.pac @@ -37,7 +37,7 @@ refine connection Handshake_Conn += { zeek::BifEvent::enqueue_ssl_session_ticket_handshake(bro_analyzer(), bro_analyzer()->Conn(), ${rec.ticket_lifetime_hint}, - make_intrusive(${rec.data}.length(), (const char*) ${rec.data}.data())); + zeek::make_intrusive(${rec.data}.length(), (const char*) ${rec.data}.data())); } return true; %} @@ -66,7 +66,7 @@ refine connection Handshake_Conn += { if ( ssl_extension ) zeek::BifEvent::enqueue_ssl_extension(bro_analyzer(), bro_analyzer()->Conn(), ${rec.is_orig}, type, - make_intrusive(length, reinterpret_cast(data))); + zeek::make_intrusive(length, reinterpret_cast(data))); return true; %} @@ -75,12 +75,12 @@ refine connection Handshake_Conn += { if ( ! ssl_extension_ec_point_formats ) return true; - auto points = make_intrusive(zeek::id::index_vec); + auto points = zeek::make_intrusive(zeek::id::index_vec); if ( point_format_list ) { for ( unsigned int i = 0; i < point_format_list->size(); ++i ) - points->Assign(i, val_mgr->Count((*point_format_list)[i])); + points->Assign(i, zeek::val_mgr->Count((*point_format_list)[i])); } zeek::BifEvent::enqueue_ssl_extension_ec_point_formats(bro_analyzer(), bro_analyzer()->Conn(), @@ -94,12 +94,12 @@ refine connection Handshake_Conn += { if ( ! ssl_extension_elliptic_curves ) return true; - auto curves = make_intrusive(zeek::id::index_vec); + auto curves = zeek::make_intrusive(zeek::id::index_vec); if ( list ) { for ( unsigned int i = 0; i < list->size(); ++i ) - curves->Assign(i, val_mgr->Count((*list)[i])); + curves->Assign(i, zeek::val_mgr->Count((*list)[i])); } zeek::BifEvent::enqueue_ssl_extension_elliptic_curves(bro_analyzer(), bro_analyzer()->Conn(), @@ -113,12 +113,12 @@ refine connection Handshake_Conn += { if ( ! ssl_extension_key_share ) return true; - auto nglist = make_intrusive(zeek::id::index_vec); + auto nglist = zeek::make_intrusive(zeek::id::index_vec); if ( keyshare ) { for ( unsigned int i = 0; i < keyshare->size(); ++i ) - nglist->Assign(i, val_mgr->Count((*keyshare)[i]->namedgroup())); + nglist->Assign(i, zeek::val_mgr->Count((*keyshare)[i]->namedgroup())); } zeek::BifEvent::enqueue_ssl_extension_key_share(bro_analyzer(), bro_analyzer()->Conn(), ${rec.is_orig}, std::move(nglist)); @@ -131,9 +131,9 @@ refine connection Handshake_Conn += { if ( ! ssl_extension_key_share ) return true; - auto nglist = make_intrusive(zeek::id::index_vec); + auto nglist = zeek::make_intrusive(zeek::id::index_vec); - nglist->Assign(0u, val_mgr->Count(keyshare->namedgroup())); + nglist->Assign(0u, zeek::val_mgr->Count(keyshare->namedgroup())); zeek::BifEvent::enqueue_ssl_extension_key_share(bro_analyzer(), bro_analyzer()->Conn(), ${rec.is_orig}, std::move(nglist)); return true; %} @@ -143,9 +143,9 @@ refine connection Handshake_Conn += { if ( ! ssl_extension_key_share ) return true; - auto nglist = make_intrusive(zeek::id::index_vec); + auto nglist = zeek::make_intrusive(zeek::id::index_vec); - nglist->Assign(0u, val_mgr->Count(namedgroup)); + nglist->Assign(0u, zeek::val_mgr->Count(namedgroup)); zeek::BifEvent::enqueue_ssl_extension_key_share(bro_analyzer(), bro_analyzer()->Conn(), ${rec.is_orig}, std::move(nglist)); return true; %} @@ -155,15 +155,15 @@ refine connection Handshake_Conn += { if ( ! ssl_extension_signature_algorithm ) return true; - auto slist = make_intrusive(zeek::id::find_type("signature_and_hashalgorithm_vec")); + auto slist = zeek::make_intrusive(zeek::id::find_type("signature_and_hashalgorithm_vec")); if ( supported_signature_algorithms ) { for ( unsigned int i = 0; i < supported_signature_algorithms->size(); ++i ) { - auto el = make_intrusive(zeek::BifType::Record::SSL::SignatureAndHashAlgorithm); - el->Assign(0, val_mgr->Count((*supported_signature_algorithms)[i]->HashAlgorithm())); - el->Assign(1, val_mgr->Count((*supported_signature_algorithms)[i]->SignatureAlgorithm())); + auto el = zeek::make_intrusive(zeek::BifType::Record::SSL::SignatureAndHashAlgorithm); + el->Assign(0, zeek::val_mgr->Count((*supported_signature_algorithms)[i]->HashAlgorithm())); + el->Assign(1, zeek::val_mgr->Count((*supported_signature_algorithms)[i]->SignatureAlgorithm())); slist->Assign(i, std::move(el)); } } @@ -178,12 +178,12 @@ refine connection Handshake_Conn += { if ( ! ssl_extension_application_layer_protocol_negotiation ) return true; - auto plist = make_intrusive(zeek::id::string_vec); + auto plist = zeek::make_intrusive(zeek::id::string_vec); if ( protocols ) { for ( unsigned int i = 0; i < protocols->size(); ++i ) - plist->Assign(i, make_intrusive((*protocols)[i]->name().length(), (const char*) (*protocols)[i]->name().data())); + plist->Assign(i, zeek::make_intrusive((*protocols)[i]->name().length(), (const char*) (*protocols)[i]->name().data())); } zeek::BifEvent::enqueue_ssl_extension_application_layer_protocol_negotiation(bro_analyzer(), bro_analyzer()->Conn(), @@ -194,7 +194,7 @@ refine connection Handshake_Conn += { function proc_server_name(rec: HandshakeRecord, list: ServerName[]) : bool %{ - auto servers = make_intrusive(zeek::id::string_vec); + auto servers = zeek::make_intrusive(zeek::id::string_vec); if ( list ) { @@ -208,7 +208,7 @@ refine connection Handshake_Conn += { } if ( servername->host_name() ) - servers->Assign(j++, make_intrusive(servername->host_name()->host_name().length(), (const char*) servername->host_name()->host_name().data())); + servers->Assign(j++, zeek::make_intrusive(servername->host_name()->host_name().length(), (const char*) servername->host_name()->host_name().data())); else bro_analyzer()->Weird("Empty server_name extension in ssl connection"); } @@ -226,12 +226,12 @@ refine connection Handshake_Conn += { if ( ! ssl_extension_supported_versions ) return true; - auto versions = make_intrusive(zeek::id::index_vec); + auto versions = zeek::make_intrusive(zeek::id::index_vec); if ( versions_list ) { for ( unsigned int i = 0; i < versions_list->size(); ++i ) - versions->Assign(i, val_mgr->Count((*versions_list)[i])); + versions->Assign(i, zeek::val_mgr->Count((*versions_list)[i])); } zeek::BifEvent::enqueue_ssl_extension_supported_versions(bro_analyzer(), bro_analyzer()->Conn(), @@ -245,8 +245,8 @@ refine connection Handshake_Conn += { if ( ! ssl_extension_supported_versions ) return true; - auto versions = make_intrusive(zeek::id::index_vec); - versions->Assign(0u, val_mgr->Count(version)); + auto versions = zeek::make_intrusive(zeek::id::index_vec); + versions->Assign(0u, zeek::val_mgr->Count(version)); zeek::BifEvent::enqueue_ssl_extension_supported_versions(bro_analyzer(), bro_analyzer()->Conn(), ${rec.is_orig}, std::move(versions)); @@ -259,12 +259,12 @@ refine connection Handshake_Conn += { if ( ! ssl_extension_psk_key_exchange_modes ) return true; - auto modes = make_intrusive(zeek::id::index_vec); + auto modes = zeek::make_intrusive(zeek::id::index_vec); if ( mode_list ) { for ( unsigned int i = 0; i < mode_list->size(); ++i ) - modes->Assign(i, val_mgr->Count((*mode_list)[i])); + modes->Assign(i, zeek::val_mgr->Count((*mode_list)[i])); } zeek::BifEvent::enqueue_ssl_extension_psk_key_exchange_modes(bro_analyzer(), bro_analyzer()->Conn(), @@ -317,7 +317,7 @@ refine connection Handshake_Conn += { zeek::BifEvent::enqueue_ssl_stapled_ocsp(bro_analyzer(), bro_analyzer()->Conn(), ${rec.is_orig}, - make_intrusive(response.length(), (const char*) response.data())); + zeek::make_intrusive(response.length(), (const char*) response.data())); file_mgr->EndOfFile(file_id); } @@ -338,28 +338,28 @@ refine connection Handshake_Conn += { zeek::BifEvent::enqueue_ssl_ecdh_server_params(bro_analyzer(), bro_analyzer()->Conn(), ${kex.params.curve}, - make_intrusive(${kex.params.point}.length(), (const char*)${kex.params.point}.data())); + zeek::make_intrusive(${kex.params.point}.length(), (const char*)${kex.params.point}.data())); if ( ssl_server_signature ) { - auto ha = make_intrusive(zeek::BifType::Record::SSL::SignatureAndHashAlgorithm); + auto ha = zeek::make_intrusive(zeek::BifType::Record::SSL::SignatureAndHashAlgorithm); if ( ${kex.signed_params.uses_signature_and_hashalgorithm} ) { - ha->Assign(0, val_mgr->Count(${kex.signed_params.algorithm.HashAlgorithm})); - ha->Assign(1, val_mgr->Count(${kex.signed_params.algorithm.SignatureAlgorithm})); + ha->Assign(0, zeek::val_mgr->Count(${kex.signed_params.algorithm.HashAlgorithm})); + ha->Assign(1, zeek::val_mgr->Count(${kex.signed_params.algorithm.SignatureAlgorithm})); } else { // set to impossible value - ha->Assign(0, val_mgr->Count(256)); - ha->Assign(1, val_mgr->Count(256)); + ha->Assign(0, zeek::val_mgr->Count(256)); + ha->Assign(1, zeek::val_mgr->Count(256)); } zeek::BifEvent::enqueue_ssl_server_signature(bro_analyzer(), bro_analyzer()->Conn(), std::move(ha), - make_intrusive(${kex.signed_params.signature}.length(), (const char*)(${kex.signed_params.signature}).data())); + zeek::make_intrusive(${kex.signed_params.signature}.length(), (const char*)(${kex.signed_params.signature}).data())); } return true; @@ -374,7 +374,7 @@ refine connection Handshake_Conn += { zeek::BifEvent::enqueue_ssl_ecdh_server_params(bro_analyzer(), bro_analyzer()->Conn(), ${kex.params.curve}, - make_intrusive(${kex.params.point}.length(), (const char*)${kex.params.point}.data())); + zeek::make_intrusive(${kex.params.point}.length(), (const char*)${kex.params.point}.data())); return true; %} @@ -384,7 +384,7 @@ refine connection Handshake_Conn += { if ( ssl_rsa_client_pms ) zeek::BifEvent::enqueue_ssl_rsa_client_pms(bro_analyzer(), bro_analyzer()->Conn(), - make_intrusive(rsa_pms.length(), (const char*)rsa_pms.data())); + zeek::make_intrusive(rsa_pms.length(), (const char*)rsa_pms.data())); return true; %} @@ -394,7 +394,7 @@ refine connection Handshake_Conn += { if ( ssl_dh_client_params ) zeek::BifEvent::enqueue_ssl_dh_client_params(bro_analyzer(), bro_analyzer()->Conn(), - make_intrusive(Yc.length(), (const char*)Yc.data())); + zeek::make_intrusive(Yc.length(), (const char*)Yc.data())); return true; %} @@ -404,7 +404,7 @@ refine connection Handshake_Conn += { if ( ssl_ecdh_client_params ) zeek::BifEvent::enqueue_ssl_ecdh_client_params(bro_analyzer(), bro_analyzer()->Conn(), - make_intrusive(point.length(), (const char*)point.data())); + zeek::make_intrusive(point.length(), (const char*)point.data())); return true; %} @@ -414,17 +414,17 @@ refine connection Handshake_Conn += { if ( ! ssl_extension_signed_certificate_timestamp ) return true; - auto ha = make_intrusive(zeek::BifType::Record::SSL::SignatureAndHashAlgorithm); - ha->Assign(0, val_mgr->Count(digitally_signed_algorithms->HashAlgorithm())); - ha->Assign(1, val_mgr->Count(digitally_signed_algorithms->SignatureAlgorithm())); + auto ha = zeek::make_intrusive(zeek::BifType::Record::SSL::SignatureAndHashAlgorithm); + ha->Assign(0, zeek::val_mgr->Count(digitally_signed_algorithms->HashAlgorithm())); + ha->Assign(1, zeek::val_mgr->Count(digitally_signed_algorithms->SignatureAlgorithm())); zeek::BifEvent::enqueue_ssl_extension_signed_certificate_timestamp(bro_analyzer(), bro_analyzer()->Conn(), ${rec.is_orig}, version, - make_intrusive(logid.length(), reinterpret_cast(logid.begin())), + zeek::make_intrusive(logid.length(), reinterpret_cast(logid.begin())), timestamp, std::move(ha), - make_intrusive(digitally_signed_signature.length(), reinterpret_cast(digitally_signed_signature.begin())) + zeek::make_intrusive(digitally_signed_signature.length(), reinterpret_cast(digitally_signed_signature.begin())) ); return true; @@ -435,30 +435,30 @@ refine connection Handshake_Conn += { if ( ssl_ecdh_server_params ) zeek::BifEvent::enqueue_ssl_dh_server_params(bro_analyzer(), bro_analyzer()->Conn(), - make_intrusive(p.length(), (const char*) p.data()), - make_intrusive(g.length(), (const char*) g.data()), - make_intrusive(Ys.length(), (const char*) Ys.data()) + zeek::make_intrusive(p.length(), (const char*) p.data()), + zeek::make_intrusive(g.length(), (const char*) g.data()), + zeek::make_intrusive(Ys.length(), (const char*) Ys.data()) ); if ( ssl_server_signature ) { - auto ha = make_intrusive(zeek::BifType::Record::SSL::SignatureAndHashAlgorithm); + auto ha = zeek::make_intrusive(zeek::BifType::Record::SSL::SignatureAndHashAlgorithm); if ( ${signed_params.uses_signature_and_hashalgorithm} ) { - ha->Assign(0, val_mgr->Count(${signed_params.algorithm.HashAlgorithm})); - ha->Assign(1, val_mgr->Count(${signed_params.algorithm.SignatureAlgorithm})); + ha->Assign(0, zeek::val_mgr->Count(${signed_params.algorithm.HashAlgorithm})); + ha->Assign(1, zeek::val_mgr->Count(${signed_params.algorithm.SignatureAlgorithm})); } else { // set to impossible value - ha->Assign(0, val_mgr->Count(256)); - ha->Assign(1, val_mgr->Count(256)); + ha->Assign(0, zeek::val_mgr->Count(256)); + ha->Assign(1, zeek::val_mgr->Count(256)); } zeek::BifEvent::enqueue_ssl_server_signature(bro_analyzer(), bro_analyzer()->Conn(), std::move(ha), - make_intrusive(${signed_params.signature}.length(), (const char*)(${signed_params.signature}).data()) + zeek::make_intrusive(${signed_params.signature}.length(), (const char*)(${signed_params.signature}).data()) ); } @@ -470,9 +470,9 @@ refine connection Handshake_Conn += { if ( ssl_dh_server_params ) zeek::BifEvent::enqueue_ssl_dh_server_params(bro_analyzer(), bro_analyzer()->Conn(), - make_intrusive(p.length(), (const char*) p.data()), - make_intrusive(g.length(), (const char*) g.data()), - make_intrusive(Ys.length(), (const char*) Ys.data()) + zeek::make_intrusive(p.length(), (const char*) p.data()), + zeek::make_intrusive(g.length(), (const char*) g.data()), + zeek::make_intrusive(Ys.length(), (const char*) Ys.data()) ); return true; @@ -492,25 +492,25 @@ refine connection Handshake_Conn += { if ( ! ssl_extension_pre_shared_key_server_hello ) return true; - auto slist = make_intrusive(zeek::id::find_type("psk_identity_vec")); + auto slist = zeek::make_intrusive(zeek::id::find_type("psk_identity_vec")); if ( identities && identities->identities() ) { for ( auto&& identity : *(identities->identities()) ) { - auto el = make_intrusive(zeek::BifType::Record::SSL::PSKIdentity); - el->Assign(0, make_intrusive(identity->identity().length(), (const char*) identity->identity().data())); - el->Assign(1, val_mgr->Count(identity->obfuscated_ticket_age())); + auto el = zeek::make_intrusive(zeek::BifType::Record::SSL::PSKIdentity); + el->Assign(0, zeek::make_intrusive(identity->identity().length(), (const char*) identity->identity().data())); + el->Assign(1, zeek::val_mgr->Count(identity->obfuscated_ticket_age())); slist->Assign(slist->Size(), std::move(el)); } } - auto blist = make_intrusive(zeek::id::string_vec); + auto blist = zeek::make_intrusive(zeek::id::string_vec); if ( binders && binders->binders() ) { for ( auto&& binder : *(binders->binders()) ) - blist->Assign(blist->Size(), make_intrusive(binder->binder().length(), (const char*) binder->binder().data())); + blist->Assign(blist->Size(), zeek::make_intrusive(binder->binder().length(), (const char*) binder->binder().data())); } zeek::BifEvent::enqueue_ssl_extension_pre_shared_key_client_hello(bro_analyzer(), bro_analyzer()->Conn(), diff --git a/src/analyzer/protocol/stepping-stone/SteppingStone.cc b/src/analyzer/protocol/stepping-stone/SteppingStone.cc index 51c43fb5f0..f99540b4fd 100644 --- a/src/analyzer/protocol/stepping-stone/SteppingStone.cc +++ b/src/analyzer/protocol/stepping-stone/SteppingStone.cc @@ -135,9 +135,9 @@ void SteppingStoneEndpoint::Event(EventHandlerPtr f, int id1, int id2) return; if ( id2 >= 0 ) - endp->TCP()->EnqueueConnEvent(f, val_mgr->Int(id1), val_mgr->Int(id2)); + endp->TCP()->EnqueueConnEvent(f, zeek::val_mgr->Int(id1), zeek::val_mgr->Int(id2)); else - endp->TCP()->EnqueueConnEvent(f, val_mgr->Int(id1)); + endp->TCP()->EnqueueConnEvent(f, zeek::val_mgr->Int(id1)); } void SteppingStoneEndpoint::CreateEndpEvent(bool is_orig) @@ -147,8 +147,8 @@ void SteppingStoneEndpoint::CreateEndpEvent(bool is_orig) endp->TCP()->EnqueueConnEvent(stp_create_endp, endp->TCP()->ConnVal(), - val_mgr->Int(stp_id), - val_mgr->Bool(is_orig) + zeek::val_mgr->Int(stp_id), + zeek::val_mgr->Bool(is_orig) ); } diff --git a/src/analyzer/protocol/stepping-stone/SteppingStone.h b/src/analyzer/protocol/stepping-stone/SteppingStone.h index b0a22ace90..972778d2d7 100644 --- a/src/analyzer/protocol/stepping-stone/SteppingStone.h +++ b/src/analyzer/protocol/stepping-stone/SteppingStone.h @@ -7,12 +7,12 @@ class NetSessions; -namespace analyzer { namespace stepping_stone { +namespace analyzer::stepping_stone { class SteppingStoneEndpoint; class SteppingStoneManager; -class SteppingStoneEndpoint : public BroObj { +class SteppingStoneEndpoint : public zeek::Obj { public: SteppingStoneEndpoint(tcp::TCP_Endpoint* e, SteppingStoneManager* m); ~SteppingStoneEndpoint() override; @@ -70,15 +70,15 @@ protected: class SteppingStoneManager { public: - PQueue& OrderedEndpoints() + zeek::PQueue& OrderedEndpoints() { return ordered_endps; } // Use postfix ++, since the first ID needs to be even. int NextID() { return endp_cnt++; } protected: - PQueue ordered_endps; + zeek::PQueue ordered_endps; int endp_cnt = 0; }; -} } // namespace analyzer::* +} // namespace analyzer::stepping_stone diff --git a/src/analyzer/protocol/syslog/syslog-analyzer.pac b/src/analyzer/protocol/syslog/syslog-analyzer.pac index f464abf3b3..1dff5f6f66 100644 --- a/src/analyzer/protocol/syslog/syslog-analyzer.pac +++ b/src/analyzer/protocol/syslog/syslog-analyzer.pac @@ -20,7 +20,7 @@ flow Syslog_Flow connection()->bro_analyzer()->Conn(), ${m.PRI.facility}, ${m.PRI.severity}, - make_intrusive(${m.msg}.length(), (const char*)${m.msg}.begin()) + zeek::make_intrusive(${m.msg}.length(), (const char*)${m.msg}.begin()) ); else zeek::BifEvent::enqueue_syslog_message( @@ -28,7 +28,7 @@ flow Syslog_Flow connection()->bro_analyzer()->Conn(), 999, 999, - make_intrusive(${m.msg}.length(), (const char*)${m.msg}.begin()) + zeek::make_intrusive(${m.msg}.length(), (const char*)${m.msg}.begin()) ); return true; diff --git a/src/analyzer/protocol/tcp/TCP.cc b/src/analyzer/protocol/tcp/TCP.cc index 4415566c01..24a4301ead 100644 --- a/src/analyzer/protocol/tcp/TCP.cc +++ b/src/analyzer/protocol/tcp/TCP.cc @@ -42,8 +42,8 @@ namespace { // local namespace static const int ORIG = 1; static const int RESP = 2; -static RecordVal* build_syn_packet_val(bool is_orig, const IP_Hdr* ip, - const struct tcphdr* tcp) +static zeek::RecordVal* build_syn_packet_val(bool is_orig, const IP_Hdr* ip, + const struct tcphdr* tcp) { int winscale = -1; int MSS = 0; @@ -108,16 +108,16 @@ static RecordVal* build_syn_packet_val(bool is_orig, const IP_Hdr* ip, } static auto SYN_packet = zeek::id::find_type("SYN_packet"); - RecordVal* v = new RecordVal(SYN_packet); + auto* v = new zeek::RecordVal(SYN_packet); - v->Assign(0, val_mgr->Bool(is_orig)); - v->Assign(1, val_mgr->Bool(int(ip->DF()))); - v->Assign(2, val_mgr->Count((ip->TTL()))); - v->Assign(3, val_mgr->Count((ip->TotalLen()))); - v->Assign(4, val_mgr->Count(ntohs(tcp->th_win))); - v->Assign(5, val_mgr->Int(winscale)); - v->Assign(6, val_mgr->Count(MSS)); - v->Assign(7, val_mgr->Bool(SACK)); + v->Assign(0, zeek::val_mgr->Bool(is_orig)); + v->Assign(1, zeek::val_mgr->Bool(int(ip->DF()))); + v->Assign(2, zeek::val_mgr->Count((ip->TTL()))); + v->Assign(3, zeek::val_mgr->Count((ip->TotalLen()))); + v->Assign(4, zeek::val_mgr->Count(ntohs(tcp->th_win))); + v->Assign(5, zeek::val_mgr->Int(winscale)); + v->Assign(6, zeek::val_mgr->Count(MSS)); + v->Assign(7, zeek::val_mgr->Bool(SACK)); return v; } @@ -788,14 +788,14 @@ void TCP_Analyzer::GeneratePacketEvent( { EnqueueConnEvent(tcp_packet, ConnVal(), - val_mgr->Bool(is_orig), - make_intrusive(flags.AsString()), - val_mgr->Count(rel_seq), - val_mgr->Count(flags.ACK() ? rel_ack : 0), - val_mgr->Count(len), + zeek::val_mgr->Bool(is_orig), + zeek::make_intrusive(flags.AsString()), + zeek::val_mgr->Count(rel_seq), + zeek::val_mgr->Count(flags.ACK() ? rel_ack : 0), + zeek::val_mgr->Count(len), // We need the min() here because Ethernet padding can lead to // caplen > len. - make_intrusive(std::min(caplen, len), (const char*) data) + zeek::make_intrusive(std::min(caplen, len), (const char*) data) ); } @@ -1097,14 +1097,14 @@ void TCP_Analyzer::DeliverPacket(int len, const u_char* data, bool is_orig, if ( flags.SYN() ) { syn_weirds(flags, endpoint, len); - RecordVal* SYN_vals = build_syn_packet_val(is_orig, ip, tp); + zeek::RecordVal* SYN_vals = build_syn_packet_val(is_orig, ip, tp); init_window(endpoint, peer, flags, SYN_vals->GetField(5)->CoerceToInt(), base_seq, ack_seq); if ( connection_SYN_packet ) EnqueueConnEvent(connection_SYN_packet, ConnVal(), - IntrusivePtr{NewRef{}, SYN_vals} + zeek::IntrusivePtr{zeek::NewRef{}, SYN_vals} ); Unref(SYN_vals); @@ -1285,15 +1285,15 @@ void TCP_Analyzer::FlipRoles() resp->is_orig = !resp->is_orig; } -void TCP_Analyzer::UpdateConnVal(RecordVal *conn_val) +void TCP_Analyzer::UpdateConnVal(zeek::RecordVal *conn_val) { - RecordVal* orig_endp_val = conn_val->GetField("orig")->AsRecordVal(); - RecordVal* resp_endp_val = conn_val->GetField("resp")->AsRecordVal(); + zeek::RecordVal* orig_endp_val = conn_val->GetField("orig")->AsRecordVal(); + zeek::RecordVal* resp_endp_val = conn_val->GetField("resp")->AsRecordVal(); - orig_endp_val->Assign(0, val_mgr->Count(orig->Size())); - orig_endp_val->Assign(1, val_mgr->Count(int(orig->state))); - resp_endp_val->Assign(0, val_mgr->Count(resp->Size())); - resp_endp_val->Assign(1, val_mgr->Count(int(resp->state))); + orig_endp_val->Assign(0, zeek::val_mgr->Count(orig->Size())); + orig_endp_val->Assign(1, zeek::val_mgr->Count(int(orig->state))); + resp_endp_val->Assign(0, zeek::val_mgr->Count(resp->Size())); + resp_endp_val->Assign(1, zeek::val_mgr->Count(int(resp->state))); // Call children's UpdateConnVal Analyzer::UpdateConnVal(conn_val); @@ -1348,34 +1348,34 @@ int TCP_Analyzer::ParseTCPOptions(const struct tcphdr* tcp, bool is_orig) auto length = kind < 2 ? 1 : o[1]; EnqueueConnEvent(tcp_option, ConnVal(), - val_mgr->Bool(is_orig), - val_mgr->Count(kind), - val_mgr->Count(length) + zeek::val_mgr->Bool(is_orig), + zeek::val_mgr->Count(kind), + zeek::val_mgr->Count(length) ); } if ( tcp_options ) { - auto option_list = make_intrusive(zeek::BifType::Vector::TCP::OptionList); + auto option_list = zeek::make_intrusive(zeek::BifType::Vector::TCP::OptionList); - auto add_option_data = [](const IntrusivePtr& rv, const u_char* odata, int olen) + auto add_option_data = [](const zeek::RecordValPtr& rv, const u_char* odata, int olen) { if ( olen <= 2 ) return; auto data_len = olen - 2; auto data = reinterpret_cast(odata + 2); - rv->Assign(2, make_intrusive(data_len, data)); + rv->Assign(2, zeek::make_intrusive(data_len, data)); }; for ( const auto& o : opts ) { auto kind = o[0]; auto length = kind < 2 ? 1 : o[1]; - auto option_record = make_intrusive(zeek::BifType::Record::TCP::Option); + auto option_record = zeek::make_intrusive(zeek::BifType::Record::TCP::Option); option_list->Assign(option_list->Size(), option_record); - option_record->Assign(0, val_mgr->Count(kind)); - option_record->Assign(1, val_mgr->Count(length)); + option_record->Assign(0, zeek::val_mgr->Count(kind)); + option_record->Assign(1, zeek::val_mgr->Count(length)); switch ( kind ) { case 2: @@ -1383,7 +1383,7 @@ int TCP_Analyzer::ParseTCPOptions(const struct tcphdr* tcp, bool is_orig) if ( length == 4 ) { auto mss = ntohs(*reinterpret_cast(o + 2)); - option_record->Assign(3, val_mgr->Count(mss)); + option_record->Assign(3, zeek::val_mgr->Count(mss)); } else { @@ -1397,7 +1397,7 @@ int TCP_Analyzer::ParseTCPOptions(const struct tcphdr* tcp, bool is_orig) if ( length == 3 ) { auto scale = o[2]; - option_record->Assign(4, val_mgr->Count(scale)); + option_record->Assign(4, zeek::val_mgr->Count(scale)); } else { @@ -1423,10 +1423,10 @@ int TCP_Analyzer::ParseTCPOptions(const struct tcphdr* tcp, bool is_orig) auto p = reinterpret_cast(o + 2); auto num_pointers = (length - 2) / 4; auto vt = zeek::id::index_vec; - auto sack = make_intrusive(std::move(vt)); + auto sack = zeek::make_intrusive(std::move(vt)); for ( auto i = 0; i < num_pointers; ++i ) - sack->Assign(sack->Size(), val_mgr->Count(ntohl(p[i]))); + sack->Assign(sack->Size(), zeek::val_mgr->Count(ntohl(p[i]))); option_record->Assign(5, sack); } @@ -1443,8 +1443,8 @@ int TCP_Analyzer::ParseTCPOptions(const struct tcphdr* tcp, bool is_orig) { auto send = ntohl(*reinterpret_cast(o + 2)); auto echo = ntohl(*reinterpret_cast(o + 6)); - option_record->Assign(6, val_mgr->Count(send)); - option_record->Assign(7, val_mgr->Count(echo)); + option_record->Assign(6, zeek::val_mgr->Count(send)); + option_record->Assign(7, zeek::val_mgr->Count(echo)); } else { @@ -1461,7 +1461,7 @@ int TCP_Analyzer::ParseTCPOptions(const struct tcphdr* tcp, bool is_orig) EnqueueConnEvent(tcp_options, ConnVal(), - val_mgr->Bool(is_orig), + zeek::val_mgr->Bool(is_orig), std::move(option_list) ); } @@ -1557,7 +1557,7 @@ void TCP_Analyzer::ExpireTimer(double t) } // Connection still active, so reschedule timer. - // ### if PQ_Element's were BroObj's, could just Ref the timer + // ### if PQ_Element's were Obj's, could just Ref the timer // and adjust its value here, instead of creating a new timer. ADD_ANALYZER_TIMER(&TCP_Analyzer::ExpireTimer, t + tcp_session_timer, false, TIMER_TCP_EXPIRE); @@ -1584,7 +1584,7 @@ void TCP_Analyzer::ConnDeleteTimer(double t) Conn()->DeleteTimer(t); } -void TCP_Analyzer::SetContentsFile(unsigned int direction, IntrusivePtr f) +void TCP_Analyzer::SetContentsFile(unsigned int direction, BroFilePtr f) { if ( direction == CONTENTS_NONE ) { @@ -1601,7 +1601,7 @@ void TCP_Analyzer::SetContentsFile(unsigned int direction, IntrusivePtr } } -IntrusivePtr TCP_Analyzer::GetContentsFile(unsigned int direction) const +BroFilePtr TCP_Analyzer::GetContentsFile(unsigned int direction) const { switch ( direction ) { case CONTENTS_NONE: @@ -1783,7 +1783,7 @@ void TCP_Analyzer::EndpointEOF(TCP_Reassembler* endp) if ( connection_EOF ) EnqueueConnEvent(connection_EOF, ConnVal(), - val_mgr->Bool(endp->IsOrig()) + zeek::val_mgr->Bool(endp->IsOrig()) ); const analyzer_list& children(GetChildren()); @@ -2063,11 +2063,11 @@ bool TCPStats_Endpoint::DataSent(double /* t */, uint64_t seq, int len, int capl if ( tcp_rexmit ) endp->TCP()->EnqueueConnEvent(tcp_rexmit, endp->TCP()->ConnVal(), - val_mgr->Bool(endp->IsOrig()), - val_mgr->Count(seq), - val_mgr->Count(len), - val_mgr->Count(data_in_flight), - val_mgr->Count(endp->peer->window) + zeek::val_mgr->Bool(endp->IsOrig()), + zeek::val_mgr->Count(seq), + zeek::val_mgr->Count(len), + zeek::val_mgr->Count(data_in_flight), + zeek::val_mgr->Count(endp->peer->window) ); } else @@ -2076,18 +2076,18 @@ bool TCPStats_Endpoint::DataSent(double /* t */, uint64_t seq, int len, int capl return false; } -RecordVal* TCPStats_Endpoint::BuildStats() +zeek::RecordVal* TCPStats_Endpoint::BuildStats() { static auto endpoint_stats = zeek::id::find_type("endpoint_stats"); - RecordVal* stats = new RecordVal(endpoint_stats); + auto* stats = new zeek::RecordVal(endpoint_stats); - stats->Assign(0, val_mgr->Count(num_pkts)); - stats->Assign(1, val_mgr->Count(num_rxmit)); - stats->Assign(2, val_mgr->Count(num_rxmit_bytes)); - stats->Assign(3, val_mgr->Count(num_in_order)); - stats->Assign(4, val_mgr->Count(num_OO)); - stats->Assign(5, val_mgr->Count(num_repl)); - stats->Assign(6, val_mgr->Count(endian_type)); + stats->Assign(0, zeek::val_mgr->Count(num_pkts)); + stats->Assign(1, zeek::val_mgr->Count(num_rxmit)); + stats->Assign(2, zeek::val_mgr->Count(num_rxmit_bytes)); + stats->Assign(3, zeek::val_mgr->Count(num_in_order)); + stats->Assign(4, zeek::val_mgr->Count(num_OO)); + stats->Assign(5, zeek::val_mgr->Count(num_repl)); + stats->Assign(6, zeek::val_mgr->Count(endian_type)); return stats; } @@ -2119,8 +2119,8 @@ void TCPStats_Analyzer::Done() if ( conn_stats ) EnqueueConnEvent(conn_stats, ConnVal(), - IntrusivePtr{AdoptRef{}, orig_stats->BuildStats()}, - IntrusivePtr{AdoptRef{}, resp_stats->BuildStats()} + zeek::IntrusivePtr{zeek::AdoptRef{}, orig_stats->BuildStats()}, + zeek::IntrusivePtr{zeek::AdoptRef{}, resp_stats->BuildStats()} ); } diff --git a/src/analyzer/protocol/tcp/TCP.h b/src/analyzer/protocol/tcp/TCP.h index 2100eda181..a1cfa69643 100644 --- a/src/analyzer/protocol/tcp/TCP.h +++ b/src/analyzer/protocol/tcp/TCP.h @@ -60,11 +60,11 @@ public: // the test is whether it has any outstanding, un-acked data. bool DataPending(TCP_Endpoint* closing_endp); - void SetContentsFile(unsigned int direction, IntrusivePtr f) override; - IntrusivePtr GetContentsFile(unsigned int direction) const override; + void SetContentsFile(unsigned int direction, BroFilePtr f) override; + BroFilePtr GetContentsFile(unsigned int direction) const override; // From Analyzer.h - void UpdateConnVal(RecordVal *conn_val) override; + void UpdateConnVal(zeek::RecordVal *conn_val) override; int ParseTCPOptions(const struct tcphdr* tcp, bool is_orig); @@ -267,7 +267,7 @@ public: bool DataSent(double t, uint64_t seq, int len, int caplen, const u_char* data, const IP_Hdr* ip, const struct tcphdr* tp); - RecordVal* BuildStats(); + zeek::RecordVal* BuildStats(); protected: TCP_Endpoint* endp; diff --git a/src/analyzer/protocol/tcp/TCP_Endpoint.cc b/src/analyzer/protocol/tcp/TCP_Endpoint.cc index 04749932b4..7e799271d8 100644 --- a/src/analyzer/protocol/tcp/TCP_Endpoint.cc +++ b/src/analyzer/protocol/tcp/TCP_Endpoint.cc @@ -239,8 +239,8 @@ bool TCP_Endpoint::DataSent(double t, uint64_t seq, int len, int caplen, if ( contents_file_write_failure ) tcp_analyzer->EnqueueConnEvent(contents_file_write_failure, Conn()->ConnVal(), - val_mgr->Bool(IsOrig()), - make_intrusive(buf) + zeek::val_mgr->Bool(IsOrig()), + zeek::make_intrusive(buf) ); } } @@ -254,7 +254,7 @@ void TCP_Endpoint::AckReceived(uint64_t seq) contents_processor->AckReceived(seq); } -void TCP_Endpoint::SetContentsFile(IntrusivePtr f) +void TCP_Endpoint::SetContentsFile(BroFilePtr f) { contents_file = std::move(f); contents_start_seq = ToRelativeSeqSpace(last_seq, seq_wraps); diff --git a/src/analyzer/protocol/tcp/TCP_Endpoint.h b/src/analyzer/protocol/tcp/TCP_Endpoint.h index 9e90f0919d..960cee689c 100644 --- a/src/analyzer/protocol/tcp/TCP_Endpoint.h +++ b/src/analyzer/protocol/tcp/TCP_Endpoint.h @@ -187,8 +187,8 @@ public: void AckReceived(uint64_t seq); - void SetContentsFile(IntrusivePtr f); - const IntrusivePtr& GetContentsFile() const { return contents_file; } + void SetContentsFile(BroFilePtr f); + const BroFilePtr& GetContentsFile() const { return contents_file; } // Codes used for tracking history. For responders, we shift these // over by 16 bits in order to fit both originator and responder @@ -211,7 +211,7 @@ public: TCP_Endpoint* peer; TCP_Reassembler* contents_processor; TCP_Analyzer* tcp_analyzer; - IntrusivePtr contents_file; + BroFilePtr contents_file; uint32_t checksum_base; double start_time, last_time; diff --git a/src/analyzer/protocol/tcp/TCP_Reassembler.cc b/src/analyzer/protocol/tcp/TCP_Reassembler.cc index 2e9ef2c84d..62b39c4378 100644 --- a/src/analyzer/protocol/tcp/TCP_Reassembler.cc +++ b/src/analyzer/protocol/tcp/TCP_Reassembler.cc @@ -3,7 +3,7 @@ #include "File.h" #include "analyzer/Analyzer.h" #include "analyzer/protocol/tcp/TCP.h" -#include "BroString.h" +#include "ZeekString.h" #include "Reporter.h" #include "RuleMatcher.h" @@ -41,9 +41,9 @@ TCP_Reassembler::TCP_Reassembler(analyzer::Analyzer* arg_dst_analyzer, if ( ::tcp_contents ) { - static auto tcp_content_delivery_ports_orig = zeek::id::find_val("tcp_content_delivery_ports_orig"); - static auto tcp_content_delivery_ports_resp = zeek::id::find_val("tcp_content_delivery_ports_resp"); - const auto& dst_port_val = val_mgr->Port(ntohs(tcp_analyzer->Conn()->RespPort()), + static auto tcp_content_delivery_ports_orig = zeek::id::find_val("tcp_content_delivery_ports_orig"); + static auto tcp_content_delivery_ports_resp = zeek::id::find_val("tcp_content_delivery_ports_resp"); + const auto& dst_port_val = zeek::val_mgr->Port(ntohs(tcp_analyzer->Conn()->RespPort()), TRANSPORT_TCP); const auto& ports = IsOrig() ? tcp_content_delivery_ports_orig : @@ -92,7 +92,7 @@ uint64_t TCP_Reassembler::NumUndeliveredBytes() const return last_block.upper - last_reassem_seq; } -void TCP_Reassembler::SetContentsFile(IntrusivePtr f) +void TCP_Reassembler::SetContentsFile(BroFilePtr f) { if ( ! f->IsOpen() ) { @@ -148,9 +148,9 @@ void TCP_Reassembler::Gap(uint64_t seq, uint64_t len) if ( report_gap(endp, endp->peer) ) dst_analyzer->EnqueueConnEvent(content_gap, dst_analyzer->ConnVal(), - val_mgr->Bool(IsOrig()), - val_mgr->Count(seq), - val_mgr->Count(len) + zeek::val_mgr->Bool(IsOrig()), + zeek::val_mgr->Count(seq), + zeek::val_mgr->Count(len) ); if ( type == Direct ) @@ -317,7 +317,7 @@ void TCP_Reassembler::MatchUndelivered(uint64_t up_to_seq, bool use_last_upper) } } -void TCP_Reassembler::RecordToSeq(uint64_t start_seq, uint64_t stop_seq, const IntrusivePtr& f) +void TCP_Reassembler::RecordToSeq(uint64_t start_seq, uint64_t stop_seq, const BroFilePtr& f) { auto it = block_list.Begin(); @@ -348,7 +348,7 @@ void TCP_Reassembler::RecordToSeq(uint64_t start_seq, uint64_t stop_seq, const I RecordGap(last_seq, stop_seq, f); } -void TCP_Reassembler::RecordBlock(const DataBlock& b, const IntrusivePtr& f) +void TCP_Reassembler::RecordBlock(const DataBlock& b, const BroFilePtr& f) { if ( f->Write((const char*) b.block, b.Size()) ) return; @@ -358,12 +358,12 @@ void TCP_Reassembler::RecordBlock(const DataBlock& b, const IntrusivePtrEnqueueConnEvent(contents_file_write_failure, Endpoint()->Conn()->ConnVal(), - val_mgr->Bool(IsOrig()), - make_intrusive("TCP reassembler content write failure") + zeek::val_mgr->Bool(IsOrig()), + zeek::make_intrusive("TCP reassembler content write failure") ); } -void TCP_Reassembler::RecordGap(uint64_t start_seq, uint64_t upper_seq, const IntrusivePtr& f) +void TCP_Reassembler::RecordGap(uint64_t start_seq, uint64_t upper_seq, const BroFilePtr& f) { if ( f->Write(fmt("\n<>\n", upper_seq - start_seq)) ) return; @@ -373,8 +373,8 @@ void TCP_Reassembler::RecordGap(uint64_t start_seq, uint64_t upper_seq, const In if ( contents_file_write_failure ) tcp_analyzer->EnqueueConnEvent(contents_file_write_failure, Endpoint()->Conn()->ConnVal(), - val_mgr->Bool(IsOrig()), - make_intrusive("TCP reassembler gap write failure") + zeek::val_mgr->Bool(IsOrig()), + zeek::make_intrusive("TCP reassembler gap write failure") ); } @@ -448,14 +448,14 @@ void TCP_Reassembler::Overlap(const u_char* b1, const u_char* b2, uint64_t n) // we've ever seen for the connection. (n > 1 || endp->peer->HasDoneSomething()) ) { - BroString* b1_s = new BroString((const u_char*) b1, n, false); - BroString* b2_s = new BroString((const u_char*) b2, n, false); + zeek::String* b1_s = new zeek::String((const u_char*) b1, n, false); + zeek::String* b2_s = new zeek::String((const u_char*) b2, n, false); tcp_analyzer->EnqueueConnEvent(rexmit_inconsistency, tcp_analyzer->ConnVal(), - make_intrusive(b1_s), - make_intrusive(b2_s), - make_intrusive(flags.AsString()) + zeek::make_intrusive(b1_s), + zeek::make_intrusive(b2_s), + zeek::make_intrusive(flags.AsString()) ); } } @@ -609,9 +609,9 @@ void TCP_Reassembler::DeliverBlock(uint64_t seq, int len, const u_char* data) if ( deliver_tcp_contents ) tcp_analyzer->EnqueueConnEvent(tcp_contents, tcp_analyzer->ConnVal(), - val_mgr->Bool(IsOrig()), - val_mgr->Count(seq), - make_intrusive(len, (const char*) data) + zeek::val_mgr->Bool(IsOrig()), + zeek::val_mgr->Count(seq), + zeek::make_intrusive(len, (const char*) data) ); // Q. Can we say this because it is already checked in DataSent()? diff --git a/src/analyzer/protocol/tcp/TCP_Reassembler.h b/src/analyzer/protocol/tcp/TCP_Reassembler.h index 1ff6b835d1..7470e1b6bf 100644 --- a/src/analyzer/protocol/tcp/TCP_Reassembler.h +++ b/src/analyzer/protocol/tcp/TCP_Reassembler.h @@ -49,8 +49,8 @@ public: // from waiting_on_hole above; and is computed in a different fashion). uint64_t NumUndeliveredBytes() const; - void SetContentsFile(IntrusivePtr f); - const IntrusivePtr& GetContentsFile() const { return record_contents_file; } + void SetContentsFile(BroFilePtr f); + const BroFilePtr& GetContentsFile() const { return record_contents_file; } void MatchUndelivered(uint64_t up_to_seq, bool use_last_upper); @@ -89,9 +89,9 @@ private: void Undelivered(uint64_t up_to_seq) override; void Gap(uint64_t seq, uint64_t len); - void RecordToSeq(uint64_t start_seq, uint64_t stop_seq, const IntrusivePtr& f); - void RecordBlock(const DataBlock& b, const IntrusivePtr& f); - void RecordGap(uint64_t start_seq, uint64_t upper_seq, const IntrusivePtr& f); + void RecordToSeq(uint64_t start_seq, uint64_t stop_seq, const BroFilePtr& f); + void RecordBlock(const DataBlock& b, const BroFilePtr& f); + void RecordGap(uint64_t start_seq, uint64_t upper_seq, const BroFilePtr& f); void BlockInserted(DataBlockMap::const_iterator it) override; void Overlap(const u_char* b1, const u_char* b2, uint64_t n) override; @@ -108,7 +108,7 @@ private: bool in_delivery; analyzer::tcp::TCP_Flags flags; - IntrusivePtr record_contents_file; // file on which to reassemble contents + BroFilePtr record_contents_file; // file on which to reassemble contents Analyzer* dst_analyzer; TCP_Analyzer* tcp_analyzer; diff --git a/src/analyzer/protocol/tcp/functions.bif b/src/analyzer/protocol/tcp/functions.bif index 043dbbdafa..7b8c4fdbbc 100644 --- a/src/analyzer/protocol/tcp/functions.bif +++ b/src/analyzer/protocol/tcp/functions.bif @@ -20,18 +20,18 @@ function get_orig_seq%(cid: conn_id%): count %{ Connection* c = sessions->FindConnection(cid); if ( ! c ) - return val_mgr->Count(0); + return zeek::val_mgr->Count(0); if ( c->ConnTransport() != TRANSPORT_TCP ) - return val_mgr->Count(0); + return zeek::val_mgr->Count(0); analyzer::Analyzer* tc = c->FindAnalyzer("TCP"); if ( tc ) - return val_mgr->Count(static_cast(tc)->OrigSeq()); + return zeek::val_mgr->Count(static_cast(tc)->OrigSeq()); else { reporter->Error("connection does not have TCP analyzer"); - return val_mgr->Count(0); + return zeek::val_mgr->Count(0); } %} @@ -49,18 +49,18 @@ function get_resp_seq%(cid: conn_id%): count %{ Connection* c = sessions->FindConnection(cid); if ( ! c ) - return val_mgr->Count(0); + return zeek::val_mgr->Count(0); if ( c->ConnTransport() != TRANSPORT_TCP ) - return val_mgr->Count(0); + return zeek::val_mgr->Count(0); analyzer::Analyzer* tc = c->FindAnalyzer("TCP"); if ( tc ) - return val_mgr->Count(static_cast(tc)->RespSeq()); + return zeek::val_mgr->Count(static_cast(tc)->RespSeq()); else { reporter->Error("connection does not have TCP analyzer"); - return val_mgr->Count(0); + return zeek::val_mgr->Count(0); } %} @@ -99,10 +99,10 @@ function set_contents_file%(cid: conn_id, direction: count, f: file%): bool %{ Connection* c = sessions->FindConnection(cid); if ( ! c ) - return val_mgr->False(); + return zeek::val_mgr->False(); - c->GetRootAnalyzer()->SetContentsFile(direction, {NewRef{}, f}); - return val_mgr->True(); + c->GetRootAnalyzer()->SetContentsFile(direction, {zeek::NewRef{}, f}); + return zeek::val_mgr->True(); %} ## Returns the file handle of the contents file of a connection. @@ -127,14 +127,14 @@ function get_contents_file%(cid: conn_id, direction: count%): file auto cf = c->GetRootAnalyzer()->GetContentsFile(direction); if ( cf ) - return make_intrusive(std::move(cf)); + return zeek::make_intrusive(std::move(cf)); } // Return some sort of error value. if ( ! c ) - builtin_error("unknown connection id in get_contents_file()", cid); + zeek::emit_builtin_error("unknown connection id in get_contents_file()", cid); else - builtin_error("no contents file for given direction"); + zeek::emit_builtin_error("no contents file for given direction"); - return make_intrusive(make_intrusive(stderr, "-", "w")); + return zeek::make_intrusive(zeek::make_intrusive(stderr, "-", "w")); %} diff --git a/src/analyzer/protocol/teredo/Teredo.cc b/src/analyzer/protocol/teredo/Teredo.cc index 263aa4d334..319882cd96 100644 --- a/src/analyzer/protocol/teredo/Teredo.cc +++ b/src/analyzer/protocol/teredo/Teredo.cc @@ -5,7 +5,7 @@ #include "IP.h" #include "Reporter.h" #include "Sessions.h" -#include "BroString.h" +#include "ZeekString.h" #include "events.bif.h" @@ -96,37 +96,37 @@ bool TeredoEncapsulation::DoParse(const u_char* data, int& len, return false; } -IntrusivePtr TeredoEncapsulation::BuildVal(const IP_Hdr* inner) const +zeek::RecordValPtr TeredoEncapsulation::BuildVal(const IP_Hdr* inner) const { static auto teredo_hdr_type = zeek::id::find_type("teredo_hdr"); static auto teredo_auth_type = zeek::id::find_type("teredo_auth"); static auto teredo_origin_type = zeek::id::find_type("teredo_origin"); - auto teredo_hdr = make_intrusive(teredo_hdr_type); + auto teredo_hdr = zeek::make_intrusive(teredo_hdr_type); if ( auth ) { - auto teredo_auth = make_intrusive(teredo_auth_type); + auto teredo_auth = zeek::make_intrusive(teredo_auth_type); uint8_t id_len = *((uint8_t*)(auth + 2)); uint8_t au_len = *((uint8_t*)(auth + 3)); uint64_t nonce = ntohll(*((uint64_t*)(auth + 4 + id_len + au_len))); uint8_t conf = *((uint8_t*)(auth + 4 + id_len + au_len + 8)); - teredo_auth->Assign(0, make_intrusive( - new BroString(auth + 4, id_len, true))); - teredo_auth->Assign(1, make_intrusive( - new BroString(auth + 4 + id_len, au_len, true))); - teredo_auth->Assign(2, val_mgr->Count(nonce)); - teredo_auth->Assign(3, val_mgr->Count(conf)); + teredo_auth->Assign(0, zeek::make_intrusive( + new zeek::String(auth + 4, id_len, true))); + teredo_auth->Assign(1, zeek::make_intrusive( + new zeek::String(auth + 4 + id_len, au_len, true))); + teredo_auth->Assign(2, zeek::val_mgr->Count(nonce)); + teredo_auth->Assign(3, zeek::val_mgr->Count(conf)); teredo_hdr->Assign(0, std::move(teredo_auth)); } if ( origin_indication ) { - auto teredo_origin = make_intrusive(teredo_origin_type); + auto teredo_origin = zeek::make_intrusive(teredo_origin_type); uint16_t port = ntohs(*((uint16_t*)(origin_indication + 2))) ^ 0xFFFF; uint32_t addr = ntohl(*((uint32_t*)(origin_indication + 4))) ^ 0xFFFFFFFF; - teredo_origin->Assign(0, val_mgr->Port(port, TRANSPORT_UDP)); - teredo_origin->Assign(1, make_intrusive(htonl(addr))); + teredo_origin->Assign(0, zeek::val_mgr->Port(port, TRANSPORT_UDP)); + teredo_origin->Assign(1, zeek::make_intrusive(htonl(addr))); teredo_hdr->Assign(1, std::move(teredo_origin)); } @@ -194,7 +194,7 @@ void Teredo_Analyzer::DeliverPacket(int len, const u_char* data, bool orig, return; } - IntrusivePtr teredo_hdr; + zeek::ValPtr teredo_hdr; if ( teredo_packet ) { diff --git a/src/analyzer/protocol/teredo/Teredo.h b/src/analyzer/protocol/teredo/Teredo.h index 6b9975537c..b8b06c0db7 100644 --- a/src/analyzer/protocol/teredo/Teredo.h +++ b/src/analyzer/protocol/teredo/Teredo.h @@ -74,7 +74,7 @@ public: const u_char* Authentication() const { return auth; } - IntrusivePtr BuildVal(const IP_Hdr* inner) const; + zeek::RecordValPtr BuildVal(const IP_Hdr* inner) const; protected: bool DoParse(const u_char* data, int& len, bool found_orig, bool found_au); diff --git a/src/analyzer/protocol/udp/UDP.cc b/src/analyzer/protocol/udp/UDP.cc index a320b9ee76..8bb63ea360 100644 --- a/src/analyzer/protocol/udp/UDP.cc +++ b/src/analyzer/protocol/udp/UDP.cc @@ -42,7 +42,7 @@ void UDP_Analyzer::Done() } void UDP_Analyzer::DeliverPacket(int len, const u_char* data, bool is_orig, - uint64_t seq, const IP_Hdr* ip, int caplen) + uint64_t seq, const IP_Hdr* ip, int caplen) { assert(ip); @@ -134,12 +134,12 @@ void UDP_Analyzer::DeliverPacket(int len, const u_char* data, bool is_orig, if ( udp_contents ) { - static auto udp_content_ports = zeek::id::find_val("udp_content_ports"); - static auto udp_content_delivery_ports_orig = zeek::id::find_val("udp_content_delivery_ports_orig"); - static auto udp_content_delivery_ports_resp = zeek::id::find_val("udp_content_delivery_ports_resp"); + static auto udp_content_ports = zeek::id::find_val("udp_content_ports"); + static auto udp_content_delivery_ports_orig = zeek::id::find_val("udp_content_delivery_ports_orig"); + static auto udp_content_delivery_ports_resp = zeek::id::find_val("udp_content_delivery_ports_resp"); bool do_udp_contents = false; - const auto& sport_val = val_mgr->Port(ntohs(up->uh_sport), TRANSPORT_UDP); - const auto& dport_val = val_mgr->Port(ntohs(up->uh_dport), TRANSPORT_UDP); + const auto& sport_val = zeek::val_mgr->Port(ntohs(up->uh_sport), TRANSPORT_UDP); + const auto& dport_val = zeek::val_mgr->Port(ntohs(up->uh_dport), TRANSPORT_UDP); if ( udp_content_ports->FindOrDefault(dport_val) || udp_content_ports->FindOrDefault(sport_val) ) @@ -148,7 +148,7 @@ void UDP_Analyzer::DeliverPacket(int len, const u_char* data, bool is_orig, { uint16_t p = udp_content_delivery_ports_use_resp ? Conn()->RespPort() : up->uh_dport; - const auto& port_val = val_mgr->Port(ntohs(p), TRANSPORT_UDP); + const auto& port_val = zeek::val_mgr->Port(ntohs(p), TRANSPORT_UDP); if ( is_orig ) { @@ -168,10 +168,9 @@ void UDP_Analyzer::DeliverPacket(int len, const u_char* data, bool is_orig, if ( do_udp_contents ) EnqueueConnEvent(udp_contents, - ConnVal(), - val_mgr->Bool(is_orig), - make_intrusive(len, (const char*) data) - ); + ConnVal(), + zeek::val_mgr->Bool(is_orig), + zeek::make_intrusive(len, (const char*) data)); } if ( is_orig ) @@ -214,10 +213,10 @@ void UDP_Analyzer::DeliverPacket(int len, const u_char* data, bool is_orig, ForwardPacket(len, data, is_orig, seq, ip, caplen); } -void UDP_Analyzer::UpdateConnVal(RecordVal *conn_val) +void UDP_Analyzer::UpdateConnVal(zeek::RecordVal* conn_val) { - RecordVal* orig_endp = conn_val->GetField("orig")->AsRecordVal(); - RecordVal* resp_endp = conn_val->GetField("resp")->AsRecordVal(); + zeek::RecordVal* orig_endp = conn_val->GetField("orig")->AsRecordVal(); + zeek::RecordVal* resp_endp = conn_val->GetField("resp")->AsRecordVal(); UpdateEndpointVal(orig_endp, true); UpdateEndpointVal(resp_endp, false); @@ -226,19 +225,19 @@ void UDP_Analyzer::UpdateConnVal(RecordVal *conn_val) Analyzer::UpdateConnVal(conn_val); } -void UDP_Analyzer::UpdateEndpointVal(RecordVal* endp, bool is_orig) +void UDP_Analyzer::UpdateEndpointVal(zeek::RecordVal* endp, bool is_orig) { bro_int_t size = is_orig ? request_len : reply_len; if ( size < 0 ) { - endp->Assign(0, val_mgr->Count(0)); - endp->Assign(1, val_mgr->Count(int(UDP_INACTIVE))); + endp->Assign(0, zeek::val_mgr->Count(0)); + endp->Assign(1, zeek::val_mgr->Count(int(UDP_INACTIVE))); } else { - endp->Assign(0, val_mgr->Count(size)); - endp->Assign(1, val_mgr->Count(int(UDP_ACTIVE))); + endp->Assign(0, zeek::val_mgr->Count(size)); + endp->Assign(1, zeek::val_mgr->Count(int(UDP_ACTIVE))); } } diff --git a/src/analyzer/protocol/udp/UDP.h b/src/analyzer/protocol/udp/UDP.h index 1fa3877772..d7df56f5e2 100644 --- a/src/analyzer/protocol/udp/UDP.h +++ b/src/analyzer/protocol/udp/UDP.h @@ -18,7 +18,7 @@ public: ~UDP_Analyzer() override; void Init() override; - void UpdateConnVal(RecordVal *conn_val) override; + void UpdateConnVal(zeek::RecordVal *conn_val) override; static analyzer::Analyzer* Instantiate(Connection* conn) { return new UDP_Analyzer(conn); } @@ -39,7 +39,7 @@ protected: bro_int_t request_len, reply_len; private: - void UpdateEndpointVal(RecordVal* endp, bool is_orig); + void UpdateEndpointVal(zeek::RecordVal* endp, bool is_orig); #define HIST_ORIG_DATA_PKT 0x1 #define HIST_RESP_DATA_PKT 0x2 diff --git a/src/analyzer/protocol/vxlan/VXLAN.cc b/src/analyzer/protocol/vxlan/VXLAN.cc index d633649ae6..50f098080a 100644 --- a/src/analyzer/protocol/vxlan/VXLAN.cc +++ b/src/analyzer/protocol/vxlan/VXLAN.cc @@ -102,7 +102,7 @@ void VXLAN_Analyzer::DeliverPacket(int len, const u_char* data, bool orig, if ( vxlan_packet ) Conn()->EnqueueEvent(vxlan_packet, nullptr, ConnVal(), - inner->ToPktHdrVal(), val_mgr->Count(vni)); + inner->ToPktHdrVal(), zeek::val_mgr->Count(vni)); EncapsulatingConn ec(Conn(), BifEnum::Tunnel::VXLAN); sessions->DoNextInnerPacket(network_time, &pkt, inner, estack, ec); diff --git a/src/binpac_bro-lib.pac b/src/binpac_bro-lib.pac index 5b5b7594b1..5fe9cfaac7 100644 --- a/src/binpac_bro-lib.pac +++ b/src/binpac_bro-lib.pac @@ -7,7 +7,7 @@ %} %code{ -IntrusivePtr utf16_to_utf8_val(Connection* conn, const bytestring& utf16) +zeek::StringValPtr utf16_to_utf8_val(Connection* conn, const bytestring& utf16) { std::string resultstring; @@ -52,10 +52,10 @@ IntrusivePtr utf16_to_utf8_val(Connection* conn, const bytestring& ut // We're relying on no nulls being in the string. //return new StringVal(resultstring.length(), (const char *) resultstring.data()); - return make_intrusive(resultstring.c_str()); + return zeek::make_intrusive(resultstring.c_str()); } -StringVal* utf16_bytestring_to_utf8_val(Connection* conn, const bytestring& utf16) +zeek::StringVal* utf16_bytestring_to_utf8_val(Connection* conn, const bytestring& utf16) { return utf16_to_utf8_val(conn, utf16).release(); } diff --git a/src/binpac_bro.h b/src/binpac_bro.h index 1d84ad0810..90b8ebcd58 100644 --- a/src/binpac_bro.h +++ b/src/binpac_bro.h @@ -1,8 +1,6 @@ #pragma once class Connection; -class Val; -class PortVal; namespace analyzer { class Analyzer; } @@ -17,32 +15,32 @@ namespace analyzer { class Analyzer; } namespace binpac { -typedef analyzer::Analyzer* BroAnalyzer; -typedef file_analysis::Analyzer BroFileAnalyzer; -typedef Val* BroVal; -typedef PortVal* BroPortVal; -typedef StringVal* BroStringVal; +using BroAnalyzer = analyzer::Analyzer*; +using BroFileAnalyzer = file_analysis::Analyzer; +using BroVal = zeek::Val*; +using BroPortVal = zeek::PortVal*; +using BroStringVal = zeek::StringVal*; [[deprecated("Remove in v4.1. Use StringVal constructor directly.")]] -inline StringVal* string_to_val(string const &str) +inline zeek::StringVal* string_to_val(string const &str) { - return new StringVal(str.c_str()); + return new zeek::StringVal(str.c_str()); } [[deprecated("Remove in v4.1. Use binpac::to_stringval() instead.")]] -inline StringVal* bytestring_to_val(const_bytestring const &str) +inline zeek::StringVal* bytestring_to_val(const_bytestring const &str) { - return new StringVal(str.length(), (const char*) str.begin()); + return new zeek::StringVal(str.length(), (const char*) str.begin()); } -inline IntrusivePtr to_stringval(const_bytestring const& str) +inline zeek::StringValPtr to_stringval(const_bytestring const& str) { - return make_intrusive(str.length(), (const char*) str.begin()); + return zeek::make_intrusive(str.length(), (const char*) str.begin()); } -IntrusivePtr utf16_to_utf8_val(Connection* conn, const bytestring& utf16); +zeek::StringValPtr utf16_to_utf8_val(Connection* conn, const bytestring& utf16); [[deprecated("Remove in v4.1. Use utf16_to_utf8_val() instead.")]] -StringVal* utf16_bytestring_to_utf8_val(Connection* conn, const bytestring& utf16); +zeek::StringVal* utf16_bytestring_to_utf8_val(Connection* conn, const bytestring& utf16); } // namespace binpac diff --git a/src/broker/Data.cc b/src/broker/Data.cc index 0b1f6006c4..b137b79361 100644 --- a/src/broker/Data.cc +++ b/src/broker/Data.cc @@ -14,11 +14,11 @@ using namespace std; -IntrusivePtr bro_broker::opaque_of_data_type; -IntrusivePtr bro_broker::opaque_of_set_iterator; -IntrusivePtr bro_broker::opaque_of_table_iterator; -IntrusivePtr bro_broker::opaque_of_vector_iterator; -IntrusivePtr bro_broker::opaque_of_record_iterator; +zeek::OpaqueTypePtr bro_broker::opaque_of_data_type; +zeek::OpaqueTypePtr bro_broker::opaque_of_set_iterator; +zeek::OpaqueTypePtr bro_broker::opaque_of_table_iterator; +zeek::OpaqueTypePtr bro_broker::opaque_of_vector_iterator; +zeek::OpaqueTypePtr bro_broker::opaque_of_record_iterator; static bool data_type_check(const broker::data& d, zeek::Type* t); @@ -73,7 +73,7 @@ TEST_CASE("converting Broker to Zeek protocol constants") } struct val_converter { - using result_type = IntrusivePtr; + using result_type = zeek::ValPtr; zeek::Type* type; @@ -85,30 +85,30 @@ struct val_converter { result_type operator()(bool a) { if ( type->Tag() == zeek::TYPE_BOOL ) - return val_mgr->Bool(a); + return zeek::val_mgr->Bool(a); return nullptr; } result_type operator()(uint64_t a) { if ( type->Tag() == zeek::TYPE_COUNT ) - return val_mgr->Count(a); + return zeek::val_mgr->Count(a); if ( type->Tag() == zeek::TYPE_COUNTER ) - return val_mgr->Count(a); + return zeek::val_mgr->Count(a); return nullptr; } result_type operator()(int64_t a) { if ( type->Tag() == zeek::TYPE_INT ) - return val_mgr->Int(a); + return zeek::val_mgr->Int(a); return nullptr; } result_type operator()(double a) { if ( type->Tag() == zeek::TYPE_DOUBLE ) - return make_intrusive(a); + return zeek::make_intrusive(a); return nullptr; } @@ -116,13 +116,13 @@ struct val_converter { { switch ( type->Tag() ) { case zeek::TYPE_STRING: - return make_intrusive(a.size(), a.data()); + return zeek::make_intrusive(a.size(), a.data()); case zeek::TYPE_FILE: { auto file = BroFile::Get(a.data()); if ( file ) - return make_intrusive(std::move(file)); + return zeek::make_intrusive(std::move(file)); return nullptr; } @@ -136,7 +136,7 @@ struct val_converter { if ( type->Tag() == zeek::TYPE_ADDR ) { auto bits = reinterpret_cast(&a.bytes()); - return make_intrusive(IPAddr(*bits)); + return zeek::make_intrusive(IPAddr(*bits)); } return nullptr; @@ -147,7 +147,7 @@ struct val_converter { if ( type->Tag() == zeek::TYPE_SUBNET ) { auto bits = reinterpret_cast(&a.network().bytes()); - return make_intrusive(IPPrefix(IPAddr(*bits), a.length())); + return zeek::make_intrusive(IPPrefix(IPAddr(*bits), a.length())); } return nullptr; @@ -156,7 +156,7 @@ struct val_converter { result_type operator()(broker::port& a) { if ( type->Tag() == zeek::TYPE_PORT ) - return val_mgr->Port(a.number(), bro_broker::to_bro_port_proto(a.type())); + return zeek::val_mgr->Port(a.number(), bro_broker::to_bro_port_proto(a.type())); return nullptr; } @@ -168,7 +168,7 @@ struct val_converter { using namespace std::chrono; auto s = duration_cast(a.time_since_epoch()); - return make_intrusive(s.count()); + return zeek::make_intrusive(s.count()); } result_type operator()(broker::timespan& a) @@ -178,7 +178,7 @@ struct val_converter { using namespace std::chrono; auto s = duration_cast(a); - return make_intrusive(s.count()); + return zeek::make_intrusive(s.count()); } result_type operator()(broker::enum_value& a) @@ -204,7 +204,7 @@ struct val_converter { return nullptr; auto tt = type->AsTableType(); - auto rval = make_intrusive(IntrusivePtr{NewRef{}, tt}); + auto rval = zeek::make_intrusive(zeek::IntrusivePtr{zeek::NewRef{}, tt}); for ( auto& item : a ) { @@ -237,7 +237,7 @@ struct val_converter { if ( expected_index_types.size() != indices->size() ) return nullptr; - auto list_val = make_intrusive(zeek::TYPE_ANY); + auto list_val = zeek::make_intrusive(zeek::TYPE_ANY); for ( auto i = 0u; i < indices->size(); ++i ) { @@ -263,7 +263,7 @@ struct val_converter { return nullptr; auto tt = type->AsTableType(); - auto rval = make_intrusive(IntrusivePtr{NewRef{}, tt}); + auto rval = zeek::make_intrusive(zeek::IntrusivePtr{zeek::NewRef{}, tt}); for ( auto& item : a ) { @@ -296,7 +296,7 @@ struct val_converter { if ( expected_index_types.size() != indices->size() ) return nullptr; - auto list_val = make_intrusive(zeek::TYPE_ANY); + auto list_val = zeek::make_intrusive(zeek::TYPE_ANY); for ( auto i = 0u; i < indices->size(); ++i ) { @@ -326,7 +326,7 @@ struct val_converter { if ( type->Tag() == zeek::TYPE_VECTOR ) { auto vt = type->AsVectorType(); - auto rval = make_intrusive(IntrusivePtr{NewRef{}, vt}); + auto rval = zeek::make_intrusive(zeek::IntrusivePtr{zeek::NewRef{}, vt}); for ( auto& item : a ) { @@ -349,7 +349,7 @@ struct val_converter { if ( ! name ) return nullptr; - const auto& id = global_scope()->Find(*name); + const auto& id = zeek::detail::global_scope()->Find(*name); if ( ! id ) return nullptr; @@ -370,7 +370,7 @@ struct val_converter { if ( ! frame ) return nullptr; - BroFunc* b = dynamic_cast(rval->AsFunc()); + auto* b = dynamic_cast(rval->AsFunc()); if ( ! b ) return nullptr; @@ -383,7 +383,7 @@ struct val_converter { else if ( type->Tag() == zeek::TYPE_RECORD ) { auto rt = type->AsRecordType(); - auto rval = make_intrusive(IntrusivePtr{NewRef{}, rt}); + auto rval = zeek::make_intrusive(zeek::IntrusivePtr{zeek::NewRef{}, rt}); auto idx = 0u; for ( auto i = 0u; i < static_cast(rt->NumFields()); ++i ) @@ -432,11 +432,11 @@ struct val_converter { return nullptr; } - auto rval = make_intrusive(re); + auto rval = zeek::make_intrusive(re); return rval; } else if ( type->Tag() == zeek::TYPE_OPAQUE ) - return OpaqueVal::Unserialize(a); + return zeek::OpaqueVal::Unserialize(a); return nullptr; } @@ -693,7 +693,7 @@ struct type_checker { if ( ! name ) return false; - const auto& id = global_scope()->Find(*name); + const auto& id = zeek::detail::global_scope()->Find(*name); if ( ! id ) return false; @@ -763,7 +763,7 @@ struct type_checker { { // TODO: Could avoid doing the full unserialization here // and just check if the type is a correct match. - auto ov = OpaqueVal::Unserialize(a); + auto ov = zeek::OpaqueVal::Unserialize(a); return ov != nullptr; } @@ -779,7 +779,7 @@ static bool data_type_check(const broker::data& d, zeek::Type* t) return caf::visit(type_checker{t}, d); } -IntrusivePtr bro_broker::data_to_val(broker::data d, zeek::Type* type) +zeek::ValPtr bro_broker::data_to_val(broker::data d, zeek::Type* type) { if ( type->Tag() == zeek::TYPE_ANY ) return bro_broker::make_data_val(move(d)); @@ -787,7 +787,7 @@ IntrusivePtr bro_broker::data_to_val(broker::data d, zeek::Type* type) return caf::visit(val_converter{type}, std::move(d)); } -broker::expected bro_broker::val_to_data(const Val* v) +broker::expected bro_broker::val_to_data(const zeek::Val* v) { switch ( v->GetType()->Tag() ) { case zeek::TYPE_BOOL: @@ -852,7 +852,7 @@ broker::expected bro_broker::val_to_data(const Val* v) return {string(v->AsFile()->Name())}; case zeek::TYPE_FUNC: { - const Func* f = v->AsFunc(); + const zeek::Func* f = v->AsFunc(); std::string name(f->Name()); broker::vector rval; @@ -860,8 +860,8 @@ broker::expected bro_broker::val_to_data(const Val* v) if ( name.find("lambda_<") == 0 ) { - // Only BroFuncs have closures. - if ( auto b = dynamic_cast(f) ) + // Only ScriptFuncs have closures. + if ( auto b = dynamic_cast(f) ) { auto bc = b->SerializeClosure(); if ( ! bc ) @@ -871,7 +871,7 @@ broker::expected bro_broker::val_to_data(const Val* v) } else { - reporter->InternalWarning("Closure with non-BroFunc"); + reporter->InternalWarning("Closure with non-ScriptFunc"); return broker::ec::invalid_data; } } @@ -891,7 +891,7 @@ broker::expected bro_broker::val_to_data(const Val* v) rval = broker::table(); HashKey* hk; - TableEntryVal* entry; + zeek::TableEntryVal* entry; auto c = table->InitForIteration(); while ( (entry = table->NextEntry(hk, c)) ) @@ -1010,28 +1010,28 @@ broker::expected bro_broker::val_to_data(const Val* v) return broker::ec::invalid_data; } -IntrusivePtr bro_broker::make_data_val(Val* v) +zeek::RecordValPtr bro_broker::make_data_val(zeek::Val* v) { - auto rval = make_intrusive(zeek::BifType::Record::Broker::Data); + auto rval = zeek::make_intrusive(zeek::BifType::Record::Broker::Data); auto data = val_to_data(v); if ( data ) - rval->Assign(0, make_intrusive(move(*data))); + rval->Assign(0, zeek::make_intrusive(move(*data))); else reporter->Warning("did not get a value from val_to_data"); return rval; } -IntrusivePtr bro_broker::make_data_val(broker::data d) +zeek::RecordValPtr bro_broker::make_data_val(broker::data d) { - auto rval = make_intrusive(zeek::BifType::Record::Broker::Data); - rval->Assign(0, make_intrusive(move(d))); + auto rval = zeek::make_intrusive(zeek::BifType::Record::Broker::Data); + rval->Assign(0, zeek::make_intrusive(move(d))); return rval; } struct data_type_getter { - using result_type = IntrusivePtr; + using result_type = zeek::EnumValPtr; result_type operator()(broker::none) { @@ -1112,12 +1112,12 @@ struct data_type_getter { } }; -IntrusivePtr bro_broker::get_data_type(RecordVal* v, Frame* frame) +zeek::EnumValPtr bro_broker::get_data_type(zeek::RecordVal* v, zeek::detail::Frame* frame) { return caf::visit(data_type_getter{}, opaque_field_to_data(v, frame)); } -broker::data& bro_broker::opaque_field_to_data(RecordVal* v, Frame* f) +broker::data& bro_broker::opaque_field_to_data(zeek::RecordVal* v, zeek::detail::Frame* f) { const auto& d = v->GetField(0); @@ -1142,12 +1142,12 @@ bool bro_broker::DataVal::canCastTo(zeek::Type* t) const return data_type_check(data, t); } -IntrusivePtr bro_broker::DataVal::castTo(zeek::Type* t) +zeek::ValPtr bro_broker::DataVal::castTo(zeek::Type* t) { return data_to_val(data, t); } -const IntrusivePtr& bro_broker::DataVal::ScriptDataType() +const zeek::TypePtr& bro_broker::DataVal::ScriptDataType() { static auto script_data_type = zeek::id::find_type("Broker::Data"); return script_data_type; diff --git a/src/broker/Data.h b/src/broker/Data.h index 33c6a6e327..b97217878f 100644 --- a/src/broker/Data.h +++ b/src/broker/Data.h @@ -5,9 +5,6 @@ #include "Frame.h" #include "Expr.h" -template -class IntrusivePtr; - class ODesc; namespace threading { @@ -17,11 +14,11 @@ struct Field; namespace bro_broker { -extern IntrusivePtr opaque_of_data_type; -extern IntrusivePtr opaque_of_set_iterator; -extern IntrusivePtr opaque_of_table_iterator; -extern IntrusivePtr opaque_of_vector_iterator; -extern IntrusivePtr opaque_of_record_iterator; +extern zeek::OpaqueTypePtr opaque_of_data_type; +extern zeek::OpaqueTypePtr opaque_of_set_iterator; +extern zeek::OpaqueTypePtr opaque_of_table_iterator; +extern zeek::OpaqueTypePtr opaque_of_vector_iterator; +extern zeek::OpaqueTypePtr opaque_of_record_iterator; /** * Convert a broker port protocol to a bro port protocol. @@ -34,14 +31,14 @@ TransportProto to_bro_port_proto(broker::port::protocol tp); * @return a Broker::Data value, where the optional field is set if the conversion * was possible, else it is unset. */ -IntrusivePtr make_data_val(Val* v); +zeek::RecordValPtr make_data_val(zeek::Val* v); /** * Create a Broker::Data value from a Broker data value. * @param d the Broker value to wrap in an opaque type. * @return a Broker::Data value that wraps the Broker value. */ -IntrusivePtr make_data_val(broker::data d); +zeek::RecordValPtr make_data_val(broker::data d); /** * Get the type of Broker data that Broker::Data wraps. @@ -49,14 +46,14 @@ IntrusivePtr make_data_val(broker::data d); * @param frame used to get location info upon error. * @return a Broker::DataType value. */ -IntrusivePtr get_data_type(RecordVal* v, Frame* frame); +zeek::EnumValPtr get_data_type(zeek::RecordVal* v, zeek::detail::Frame* frame); /** * Convert a Bro value to a Broker data value. * @param v a Bro value. * @return a Broker data value if the Bro value could be converted to one. */ -broker::expected val_to_data(const Val* v); +broker::expected val_to_data(const zeek::Val* v); /** * Convert a Broker data value to a Bro value. @@ -65,7 +62,7 @@ broker::expected val_to_data(const Val* v); * @return a pointer to a new Bro value or a nullptr if the conversion was not * possible. */ -IntrusivePtr data_to_val(broker::data d, zeek::Type* type); +zeek::ValPtr data_to_val(broker::data d, zeek::Type* type); /** * Convert a Bro threading::Value to a Broker data value. @@ -100,7 +97,7 @@ threading::Field* data_to_threading_field(broker::data d); /** * A Bro value which wraps a Broker data value. */ -class DataVal : public OpaqueVal { +class DataVal : public zeek::OpaqueVal { public: DataVal(broker::data arg_data) @@ -109,13 +106,13 @@ public: void ValDescribe(ODesc* d) const override; - IntrusivePtr castTo(zeek::Type* t); + zeek::ValPtr castTo(zeek::Type* t); bool canCastTo(zeek::Type* t) const; // Returns the Bro type that scripts use to represent a Broker data // instance. This may be wrapping the opaque value inside another // type. - static const IntrusivePtr& ScriptDataType(); + static const zeek::TypePtr& ScriptDataType(); broker::data data; @@ -191,7 +188,7 @@ struct type_name_getter { * @return a reference to the wrapped Broker data value. A runtime interpreter * exception is thrown if the the optional opaque value of \a v is not set. */ -broker::data& opaque_field_to_data(RecordVal* v, Frame* f); +broker::data& opaque_field_to_data(zeek::RecordVal* v, zeek::detail::Frame* f); /** * Retrieve variant data from a Broker data value. @@ -204,7 +201,7 @@ broker::data& opaque_field_to_data(RecordVal* v, Frame* f); * is not currently stored in the Broker data. */ template -T& require_data_type(broker::data& d, zeek::TypeTag tag, Frame* f) +T& require_data_type(broker::data& d, zeek::TypeTag tag, zeek::detail::Frame* f) { auto ptr = caf::get_if(&d); if ( ! ptr ) @@ -220,18 +217,18 @@ T& require_data_type(broker::data& d, zeek::TypeTag tag, Frame* f) * @see require_data_type() and opaque_field_to_data(). */ template -inline T& require_data_type(RecordVal* v, zeek::TypeTag tag, Frame* f) +inline T& require_data_type(zeek::RecordVal* v, zeek::TypeTag tag, zeek::detail::Frame* f) { return require_data_type(opaque_field_to_data(v, f), tag, f); } // Copying data in to iterator vals is not the fastest approach, but safer... -class SetIterator : public OpaqueVal { +class SetIterator : public zeek::OpaqueVal { public: - SetIterator(RecordVal* v, zeek::TypeTag tag, Frame* f) - : OpaqueVal(bro_broker::opaque_of_set_iterator), + SetIterator(zeek::RecordVal* v, zeek::TypeTag tag, zeek::detail::Frame* f) + : zeek::OpaqueVal(bro_broker::opaque_of_set_iterator), dat(require_data_type(v, zeek::TYPE_TABLE, f)), it(dat.begin()) {} @@ -241,17 +238,17 @@ public: protected: SetIterator() - : OpaqueVal(bro_broker::opaque_of_set_iterator) + : zeek::OpaqueVal(bro_broker::opaque_of_set_iterator) {} DECLARE_OPAQUE_VALUE(bro_broker::SetIterator) }; -class TableIterator : public OpaqueVal { +class TableIterator : public zeek::OpaqueVal { public: - TableIterator(RecordVal* v, zeek::TypeTag tag, Frame* f) - : OpaqueVal(bro_broker::opaque_of_table_iterator), + TableIterator(zeek::RecordVal* v, zeek::TypeTag tag, zeek::detail::Frame* f) + : zeek::OpaqueVal(bro_broker::opaque_of_table_iterator), dat(require_data_type(v, zeek::TYPE_TABLE, f)), it(dat.begin()) {} @@ -261,17 +258,17 @@ public: protected: TableIterator() - : OpaqueVal(bro_broker::opaque_of_table_iterator) + : zeek::OpaqueVal(bro_broker::opaque_of_table_iterator) {} DECLARE_OPAQUE_VALUE(bro_broker::TableIterator) }; -class VectorIterator : public OpaqueVal { +class VectorIterator : public zeek::OpaqueVal { public: - VectorIterator(RecordVal* v, zeek::TypeTag tag, Frame* f) - : OpaqueVal(bro_broker::opaque_of_vector_iterator), + VectorIterator(zeek::RecordVal* v, zeek::TypeTag tag, zeek::detail::Frame* f) + : zeek::OpaqueVal(bro_broker::opaque_of_vector_iterator), dat(require_data_type(v, zeek::TYPE_VECTOR, f)), it(dat.begin()) {} @@ -281,17 +278,17 @@ public: protected: VectorIterator() - : OpaqueVal(bro_broker::opaque_of_vector_iterator) + : zeek::OpaqueVal(bro_broker::opaque_of_vector_iterator) {} DECLARE_OPAQUE_VALUE(bro_broker::VectorIterator) }; -class RecordIterator : public OpaqueVal { +class RecordIterator : public zeek::OpaqueVal { public: - RecordIterator(RecordVal* v, zeek::TypeTag tag, Frame* f) - : OpaqueVal(bro_broker::opaque_of_record_iterator), + RecordIterator(zeek::RecordVal* v, zeek::TypeTag tag, zeek::detail::Frame* f) + : zeek::OpaqueVal(bro_broker::opaque_of_record_iterator), dat(require_data_type(v, zeek::TYPE_RECORD, f)), it(dat.begin()) {} @@ -301,7 +298,7 @@ public: protected: RecordIterator() - : OpaqueVal(bro_broker::opaque_of_record_iterator) + : zeek::OpaqueVal(bro_broker::opaque_of_record_iterator) {} DECLARE_OPAQUE_VALUE(bro_broker::RecordIterator) diff --git a/src/broker/Manager.cc b/src/broker/Manager.cc index 36631f13a2..a0c9797bd7 100644 --- a/src/broker/Manager.cc +++ b/src/broker/Manager.cc @@ -28,9 +28,9 @@ using namespace std; namespace bro_broker { -static inline Val* get_option(const char* option) +static inline zeek::Val* get_option(const char* option) { - const auto& id = global_scope()->Find(option); + const auto& id = zeek::detail::global_scope()->Find(option); if ( ! (id && id->GetVal()) ) reporter->FatalError("Unknown Broker option %s", option); @@ -70,7 +70,7 @@ const broker::endpoint_info Manager::NoPeer{{}, {}}; int Manager::script_scope = 0; struct scoped_reporter_location { - scoped_reporter_location(Frame* frame) + scoped_reporter_location(zeek::detail::Frame* frame) { reporter->PushLocation(frame->GetCall()->GetLocationInfo()); } @@ -152,13 +152,13 @@ void Manager::InitPostScript() log_id_type = zeek::id::find_type("Log::ID")->AsEnumType(); writer_id_type = zeek::id::find_type("Log::Writer")->AsEnumType(); - opaque_of_data_type = make_intrusive("Broker::Data"); - opaque_of_set_iterator = make_intrusive("Broker::SetIterator"); - opaque_of_table_iterator = make_intrusive("Broker::TableIterator"); - opaque_of_vector_iterator = make_intrusive("Broker::VectorIterator"); - opaque_of_record_iterator = make_intrusive("Broker::RecordIterator"); - opaque_of_store_handle = make_intrusive("Broker::Store"); - vector_of_data_type = make_intrusive(zeek::id::find_type("Broker::Data")); + opaque_of_data_type = zeek::make_intrusive("Broker::Data"); + opaque_of_set_iterator = zeek::make_intrusive("Broker::SetIterator"); + opaque_of_table_iterator = zeek::make_intrusive("Broker::TableIterator"); + opaque_of_vector_iterator = zeek::make_intrusive("Broker::VectorIterator"); + opaque_of_record_iterator = zeek::make_intrusive("Broker::RecordIterator"); + opaque_of_store_handle = zeek::make_intrusive("Broker::Store"); + vector_of_data_type = zeek::make_intrusive(zeek::id::find_type("Broker::Data")); // Register as a "dont-count" source first, we may change that later. iosource_mgr->Register(this, true); @@ -379,7 +379,7 @@ bool Manager::PublishEvent(string topic, std::string name, broker::vector args) return true; } -bool Manager::PublishEvent(string topic, RecordVal* args) +bool Manager::PublishEvent(string topic, zeek::RecordVal* args) { if ( bstate->endpoint.is_shutdown() ) return true; @@ -413,7 +413,7 @@ bool Manager::PublishIdentifier(std::string topic, std::string id) if ( peer_count == 0 ) return true; - const auto& i = global_scope()->Find(id); + const auto& i = zeek::detail::global_scope()->Find(id); if ( ! i ) return false; @@ -442,10 +442,10 @@ bool Manager::PublishIdentifier(std::string topic, std::string id) return true; } -bool Manager::PublishLogCreate(EnumVal* stream, EnumVal* writer, - const logging::WriterBackend::WriterInfo& info, - int num_fields, const threading::Field* const * fields, - const broker::endpoint_info& peer) +bool Manager::PublishLogCreate(zeek::EnumVal* stream, zeek::EnumVal* writer, + const logging::WriterBackend::WriterInfo& info, + int num_fields, const threading::Field* const * fields, + const broker::endpoint_info& peer) { if ( bstate->endpoint.is_shutdown() ) return true; @@ -499,7 +499,8 @@ bool Manager::PublishLogCreate(EnumVal* stream, EnumVal* writer, return true; } -bool Manager::PublishLogWrite(EnumVal* stream, EnumVal* writer, string path, int num_fields, const threading::Value* const * vals) +bool Manager::PublishLogWrite(zeek::EnumVal* stream, zeek::EnumVal* writer, string path, + int num_fields, const threading::Value* const * vals) { if ( bstate->endpoint.is_shutdown() ) return true; @@ -553,8 +554,8 @@ bool Manager::PublishLogWrite(EnumVal* stream, EnumVal* writer, string path, int std::string serial_data(data, len); free(data); - auto v = log_topic_func->Invoke(IntrusivePtr{NewRef{}, stream}, - make_intrusive(path)); + auto v = log_topic_func->Invoke(zeek::IntrusivePtr{zeek::NewRef{}, stream}, + zeek::make_intrusive(path)); if ( ! v ) { @@ -632,12 +633,12 @@ void Manager::Error(const char* format, ...) va_end(args); if ( script_scope ) - builtin_error(msg); + zeek::emit_builtin_error(msg); else reporter->Error("%s", msg); } -bool Manager::AutoPublishEvent(string topic, Val* event) +bool Manager::AutoPublishEvent(string topic, zeek::Val* event) { if ( event->GetType()->Tag() != zeek::TYPE_FUNC ) { @@ -666,7 +667,7 @@ bool Manager::AutoPublishEvent(string topic, Val* event) return true; } -bool Manager::AutoUnpublishEvent(const string& topic, Val* event) +bool Manager::AutoUnpublishEvent(const string& topic, zeek::Val* event) { if ( event->GetType()->Tag() != zeek::TYPE_FUNC ) { @@ -698,12 +699,12 @@ bool Manager::AutoUnpublishEvent(const string& topic, Val* event) return true; } -RecordVal* Manager::MakeEvent(val_list* args, Frame* frame) +zeek::RecordVal* Manager::MakeEvent(val_list* args, zeek::detail::Frame* frame) { - auto rval = new RecordVal(zeek::BifType::Record::Broker::Event); - auto arg_vec = make_intrusive(vector_of_data_type); + auto rval = new zeek::RecordVal(zeek::BifType::Record::Broker::Event); + auto arg_vec = zeek::make_intrusive(vector_of_data_type); rval->Assign(1, arg_vec); - Func* func = nullptr; + zeek::Func* func = nullptr; scoped_reporter_location srl{frame}; for ( auto i = 0; i < args->length(); ++i ) @@ -737,7 +738,7 @@ RecordVal* Manager::MakeEvent(val_list* args, Frame* frame) return rval; } - rval->Assign(0, make_intrusive(func->Name())); + rval->Assign(0, zeek::make_intrusive(func->Name())); continue; } @@ -753,10 +754,10 @@ RecordVal* Manager::MakeEvent(val_list* args, Frame* frame) return rval; } - IntrusivePtr data_val; + zeek::RecordValPtr data_val; if ( same_type(got_type, bro_broker::DataVal::ScriptDataType()) ) - data_val = {NewRef{}, (*args)[i]->AsRecordVal()}; + data_val = {zeek::NewRef{}, (*args)[i]->AsRecordVal()}; else data_val = make_data_val((*args)[i]); @@ -1187,7 +1188,7 @@ bool Manager::ProcessIdentifierUpdate(broker::zeek::IdentifierUpdate iu) ++statistics.num_ids_incoming; auto id_name = std::move(iu.id_name()); auto id_value = std::move(iu.id_value()); - const auto& id = global_scope()->Find(id_name); + const auto& id = zeek::detail::global_scope()->Find(id_name); if ( ! id ) { @@ -1247,32 +1248,32 @@ void Manager::ProcessStatus(broker::status stat) return; static auto ei = zeek::id::find_type("Broker::EndpointInfo"); - auto endpoint_info = make_intrusive(ei); + auto endpoint_info = zeek::make_intrusive(ei); if ( ctx ) { - endpoint_info->Assign(0, make_intrusive(to_string(ctx->node))); + endpoint_info->Assign(0, zeek::make_intrusive(to_string(ctx->node))); static auto ni = zeek::id::find_type("Broker::NetworkInfo"); - auto network_info = make_intrusive(ni); + auto network_info = zeek::make_intrusive(ni); if ( ctx->network ) { - network_info->Assign(0, make_intrusive(ctx->network->address.data())); - network_info->Assign(1, val_mgr->Port(ctx->network->port, TRANSPORT_TCP)); + network_info->Assign(0, zeek::make_intrusive(ctx->network->address.data())); + network_info->Assign(1, zeek::val_mgr->Port(ctx->network->port, TRANSPORT_TCP)); } else { // TODO: are there any status messages where the ctx->network // is not set and actually could be? - network_info->Assign(0, make_intrusive("")); - network_info->Assign(1, val_mgr->Port(0, TRANSPORT_TCP)); + network_info->Assign(0, zeek::make_intrusive("")); + network_info->Assign(1, zeek::val_mgr->Port(0, TRANSPORT_TCP)); } endpoint_info->Assign(1, std::move(network_info)); } auto str = stat.message(); - auto msg = make_intrusive(str ? *str : ""); + auto msg = zeek::make_intrusive(str ? *str : ""); mgr.Enqueue(event, std::move(endpoint_info), std::move(msg)); } @@ -1353,7 +1354,7 @@ void Manager::ProcessError(broker::error err) mgr.Enqueue(Broker::error, zeek::BifType::Enum::Broker::ErrorCode->GetVal(ec), - make_intrusive(msg) + zeek::make_intrusive(msg) ); } diff --git a/src/broker/Manager.h b/src/broker/Manager.h index 30f917546a..ca079ca890 100644 --- a/src/broker/Manager.h +++ b/src/broker/Manager.h @@ -21,11 +21,14 @@ #include "iosource/IOSource.h" #include "logging/WriterBackend.h" -class Frame; -class Func; - +ZEEK_FORWARD_DECLARE_NAMESPACED(Func, zeek); +ZEEK_FORWARD_DECLARE_NAMESPACED(Frame, zeek::detail); ZEEK_FORWARD_DECLARE_NAMESPACED(VectorType, zeek); +namespace zeek { +using VectorTypePtr = zeek::IntrusivePtr; +} + namespace bro_broker { class StoreHandleVal; @@ -165,7 +168,7 @@ public: * a Broker::Event record type. * @return true if the message is sent successfully. */ - bool PublishEvent(std::string topic, RecordVal* ev); + bool PublishEvent(std::string topic, zeek::RecordVal* ev); /** * Send a message to create a log stream to any interested peers. @@ -180,7 +183,7 @@ public: * @param peer If given, send the message only to this peer. * @return true if the message is sent successfully. */ - bool PublishLogCreate(EnumVal* stream, EnumVal* writer, + bool PublishLogCreate(zeek::EnumVal* stream, zeek::EnumVal* writer, const logging::WriterBackend::WriterInfo& info, int num_fields, const threading::Field* const * fields, @@ -197,8 +200,9 @@ public: * See the Broker::SendFlags record type. * @return true if the message is sent successfully. */ - bool PublishLogWrite(EnumVal* stream, EnumVal* writer, std::string path, int num_vals, - const threading::Value* const * vals); + bool PublishLogWrite(zeek::EnumVal* stream, zeek::EnumVal* writer, + std::string path, int num_vals, + const threading::Value* const * vals); /** * Automatically send an event to any interested peers whenever it is @@ -209,7 +213,7 @@ public: * @param event a Bro event value. * @return true if automatic event sending is now enabled. */ - bool AutoPublishEvent(std::string topic, Val* event); + bool AutoPublishEvent(std::string topic, zeek::Val* event); /** * Stop automatically sending an event to peers upon local dispatch. @@ -217,7 +221,7 @@ public: * @param event an event originally given to bro_broker::Manager::AutoPublish(). * @return true if automatic events will no occur for the topic/event pair. */ - bool AutoUnpublishEvent(const std::string& topic, Val* event); + bool AutoUnpublishEvent(const std::string& topic, zeek::Val* event); /** * Create an `Event` record value from an event and its arguments. @@ -227,7 +231,7 @@ public: * @return an `Event` record value. If an invalid event or arguments * were supplied the optional "name" field will not be set. */ - RecordVal* MakeEvent(val_list* args, Frame* frame); + zeek::RecordVal* MakeEvent(val_list* args, zeek::detail::Frame* frame); /** * Register interest in peer event messages that use a certain topic prefix. @@ -396,8 +400,8 @@ private: int peer_count; size_t log_batch_size; - Func* log_topic_func; - IntrusivePtr vector_of_data_type; + zeek::Func* log_topic_func; + zeek::VectorTypePtr vector_of_data_type; zeek::EnumType* log_id_type; zeek::EnumType* writer_id_type; diff --git a/src/broker/Store.cc b/src/broker/Store.cc index 63a63953ef..c6c05f9695 100644 --- a/src/broker/Store.cc +++ b/src/broker/Store.cc @@ -5,9 +5,9 @@ namespace bro_broker { -IntrusivePtr opaque_of_store_handle; +zeek::OpaqueTypePtr opaque_of_store_handle; -IntrusivePtr query_status(bool success) +zeek::EnumValPtr query_status(bool success) { static zeek::EnumType* store_query_status = nullptr; static int success_val; @@ -99,7 +99,7 @@ broker::backend to_backend_type(BifEnum::Broker::BackendType type) } broker::backend_options to_backend_options(broker::backend backend, - RecordVal* options) + zeek::RecordVal* options) { switch ( backend ) { case broker::backend::sqlite: diff --git a/src/broker/Store.h b/src/broker/Store.h index 03b6fdd637..cd4c9e2298 100644 --- a/src/broker/Store.h +++ b/src/broker/Store.h @@ -11,24 +11,24 @@ namespace bro_broker { -extern IntrusivePtr opaque_of_store_handle; +extern zeek::OpaqueTypePtr opaque_of_store_handle; /** * Create a Broker::QueryStatus value. * @param success whether the query status should be set to success or failure. * @return a Broker::QueryStatus value. */ -IntrusivePtr query_status(bool success); +zeek::EnumValPtr query_status(bool success); /** * @return a Broker::QueryResult value that has a Broker::QueryStatus indicating * a failure. */ -inline IntrusivePtr query_result() +inline zeek::RecordValPtr query_result() { - auto rval = make_intrusive(zeek::BifType::Record::Broker::QueryResult); + auto rval = zeek::make_intrusive(zeek::BifType::Record::Broker::QueryResult); rval->Assign(0, query_status(false)); - rval->Assign(1, make_intrusive(zeek::BifType::Record::Broker::Data)); + rval->Assign(1, zeek::make_intrusive(zeek::BifType::Record::Broker::Data)); return rval; } @@ -37,9 +37,9 @@ inline IntrusivePtr query_result() * @return a Broker::QueryResult value that has a Broker::QueryStatus indicating * a success. */ -inline IntrusivePtr query_result(IntrusivePtr data) +inline zeek::RecordValPtr query_result(zeek::RecordValPtr data) { - auto rval = make_intrusive(zeek::BifType::Record::Broker::QueryResult); + auto rval = zeek::make_intrusive(zeek::BifType::Record::Broker::QueryResult); rval->Assign(0, query_status(true)); rval->Assign(1, std::move(data)); return rval; @@ -62,7 +62,7 @@ public: Unref(trigger); } - void Result(const IntrusivePtr& result) + void Result(const zeek::RecordValPtr& result) { trigger->Cache(call, result.get()); trigger->Release(); @@ -91,10 +91,10 @@ private: /** * An opaque handle which wraps a Broker data store. */ -class StoreHandleVal : public OpaqueVal { +class StoreHandleVal : public zeek::OpaqueVal { public: StoreHandleVal(broker::store s) - : OpaqueVal(bro_broker::opaque_of_store_handle), store{s}, proxy{store} + : zeek::OpaqueVal(bro_broker::opaque_of_store_handle), store{s}, proxy{store} { } void ValDescribe(ODesc* d) const override; @@ -104,11 +104,11 @@ public: protected: - IntrusivePtr DoClone(CloneState* state) override - { return {NewRef{}, this}; } + zeek::IntrusivePtr DoClone(CloneState* state) override + { return { zeek::NewRef{}, this }; } StoreHandleVal() - : OpaqueVal(bro_broker::opaque_of_store_handle) + : zeek::OpaqueVal(bro_broker::opaque_of_store_handle) {} DECLARE_OPAQUE_VALUE(StoreHandleVal) @@ -119,6 +119,6 @@ broker::backend to_backend_type(BifEnum::Broker::BackendType type); // Helper function to construct broker backend options from script land. broker::backend_options to_backend_options(broker::backend backend, - RecordVal* options); + zeek::RecordVal* options); } // namespace bro_broker diff --git a/src/broker/comm.bif b/src/broker/comm.bif index 6b63029f17..f9baff387f 100644 --- a/src/broker/comm.bif +++ b/src/broker/comm.bif @@ -22,7 +22,7 @@ event Broker::peer_lost%(endpoint: EndpointInfo, msg: string%); ## Generated when an error occurs in the Broker sub-system. event Broker::error%(code: ErrorCode, msg: string%); -## Enumerates the possible error types. +## Enumerates the possible error types. enum ErrorCode %{ UNSPECIFIED = 1, PEER_INCOMPATIBLE = 2, @@ -55,12 +55,12 @@ function Broker::__listen%(a: string, p: port%): port if ( ! p->IsTCP() ) { - builtin_error("listen port must use tcp"); - return val_mgr->Port(0, TRANSPORT_UNKNOWN); + zeek::emit_builtin_error("listen port must use tcp"); + return zeek::val_mgr->Port(0, TRANSPORT_UNKNOWN); } auto rval = broker_mgr->Listen(a->Len() ? a->CheckString() : "", p->Port()); - return val_mgr->Port(rval, TRANSPORT_TCP); + return zeek::val_mgr->Port(rval, TRANSPORT_TCP); %} function Broker::__peer%(a: string, p: port, retry: interval%): bool @@ -69,12 +69,12 @@ function Broker::__peer%(a: string, p: port, retry: interval%): bool if ( ! p->IsTCP() ) { - builtin_error("remote connection port must use tcp"); - return val_mgr->False(); + zeek::emit_builtin_error("remote connection port must use tcp"); + return zeek::val_mgr->False(); } broker_mgr->Peer(a->CheckString(), p->Port(), retry); - return val_mgr->True(); + return zeek::val_mgr->True(); %} function Broker::__unpeer%(a: string, p: port%): bool @@ -83,18 +83,18 @@ function Broker::__unpeer%(a: string, p: port%): bool if ( ! p->IsTCP() ) { - builtin_error("remote connection port must use tcp"); - return val_mgr->False(); + zeek::emit_builtin_error("remote connection port must use tcp"); + return zeek::val_mgr->False(); } broker_mgr->Unpeer(a->CheckString(), p->Port()); - return val_mgr->True(); + return zeek::val_mgr->True(); %} function Broker::__peers%(%): PeerInfos %{ bro_broker::Manager::ScriptScopeGuard ssg; - auto rval = make_intrusive(zeek::id::find_type("Broker::PeerInfos")); + auto rval = zeek::make_intrusive(zeek::id::find_type("Broker::PeerInfos")); auto i = 0; for ( auto& p : broker_mgr->Peers() ) @@ -102,23 +102,23 @@ function Broker::__peers%(%): PeerInfos const auto& pi = zeek::id::find_type("Broker::PeerInfo"); const auto& ei = zeek::id::find_type("Broker::EndpointInfo"); const auto& ni = zeek::id::find_type("Broker::NetworkInfo"); - auto peer_info = make_intrusive(pi); - auto endpoint_info = make_intrusive(ei); - auto network_info = make_intrusive(ni); + auto peer_info = zeek::make_intrusive(pi); + auto endpoint_info = zeek::make_intrusive(ei); + auto network_info = zeek::make_intrusive(ni); auto n = p.peer.network; if ( n ) { - network_info->Assign(0, make_intrusive(IPAddr(n->address))); - network_info->Assign(1, val_mgr->Port(n->port, TRANSPORT_TCP)); + network_info->Assign(0, zeek::make_intrusive(IPAddr(n->address))); + network_info->Assign(1, zeek::val_mgr->Port(n->port, TRANSPORT_TCP)); } else { - network_info->Assign(0, make_intrusive("0.0.0.0")); - network_info->Assign(1, val_mgr->Port(0, TRANSPORT_TCP)); + network_info->Assign(0, zeek::make_intrusive("0.0.0.0")); + network_info->Assign(1, zeek::val_mgr->Port(0, TRANSPORT_TCP)); } - endpoint_info->Assign(0, make_intrusive(to_string(p.peer.node))); + endpoint_info->Assign(0, zeek::make_intrusive(to_string(p.peer.node))); endpoint_info->Assign(1, std::move(network_info)); auto ps = (BifEnum::Broker::PeerStatus)p.status; @@ -135,5 +135,5 @@ function Broker::__peers%(%): PeerInfos function Broker::__node_id%(%): string %{ bro_broker::Manager::ScriptScopeGuard ssg; - return make_intrusive(broker_mgr->NodeID()); + return zeek::make_intrusive(broker_mgr->NodeID()); %} diff --git a/src/broker/data.bif b/src/broker/data.bif index 2091a1cb99..1d3cf1c799 100644 --- a/src/broker/data.bif +++ b/src/broker/data.bif @@ -48,8 +48,8 @@ function Broker::__opaque_clone_through_serialization%(d: any%): any if ( ! x ) { - builtin_error("cannot serialize object to clone"); - return val_mgr->False(); + zeek::emit_builtin_error("cannot serialize object to clone"); + return zeek::val_mgr->False(); } return OpaqueVal::Unserialize(std::move(*x)); @@ -65,14 +65,14 @@ function Broker::__set_clear%(s: Broker::Data%): bool auto& v = bro_broker::require_data_type(s->AsRecordVal(), zeek::TYPE_TABLE, frame); v.clear(); - return val_mgr->True(); + return zeek::val_mgr->True(); %} function Broker::__set_size%(s: Broker::Data%): count %{ auto& v = bro_broker::require_data_type(s->AsRecordVal(), zeek::TYPE_TABLE, frame); - return val_mgr->Count(static_cast(v.size())); + return zeek::val_mgr->Count(static_cast(v.size())); %} function Broker::__set_contains%(s: Broker::Data, key: any%): bool @@ -83,11 +83,11 @@ function Broker::__set_contains%(s: Broker::Data, key: any%): bool if ( ! k ) { - builtin_error("invalid Broker data conversion for key argument"); - return val_mgr->False(); + zeek::emit_builtin_error("invalid Broker data conversion for key argument"); + return zeek::val_mgr->False(); } - return val_mgr->Bool(v.find(*k) != v.end()); + return zeek::val_mgr->Bool(v.find(*k) != v.end()); %} function Broker::__set_insert%(s: Broker::Data, key: any%): bool @@ -99,11 +99,11 @@ function Broker::__set_insert%(s: Broker::Data, key: any%): bool if ( ! k ) { - builtin_error("invalid Broker data conversion for key argument"); - return val_mgr->False(); + zeek::emit_builtin_error("invalid Broker data conversion for key argument"); + return zeek::val_mgr->False(); } - return val_mgr->Bool(v.insert(std::move(*k)).second); + return zeek::val_mgr->Bool(v.insert(std::move(*k)).second); %} function Broker::__set_remove%(s: Broker::Data, key: any%): bool @@ -114,22 +114,22 @@ function Broker::__set_remove%(s: Broker::Data, key: any%): bool if ( ! k ) { - builtin_error("invalid Broker data conversion for key argument"); - return val_mgr->False(); + zeek::emit_builtin_error("invalid Broker data conversion for key argument"); + return zeek::val_mgr->False(); } - return val_mgr->Bool(v.erase(*k) > 0); + return zeek::val_mgr->Bool(v.erase(*k) > 0); %} function Broker::__set_iterator%(s: Broker::Data%): opaque of Broker::SetIterator %{ - return make_intrusive(s->AsRecordVal(), zeek::TYPE_TABLE, frame); + return zeek::make_intrusive(s->AsRecordVal(), zeek::TYPE_TABLE, frame); %} function Broker::__set_iterator_last%(it: opaque of Broker::SetIterator%): bool %{ auto set_it = static_cast(it); - return val_mgr->Bool(set_it->it == set_it->dat.end()); + return zeek::val_mgr->Bool(set_it->it == set_it->dat.end()); %} function Broker::__set_iterator_next%(it: opaque of Broker::SetIterator%): bool @@ -137,24 +137,24 @@ function Broker::__set_iterator_next%(it: opaque of Broker::SetIterator%): bool auto set_it = static_cast(it); if ( set_it->it == set_it->dat.end() ) - return val_mgr->False(); + return zeek::val_mgr->False(); ++set_it->it; - return val_mgr->Bool(set_it->it != set_it->dat.end()); + return zeek::val_mgr->Bool(set_it->it != set_it->dat.end()); %} function Broker::__set_iterator_value%(it: opaque of Broker::SetIterator%): Broker::Data %{ auto set_it = static_cast(it); - auto rval = make_intrusive(zeek::BifType::Record::Broker::Data); + auto rval = zeek::make_intrusive(zeek::BifType::Record::Broker::Data); if ( set_it->it == set_it->dat.end() ) { - builtin_error("attempt to retrieve value of invalid set iterator"); + zeek::emit_builtin_error("attempt to retrieve value of invalid set iterator"); return rval; } - rval->Assign(0, make_intrusive(*set_it->it)); + rval->Assign(0, zeek::make_intrusive(*set_it->it)); return rval; %} @@ -168,14 +168,14 @@ function Broker::__table_clear%(t: Broker::Data%): bool auto& v = bro_broker::require_data_type(t->AsRecordVal(), zeek::TYPE_TABLE, frame); v.clear(); - return val_mgr->True(); + return zeek::val_mgr->True(); %} function Broker::__table_size%(t: Broker::Data%): count %{ auto& v = bro_broker::require_data_type(t->AsRecordVal(), zeek::TYPE_TABLE, frame); - return val_mgr->Count(static_cast(v.size())); + return zeek::val_mgr->Count(static_cast(v.size())); %} function Broker::__table_contains%(t: Broker::Data, key: any%): bool @@ -187,11 +187,11 @@ function Broker::__table_contains%(t: Broker::Data, key: any%): bool if ( ! k ) { - builtin_error("invalid Broker data conversion for key argument"); - return val_mgr->False(); + zeek::emit_builtin_error("invalid Broker data conversion for key argument"); + return zeek::val_mgr->False(); } - return val_mgr->Bool(v.find(*k) != v.end()); + return zeek::val_mgr->Bool(v.find(*k) != v.end()); %} function Broker::__table_insert%(t: Broker::Data, key: any, val: any%): Broker::Data @@ -203,16 +203,16 @@ function Broker::__table_insert%(t: Broker::Data, key: any, val: any%): Broker:: if ( ! k ) { - builtin_error("invalid Broker data conversion for key argument"); - return make_intrusive(zeek::BifType::Record::Broker::Data); + zeek::emit_builtin_error("invalid Broker data conversion for key argument"); + return zeek::make_intrusive(zeek::BifType::Record::Broker::Data); } auto v = bro_broker::val_to_data(val); if ( ! v ) { - builtin_error("invalid Broker data conversion for value argument"); - return make_intrusive(zeek::BifType::Record::Broker::Data); + zeek::emit_builtin_error("invalid Broker data conversion for value argument"); + return zeek::make_intrusive(zeek::BifType::Record::Broker::Data); } try @@ -225,7 +225,7 @@ function Broker::__table_insert%(t: Broker::Data, key: any, val: any%): Broker:: catch (const std::out_of_range&) { table[std::move(*k)] = std::move(*v); - return make_intrusive(zeek::BifType::Record::Broker::Data); + return zeek::make_intrusive(zeek::BifType::Record::Broker::Data); } %} @@ -238,14 +238,14 @@ function Broker::__table_remove%(t: Broker::Data, key: any%): Broker::Data if ( ! k ) { - builtin_error("invalid Broker data conversion for key argument"); - return make_intrusive(zeek::BifType::Record::Broker::Data); + zeek::emit_builtin_error("invalid Broker data conversion for key argument"); + return zeek::make_intrusive(zeek::BifType::Record::Broker::Data); } auto it = table.find(*k); if ( it == table.end() ) - return make_intrusive(zeek::BifType::Record::Broker::Data); + return zeek::make_intrusive(zeek::BifType::Record::Broker::Data); else { auto rval = bro_broker::make_data_val(move(it->second)); @@ -263,27 +263,27 @@ function Broker::__table_lookup%(t: Broker::Data, key: any%): Broker::Data if ( ! k ) { - builtin_error("invalid Broker data conversion for key argument"); - return make_intrusive(zeek::BifType::Record::Broker::Data); + zeek::emit_builtin_error("invalid Broker data conversion for key argument"); + return zeek::make_intrusive(zeek::BifType::Record::Broker::Data); } auto it = table.find(*k); if ( it == table.end() ) - return make_intrusive(zeek::BifType::Record::Broker::Data); + return zeek::make_intrusive(zeek::BifType::Record::Broker::Data); else return bro_broker::make_data_val(it->second); %} function Broker::__table_iterator%(t: Broker::Data%): opaque of Broker::TableIterator %{ - return make_intrusive(t->AsRecordVal(), zeek::TYPE_TABLE, frame); + return zeek::make_intrusive(t->AsRecordVal(), zeek::TYPE_TABLE, frame); %} function Broker::__table_iterator_last%(it: opaque of Broker::TableIterator%): bool %{ auto ti = static_cast(it); - return val_mgr->Bool(ti->it == ti->dat.end()); + return zeek::val_mgr->Bool(ti->it == ti->dat.end()); %} function Broker::__table_iterator_next%(it: opaque of Broker::TableIterator%): bool @@ -291,29 +291,29 @@ function Broker::__table_iterator_next%(it: opaque of Broker::TableIterator%): b auto ti = static_cast(it); if ( ti->it == ti->dat.end() ) - return val_mgr->False(); + return zeek::val_mgr->False(); ++ti->it; - return val_mgr->Bool(ti->it != ti->dat.end()); + return zeek::val_mgr->Bool(ti->it != ti->dat.end()); %} function Broker::__table_iterator_value%(it: opaque of Broker::TableIterator%): Broker::TableItem %{ auto ti = static_cast(it); - auto rval = make_intrusive(zeek::BifType::Record::Broker::TableItem); - auto key_val = make_intrusive(zeek::BifType::Record::Broker::Data); - auto val_val = make_intrusive(zeek::BifType::Record::Broker::Data); + auto rval = zeek::make_intrusive(zeek::BifType::Record::Broker::TableItem); + auto key_val = zeek::make_intrusive(zeek::BifType::Record::Broker::Data); + auto val_val = zeek::make_intrusive(zeek::BifType::Record::Broker::Data); rval->Assign(0, key_val); rval->Assign(1, val_val); if ( ti->it == ti->dat.end() ) { - builtin_error("attempt to retrieve value of invalid table iterator"); + zeek::emit_builtin_error("attempt to retrieve value of invalid table iterator"); return rval; } - key_val->Assign(0, make_intrusive(ti->it->first)); - val_val->Assign(0, make_intrusive(ti->it->second)); + key_val->Assign(0, zeek::make_intrusive(ti->it->first)); + val_val->Assign(0, zeek::make_intrusive(ti->it->second)); return rval; %} @@ -327,14 +327,14 @@ function Broker::__vector_clear%(v: Broker::Data%): bool auto& vec = bro_broker::require_data_type(v->AsRecordVal(), zeek::TYPE_VECTOR, frame); vec.clear(); - return val_mgr->True(); + return zeek::val_mgr->True(); %} function Broker::__vector_size%(v: Broker::Data%): count %{ auto& vec = bro_broker::require_data_type(v->AsRecordVal(), zeek::TYPE_VECTOR, frame); - return val_mgr->Count(static_cast(vec.size())); + return zeek::val_mgr->Count(static_cast(vec.size())); %} function Broker::__vector_insert%(v: Broker::Data, idx:count, d: any%): bool @@ -345,13 +345,13 @@ function Broker::__vector_insert%(v: Broker::Data, idx:count, d: any%): bool if ( ! item ) { - builtin_error("invalid Broker data conversion for item argument"); - return val_mgr->False(); + zeek::emit_builtin_error("invalid Broker data conversion for item argument"); + return zeek::val_mgr->False(); } idx = min(idx, static_cast(vec.size())); vec.insert(vec.begin() + idx, std::move(*item)); - return val_mgr->True(); + return zeek::val_mgr->True(); %} function Broker::__vector_replace%(v: Broker::Data, idx: count, d: any%): Broker::Data @@ -362,12 +362,12 @@ function Broker::__vector_replace%(v: Broker::Data, idx: count, d: any%): Broker if ( ! item ) { - builtin_error("invalid Broker data conversion for item argument"); - return val_mgr->False(); + zeek::emit_builtin_error("invalid Broker data conversion for item argument"); + return zeek::val_mgr->False(); } if ( idx >= vec.size() ) - return make_intrusive(zeek::BifType::Record::Broker::Data); + return zeek::make_intrusive(zeek::BifType::Record::Broker::Data); auto rval = bro_broker::make_data_val(move(vec[idx])); vec[idx] = std::move(*item); @@ -380,7 +380,7 @@ function Broker::__vector_remove%(v: Broker::Data, idx: count%): Broker::Data zeek::TYPE_VECTOR, frame); if ( idx >= vec.size() ) - return make_intrusive(zeek::BifType::Record::Broker::Data); + return zeek::make_intrusive(zeek::BifType::Record::Broker::Data); auto rval = bro_broker::make_data_val(move(vec[idx])); vec.erase(vec.begin() + idx); @@ -393,20 +393,20 @@ function Broker::__vector_lookup%(v: Broker::Data, idx: count%): Broker::Data zeek::TYPE_VECTOR, frame); if ( idx >= vec.size() ) - return make_intrusive(zeek::BifType::Record::Broker::Data); + return zeek::make_intrusive(zeek::BifType::Record::Broker::Data); return bro_broker::make_data_val(vec[idx]); %} function Broker::__vector_iterator%(v: Broker::Data%): opaque of Broker::VectorIterator %{ - return make_intrusive(v->AsRecordVal(), zeek::TYPE_VECTOR, frame); + return zeek::make_intrusive(v->AsRecordVal(), zeek::TYPE_VECTOR, frame); %} function Broker::__vector_iterator_last%(it: opaque of Broker::VectorIterator%): bool %{ auto vi = static_cast(it); - return val_mgr->Bool(vi->it == vi->dat.end()); + return zeek::val_mgr->Bool(vi->it == vi->dat.end()); %} function Broker::__vector_iterator_next%(it: opaque of Broker::VectorIterator%): bool @@ -414,24 +414,24 @@ function Broker::__vector_iterator_next%(it: opaque of Broker::VectorIterator%): auto vi = static_cast(it); if ( vi->it == vi->dat.end() ) - return val_mgr->False(); + return zeek::val_mgr->False(); ++vi->it; - return val_mgr->Bool(vi->it != vi->dat.end()); + return zeek::val_mgr->Bool(vi->it != vi->dat.end()); %} function Broker::__vector_iterator_value%(it: opaque of Broker::VectorIterator%): Broker::Data %{ auto vi = static_cast(it); - auto rval = make_intrusive(zeek::BifType::Record::Broker::Data); + auto rval = zeek::make_intrusive(zeek::BifType::Record::Broker::Data); if ( vi->it == vi->dat.end() ) { - builtin_error("attempt to retrieve value of invalid vector iterator"); + zeek::emit_builtin_error("attempt to retrieve value of invalid vector iterator"); return rval; } - rval->Assign(0, make_intrusive(*vi->it)); + rval->Assign(0, zeek::make_intrusive(*vi->it)); return rval; %} @@ -444,7 +444,7 @@ function Broker::__record_size%(r: Broker::Data%): count %{ auto& v = bro_broker::require_data_type(r->AsRecordVal(), zeek::TYPE_RECORD, frame); - return val_mgr->Count(static_cast(v.size())); + return zeek::val_mgr->Count(static_cast(v.size())); %} function Broker::__record_assign%(r: Broker::Data, idx: count, d: any%): bool @@ -452,18 +452,18 @@ function Broker::__record_assign%(r: Broker::Data, idx: count, d: any%): bool auto& v = bro_broker::require_data_type(r->AsRecordVal(), zeek::TYPE_RECORD, frame); if ( idx >= v.size() ) - return val_mgr->False(); + return zeek::val_mgr->False(); auto item = bro_broker::val_to_data(d); if ( ! item ) { - builtin_error("invalid Broker data conversion for item argument"); - return val_mgr->False(); + zeek::emit_builtin_error("invalid Broker data conversion for item argument"); + return zeek::val_mgr->False(); } v[idx] = std::move(*item); - return val_mgr->True(); + return zeek::val_mgr->True(); %} function Broker::__record_lookup%(r: Broker::Data, idx: count%): Broker::Data @@ -472,20 +472,20 @@ function Broker::__record_lookup%(r: Broker::Data, idx: count%): Broker::Data zeek::TYPE_RECORD, frame); if ( idx >= v.size() || caf::get_if(&v[idx]) ) - return make_intrusive(zeek::BifType::Record::Broker::Data); + return zeek::make_intrusive(zeek::BifType::Record::Broker::Data); return bro_broker::make_data_val(v[idx]); %} function Broker::__record_iterator%(r: Broker::Data%): opaque of Broker::RecordIterator %{ - return make_intrusive(r->AsRecordVal(), zeek::TYPE_RECORD, frame); + return zeek::make_intrusive(r->AsRecordVal(), zeek::TYPE_RECORD, frame); %} function Broker::__record_iterator_last%(it: opaque of Broker::RecordIterator%): bool %{ auto ri = static_cast(it); - return val_mgr->Bool(ri->it == ri->dat.end()); + return zeek::val_mgr->Bool(ri->it == ri->dat.end()); %} function Broker::__record_iterator_next%(it: opaque of Broker::RecordIterator%): bool @@ -493,26 +493,26 @@ function Broker::__record_iterator_next%(it: opaque of Broker::RecordIterator%): auto ri = static_cast(it); if ( ri->it == ri->dat.end() ) - return val_mgr->False(); + return zeek::val_mgr->False(); ++ri->it; - return val_mgr->Bool(ri->it != ri->dat.end()); + return zeek::val_mgr->Bool(ri->it != ri->dat.end()); %} function Broker::__record_iterator_value%(it: opaque of Broker::RecordIterator%): Broker::Data %{ auto ri = static_cast(it); - auto rval = make_intrusive(zeek::BifType::Record::Broker::Data); + auto rval = zeek::make_intrusive(zeek::BifType::Record::Broker::Data); if ( ri->it == ri->dat.end() ) { - builtin_error("attempt to retrieve value of invalid record iterator"); + zeek::emit_builtin_error("attempt to retrieve value of invalid record iterator"); return rval; } if ( caf::get_if(&(*ri->it)) ) return rval; // field isn't set - rval->Assign(0, make_intrusive(*ri->it)); + rval->Assign(0, zeek::make_intrusive(*ri->it)); return rval; %} diff --git a/src/broker/messaging.bif b/src/broker/messaging.bif index 0bfa56796e..bae4ad625c 100644 --- a/src/broker/messaging.bif +++ b/src/broker/messaging.bif @@ -20,7 +20,7 @@ static bool is_string_set(const zeek::Type* type) return index_types[0]->Tag() == zeek::TYPE_STRING; } -std::set val_to_topic_set(Val* val) +std::set val_to_topic_set(zeek::Val* val) { std::set rval; @@ -28,12 +28,12 @@ std::set val_to_topic_set(Val* val) rval.emplace(val->AsString()->CheckString()); else { - const PDict* tbl = val->AsTable(); + const zeek::PDict* tbl = val->AsTable(); if ( tbl->Length() == 0 ) return rval; - IterCookie* c = tbl->InitForIteration(); + zeek::IterCookie* c = tbl->InitForIteration(); HashKey* k; while ( tbl->NextEntry(k, c) ) @@ -47,8 +47,8 @@ std::set val_to_topic_set(Val* val) return rval; } -static bool publish_event_args(val_list& args, const BroString* topic, - Frame* frame) +static bool publish_event_args(val_list& args, const zeek::String* topic, + zeek::detail::Frame* frame) { bro_broker::Manager::ScriptScopeGuard ssg; auto rval = false; @@ -89,7 +89,7 @@ function Broker::make_event%(...%): Broker::Event for ( auto i = 0u; i < bif_args->size(); ++i ) args.push_back((*bif_args)[i].get()); - return IntrusivePtr{AdoptRef{}, broker_mgr->MakeEvent(&args, frame)}; + return RecordValPtr{zeek::AdoptRef{}, broker_mgr->MakeEvent(&args, frame)}; %} ## Publishes an event at a given topic. @@ -110,13 +110,13 @@ function Broker::publish%(topic: string, ...%): bool args.push_back((*bif_args)[i].get()); auto rval = publish_event_args(args, topic->AsString(), frame); - return val_mgr->Bool(rval); + return zeek::val_mgr->Bool(rval); %} function Broker::__flush_logs%(%): count %{ auto rval = broker_mgr->FlushLogBuffers(); - return val_mgr->Count(static_cast(rval)); + return zeek::val_mgr->Count(static_cast(rval)); %} function Broker::__publish_id%(topic: string, id: string%): bool @@ -124,42 +124,42 @@ function Broker::__publish_id%(topic: string, id: string%): bool bro_broker::Manager::ScriptScopeGuard ssg; auto rval = broker_mgr->PublishIdentifier(topic->CheckString(), id->CheckString()); - return val_mgr->Bool(rval); + return zeek::val_mgr->Bool(rval); %} function Broker::__auto_publish%(topic: string, ev: any%): bool %{ bro_broker::Manager::ScriptScopeGuard ssg; auto rval = broker_mgr->AutoPublishEvent(topic->CheckString(), ev); - return val_mgr->Bool(rval); + return zeek::val_mgr->Bool(rval); %} function Broker::__auto_unpublish%(topic: string, ev: any%): bool %{ bro_broker::Manager::ScriptScopeGuard ssg; auto rval = broker_mgr->AutoUnpublishEvent(topic->CheckString(), ev); - return val_mgr->Bool(rval); + return zeek::val_mgr->Bool(rval); %} function Broker::__subscribe%(topic_prefix: string%): bool %{ bro_broker::Manager::ScriptScopeGuard ssg; auto rval = broker_mgr->Subscribe(topic_prefix->CheckString()); - return val_mgr->Bool(rval); + return zeek::val_mgr->Bool(rval); %} function Broker::__forward%(topic_prefix: string%): bool %{ bro_broker::Manager::ScriptScopeGuard ssg; auto rval = broker_mgr->Forward(topic_prefix->CheckString()); - return val_mgr->Bool(rval); + return zeek::val_mgr->Bool(rval); %} function Broker::__unsubscribe%(topic_prefix: string%): bool %{ bro_broker::Manager::ScriptScopeGuard ssg; auto rval = broker_mgr->Unsubscribe(topic_prefix->CheckString()); - return val_mgr->Bool(rval); + return zeek::val_mgr->Bool(rval); %} module Cluster; @@ -182,16 +182,16 @@ type Cluster::Pool: record; ## Returns: true if the message is sent. function Cluster::publish_rr%(pool: Pool, key: string, ...%): bool %{ - static Func* topic_func = 0; + static zeek::Func* topic_func = nullptr; if ( ! topic_func ) - topic_func = global_scope()->Find("Cluster::rr_topic")->GetVal()->AsFunc(); + topic_func = zeek::detail::global_scope()->Find("Cluster::rr_topic")->GetVal()->AsFunc(); - zeek::Args vl{{NewRef{}, pool}, {NewRef{}, key}}; + zeek::Args vl{{zeek::NewRef{}, pool}, {zeek::NewRef{}, key}}; auto topic = topic_func->Invoke(&vl); if ( ! topic->AsString()->Len() ) - return val_mgr->False(); + return zeek::val_mgr->False(); const auto& bif_args = @ARGS@; val_list args(bif_args->size() - 2); @@ -200,7 +200,7 @@ function Cluster::publish_rr%(pool: Pool, key: string, ...%): bool args.push_back((*bif_args)[i].get()); auto rval = publish_event_args(args, topic->AsString(), frame); - return val_mgr->Bool(rval); + return zeek::val_mgr->Bool(rval); %} @@ -219,16 +219,16 @@ function Cluster::publish_rr%(pool: Pool, key: string, ...%): bool ## Returns: true if the message is sent. function Cluster::publish_hrw%(pool: Pool, key: any, ...%): bool %{ - static Func* topic_func = 0; + static zeek::Func* topic_func = nullptr; if ( ! topic_func ) - topic_func = global_scope()->Find("Cluster::hrw_topic")->GetVal()->AsFunc(); + topic_func = zeek::detail::global_scope()->Find("Cluster::hrw_topic")->GetVal()->AsFunc(); - zeek::Args vl{{NewRef{}, pool}, {NewRef{}, key}}; + zeek::Args vl{{zeek::NewRef{}, pool}, {zeek::NewRef{}, key}}; auto topic = topic_func->Invoke(&vl); if ( ! topic->AsString()->Len() ) - return val_mgr->False(); + return zeek::val_mgr->False(); const auto& bif_args = @ARGS@; val_list args(bif_args->size() - 2); @@ -237,5 +237,5 @@ function Cluster::publish_hrw%(pool: Pool, key: any, ...%): bool args.push_back((*bif_args)[i].get()); auto rval = publish_event_args(args, topic->AsString(), frame); - return val_mgr->Bool(rval); + return zeek::val_mgr->Bool(rval); %} diff --git a/src/broker/store.bif b/src/broker/store.bif index 68262f667b..8b4b955724 100644 --- a/src/broker/store.bif +++ b/src/broker/store.bif @@ -42,17 +42,17 @@ function Broker::__create_master%(id: string, b: BackendType, auto rval = broker_mgr->LookupStore(name); if ( rval ) - return IntrusivePtr{NewRef{}, rval}; + return ValPtr{zeek::NewRef{}, rval}; auto e = static_cast(b->AsEnum()); auto type = bro_broker::to_backend_type(e); auto opts = bro_broker::to_backend_options(type, options->AsRecordVal()); - IntrusivePtr store{AdoptRef{}, broker_mgr->MakeMaster(name, type, std::move(opts))}; + ValPtr store{zeek::AdoptRef{}, broker_mgr->MakeMaster(name, type, std::move(opts))}; if ( ! store ) { - builtin_error(fmt("Could not create Broker master store '%s'", name)); + zeek::emit_builtin_error(fmt("Could not create Broker master store '%s'", name)); return nullptr; } @@ -68,16 +68,16 @@ function Broker::__create_clone%(id: string, resync_interval: interval, auto rval = broker_mgr->LookupStore(name); if ( rval ) - return IntrusivePtr{NewRef{}, rval}; + return ValPtr{zeek::NewRef{}, rval}; - IntrusivePtr store {AdoptRef{}, - broker_mgr->MakeClone(name, resync_interval, - stale_interval, - mutation_buffer_interval)}; + ValPtr store {zeek::AdoptRef{}, + broker_mgr->MakeClone(name, resync_interval, + stale_interval, + mutation_buffer_interval)}; if ( ! store ) { - builtin_error(fmt("Could not create clone of Broker store '%s'", name)); + zeek::emit_builtin_error(fmt("Could not create clone of Broker store '%s'", name)); return nullptr; } @@ -90,12 +90,12 @@ function Broker::__is_closed%(h: opaque of Broker::Store%): bool if ( ! h ) { - builtin_error("invalid Broker store handle"); - return val_mgr->False(); + zeek::emit_builtin_error("invalid Broker store handle"); + return zeek::val_mgr->False(); } auto handle = static_cast(h); - return val_mgr->Bool(broker_mgr->LookupStore(handle->store.name())); + return zeek::val_mgr->Bool(broker_mgr->LookupStore(handle->store.name())); %} function Broker::__close%(h: opaque of Broker::Store%): bool @@ -104,24 +104,24 @@ function Broker::__close%(h: opaque of Broker::Store%): bool if ( ! h ) { - builtin_error("invalid Broker store handle"); - return val_mgr->False(); + zeek::emit_builtin_error("invalid Broker store handle"); + return zeek::val_mgr->False(); } auto handle = static_cast(h); - return val_mgr->Bool(broker_mgr->CloseStore(handle->store.name())); + return zeek::val_mgr->Bool(broker_mgr->CloseStore(handle->store.name())); %} function Broker::__store_name%(h: opaque of Broker::Store%): string %{ if ( ! h ) { - builtin_error("invalid Broker store handle"); - return val_mgr->EmptyString(); + zeek::emit_builtin_error("invalid Broker store handle"); + return zeek::val_mgr->EmptyString(); } auto handle = static_cast(h); - return make_intrusive(handle->store.name()); + return zeek::make_intrusive(handle->store.name()); %} function Broker::__exists%(h: opaque of Broker::Store, @@ -129,8 +129,8 @@ function Broker::__exists%(h: opaque of Broker::Store, %{ if ( ! h ) { - builtin_error("invalid Broker store handle"); - return val_mgr->False(); + zeek::emit_builtin_error("invalid Broker store handle"); + return zeek::val_mgr->False(); } auto handle = static_cast(h); @@ -138,7 +138,7 @@ function Broker::__exists%(h: opaque of Broker::Store, if ( ! key ) { - builtin_error("invalid Broker data conversion for key argument"); + zeek::emit_builtin_error("invalid Broker data conversion for key argument"); return bro_broker::query_result(); } @@ -146,7 +146,7 @@ function Broker::__exists%(h: opaque of Broker::Store, if ( ! trigger ) { - builtin_error("Broker queries can only be called inside when-condition"); + zeek::emit_builtin_error("Broker queries can only be called inside when-condition"); return bro_broker::query_result(); } @@ -154,7 +154,7 @@ function Broker::__exists%(h: opaque of Broker::Store, if ( timeout < 0 ) { - builtin_error("Broker queries must specify a timeout block"); + zeek::emit_builtin_error("Broker queries must specify a timeout block"); return bro_broker::query_result(); } @@ -174,8 +174,8 @@ function Broker::__get%(h: opaque of Broker::Store, %{ if ( ! h ) { - builtin_error("invalid Broker store handle"); - return val_mgr->False(); + zeek::emit_builtin_error("invalid Broker store handle"); + return zeek::val_mgr->False(); } auto handle = static_cast(h); @@ -183,7 +183,7 @@ function Broker::__get%(h: opaque of Broker::Store, if ( ! key ) { - builtin_error("invalid Broker data conversion for key argument"); + zeek::emit_builtin_error("invalid Broker data conversion for key argument"); return bro_broker::query_result(); } @@ -191,7 +191,7 @@ function Broker::__get%(h: opaque of Broker::Store, if ( ! trigger ) { - builtin_error("Broker queries can only be called inside when-condition"); + zeek::emit_builtin_error("Broker queries can only be called inside when-condition"); return bro_broker::query_result(); } @@ -199,7 +199,7 @@ function Broker::__get%(h: opaque of Broker::Store, if ( timeout < 0 ) { - builtin_error("Broker queries must specify a timeout block"); + zeek::emit_builtin_error("Broker queries must specify a timeout block"); return bro_broker::query_result(); } @@ -219,8 +219,8 @@ function Broker::__put_unique%(h: opaque of Broker::Store, %{ if ( ! h ) { - builtin_error("invalid Broker store handle"); - return val_mgr->False(); + zeek::emit_builtin_error("invalid Broker store handle"); + return zeek::val_mgr->False(); } auto handle = static_cast(h); @@ -229,13 +229,13 @@ function Broker::__put_unique%(h: opaque of Broker::Store, if ( ! key ) { - builtin_error("invalid Broker data conversion for key argument"); + zeek::emit_builtin_error("invalid Broker data conversion for key argument"); return bro_broker::query_result(); } if ( ! val ) { - builtin_error("invalid Broker data conversion for value argument"); + zeek::emit_builtin_error("invalid Broker data conversion for value argument"); return bro_broker::query_result(); } @@ -243,7 +243,7 @@ function Broker::__put_unique%(h: opaque of Broker::Store, if ( ! trigger ) { - builtin_error("Broker queries can only be called inside when-condition"); + zeek::emit_builtin_error("Broker queries can only be called inside when-condition"); return bro_broker::query_result(); } @@ -251,7 +251,7 @@ function Broker::__put_unique%(h: opaque of Broker::Store, if ( timeout < 0 ) { - builtin_error("Broker queries must specify a timeout block"); + zeek::emit_builtin_error("Broker queries must specify a timeout block"); return bro_broker::query_result(); } @@ -273,8 +273,8 @@ function Broker::__get_index_from_value%(h: opaque of Broker::Store, %{ if ( ! h ) { - builtin_error("invalid Broker store handle"); - return val_mgr->False(); + zeek::emit_builtin_error("invalid Broker store handle"); + return zeek::val_mgr->False(); } auto handle = static_cast(h); @@ -282,7 +282,7 @@ function Broker::__get_index_from_value%(h: opaque of Broker::Store, if ( ! key ) { - builtin_error("invalid Broker data conversion for key argument"); + zeek::emit_builtin_error("invalid Broker data conversion for key argument"); return bro_broker::query_result(); } @@ -290,15 +290,15 @@ function Broker::__get_index_from_value%(h: opaque of Broker::Store, if ( ! index ) { - builtin_error("invalid Broker data conversion for index argument"); + zeek::emit_builtin_error("invalid Broker data conversion for index argument"); return bro_broker::query_result(); } - + auto trigger = frame->GetTrigger(); if ( ! trigger ) { - builtin_error("Broker queries can only be called inside when-condition"); + zeek::emit_builtin_error("Broker queries can only be called inside when-condition"); return bro_broker::query_result(); } @@ -306,7 +306,7 @@ function Broker::__get_index_from_value%(h: opaque of Broker::Store, if ( timeout < 0 ) { - builtin_error("Broker queries must specify a timeout block"); + zeek::emit_builtin_error("Broker queries must specify a timeout block"); return bro_broker::query_result(); } @@ -326,8 +326,8 @@ function Broker::__keys%(h: opaque of Broker::Store%): Broker::QueryResult %{ if ( ! h ) { - builtin_error("invalid Broker store handle"); - return val_mgr->False(); + zeek::emit_builtin_error("invalid Broker store handle"); + return zeek::val_mgr->False(); } auto handle = static_cast(h); @@ -336,7 +336,7 @@ function Broker::__keys%(h: opaque of Broker::Store%): Broker::QueryResult if ( ! trigger ) { - builtin_error("Broker queries can only be called inside when-condition"); + zeek::emit_builtin_error("Broker queries can only be called inside when-condition"); return bro_broker::query_result(); } @@ -344,7 +344,7 @@ function Broker::__keys%(h: opaque of Broker::Store%): Broker::QueryResult if ( timeout < 0 ) { - builtin_error("Broker queries must specify a timeout block"); + zeek::emit_builtin_error("Broker queries must specify a timeout block"); return bro_broker::query_result(); } @@ -364,8 +364,8 @@ function Broker::__put%(h: opaque of Broker::Store, %{ if ( ! h ) { - builtin_error("invalid Broker store handle"); - return val_mgr->False(); + zeek::emit_builtin_error("invalid Broker store handle"); + return zeek::val_mgr->False(); } auto handle = static_cast(h); @@ -374,26 +374,26 @@ function Broker::__put%(h: opaque of Broker::Store, if ( ! key ) { - builtin_error("invalid Broker data conversion for key argument"); - return val_mgr->False(); + zeek::emit_builtin_error("invalid Broker data conversion for key argument"); + return zeek::val_mgr->False(); } if ( ! val ) { - builtin_error("invalid Broker data conversion for value argument"); - return val_mgr->False(); + zeek::emit_builtin_error("invalid Broker data conversion for value argument"); + return zeek::val_mgr->False(); } handle->store.put(std::move(*key), std::move(*val), prepare_expiry(e)); - return val_mgr->True(); + return zeek::val_mgr->True(); %} function Broker::__erase%(h: opaque of Broker::Store, k: any%): bool %{ if ( ! h ) { - builtin_error("invalid Broker store handle"); - return val_mgr->False(); + zeek::emit_builtin_error("invalid Broker store handle"); + return zeek::val_mgr->False(); } auto handle = static_cast(h); @@ -401,12 +401,12 @@ function Broker::__erase%(h: opaque of Broker::Store, k: any%): bool if ( ! key ) { - builtin_error("invalid Broker data conversion for key argument"); - return val_mgr->False(); + zeek::emit_builtin_error("invalid Broker data conversion for key argument"); + return zeek::val_mgr->False(); } handle->store.erase(std::move(*key)); - return val_mgr->True(); + return zeek::val_mgr->True(); %} function Broker::__increment%(h: opaque of Broker::Store, k: any, a: any, @@ -414,8 +414,8 @@ function Broker::__increment%(h: opaque of Broker::Store, k: any, a: any, %{ if ( ! h ) { - builtin_error("invalid Broker store handle"); - return val_mgr->False(); + zeek::emit_builtin_error("invalid Broker store handle"); + return zeek::val_mgr->False(); } auto handle = static_cast(h); @@ -424,19 +424,19 @@ function Broker::__increment%(h: opaque of Broker::Store, k: any, a: any, if ( ! key ) { - builtin_error("invalid Broker data conversion for key argument"); - return val_mgr->False(); + zeek::emit_builtin_error("invalid Broker data conversion for key argument"); + return zeek::val_mgr->False(); } if ( ! amount ) { - builtin_error("invalid Broker data conversion for amount argument"); - return val_mgr->False(); + zeek::emit_builtin_error("invalid Broker data conversion for amount argument"); + return zeek::val_mgr->False(); } handle->store.increment(std::move(*key), std::move(*amount), prepare_expiry(e)); - return val_mgr->True(); + return zeek::val_mgr->True(); %} function Broker::__decrement%(h: opaque of Broker::Store, k: any, a: any, @@ -444,8 +444,8 @@ function Broker::__decrement%(h: opaque of Broker::Store, k: any, a: any, %{ if ( ! h ) { - builtin_error("invalid Broker store handle"); - return val_mgr->False(); + zeek::emit_builtin_error("invalid Broker store handle"); + return zeek::val_mgr->False(); } auto handle = static_cast(h); @@ -454,18 +454,18 @@ function Broker::__decrement%(h: opaque of Broker::Store, k: any, a: any, if ( ! key ) { - builtin_error("invalid Broker data conversion for key argument"); - return val_mgr->False(); + zeek::emit_builtin_error("invalid Broker data conversion for key argument"); + return zeek::val_mgr->False(); } if ( ! amount ) { - builtin_error("invalid Broker data conversion for amount argument"); - return val_mgr->False(); + zeek::emit_builtin_error("invalid Broker data conversion for amount argument"); + return zeek::val_mgr->False(); } handle->store.decrement(std::move(*key), std::move(*amount), prepare_expiry(e)); - return val_mgr->True(); + return zeek::val_mgr->True(); %} function Broker::__append%(h: opaque of Broker::Store, k: any, s: any, @@ -473,8 +473,8 @@ function Broker::__append%(h: opaque of Broker::Store, k: any, s: any, %{ if ( ! h ) { - builtin_error("invalid Broker store handle"); - return val_mgr->False(); + zeek::emit_builtin_error("invalid Broker store handle"); + return zeek::val_mgr->False(); } auto handle = static_cast(h); @@ -483,18 +483,18 @@ function Broker::__append%(h: opaque of Broker::Store, k: any, s: any, if ( ! key ) { - builtin_error("invalid Broker data conversion for key argument"); - return val_mgr->False(); + zeek::emit_builtin_error("invalid Broker data conversion for key argument"); + return zeek::val_mgr->False(); } if ( ! str ) { - builtin_error("invalid Broker data conversion for str argument"); - return val_mgr->False(); + zeek::emit_builtin_error("invalid Broker data conversion for str argument"); + return zeek::val_mgr->False(); } handle->store.append(std::move(*key), std::move(*str), prepare_expiry(e)); - return val_mgr->True(); + return zeek::val_mgr->True(); %} function Broker::__insert_into_set%(h: opaque of Broker::Store, k: any, i: any, @@ -502,8 +502,8 @@ function Broker::__insert_into_set%(h: opaque of Broker::Store, k: any, i: any, %{ if ( ! h ) { - builtin_error("invalid Broker store handle"); - return val_mgr->False(); + zeek::emit_builtin_error("invalid Broker store handle"); + return zeek::val_mgr->False(); } auto handle = static_cast(h); @@ -512,19 +512,19 @@ function Broker::__insert_into_set%(h: opaque of Broker::Store, k: any, i: any, if ( ! key ) { - builtin_error("invalid Broker data conversion for key argument"); - return val_mgr->False(); + zeek::emit_builtin_error("invalid Broker data conversion for key argument"); + return zeek::val_mgr->False(); } if ( ! idx ) { - builtin_error("invalid Broker data conversion for index argument"); - return val_mgr->False(); + zeek::emit_builtin_error("invalid Broker data conversion for index argument"); + return zeek::val_mgr->False(); } handle->store.insert_into(std::move(*key), std::move(*idx), prepare_expiry(e)); - return val_mgr->True(); + return zeek::val_mgr->True(); %} function Broker::__insert_into_table%(h: opaque of Broker::Store, k: any, @@ -532,8 +532,8 @@ function Broker::__insert_into_table%(h: opaque of Broker::Store, k: any, %{ if ( ! h ) { - builtin_error("invalid Broker store handle"); - return val_mgr->False(); + zeek::emit_builtin_error("invalid Broker store handle"); + return zeek::val_mgr->False(); } auto handle = static_cast(h); @@ -543,25 +543,25 @@ function Broker::__insert_into_table%(h: opaque of Broker::Store, k: any, if ( ! key ) { - builtin_error("invalid Broker data conversion for key argument"); - return val_mgr->False(); + zeek::emit_builtin_error("invalid Broker data conversion for key argument"); + return zeek::val_mgr->False(); } if ( ! idx ) { - builtin_error("invalid Broker data conversion for index argument"); - return val_mgr->False(); + zeek::emit_builtin_error("invalid Broker data conversion for index argument"); + return zeek::val_mgr->False(); } if ( ! val ) { - builtin_error("invalid Broker data conversion for value argument"); - return val_mgr->False(); + zeek::emit_builtin_error("invalid Broker data conversion for value argument"); + return zeek::val_mgr->False(); } handle->store.insert_into(std::move(*key), std::move(*idx), std::move(*val), prepare_expiry(e)); - return val_mgr->True(); + return zeek::val_mgr->True(); %} function Broker::__remove_from%(h: opaque of Broker::Store, k: any, i: any, @@ -569,8 +569,8 @@ function Broker::__remove_from%(h: opaque of Broker::Store, k: any, i: any, %{ if ( ! h ) { - builtin_error("invalid Broker store handle"); - return val_mgr->False(); + zeek::emit_builtin_error("invalid Broker store handle"); + return zeek::val_mgr->False(); } auto handle = static_cast(h); @@ -579,19 +579,19 @@ function Broker::__remove_from%(h: opaque of Broker::Store, k: any, i: any, if ( ! key ) { - builtin_error("invalid Broker data conversion for key argument"); - return val_mgr->False(); + zeek::emit_builtin_error("invalid Broker data conversion for key argument"); + return zeek::val_mgr->False(); } if ( ! idx ) { - builtin_error("invalid Broker data conversion for index argument"); - return val_mgr->False(); + zeek::emit_builtin_error("invalid Broker data conversion for index argument"); + return zeek::val_mgr->False(); } handle->store.remove_from(std::move(*key), std::move(*idx), prepare_expiry(e)); - return val_mgr->True(); + return zeek::val_mgr->True(); %} function Broker::__push%(h: opaque of Broker::Store, k: any, v: any, @@ -599,8 +599,8 @@ function Broker::__push%(h: opaque of Broker::Store, k: any, v: any, %{ if ( ! h ) { - builtin_error("invalid Broker store handle"); - return val_mgr->False(); + zeek::emit_builtin_error("invalid Broker store handle"); + return zeek::val_mgr->False(); } auto handle = static_cast(h); @@ -609,26 +609,26 @@ function Broker::__push%(h: opaque of Broker::Store, k: any, v: any, if ( ! key ) { - builtin_error("invalid Broker data conversion for key argument"); - return val_mgr->False(); + zeek::emit_builtin_error("invalid Broker data conversion for key argument"); + return zeek::val_mgr->False(); } if ( ! val ) { - builtin_error("invalid Broker data conversion for value argument"); - return val_mgr->False(); + zeek::emit_builtin_error("invalid Broker data conversion for value argument"); + return zeek::val_mgr->False(); } handle->store.push(std::move(*key), std::move(*val), prepare_expiry(e)); - return val_mgr->True(); + return zeek::val_mgr->True(); %} function Broker::__pop%(h: opaque of Broker::Store, k: any, e: interval%): bool %{ if ( ! h ) { - builtin_error("invalid Broker store handle"); - return val_mgr->False(); + zeek::emit_builtin_error("invalid Broker store handle"); + return zeek::val_mgr->False(); } auto handle = static_cast(h); @@ -636,24 +636,24 @@ function Broker::__pop%(h: opaque of Broker::Store, k: any, e: interval%): bool if ( ! key ) { - builtin_error("invalid Broker data conversion for key argument"); - return val_mgr->False(); + zeek::emit_builtin_error("invalid Broker data conversion for key argument"); + return zeek::val_mgr->False(); } handle->store.pop(std::move(*key), prepare_expiry(e)); - return val_mgr->True(); + return zeek::val_mgr->True(); %} function Broker::__clear%(h: opaque of Broker::Store%): bool %{ if ( ! h ) { - builtin_error("invalid Broker store handle"); - return val_mgr->False(); + zeek::emit_builtin_error("invalid Broker store handle"); + return zeek::val_mgr->False(); } auto handle = static_cast(h); handle->store.clear(); - return val_mgr->True(); + return zeek::val_mgr->True(); %} diff --git a/src/file_analysis/Analyzer.cc b/src/file_analysis/Analyzer.cc index 27066ba826..b39e29e96a 100644 --- a/src/file_analysis/Analyzer.cc +++ b/src/file_analysis/Analyzer.cc @@ -19,7 +19,7 @@ void file_analysis::Analyzer::SetAnalyzerTag(const file_analysis::Tag& arg_tag) } file_analysis::Analyzer::Analyzer(file_analysis::Tag arg_tag, - IntrusivePtr arg_args, + zeek::RecordValPtr arg_args, File* arg_file) : tag(arg_tag), args(std::move(arg_args)), @@ -30,16 +30,16 @@ file_analysis::Analyzer::Analyzer(file_analysis::Tag arg_tag, id = ++id_counter; } -file_analysis::Analyzer::Analyzer(IntrusivePtr arg_args, File* arg_file) +file_analysis::Analyzer::Analyzer(zeek::RecordValPtr arg_args, File* arg_file) : Analyzer({}, std::move(arg_args), arg_file) {} file_analysis::Analyzer::Analyzer(file_analysis::Tag arg_tag, - RecordVal* arg_args, + zeek::RecordVal* arg_args, File* arg_file) - : Analyzer(arg_tag, {NewRef{}, arg_args}, arg_file) + : Analyzer(arg_tag, {zeek::NewRef{}, arg_args}, arg_file) {} -file_analysis::Analyzer::Analyzer(RecordVal* arg_args, File* arg_file) - : Analyzer({}, {NewRef{}, arg_args}, arg_file) +file_analysis::Analyzer::Analyzer(zeek::RecordVal* arg_args, File* arg_file) + : Analyzer({}, {zeek::NewRef{}, arg_args}, arg_file) {} diff --git a/src/file_analysis/Analyzer.h b/src/file_analysis/Analyzer.h index fe0b2bf521..8858b17a7c 100644 --- a/src/file_analysis/Analyzer.h +++ b/src/file_analysis/Analyzer.h @@ -6,7 +6,10 @@ #include // for u_char -class RecordVal; +ZEEK_FORWARD_DECLARE_NAMESPACED(RecordVal, zeek); +namespace zeek { +using RecordValPtr = zeek::IntrusivePtr; +} namespace file_analysis { @@ -95,11 +98,11 @@ public: /** * @return the AnalyzerArgs associated with the analyzer. */ - const IntrusivePtr& GetArgs() const + const zeek::RecordValPtr& GetArgs() const { return args; } [[deprecated("Remove in v4.1. Use GetArgs().")]] - RecordVal* Args() const + zeek::RecordVal* Args() const { return args.get(); } /** @@ -151,11 +154,10 @@ protected: * tunable options, if any, related to a particular analyzer type. * @param arg_file the file to which the the analyzer is being attached. */ - Analyzer(file_analysis::Tag arg_tag, IntrusivePtr arg_args, - File* arg_file); + Analyzer(file_analysis::Tag arg_tag, zeek::RecordValPtr arg_args, File* arg_file); [[deprecated("Remove in v4.1.. Construct using IntrusivePtr instead.")]] - Analyzer(file_analysis::Tag arg_tag, RecordVal* arg_args, File* arg_file); + Analyzer(file_analysis::Tag arg_tag, zeek::RecordVal* arg_args, File* arg_file); /** * Constructor. Only derived classes are meant to be instantiated. @@ -166,16 +168,16 @@ protected: * tunable options, if any, related to a particular analyzer type. * @param arg_file the file to which the the analyzer is being attached. */ - Analyzer(IntrusivePtr arg_args, File* arg_file); + Analyzer(zeek::RecordValPtr arg_args, File* arg_file); [[deprecated("Remove in v4.1.. Construct using IntrusivePtr instead.")]] - Analyzer(RecordVal* arg_args, File* arg_file); + Analyzer(zeek::RecordVal* arg_args, File* arg_file); private: ID id; /**< Unique instance ID. */ file_analysis::Tag tag; /**< The particular type of the analyzer instance. */ - IntrusivePtr args; /**< \c AnalyzerArgs val gives tunable analyzer params. */ + zeek::RecordValPtr args; /**< \c AnalyzerArgs val gives tunable analyzer params. */ File* file; /**< The file to which the analyzer is attached. */ bool got_stream_delivery; bool skip; diff --git a/src/file_analysis/AnalyzerSet.cc b/src/file_analysis/AnalyzerSet.cc index 2f7d5ae6a0..042f7b029a 100644 --- a/src/file_analysis/AnalyzerSet.cc +++ b/src/file_analysis/AnalyzerSet.cc @@ -20,7 +20,7 @@ static void analyzer_del_func(void* v) AnalyzerSet::AnalyzerSet(File* arg_file) : file(arg_file) { - auto t = make_intrusive(); + auto t = zeek::make_intrusive(); t->Append(file_mgr->GetTagType()); t->Append(zeek::BifType::Record::Files::AnalyzerArgs); analyzer_hash = new CompositeHash(std::move(t)); @@ -41,14 +41,14 @@ AnalyzerSet::~AnalyzerSet() } Analyzer* AnalyzerSet::Find(const file_analysis::Tag& tag, - IntrusivePtr args) + zeek::RecordValPtr args) { auto key = GetKey(tag, std::move(args)); Analyzer* rval = analyzer_map.Lookup(key.get()); return rval; } -bool AnalyzerSet::Add(const file_analysis::Tag& tag, IntrusivePtr args) +bool AnalyzerSet::Add(const file_analysis::Tag& tag, zeek::RecordValPtr args) { auto key = GetKey(tag, args); @@ -72,7 +72,7 @@ bool AnalyzerSet::Add(const file_analysis::Tag& tag, IntrusivePtr arg } Analyzer* AnalyzerSet::QueueAdd(const file_analysis::Tag& tag, - IntrusivePtr args) + zeek::RecordValPtr args) { auto key = GetKey(tag, args); file_analysis::Analyzer* a = InstantiateAnalyzer(tag, std::move(args)); @@ -108,7 +108,7 @@ void AnalyzerSet::AddMod::Abort() } bool AnalyzerSet::Remove(const file_analysis::Tag& tag, - IntrusivePtr args) + zeek::RecordValPtr args) { return Remove(tag, GetKey(tag, std::move(args))); } @@ -140,7 +140,7 @@ bool AnalyzerSet::Remove(const file_analysis::Tag& tag, } bool AnalyzerSet::QueueRemove(const file_analysis::Tag& tag, - IntrusivePtr args) + zeek::RecordValPtr args) { auto key = GetKey(tag, std::move(args)); auto rval = analyzer_map.Lookup(key.get()); @@ -154,9 +154,9 @@ bool AnalyzerSet::RemoveMod::Perform(AnalyzerSet* set) } std::unique_ptr AnalyzerSet::GetKey(const file_analysis::Tag& t, - IntrusivePtr args) const + zeek::RecordValPtr args) const { - auto lv = make_intrusive(zeek::TYPE_ANY); + auto lv = zeek::make_intrusive(zeek::TYPE_ANY); lv->Append(t.AsVal()); lv->Append(std::move(args)); auto key = analyzer_hash->MakeHashKey(*lv, true); @@ -168,7 +168,7 @@ std::unique_ptr AnalyzerSet::GetKey(const file_analysis::Tag& t, } file_analysis::Analyzer* AnalyzerSet::InstantiateAnalyzer(const Tag& tag, - IntrusivePtr args) const + zeek::RecordValPtr args) const { auto a = file_mgr->InstantiateAnalyzer(tag, std::move(args), file); diff --git a/src/file_analysis/AnalyzerSet.h b/src/file_analysis/AnalyzerSet.h index c0ef1d6fc0..0860d35989 100644 --- a/src/file_analysis/AnalyzerSet.h +++ b/src/file_analysis/AnalyzerSet.h @@ -9,7 +9,11 @@ #include "Tag.h" class CompositeHash; -class RecordVal; + +ZEEK_FORWARD_DECLARE_NAMESPACED(RecordVal, zeek); +namespace zeek { +using RecordValPtr = zeek::IntrusivePtr; +} namespace file_analysis { @@ -43,7 +47,7 @@ public: * @param args an \c AnalyzerArgs record. * @return pointer to an analyzer instance, or a null pointer if not found. */ - Analyzer* Find(const file_analysis::Tag& tag, IntrusivePtr args); + Analyzer* Find(const file_analysis::Tag& tag, zeek::RecordValPtr args); /** * Attach an analyzer to #file immediately. @@ -51,7 +55,7 @@ public: * @param args an \c AnalyzerArgs value which specifies an analyzer. * @return true if analyzer was instantiated/attached, else false. */ - bool Add(const file_analysis::Tag& tag, IntrusivePtr args); + bool Add(const file_analysis::Tag& tag, zeek::RecordValPtr args); /** * Queue the attachment of an analyzer to #file. @@ -61,7 +65,7 @@ public: * a null pointer. The caller does *not* take ownership of the memory. */ file_analysis::Analyzer* QueueAdd(const file_analysis::Tag& tag, - IntrusivePtr args); + zeek::RecordValPtr args); /** * Remove an analyzer from #file immediately. @@ -69,7 +73,7 @@ public: * @param args an \c AnalyzerArgs value which specifies an analyzer. * @return false if analyzer didn't exist and so wasn't removed, else true. */ - bool Remove(const file_analysis::Tag& tag, IntrusivePtr args); + bool Remove(const file_analysis::Tag& tag, zeek::RecordValPtr args); /** * Queue the removal of an analyzer from #file. @@ -77,7 +81,7 @@ public: * @param args an \c AnalyzerArgs value which specifies an analyzer. * @return true if analyzer exists at time of call, else false; */ - bool QueueRemove(const file_analysis::Tag& tag, IntrusivePtr args); + bool QueueRemove(const file_analysis::Tag& tag, zeek::RecordValPtr args); /** * Perform all queued modifications to the current analyzer set. @@ -89,7 +93,7 @@ public: * @see Dictionary#InitForIteration * @return an iterator that may be used to loop over analyzers in the set. */ - IterCookie* InitForIteration() const + zeek::IterCookie* InitForIteration() const { return analyzer_map.InitForIteration(); } /** @@ -99,7 +103,7 @@ public: * @return the next analyzer in the set or a null pointer if there is no * more left (in that case the cookie is also deleted). */ - file_analysis::Analyzer* NextEntry(IterCookie* c) + file_analysis::Analyzer* NextEntry(zeek::IterCookie* c) { return analyzer_map.NextEntry(c); } protected: @@ -111,7 +115,7 @@ protected: * @return the hash key calculated from \a args */ std::unique_ptr GetKey(const file_analysis::Tag& tag, - IntrusivePtr args) const; + zeek::RecordValPtr args) const; /** * Create an instance of a file analyzer. @@ -120,7 +124,7 @@ protected: * @return a new file analyzer instance. */ file_analysis::Analyzer* InstantiateAnalyzer(const file_analysis::Tag& tag, - IntrusivePtr args) const; + zeek::RecordValPtr args) const; /** * Insert an analyzer instance in to the set. @@ -141,7 +145,7 @@ private: File* file; /**< File which owns the set */ CompositeHash* analyzer_hash; /**< AnalyzerArgs hashes. */ - PDict analyzer_map; /**< Indexed by AnalyzerArgs. */ + zeek::PDict analyzer_map; /**< Indexed by AnalyzerArgs. */ /** * Abstract base class for analyzer set modifications. diff --git a/src/file_analysis/Component.h b/src/file_analysis/Component.h index 98ac262127..07621ce5b2 100644 --- a/src/file_analysis/Component.h +++ b/src/file_analysis/Component.h @@ -8,7 +8,10 @@ #include "../zeek-config.h" -class RecordVal; +ZEEK_FORWARD_DECLARE_NAMESPACED(RecordVal, zeek); +namespace zeek { +using RecordValPtr = zeek::IntrusivePtr; +} namespace file_analysis { @@ -25,8 +28,8 @@ class Manager; class Component : public zeek::plugin::Component, public plugin::TaggedComponent { public: - typedef Analyzer* (*factory_callback)(RecordVal* args, File* file); - using factory_function = Analyzer* (*)(IntrusivePtr args, File* file); + typedef Analyzer* (*factory_callback)(zeek::RecordVal* args, File* file); + using factory_function = Analyzer* (*)(zeek::RecordValPtr args, File* file); /** * Constructor. diff --git a/src/file_analysis/File.cc b/src/file_analysis/File.cc index 2b97a746c6..af780815ef 100644 --- a/src/file_analysis/File.cc +++ b/src/file_analysis/File.cc @@ -21,22 +21,22 @@ using namespace file_analysis; -static IntrusivePtr empty_connection_table() +static zeek::TableValPtr empty_connection_table() { - auto tbl_index = make_intrusive(zeek::id::conn_id); + auto tbl_index = zeek::make_intrusive(zeek::id::conn_id); tbl_index->Append(zeek::id::conn_id); - auto tbl_type = make_intrusive(std::move(tbl_index), + auto tbl_type = zeek::make_intrusive(std::move(tbl_index), zeek::id::connection); - return make_intrusive(std::move(tbl_type)); + return zeek::make_intrusive(std::move(tbl_type)); } -static IntrusivePtr get_conn_id_val(const Connection* conn) +static zeek::RecordValPtr get_conn_id_val(const Connection* conn) { - auto v = make_intrusive(zeek::id::conn_id); - v->Assign(0, make_intrusive(conn->OrigAddr())); - v->Assign(1, val_mgr->Port(ntohs(conn->OrigPort()), conn->ConnTransport())); - v->Assign(2, make_intrusive(conn->RespAddr())); - v->Assign(3, val_mgr->Port(ntohs(conn->RespPort()), conn->ConnTransport())); + auto v = zeek::make_intrusive(zeek::id::conn_id); + v->Assign(0, zeek::make_intrusive(conn->OrigAddr())); + v->Assign(1, zeek::val_mgr->Port(ntohs(conn->OrigPort()), conn->ConnTransport())); + v->Assign(2, zeek::make_intrusive(conn->RespAddr())); + v->Assign(3, zeek::val_mgr->Port(ntohs(conn->RespPort()), conn->ConnTransport())); return v; } @@ -91,13 +91,13 @@ File::File(const std::string& file_id, const std::string& source_name, Connectio DBG_LOG(DBG_FILE_ANALYSIS, "[%s] Creating new File object", file_id.c_str()); - val = make_intrusive(zeek::id::fa_file); - val->Assign(id_idx, make_intrusive(file_id.c_str())); + val = zeek::make_intrusive(zeek::id::fa_file); + val->Assign(id_idx, zeek::make_intrusive(file_id.c_str())); SetSource(source_name); if ( conn ) { - val->Assign(is_orig_idx, val_mgr->Bool(is_orig)); + val->Assign(is_orig_idx, zeek::val_mgr->Bool(is_orig)); UpdateConnectionFields(conn, is_orig); } @@ -115,7 +115,7 @@ File::~File() void File::UpdateLastActivityTime() { - val->Assign(last_active_idx, make_intrusive(network_time)); + val->Assign(last_active_idx, zeek::make_intrusive(network_time)); } double File::GetLastActivityTime() const @@ -128,7 +128,7 @@ bool File::UpdateConnectionFields(Connection* conn, bool is_orig) if ( ! conn ) return false; - Val* conns = val->GetField(conns_idx).get(); + zeek::Val* conns = val->GetField(conns_idx).get(); if ( ! conns ) { @@ -153,7 +153,7 @@ void File::RaiseFileOverNewConnection(Connection* conn, bool is_orig) FileEvent(file_over_new_connection, { val, conn->ConnVal(), - val_mgr->Bool(is_orig), + zeek::val_mgr->Bool(is_orig), }); } } @@ -190,7 +190,7 @@ std::string File::GetSource() const void File::SetSource(const std::string& source) { - val->Assign(source_idx, make_intrusive(source.c_str())); + val->Assign(source_idx, zeek::make_intrusive(source.c_str())); } double File::GetTimeoutInterval() const @@ -200,13 +200,13 @@ double File::GetTimeoutInterval() const void File::SetTimeoutInterval(double interval) { - val->Assign(timeout_interval_idx, make_intrusive(interval)); + val->Assign(timeout_interval_idx, zeek::make_intrusive(interval)); } -bool File::SetExtractionLimit(RecordVal* args, uint64_t bytes) - { return SetExtractionLimit({NewRef{}, args}, bytes); } +bool File::SetExtractionLimit(zeek::RecordVal* args, uint64_t bytes) + { return SetExtractionLimit({zeek::NewRef{}, args}, bytes); } -bool File::SetExtractionLimit(IntrusivePtr args, uint64_t bytes) +bool File::SetExtractionLimit(zeek::RecordValPtr args, uint64_t bytes) { Analyzer* a = analyzers.Find(file_mgr->GetComponentTag("EXTRACT"), std::move(args)); @@ -226,13 +226,13 @@ bool File::SetExtractionLimit(IntrusivePtr args, uint64_t bytes) void File::IncrementByteCount(uint64_t size, int field_idx) { uint64_t old = LookupFieldDefaultCount(field_idx); - val->Assign(field_idx, val_mgr->Count(old + size)); + val->Assign(field_idx, zeek::val_mgr->Count(old + size)); } void File::SetTotalBytes(uint64_t size) { DBG_LOG(DBG_FILE_ANALYSIS, "[%s] Total bytes %" PRIu64, id.c_str(), size); - val->Assign(total_bytes_idx, val_mgr->Count(size)); + val->Assign(total_bytes_idx, zeek::val_mgr->Count(size)); } bool File::IsComplete() const @@ -253,10 +253,10 @@ void File::ScheduleInactivityTimer() const timer_mgr->Add(new FileTimer(network_time, id, GetTimeoutInterval())); } -bool File::AddAnalyzer(file_analysis::Tag tag, RecordVal* args) - { return AddAnalyzer(tag, {NewRef{}, args}); } +bool File::AddAnalyzer(file_analysis::Tag tag, zeek::RecordVal* args) + { return AddAnalyzer(tag, {zeek::NewRef{}, args}); } -bool File::AddAnalyzer(file_analysis::Tag tag, IntrusivePtr args) +bool File::AddAnalyzer(file_analysis::Tag tag, zeek::RecordValPtr args) { DBG_LOG(DBG_FILE_ANALYSIS, "[%s] Queuing addition of %s analyzer", id.c_str(), file_mgr->GetComponentName(tag).c_str()); @@ -267,10 +267,10 @@ bool File::AddAnalyzer(file_analysis::Tag tag, IntrusivePtr args) return analyzers.QueueAdd(tag, std::move(args)) != nullptr; } -bool File::RemoveAnalyzer(file_analysis::Tag tag, RecordVal* args) - { return RemoveAnalyzer(tag, {NewRef{}, args}); } +bool File::RemoveAnalyzer(file_analysis::Tag tag, zeek::RecordVal* args) + { return RemoveAnalyzer(tag, {zeek::NewRef{}, args}); } -bool File::RemoveAnalyzer(file_analysis::Tag tag, IntrusivePtr args) +bool File::RemoveAnalyzer(file_analysis::Tag tag, zeek::RecordValPtr args) { DBG_LOG(DBG_FILE_ANALYSIS, "[%s] Queuing remove of %s analyzer", id.c_str(), file_mgr->GetComponentName(tag).c_str()); @@ -306,9 +306,9 @@ bool File::SetMime(const std::string& mime_type) if ( ! FileEventAvailable(file_sniff) ) return false; - auto meta = make_intrusive(zeek::id::fa_metadata); - meta->Assign(meta_mime_type_idx, make_intrusive(mime_type)); - meta->Assign(meta_inferred_idx, val_mgr->False()); + auto meta = zeek::make_intrusive(zeek::id::fa_metadata); + meta->Assign(meta_mime_type_idx, zeek::make_intrusive(mime_type)); + meta->Assign(meta_inferred_idx, zeek::val_mgr->False()); FileEvent(file_sniff, {val, std::move(meta)}); return true; @@ -318,15 +318,15 @@ void File::InferMetadata() { did_metadata_inference = true; - Val* bof_buffer_val = val->GetField(bof_buffer_idx).get(); + zeek::Val* bof_buffer_val = val->GetField(bof_buffer_idx).get(); if ( ! bof_buffer_val ) { if ( bof_buffer.size == 0 ) return; - BroString* bs = concatenate(bof_buffer.chunks); - val->Assign(bof_buffer_idx, bs); + zeek::String* bs = concatenate(bof_buffer.chunks); + val->Assign(bof_buffer_idx, bs); bof_buffer_val = val->GetField(bof_buffer_idx).get(); } @@ -339,11 +339,11 @@ void File::InferMetadata() len = std::min(len, LookupFieldDefaultCount(bof_buffer_size_idx)); file_mgr->DetectMIME(data, len, &matches); - auto meta = make_intrusive(zeek::id::fa_metadata); + auto meta = zeek::make_intrusive(zeek::id::fa_metadata); if ( ! matches.empty() ) { - meta->Assign(meta_mime_type_idx, + meta->Assign(meta_mime_type_idx, *(matches.begin()->second.begin())); meta->Assign(meta_mime_types_idx, file_analysis::GenMIMEMatchesVal(matches)); @@ -359,7 +359,7 @@ bool File::BufferBOF(const u_char* data, uint64_t len) uint64_t desired_size = LookupFieldDefaultCount(bof_buffer_size_idx); - bof_buffer.chunks.push_back(new BroString(data, len, false)); + bof_buffer.chunks.push_back(new zeek::String(data, len, false)); bof_buffer.size += len; if ( bof_buffer.size < desired_size ) @@ -369,8 +369,8 @@ bool File::BufferBOF(const u_char* data, uint64_t len) if ( bof_buffer.size > 0 ) { - BroString* bs = concatenate(bof_buffer.chunks); - val->Assign(bof_buffer_idx, make_intrusive(bs)); + zeek::String* bs = concatenate(bof_buffer.chunks); + val->Assign(bof_buffer_idx, zeek::make_intrusive(bs)); } return false; @@ -394,7 +394,7 @@ void File::DeliverStream(const u_char* data, uint64_t len) len > 40 ? "..." : ""); file_analysis::Analyzer* a = nullptr; - IterCookie* c = analyzers.InitForIteration(); + zeek::IterCookie* c = analyzers.InitForIteration(); while ( (a = analyzers.NextEntry(c)) ) { @@ -462,8 +462,8 @@ void File::DeliverChunk(const u_char* data, uint64_t len, uint64_t offset) { FileEvent(file_reassembly_overflow, { val, - val_mgr->Count(current_offset), - val_mgr->Count(gap_bytes) + zeek::val_mgr->Count(current_offset), + zeek::val_mgr->Count(gap_bytes) }); } } @@ -498,7 +498,7 @@ void File::DeliverChunk(const u_char* data, uint64_t len, uint64_t offset) len > 40 ? "..." : ""); file_analysis::Analyzer* a = nullptr; - IterCookie* c = analyzers.InitForIteration(); + zeek::IterCookie* c = analyzers.InitForIteration(); while ( (a = analyzers.NextEntry(c)) ) { @@ -562,7 +562,7 @@ void File::EndOfFile() done = true; file_analysis::Analyzer* a = nullptr; - IterCookie* c = analyzers.InitForIteration(); + zeek::IterCookie* c = analyzers.InitForIteration(); while ( (a = analyzers.NextEntry(c)) ) { @@ -595,7 +595,7 @@ void File::Gap(uint64_t offset, uint64_t len) } file_analysis::Analyzer* a = nullptr; - IterCookie* c = analyzers.InitForIteration(); + zeek::IterCookie* c = analyzers.InitForIteration(); while ( (a = analyzers.NextEntry(c)) ) { @@ -604,7 +604,7 @@ void File::Gap(uint64_t offset, uint64_t len) } if ( FileEventAvailable(file_gap) ) - FileEvent(file_gap, {val, val_mgr->Count(offset), val_mgr->Count(len)}); + FileEvent(file_gap, {val, zeek::val_mgr->Count(offset), zeek::val_mgr->Count(len)}); analyzers.DrainModifications(); diff --git a/src/file_analysis/File.h b/src/file_analysis/File.h index 0eacf90a6b..2af8def6b6 100644 --- a/src/file_analysis/File.h +++ b/src/file_analysis/File.h @@ -8,16 +8,20 @@ #include "analyzer/Tag.h" #include "AnalyzerSet.h" -#include "BroString.h" +#include "ZeekString.h" #include "BroList.h" // for val_list #include "ZeekArgs.h" #include "WeirdState.h" class Connection; -class RecordVal; class EventHandlerPtr; +ZEEK_FORWARD_DECLARE_NAMESPACED(RecordVal, zeek); ZEEK_FORWARD_DECLARE_NAMESPACED(RecordType, zeek); +namespace zeek { +using RecordValPtr = zeek::IntrusivePtr; +using RecordTypePtr = zeek::IntrusivePtr; +} namespace file_analysis { @@ -39,11 +43,11 @@ public: /** * @return the wrapped \c fa_file record value, #val. */ - const IntrusivePtr& ToVal() const + const zeek::RecordValPtr& ToVal() const { return val; } [[deprecated("Remove in v4.1. Use ToVal().")]] - RecordVal* GetVal() const + zeek::RecordVal* GetVal() const { return val.get(); } /** @@ -75,10 +79,10 @@ public: * @param bytes new limit. * @return false if no extraction analyzer is active, else true. */ - bool SetExtractionLimit(IntrusivePtr args, uint64_t bytes); + bool SetExtractionLimit(zeek::RecordValPtr args, uint64_t bytes); [[deprecated("Remove in v4.1. Pass an IntrusivePtr instead.")]] - bool SetExtractionLimit(RecordVal* args, uint64_t bytes); + bool SetExtractionLimit(zeek::RecordVal* args, uint64_t bytes); /** * @return value of the "id" field from #val record. @@ -123,10 +127,10 @@ public: * @param args an \c AnalyzerArgs value representing a file analyzer. * @return false if analyzer can't be instantiated, else true. */ - bool AddAnalyzer(file_analysis::Tag tag, IntrusivePtr args); + bool AddAnalyzer(file_analysis::Tag tag, zeek::RecordValPtr args); [[deprecated("Remove in v4.1. Pass an IntrusivePtr instead.")]] - bool AddAnalyzer(file_analysis::Tag tag, RecordVal* args); + bool AddAnalyzer(file_analysis::Tag tag, zeek::RecordVal* args); /** * Queues removal of an analyzer. @@ -134,10 +138,10 @@ public: * @param args an \c AnalyzerArgs value representing a file analyzer. * @return true if analyzer was active at time of call, else false. */ - bool RemoveAnalyzer(file_analysis::Tag tag, IntrusivePtr args); + bool RemoveAnalyzer(file_analysis::Tag tag, zeek::RecordValPtr args); [[deprecated("Remove in v4.1. Pass an IntrusivePtr instead.")]] - bool RemoveAnalyzer(file_analysis::Tag tag, RecordVal* args); + bool RemoveAnalyzer(file_analysis::Tag tag, zeek::RecordVal* args); /** * Signal that this analyzer can be deleted once it's safe to do so. @@ -338,7 +342,7 @@ protected: * @return the field offset in #val record corresponding to \a field_name. */ static int Idx(const std::string& field_name, const zeek::RecordType* type); - static int Idx(const std::string& field_name, const IntrusivePtr& type) + static int Idx(const std::string& field_name, const zeek::RecordTypePtr& type) { return Idx(field_name, type.get()); } /** @@ -348,7 +352,7 @@ protected: protected: std::string id; /**< A pretty hash that likely identifies file */ - IntrusivePtr val; /**< \c fa_file from script layer. */ + zeek::RecordValPtr val; /**< \c fa_file from script layer. */ FileReassembler* file_reassembler; /**< A reassembler for the file if it's needed. */ uint64_t stream_offset; /**< The offset of the file which has been forwarded. */ uint64_t reassembly_max_buffer; /**< Maximum allowed buffer for reassembly. */ @@ -366,7 +370,7 @@ protected: bool full; uint64_t size; - BroString::CVec chunks; + zeek::String::CVec chunks; } bof_buffer; /**< Beginning of file buffer. */ WeirdStateMap weird_state; diff --git a/src/file_analysis/Manager.cc b/src/file_analysis/Manager.cc index c2c734e7c6..da4b92d6c1 100644 --- a/src/file_analysis/Manager.cc +++ b/src/file_analysis/Manager.cc @@ -80,7 +80,7 @@ void Manager::SetHandle(const string& handle) #ifdef DEBUG if ( debug_logger.IsEnabled(DBG_FILE_ANALYSIS) ) { - BroString tmp{handle}; + zeek::String tmp{handle}; auto rendered = tmp.Render(); DBG_LOG(DBG_FILE_ANALYSIS, "Set current handle to %s", rendered); delete [] rendered; @@ -258,12 +258,12 @@ bool Manager::SetReassemblyBuffer(const string& file_id, uint64_t max) return true; } -bool Manager::SetExtractionLimit(const string& file_id, RecordVal* args, +bool Manager::SetExtractionLimit(const string& file_id, zeek::RecordVal* args, uint64_t n) const - { return SetExtractionLimit(file_id, {NewRef{}, args}, n); } + { return SetExtractionLimit(file_id, {zeek::NewRef{}, args}, n); } bool Manager::SetExtractionLimit(const string& file_id, - IntrusivePtr args, uint64_t n) const + zeek::RecordValPtr args, uint64_t n) const { File* file = LookupFile(file_id); @@ -274,11 +274,11 @@ bool Manager::SetExtractionLimit(const string& file_id, } bool Manager::AddAnalyzer(const string& file_id, const file_analysis::Tag& tag, - RecordVal* args) const - { return AddAnalyzer(file_id, tag, {NewRef{}, args}); } + zeek::RecordVal* args) const + { return AddAnalyzer(file_id, tag, {zeek::NewRef{}, args}); } bool Manager::AddAnalyzer(const string& file_id, const file_analysis::Tag& tag, - IntrusivePtr args) const + zeek::RecordValPtr args) const { File* file = LookupFile(file_id); @@ -289,11 +289,11 @@ bool Manager::AddAnalyzer(const string& file_id, const file_analysis::Tag& tag, } bool Manager::RemoveAnalyzer(const string& file_id, const file_analysis::Tag& tag, - RecordVal* args) const - { return RemoveAnalyzer(file_id, tag, {NewRef{}, args}); } + zeek::RecordVal* args) const + { return RemoveAnalyzer(file_id, tag, {zeek::NewRef{}, args}); } bool Manager::RemoveAnalyzer(const string& file_id, const file_analysis::Tag& tag, - IntrusivePtr args) const + zeek::RecordValPtr args) const { File* file = LookupFile(file_id); @@ -435,7 +435,7 @@ string Manager::GetFileID(const analyzer::Tag& tag, Connection* c, bool is_orig) const auto& tagval = tag.AsVal(); - mgr.Enqueue(get_file_handle, tagval, c->ConnVal(), val_mgr->Bool(is_orig)); + mgr.Enqueue(get_file_handle, tagval, c->ConnVal(), zeek::val_mgr->Bool(is_orig)); mgr.Drain(); // need file handle immediately so we don't have to buffer data return current_file_id; } @@ -445,7 +445,7 @@ bool Manager::IsDisabled(const analyzer::Tag& tag) if ( ! disabled ) disabled = zeek::id::find_const("Files::disable")->AsTableVal(); - auto index = val_mgr->Count(bool(tag)); + auto index = zeek::val_mgr->Count(bool(tag)); auto yield = disabled->FindOrDefault(index); if ( ! yield ) @@ -454,11 +454,11 @@ bool Manager::IsDisabled(const analyzer::Tag& tag) return yield->AsBool(); } -Analyzer* Manager::InstantiateAnalyzer(const Tag& tag, RecordVal* args, File* f) const - { return InstantiateAnalyzer(tag, {NewRef{}, args}, f); } +Analyzer* Manager::InstantiateAnalyzer(const Tag& tag, zeek::RecordVal* args, File* f) const + { return InstantiateAnalyzer(tag, {zeek::NewRef{}, args}, f); } Analyzer* Manager::InstantiateAnalyzer(const Tag& tag, - IntrusivePtr args, + zeek::RecordValPtr args, File* f) const { Component* c = Lookup(tag); @@ -517,22 +517,22 @@ string Manager::DetectMIME(const u_char* data, uint64_t len) const return *(matches.begin()->second.begin()); } -IntrusivePtr file_analysis::GenMIMEMatchesVal(const RuleMatcher::MIME_Matches& m) +zeek::VectorValPtr file_analysis::GenMIMEMatchesVal(const RuleMatcher::MIME_Matches& m) { static auto mime_matches = zeek::id::find_type("mime_matches"); static auto mime_match = zeek::id::find_type("mime_match"); - auto rval = make_intrusive(mime_matches); + auto rval = zeek::make_intrusive(mime_matches); for ( RuleMatcher::MIME_Matches::const_iterator it = m.begin(); it != m.end(); ++it ) { - auto element = make_intrusive(mime_match); + auto element = zeek::make_intrusive(mime_match); for ( set::const_iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2 ) { - element->Assign(0, val_mgr->Int(it->first)); - element->Assign(1, make_intrusive(*it2)); + element->Assign(0, zeek::val_mgr->Int(it->first)); + element->Assign(1, zeek::make_intrusive(*it2)); } rval->Assign(rval->Size(), std::move(element)); diff --git a/src/file_analysis/Manager.h b/src/file_analysis/Manager.h index 6a233192e9..4b67d7d282 100644 --- a/src/file_analysis/Manager.h +++ b/src/file_analysis/Manager.h @@ -14,8 +14,8 @@ #include "analyzer/Tag.h" -class TableVal; -class VectorVal; +ZEEK_FORWARD_DECLARE_NAMESPACED(TableVal, zeek); +ZEEK_FORWARD_DECLARE_NAMESPACED(VectorVal, zeek); namespace analyzer { class Analyzer; @@ -254,10 +254,10 @@ public: * else true. */ bool SetExtractionLimit(const std::string& file_id, - IntrusivePtr args, uint64_t n) const; + zeek::RecordValPtr args, uint64_t n) const; [[deprecated("Remove in v4.1. Pass IntrusivePtr args param instead.")]] - bool SetExtractionLimit(const std::string& file_id, RecordVal* args, + bool SetExtractionLimit(const std::string& file_id, zeek::RecordVal* args, uint64_t n) const; /** @@ -278,11 +278,11 @@ public: * @return false if the analyzer failed to be instantiated, else true. */ bool AddAnalyzer(const std::string& file_id, const file_analysis::Tag& tag, - IntrusivePtr args) const; + zeek::RecordValPtr args) const; [[deprecated("Remove in v4.1. Pass IntrusivePtr args param instead.")]] bool AddAnalyzer(const std::string& file_id, const file_analysis::Tag& tag, - RecordVal* args) const; + zeek::RecordVal* args) const; /** * Queue removal of an analyzer for a given file identifier. @@ -292,11 +292,11 @@ public: * @return true if the analyzer is active at the time of call, else false. */ bool RemoveAnalyzer(const std::string& file_id, const file_analysis::Tag& tag, - IntrusivePtr args) const; + zeek::RecordValPtr args) const; [[deprecated("Remove in v4.1. Pass IntrusivePtr args param instead.")]] bool RemoveAnalyzer(const std::string& file_id, const file_analysis::Tag& tag, - RecordVal* args) const; + zeek::RecordVal* args) const; /** * Tells whether analysis for a file is active or ignored. @@ -312,11 +312,11 @@ public: * @param f The file analzer is to be associated with. * @return The new analyzer instance or null if tag is invalid. */ - Analyzer* InstantiateAnalyzer(const Tag& tag, IntrusivePtr args, + Analyzer* InstantiateAnalyzer(const Tag& tag, zeek::RecordValPtr args, File* f) const; [[deprecated("Remove in v4.1. Pass in IntrusivePtr args instead.")]] - Analyzer* InstantiateAnalyzer(const Tag& tag, RecordVal* args, File* f) const; + Analyzer* InstantiateAnalyzer(const Tag& tag, zeek::RecordVal* args, File* f) const; /** * Returns a set of all matching MIME magic signatures for a given @@ -427,7 +427,7 @@ private: RuleFileMagicState* magic_state; /**< File magic signature match state. */ MIMEMap mime_types;/**< Mapping of MIME types to analyzers. */ - inline static TableVal* disabled = nullptr; /**< Table of disabled analyzers. */ + inline static zeek::TableVal* disabled = nullptr; /**< Table of disabled analyzers. */ inline static zeek::TableType* tag_set_type = nullptr; /**< Type for set[tag]. */ size_t cumulative_files; @@ -438,7 +438,7 @@ private: * Returns a script-layer value corresponding to the \c mime_matches type. * @param m The MIME match information with which to populate the value. */ -IntrusivePtr GenMIMEMatchesVal(const RuleMatcher::MIME_Matches& m); +zeek::VectorValPtr GenMIMEMatchesVal(const RuleMatcher::MIME_Matches& m); } // namespace file_analysis diff --git a/src/file_analysis/Tag.cc b/src/file_analysis/Tag.cc index 1789600f26..712f90dd59 100644 --- a/src/file_analysis/Tag.cc +++ b/src/file_analysis/Tag.cc @@ -18,20 +18,20 @@ file_analysis::Tag& file_analysis::Tag::operator=(const file_analysis::Tag& othe return *this; } -const IntrusivePtr& file_analysis::Tag::AsVal() const +const zeek::EnumValPtr& file_analysis::Tag::AsVal() const { return ::Tag::AsVal(file_mgr->GetTagType()); } -EnumVal* file_analysis::Tag::AsEnumVal() const +zeek::EnumVal* file_analysis::Tag::AsEnumVal() const { return AsVal().get(); } -file_analysis::Tag::Tag(IntrusivePtr val) +file_analysis::Tag::Tag(zeek::EnumValPtr val) : ::Tag(std::move(val)) { } -file_analysis::Tag::Tag(EnumVal* val) - : ::Tag({NewRef{}, val}) +file_analysis::Tag::Tag(zeek::EnumVal* val) + : ::Tag({zeek::NewRef{}, val}) { } diff --git a/src/file_analysis/Tag.h b/src/file_analysis/Tag.h index e2a1e1a1d8..1aa758b6ff 100644 --- a/src/file_analysis/Tag.h +++ b/src/file_analysis/Tag.h @@ -5,7 +5,7 @@ #include "zeek-config.h" #include "../Tag.h" -class EnumVal; +ZEEK_FORWARD_DECLARE_NAMESPACED(EnumVal, zeek); namespace zeek::plugin { template class TaggedComponent; @@ -88,10 +88,10 @@ public: * * @param etype the script-layer enum type associated with the tag. */ - const IntrusivePtr& AsVal() const; + const zeek::EnumValPtr& AsVal() const; [[deprecated("Remove in v4.1. Use AsVal() instead.")]] - EnumVal* AsEnumVal() const; + zeek::EnumVal* AsEnumVal() const; static const Tag Error; @@ -116,10 +116,10 @@ protected: * * @param val An enum value of script type \c Files::Tag. */ - explicit Tag(IntrusivePtr val); + explicit Tag(zeek::EnumValPtr val); [[deprecated("Remove in v4.1. Construct from IntrusivePtr instead.")]] - explicit Tag(EnumVal* val); + explicit Tag(zeek::EnumVal* val); }; } diff --git a/src/file_analysis/analyzer/data_event/DataEvent.cc b/src/file_analysis/analyzer/data_event/DataEvent.cc index 04175723af..17d2e58618 100644 --- a/src/file_analysis/analyzer/data_event/DataEvent.cc +++ b/src/file_analysis/analyzer/data_event/DataEvent.cc @@ -11,7 +11,7 @@ using namespace file_analysis; -DataEvent::DataEvent(IntrusivePtr args, File* file, +DataEvent::DataEvent(zeek::RecordValPtr args, File* file, EventHandlerPtr ce, EventHandlerPtr se) : file_analysis::Analyzer(file_mgr->GetComponentTag("DATA_EVENT"), std::move(args), file), @@ -19,7 +19,7 @@ DataEvent::DataEvent(IntrusivePtr args, File* file, { } -file_analysis::Analyzer* DataEvent::Instantiate(IntrusivePtr args, +file_analysis::Analyzer* DataEvent::Instantiate(zeek::RecordValPtr args, File* file) { const auto& chunk_val = args->GetField("chunk_event"); @@ -44,9 +44,9 @@ bool DataEvent::DeliverChunk(const u_char* data, uint64_t len, uint64_t offset) if ( ! chunk_event ) return true; mgr.Enqueue(chunk_event, - GetFile()->ToVal(), - make_intrusive(new BroString(data, len, false)), - val_mgr->Count(offset) + GetFile()->ToVal(), + zeek::make_intrusive(new zeek::String(data, len, false)), + zeek::val_mgr->Count(offset) ); return true; @@ -57,8 +57,8 @@ bool DataEvent::DeliverStream(const u_char* data, uint64_t len) if ( ! stream_event ) return true; mgr.Enqueue(stream_event, - GetFile()->ToVal(), - make_intrusive(new BroString(data, len, false)) + GetFile()->ToVal(), + zeek::make_intrusive(new zeek::String(data, len, false)) ); return true; diff --git a/src/file_analysis/analyzer/data_event/DataEvent.h b/src/file_analysis/analyzer/data_event/DataEvent.h index c1dd1ab64b..6c340e0f17 100644 --- a/src/file_analysis/analyzer/data_event/DataEvent.h +++ b/src/file_analysis/analyzer/data_event/DataEvent.h @@ -43,7 +43,7 @@ public: * @return the new DataEvent analyzer instance or a null pointer if * no "chunk_event" or "stream_event" field was specfied in \a args. */ - static file_analysis::Analyzer* Instantiate(IntrusivePtr args, + static file_analysis::Analyzer* Instantiate(zeek::RecordValPtr args, File* file); protected: @@ -57,7 +57,7 @@ protected: * @param se pointer to event handler which will be called to receive * sequential file data. */ - DataEvent(IntrusivePtr args, File* file, + DataEvent(zeek::RecordValPtr args, File* file, EventHandlerPtr ce, EventHandlerPtr se); private: diff --git a/src/file_analysis/analyzer/entropy/Entropy.cc b/src/file_analysis/analyzer/entropy/Entropy.cc index 93d92eefee..5d532e936d 100644 --- a/src/file_analysis/analyzer/entropy/Entropy.cc +++ b/src/file_analysis/analyzer/entropy/Entropy.cc @@ -9,12 +9,12 @@ using namespace file_analysis; -Entropy::Entropy(IntrusivePtr args, File* file) +Entropy::Entropy(zeek::RecordValPtr args, File* file) : file_analysis::Analyzer(file_mgr->GetComponentTag("ENTROPY"), std::move(args), file) { //entropy->Init(); - entropy = new EntropyVal; + entropy = new zeek::EntropyVal; fed = false; } @@ -23,7 +23,7 @@ Entropy::~Entropy() Unref(entropy); } -file_analysis::Analyzer* Entropy::Instantiate(IntrusivePtr args, +file_analysis::Analyzer* Entropy::Instantiate(zeek::RecordValPtr args, File* file) { return new Entropy(std::move(args), file); @@ -63,12 +63,12 @@ void Entropy::Finalize() entropy->Get(&ent, &chisq, &mean, &montepi, &scc); static auto entropy_test_result = zeek::id::find_type("entropy_test_result"); - auto ent_result = make_intrusive(entropy_test_result); - ent_result->Assign(0, ent); - ent_result->Assign(1, chisq); - ent_result->Assign(2, mean); - ent_result->Assign(3, montepi); - ent_result->Assign(4, scc); + auto ent_result = zeek::make_intrusive(entropy_test_result); + ent_result->Assign(0, ent); + ent_result->Assign(1, chisq); + ent_result->Assign(2, mean); + ent_result->Assign(3, montepi); + ent_result->Assign(4, scc); mgr.Enqueue(file_entropy, GetFile()->ToVal(), diff --git a/src/file_analysis/analyzer/entropy/Entropy.h b/src/file_analysis/analyzer/entropy/Entropy.h index 2f65f1aa56..0614e10df7 100644 --- a/src/file_analysis/analyzer/entropy/Entropy.h +++ b/src/file_analysis/analyzer/entropy/Entropy.h @@ -31,7 +31,7 @@ public: * @return the new Entropy analyzer instance or a null pointer if the * the "extraction_file" field of \a args wasn't set. */ - static file_analysis::Analyzer* Instantiate(IntrusivePtr args, + static file_analysis::Analyzer* Instantiate(zeek::RecordValPtr args, File* file); /** @@ -66,7 +66,7 @@ protected: * @param hv specific hash calculator object. * @param kind human readable name of the hash algorithm to use. */ - Entropy(IntrusivePtr args, File* file); + Entropy(zeek::RecordValPtr args, File* file); /** * If some file contents have been seen, finalizes the entropy of them and @@ -75,7 +75,7 @@ protected: void Finalize(); private: - EntropyVal* entropy; + zeek::EntropyVal* entropy; bool fed; }; diff --git a/src/file_analysis/analyzer/extract/Extract.cc b/src/file_analysis/analyzer/extract/Extract.cc index 869c8e8724..23db79deb3 100644 --- a/src/file_analysis/analyzer/extract/Extract.cc +++ b/src/file_analysis/analyzer/extract/Extract.cc @@ -10,7 +10,7 @@ using namespace file_analysis; -Extract::Extract(IntrusivePtr args, File* file, +Extract::Extract(zeek::RecordValPtr args, File* file, const std::string& arg_filename, uint64_t arg_limit) : file_analysis::Analyzer(file_mgr->GetComponentTag("EXTRACT"), std::move(args), file), @@ -33,8 +33,8 @@ Extract::~Extract() safe_close(fd); } -static const IntrusivePtr& get_extract_field_val(const IntrusivePtr& args, - const char* name) +static const zeek::ValPtr& get_extract_field_val(const zeek::RecordValPtr& args, + const char* name) { const auto& rval = args->GetField(name); @@ -44,7 +44,7 @@ static const IntrusivePtr& get_extract_field_val(const IntrusivePtr args, File* file) +file_analysis::Analyzer* Extract::Instantiate(zeek::RecordValPtr args, File* file) { const auto& fname = get_extract_field_val(args, "extract_filename"); const auto& limit = get_extract_field_val(args, "extract_limit"); @@ -96,8 +96,8 @@ bool Extract::DeliverStream(const u_char* data, uint64_t len) f->FileEvent(file_extraction_limit, { f->ToVal(), GetArgs(), - val_mgr->Count(limit), - val_mgr->Count(len) + zeek::val_mgr->Count(limit), + zeek::val_mgr->Count(len) }); // Limit may have been modified by a BIF, re-check it. diff --git a/src/file_analysis/analyzer/extract/Extract.h b/src/file_analysis/analyzer/extract/Extract.h index c51e2e1a80..3d146dba68 100644 --- a/src/file_analysis/analyzer/extract/Extract.h +++ b/src/file_analysis/analyzer/extract/Extract.h @@ -47,7 +47,7 @@ public: * @return the new Extract analyzer instance or a null pointer if the * the "extraction_file" field of \a args wasn't set. */ - static file_analysis::Analyzer* Instantiate(IntrusivePtr args, + static file_analysis::Analyzer* Instantiate(zeek::RecordValPtr args, File* file); /** @@ -67,7 +67,7 @@ protected: * to which the contents of the file will be extracted/written. * @param arg_limit the maximum allowed file size. */ - Extract(IntrusivePtr args, File* file, + Extract(zeek::RecordValPtr args, File* file, const std::string& arg_filename, uint64_t arg_limit); private: diff --git a/src/file_analysis/analyzer/extract/functions.bif b/src/file_analysis/analyzer/extract/functions.bif index 9d76849f23..60efadffbf 100644 --- a/src/file_analysis/analyzer/extract/functions.bif +++ b/src/file_analysis/analyzer/extract/functions.bif @@ -14,7 +14,7 @@ function FileExtract::__set_limit%(file_id: string, args: any, n: count%): bool auto rv = args->AsRecordVal()->CoerceTo(AnalyzerArgs); bool result = file_mgr->SetExtractionLimit(file_id->CheckString(), std::move(rv), n); - return val_mgr->Bool(result); + return zeek::val_mgr->Bool(result); %} module GLOBAL; diff --git a/src/file_analysis/analyzer/hash/Hash.cc b/src/file_analysis/analyzer/hash/Hash.cc index 011b6ef443..53a640da02 100644 --- a/src/file_analysis/analyzer/hash/Hash.cc +++ b/src/file_analysis/analyzer/hash/Hash.cc @@ -9,7 +9,7 @@ using namespace file_analysis; -Hash::Hash(IntrusivePtr args, File* file, HashVal* hv, const char* arg_kind) +Hash::Hash(zeek::RecordValPtr args, File* file, zeek::HashVal* hv, const char* arg_kind) : file_analysis::Analyzer(file_mgr->GetComponentTag(to_upper(arg_kind).c_str()), std::move(args), file), hash(hv), fed(false), kind(arg_kind) @@ -54,8 +54,8 @@ void Hash::Finalize() return; mgr.Enqueue(file_hash, - GetFile()->ToVal(), - make_intrusive(kind), - hash->Get() + GetFile()->ToVal(), + zeek::make_intrusive(kind), + hash->Get() ); } diff --git a/src/file_analysis/analyzer/hash/Hash.h b/src/file_analysis/analyzer/hash/Hash.h index 190152d1c3..3a87e00182 100644 --- a/src/file_analysis/analyzer/hash/Hash.h +++ b/src/file_analysis/analyzer/hash/Hash.h @@ -56,7 +56,7 @@ protected: * @param hv specific hash calculator object. * @param kind human readable name of the hash algorithm to use. */ - Hash(IntrusivePtr args, File* file, HashVal* hv, const char* kind); + Hash(zeek::RecordValPtr args, File* file, zeek::HashVal* hv, const char* kind); /** * If some file contents have been seen, finalizes the hash of them and @@ -65,7 +65,7 @@ protected: void Finalize(); private: - HashVal* hash; + zeek::HashVal* hash; bool fed; const char* kind; }; @@ -83,7 +83,7 @@ public: * @return the new MD5 analyzer instance or a null pointer if there's no * handler for the "file_hash" event. */ - static file_analysis::Analyzer* Instantiate(IntrusivePtr args, + static file_analysis::Analyzer* Instantiate(zeek::RecordValPtr args, File* file) { return file_hash ? new MD5(std::move(args), file) : nullptr; } @@ -94,8 +94,8 @@ protected: * @param args the \c AnalyzerArgs value which represents the analyzer. * @param file the file to which the analyzer will be attached. */ - MD5(IntrusivePtr args, File* file) - : Hash(std::move(args), file, new MD5Val(), "md5") + MD5(zeek::RecordValPtr args, File* file) + : Hash(std::move(args), file, new zeek::MD5Val(), "md5") {} }; @@ -112,7 +112,7 @@ public: * @return the new MD5 analyzer instance or a null pointer if there's no * handler for the "file_hash" event. */ - static file_analysis::Analyzer* Instantiate(IntrusivePtr args, + static file_analysis::Analyzer* Instantiate(zeek::RecordValPtr args, File* file) { return file_hash ? new SHA1(std::move(args), file) : nullptr; } @@ -123,8 +123,8 @@ protected: * @param args the \c AnalyzerArgs value which represents the analyzer. * @param file the file to which the analyzer will be attached. */ - SHA1(IntrusivePtr args, File* file) - : Hash(std::move(args), file, new SHA1Val(), "sha1") + SHA1(zeek::RecordValPtr args, File* file) + : Hash(std::move(args), file, new zeek::SHA1Val(), "sha1") {} }; @@ -141,7 +141,7 @@ public: * @return the new MD5 analyzer instance or a null pointer if there's no * handler for the "file_hash" event. */ - static file_analysis::Analyzer* Instantiate(IntrusivePtr args, + static file_analysis::Analyzer* Instantiate(zeek::RecordValPtr args, File* file) { return file_hash ? new SHA256(std::move(args), file) : nullptr; } @@ -152,8 +152,8 @@ protected: * @param args the \c AnalyzerArgs value which represents the analyzer. * @param file the file to which the analyzer will be attached. */ - SHA256(IntrusivePtr args, File* file) - : Hash(std::move(args), file, new SHA256Val(), "sha256") + SHA256(zeek::RecordValPtr args, File* file) + : Hash(std::move(args), file, new zeek::SHA256Val(), "sha256") {} }; diff --git a/src/file_analysis/analyzer/pe/PE.cc b/src/file_analysis/analyzer/pe/PE.cc index 0962f51dfa..5217f4e107 100644 --- a/src/file_analysis/analyzer/pe/PE.cc +++ b/src/file_analysis/analyzer/pe/PE.cc @@ -3,7 +3,7 @@ using namespace file_analysis; -PE::PE(IntrusivePtr args, File* file) +PE::PE(zeek::RecordValPtr args, File* file) : file_analysis::Analyzer(file_mgr->GetComponentTag("PE"), std::move(args), file) { diff --git a/src/file_analysis/analyzer/pe/PE.h b/src/file_analysis/analyzer/pe/PE.h index 87a82825f4..ef14744c3f 100644 --- a/src/file_analysis/analyzer/pe/PE.h +++ b/src/file_analysis/analyzer/pe/PE.h @@ -15,7 +15,7 @@ class PE : public file_analysis::Analyzer { public: ~PE(); - static file_analysis::Analyzer* Instantiate(IntrusivePtr args, + static file_analysis::Analyzer* Instantiate(zeek::RecordValPtr args, File* file) { return new PE(std::move(args), file); } @@ -24,7 +24,7 @@ public: virtual bool EndOfFile(); protected: - PE(IntrusivePtr args, File* file); + PE(zeek::RecordValPtr args, File* file); binpac::PE::File* interp; binpac::PE::MockConnection* conn; bool done; diff --git a/src/file_analysis/analyzer/pe/pe-analyzer.pac b/src/file_analysis/analyzer/pe/pe-analyzer.pac index ce34f015e6..d8771a0411 100644 --- a/src/file_analysis/analyzer/pe/pe-analyzer.pac +++ b/src/file_analysis/analyzer/pe/pe-analyzer.pac @@ -5,31 +5,31 @@ %} %header{ -IntrusivePtr process_rvas(const RVAS* rvas); -IntrusivePtr characteristics_to_bro(uint32_t c, uint8_t len); +zeek::VectorValPtr process_rvas(const RVAS* rvas); +zeek::TableValPtr characteristics_to_bro(uint32_t c, uint8_t len); %} %code{ -IntrusivePtr process_rvas(const RVAS* rva_table) +zeek::VectorValPtr process_rvas(const RVAS* rva_table) { - auto rvas = make_intrusive(zeek::id::index_vec); + auto rvas = zeek::make_intrusive(zeek::id::index_vec); for ( uint16 i=0; i < rva_table->rvas()->size(); ++i ) - rvas->Assign(i, val_mgr->Count((*rva_table->rvas())[i]->size())); + rvas->Assign(i, zeek::val_mgr->Count((*rva_table->rvas())[i]->size())); return rvas; } -IntrusivePtr characteristics_to_bro(uint32_t c, uint8_t len) +zeek::TableValPtr characteristics_to_bro(uint32_t c, uint8_t len) { uint64 mask = (len==16) ? 0xFFFF : 0xFFFFFFFF; - auto char_set = make_intrusive(zeek::id::count_set); + auto char_set = zeek::make_intrusive(zeek::id::count_set); for ( uint16 i=0; i < len; ++i ) { if ( ((c >> i) & 0x1) == 1 ) { - auto ch = val_mgr->Count((1<Count((1<Assign(std::move(ch), 0); } } @@ -46,24 +46,24 @@ refine flow File += { %{ if ( pe_dos_header ) { - auto dh = make_intrusive(zeek::BifType::Record::PE::DOSHeader); - dh->Assign(0, make_intrusive(${h.signature}.length(), (const char*) ${h.signature}.data())); - dh->Assign(1, val_mgr->Count(${h.UsedBytesInTheLastPage})); - dh->Assign(2, val_mgr->Count(${h.FileSizeInPages})); - dh->Assign(3, val_mgr->Count(${h.NumberOfRelocationItems})); - dh->Assign(4, val_mgr->Count(${h.HeaderSizeInParagraphs})); - dh->Assign(5, val_mgr->Count(${h.MinimumExtraParagraphs})); - dh->Assign(6, val_mgr->Count(${h.MaximumExtraParagraphs})); - dh->Assign(7, val_mgr->Count(${h.InitialRelativeSS})); - dh->Assign(8, val_mgr->Count(${h.InitialSP})); - dh->Assign(9, val_mgr->Count(${h.Checksum})); - dh->Assign(10, val_mgr->Count(${h.InitialIP})); - dh->Assign(11, val_mgr->Count(${h.InitialRelativeCS})); - dh->Assign(12, val_mgr->Count(${h.AddressOfRelocationTable})); - dh->Assign(13, val_mgr->Count(${h.OverlayNumber})); - dh->Assign(14, val_mgr->Count(${h.OEMid})); - dh->Assign(15, val_mgr->Count(${h.OEMinfo})); - dh->Assign(16, val_mgr->Count(${h.AddressOfNewExeHeader})); + auto dh = zeek::make_intrusive(zeek::BifType::Record::PE::DOSHeader); + dh->Assign(0, zeek::make_intrusive(${h.signature}.length(), (const char*) ${h.signature}.data())); + dh->Assign(1, zeek::val_mgr->Count(${h.UsedBytesInTheLastPage})); + dh->Assign(2, zeek::val_mgr->Count(${h.FileSizeInPages})); + dh->Assign(3, zeek::val_mgr->Count(${h.NumberOfRelocationItems})); + dh->Assign(4, zeek::val_mgr->Count(${h.HeaderSizeInParagraphs})); + dh->Assign(5, zeek::val_mgr->Count(${h.MinimumExtraParagraphs})); + dh->Assign(6, zeek::val_mgr->Count(${h.MaximumExtraParagraphs})); + dh->Assign(7, zeek::val_mgr->Count(${h.InitialRelativeSS})); + dh->Assign(8, zeek::val_mgr->Count(${h.InitialSP})); + dh->Assign(9, zeek::val_mgr->Count(${h.Checksum})); + dh->Assign(10, zeek::val_mgr->Count(${h.InitialIP})); + dh->Assign(11, zeek::val_mgr->Count(${h.InitialRelativeCS})); + dh->Assign(12, zeek::val_mgr->Count(${h.AddressOfRelocationTable})); + dh->Assign(13, zeek::val_mgr->Count(${h.OverlayNumber})); + dh->Assign(14, zeek::val_mgr->Count(${h.OEMid})); + dh->Assign(15, zeek::val_mgr->Count(${h.OEMinfo})); + dh->Assign(16, zeek::val_mgr->Count(${h.AddressOfNewExeHeader})); mgr.Enqueue(pe_dos_header, connection()->bro_analyzer()->GetFile()->ToVal(), @@ -77,7 +77,7 @@ refine flow File += { if ( pe_dos_code ) mgr.Enqueue(pe_dos_code, connection()->bro_analyzer()->GetFile()->ToVal(), - make_intrusive(code.length(), (const char*) code.data()) + zeek::make_intrusive(code.length(), (const char*) code.data()) ); return true; %} @@ -96,12 +96,12 @@ refine flow File += { %{ if ( pe_file_header ) { - auto fh = make_intrusive(zeek::BifType::Record::PE::FileHeader); - fh->Assign(0, val_mgr->Count(${h.Machine})); - fh->Assign(1, make_intrusive(static_cast(${h.TimeDateStamp}))); - fh->Assign(2, val_mgr->Count(${h.PointerToSymbolTable})); - fh->Assign(3, val_mgr->Count(${h.NumberOfSymbols})); - fh->Assign(4, val_mgr->Count(${h.SizeOfOptionalHeader})); + auto fh = zeek::make_intrusive(zeek::BifType::Record::PE::FileHeader); + fh->Assign(0, zeek::val_mgr->Count(${h.Machine})); + fh->Assign(1, zeek::make_intrusive(static_cast(${h.TimeDateStamp}))); + fh->Assign(2, zeek::val_mgr->Count(${h.PointerToSymbolTable})); + fh->Assign(3, zeek::val_mgr->Count(${h.NumberOfSymbols})); + fh->Assign(4, zeek::val_mgr->Count(${h.SizeOfOptionalHeader})); fh->Assign(5, characteristics_to_bro(${h.Characteristics}, 16)); mgr.Enqueue(pe_file_header, @@ -124,33 +124,33 @@ refine flow File += { if ( pe_optional_header ) { - auto oh = make_intrusive(zeek::BifType::Record::PE::OptionalHeader); + auto oh = zeek::make_intrusive(zeek::BifType::Record::PE::OptionalHeader); - oh->Assign(0, val_mgr->Count(${h.magic})); - oh->Assign(1, val_mgr->Count(${h.major_linker_version})); - oh->Assign(2, val_mgr->Count(${h.minor_linker_version})); - oh->Assign(3, val_mgr->Count(${h.size_of_code})); - oh->Assign(4, val_mgr->Count(${h.size_of_init_data})); - oh->Assign(5, val_mgr->Count(${h.size_of_uninit_data})); - oh->Assign(6, val_mgr->Count(${h.addr_of_entry_point})); - oh->Assign(7, val_mgr->Count(${h.base_of_code})); + oh->Assign(0, zeek::val_mgr->Count(${h.magic})); + oh->Assign(1, zeek::val_mgr->Count(${h.major_linker_version})); + oh->Assign(2, zeek::val_mgr->Count(${h.minor_linker_version})); + oh->Assign(3, zeek::val_mgr->Count(${h.size_of_code})); + oh->Assign(4, zeek::val_mgr->Count(${h.size_of_init_data})); + oh->Assign(5, zeek::val_mgr->Count(${h.size_of_uninit_data})); + oh->Assign(6, zeek::val_mgr->Count(${h.addr_of_entry_point})); + oh->Assign(7, zeek::val_mgr->Count(${h.base_of_code})); if ( ${h.pe_format} != PE32_PLUS ) - oh->Assign(8, val_mgr->Count(${h.base_of_data})); + oh->Assign(8, zeek::val_mgr->Count(${h.base_of_data})); - oh->Assign(9, val_mgr->Count(${h.image_base})); - oh->Assign(10, val_mgr->Count(${h.section_alignment})); - oh->Assign(11, val_mgr->Count(${h.file_alignment})); - oh->Assign(12, val_mgr->Count(${h.os_version_major})); - oh->Assign(13, val_mgr->Count(${h.os_version_minor})); - oh->Assign(14, val_mgr->Count(${h.major_image_version})); - oh->Assign(15, val_mgr->Count(${h.minor_image_version})); - oh->Assign(16, val_mgr->Count(${h.minor_subsys_version})); - oh->Assign(17, val_mgr->Count(${h.minor_subsys_version})); - oh->Assign(18, val_mgr->Count(${h.size_of_image})); - oh->Assign(19, val_mgr->Count(${h.size_of_headers})); - oh->Assign(20, val_mgr->Count(${h.checksum})); - oh->Assign(21, val_mgr->Count(${h.subsystem})); + oh->Assign(9, zeek::val_mgr->Count(${h.image_base})); + oh->Assign(10, zeek::val_mgr->Count(${h.section_alignment})); + oh->Assign(11, zeek::val_mgr->Count(${h.file_alignment})); + oh->Assign(12, zeek::val_mgr->Count(${h.os_version_major})); + oh->Assign(13, zeek::val_mgr->Count(${h.os_version_minor})); + oh->Assign(14, zeek::val_mgr->Count(${h.major_image_version})); + oh->Assign(15, zeek::val_mgr->Count(${h.minor_image_version})); + oh->Assign(16, zeek::val_mgr->Count(${h.minor_subsys_version})); + oh->Assign(17, zeek::val_mgr->Count(${h.minor_subsys_version})); + oh->Assign(18, zeek::val_mgr->Count(${h.size_of_image})); + oh->Assign(19, zeek::val_mgr->Count(${h.size_of_headers})); + oh->Assign(20, zeek::val_mgr->Count(${h.checksum})); + oh->Assign(21, zeek::val_mgr->Count(${h.subsystem})); oh->Assign(22, characteristics_to_bro(${h.dll_characteristics}, 16)); oh->Assign(23, process_rvas(${h.rvas})); @@ -166,7 +166,7 @@ refine flow File += { %{ if ( pe_section_header ) { - auto section_header = make_intrusive(zeek::BifType::Record::PE::SectionHeader); + auto section_header = zeek::make_intrusive(zeek::BifType::Record::PE::SectionHeader); // Strip null characters from the end of the section name. u_char* first_null = (u_char*) memchr(${h.name}.data(), 0, ${h.name}.length()); @@ -175,16 +175,16 @@ refine flow File += { name_len = ${h.name}.length(); else name_len = first_null - ${h.name}.data(); - section_header->Assign(0, make_intrusive(name_len, (const char*) ${h.name}.data())); + section_header->Assign(0, zeek::make_intrusive(name_len, (const char*) ${h.name}.data())); - section_header->Assign(1, val_mgr->Count(${h.virtual_size})); - section_header->Assign(2, val_mgr->Count(${h.virtual_addr})); - section_header->Assign(3, val_mgr->Count(${h.size_of_raw_data})); - section_header->Assign(4, val_mgr->Count(${h.ptr_to_raw_data})); - section_header->Assign(5, val_mgr->Count(${h.non_used_ptr_to_relocs})); - section_header->Assign(6, val_mgr->Count(${h.non_used_ptr_to_line_nums})); - section_header->Assign(7, val_mgr->Count(${h.non_used_num_of_relocs})); - section_header->Assign(8, val_mgr->Count(${h.non_used_num_of_line_nums})); + section_header->Assign(1, zeek::val_mgr->Count(${h.virtual_size})); + section_header->Assign(2, zeek::val_mgr->Count(${h.virtual_addr})); + section_header->Assign(3, zeek::val_mgr->Count(${h.size_of_raw_data})); + section_header->Assign(4, zeek::val_mgr->Count(${h.ptr_to_raw_data})); + section_header->Assign(5, zeek::val_mgr->Count(${h.non_used_ptr_to_relocs})); + section_header->Assign(6, zeek::val_mgr->Count(${h.non_used_ptr_to_line_nums})); + section_header->Assign(7, zeek::val_mgr->Count(${h.non_used_num_of_relocs})); + section_header->Assign(8, zeek::val_mgr->Count(${h.non_used_num_of_line_nums})); section_header->Assign(9, characteristics_to_bro(${h.characteristics}, 32)); mgr.Enqueue(pe_section_header, diff --git a/src/file_analysis/analyzer/unified2/Unified2.cc b/src/file_analysis/analyzer/unified2/Unified2.cc index e9b14373c6..0fdde8f668 100644 --- a/src/file_analysis/analyzer/unified2/Unified2.cc +++ b/src/file_analysis/analyzer/unified2/Unified2.cc @@ -5,7 +5,7 @@ using namespace file_analysis; -Unified2::Unified2(IntrusivePtr args, File* file) +Unified2::Unified2(zeek::RecordValPtr args, File* file) : file_analysis::Analyzer(file_mgr->GetComponentTag("UNIFIED2"), std::move(args), file) { interp = new binpac::Unified2::Unified2_Analyzer(this); @@ -16,7 +16,7 @@ Unified2::~Unified2() delete interp; } -file_analysis::Analyzer* Unified2::Instantiate(IntrusivePtr args, File* file) +file_analysis::Analyzer* Unified2::Instantiate(zeek::RecordValPtr args, File* file) { return new Unified2(std::move(args), file); } @@ -27,7 +27,6 @@ bool Unified2::DeliverStream(const u_char* data, uint64_t len) { interp->NewData(true, data, data + len); } - catch ( const binpac::Exception& e ) { printf("Binpac exception: %s\n", e.c_msg()); diff --git a/src/file_analysis/analyzer/unified2/Unified2.h b/src/file_analysis/analyzer/unified2/Unified2.h index b65c25e0a1..479ac96e84 100644 --- a/src/file_analysis/analyzer/unified2/Unified2.h +++ b/src/file_analysis/analyzer/unified2/Unified2.h @@ -20,11 +20,10 @@ public: bool DeliverStream(const u_char* data, uint64_t len) override; - static file_analysis::Analyzer* Instantiate(IntrusivePtr args, - File* file); + static file_analysis::Analyzer* Instantiate(zeek::RecordValPtr args, File* file); protected: - Unified2(IntrusivePtr args, File* file); + Unified2(zeek::RecordValPtr args, File* file); private: binpac::Unified2::Unified2_Analyzer* interp; diff --git a/src/file_analysis/analyzer/unified2/unified2-analyzer.pac b/src/file_analysis/analyzer/unified2/unified2-analyzer.pac index f29128dbeb..81700f080c 100644 --- a/src/file_analysis/analyzer/unified2/unified2-analyzer.pac +++ b/src/file_analysis/analyzer/unified2/unified2-analyzer.pac @@ -8,25 +8,25 @@ %} %code{ -IntrusivePtr binpac::Unified2::Flow::unified2_addr_to_bro_addr(std::vector* a) +zeek::AddrValPtr binpac::Unified2::Flow::unified2_addr_to_bro_addr(std::vector* a) { if ( a->size() == 1 ) { - return make_intrusive(IPAddr(IPv4, &(a->at(0)), IPAddr::Host)); + return zeek::make_intrusive(IPAddr(IPv4, &(a->at(0)), IPAddr::Host)); } else if ( a->size() == 4 ) { uint32 tmp[4] = { a->at(0), a->at(1), a->at(2), a->at(3) }; - return make_intrusive(IPAddr(IPv6, tmp, IPAddr::Host)); + return zeek::make_intrusive(IPAddr(IPv6, tmp, IPAddr::Host)); } else { // Should never reach here. - return make_intrusive(1); + return zeek::make_intrusive(1); } } -IntrusivePtr binpac::Unified2::Flow::to_port(uint16_t n, uint8_t p) +zeek::ValPtr binpac::Unified2::Flow::to_port(uint16_t n, uint8_t p) { TransportProto proto = TRANSPORT_UNKNOWN; switch ( p ) { @@ -35,15 +35,15 @@ IntrusivePtr binpac::Unified2::Flow::to_port(uint16_t n, uint8_t p) case 17: proto = TRANSPORT_UDP; break; } - return val_mgr->Port(n, proto); + return zeek::val_mgr->Port(n, proto); } %} refine flow Flow += { %member{ - IntrusivePtr unified2_addr_to_bro_addr(std::vector* a); - IntrusivePtr to_port(uint16_t n, uint8_t p); + zeek::AddrValPtr unified2_addr_to_bro_addr(std::vector* a); + zeek::ValPtr to_port(uint16_t n, uint8_t p); %} %init{ @@ -71,20 +71,20 @@ refine flow Flow += { %{ if ( ::unified2_event ) { - auto ids_event = make_intrusive(zeek::BifType::Record::Unified2::IDSEvent); - ids_event->Assign(0, val_mgr->Count(${ev.sensor_id})); - ids_event->Assign(1, val_mgr->Count(${ev.event_id})); - ids_event->Assign(2, make_intrusive(ts_to_double(${ev.ts}))); - ids_event->Assign(3, val_mgr->Count(${ev.signature_id})); - ids_event->Assign(4, val_mgr->Count(${ev.generator_id})); - ids_event->Assign(5, val_mgr->Count(${ev.signature_revision})); - ids_event->Assign(6, val_mgr->Count(${ev.classification_id})); - ids_event->Assign(7, val_mgr->Count(${ev.priority_id})); + auto ids_event = zeek::make_intrusive(zeek::BifType::Record::Unified2::IDSEvent); + ids_event->Assign(0, zeek::val_mgr->Count(${ev.sensor_id})); + ids_event->Assign(1, zeek::val_mgr->Count(${ev.event_id})); + ids_event->Assign(2, zeek::make_intrusive(ts_to_double(${ev.ts}))); + ids_event->Assign(3, zeek::val_mgr->Count(${ev.signature_id})); + ids_event->Assign(4, zeek::val_mgr->Count(${ev.generator_id})); + ids_event->Assign(5, zeek::val_mgr->Count(${ev.signature_revision})); + ids_event->Assign(6, zeek::val_mgr->Count(${ev.classification_id})); + ids_event->Assign(7, zeek::val_mgr->Count(${ev.priority_id})); ids_event->Assign(8, unified2_addr_to_bro_addr(${ev.src_ip})); ids_event->Assign(9, unified2_addr_to_bro_addr(${ev.dst_ip})); ids_event->Assign(10, to_port(${ev.src_p}, ${ev.protocol})); ids_event->Assign(11, to_port(${ev.dst_p}, ${ev.protocol})); - ids_event->Assign(17, val_mgr->Count(${ev.packet_action})); + ids_event->Assign(17, zeek::val_mgr->Count(${ev.packet_action})); mgr.Enqueue(::unified2_event, connection()->bro_analyzer()->GetFile()->ToVal(), @@ -97,24 +97,24 @@ refine flow Flow += { %{ if ( ::unified2_event ) { - auto ids_event = make_intrusive(zeek::BifType::Record::Unified2::IDSEvent); - ids_event->Assign(0, val_mgr->Count(${ev.sensor_id})); - ids_event->Assign(1, val_mgr->Count(${ev.event_id})); - ids_event->Assign(2, make_intrusive(ts_to_double(${ev.ts}))); - ids_event->Assign(3, val_mgr->Count(${ev.signature_id})); - ids_event->Assign(4, val_mgr->Count(${ev.generator_id})); - ids_event->Assign(5, val_mgr->Count(${ev.signature_revision})); - ids_event->Assign(6, val_mgr->Count(${ev.classification_id})); - ids_event->Assign(7, val_mgr->Count(${ev.priority_id})); + auto ids_event = zeek::make_intrusive(zeek::BifType::Record::Unified2::IDSEvent); + ids_event->Assign(0, zeek::val_mgr->Count(${ev.sensor_id})); + ids_event->Assign(1, zeek::val_mgr->Count(${ev.event_id})); + ids_event->Assign(2, zeek::make_intrusive(ts_to_double(${ev.ts}))); + ids_event->Assign(3, zeek::val_mgr->Count(${ev.signature_id})); + ids_event->Assign(4, zeek::val_mgr->Count(${ev.generator_id})); + ids_event->Assign(5, zeek::val_mgr->Count(${ev.signature_revision})); + ids_event->Assign(6, zeek::val_mgr->Count(${ev.classification_id})); + ids_event->Assign(7, zeek::val_mgr->Count(${ev.priority_id})); ids_event->Assign(8, unified2_addr_to_bro_addr(${ev.src_ip})); ids_event->Assign(9, unified2_addr_to_bro_addr(${ev.dst_ip})); ids_event->Assign(10, to_port(${ev.src_p}, ${ev.protocol})); ids_event->Assign(11, to_port(${ev.dst_p}, ${ev.protocol})); - ids_event->Assign(12, val_mgr->Count(${ev.impact_flag})); - ids_event->Assign(13, val_mgr->Count(${ev.impact})); - ids_event->Assign(14, val_mgr->Count(${ev.blocked})); - ids_event->Assign(15, val_mgr->Count(${ev.mpls_label})); - ids_event->Assign(16, val_mgr->Count(${ev.vlan_id})); + ids_event->Assign(12, zeek::val_mgr->Count(${ev.impact_flag})); + ids_event->Assign(13, zeek::val_mgr->Count(${ev.impact})); + ids_event->Assign(14, zeek::val_mgr->Count(${ev.blocked})); + ids_event->Assign(15, zeek::val_mgr->Count(${ev.mpls_label})); + ids_event->Assign(16, zeek::val_mgr->Count(${ev.vlan_id})); mgr.Enqueue(::unified2_event, connection()->bro_analyzer()->GetFile()->ToVal(), @@ -128,12 +128,12 @@ refine flow Flow += { %{ if ( ::unified2_packet ) { - auto packet = make_intrusive(zeek::BifType::Record::Unified2::Packet); - packet->Assign(0, val_mgr->Count(${pkt.sensor_id})); - packet->Assign(1, val_mgr->Count(${pkt.event_id})); - packet->Assign(2, val_mgr->Count(${pkt.event_second})); - packet->Assign(3, make_intrusive(ts_to_double(${pkt.packet_ts}))); - packet->Assign(4, val_mgr->Count(${pkt.link_type})); + auto packet = zeek::make_intrusive(zeek::BifType::Record::Unified2::Packet); + packet->Assign(0, zeek::val_mgr->Count(${pkt.sensor_id})); + packet->Assign(1, zeek::val_mgr->Count(${pkt.event_id})); + packet->Assign(2, zeek::val_mgr->Count(${pkt.event_second})); + packet->Assign(3, zeek::make_intrusive(ts_to_double(${pkt.packet_ts}))); + packet->Assign(4, zeek::val_mgr->Count(${pkt.link_type})); packet->Assign(5, to_stringval(${pkt.packet_data})); mgr.Enqueue(::unified2_packet, diff --git a/src/file_analysis/analyzer/x509/OCSP.cc b/src/file_analysis/analyzer/x509/OCSP.cc index 972742b5c3..c77b23fafd 100644 --- a/src/file_analysis/analyzer/x509/OCSP.cc +++ b/src/file_analysis/analyzer/x509/OCSP.cc @@ -1,3 +1,4 @@ + // See the file "COPYING" in the main distribution directory for copyright. #include @@ -79,10 +80,10 @@ static bool ocsp_add_cert_id(const OCSP_CERTID* cert_id, zeek::Args* vl, BIO* bi if ( ! res ) { reporter->Weird("OpenSSL failed to get OCSP_CERTID info"); - vl->emplace_back(val_mgr->EmptyString()); - vl->emplace_back(val_mgr->EmptyString()); - vl->emplace_back(val_mgr->EmptyString()); - vl->emplace_back(val_mgr->EmptyString()); + vl->emplace_back(zeek::val_mgr->EmptyString()); + vl->emplace_back(zeek::val_mgr->EmptyString()); + vl->emplace_back(zeek::val_mgr->EmptyString()); + vl->emplace_back(zeek::val_mgr->EmptyString()); return false; } @@ -91,40 +92,38 @@ static bool ocsp_add_cert_id(const OCSP_CERTID* cert_id, zeek::Args* vl, BIO* bi i2a_ASN1_OBJECT(bio, hash_alg); int len = BIO_read(bio, buf, sizeof(buf)); - vl->emplace_back(make_intrusive(len, buf)); + vl->emplace_back(zeek::make_intrusive(len, buf)); BIO_reset(bio); i2a_ASN1_STRING(bio, issuer_name_hash, V_ASN1_OCTET_STRING); len = BIO_read(bio, buf, sizeof(buf)); - vl->emplace_back(make_intrusive(len, buf)); + vl->emplace_back(zeek::make_intrusive(len, buf)); BIO_reset(bio); i2a_ASN1_STRING(bio, issuer_key_hash, V_ASN1_OCTET_STRING); len = BIO_read(bio, buf, sizeof(buf)); - vl->emplace_back(make_intrusive(len, buf)); + vl->emplace_back(zeek::make_intrusive(len, buf)); BIO_reset(bio); i2a_ASN1_INTEGER(bio, serial_number); len = BIO_read(bio, buf, sizeof(buf)); - vl->emplace_back(make_intrusive(len, buf)); + vl->emplace_back(zeek::make_intrusive(len, buf)); BIO_reset(bio); return true; } -file_analysis::Analyzer* OCSP::InstantiateRequest(IntrusivePtr args, - File* file) +file_analysis::Analyzer* OCSP::InstantiateRequest(zeek::RecordValPtr args, File* file) { return new OCSP(std::move(args), file, true); } -file_analysis::Analyzer* OCSP::InstantiateReply(IntrusivePtr args, - File* file) +file_analysis::Analyzer* OCSP::InstantiateReply(zeek::RecordValPtr args, File* file) { return new OCSP(std::move(args), file, false); } -file_analysis::OCSP::OCSP(IntrusivePtr args, file_analysis::File* file, +file_analysis::OCSP::OCSP(zeek::RecordValPtr args, file_analysis::File* file, bool arg_request) : file_analysis::X509Common::X509Common(file_mgr->GetComponentTag("OCSP"), std::move(args), file), @@ -210,9 +209,9 @@ typedef struct ocsp_basic_response_st { STACK_OF(X509) *certs; } OCSP_BASICRESP; */ -static IntrusivePtr parse_basic_resp_sig_alg(OCSP_BASICRESP* basic_resp, - BIO* bio, char* buf, - size_t buf_len) +static zeek::StringValPtr parse_basic_resp_sig_alg(OCSP_BASICRESP* basic_resp, + BIO* bio, char* buf, + size_t buf_len) { int der_basic_resp_len = 0; unsigned char* der_basic_resp_dat = nullptr; @@ -220,7 +219,7 @@ static IntrusivePtr parse_basic_resp_sig_alg(OCSP_BASICRESP* basic_re der_basic_resp_len = i2d_OCSP_BASICRESP(basic_resp, &der_basic_resp_dat); if ( der_basic_resp_len <= 0 ) - return val_mgr->EmptyString(); + return zeek::val_mgr->EmptyString(); const unsigned char* const_der_basic_resp_dat = der_basic_resp_dat; @@ -229,13 +228,13 @@ static IntrusivePtr parse_basic_resp_sig_alg(OCSP_BASICRESP* basic_re if ( ! bseq ) { OPENSSL_free(der_basic_resp_dat); - return val_mgr->EmptyString(); + return zeek::val_mgr->EmptyString(); } if ( sk_ASN1_TYPE_num(bseq) < 3 ) { OPENSSL_free(der_basic_resp_dat); - return val_mgr->EmptyString(); + return zeek::val_mgr->EmptyString(); } auto constexpr sig_alg_idx = 1u; @@ -244,7 +243,7 @@ static IntrusivePtr parse_basic_resp_sig_alg(OCSP_BASICRESP* basic_re if ( ASN1_TYPE_get(aseq_type) != V_ASN1_SEQUENCE ) { OPENSSL_free(der_basic_resp_dat); - return val_mgr->EmptyString(); + return zeek::val_mgr->EmptyString(); } auto aseq_str = aseq_type->value.asn1_string; @@ -256,13 +255,13 @@ static IntrusivePtr parse_basic_resp_sig_alg(OCSP_BASICRESP* basic_re if ( ! aseq ) { OPENSSL_free(der_basic_resp_dat); - return val_mgr->EmptyString(); + return zeek::val_mgr->EmptyString(); } if ( sk_ASN1_TYPE_num(aseq) < 1 ) { OPENSSL_free(der_basic_resp_dat); - return val_mgr->EmptyString(); + return zeek::val_mgr->EmptyString(); } auto constexpr alg_obj_idx = 0u; @@ -271,20 +270,20 @@ static IntrusivePtr parse_basic_resp_sig_alg(OCSP_BASICRESP* basic_re if ( ASN1_TYPE_get(alg_obj_type) != V_ASN1_OBJECT ) { OPENSSL_free(der_basic_resp_dat); - return val_mgr->EmptyString(); + return zeek::val_mgr->EmptyString(); } auto alg_obj = alg_obj_type->value.object; i2a_ASN1_OBJECT(bio, alg_obj); auto alg_len = BIO_read(bio, buf, buf_len); - auto rval = make_intrusive(alg_len, buf); + auto rval = zeek::make_intrusive(alg_len, buf); BIO_reset(bio); OPENSSL_free(der_basic_resp_dat); return rval; } -static IntrusivePtr parse_basic_resp_data_version(OCSP_BASICRESP* basic_resp) +static zeek::ValPtr parse_basic_resp_data_version(OCSP_BASICRESP* basic_resp) { int der_basic_resp_len = 0; unsigned char* der_basic_resp_dat = nullptr; @@ -292,7 +291,7 @@ static IntrusivePtr parse_basic_resp_data_version(OCSP_BASICRESP* basic_res der_basic_resp_len = i2d_OCSP_BASICRESP(basic_resp, &der_basic_resp_dat); if ( der_basic_resp_len <= 0 ) - return val_mgr->Count(-1); + return zeek::val_mgr->Count(-1); const unsigned char* const_der_basic_resp_dat = der_basic_resp_dat; @@ -301,13 +300,13 @@ static IntrusivePtr parse_basic_resp_data_version(OCSP_BASICRESP* basic_res if ( ! bseq ) { OPENSSL_free(der_basic_resp_dat); - return val_mgr->Count(-1); + return zeek::val_mgr->Count(-1); } if ( sk_ASN1_TYPE_num(bseq) < 3 ) { OPENSSL_free(der_basic_resp_dat); - return val_mgr->Count(-1); + return zeek::val_mgr->Count(-1); } auto constexpr resp_data_idx = 0u; @@ -316,7 +315,7 @@ static IntrusivePtr parse_basic_resp_data_version(OCSP_BASICRESP* basic_res if ( ASN1_TYPE_get(dseq_type) != V_ASN1_SEQUENCE ) { OPENSSL_free(der_basic_resp_dat); - return val_mgr->Count(-1); + return zeek::val_mgr->Count(-1); } auto dseq_str = dseq_type->value.asn1_string; @@ -328,13 +327,13 @@ static IntrusivePtr parse_basic_resp_data_version(OCSP_BASICRESP* basic_res if ( ! dseq ) { OPENSSL_free(der_basic_resp_dat); - return val_mgr->Count(-1); + return zeek::val_mgr->Count(-1); } if ( sk_ASN1_TYPE_num(dseq) < 1 ) { OPENSSL_free(der_basic_resp_dat); - return val_mgr->Count(-1); + return zeek::val_mgr->Count(-1); } /*- ResponseData ::= SEQUENCE { @@ -352,12 +351,12 @@ static IntrusivePtr parse_basic_resp_data_version(OCSP_BASICRESP* basic_res { OPENSSL_free(der_basic_resp_dat); // Not present, use default value. - return val_mgr->Count(0); + return zeek::val_mgr->Count(0); } uint64_t asn1_int = ASN1_INTEGER_get(version_type->value.integer); OPENSSL_free(der_basic_resp_dat); - return val_mgr->Count(asn1_int); + return zeek::val_mgr->Count(asn1_int); } static uint64_t parse_request_version(OCSP_REQUEST* req) @@ -418,7 +417,7 @@ void file_analysis::OCSP::ParseRequest(OCSP_REQUEST* req) if ( ocsp_request ) mgr.Enqueue(ocsp_request, GetFile()->ToVal(), - val_mgr->Count(version) + zeek::val_mgr->Count(version) ); BIO *bio = BIO_new(BIO_s_mem()); @@ -452,14 +451,14 @@ void file_analysis::OCSP::ParseResponse(OCSP_RESPONSE *resp) const STACK_OF(X509)* certs = nullptr; int resp_count, num_ext = 0; - VectorVal *certs_vector = nullptr; + zeek::VectorVal *certs_vector = nullptr; int len = 0; char buf[OCSP_STRING_BUF_SIZE]; memset(buf, 0, sizeof(buf)); const char *status_str = OCSP_response_status_str(OCSP_response_status(resp)); - auto status_val = make_intrusive(strlen(status_str), status_str); + auto status_val = zeek::make_intrusive(strlen(status_str), status_str); if ( ocsp_response_status ) mgr.Enqueue(ocsp_response_status, GetFile()->ToVal(), status_val); @@ -493,7 +492,7 @@ void file_analysis::OCSP::ParseResponse(OCSP_RESPONSE *resp) vl.emplace_back(std::move(status_val)); #if ( OPENSSL_VERSION_NUMBER < 0x10100000L ) || defined(LIBRESSL_VERSION_NUMBER) - vl.emplace_back(val_mgr->Count((uint64_t)ASN1_INTEGER_get(resp_data->version))); + vl.emplace_back(zeek::val_mgr->Count((uint64_t)ASN1_INTEGER_get(resp_data->version))); #else vl.emplace_back(parse_basic_resp_data_version(basic_resp)); #endif @@ -502,13 +501,13 @@ void file_analysis::OCSP::ParseResponse(OCSP_RESPONSE *resp) if ( OCSP_RESPID_bio(basic_resp, bio) ) { len = BIO_read(bio, buf, sizeof(buf)); - vl.emplace_back(make_intrusive(len, buf)); + vl.emplace_back(zeek::make_intrusive(len, buf)); BIO_reset(bio); } else { reporter->Weird("OpenSSL failed to get OCSP responder id"); - vl.emplace_back(val_mgr->EmptyString()); + vl.emplace_back(zeek::val_mgr->EmptyString()); } // producedAt @@ -518,7 +517,7 @@ void file_analysis::OCSP::ParseResponse(OCSP_RESPONSE *resp) produced_at = OCSP_resp_get0_produced_at(basic_resp); #endif - vl.emplace_back(make_intrusive(GetTimeFromAsn1(produced_at, GetFile(), reporter))); + vl.emplace_back(zeek::make_intrusive(GetTimeFromAsn1(produced_at, GetFile(), reporter))); // responses @@ -561,36 +560,36 @@ void file_analysis::OCSP::ParseResponse(OCSP_RESPONSE *resp) reporter->Weird("OpenSSL failed to find status of OCSP response"); const char* cert_status_str = OCSP_cert_status_str(status); - rvl.emplace_back(make_intrusive(strlen(cert_status_str), cert_status_str)); + rvl.emplace_back(zeek::make_intrusive(strlen(cert_status_str), cert_status_str)); // revocation time and reason if revoked if ( status == V_OCSP_CERTSTATUS_REVOKED ) { - rvl.emplace_back(make_intrusive(GetTimeFromAsn1(revoke_time, GetFile(), reporter))); + rvl.emplace_back(zeek::make_intrusive(GetTimeFromAsn1(revoke_time, GetFile(), reporter))); if ( reason != OCSP_REVOKED_STATUS_NOSTATUS ) { const char* revoke_reason = OCSP_crl_reason_str(reason); - rvl.emplace_back(make_intrusive(strlen(revoke_reason), revoke_reason)); + rvl.emplace_back(zeek::make_intrusive(strlen(revoke_reason), revoke_reason)); } else - rvl.emplace_back(make_intrusive(0, "")); + rvl.emplace_back(zeek::make_intrusive(0, "")); } else { - rvl.emplace_back(make_intrusive(0.0)); - rvl.emplace_back(make_intrusive(0, "")); + rvl.emplace_back(zeek::make_intrusive(0.0)); + rvl.emplace_back(zeek::make_intrusive(0, "")); } if ( this_update ) - rvl.emplace_back(make_intrusive(GetTimeFromAsn1(this_update, GetFile(), reporter))); + rvl.emplace_back(zeek::make_intrusive(GetTimeFromAsn1(this_update, GetFile(), reporter))); else - rvl.emplace_back(make_intrusive(0.0)); + rvl.emplace_back(zeek::make_intrusive(0.0)); if ( next_update ) - rvl.emplace_back(make_intrusive(GetTimeFromAsn1(next_update, GetFile(), reporter))); + rvl.emplace_back(zeek::make_intrusive(GetTimeFromAsn1(next_update, GetFile(), reporter))); else - rvl.emplace_back(make_intrusive(0.0)); + rvl.emplace_back(zeek::make_intrusive(0.0)); if ( ocsp_response_certificate ) mgr.Enqueue(ocsp_response_certificate, std::move(rvl)); @@ -609,7 +608,7 @@ void file_analysis::OCSP::ParseResponse(OCSP_RESPONSE *resp) #if ( OPENSSL_VERSION_NUMBER < 0x10100000L ) || defined(LIBRESSL_VERSION_NUMBER) i2a_ASN1_OBJECT(bio, basic_resp->signatureAlgorithm->algorithm); len = BIO_read(bio, buf, sizeof(buf)); - vl.emplace_back(make_intrusive(len, buf)); + vl.emplace_back(zeek::make_intrusive(len, buf)); BIO_reset(bio); #else vl.emplace_back(parse_basic_resp_sig_alg(basic_resp, bio, buf, sizeof(buf))); @@ -617,11 +616,11 @@ void file_analysis::OCSP::ParseResponse(OCSP_RESPONSE *resp) //i2a_ASN1_OBJECT(bio, basic_resp->signature); //len = BIO_read(bio, buf, sizeof(buf)); - //ocsp_resp_record->Assign(7, make_intrusive(len, buf)); + //ocsp_resp_record->Assign(7, zeek::make_intrusive(len, buf)); //BIO_reset(bio); - certs_vector = new VectorVal(zeek::id::find_type("x509_opaque_vector")); - vl.emplace_back(AdoptRef{}, certs_vector); + certs_vector = new zeek::VectorVal(zeek::id::find_type("x509_opaque_vector")); + vl.emplace_back(zeek::AdoptRef{}, certs_vector); #if ( OPENSSL_VERSION_NUMBER < 0x10100000L ) || defined(LIBRESSL_VERSION_NUMBER) certs = basic_resp->certs; @@ -637,7 +636,7 @@ void file_analysis::OCSP::ParseResponse(OCSP_RESPONSE *resp) ::X509 *this_cert = X509_dup(helper_sk_X509_value(certs, i)); //::X509 *this_cert = X509_dup(sk_X509_value(certs, i)); if (this_cert) - certs_vector->Assign(i, make_intrusive(this_cert)); + certs_vector->Assign(i, zeek::make_intrusive(this_cert)); else reporter->Weird("OpenSSL returned null certificate"); } diff --git a/src/file_analysis/analyzer/x509/OCSP.h b/src/file_analysis/analyzer/x509/OCSP.h index c3cec77cec..e0ebc8eca8 100644 --- a/src/file_analysis/analyzer/x509/OCSP.h +++ b/src/file_analysis/analyzer/x509/OCSP.h @@ -18,13 +18,13 @@ public: bool Undelivered(uint64_t offset, uint64_t len) override; bool EndOfFile() override; - static file_analysis::Analyzer* InstantiateRequest(IntrusivePtr args, + static file_analysis::Analyzer* InstantiateRequest(zeek::RecordValPtr args, File* file); - static file_analysis::Analyzer* InstantiateReply(IntrusivePtr args, + static file_analysis::Analyzer* InstantiateReply(zeek::RecordValPtr args, File* file); protected: - OCSP(IntrusivePtr args, File* file, bool request); + OCSP(zeek::RecordValPtr args, File* file, bool request); private: void ParseResponse(OCSP_RESPONSE*); diff --git a/src/file_analysis/analyzer/x509/X509.cc b/src/file_analysis/analyzer/x509/X509.cc index a5cd0a1ce2..a978762b07 100644 --- a/src/file_analysis/analyzer/x509/X509.cc +++ b/src/file_analysis/analyzer/x509/X509.cc @@ -23,7 +23,7 @@ using namespace file_analysis; -file_analysis::X509::X509(IntrusivePtr args, file_analysis::File* file) +file_analysis::X509::X509(zeek::RecordValPtr args, file_analysis::File* file) : file_analysis::X509Common::X509Common(file_mgr->GetComponentTag("X509"), std::move(args), file) { @@ -53,7 +53,7 @@ bool file_analysis::X509::EndOfFile() hash_update(ctx, cert_char, cert_data.size()); hash_final(ctx, buf); std::string cert_sha256 = sha256_digest_print(buf); - auto index = make_intrusive(cert_sha256); + auto index = zeek::make_intrusive(cert_sha256); const auto& entry = certificate_cache->Find(index); if ( entry ) @@ -65,7 +65,7 @@ bool file_analysis::X509::EndOfFile() // yup, let's call the callback. cache_hit_callback->Invoke(GetFile()->ToVal(), entry, - make_intrusive(cert_sha256)); + zeek::make_intrusive(cert_sha256)); return false; } } @@ -88,7 +88,7 @@ bool file_analysis::X509::EndOfFile() if ( x509_certificate ) mgr.Enqueue(x509_certificate, GetFile()->ToVal(), - IntrusivePtr{NewRef{}, cert_val}, + zeek::IntrusivePtr{zeek::NewRef{}, cert_val}, cert_record); // after parsing the certificate - parse the extensions... @@ -113,25 +113,25 @@ bool file_analysis::X509::EndOfFile() return false; } -IntrusivePtr file_analysis::X509::ParseCertificate(X509Val* cert_val, File* f) +zeek::RecordValPtr file_analysis::X509::ParseCertificate(X509Val* cert_val, File* f) { ::X509* ssl_cert = cert_val->GetCertificate(); char buf[2048]; // we need a buffer for some of the openssl functions memset(buf, 0, sizeof(buf)); - auto pX509Cert = make_intrusive(zeek::BifType::Record::X509::Certificate); + auto pX509Cert = zeek::make_intrusive(zeek::BifType::Record::X509::Certificate); BIO *bio = BIO_new(BIO_s_mem()); - pX509Cert->Assign(0, val_mgr->Count((uint64_t) X509_get_version(ssl_cert) + 1)); + pX509Cert->Assign(0, zeek::val_mgr->Count((uint64_t) X509_get_version(ssl_cert) + 1)); i2a_ASN1_INTEGER(bio, X509_get_serialNumber(ssl_cert)); int len = BIO_read(bio, buf, sizeof(buf)); - pX509Cert->Assign(1, make_intrusive(len, buf)); + pX509Cert->Assign(1, zeek::make_intrusive(len, buf)); BIO_reset(bio); X509_NAME_print_ex(bio, X509_get_subject_name(ssl_cert), 0, XN_FLAG_RFC2253); len = BIO_gets(bio, buf, sizeof(buf)); - pX509Cert->Assign(2, make_intrusive(len, buf)); + pX509Cert->Assign(2, zeek::make_intrusive(len, buf)); BIO_reset(bio); X509_NAME *subject_name = X509_get_subject_name(ssl_cert); @@ -151,17 +151,17 @@ IntrusivePtr file_analysis::X509::ParseCertificate(X509Val* cert_val, // we found a common name ASN1_STRING_print(bio, X509_NAME_ENTRY_get_data(X509_NAME_get_entry(subject_name, namepos))); len = BIO_gets(bio, buf, sizeof(buf)); - pX509Cert->Assign(4, make_intrusive(len, buf)); + pX509Cert->Assign(4, zeek::make_intrusive(len, buf)); BIO_reset(bio); } X509_NAME_print_ex(bio, X509_get_issuer_name(ssl_cert), 0, XN_FLAG_RFC2253); len = BIO_gets(bio, buf, sizeof(buf)); - pX509Cert->Assign(3, make_intrusive(len, buf)); + pX509Cert->Assign(3, zeek::make_intrusive(len, buf)); BIO_free(bio); - pX509Cert->Assign(5, make_intrusive(GetTimeFromAsn1(X509_get_notBefore(ssl_cert), f, reporter))); - pX509Cert->Assign(6, make_intrusive(GetTimeFromAsn1(X509_get_notAfter(ssl_cert), f, reporter))); + pX509Cert->Assign(5, zeek::make_intrusive(GetTimeFromAsn1(X509_get_notBefore(ssl_cert), f, reporter))); + pX509Cert->Assign(6, zeek::make_intrusive(GetTimeFromAsn1(X509_get_notAfter(ssl_cert), f, reporter))); // we only read 255 bytes because byte 256 is always 0. // if the string is longer than 255, that will be our null-termination, @@ -171,7 +171,7 @@ IntrusivePtr file_analysis::X509::ParseCertificate(X509Val* cert_val, if ( ! i2t_ASN1_OBJECT(buf, 255, algorithm) ) buf[0] = 0; - pX509Cert->Assign(7, make_intrusive(buf)); + pX509Cert->Assign(7, zeek::make_intrusive(buf)); // Special case for RDP server certificates. For some reason some (all?) RDP server // certificates like to specify their key algorithm as md5WithRSAEncryption, which @@ -193,25 +193,25 @@ IntrusivePtr file_analysis::X509::ParseCertificate(X509Val* cert_val, if ( ! i2t_ASN1_OBJECT(buf, 255, OBJ_nid2obj(X509_get_signature_nid(ssl_cert))) ) buf[0] = 0; - pX509Cert->Assign(8, make_intrusive(buf)); + pX509Cert->Assign(8, zeek::make_intrusive(buf)); // Things we can do when we have the key... EVP_PKEY *pkey = X509_extract_key(ssl_cert); if ( pkey != NULL ) { if ( EVP_PKEY_base_id(pkey) == EVP_PKEY_DSA ) - pX509Cert->Assign(9, make_intrusive("dsa")); + pX509Cert->Assign(9, zeek::make_intrusive("dsa")); else if ( EVP_PKEY_base_id(pkey) == EVP_PKEY_RSA ) { - pX509Cert->Assign(9, make_intrusive("rsa")); + pX509Cert->Assign(9, zeek::make_intrusive("rsa")); const BIGNUM *e; RSA_get0_key(EVP_PKEY_get0_RSA(pkey), NULL, &e, NULL); char *exponent = BN_bn2dec(e); if ( exponent != NULL ) { - pX509Cert->Assign(11, make_intrusive(exponent)); + pX509Cert->Assign(11, zeek::make_intrusive(exponent)); OPENSSL_free(exponent); exponent = NULL; } @@ -219,7 +219,7 @@ IntrusivePtr file_analysis::X509::ParseCertificate(X509Val* cert_val, #ifndef OPENSSL_NO_EC else if ( EVP_PKEY_base_id(pkey) == EVP_PKEY_EC ) { - pX509Cert->Assign(9, make_intrusive("ecdsa")); + pX509Cert->Assign(9, zeek::make_intrusive("ecdsa")); pX509Cert->Assign(12, KeyCurve(pkey)); } #endif @@ -231,7 +231,7 @@ IntrusivePtr file_analysis::X509::ParseCertificate(X509Val* cert_val, unsigned int length = KeyLength(pkey); if ( length > 0 ) - pX509Cert->Assign(10, val_mgr->Count(length)); + pX509Cert->Assign(10, zeek::val_mgr->Count(length)); EVP_PKEY_free(pkey); } @@ -240,7 +240,7 @@ IntrusivePtr file_analysis::X509::ParseCertificate(X509Val* cert_val, return pX509Cert; } -X509_STORE* file_analysis::X509::GetRootStore(TableVal* root_certs) +X509_STORE* file_analysis::X509::GetRootStore(zeek::TableVal* root_certs) { // If this certificate store was built previously, just reuse the old one. if ( x509_stores.count(root_certs) > 0 ) @@ -254,13 +254,13 @@ X509_STORE* file_analysis::X509::GetRootStore(TableVal* root_certs) { const auto& key = idxs->Idx(i); auto val = root_certs->FindOrDefault(key); - StringVal* sv = val->AsStringVal(); + zeek::StringVal* sv = val->AsStringVal(); assert(sv); const uint8_t* data = sv->Bytes(); ::X509* x = d2i_X509(NULL, &data, sv->Len()); if ( ! x ) { - builtin_error(fmt("Root CA error: %s", ERR_error_string(ERR_get_error(), NULL))); + zeek::emit_builtin_error(fmt("Root CA error: %s", ERR_error_string(ERR_get_error(), NULL))); return nullptr; } @@ -290,11 +290,11 @@ void file_analysis::X509::ParseBasicConstraints(X509_EXTENSION* ex) { if ( x509_ext_basic_constraints ) { - auto pBasicConstraint = make_intrusive(zeek::BifType::Record::X509::BasicConstraints); - pBasicConstraint->Assign(0, val_mgr->Bool(constr->ca)); + auto pBasicConstraint = zeek::make_intrusive(zeek::BifType::Record::X509::BasicConstraints); + pBasicConstraint->Assign(0, zeek::val_mgr->Bool(constr->ca)); if ( constr->pathlen ) - pBasicConstraint->Assign(1, val_mgr->Count((int32_t) ASN1_INTEGER_get(constr->pathlen))); + pBasicConstraint->Assign(1, zeek::val_mgr->Count((int32_t) ASN1_INTEGER_get(constr->pathlen))); mgr.Enqueue(x509_ext_basic_constraints, GetFile()->ToVal(), @@ -340,10 +340,10 @@ void file_analysis::X509::ParseSAN(X509_EXTENSION* ext) return; } - IntrusivePtr names; - IntrusivePtr emails; - IntrusivePtr uris; - IntrusivePtr ips; + zeek::VectorValPtr names; + zeek::VectorValPtr emails; + zeek::VectorValPtr uris; + zeek::VectorValPtr ips; bool otherfields = false; @@ -365,27 +365,27 @@ void file_analysis::X509::ParseSAN(X509_EXTENSION* ext) #else const char* name = (const char*) ASN1_STRING_get0_data(gen->d.ia5); #endif - auto bs = make_intrusive(name); + auto bs = zeek::make_intrusive(name); switch ( gen->type ) { case GEN_DNS: if ( names == nullptr ) - names = make_intrusive(zeek::id::string_vec); + names = zeek::make_intrusive(zeek::id::string_vec); names->Assign(names->Size(), std::move(bs)); break; case GEN_URI: if ( uris == nullptr ) - uris = make_intrusive(zeek::id::string_vec); + uris = zeek::make_intrusive(zeek::id::string_vec); uris->Assign(uris->Size(), std::move(bs)); break; case GEN_EMAIL: if ( emails == nullptr ) - emails = make_intrusive(zeek::id::string_vec); + emails = zeek::make_intrusive(zeek::id::string_vec); emails->Assign(emails->Size(), std::move(bs)); break; @@ -395,15 +395,15 @@ void file_analysis::X509::ParseSAN(X509_EXTENSION* ext) else if ( gen->type == GEN_IPADD ) { if ( ips == nullptr ) - ips = make_intrusive(zeek::id::find_type("addr_vec")); + ips = zeek::make_intrusive(zeek::id::find_type("addr_vec")); uint32_t* addr = (uint32_t*) gen->d.ip->data; if( gen->d.ip->length == 4 ) - ips->Assign(ips->Size(), make_intrusive(*addr)); + ips->Assign(ips->Size(), zeek::make_intrusive(*addr)); else if ( gen->d.ip->length == 16 ) - ips->Assign(ips->Size(), make_intrusive(addr)); + ips->Assign(ips->Size(), zeek::make_intrusive(addr)); else { @@ -421,7 +421,7 @@ void file_analysis::X509::ParseSAN(X509_EXTENSION* ext) } } - auto sanExt = make_intrusive(zeek::BifType::Record::X509::SubjectAlternativeName); + auto sanExt = zeek::make_intrusive(zeek::BifType::Record::X509::SubjectAlternativeName); if ( names != nullptr ) sanExt->Assign(0, names); @@ -435,7 +435,7 @@ void file_analysis::X509::ParseSAN(X509_EXTENSION* ext) if ( ips != nullptr ) sanExt->Assign(3, ips); - sanExt->Assign(4, val_mgr->Bool(otherfields)); + sanExt->Assign(4, zeek::val_mgr->Bool(otherfields)); mgr.Enqueue(x509_ext_subject_alternative_name, GetFile()->ToVal(), @@ -443,7 +443,7 @@ void file_analysis::X509::ParseSAN(X509_EXTENSION* ext) GENERAL_NAMES_free(altname); } -IntrusivePtr file_analysis::X509::KeyCurve(EVP_PKEY* key) +zeek::StringValPtr file_analysis::X509::KeyCurve(EVP_PKEY* key) { assert(key != nullptr); @@ -472,7 +472,7 @@ IntrusivePtr file_analysis::X509::KeyCurve(EVP_PKEY* key) if ( curve_name == nullptr ) return nullptr; - return make_intrusive(curve_name); + return zeek::make_intrusive(curve_name); #endif } @@ -543,9 +543,9 @@ X509Val::~X509Val() X509_free(certificate); } -IntrusivePtr X509Val::DoClone(CloneState* state) +zeek::ValPtr X509Val::DoClone(CloneState* state) { - auto copy = make_intrusive(); + auto copy = zeek::make_intrusive(); if ( certificate ) copy->certificate = X509_dup(certificate); diff --git a/src/file_analysis/analyzer/x509/X509.h b/src/file_analysis/analyzer/x509/X509.h index 092ac9aa94..884e1402d1 100644 --- a/src/file_analysis/analyzer/x509/X509.h +++ b/src/file_analysis/analyzer/x509/X509.h @@ -86,9 +86,9 @@ public: * @param Returns the new record value and passes ownership to * caller. */ - static IntrusivePtr ParseCertificate(X509Val* cert_val, File* file = nullptr); + static zeek::RecordValPtr ParseCertificate(X509Val* cert_val, File* file = nullptr); - static file_analysis::Analyzer* Instantiate(IntrusivePtr args, + static file_analysis::Analyzer* Instantiate(zeek::RecordValPtr args, File* file) { return new X509(std::move(args), file); } @@ -102,7 +102,7 @@ public: * * @return OpenSSL's X509 store associated with the table value. */ - static X509_STORE* GetRootStore(TableVal* root_certs); + static X509_STORE* GetRootStore(zeek::TableVal* root_certs); /** * Frees memory obtained from OpenSSL that is associated with the global @@ -117,17 +117,17 @@ public: /** * Sets the table[string] that used as the certificate cache inside of Zeek. */ - static void SetCertificateCache(IntrusivePtr cache) + static void SetCertificateCache(zeek::TableValPtr cache) { certificate_cache = std::move(cache); } /** * Sets the callback when a certificate cache hit is encountered */ - static void SetCertificateCacheHitCallback(IntrusivePtr func) + static void SetCertificateCacheHitCallback(zeek::FuncPtr func) { cache_hit_callback = std::move(func); } protected: - X509(IntrusivePtr args, File* file); + X509(zeek::RecordValPtr args, File* file); private: void ParseBasicConstraints(X509_EXTENSION* ex); @@ -137,12 +137,12 @@ private: std::string cert_data; // Helpers for ParseCertificate. - static IntrusivePtr KeyCurve(EVP_PKEY* key); + static zeek::StringValPtr KeyCurve(EVP_PKEY* key); static unsigned int KeyLength(EVP_PKEY *key); /** X509 stores associated with global script-layer values */ - inline static std::map x509_stores = std::map(); - inline static IntrusivePtr certificate_cache = nullptr; - inline static IntrusivePtr cache_hit_callback = nullptr; + inline static std::map x509_stores = std::map(); + inline static zeek::TableValPtr certificate_cache = nullptr; + inline static zeek::FuncPtr cache_hit_callback = nullptr; }; /** @@ -152,7 +152,7 @@ private: * script-land. Otherwise, we cannot verify certificates from Bro * scriptland */ -class X509Val : public OpaqueVal { +class X509Val : public zeek::OpaqueVal { public: /** * Construct an X509Val. @@ -170,7 +170,7 @@ public: * * @return A cloned X509Val. */ - IntrusivePtr DoClone(CloneState* state) override; + zeek::ValPtr DoClone(CloneState* state) override; /** * Destructor. diff --git a/src/file_analysis/analyzer/x509/X509Common.cc b/src/file_analysis/analyzer/x509/X509Common.cc index e30ac06f7c..27d8098833 100644 --- a/src/file_analysis/analyzer/x509/X509Common.cc +++ b/src/file_analysis/analyzer/x509/X509Common.cc @@ -17,7 +17,7 @@ using namespace file_analysis; X509Common::X509Common(const file_analysis::Tag& arg_tag, - IntrusivePtr arg_args, File* arg_file) + zeek::RecordValPtr arg_args, File* arg_file) : file_analysis::Analyzer(arg_tag, std::move(arg_args), arg_file) { } @@ -268,16 +268,16 @@ void file_analysis::X509Common::ParseExtension(X509_EXTENSION* ex, const EventHa } if ( ! ext_val ) - ext_val = make_intrusive(0, ""); + ext_val = zeek::make_intrusive(0, ""); - auto pX509Ext = make_intrusive(zeek::BifType::Record::X509::Extension); - pX509Ext->Assign(0, make_intrusive(name)); + auto pX509Ext = zeek::make_intrusive(zeek::BifType::Record::X509::Extension); + pX509Ext->Assign(0, zeek::make_intrusive(name)); if ( short_name and strlen(short_name) > 0 ) - pX509Ext->Assign(1, make_intrusive(short_name)); + pX509Ext->Assign(1, zeek::make_intrusive(short_name)); - pX509Ext->Assign(2, make_intrusive(oid)); - pX509Ext->Assign(3, val_mgr->Bool(critical)); + pX509Ext->Assign(2, zeek::make_intrusive(oid)); + pX509Ext->Assign(3, zeek::val_mgr->Bool(critical)); pX509Ext->Assign(4, ext_val); // send off generic extension event @@ -290,7 +290,7 @@ void file_analysis::X509Common::ParseExtension(X509_EXTENSION* ex, const EventHa if ( h == ocsp_extension ) mgr.Enqueue(h, GetFile()->ToVal(), std::move(pX509Ext), - val_mgr->Bool(global)); + zeek::val_mgr->Bool(global)); else mgr.Enqueue(h, GetFile()->ToVal(), std::move(pX509Ext)); @@ -298,7 +298,7 @@ void file_analysis::X509Common::ParseExtension(X509_EXTENSION* ex, const EventHa ParseExtensionsSpecific(ex, global, ext_asn, oid); } -IntrusivePtr file_analysis::X509Common::GetExtensionFromBIO(BIO* bio, File* f) +zeek::StringValPtr file_analysis::X509Common::GetExtensionFromBIO(BIO* bio, File* f) { BIO_flush(bio); ERR_clear_error(); @@ -316,7 +316,7 @@ IntrusivePtr file_analysis::X509Common::GetExtensionFromBIO(BIO* bio, if ( length == 0 ) { BIO_free_all(bio); - return val_mgr->EmptyString(); + return zeek::val_mgr->EmptyString(); } char* buffer = (char*) malloc(length); @@ -331,7 +331,7 @@ IntrusivePtr file_analysis::X509Common::GetExtensionFromBIO(BIO* bio, } BIO_read(bio, (void*) buffer, length); - auto ext_val = make_intrusive(length, buffer); + auto ext_val = zeek::make_intrusive(length, buffer); free(buffer); BIO_free_all(bio); diff --git a/src/file_analysis/analyzer/x509/X509Common.h b/src/file_analysis/analyzer/x509/X509Common.h index a7c9254d0b..677d886363 100644 --- a/src/file_analysis/analyzer/x509/X509Common.h +++ b/src/file_analysis/analyzer/x509/X509Common.h @@ -12,8 +12,12 @@ class EventHandlerPtr; class Reporter; -class StringVal; + +ZEEK_FORWARD_DECLARE_NAMESPACED(StringVal, zeek); +namespace zeek { template class IntrusivePtr; +using StringValPtr = zeek::IntrusivePtr; +} namespace file_analysis { @@ -35,13 +39,13 @@ public: * * @return The X509 extension value. */ - static IntrusivePtr GetExtensionFromBIO(BIO* bio, File* f = nullptr); + static zeek::StringValPtr GetExtensionFromBIO(BIO* bio, File* f = nullptr); static double GetTimeFromAsn1(const ASN1_TIME* atime, File* f, Reporter* reporter); protected: X509Common(const file_analysis::Tag& arg_tag, - IntrusivePtr arg_args, File* arg_file); + zeek::RecordValPtr arg_args, File* arg_file); void ParseExtension(X509_EXTENSION* ex, const EventHandlerPtr& h, bool global); void ParseSignedCertificateTimestamps(X509_EXTENSION* ext); diff --git a/src/file_analysis/analyzer/x509/functions.bif b/src/file_analysis/analyzer/x509/functions.bif index 214c10f24a..bb50e67b8b 100644 --- a/src/file_analysis/analyzer/x509/functions.bif +++ b/src/file_analysis/analyzer/x509/functions.bif @@ -11,12 +11,12 @@ #include // construct an error record -static IntrusivePtr x509_result_record(uint64_t num, const char* reason, IntrusivePtr chainVector = nullptr) +static zeek::RecordValPtr x509_result_record(uint64_t num, const char* reason, zeek::ValPtr chainVector = nullptr) { - auto rrecord = make_intrusive(zeek::BifType::Record::X509::Result); + auto rrecord = zeek::make_intrusive(zeek::BifType::Record::X509::Result); - rrecord->Assign(0, val_mgr->Int(num)); - rrecord->Assign(1, make_intrusive(reason)); + rrecord->Assign(0, zeek::val_mgr->Int(num)); + rrecord->Assign(1, zeek::make_intrusive(reason)); if ( chainVector ) rrecord->Assign(2, std::move(chainVector)); @@ -24,12 +24,13 @@ static IntrusivePtr x509_result_record(uint64_t num, const char* reas } // get all cretificates starting at the second one (assuming the first one is the host certificate) -STACK_OF(X509)* x509_get_untrusted_stack(VectorVal* certs_vec) +STACK_OF(X509)* x509_get_untrusted_stack(zeek::VectorVal* certs_vec) { STACK_OF(X509)* untrusted_certs = sk_X509_new_null(); if ( ! untrusted_certs ) { - builtin_error(fmt("Untrusted certificate stack initialization error: %s", ERR_error_string(ERR_get_error(),NULL))); + zeek::emit_builtin_error(fmt("Untrusted certificate stack initialization error: %s", + ERR_error_string(ERR_get_error(),NULL))); return 0; } @@ -45,7 +46,7 @@ STACK_OF(X509)* x509_get_untrusted_stack(VectorVal* certs_vec) if ( ! x ) { sk_X509_free(untrusted_certs); - builtin_error(fmt("No certificate in opaque in stack")); + zeek::emit_builtin_error(fmt("No certificate in opaque in stack")); return 0; } @@ -161,7 +162,7 @@ function x509_parse%(cert: opaque of x509%): X509::Certificate function x509_from_der%(der: string%): opaque of x509 %{ const u_char* data = der->Bytes(); - return make_intrusive(d2i_X509(nullptr, &data, der->Len())); + return zeek::make_intrusive(d2i_X509(nullptr, &data, der->Len())); %} ## Returns the string form of a certificate. @@ -192,7 +193,7 @@ function x509_get_certificate_string%(cert: opaque of x509, pem: bool &default=F auto ext_val = file_analysis::X509::GetExtensionFromBIO(bio); if ( ! ext_val ) - ext_val = val_mgr->EmptyString(); + ext_val = zeek::val_mgr->EmptyString(); return ext_val; %} @@ -215,13 +216,13 @@ function x509_get_certificate_string%(cert: opaque of x509, pem: bool &default=F ## x509_get_certificate_string x509_verify function x509_ocsp_verify%(certs: x509_opaque_vector, ocsp_reply: string, root_certs: table_string_of_string, verify_time: time &default=network_time()%): X509::Result %{ - IntrusivePtr rval; + zeek::RecordValPtr rval; X509_STORE* ctx = ::file_analysis::X509::GetRootStore(root_certs->AsTableVal()); if ( ! ctx ) return x509_result_record(-1, "Problem initializing root store"); - VectorVal *certs_vec = certs->AsVectorVal(); + zeek::VectorVal *certs_vec = certs->AsVectorVal(); if ( certs_vec->Size() < 1 ) { reporter->Error("No certificates given in vector"); @@ -233,7 +234,7 @@ function x509_ocsp_verify%(certs: x509_opaque_vector, ocsp_reply: string, root_c const auto& sv = certs_vec->At(index); if ( ! sv ) { - builtin_error("undefined value in certificate vector"); + zeek::emit_builtin_error("undefined value in certificate vector"); return x509_result_record(-1, "undefined value in certificate vector"); } @@ -242,7 +243,7 @@ function x509_ocsp_verify%(certs: x509_opaque_vector, ocsp_reply: string, root_c X509* cert = cert_handle->GetCertificate(); if ( ! cert ) { - builtin_error(fmt("No certificate in opaque")); + zeek::emit_builtin_error(fmt("No certificate in opaque")); return x509_result_record(-1, "No certificate in opaque"); } @@ -507,7 +508,7 @@ function x509_verify%(certs: x509_opaque_vector, root_certs: table_string_of_str return x509_result_record(-1, "Problem initializing root store"); - VectorVal *certs_vec = certs->AsVectorVal(); + zeek::VectorVal *certs_vec = certs->AsVectorVal(); if ( ! certs_vec || certs_vec->Size() < 1 ) { reporter->Error("No certificates given in vector"); @@ -519,7 +520,7 @@ function x509_verify%(certs: x509_opaque_vector, root_certs: table_string_of_str const auto& sv = certs_vec->At(index); if ( !sv ) { - builtin_error("undefined value in certificate vector"); + zeek::emit_builtin_error("undefined value in certificate vector"); return x509_result_record(-1, "undefined value in certificate vector"); } file_analysis::X509Val* cert_handle = (file_analysis::X509Val*) sv.get(); @@ -527,7 +528,7 @@ function x509_verify%(certs: x509_opaque_vector, root_certs: table_string_of_str X509* cert = cert_handle->GetCertificate(); if ( ! cert ) { - builtin_error(fmt("No certificate in opaque")); + zeek::emit_builtin_error(fmt("No certificate in opaque")); return x509_result_record(-1, "No certificate in opaque"); } @@ -542,7 +543,7 @@ function x509_verify%(certs: x509_opaque_vector, root_certs: table_string_of_str int result = X509_verify_cert(csc); - IntrusivePtr chainVector; + zeek::VectorValPtr chainVector; if ( result == 1 ) // we have a valid chain. try to get it... { @@ -556,7 +557,7 @@ function x509_verify%(certs: x509_opaque_vector, root_certs: table_string_of_str } int num_certs = sk_X509_num(chain); - chainVector = make_intrusive(zeek::id::find_type("x509_opaque_vector")); + chainVector = zeek::make_intrusive(zeek::id::find_type("x509_opaque_vector")); for ( int i = 0; i < num_certs; i++ ) { @@ -564,7 +565,7 @@ function x509_verify%(certs: x509_opaque_vector, root_certs: table_string_of_str if ( currcert ) // X509Val takes ownership of currcert. - chainVector->Assign(i, make_intrusive(currcert)); + chainVector->Assign(i, zeek::make_intrusive(currcert)); else { reporter->InternalWarning("OpenSSL returned null certificate"); @@ -623,7 +624,7 @@ function sct_verify%(cert: opaque of x509, logid: string, log_key: string, signa if ( precert && issuer_key_hash->Len() != 32) { reporter->Error("Invalid issuer_key_hash length"); - return val_mgr->False(); + return zeek::val_mgr->False(); } std::string data; @@ -647,7 +648,7 @@ function sct_verify%(cert: opaque of x509, logid: string, log_key: string, signa if ( pos < 0 ) { reporter->Error("NID_ct_precert_scts not found"); - return val_mgr->False(); + return zeek::val_mgr->False(); } #else int num_ext = X509_get_ext_count(x); @@ -742,7 +743,7 @@ function sct_verify%(cert: opaque of x509, logid: string, log_key: string, signa EVP_MD_CTX_destroy(mdctx); EVP_PKEY_free(key); - return val_mgr->Bool(success); + return zeek::val_mgr->Bool(success); sct_verify_err: if (mdctx) @@ -751,7 +752,7 @@ sct_verify_err: EVP_PKEY_free(key); reporter->Error("%s", errstr.c_str()); - return val_mgr->False(); + return zeek::val_mgr->False(); %} @@ -761,7 +762,7 @@ sct_verify_err: * 1 -> issuer name * 2 -> pubkey */ -IntrusivePtr x509_entity_hash(file_analysis::X509Val *cert_handle, unsigned int hash_alg, unsigned int type) +zeek::StringValPtr x509_entity_hash(file_analysis::X509Val *cert_handle, unsigned int hash_alg, unsigned int type) { assert(cert_handle); @@ -774,7 +775,7 @@ IntrusivePtr x509_entity_hash(file_analysis::X509Val *cert_handle, un X509 *cert_x509 = cert_handle->GetCertificate(); if ( cert_x509 == nullptr ) { - builtin_error("cannot get cert from opaque"); + zeek::emit_builtin_error("cannot get cert from opaque"); return nullptr; } @@ -782,14 +783,14 @@ IntrusivePtr x509_entity_hash(file_analysis::X509Val *cert_handle, un X509_NAME *issuer_name = X509_get_issuer_name(cert_x509); if ( subject_name == nullptr || issuer_name == nullptr ) { - builtin_error("fail to get subject/issuer name from certificate"); + zeek::emit_builtin_error("fail to get subject/issuer name from certificate"); return nullptr; } const EVP_MD *dgst = hash_to_evp(hash_alg); if ( dgst == nullptr ) { - builtin_error("Unknown hash algorithm."); + zeek::emit_builtin_error("Unknown hash algorithm."); return nullptr; } @@ -809,7 +810,7 @@ IntrusivePtr x509_entity_hash(file_analysis::X509Val *cert_handle, un int pklen = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert_x509), &spki); if ( ! pklen ) { - builtin_error("Could not get SPKI"); + zeek::emit_builtin_error("Could not get SPKI"); return nullptr; } res = EVP_Digest(spki, pklen, md, &len, dgst, nullptr); @@ -818,13 +819,13 @@ IntrusivePtr x509_entity_hash(file_analysis::X509Val *cert_handle, un if ( ! res ) { - builtin_error("Could not perform hash"); + zeek::emit_builtin_error("Could not perform hash"); return nullptr; } assert( len <= sizeof(md) ); - return make_intrusive(len, reinterpret_cast(md)); + return zeek::make_intrusive(len, reinterpret_cast(md)); } %%} @@ -900,9 +901,9 @@ function x509_spki_hash%(cert: opaque of x509, hash_alg: count%): string ## .. zeek:see:: x509_set_certificate_cache_hit_callback function x509_set_certificate_cache%(tbl: string_any_table%) : bool %{ - file_analysis::X509::SetCertificateCache({NewRef{}, tbl->AsTableVal()}); + file_analysis::X509::SetCertificateCache({zeek::NewRef{}, tbl->AsTableVal()}); - return val_mgr->True(); + return zeek::val_mgr->True(); %} ## This function sets up the callback that is called when an entry is matched against the table set @@ -918,7 +919,7 @@ function x509_set_certificate_cache%(tbl: string_any_table%) : bool ## .. zeek:see:: x509_set_certificate_cache function x509_set_certificate_cache_hit_callback%(f: string_any_file_hook%) : bool %{ - file_analysis::X509::SetCertificateCacheHitCallback({NewRef{}, f->AsFunc()}); + file_analysis::X509::SetCertificateCacheHitCallback({zeek::NewRef{}, f->AsFunc()}); - return val_mgr->True(); + return zeek::val_mgr->True(); %} diff --git a/src/file_analysis/analyzer/x509/x509-extension.pac b/src/file_analysis/analyzer/x509/x509-extension.pac index 9aaf095b71..6870244c35 100644 --- a/src/file_analysis/analyzer/x509/x509-extension.pac +++ b/src/file_analysis/analyzer/x509/x509-extension.pac @@ -40,12 +40,12 @@ refine connection MockConnection += { mgr.Enqueue(x509_ocsp_ext_signed_certificate_timestamp, bro_analyzer()->GetFile()->ToVal(), - val_mgr->Count(version), - make_intrusive(logid.length(), reinterpret_cast(logid.begin())), - val_mgr->Count(timestamp), - val_mgr->Count(digitally_signed_algorithms->HashAlgorithm()), - val_mgr->Count(digitally_signed_algorithms->SignatureAlgorithm()), - make_intrusive(digitally_signed_signature.length(), reinterpret_cast(digitally_signed_signature.begin())) + zeek::val_mgr->Count(version), + zeek::make_intrusive(logid.length(), reinterpret_cast(logid.begin())), + zeek::val_mgr->Count(timestamp), + zeek::val_mgr->Count(digitally_signed_algorithms->HashAlgorithm()), + zeek::val_mgr->Count(digitally_signed_algorithms->SignatureAlgorithm()), + zeek::make_intrusive(digitally_signed_signature.length(), reinterpret_cast(digitally_signed_signature.begin())) ); return true; diff --git a/src/file_analysis/file_analysis.bif b/src/file_analysis/file_analysis.bif index 7f60bc2845..c79e23fcac 100644 --- a/src/file_analysis/file_analysis.bif +++ b/src/file_analysis/file_analysis.bif @@ -14,28 +14,28 @@ type AnalyzerArgs: record; function Files::__set_timeout_interval%(file_id: string, t: interval%): bool %{ bool result = file_mgr->SetTimeoutInterval(file_id->CheckString(), t); - return val_mgr->Bool(result); + return zeek::val_mgr->Bool(result); %} ## :zeek:see:`Files::enable_reassembly`. function Files::__enable_reassembly%(file_id: string%): bool %{ bool result = file_mgr->EnableReassembly(file_id->CheckString()); - return val_mgr->Bool(result); + return zeek::val_mgr->Bool(result); %} ## :zeek:see:`Files::disable_reassembly`. function Files::__disable_reassembly%(file_id: string%): bool %{ bool result = file_mgr->DisableReassembly(file_id->CheckString()); - return val_mgr->Bool(result); + return zeek::val_mgr->Bool(result); %} ## :zeek:see:`Files::set_reassembly_buffer_size`. function Files::__set_reassembly_buffer%(file_id: string, max: count%): bool %{ bool result = file_mgr->SetReassemblyBuffer(file_id->CheckString(), max); - return val_mgr->Bool(result); + return zeek::val_mgr->Bool(result); %} ## :zeek:see:`Files::add_analyzer`. @@ -46,7 +46,7 @@ function Files::__add_analyzer%(file_id: string, tag: Files::Tag, args: any%): b bool result = file_mgr->AddAnalyzer(file_id->CheckString(), file_mgr->GetComponentTag(tag), std::move(rv)); - return val_mgr->Bool(result); + return zeek::val_mgr->Bool(result); %} ## :zeek:see:`Files::remove_analyzer`. @@ -57,30 +57,30 @@ function Files::__remove_analyzer%(file_id: string, tag: Files::Tag, args: any%) bool result = file_mgr->RemoveAnalyzer(file_id->CheckString(), file_mgr->GetComponentTag(tag), std::move(rv)); - return val_mgr->Bool(result); + return zeek::val_mgr->Bool(result); %} ## :zeek:see:`Files::stop`. function Files::__stop%(file_id: string%): bool %{ bool result = file_mgr->IgnoreFile(file_id->CheckString()); - return val_mgr->Bool(result); + return zeek::val_mgr->Bool(result); %} ## :zeek:see:`Files::analyzer_name`. function Files::__analyzer_name%(tag: Files::Tag%) : string %{ - const auto& n = file_mgr->GetComponentName(IntrusivePtr{NewRef{}, tag->AsEnumVal()}); - return make_intrusive(n); + const auto& n = file_mgr->GetComponentName(zeek::IntrusivePtr{zeek::NewRef{}, tag->AsEnumVal()}); + return zeek::make_intrusive(n); %} ## :zeek:see:`Files::file_exists`. function Files::__file_exists%(fuid: string%): bool %{ if ( file_mgr->LookupFile(fuid->CheckString()) != nullptr ) - return val_mgr->True(); + return zeek::val_mgr->True(); else - return val_mgr->False(); + return zeek::val_mgr->False(); %} ## :zeek:see:`Files::lookup_file`. diff --git a/src/input.h b/src/input.h index 2aacbea9a8..ab21d276ad 100644 --- a/src/input.h +++ b/src/input.h @@ -18,7 +18,7 @@ extern void add_input_file_at_front(const char* file); // Adds the substrings (using the given delimiter) in a string to the // given namelist. -extern void add_to_name_list(char* s, char delim, name_list& nl); +extern void add_to_name_list(char* s, char delim, zeek::name_list& nl); extern void begin_RE(); diff --git a/src/input/Manager.cc b/src/input/Manager.cc index f4fa7ea7e5..324e4f9288 100644 --- a/src/input/Manager.cc +++ b/src/input/Manager.cc @@ -61,12 +61,12 @@ public: StreamType stream_type; // to distinguish between event and table streams - EnumVal* type; + zeek::EnumVal* type; ReaderFrontend* reader; - TableVal* config; + zeek::TableVal* config; EventHandlerPtr error_event; - RecordVal* description; + zeek::RecordVal* description; virtual ~Stream(); @@ -95,14 +95,14 @@ public: unsigned int num_val_fields; bool want_record; - TableVal* tab; + zeek::TableVal* tab; zeek::RecordType* rtype; zeek::RecordType* itype; - PDict* currDict; - PDict* lastDict; + zeek::PDict* currDict; + zeek::PDict* lastDict; - Func* pred; + zeek::Func* pred; EventHandlerPtr event; @@ -198,7 +198,7 @@ Manager::~Manager() } -ReaderBackend* Manager::CreateBackend(ReaderFrontend* frontend, EnumVal* tag) +ReaderBackend* Manager::CreateBackend(ReaderFrontend* frontend, zeek::EnumVal* tag) { Component* c = Lookup(tag); @@ -215,7 +215,7 @@ ReaderBackend* Manager::CreateBackend(ReaderFrontend* frontend, EnumVal* tag) } // Create a new input reader object to be used at whomevers leisure later on. -bool Manager::CreateStream(Stream* info, RecordVal* description) +bool Manager::CreateStream(Stream* info, zeek::RecordVal* description) { zeek::RecordType* rtype = description->GetType()->AsRecordType(); if ( ! ( same_type(rtype, zeek::BifType::Record::Input::TableDescription, false) @@ -239,7 +239,7 @@ bool Manager::CreateStream(Stream* info, RecordVal* description) // get the source ... auto source_val = description->GetFieldOrDefault("source"); - const BroString* bsource = source_val->AsString(); + const zeek::String* bsource = source_val->AsString(); string source((const char*) bsource->Bytes(), bsource->Len()); ReaderBackend::ReaderInfo rinfo; @@ -273,9 +273,9 @@ bool Manager::CreateStream(Stream* info, RecordVal* description) { // create config mapping in ReaderInfo. Has to be done before the construction of reader_obj. HashKey* k; - IterCookie* c = info->config->AsTable()->InitForIteration(); + zeek::IterCookie* c = info->config->AsTable()->InitForIteration(); - TableEntryVal* v; + zeek::TableEntryVal* v; while ( (v = info->config->AsTable()->NextEntry(k, c)) ) { auto index = info->config->RecreateIndex(*k); @@ -303,7 +303,7 @@ bool Manager::CreateStream(Stream* info, RecordVal* description) return true; } -bool Manager::CreateEventStream(RecordVal* fval) +bool Manager::CreateEventStream(zeek::RecordVal* fval) { zeek::RecordType* rtype = fval->GetType()->AsRecordType(); if ( ! same_type(rtype, zeek::BifType::Record::Input::EventDescription, false) ) @@ -320,7 +320,7 @@ bool Manager::CreateEventStream(RecordVal* fval) auto want_record = fval->GetFieldOrDefault("want_record"); auto ev_val = fval->GetFieldOrDefault("ev"); - Func* event = ev_val->AsFunc(); + zeek::Func* event = ev_val->AsFunc(); const auto& etype = event->GetType(); @@ -409,7 +409,7 @@ bool Manager::CreateEventStream(RecordVal* fval) assert(false); auto error_event_val = fval->GetFieldOrDefault("error_ev"); - Func* error_event = error_event_val ? error_event_val->AsFunc() : nullptr; + zeek::Func* error_event = error_event_val ? error_event_val->AsFunc() : nullptr; if ( ! CheckErrorEventTypes(stream_name, error_event, false) ) return false; @@ -457,7 +457,7 @@ bool Manager::CreateEventStream(RecordVal* fval) return true; } -bool Manager::CreateTableStream(RecordVal* fval) +bool Manager::CreateTableStream(zeek::RecordVal* fval) { zeek::RecordType* rtype = fval->GetType()->AsRecordType(); if ( ! same_type(rtype, zeek::BifType::Record::Input::TableDescription, false) ) @@ -472,7 +472,7 @@ bool Manager::CreateTableStream(RecordVal* fval) auto idx_val = fval->GetFieldOrDefault("idx"); zeek::RecordType* idx = idx_val->AsType()->AsTypeType()->GetType()->AsRecordType(); - IntrusivePtr val; + zeek::RecordTypePtr val; auto val_val = fval->GetFieldOrDefault("val"); if ( val_val ) @@ -545,7 +545,7 @@ bool Manager::CreateTableStream(RecordVal* fval) } auto event_val = fval->GetFieldOrDefault("ev"); - Func* event = event_val ? event_val->AsFunc() : nullptr; + zeek::Func* event = event_val ? event_val->AsFunc() : nullptr; if ( event ) { @@ -618,7 +618,7 @@ bool Manager::CreateTableStream(RecordVal* fval) } auto error_event_val = fval->GetFieldOrDefault("error_ev"); - Func* error_event = error_event_val ? error_event_val->AsFunc() : nullptr; + zeek::Func* error_event = error_event_val ? error_event_val->AsFunc() : nullptr; if ( ! CheckErrorEventTypes(stream_name, error_event, true) ) return false; @@ -674,9 +674,9 @@ bool Manager::CreateTableStream(RecordVal* fval) stream->itype = idx->Ref()->AsRecordType(); stream->event = event ? event_registry->Lookup(event->Name()) : nullptr; stream->error_event = error_event ? event_registry->Lookup(error_event->Name()) : nullptr; - stream->currDict = new PDict; + stream->currDict = new zeek::PDict; stream->currDict->SetDeleteFunc(input_hash_delete_func); - stream->lastDict = new PDict; + stream->lastDict = new zeek::PDict; stream->lastDict->SetDeleteFunc(input_hash_delete_func); stream->want_record = ( want_record->InternalInt() == 1 ); @@ -691,7 +691,7 @@ bool Manager::CreateTableStream(RecordVal* fval) return true; } -bool Manager::CheckErrorEventTypes(const std::string& stream_name, const Func* ev, bool table) const +bool Manager::CheckErrorEventTypes(const std::string& stream_name, const zeek::Func* ev, bool table) const { if ( ev == nullptr ) return true; @@ -739,7 +739,7 @@ bool Manager::CheckErrorEventTypes(const std::string& stream_name, const Func* e return true; } -bool Manager::CreateAnalysisStream(RecordVal* fval) +bool Manager::CreateAnalysisStream(zeek::RecordVal* fval) { zeek::RecordType* rtype = fval->GetType()->AsRecordType(); @@ -929,7 +929,7 @@ bool Manager::UnrollRecordType(vector *fields, const zeek::RecordType *r { string name = nameprepend + rec->FieldName(i); const char* secondary = nullptr; - IntrusivePtr c; + zeek::ValPtr c; zeek::TypeTag ty = rec->GetFieldType(i)->Tag(); zeek::TypeTag st = zeek::TYPE_VOID; bool optional = false; @@ -989,9 +989,9 @@ bool Manager::ForceUpdate(const string &name) } -Val* Manager::RecordValToIndexVal(RecordVal *r) const +zeek::Val* Manager::RecordValToIndexVal(zeek::RecordVal* r) const { - IntrusivePtr idxval; + zeek::ValPtr idxval; zeek::RecordType *type = r->GetType()->AsRecordType(); @@ -1002,7 +1002,7 @@ Val* Manager::RecordValToIndexVal(RecordVal *r) const else { - auto l = make_intrusive(zeek::TYPE_ANY); + auto l = zeek::make_intrusive(zeek::TYPE_ANY); for ( int j = 0 ; j < num_fields; j++ ) l->Append(r->GetFieldOrDefault(j)); @@ -1014,12 +1014,12 @@ Val* Manager::RecordValToIndexVal(RecordVal *r) const } -Val* Manager::ValueToIndexVal(const Stream* i, int num_fields, const zeek::RecordType *type, const Value* const *vals, bool& have_error) const +zeek::Val* Manager::ValueToIndexVal(const Stream* i, int num_fields, const zeek::RecordType *type, + const Value* const *vals, bool& have_error) const { - Val* idxval; + zeek::Val* idxval; int position = 0; - if ( num_fields == 1 && type->GetFieldType(0)->Tag() != zeek::TYPE_RECORD ) { idxval = ValueToVal(i, vals[0], type->GetFieldType(0).get(), have_error); @@ -1027,15 +1027,15 @@ Val* Manager::ValueToIndexVal(const Stream* i, int num_fields, const zeek::Recor } else { - ListVal *l = new ListVal(zeek::TYPE_ANY); + auto* l = new zeek::ListVal(zeek::TYPE_ANY); for ( int j = 0 ; j < type->NumFields(); j++ ) { if ( type->GetFieldType(j)->Tag() == zeek::TYPE_RECORD ) - l->Append({AdoptRef{}, ValueToRecordVal(i, vals, + l->Append({zeek::AdoptRef{}, ValueToRecordVal(i, vals, type->GetFieldType(j)->AsRecordType(), &position, have_error)}); else { - l->Append({AdoptRef{}, ValueToVal(i, vals[position], type->GetFieldType(j).get(), have_error)}); + l->Append({zeek::AdoptRef{}, ValueToVal(i, vals[position], type->GetFieldType(j).get(), have_error)}); position++; } } @@ -1140,8 +1140,8 @@ int Manager::SendEntryTable(Stream* i, const Value* const *vals) } - Val* valval; - RecordVal* predidx = nullptr; + zeek::Val* valval; + zeek::RecordVal* predidx = nullptr; int position = stream->num_idx_fields; @@ -1159,7 +1159,7 @@ int Manager::SendEntryTable(Stream* i, const Value* const *vals) // call stream first to determine if we really add / change the entry if ( stream->pred && ! convert_error ) { - IntrusivePtr ev; + zeek::EnumValPtr ev; int startpos = 0; bool pred_convert_error = false; predidx = ValueToRecordVal(i, vals, stream->itype, &startpos, pred_convert_error); @@ -1208,7 +1208,7 @@ int Manager::SendEntryTable(Stream* i, const Value* const *vals) delete h; h = nullptr; - Val* idxval; + zeek::Val* idxval; if ( predidx != nullptr ) { idxval = RecordValToIndexVal(predidx); @@ -1230,12 +1230,12 @@ int Manager::SendEntryTable(Stream* i, const Value* const *vals) assert(idxval); - IntrusivePtr oldval; + zeek::ValPtr oldval; if ( updated == true ) { assert(stream->num_val_fields > 0); // in that case, we need the old value to send the event (if we send an event). - oldval = stream->tab->Find({NewRef{}, idxval}); + oldval = stream->tab->Find({zeek::NewRef{}, idxval}); } auto k = stream->tab->MakeHashKey(*idxval); @@ -1247,7 +1247,7 @@ int Manager::SendEntryTable(Stream* i, const Value* const *vals) ih->idxkey = new HashKey(k->Key(), k->Size(), k->Hash()); ih->valhash = valhash; - stream->tab->Assign({AdoptRef{}, idxval}, std::move(k), {AdoptRef{}, valval}); + stream->tab->Assign({zeek::AdoptRef{}, idxval}, std::move(k), {zeek::AdoptRef{}, valval}); if ( predidx != nullptr ) Unref(predidx); @@ -1259,7 +1259,7 @@ int Manager::SendEntryTable(Stream* i, const Value* const *vals) if ( stream->event ) { int startpos = 0; - Val* predidx = ValueToRecordVal(i, vals, stream->itype, &startpos, convert_error); + zeek::Val* predidx = ValueToRecordVal(i, vals, stream->itype, &startpos, convert_error); if ( convert_error ) { @@ -1319,16 +1319,16 @@ void Manager::EndCurrentSend(ReaderFrontend* reader) TableStream* stream = (TableStream*) i; // lastdict contains all deleted entries and should be empty apart from that - IterCookie *c = stream->lastDict->InitForIteration(); + zeek::IterCookie *c = stream->lastDict->InitForIteration(); stream->lastDict->MakeRobustCookie(c); InputHash* ih; HashKey *lastDictIdxKey; while ( ( ih = stream->lastDict->NextEntry(lastDictIdxKey, c) ) ) { - IntrusivePtr val; - IntrusivePtr predidx; - IntrusivePtr ev; + zeek::ValPtr val; + zeek::ValPtr predidx; + zeek::EnumValPtr ev; int startpos = 0; if ( stream->pred || stream->event ) @@ -1337,7 +1337,7 @@ void Manager::EndCurrentSend(ReaderFrontend* reader) assert(idx != nullptr); val = stream->tab->FindOrDefault(idx); assert(val != nullptr); - predidx = {AdoptRef{}, ListValToRecordVal(idx.get(), stream->itype, &startpos)}; + predidx = {zeek::AdoptRef{}, ListValToRecordVal(idx.get(), stream->itype, &startpos)}; ev = zeek::BifType::Enum::Input::Event->GetVal(BifEnum::Input::EVENT_REMOVED); } @@ -1372,7 +1372,7 @@ void Manager::EndCurrentSend(ReaderFrontend* reader) delete(stream->lastDict); stream->lastDict = stream->currDict; - stream->currDict = new PDict; + stream->currDict = new zeek::PDict; stream->currDict->SetDeleteFunc(input_hash_delete_func); #ifdef DEBUG @@ -1404,8 +1404,8 @@ void Manager::SendEndOfData(const Stream *i) DBG_LOG(DBG_INPUT, "SendEndOfData for stream %s", i->name.c_str()); #endif - SendEvent(end_of_data, 2, new StringVal(i->name.c_str()), - new StringVal(i->reader->Info().source)); + SendEvent(end_of_data, 2, new zeek::StringVal(i->name.c_str()), + new zeek::StringVal(i->reader->Info().source)); if ( i->stream_type == ANALYSIS_STREAM ) file_mgr->EndOfFile(static_cast(i)->file_id); @@ -1451,14 +1451,14 @@ void Manager::Put(ReaderFrontend* reader, Value* *vals) Value::delete_value_ptr_array(vals, readFields); } -int Manager::SendEventStreamEvent(Stream* i, EnumVal* type, const Value* const *vals) +int Manager::SendEventStreamEvent(Stream* i, zeek::EnumVal* type, const Value* const *vals) { assert(i); assert(i->stream_type == EVENT_STREAM); EventStream* stream = (EventStream*) i; - list out_vals; + list out_vals; Ref(stream->description); out_vals.push_back(stream->description); // no tracking, send everything with a new event... @@ -1470,7 +1470,7 @@ int Manager::SendEventStreamEvent(Stream* i, EnumVal* type, const Value* const * if ( stream->want_record ) { - RecordVal * r = ValueToRecordVal(i, vals, stream->fields, &position, convert_error); + zeek::RecordVal * r = ValueToRecordVal(i, vals, stream->fields, &position, convert_error); out_vals.push_back(r); } @@ -1478,7 +1478,7 @@ int Manager::SendEventStreamEvent(Stream* i, EnumVal* type, const Value* const * { for ( int j = 0; j < stream->fields->NumFields(); j++) { - Val* val = nullptr; + zeek::Val* val = nullptr; if ( stream->fields->GetFieldType(j)->Tag() == zeek::TYPE_RECORD ) val = ValueToRecordVal(i, vals, @@ -1498,7 +1498,7 @@ int Manager::SendEventStreamEvent(Stream* i, EnumVal* type, const Value* const * if ( convert_error ) { // we have an error somewhere in our out_vals. Just delete all of them. - for ( list::const_iterator it = out_vals.begin(), end = out_vals.end(); it != end; ++it ) + for ( list::const_iterator it = out_vals.begin(), end = out_vals.end(); it != end; ++it ) Unref(*it); } else @@ -1516,8 +1516,8 @@ int Manager::PutTable(Stream* i, const Value* const *vals) bool convert_error = false; - Val* idxval = ValueToIndexVal(i, stream->num_idx_fields, stream->itype, vals, convert_error); - Val* valval; + zeek::Val* idxval = ValueToIndexVal(i, stream->num_idx_fields, stream->itype, vals, convert_error); + zeek::Val* valval; int position = stream->num_idx_fields; @@ -1541,12 +1541,12 @@ int Manager::PutTable(Stream* i, const Value* const *vals) if ( stream->pred || stream->event ) { bool updated = false; - IntrusivePtr oldval; + zeek::ValPtr oldval; if ( stream->num_val_fields > 0 ) { // in that case, we need the old value to send the event (if we send an event). - oldval = stream->tab->Find({NewRef{}, idxval}); + oldval = stream->tab->Find({zeek::NewRef{}, idxval}); } if ( oldval != nullptr ) @@ -1559,10 +1559,10 @@ int Manager::PutTable(Stream* i, const Value* const *vals) // predicate if we want the update or not if ( stream->pred ) { - IntrusivePtr ev; + zeek::EnumValPtr ev; int startpos = 0; bool pred_convert_error = false; - Val* predidx = ValueToRecordVal(i, vals, stream->itype, &startpos, pred_convert_error); + zeek::Val* predidx = ValueToRecordVal(i, vals, stream->itype, &startpos, pred_convert_error); if ( pred_convert_error ) Unref(predidx); @@ -1593,13 +1593,13 @@ int Manager::PutTable(Stream* i, const Value* const *vals) } - stream->tab->Assign({NewRef{}, idxval}, {AdoptRef{}, valval}); + stream->tab->Assign({zeek::NewRef{}, idxval}, {zeek::AdoptRef{}, valval}); if ( stream->event ) { int startpos = 0; bool event_convert_error = false; - Val* predidx = ValueToRecordVal(i, vals, stream->itype, &startpos, event_convert_error); + zeek::Val* predidx = ValueToRecordVal(i, vals, stream->itype, &startpos, event_convert_error); if ( event_convert_error ) Unref(predidx); @@ -1631,7 +1631,7 @@ int Manager::PutTable(Stream* i, const Value* const *vals) } else // no predicates or other stuff - stream->tab->Assign({NewRef{}, idxval}, {AdoptRef{}, valval}); + stream->tab->Assign({zeek::NewRef{}, idxval}, {zeek::AdoptRef{}, valval}); Unref(idxval); // not consumed by assign @@ -1677,7 +1677,7 @@ bool Manager::Delete(ReaderFrontend* reader, Value* *vals) { TableStream* stream = (TableStream*) i; bool convert_error = false; - Val* idxval = ValueToIndexVal(i, stream->num_idx_fields, stream->itype, vals, convert_error); + zeek::Val* idxval = ValueToIndexVal(i, stream->num_idx_fields, stream->itype, vals, convert_error); assert(idxval != nullptr); readVals = stream->num_idx_fields + stream->num_val_fields; bool streamresult = true; @@ -1690,12 +1690,12 @@ bool Manager::Delete(ReaderFrontend* reader, Value* *vals) if ( stream->pred || stream->event ) { - auto val = stream->tab->FindOrDefault({NewRef{}, idxval}); + auto val = stream->tab->FindOrDefault({zeek::NewRef{}, idxval}); if ( stream->pred ) { int startpos = 0; - Val* predidx = ValueToRecordVal(i, vals, stream->itype, &startpos, convert_error); + zeek::Val* predidx = ValueToRecordVal(i, vals, stream->itype, &startpos, convert_error); if ( convert_error ) Unref(predidx); @@ -1703,7 +1703,7 @@ bool Manager::Delete(ReaderFrontend* reader, Value* *vals) { auto ev = zeek::BifType::Enum::Input::Event->GetVal(BifEnum::Input::EVENT_REMOVED); - streamresult = CallPred(stream->pred, 3, ev.release(), predidx, IntrusivePtr{val}.release()); + streamresult = CallPred(stream->pred, 3, ev.release(), predidx, zeek::IntrusivePtr{val}.release()); if ( streamresult == false ) { @@ -1721,7 +1721,7 @@ bool Manager::Delete(ReaderFrontend* reader, Value* *vals) Ref(idxval); assert(val != nullptr); auto ev = zeek::BifType::Enum::Input::Event->GetVal(BifEnum::Input::EVENT_REMOVED); - SendEvent(stream->event, 4, stream->description->Ref(), ev.release(), idxval, IntrusivePtr{val}.release()); + SendEvent(stream->event, 4, stream->description->Ref(), ev.release(), idxval, zeek::IntrusivePtr{val}.release()); } } @@ -1756,7 +1756,7 @@ bool Manager::Delete(ReaderFrontend* reader, Value* *vals) return success; } -bool Manager::CallPred(Func* pred_func, const int numvals, ...) const +bool Manager::CallPred(zeek::Func* pred_func, const int numvals, ...) const { bool result = false; zeek::Args vl; @@ -1765,7 +1765,7 @@ bool Manager::CallPred(Func* pred_func, const int numvals, ...) const va_list lP; va_start(lP, numvals); for ( int i = 0; i < numvals; i++ ) - vl.emplace_back(AdoptRef{}, va_arg(lP, Val*)); + vl.emplace_back(zeek::AdoptRef{}, va_arg(lP, zeek::Val*)); va_end(lP); @@ -1790,7 +1790,7 @@ void Manager::SendEvent(EventHandlerPtr ev, const int numvals, ...) const va_list lP; va_start(lP, numvals); for ( int i = 0; i < numvals; i++ ) - vl.emplace_back(AdoptRef{}, va_arg(lP, Val*)); + vl.emplace_back(zeek::AdoptRef{}, va_arg(lP, zeek::Val*)); va_end(lP); @@ -1798,7 +1798,7 @@ void Manager::SendEvent(EventHandlerPtr ev, const int numvals, ...) const mgr.Enqueue(ev, std::move(vl), SOURCE_LOCAL); } -void Manager::SendEvent(EventHandlerPtr ev, list events) const +void Manager::SendEvent(EventHandlerPtr ev, list events) const { zeek::Args vl; vl.reserve(events.size()); @@ -1808,8 +1808,8 @@ void Manager::SendEvent(EventHandlerPtr ev, list events) const events.size()); #endif - for ( list::iterator i = events.begin(); i != events.end(); i++ ) - vl.emplace_back(AdoptRef{}, *i); + for ( list::iterator i = events.begin(); i != events.end(); i++ ) + vl.emplace_back(zeek::AdoptRef{}, *i); if ( ev ) mgr.Enqueue(ev, std::move(vl), SOURCE_LOCAL); @@ -1817,11 +1817,11 @@ void Manager::SendEvent(EventHandlerPtr ev, list events) const // Convert a bro list value to a bro record value. // I / we could think about moving this functionality to val.cc -RecordVal* Manager::ListValToRecordVal(ListVal* list, zeek::RecordType *request_type, int* position) const +zeek::RecordVal* Manager::ListValToRecordVal(zeek::ListVal* list, zeek::RecordType *request_type, int* position) const { assert(position != nullptr); // we need the pointer to point to data; - RecordVal* rec = new RecordVal({NewRef{}, request_type}); + auto* rec = new zeek::RecordVal({zeek::NewRef{}, request_type}); assert(list != nullptr); int maxpos = list->Length(); @@ -1830,7 +1830,7 @@ RecordVal* Manager::ListValToRecordVal(ListVal* list, zeek::RecordType *request_ { assert ( (*position) <= maxpos ); - Val* fieldVal = nullptr; + zeek::Val* fieldVal = nullptr; if ( request_type->GetFieldType(i)->Tag() == zeek::TYPE_RECORD ) fieldVal = ListValToRecordVal(list, request_type->GetFieldType(i)->AsRecordType(), position); else @@ -1839,22 +1839,22 @@ RecordVal* Manager::ListValToRecordVal(ListVal* list, zeek::RecordType *request_ (*position)++; } - rec->Assign(i, {NewRef{}, fieldVal}); + rec->Assign(i, {zeek::NewRef{}, fieldVal}); } return rec; } // Convert a threading value to a record value -RecordVal* Manager::ValueToRecordVal(const Stream* stream, const Value* const *vals, - zeek::RecordType *request_type, int* position, bool& have_error) const +zeek::RecordVal* Manager::ValueToRecordVal(const Stream* stream, const Value* const *vals, + zeek::RecordType *request_type, int* position, bool& have_error) const { assert(position != nullptr); // we need the pointer to point to data. - RecordVal* rec = new RecordVal({NewRef{}, request_type}); + auto* rec = new zeek::RecordVal({zeek::NewRef{}, request_type}); for ( int i = 0; i < request_type->NumFields(); i++ ) { - Val* fieldVal = nullptr; + zeek::Val* fieldVal = nullptr; if ( request_type->GetFieldType(i)->Tag() == zeek::TYPE_RECORD ) fieldVal = ValueToRecordVal(stream, vals, request_type->GetFieldType(i)->AsRecordType(), position, have_error); else if ( request_type->GetFieldType(i)->Tag() == zeek::TYPE_FILE || @@ -1876,7 +1876,7 @@ RecordVal* Manager::ValueToRecordVal(const Stream* stream, const Value* const *v } if ( fieldVal ) - rec->Assign(i, {AdoptRef{}, fieldVal}); + rec->Assign(i, {zeek::AdoptRef{}, fieldVal}); } return rec; @@ -2159,7 +2159,7 @@ HashKey* Manager::HashValues(const int num_elements, const Value* const *vals) c // have_error is a reference to a boolean which is set to true as soon as an error occurs. // When have_error is set to true at the beginning of the function, it is assumed that // an error already occurred in the past and processing is aborted. -Val* Manager::ValueToVal(const Stream* i, const Value* val, zeek::Type* request_type, bool& have_error) const +zeek::Val* Manager::ValueToVal(const Stream* i, const Value* val, zeek::Type* request_type, bool& have_error) const { if ( have_error ) return nullptr; @@ -2175,32 +2175,32 @@ Val* Manager::ValueToVal(const Stream* i, const Value* val, zeek::Type* request_ switch ( val->type ) { case zeek::TYPE_BOOL: - return val_mgr->Bool(val->val.int_val)->Ref(); + return zeek::val_mgr->Bool(val->val.int_val)->Ref(); case zeek::TYPE_INT: - return val_mgr->Int(val->val.int_val).release(); + return zeek::val_mgr->Int(val->val.int_val).release(); case zeek::TYPE_COUNT: case zeek::TYPE_COUNTER: - return val_mgr->Count(val->val.int_val).release(); + return zeek::val_mgr->Count(val->val.int_val).release(); case zeek::TYPE_DOUBLE: - return new DoubleVal(val->val.double_val); + return new zeek::DoubleVal(val->val.double_val); case zeek::TYPE_TIME: - return new TimeVal(val->val.double_val); + return new zeek::TimeVal(val->val.double_val); case zeek::TYPE_INTERVAL: - return new IntervalVal(val->val.double_val); + return new zeek::IntervalVal(val->val.double_val); case zeek::TYPE_STRING: { - BroString *s = new BroString((const u_char*)val->val.string_val.data, val->val.string_val.length, true); - return new StringVal(s); + zeek::String *s = new zeek::String((const u_char*)val->val.string_val.data, val->val.string_val.length, true); + return new zeek::StringVal(s); } case zeek::TYPE_PORT: - return val_mgr->Port(val->val.port_val.port, val->val.port_val.proto)->Ref(); + return zeek::val_mgr->Port(val->val.port_val.port, val->val.port_val.proto)->Ref(); case zeek::TYPE_ADDR: { @@ -2218,7 +2218,7 @@ Val* Manager::ValueToVal(const Stream* i, const Value* val, zeek::Type* request_ assert(false); } - AddrVal* addrval = new AddrVal(*addr); + auto* addrval = new zeek::AddrVal(*addr); delete addr; return addrval; } @@ -2239,7 +2239,7 @@ Val* Manager::ValueToVal(const Stream* i, const Value* val, zeek::Type* request_ assert(false); } - SubNetVal* subnetval = new SubNetVal(*addr, val->val.subnet_val.length); + auto* subnetval = new zeek::SubNetVal(*addr, val->val.subnet_val.length); delete addr; return subnetval; } @@ -2248,22 +2248,22 @@ Val* Manager::ValueToVal(const Stream* i, const Value* val, zeek::Type* request_ { RE_Matcher* re = new RE_Matcher(val->val.pattern_text_val); re->Compile(); - return new PatternVal(re); + return new zeek::PatternVal(re); } case zeek::TYPE_TABLE: { // all entries have to have the same type... const auto& type = request_type->AsTableType()->GetIndices()->GetPureType(); - auto set_index = make_intrusive(type); + auto set_index = zeek::make_intrusive(type); set_index->Append(type); - auto s = make_intrusive(std::move(set_index), nullptr); - TableVal* t = new TableVal(std::move(s)); + auto s = zeek::make_intrusive(std::move(set_index), nullptr); + auto* t = new zeek::TableVal(std::move(s)); for ( int j = 0; j < val->val.set_val.size; j++ ) { - Val* assignval = ValueToVal(i, val->val.set_val.vals[j], type.get(), have_error); + zeek::Val* assignval = ValueToVal(i, val->val.set_val.vals[j], type.get(), have_error); - t->Assign({AdoptRef{}, assignval}, nullptr); + t->Assign({zeek::AdoptRef{}, assignval}, nullptr); } return t; @@ -2273,13 +2273,13 @@ Val* Manager::ValueToVal(const Stream* i, const Value* val, zeek::Type* request_ { // all entries have to have the same type... const auto& type = request_type->AsVectorType()->Yield(); - auto vt = make_intrusive(type); - auto v = make_intrusive(std::move(vt)); + auto vt = zeek::make_intrusive(type); + auto v = zeek::make_intrusive(std::move(vt)); for ( int j = 0; j < val->val.vector_val.size; j++ ) { auto el = ValueToVal(i, val->val.vector_val.vals[j], type.get(), have_error); - v->Assign(j, {AdoptRef{}, el}); + v->Assign(j, {zeek::AdoptRef{}, el}); } return v.release(); @@ -2435,7 +2435,7 @@ void Manager::ErrorHandler(const Stream* i, ErrorType et, bool reporter_send, co // send our script level error event if ( i->error_event ) { - IntrusivePtr ev; + zeek::EnumValPtr ev; switch (et) { case ErrorType::INFO: @@ -2455,7 +2455,7 @@ void Manager::ErrorHandler(const Stream* i, ErrorType et, bool reporter_send, co __builtin_unreachable(); } - StringVal* message = new StringVal(buf); + auto* message = new zeek::StringVal(buf); SendEvent(i->error_event, 3, i->description->Ref(), message, ev.release()); } diff --git a/src/input/Manager.h b/src/input/Manager.h index 8f5d7df3f6..55e47243c1 100644 --- a/src/input/Manager.h +++ b/src/input/Manager.h @@ -12,7 +12,7 @@ #include "threading/SerialTypes.h" #include "Tag.h" -class RecordVal; +ZEEK_FORWARD_DECLARE_NAMESPACED(RecordVal, zeek); namespace input { @@ -44,7 +44,7 @@ public: * This method corresponds directly to the internal BiF defined in * input.bif, which just forwards here. */ - bool CreateTableStream(RecordVal* description); + bool CreateTableStream(zeek::RecordVal* description); /** * Creates a new input stream which sends events for read input data. @@ -55,7 +55,7 @@ public: * This method corresponds directly to the internal BiF defined in * input.bif, which just forwards here. */ - bool CreateEventStream(RecordVal* description); + bool CreateEventStream(zeek::RecordVal* description); /** * Creates a new input stream which will forward the data from the data @@ -67,7 +67,7 @@ public: * @param description A record of the script type \c * Input::AnalysisDescription */ - bool CreateAnalysisStream(RecordVal* description); + bool CreateAnalysisStream(zeek::RecordVal* description); /** * Force update on a input stream. Forces a re-read of the whole @@ -143,7 +143,7 @@ protected: // Instantiates a new ReaderBackend of the given type (note that // doing so creates a new thread!). - ReaderBackend* CreateBackend(ReaderFrontend* frontend, EnumVal* tag); + ReaderBackend* CreateBackend(ReaderFrontend* frontend, zeek::EnumVal* tag); // Function called from the ReaderBackend to notify the manager that // a stream has been removed or a stream has been closed. Used to @@ -180,12 +180,12 @@ private: // protected definitions are wrappers around this function. bool RemoveStream(Stream* i); - bool CreateStream(Stream*, RecordVal* description); + bool CreateStream(Stream*, zeek::RecordVal* description); // Check if the types of the error_ev event are correct. If table is // true, check for tablestream type, otherwhise check for eventstream // type. - bool CheckErrorEventTypes(const std::string& stream_name, const Func* error_event, bool table) const; + bool CheckErrorEventTypes(const std::string& stream_name, const zeek::Func* error_event, bool table) const; // SendEntry implementation for Table stream. int SendEntryTable(Stream* i, const threading::Value* const *vals); @@ -194,7 +194,7 @@ private: int PutTable(Stream* i, const threading::Value* const *vals); // SendEntry and Put implementation for Event stream. - int SendEventStreamEvent(Stream* i, EnumVal* type, const threading::Value* const *vals); + int SendEventStreamEvent(Stream* i, zeek::EnumVal* type, const threading::Value* const *vals); // Check if a record is made up of compatible types and return a list // of all fields that are in the record in order. Recursively unrolls @@ -203,13 +203,13 @@ private: // Send events void SendEvent(EventHandlerPtr ev, const int numvals, ...) const; - void SendEvent(EventHandlerPtr ev, std::list events) const; + void SendEvent(EventHandlerPtr ev, std::list events) const; // Implementation of SendEndOfData (send end_of_data event). void SendEndOfData(const Stream *i); // Call predicate function and return result. - bool CallPred(Func* pred_func, const int numvals, ...) const; + bool CallPred(zeek::Func* pred_func, const int numvals, ...) const; // Get a hashkey for a set of threading::Values. HashKey* HashValues(const int num_elements, const threading::Value* const *vals) const; @@ -222,19 +222,19 @@ private: int CopyValue(char *data, const int startpos, const threading::Value* val) const; // Convert Threading::Value to an internal Bro Type (works with Records). - Val* ValueToVal(const Stream* i, const threading::Value* val, zeek::Type* request_type, bool& have_error) const; + zeek::Val* ValueToVal(const Stream* i, const threading::Value* val, zeek::Type* request_type, bool& have_error) const; // Convert Threading::Value to an internal Bro list type. - Val* ValueToIndexVal(const Stream* i, int num_fields, const zeek::RecordType* type, const threading::Value* const *vals, bool& have_error) const; + zeek::Val* ValueToIndexVal(const Stream* i, int num_fields, const zeek::RecordType* type, const threading::Value* const *vals, bool& have_error) const; // Converts a threading::value to a record type. Mostly used by // ValueToVal. - RecordVal* ValueToRecordVal(const Stream* i, const threading::Value* const *vals, zeek::RecordType *request_type, int* position, bool& have_error) const; + zeek::RecordVal* ValueToRecordVal(const Stream* i, const threading::Value* const *vals, zeek::RecordType *request_type, int* position, bool& have_error) const; - Val* RecordValToIndexVal(RecordVal *r) const; + zeek::Val* RecordValToIndexVal(zeek::RecordVal *r) const; // Converts a Bro ListVal to a RecordVal given the record type. - RecordVal* ListValToRecordVal(ListVal* list, zeek::RecordType *request_type, int* position) const; + zeek::RecordVal* ListValToRecordVal(zeek::ListVal* list, zeek::RecordType *request_type, int* position) const; // Internally signal errors, warnings, etc. // These are sent on to input scriptland and reporter.log diff --git a/src/input/ReaderBackend.h b/src/input/ReaderBackend.h index 2748d1e2d2..f6ad3995ba 100644 --- a/src/input/ReaderBackend.h +++ b/src/input/ReaderBackend.h @@ -2,7 +2,7 @@ #pragma once -#include "BroString.h" +#include "ZeekString.h" #include "threading/SerialTypes.h" #include "threading/MsgThread.h" diff --git a/src/input/ReaderFrontend.cc b/src/input/ReaderFrontend.cc index e634570d85..17d3f6ff49 100644 --- a/src/input/ReaderFrontend.cc +++ b/src/input/ReaderFrontend.cc @@ -34,7 +34,7 @@ public: bool Process() override { return Object()->Update(); } }; -ReaderFrontend::ReaderFrontend(const ReaderBackend::ReaderInfo& arg_info, EnumVal* type) +ReaderFrontend::ReaderFrontend(const ReaderBackend::ReaderInfo& arg_info, zeek::EnumVal* type) { disabled = initialized = false; info = new ReaderBackend::ReaderInfo(arg_info); diff --git a/src/input/ReaderFrontend.h b/src/input/ReaderFrontend.h index 9a30995ada..9a6392adbe 100644 --- a/src/input/ReaderFrontend.h +++ b/src/input/ReaderFrontend.h @@ -5,7 +5,7 @@ #include "ReaderBackend.h" #include "threading/SerialTypes.h" -class EnumVal; +ZEEK_FORWARD_DECLARE_NAMESPACED(EnumVal, zeek); namespace input { @@ -33,7 +33,7 @@ public: * * Frontends must only be instantiated by the main thread. */ - ReaderFrontend(const ReaderBackend::ReaderInfo& info, EnumVal* type); + ReaderFrontend(const ReaderBackend::ReaderInfo& info, zeek::EnumVal* type); /** * Destructor. diff --git a/src/input/Tag.cc b/src/input/Tag.cc index cbdcd59aae..86c481d843 100644 --- a/src/input/Tag.cc +++ b/src/input/Tag.cc @@ -16,20 +16,20 @@ input::Tag& input::Tag::operator=(const input::Tag& other) return *this; } -const IntrusivePtr& input::Tag::AsVal() const +const zeek::EnumValPtr& input::Tag::AsVal() const { return ::Tag::AsVal(input_mgr->GetTagType()); } -EnumVal* input::Tag::AsEnumVal() const +zeek::EnumVal* input::Tag::AsEnumVal() const { return AsVal().get(); } -input::Tag::Tag(IntrusivePtr val) +input::Tag::Tag(zeek::EnumValPtr val) : ::Tag(std::move(val)) { } -input::Tag::Tag(EnumVal* val) - : ::Tag({NewRef{}, val}) +input::Tag::Tag(zeek::EnumVal* val) + : ::Tag({zeek::NewRef{}, val}) { } diff --git a/src/input/Tag.h b/src/input/Tag.h index b4aa4b11f7..534314fbc0 100644 --- a/src/input/Tag.h +++ b/src/input/Tag.h @@ -5,7 +5,7 @@ #include "zeek-config.h" #include "../Tag.h" -class EnumVal; +ZEEK_FORWARD_DECLARE_NAMESPACED(EnumVal, zeek); namespace zeek::plugin { template class TaggedComponent; @@ -89,10 +89,10 @@ public: * * @param etype the script-layer enum type associated with the tag. */ - const IntrusivePtr& AsVal() const; + const zeek::EnumValPtr& AsVal() const; [[deprecated("Remove in v4.1. Use AsVal() instead.")]] - EnumVal* AsEnumVal() const; + zeek::EnumVal* AsEnumVal() const; static const Tag Error; @@ -117,10 +117,10 @@ protected: * * @param val An enum value of script type \c Input::Reader. */ - explicit Tag(IntrusivePtr val); + explicit Tag(zeek::EnumValPtr val); [[deprecated("Remove in v4.1. Construct from IntrusivePtr isntead.")]] - explicit Tag(EnumVal* val); + explicit Tag(zeek::EnumVal* val); }; } diff --git a/src/input/input.bif b/src/input/input.bif index a90564acdc..bcb2d06558 100644 --- a/src/input/input.bif +++ b/src/input/input.bif @@ -19,34 +19,33 @@ type AnalysisDescription: record; function Input::__create_table_stream%(description: Input::TableDescription%) : bool %{ bool res = input_mgr->CreateTableStream(description->AsRecordVal()); - return val_mgr->Bool(res); + return zeek::val_mgr->Bool(res); %} function Input::__create_event_stream%(description: Input::EventDescription%) : bool %{ bool res = input_mgr->CreateEventStream(description->AsRecordVal()); - return val_mgr->Bool(res); + return zeek::val_mgr->Bool(res); %} function Input::__create_analysis_stream%(description: Input::AnalysisDescription%) : bool %{ bool res = input_mgr->CreateAnalysisStream(description->AsRecordVal()); - return val_mgr->Bool(res); + return zeek::val_mgr->Bool(res); %} function Input::__remove_stream%(id: string%) : bool %{ bool res = input_mgr->RemoveStream(id->AsString()->CheckString()); - return val_mgr->Bool(res); + return zeek::val_mgr->Bool(res); %} function Input::__force_update%(id: string%) : bool %{ bool res = input_mgr->ForceUpdate(id->AsString()->CheckString()); - return val_mgr->Bool(res); + return zeek::val_mgr->Bool(res); %} # Options for the input framework const accept_unsupported_types: bool; - diff --git a/src/input/readers/config/Config.cc b/src/input/readers/config/Config.cc index 56d93fcfb0..ec5c731b2b 100644 --- a/src/input/readers/config/Config.cc +++ b/src/input/readers/config/Config.cc @@ -27,7 +27,7 @@ Config::Config(ReaderFrontend *frontend) : ReaderBackend(frontend) fail_on_file_problem = false; // find all option names and their types. - const auto& globals = global_scope()->Vars(); + const auto& globals = zeek::detail::global_scope()->Vars(); for ( const auto& entry : globals ) { diff --git a/src/iosource/Packet.cc b/src/iosource/Packet.cc index 1843868f10..b0284414f4 100644 --- a/src/iosource/Packet.cc +++ b/src/iosource/Packet.cc @@ -2,7 +2,6 @@ #include "Sessions.h" #include "Desc.h" #include "IP.h" -#include "IntrusivePtr.h" #include "iosource/Manager.h" #include "Var.h" @@ -592,12 +591,12 @@ void Packet::ProcessLayer2() hdr_size = (pdata - data); } -IntrusivePtr Packet::ToRawPktHdrVal() const +zeek::RecordValPtr Packet::ToRawPktHdrVal() const { static auto raw_pkt_hdr_type = zeek::id::find_type("raw_pkt_hdr"); static auto l2_hdr_type = zeek::id::find_type("l2_hdr"); - auto pkt_hdr = make_intrusive(raw_pkt_hdr_type); - auto l2_hdr = make_intrusive(l2_hdr_type); + auto pkt_hdr = zeek::make_intrusive(raw_pkt_hdr_type); + auto l2_hdr = zeek::make_intrusive(l2_hdr_type); bool is_ethernet = link_type == DLT_EN10MB; @@ -632,12 +631,12 @@ IntrusivePtr Packet::ToRawPktHdrVal() const l2_hdr->Assign(4, FmtEUI48(data)); // dst if ( vlan ) - l2_hdr->Assign(5, val_mgr->Count(vlan)); + l2_hdr->Assign(5, zeek::val_mgr->Count(vlan)); if ( inner_vlan ) - l2_hdr->Assign(6, val_mgr->Count(inner_vlan)); + l2_hdr->Assign(6, zeek::val_mgr->Count(inner_vlan)); - l2_hdr->Assign(7, val_mgr->Count(eth_type)); + l2_hdr->Assign(7, zeek::val_mgr->Count(eth_type)); if ( eth_type == ETHERTYPE_ARP || eth_type == ETHERTYPE_REVARP ) // We also identify ARP for L3 over ethernet @@ -646,8 +645,8 @@ IntrusivePtr Packet::ToRawPktHdrVal() const else l2_hdr->Assign(0, zeek::BifType::Enum::link_encap->GetVal(BifEnum::LINK_UNKNOWN)); - l2_hdr->Assign(1, val_mgr->Count(len)); - l2_hdr->Assign(2, val_mgr->Count(cap_len)); + l2_hdr->Assign(1, zeek::val_mgr->Count(len)); + l2_hdr->Assign(2, zeek::val_mgr->Count(cap_len)); l2_hdr->Assign(8, zeek::BifType::Enum::layer3_proto->GetVal(l3)); @@ -669,17 +668,17 @@ IntrusivePtr Packet::ToRawPktHdrVal() const return pkt_hdr; } -RecordVal* Packet::BuildPktHdrVal() const +zeek::RecordVal* Packet::BuildPktHdrVal() const { return ToRawPktHdrVal().release(); } -IntrusivePtr Packet::FmtEUI48(const u_char* mac) const +zeek::ValPtr Packet::FmtEUI48(const u_char* mac) const { char buf[20]; snprintf(buf, sizeof buf, "%02x:%02x:%02x:%02x:%02x:%02x", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); - return make_intrusive(buf); + return zeek::make_intrusive(buf); } void Packet::Describe(ODesc* d) const diff --git a/src/iosource/Packet.h b/src/iosource/Packet.h index 83b0fddb59..5d2e927d99 100644 --- a/src/iosource/Packet.h +++ b/src/iosource/Packet.h @@ -1,5 +1,7 @@ #pragma once +#include "zeek-config.h" + #include #include @@ -12,11 +14,17 @@ typedef struct bpf_timeval pkt_timeval; typedef struct timeval pkt_timeval; #endif -class Val; +ZEEK_FORWARD_DECLARE_NAMESPACED(Val, zeek); +ZEEK_FORWARD_DECLARE_NAMESPACED(RecordVal, zeek); + +namespace zeek { +template class IntrusivePtr; +using ValPtr = zeek::IntrusivePtr; +using RecordValPtr = zeek::IntrusivePtr; +} + class ODesc; class IP_Hdr; -class RecordVal; -template class IntrusivePtr; /** * The Layer 3 type of a packet, as determined by the parsing code in Packet. @@ -128,10 +136,10 @@ public: * Returns a \c raw_pkt_hdr RecordVal, which includes layer 2 and * also everything in IP_Hdr (i.e., IP4/6 + TCP/UDP/ICMP). */ - IntrusivePtr ToRawPktHdrVal() const; + zeek::RecordValPtr ToRawPktHdrVal() const; [[deprecated("Remove in v4.1. Use ToRawPktHdrval() instead.")]] - RecordVal* BuildPktHdrVal() const; + zeek::RecordVal* BuildPktHdrVal() const; /** * Static method returning the link-layer header size for a given @@ -225,7 +233,7 @@ private: void Weird(const char* name); // Renders an MAC address into its ASCII representation. - IntrusivePtr FmtEUI48(const u_char* mac) const; + zeek::ValPtr FmtEUI48(const u_char* mac) const; // True if we need to delete associated packet memory upon // destruction. diff --git a/src/iosource/pcap/Source.cc b/src/iosource/pcap/Source.cc index 897cea0f25..a35e65b83a 100644 --- a/src/iosource/pcap/Source.cc +++ b/src/iosource/pcap/Source.cc @@ -47,7 +47,7 @@ void PcapSource::Close() Closed(); if ( Pcap::file_done ) - mgr.Enqueue(Pcap::file_done, make_intrusive(props.path)); + mgr.Enqueue(Pcap::file_done, zeek::make_intrusive(props.path)); } void PcapSource::OpenLive() diff --git a/src/iosource/pcap/pcap.bif b/src/iosource/pcap/pcap.bif index fd4dbd60fe..5fe6b92233 100644 --- a/src/iosource/pcap/pcap.bif +++ b/src/iosource/pcap/pcap.bif @@ -33,8 +33,8 @@ function precompile_pcap_filter%(id: PcapFilterID, s: string%): bool // We use a vector as underlying data structure for fast // lookups and limit the ID space so that that doesn't grow too // large. - builtin_error(fmt("PCAP filter ids must remain below 100 (is %" PRId64 ")", id->AsInt())); - return val_mgr->False(); + zeek::emit_builtin_error(fmt("PCAP filter ids must remain below 100 (is %" PRId64 ")", id->AsInt())); + return zeek::val_mgr->False(); } bool success = true; @@ -43,7 +43,7 @@ function precompile_pcap_filter%(id: PcapFilterID, s: string%): bool if ( ps && ! ps->PrecompileFilter(id->ForceAsInt(), s->CheckString()) ) success = false; - return val_mgr->Bool(success); + return zeek::val_mgr->Bool(success); %} ## Installs a PCAP filter that has been precompiled with @@ -72,7 +72,7 @@ function Pcap::install_pcap_filter%(id: PcapFilterID%): bool if ( ps && ! ps->SetFilter(id->ForceAsInt()) ) success = false; - return val_mgr->Bool(success); + return zeek::val_mgr->Bool(success); %} ## Returns a string representation of the last PCAP error. @@ -96,8 +96,8 @@ function error%(%): string { const char* err = ps->ErrorMsg(); if ( *err ) - return make_intrusive(err); + return zeek::make_intrusive(err); } - return make_intrusive("no error"); + return zeek::make_intrusive("no error"); %} diff --git a/src/logging/Manager.cc b/src/logging/Manager.cc index cff56c63d0..98e3bb6ff6 100644 --- a/src/logging/Manager.cc +++ b/src/logging/Manager.cc @@ -31,24 +31,24 @@ using namespace std; using namespace logging; struct Manager::Filter { - Val* fval; + zeek::Val* fval; string name; - EnumVal* id; - Func* pred; - Func* path_func; + zeek::EnumVal* id; + zeek::Func* pred; + zeek::Func* path_func; string path; - Val* path_val; - EnumVal* writer; - TableVal* config; - TableVal* field_name_map; + zeek::Val* path_val; + zeek::EnumVal* writer; + zeek::TableVal* config; + zeek::TableVal* field_name_map; string scope_sep; string ext_prefix; - Func* ext_func; + zeek::Func* ext_func; int num_ext_fields; bool local; bool remote; double interval; - Func* postprocessor; + zeek::Func* postprocessor; int num_fields; threading::Field** fields; @@ -62,11 +62,11 @@ struct Manager::Filter { }; struct Manager::WriterInfo { - EnumVal* type; + zeek::EnumVal* type; double open_time; Timer* rotation_timer; double interval; - Func* postprocessor; + zeek::Func* postprocessor; WriterFrontend* writer; WriterBackend::WriterInfo* info; bool from_remote; @@ -75,7 +75,7 @@ struct Manager::WriterInfo { }; struct Manager::Stream { - EnumVal* id; + zeek::EnumVal* id; bool enabled; string name; zeek::RecordType* columns; @@ -142,7 +142,7 @@ Manager::~Manager() delete *s; } -WriterBackend* Manager::CreateBackend(WriterFrontend* frontend, EnumVal* tag) +WriterBackend* Manager::CreateBackend(WriterFrontend* frontend, zeek::EnumVal* tag) { Component* c = Lookup(tag); @@ -158,7 +158,7 @@ WriterBackend* Manager::CreateBackend(WriterFrontend* frontend, EnumVal* tag) return backend; } -Manager::Stream* Manager::FindStream(EnumVal* id) +Manager::Stream* Manager::FindStream(zeek::EnumVal* id) { unsigned int idx = id->AsEnum(); @@ -228,7 +228,7 @@ void Manager::RemoveDisabledWriters(Stream* stream) stream->writers.erase(*j); } -bool Manager::CreateStream(EnumVal* id, RecordVal* sval) +bool Manager::CreateStream(zeek::EnumVal* id, zeek::RecordVal* sval) { if ( ! same_type(sval->GetType(), zeek::BifType::Record::Log::Stream, false) ) { @@ -264,7 +264,7 @@ bool Manager::CreateStream(EnumVal* id, RecordVal* sval) } const auto& event_val = sval->GetField("ev"); - Func* event = event_val ? event_val->AsFunc() : nullptr; + zeek::Func* event = event_val ? event_val->AsFunc() : nullptr; if ( event ) { @@ -320,7 +320,7 @@ bool Manager::CreateStream(EnumVal* id, RecordVal* sval) return true; } -bool Manager::RemoveStream(EnumVal* id) +bool Manager::RemoveStream(zeek::EnumVal* id) { unsigned int idx = id->AsEnum(); @@ -353,7 +353,7 @@ bool Manager::RemoveStream(EnumVal* id) return true; } -bool Manager::EnableStream(EnumVal* id) +bool Manager::EnableStream(zeek::EnumVal* id) { Stream* stream = FindStream(id); @@ -369,7 +369,7 @@ bool Manager::EnableStream(EnumVal* id) return true; } -bool Manager::DisableStream(EnumVal* id) +bool Manager::DisableStream(zeek::EnumVal* id) { Stream* stream = FindStream(id); @@ -387,7 +387,8 @@ bool Manager::DisableStream(EnumVal* id) // Helper for recursive record field unrolling. bool Manager::TraverseRecord(Stream* stream, Filter* filter, zeek::RecordType* rt, - TableVal* include, TableVal* exclude, const string& path, const list& indices) + zeek::TableVal* include, zeek::TableVal* exclude, + const string& path, const list& indices) { // Only include extensions for the outer record. int num_ext_fields = (indices.size() == 0) ? filter->num_ext_fields : 0; @@ -476,7 +477,7 @@ bool Manager::TraverseRecord(Stream* stream, Filter* filter, zeek::RecordType* r // If include fields are specified, only include if explicitly listed. if ( include ) { - auto new_path_val = make_intrusive(new_path.c_str()); + auto new_path_val = zeek::make_intrusive(new_path.c_str()); bool result = (bool)include->FindOrDefault(new_path_val); if ( ! result ) @@ -486,7 +487,7 @@ bool Manager::TraverseRecord(Stream* stream, Filter* filter, zeek::RecordType* r // If exclude fields are specified, do not only include if listed. if ( exclude ) { - auto new_path_val = make_intrusive(new_path.c_str()); + auto new_path_val = zeek::make_intrusive(new_path.c_str()); bool result = (bool)exclude->FindOrDefault(new_path_val); if ( result ) @@ -525,7 +526,7 @@ bool Manager::TraverseRecord(Stream* stream, Filter* filter, zeek::RecordType* r return true; } -bool Manager::AddFilter(EnumVal* id, RecordVal* fval) +bool Manager::AddFilter(zeek::EnumVal* id, zeek::RecordVal* fval) { if ( ! same_type(fval->GetType(), zeek::BifType::Record::Log::Filter, false) ) { @@ -538,7 +539,7 @@ bool Manager::AddFilter(EnumVal* id, RecordVal* fval) return false; // Find the right writer type. - auto writer = fval->GetFieldOrDefault("writer"); + auto writer = fval->GetFieldOrDefault("writer"); // Create a new Filter instance. @@ -654,12 +655,12 @@ bool Manager::AddFilter(EnumVal* id, RecordVal* fval) return true; } -bool Manager::RemoveFilter(EnumVal* id, StringVal* name) +bool Manager::RemoveFilter(zeek::EnumVal* id, zeek::StringVal* name) { return RemoveFilter(id, name->AsString()->CheckString()); } -bool Manager::RemoveFilter(EnumVal* id, const string& name) +bool Manager::RemoveFilter(zeek::EnumVal* id, const string& name) { Stream* stream = FindStream(id); if ( ! stream ) @@ -686,7 +687,7 @@ bool Manager::RemoveFilter(EnumVal* id, const string& name) return true; } -bool Manager::Write(EnumVal* id, RecordVal* columns_arg) +bool Manager::Write(zeek::EnumVal* id, zeek::RecordVal* columns_arg) { Stream* stream = FindStream(id); if ( ! stream ) @@ -695,7 +696,7 @@ bool Manager::Write(EnumVal* id, RecordVal* columns_arg) if ( ! stream->enabled ) return true; - auto columns = columns_arg->CoerceTo({NewRef{}, stream->columns}); + auto columns = columns_arg->CoerceTo({zeek::NewRef{}, stream->columns}); if ( ! columns ) { @@ -730,23 +731,23 @@ bool Manager::Write(EnumVal* id, RecordVal* columns_arg) if ( filter->path_func ) { - IntrusivePtr path_arg; + zeek::ValPtr path_arg; if ( filter->path_val ) - path_arg = {NewRef{}, filter->path_val}; + path_arg = {zeek::NewRef{}, filter->path_val}; else - path_arg = val_mgr->EmptyString(); + path_arg = zeek::val_mgr->EmptyString(); - IntrusivePtr rec_arg; + zeek::ValPtr rec_arg; const auto& rt = filter->path_func->GetType()->Params()->GetFieldType("rec"); if ( rt->Tag() == zeek::TYPE_RECORD ) - rec_arg = columns->CoerceTo(cast_intrusive(rt), true); + rec_arg = columns->CoerceTo(zeek::cast_intrusive(rt), true); else // Can be TYPE_ANY here. rec_arg = columns; - auto v = filter->path_func->Invoke(IntrusivePtr{NewRef{}, id}, + auto v = filter->path_func->Invoke(zeek::IntrusivePtr{zeek::NewRef{}, id}, std::move(path_arg), std::move(rec_arg)); @@ -796,7 +797,7 @@ bool Manager::Write(EnumVal* id, RecordVal* columns_arg) CheckFilterWriterConflict(w->second, filter) ); Unref(filter->path_val); - filter->path_val = new StringVal(new_path.c_str()); + filter->path_val = new zeek::StringVal(new_path.c_str()); reporter->Warning("Write using filter '%s' on path '%s' changed to" " use new path '%s' to avoid conflict with filter '%s'", @@ -842,7 +843,7 @@ bool Manager::Write(EnumVal* id, RecordVal* columns_arg) if ( filter->field_name_map ) { const char* name = filter->fields[j]->name; - auto fn = make_intrusive(name); + auto fn = zeek::make_intrusive(name); if ( const auto& val = filter->field_name_map->Find(fn) ) { @@ -858,9 +859,9 @@ bool Manager::Write(EnumVal* id, RecordVal* columns_arg) info->network_time = network_time; HashKey* k; - IterCookie* c = filter->config->AsTable()->InitForIteration(); + zeek::IterCookie* c = filter->config->AsTable()->InitForIteration(); - TableEntryVal* v; + zeek::TableEntryVal* v; while ( (v = filter->config->AsTable()->NextEntry(k, c)) ) { auto index = filter->config->RecreateIndex(*k); @@ -913,7 +914,7 @@ bool Manager::Write(EnumVal* id, RecordVal* columns_arg) return true; } -threading::Value* Manager::ValToLogVal(Val* val, zeek::Type* ty) +threading::Value* Manager::ValToLogVal(zeek::Val* val, zeek::Type* ty) { if ( ! ty ) ty = val->GetType().get(); @@ -975,7 +976,7 @@ threading::Value* Manager::ValToLogVal(Val* val, zeek::Type* ty) case zeek::TYPE_STRING: { - const BroString* s = val->AsString(); + const zeek::String* s = val->AsString(); char* buf = new char[s->Len()]; memcpy(buf, s->Bytes(), s->Len()); @@ -996,7 +997,7 @@ threading::Value* Manager::ValToLogVal(Val* val, zeek::Type* ty) case zeek::TYPE_FUNC: { ODesc d; - const Func* f = val->AsFunc(); + const zeek::Func* f = val->AsFunc(); f->Describe(&d); const char* s = d.Description(); lval->val.string_val.data = copy_string(s); @@ -1010,7 +1011,7 @@ threading::Value* Manager::ValToLogVal(Val* val, zeek::Type* ty) if ( ! set ) // ToPureListVal has reported an internal warning // already. Just keep going by making something up. - set = make_intrusive(zeek::TYPE_INT); + set = zeek::make_intrusive(zeek::TYPE_INT); lval->val.set_val.size = set->Length(); lval->val.set_val.vals = new threading::Value* [lval->val.set_val.size]; @@ -1023,7 +1024,7 @@ threading::Value* Manager::ValToLogVal(Val* val, zeek::Type* ty) case zeek::TYPE_VECTOR: { - VectorVal* vec = val->AsVectorVal(); + zeek::VectorVal* vec = val->AsVectorVal(); lval->val.vector_val.size = vec->Size(); lval->val.vector_val.vals = new threading::Value* [lval->val.vector_val.size]; @@ -1046,23 +1047,23 @@ threading::Value* Manager::ValToLogVal(Val* val, zeek::Type* ty) } threading::Value** Manager::RecordToFilterVals(Stream* stream, Filter* filter, - RecordVal* columns) + zeek::RecordVal* columns) { - IntrusivePtr ext_rec; + zeek::RecordValPtr ext_rec; if ( filter->num_ext_fields > 0 ) { - auto res = filter->ext_func->Invoke(IntrusivePtr{NewRef{}, filter->path_val}); + auto res = filter->ext_func->Invoke(zeek::IntrusivePtr{zeek::NewRef{}, filter->path_val}); if ( res ) - ext_rec = {AdoptRef{}, res.release()->AsRecordVal()}; + ext_rec = {zeek::AdoptRef{}, res.release()->AsRecordVal()}; } threading::Value** vals = new threading::Value*[filter->num_fields]; for ( int i = 0; i < filter->num_fields; ++i ) { - Val* val; + zeek::Val* val; if ( i < filter->num_ext_fields ) { if ( ! ext_rec ) @@ -1100,7 +1101,7 @@ threading::Value** Manager::RecordToFilterVals(Stream* stream, Filter* filter, return vals; } -bool Manager::CreateWriterForRemoteLog(EnumVal* id, EnumVal* writer, WriterBackend::WriterInfo* info, +bool Manager::CreateWriterForRemoteLog(zeek::EnumVal* id, zeek::EnumVal* writer, WriterBackend::WriterInfo* info, int num_fields, const threading::Field* const* fields) { return CreateWriter(id, writer, info, num_fields, fields, true, false, true); @@ -1115,9 +1116,9 @@ static void delete_info_and_fields(WriterBackend::WriterInfo* info, int num_fiel delete info; } -WriterFrontend* Manager::CreateWriter(EnumVal* id, EnumVal* writer, WriterBackend::WriterInfo* info, - int num_fields, const threading::Field* const* fields, bool local, bool remote, bool from_remote, - const string& instantiating_filter) +WriterFrontend* Manager::CreateWriter(zeek::EnumVal* id, zeek::EnumVal* writer, WriterBackend::WriterInfo* info, + int num_fields, const threading::Field* const* fields, bool local, + bool remote, bool from_remote, const string& instantiating_filter) { WriterFrontend* result = nullptr; @@ -1176,7 +1177,7 @@ WriterFrontend* Manager::CreateWriter(EnumVal* id, EnumVal* writer, WriterBacken if ( ! found_filter_match ) { - const auto& id = global_scope()->Find("Log::default_rotation_interval"); + const auto& id = zeek::detail::global_scope()->Find("Log::default_rotation_interval"); assert(id); winfo->interval = id->GetVal()->AsInterval(); } @@ -1187,7 +1188,7 @@ WriterFrontend* Manager::CreateWriter(EnumVal* id, EnumVal* writer, WriterBacken // Still need to set the WriterInfo's rotation parameters, which we // computed above. - static auto log_rotate_base_time = zeek::id::find_val("log_rotate_base_time"); + static auto log_rotate_base_time = zeek::id::find_val("log_rotate_base_time"); static auto base_time = log_rotate_base_time->AsString()->CheckString(); winfo->info->rotation_interval = winfo->interval; @@ -1219,8 +1220,8 @@ void Manager::DeleteVals(int num_fields, threading::Value** vals) delete [] vals; } -bool Manager::WriteFromRemote(EnumVal* id, EnumVal* writer, const string& path, int num_fields, - threading::Value** vals) +bool Manager::WriteFromRemote(zeek::EnumVal* id, zeek::EnumVal* writer, const string& path, int num_fields, + threading::Value** vals) { Stream* stream = FindStream(id); @@ -1295,7 +1296,7 @@ void Manager::SendAllWritersTo(const broker::endpoint_info& ei) } } -bool Manager::SetBuf(EnumVal* id, bool enabled) +bool Manager::SetBuf(zeek::EnumVal* id, bool enabled) { Stream* stream = FindStream(id); if ( ! stream ) @@ -1310,7 +1311,7 @@ bool Manager::SetBuf(EnumVal* id, bool enabled) return true; } -bool Manager::Flush(EnumVal* id) +bool Manager::Flush(zeek::EnumVal* id) { Stream* stream = FindStream(id); if ( ! stream ) @@ -1341,7 +1342,7 @@ void Manager::Terminate() } } -bool Manager::EnableRemoteLogs(EnumVal* stream_id) +bool Manager::EnableRemoteLogs(zeek::EnumVal* stream_id) { auto stream = FindStream(stream_id); @@ -1352,7 +1353,7 @@ bool Manager::EnableRemoteLogs(EnumVal* stream_id) return true; } -bool Manager::DisableRemoteLogs(EnumVal* stream_id) +bool Manager::DisableRemoteLogs(zeek::EnumVal* stream_id) { auto stream = FindStream(stream_id); @@ -1363,7 +1364,7 @@ bool Manager::DisableRemoteLogs(EnumVal* stream_id) return true; } -bool Manager::RemoteLogsAreEnabled(EnumVal* stream_id) +bool Manager::RemoteLogsAreEnabled(zeek::EnumVal* stream_id) { auto stream = FindStream(stream_id); @@ -1373,7 +1374,7 @@ bool Manager::RemoteLogsAreEnabled(EnumVal* stream_id) return stream->enable_remote; } -zeek::RecordType* Manager::StreamColumns(EnumVal* stream_id) +zeek::RecordType* Manager::StreamColumns(zeek::EnumVal* stream_id) { auto stream = FindStream(stream_id); @@ -1447,7 +1448,7 @@ void Manager::InstallRotationTimer(WriterInfo* winfo) if ( ! winfo->open_time ) winfo->open_time = network_time; - static auto log_rotate_base_time = zeek::id::find_val("log_rotate_base_time"); + static auto log_rotate_base_time = zeek::id::find_val("log_rotate_base_time"); static auto base_time = log_rotate_base_time->AsString()->CheckString(); double base = parse_rotate_base_time(base_time); @@ -1508,18 +1509,18 @@ bool Manager::FinishedRotation(WriterFrontend* writer, const char* new_name, con return true; // Create the RotationInfo record. - auto info = make_intrusive(zeek::BifType::Record::Log::RotationInfo); - info->Assign(0, {NewRef{}, winfo->type}); - info->Assign(1, make_intrusive(new_name)); - info->Assign(2, make_intrusive(winfo->writer->Info().path)); - info->Assign(3, make_intrusive(open)); - info->Assign(4, make_intrusive(close)); - info->Assign(5, val_mgr->Bool(terminating)); + auto info = zeek::make_intrusive(zeek::BifType::Record::Log::RotationInfo); + info->Assign(0, {zeek::NewRef{}, winfo->type}); + info->Assign(1, zeek::make_intrusive(new_name)); + info->Assign(2, zeek::make_intrusive(winfo->writer->Info().path)); + info->Assign(3, zeek::make_intrusive(open)); + info->Assign(4, zeek::make_intrusive(close)); + info->Assign(5, zeek::val_mgr->Bool(terminating)); - Func* func = winfo->postprocessor; + zeek::Func* func = winfo->postprocessor; if ( ! func ) { - const auto& id = global_scope()->Find("Log::__default_rotation_postprocessor"); + const auto& id = zeek::detail::global_scope()->Find("Log::__default_rotation_postprocessor"); assert(id); func = id->GetVal()->AsFunc(); } diff --git a/src/logging/Manager.h b/src/logging/Manager.h index 23a61f9d69..620680938d 100644 --- a/src/logging/Manager.h +++ b/src/logging/Manager.h @@ -46,7 +46,7 @@ public: * This method corresponds directly to the internal BiF defined in * logging.bif, which just forwards here. */ - bool CreateStream(EnumVal* id, RecordVal* stream); + bool CreateStream(zeek::EnumVal* id, zeek::RecordVal* stream); /** * Remove a log stream, stopping all threads. @@ -56,7 +56,7 @@ public: * This methods corresponds directly to the internal BiF defined in * logging.bif, which just forwards here. */ - bool RemoveStream(EnumVal* id); + bool RemoveStream(zeek::EnumVal* id); /** * Enables a log log stream. @@ -66,7 +66,7 @@ public: * This method corresponds directly to the internal BiF defined in * logging.bif, which just forwards here. */ - bool EnableStream(EnumVal* id); + bool EnableStream(zeek::EnumVal* id); /** * Disables a log stream. @@ -76,7 +76,7 @@ public: * This methods corresponds directly to the internal BiF defined in * logging.bif, which just forwards here. */ - bool DisableStream(EnumVal* id); + bool DisableStream(zeek::EnumVal* id); /** * Adds a filter to a log stream. @@ -88,7 +88,7 @@ public: * This methods corresponds directly to the internal BiF defined in * logging.bif, which just forwards here. */ - bool AddFilter(EnumVal* id, RecordVal* filter); + bool AddFilter(zeek::EnumVal* id, zeek::RecordVal* filter); /** * Removes a filter from a log stream. @@ -100,7 +100,7 @@ public: * This methods corresponds directly to the internal BiF defined in * logging.bif, which just forwards here. */ - bool RemoveFilter(EnumVal* id, StringVal* name); + bool RemoveFilter(zeek::EnumVal* id, zeek::StringVal* name); /** * Removes a filter from a log stream. @@ -112,7 +112,7 @@ public: * This methods corresponds directly to the internal BiF defined in * logging.bif, which just forwards here. */ - bool RemoveFilter(EnumVal* id, const std::string& name); + bool RemoveFilter(zeek::EnumVal* id, const std::string& name); /** * Write a record to a log stream. @@ -125,7 +125,7 @@ public: * This methods corresponds directly to the internal BiF defined in * logging.bif, which just forwards here. */ - bool Write(EnumVal* id, RecordVal* columns); + bool Write(zeek::EnumVal* id, zeek::RecordVal* columns); /** * Create a new log writer frontend. This is exposed so that the @@ -146,8 +146,8 @@ public: * * @return Returns true if the writer was successfully created. */ - bool CreateWriterForRemoteLog(EnumVal* id, EnumVal* writer, WriterBackend::WriterInfo* info, - int num_fields, const threading::Field* const* fields); + bool CreateWriterForRemoteLog(zeek::EnumVal* id, zeek::EnumVal* writer, WriterBackend::WriterInfo* info, + int num_fields, const threading::Field* const* fields); /** * Writes out log entries that have already passed through all @@ -165,8 +165,8 @@ public: * @param vals An array of log values to write, of size num_fields. * The method takes ownership of the array. */ - bool WriteFromRemote(EnumVal* stream, EnumVal* writer, const std::string& path, - int num_fields, threading::Value** vals); + bool WriteFromRemote(zeek::EnumVal* stream, zeek::EnumVal* writer, const std::string& path, + int num_fields, threading::Value** vals); /** * Announces all instantiated writers to a given Broker peer. @@ -184,7 +184,7 @@ public: * This methods corresponds directly to the internal BiF defined in * logging.bif, which just forwards here. */ - bool SetBuf(EnumVal* id, bool enabled); + bool SetBuf(zeek::EnumVal* id, bool enabled); /** * Flushes a log stream. This flushed all associated writers. @@ -194,7 +194,7 @@ public: * This methods corresponds directly to the internal BiF defined in * logging.bif, which just forwards here. */ - bool Flush(EnumVal* id); + bool Flush(zeek::EnumVal* id); /** * Signals the manager to shutdown at Bro's termination. @@ -206,25 +206,25 @@ public: * @param stream_id the stream to enable remote logs for. * @return true if remote logs are enabled. */ - bool EnableRemoteLogs(EnumVal* stream_id); + bool EnableRemoteLogs(zeek::EnumVal* stream_id); /** * Disable remote logs for a given stream. * @param stream_id the stream to disable remote logs for. * @return true if remote logs are disabled. */ - bool DisableRemoteLogs(EnumVal* stream_id); + bool DisableRemoteLogs(zeek::EnumVal* stream_id); /** * @return true if remote logs are enabled for a given stream. */ - bool RemoteLogsAreEnabled(EnumVal* stream_id); + bool RemoteLogsAreEnabled(zeek::EnumVal* stream_id); /** * @return the type which corresponds to the columns in a log entry for * a given log stream. */ - zeek::RecordType* StreamColumns(EnumVal* stream_id); + zeek::RecordType* StreamColumns(zeek::EnumVal* stream_id); protected: friend class WriterFrontend; @@ -234,18 +234,19 @@ protected: // Instantiates a new WriterBackend of the given type (note that // doing so creates a new thread!). - WriterBackend* CreateBackend(WriterFrontend* frontend, EnumVal* tag); + WriterBackend* CreateBackend(WriterFrontend* frontend, zeek::EnumVal* tag); //// Function also used by the RemoteSerializer. // Takes ownership of fields and info. - WriterFrontend* CreateWriter(EnumVal* id, EnumVal* writer, WriterBackend::WriterInfo* info, - int num_fields, const threading::Field* const* fields, - bool local, bool remote, bool from_remote, const std::string& instantiating_filter=""); + WriterFrontend* CreateWriter(zeek::EnumVal* id, zeek::EnumVal* writer, WriterBackend::WriterInfo* info, + int num_fields, const threading::Field* const* fields, + bool local, bool remote, bool from_remote, + const std::string& instantiating_filter=""); // Signals that a file has been rotated. bool FinishedRotation(WriterFrontend* writer, const char* new_name, const char* old_name, - double open, double close, bool success, bool terminating); + double open, double close, bool success, bool terminating); // Deletes the values as passed into Write(). void DeleteVals(int num_fields, threading::Value** vals); @@ -256,13 +257,14 @@ private: struct WriterInfo; bool TraverseRecord(Stream* stream, Filter* filter, zeek::RecordType* rt, - TableVal* include, TableVal* exclude, const std::string& path, const std::list& indices); + zeek::TableVal* include, zeek::TableVal* exclude, + const std::string& path, const std::list& indices); threading::Value** RecordToFilterVals(Stream* stream, Filter* filter, - RecordVal* columns); + zeek::RecordVal* columns); - threading::Value* ValToLogVal(Val* val, zeek::Type* ty = nullptr); - Stream* FindStream(EnumVal* id); + threading::Value* ValToLogVal(zeek::Val* val, zeek::Type* ty = nullptr); + Stream* FindStream(zeek::EnumVal* id); void RemoveDisabledWriters(Stream* stream); void InstallRotationTimer(WriterInfo* winfo); void Rotate(WriterInfo* info); diff --git a/src/logging/Tag.cc b/src/logging/Tag.cc index 69d9e0ad67..03b7131bf7 100644 --- a/src/logging/Tag.cc +++ b/src/logging/Tag.cc @@ -22,20 +22,20 @@ logging::Tag& logging::Tag::operator=(const logging::Tag&& other) noexcept return *this; } -const IntrusivePtr& logging::Tag::AsVal() const +const zeek::EnumValPtr& logging::Tag::AsVal() const { return ::Tag::AsVal(log_mgr->GetTagType()); } -EnumVal* logging::Tag::AsEnumVal() const +zeek::EnumVal* logging::Tag::AsEnumVal() const { return AsVal().get(); } -logging::Tag::Tag(IntrusivePtr val) +logging::Tag::Tag(zeek::EnumValPtr val) : ::Tag(std::move(val)) { } -logging::Tag::Tag(EnumVal* val) - : ::Tag({NewRef{}, val}) +logging::Tag::Tag(zeek::EnumVal* val) + : ::Tag({zeek::NewRef{}, val}) { } diff --git a/src/logging/Tag.h b/src/logging/Tag.h index 01cfb4b04e..144789c5ef 100644 --- a/src/logging/Tag.h +++ b/src/logging/Tag.h @@ -5,7 +5,7 @@ #include "zeek-config.h" #include "../Tag.h" -class EnumVal; +ZEEK_FORWARD_DECLARE_NAMESPACED(EnumVal, zeek); namespace zeek::plugin { template class TaggedComponent; @@ -94,10 +94,10 @@ public: * * @param etype the script-layer enum type associated with the tag. */ - const IntrusivePtr& AsVal() const; + const zeek::EnumValPtr& AsVal() const; [[deprecated("Remove in v4.1. Use AsVal() instead.")]] - EnumVal* AsEnumVal() const; + zeek::EnumVal* AsEnumVal() const; static const Tag Error; @@ -122,10 +122,10 @@ protected: * * @param val An enum value of script type \c Log::Writer. */ - explicit Tag(IntrusivePtr val); + explicit Tag(zeek::EnumValPtr val); [[deprecated("Remove in v4.1. Construct from IntrusivePtr instead.")]] - explicit Tag(EnumVal* val); + explicit Tag(zeek::EnumVal* val); }; } diff --git a/src/logging/WriterFrontend.cc b/src/logging/WriterFrontend.cc index 307b121e17..15432117c3 100644 --- a/src/logging/WriterFrontend.cc +++ b/src/logging/WriterFrontend.cc @@ -98,7 +98,8 @@ private: using namespace logging; -WriterFrontend::WriterFrontend(const WriterBackend::WriterInfo& arg_info, EnumVal* arg_stream, EnumVal* arg_writer, bool arg_local, bool arg_remote) +WriterFrontend::WriterFrontend(const WriterBackend::WriterInfo& arg_info, zeek::EnumVal* arg_stream, + zeek::EnumVal* arg_writer, bool arg_local, bool arg_remote) { stream = arg_stream; writer = arg_writer; diff --git a/src/logging/WriterFrontend.h b/src/logging/WriterFrontend.h index 9a78ecf7db..d2e5b846d6 100644 --- a/src/logging/WriterFrontend.h +++ b/src/logging/WriterFrontend.h @@ -38,7 +38,8 @@ public: * * Frontends must only be instantiated by the main thread. */ - WriterFrontend(const WriterBackend::WriterInfo& info, EnumVal* stream, EnumVal* writer, bool local, bool remote); + WriterFrontend(const WriterBackend::WriterInfo& info, zeek::EnumVal* stream, + zeek::EnumVal* writer, bool local, bool remote); /** * Destructor. @@ -187,8 +188,8 @@ protected: void DeleteVals(int num_fields, threading::Value** vals); - EnumVal* stream; - EnumVal* writer; + zeek::EnumVal* stream; + zeek::EnumVal* writer; WriterBackend* backend; // The backend we have instantiated. bool disabled; // True if disabled. diff --git a/src/logging/logging.bif b/src/logging/logging.bif index efe08b26d9..07a701e6e4 100644 --- a/src/logging/logging.bif +++ b/src/logging/logging.bif @@ -19,53 +19,53 @@ enum PrintLogType %{ function Log::__create_stream%(id: Log::ID, stream: Log::Stream%) : bool %{ bool result = log_mgr->CreateStream(id->AsEnumVal(), stream->AsRecordVal()); - return val_mgr->Bool(result); + return zeek::val_mgr->Bool(result); %} function Log::__remove_stream%(id: Log::ID%) : bool %{ bool result = log_mgr->RemoveStream(id->AsEnumVal()); - return val_mgr->Bool(result); + return zeek::val_mgr->Bool(result); %} function Log::__enable_stream%(id: Log::ID%) : bool %{ bool result = log_mgr->EnableStream(id->AsEnumVal()); - return val_mgr->Bool(result); + return zeek::val_mgr->Bool(result); %} function Log::__disable_stream%(id: Log::ID%) : bool %{ bool result = log_mgr->DisableStream(id->AsEnumVal()); - return val_mgr->Bool(result); + return zeek::val_mgr->Bool(result); %} function Log::__add_filter%(id: Log::ID, filter: Log::Filter%) : bool %{ bool result = log_mgr->AddFilter(id->AsEnumVal(), filter->AsRecordVal()); - return val_mgr->Bool(result); + return zeek::val_mgr->Bool(result); %} function Log::__remove_filter%(id: Log::ID, name: string%) : bool %{ bool result = log_mgr->RemoveFilter(id->AsEnumVal(), name); - return val_mgr->Bool(result); + return zeek::val_mgr->Bool(result); %} function Log::__write%(id: Log::ID, columns: any%) : bool %{ bool result = log_mgr->Write(id->AsEnumVal(), columns->AsRecordVal()); - return val_mgr->Bool(result); + return zeek::val_mgr->Bool(result); %} function Log::__set_buf%(id: Log::ID, buffered: bool%): bool %{ bool result = log_mgr->SetBuf(id->AsEnumVal(), buffered); - return val_mgr->Bool(result); + return zeek::val_mgr->Bool(result); %} function Log::__flush%(id: Log::ID%): bool %{ bool result = log_mgr->Flush(id->AsEnumVal()); - return val_mgr->Bool(result); + return zeek::val_mgr->Bool(result); %} diff --git a/src/option.bif b/src/option.bif index 8d5daa9878..f2e5ee939b 100644 --- a/src/option.bif +++ b/src/option.bif @@ -7,9 +7,8 @@ module Option; #include "NetVar.h" #include "broker/Data.h" -static bool call_option_handlers_and_set_value(StringVal* name, const IntrusivePtr& i, - IntrusivePtr val, - StringVal* location) +static bool call_option_handlers_and_set_value(zeek::StringVal* name, const zeek::detail::IDPtr& i, + zeek::ValPtr val, zeek::StringVal* location) { if ( i->HasOptionHandlers() ) { @@ -18,11 +17,11 @@ static bool call_option_handlers_and_set_value(StringVal* name, const IntrusiveP bool add_loc = handler_function->GetType()->ParamList()->GetTypes().size() == 3; zeek::Args vl; vl.reserve(2 + add_loc); - vl.emplace_back(NewRef{}, name); + vl.emplace_back(zeek::NewRef{}, name); vl.emplace_back(val); if ( add_loc ) - vl.emplace_back(NewRef{}, location); + vl.emplace_back(zeek::NewRef{}, location); val = handler_function->Invoke(&vl); // consumed by next call. @@ -59,24 +58,24 @@ static bool call_option_handlers_and_set_value(StringVal* name, const IntrusiveP ## lower-level function. function Option::set%(ID: string, val: any, location: string &default=""%): bool %{ - const auto& i = global_scope()->Find(ID->CheckString()); + const auto& i = zeek::detail::global_scope()->Find(ID->CheckString()); if ( ! i ) { - builtin_error(fmt("Could not find ID named '%s'", ID->CheckString())); - return val_mgr->False(); + zeek::emit_builtin_error(fmt("Could not find ID named '%s'", ID->CheckString())); + return zeek::val_mgr->False(); } if ( ! i->HasVal() ) { // should be impossible because initialization is enforced - builtin_error(fmt("ID '%s' has no value", ID->CheckString())); - return val_mgr->False(); + zeek::emit_builtin_error(fmt("ID '%s' has no value", ID->CheckString())); + return zeek::val_mgr->False(); } if ( ! i->IsOption() ) { - builtin_error(fmt("ID '%s' is not an option", ID->CheckString())); - return val_mgr->False(); + zeek::emit_builtin_error(fmt("ID '%s' is not an option", ID->CheckString())); + return zeek::val_mgr->False(); } if ( same_type(val->GetType(), bro_broker::DataVal::ScriptDataType()) ) @@ -86,13 +85,14 @@ function Option::set%(ID: string, val: any, location: string &default=""%): bool if ( ! val_from_data ) { - builtin_error(fmt("Incompatible type for set of ID '%s': got broker data '%s', need '%s'", - ID->CheckString(), dv->data.get_type_name(), type_name(i->GetType()->Tag()))); - return val_mgr->False(); + zeek::emit_builtin_error(fmt("Incompatible type for set of ID '%s': got broker data '%s', need '%s'", + ID->CheckString(), dv->data.get_type_name(), + type_name(i->GetType()->Tag()))); + return zeek::val_mgr->False(); } auto rval = call_option_handlers_and_set_value(ID, i, std::move(val_from_data), location); - return val_mgr->Bool(rval); + return zeek::val_mgr->Bool(rval); } if ( ! same_type(i->GetType(), val->GetType()) ) @@ -102,20 +102,21 @@ function Option::set%(ID: string, val: any, location: string &default=""%): bool val->GetType()->AsTableType()->IsUnspecifiedTable() ) { // Just coerce an empty/unspecified table to the right type. - auto tv = make_intrusive( - cast_intrusive(i->GetType()), + auto tv = zeek::make_intrusive( + zeek::cast_intrusive(i->GetType()), i->GetVal()->AsTableVal()->GetAttrs()); auto rval = call_option_handlers_and_set_value(ID, i, std::move(tv), location); - return val_mgr->Bool(rval); + return zeek::val_mgr->Bool(rval); } - builtin_error(fmt("Incompatible type for set of ID '%s': got '%s', need '%s'", - ID->CheckString(), type_name(val->GetType()->Tag()), type_name(i->GetType()->Tag()))); - return val_mgr->False(); + zeek::emit_builtin_error(fmt("Incompatible type for set of ID '%s': got '%s', need '%s'", + ID->CheckString(), type_name(val->GetType()->Tag()), + type_name(i->GetType()->Tag()))); + return zeek::val_mgr->False(); } - auto rval = call_option_handlers_and_set_value(ID, i, {NewRef{}, val}, location); - return val_mgr->Bool(rval); + auto rval = call_option_handlers_and_set_value(ID, i, {zeek::NewRef{}, val}, location); + return zeek::val_mgr->Bool(rval); %} ## Set a change handler for an option. The change handler will be @@ -144,68 +145,70 @@ function Option::set%(ID: string, val: any, location: string &default=""%): bool ## .. zeek:see:: Option::set function Option::set_change_handler%(ID: string, on_change: any, priority: int &default=0%): bool %{ - const auto& i = global_scope()->Find(ID->CheckString()); + const auto& i = zeek::detail::global_scope()->Find(ID->CheckString()); if ( ! i ) { - builtin_error(fmt("Could not find ID named '%s'", ID->CheckString())); - return val_mgr->False(); + zeek::emit_builtin_error(fmt("Could not find ID named '%s'", ID->CheckString())); + return zeek::val_mgr->False(); } if ( ! i->IsOption() ) { - builtin_error(fmt("ID '%s' is not an option", ID->CheckString())); - return val_mgr->False(); + zeek::emit_builtin_error(fmt("ID '%s' is not an option", ID->CheckString())); + return zeek::val_mgr->False(); } if ( on_change->GetType()->Tag() != TYPE_FUNC ) { - builtin_error(fmt("Option::on_change needs function argument; got '%s' for ID '%s'", - type_name(on_change->GetType()->Tag()), ID->CheckString())); - return val_mgr->False(); + zeek::emit_builtin_error(fmt("Option::on_change needs function argument; got '%s' for ID '%s'", + type_name(on_change->GetType()->Tag()), ID->CheckString())); + return zeek::val_mgr->False(); } if ( on_change->GetType()->AsFuncType()->Flavor() != zeek::FUNC_FLAVOR_FUNCTION ) { - builtin_error("Option::on_change needs function argument; not hook or event"); - return val_mgr->False(); + zeek::emit_builtin_error("Option::on_change needs function argument; not hook or event"); + return zeek::val_mgr->False(); } const auto& args = on_change->GetType()->AsFuncType()->ParamList()->GetTypes(); if ( args.size() < 2 || args.size() > 3 ) { - builtin_error(fmt("Wrong number of arguments for passed function in Option::on_change for ID '%s'; expected 2 or 3, got %zu", - ID->CheckString(), args.size())); - return val_mgr->False(); + zeek::emit_builtin_error(fmt("Wrong number of arguments for passed function in Option::on_change for ID '%s'; expected 2 or 3, got %zu", + ID->CheckString(), args.size())); + return zeek::val_mgr->False(); } if ( args[0]->Tag() != TYPE_STRING ) { - builtin_error(fmt("First argument of passed function has to be string in Option::on_change for ID '%s'; got '%s'", - ID->CheckString(), type_name(args[0]->Tag()))); - return val_mgr->False(); + zeek::emit_builtin_error(fmt("First argument of passed function has to be string in Option::on_change for ID '%s'; got '%s'", + ID->CheckString(), type_name(args[0]->Tag()))); + return zeek::val_mgr->False(); } if ( ! same_type(args[1], i->GetType()) ) { - builtin_error(fmt("Second argument of passed function has to be %s in Option::on_change for ID '%s'; got '%s'", - type_name(i->GetType()->Tag()), ID->CheckString(), type_name(args[1]->Tag()))); - return val_mgr->False(); + zeek::emit_builtin_error(fmt("Second argument of passed function has to be %s in Option::on_change for ID '%s'; got '%s'", + type_name(i->GetType()->Tag()), ID->CheckString(), + type_name(args[1]->Tag()))); + return zeek::val_mgr->False(); } if ( args.size() == 3 && args[2]->Tag() != TYPE_STRING ) { - builtin_error(fmt("Third argument of passed function has to be string in Option::on_change for ID '%s'; got '%s'", + zeek::emit_builtin_error(fmt("Third argument of passed function has to be string in Option::on_change for ID '%s'; got '%s'", ID->CheckString(), type_name(args[2]->Tag()))); - return val_mgr->False(); + return zeek::val_mgr->False(); } if ( ! same_type(on_change->GetType()->AsFuncType()->Yield(), i->GetType()) ) { - builtin_error(fmt("Passed function needs to return type '%s' for ID '%s'; got '%s'", - type_name(i->GetType()->Tag()), ID->CheckString(), type_name(on_change->GetType()->AsFuncType()->Yield()->Tag()))); - return val_mgr->False(); + zeek::emit_builtin_error(fmt("Passed function needs to return type '%s' for ID '%s'; got '%s'", + type_name(i->GetType()->Tag()), ID->CheckString(), + type_name(on_change->GetType()->AsFuncType()->Yield()->Tag()))); + return zeek::val_mgr->False(); } i->AddOptionHandler(on_change->AsFuncPtr(), -priority); - return val_mgr->True(); + return zeek::val_mgr->True(); %} diff --git a/src/parse.y b/src/parse.y index afbea2aea0..5e0119de1f 100644 --- a/src/parse.y +++ b/src/parse.y @@ -82,7 +82,6 @@ #include "Desc.h" #include "Expr.h" #include "Func.h" -#include "IntrusivePtr.h" #include "Stmt.h" #include "Val.h" #include "Var.h" @@ -114,7 +113,9 @@ extern int brolex(); * Part of the module facility: while parsing, keep track of which * module to put things in. */ -std::string current_module = GLOBAL_MODULE_NAME; +std::string zeek::detail::current_module = GLOBAL_MODULE_NAME; +std::string& current_module = zeek::detail::current_module; + bool is_export = false; // true if in an export {} block /* @@ -125,8 +126,6 @@ extern zeek::detail::Expr* g_curr_debug_expr; extern bool in_debug; extern const char* g_curr_debug_error; -#define YYLTYPE yyltype - static int in_hook = 0; int in_init = 0; int in_record = 0; @@ -134,7 +133,7 @@ bool resolving_global_ID = false; bool defining_global_ID = false; std::vector saved_in_init; -static Location func_hdr_location; +static zeek::detail::Location func_hdr_location; zeek::EnumType* cur_enum_type = nullptr; static zeek::detail::ID* cur_decl_type_id = nullptr; @@ -167,7 +166,7 @@ static void parser_redef_enum (zeek::detail::ID *id) } static void extend_record(zeek::detail::ID* id, std::unique_ptr fields, - std::unique_ptr>> attrs) + std::unique_ptr> attrs) { std::set types = zeek::Type::GetAliases(id->Name()); @@ -199,14 +198,14 @@ static void extend_record(zeek::detail::ID* id, std::unique_ptr -make_attributes(std::vector>* attrs, - IntrusivePtr t, bool in_record, bool is_global) +static zeek::detail::AttributesPtr +make_attributes(std::vector* attrs, + zeek::TypePtr t, bool in_record, bool is_global) { if ( ! attrs ) return nullptr; - auto rval = make_intrusive(std::move(*attrs), std::move(t), + auto rval = zeek::make_intrusive(std::move(*attrs), std::move(t), in_record, is_global); delete attrs; return rval; @@ -235,7 +234,7 @@ static bool expr_is_table_type_name(const zeek::detail::Expr* expr) zeek::detail::ID* id; id_list* id_l; zeek::detail::InitClass ic; - Val* val; + zeek::Val* val; RE_Matcher* re; zeek::detail::Expr* expr; zeek::detail::EventExpr* event_expr; @@ -250,7 +249,7 @@ static bool expr_is_table_type_name(const zeek::detail::Expr* expr) zeek::detail::Case* c_case; zeek::detail::case_list* case_l; zeek::detail::Attr* attr; - std::vector>* attr_l; + std::vector* attr_l; zeek::detail::AttrTag attrtag; } @@ -266,7 +265,7 @@ bro: // Any objects creates from here on out should not // have file positions associated with them. - set_location(no_location); + set_location(zeek::detail::no_location); } | /* Silly way of allowing the debugger to call yyparse() @@ -300,157 +299,157 @@ expr: | TOK_COPY '(' expr ')' { set_location(@1, @4); - $$ = new zeek::detail::CloneExpr({AdoptRef{}, $3}); + $$ = new zeek::detail::CloneExpr({zeek::AdoptRef{}, $3}); } | TOK_INCR expr { set_location(@1, @2); - $$ = new zeek::detail::IncrExpr(zeek::detail::EXPR_INCR, {AdoptRef{}, $2}); + $$ = new zeek::detail::IncrExpr(zeek::detail::EXPR_INCR, {zeek::AdoptRef{}, $2}); } | TOK_DECR expr { set_location(@1, @2); - $$ = new zeek::detail::IncrExpr(zeek::detail::EXPR_DECR, {AdoptRef{}, $2}); + $$ = new zeek::detail::IncrExpr(zeek::detail::EXPR_DECR, {zeek::AdoptRef{}, $2}); } | '!' expr { set_location(@1, @2); - $$ = new zeek::detail::NotExpr({AdoptRef{}, $2}); + $$ = new zeek::detail::NotExpr({zeek::AdoptRef{}, $2}); } | '~' expr { set_location(@1, @2); - $$ = new zeek::detail::ComplementExpr({AdoptRef{}, $2}); + $$ = new zeek::detail::ComplementExpr({zeek::AdoptRef{}, $2}); } | '-' expr %prec '!' { set_location(@1, @2); - $$ = new zeek::detail::NegExpr({AdoptRef{}, $2}); + $$ = new zeek::detail::NegExpr({zeek::AdoptRef{}, $2}); } | '+' expr %prec '!' { set_location(@1, @2); - $$ = new zeek::detail::PosExpr({AdoptRef{}, $2}); + $$ = new zeek::detail::PosExpr({zeek::AdoptRef{}, $2}); } | expr '+' expr { set_location(@1, @3); - $$ = new zeek::detail::AddExpr({AdoptRef{}, $1}, {AdoptRef{}, $3}); + $$ = new zeek::detail::AddExpr({zeek::AdoptRef{}, $1}, {zeek::AdoptRef{}, $3}); } | expr TOK_ADD_TO expr { set_location(@1, @3); - $$ = new zeek::detail::AddToExpr({AdoptRef{}, $1}, {AdoptRef{}, $3}); + $$ = new zeek::detail::AddToExpr({zeek::AdoptRef{}, $1}, {zeek::AdoptRef{}, $3}); } | expr '-' expr { set_location(@1, @3); - $$ = new zeek::detail::SubExpr({AdoptRef{}, $1}, {AdoptRef{}, $3}); + $$ = new zeek::detail::SubExpr({zeek::AdoptRef{}, $1}, {zeek::AdoptRef{}, $3}); } | expr TOK_REMOVE_FROM expr { set_location(@1, @3); - $$ = new zeek::detail::RemoveFromExpr({AdoptRef{}, $1}, {AdoptRef{}, $3}); + $$ = new zeek::detail::RemoveFromExpr({zeek::AdoptRef{}, $1}, {zeek::AdoptRef{}, $3}); } | expr '*' expr { set_location(@1, @3); - $$ = new zeek::detail::TimesExpr({AdoptRef{}, $1}, {AdoptRef{}, $3}); + $$ = new zeek::detail::TimesExpr({zeek::AdoptRef{}, $1}, {zeek::AdoptRef{}, $3}); } | expr '/' expr { set_location(@1, @3); - $$ = new zeek::detail::DivideExpr({AdoptRef{}, $1}, {AdoptRef{}, $3}); + $$ = new zeek::detail::DivideExpr({zeek::AdoptRef{}, $1}, {zeek::AdoptRef{}, $3}); } | expr '%' expr { set_location(@1, @3); - $$ = new zeek::detail::ModExpr({AdoptRef{}, $1}, {AdoptRef{}, $3}); + $$ = new zeek::detail::ModExpr({zeek::AdoptRef{}, $1}, {zeek::AdoptRef{}, $3}); } | expr '&' expr { set_location(@1, @3); - $$ = new zeek::detail::BitExpr(zeek::detail::EXPR_AND, {AdoptRef{}, $1}, {AdoptRef{}, $3}); + $$ = new zeek::detail::BitExpr(zeek::detail::EXPR_AND, {zeek::AdoptRef{}, $1}, {zeek::AdoptRef{}, $3}); } | expr '|' expr { set_location(@1, @3); - $$ = new zeek::detail::BitExpr(zeek::detail::EXPR_OR, {AdoptRef{}, $1}, {AdoptRef{}, $3}); + $$ = new zeek::detail::BitExpr(zeek::detail::EXPR_OR, {zeek::AdoptRef{}, $1}, {zeek::AdoptRef{}, $3}); } | expr '^' expr { set_location(@1, @3); - $$ = new zeek::detail::BitExpr(zeek::detail::EXPR_XOR, {AdoptRef{}, $1}, {AdoptRef{}, $3}); + $$ = new zeek::detail::BitExpr(zeek::detail::EXPR_XOR, {zeek::AdoptRef{}, $1}, {zeek::AdoptRef{}, $3}); } | expr TOK_AND_AND expr { set_location(@1, @3); - $$ = new zeek::detail::BoolExpr(zeek::detail::EXPR_AND_AND, {AdoptRef{}, $1}, {AdoptRef{}, $3}); + $$ = new zeek::detail::BoolExpr(zeek::detail::EXPR_AND_AND, {zeek::AdoptRef{}, $1}, {zeek::AdoptRef{}, $3}); } | expr TOK_OR_OR expr { set_location(@1, @3); - $$ = new zeek::detail::BoolExpr(zeek::detail::EXPR_OR_OR, {AdoptRef{}, $1}, {AdoptRef{}, $3}); + $$ = new zeek::detail::BoolExpr(zeek::detail::EXPR_OR_OR, {zeek::AdoptRef{}, $1}, {zeek::AdoptRef{}, $3}); } | expr TOK_EQ expr { set_location(@1, @3); - $$ = new zeek::detail::EqExpr(zeek::detail::EXPR_EQ, {AdoptRef{}, $1}, {AdoptRef{}, $3}); + $$ = new zeek::detail::EqExpr(zeek::detail::EXPR_EQ, {zeek::AdoptRef{}, $1}, {zeek::AdoptRef{}, $3}); } | expr TOK_NE expr { set_location(@1, @3); - $$ = new zeek::detail::EqExpr(zeek::detail::EXPR_NE, {AdoptRef{}, $1}, {AdoptRef{}, $3}); + $$ = new zeek::detail::EqExpr(zeek::detail::EXPR_NE, {zeek::AdoptRef{}, $1}, {zeek::AdoptRef{}, $3}); } | expr '<' expr { set_location(@1, @3); - $$ = new zeek::detail::RelExpr(zeek::detail::EXPR_LT, {AdoptRef{}, $1}, {AdoptRef{}, $3}); + $$ = new zeek::detail::RelExpr(zeek::detail::EXPR_LT, {zeek::AdoptRef{}, $1}, {zeek::AdoptRef{}, $3}); } | expr TOK_LE expr { set_location(@1, @3); - $$ = new zeek::detail::RelExpr(zeek::detail::EXPR_LE, {AdoptRef{}, $1}, {AdoptRef{}, $3}); + $$ = new zeek::detail::RelExpr(zeek::detail::EXPR_LE, {zeek::AdoptRef{}, $1}, {zeek::AdoptRef{}, $3}); } | expr '>' expr { set_location(@1, @3); - $$ = new zeek::detail::RelExpr(zeek::detail::EXPR_GT, {AdoptRef{}, $1}, {AdoptRef{}, $3}); + $$ = new zeek::detail::RelExpr(zeek::detail::EXPR_GT, {zeek::AdoptRef{}, $1}, {zeek::AdoptRef{}, $3}); } | expr TOK_GE expr { set_location(@1, @3); - $$ = new zeek::detail::RelExpr(zeek::detail::EXPR_GE, {AdoptRef{}, $1}, {AdoptRef{}, $3}); + $$ = new zeek::detail::RelExpr(zeek::detail::EXPR_GE, {zeek::AdoptRef{}, $1}, {zeek::AdoptRef{}, $3}); } | expr '?' expr ':' expr { set_location(@1, @5); - $$ = new zeek::detail::CondExpr({AdoptRef{}, $1}, {AdoptRef{}, $3}, {AdoptRef{}, $5}); + $$ = new zeek::detail::CondExpr({zeek::AdoptRef{}, $1}, {zeek::AdoptRef{}, $3}, {zeek::AdoptRef{}, $5}); } | expr '=' expr @@ -462,20 +461,20 @@ expr: " in arbitrary expression contexts, only" " as a statement"); - $$ = zeek::detail::get_assign_expr({AdoptRef{}, $1}, {AdoptRef{}, $3}, in_init).release(); + $$ = zeek::detail::get_assign_expr({zeek::AdoptRef{}, $1}, {zeek::AdoptRef{}, $3}, in_init).release(); } | TOK_LOCAL local_id '=' expr { set_location(@2, @4); - $$ = add_and_assign_local({AdoptRef{}, $2}, {AdoptRef{}, $4}, - val_mgr->True()).release(); + $$ = add_and_assign_local({zeek::AdoptRef{}, $2}, {zeek::AdoptRef{}, $4}, + zeek::val_mgr->True()).release(); } | expr '[' expr_list ']' { set_location(@1, @4); - $$ = new zeek::detail::IndexExpr({AdoptRef{}, $1}, {AdoptRef{}, $3}); + $$ = new zeek::detail::IndexExpr({zeek::AdoptRef{}, $1}, {zeek::AdoptRef{}, $3}); } | index_slice @@ -483,41 +482,41 @@ expr: | expr '$' TOK_ID { set_location(@1, @3); - $$ = new zeek::detail::FieldExpr({AdoptRef{}, $1}, $3); + $$ = new zeek::detail::FieldExpr({zeek::AdoptRef{}, $1}, $3); } | '$' TOK_ID '=' expr { set_location(@1, @4); - $$ = new zeek::detail::FieldAssignExpr($2, {AdoptRef{}, $4}); + $$ = new zeek::detail::FieldAssignExpr($2, {zeek::AdoptRef{}, $4}); } | '$' TOK_ID func_params '=' { func_hdr_location = @1; - auto func_id = current_scope()->GenerateTemporary("anonymous-function"); + auto func_id = zeek::detail::current_scope()->GenerateTemporary("anonymous-function"); func_id->SetInferReturnType(true); - begin_func(std::move(func_id), current_module.c_str(), + begin_func(std::move(func_id), zeek::detail::current_module.c_str(), zeek::FUNC_FLAVOR_FUNCTION, false, - {AdoptRef{}, $3}); + {zeek::AdoptRef{}, $3}); } lambda_body { - $$ = new zeek::detail::FieldAssignExpr($2, IntrusivePtr{AdoptRef{}, $6}); + $$ = new zeek::detail::FieldAssignExpr($2, zeek::IntrusivePtr{zeek::AdoptRef{}, $6}); } | expr TOK_IN expr { set_location(@1, @3); - $$ = new zeek::detail::InExpr({AdoptRef{}, $1}, {AdoptRef{}, $3}); + $$ = new zeek::detail::InExpr({zeek::AdoptRef{}, $1}, {zeek::AdoptRef{}, $3}); } | expr TOK_NOT_IN expr { set_location(@1, @3); - $$ = new zeek::detail::NotExpr(make_intrusive( - IntrusivePtr{AdoptRef{}, $1}, - IntrusivePtr{AdoptRef{}, $3})); + $$ = new zeek::detail::NotExpr(zeek::make_intrusive( + zeek::detail::ExprPtr{zeek::AdoptRef{}, $1}, + zeek::detail::ExprPtr{zeek::AdoptRef{}, $3})); } | '[' expr_list ']' @@ -540,7 +539,7 @@ expr: } if ( is_record_ctor ) - $$ = new zeek::detail::RecordConstructorExpr({AdoptRef{}, $2}); + $$ = new zeek::detail::RecordConstructorExpr({zeek::AdoptRef{}, $2}); else $$ = $2; } @@ -548,35 +547,35 @@ expr: | '[' ']' { // We interpret this as an empty record constructor. - $$ = new zeek::detail::RecordConstructorExpr(make_intrusive()); + $$ = new zeek::detail::RecordConstructorExpr(zeek::make_intrusive()); } | TOK_RECORD '(' expr_list ')' { set_location(@1, @4); - $$ = new zeek::detail::RecordConstructorExpr({AdoptRef{}, $3}); + $$ = new zeek::detail::RecordConstructorExpr({zeek::AdoptRef{}, $3}); } | TOK_TABLE '(' { ++in_init; } opt_expr_list ')' { --in_init; } opt_attr { // the ++in_init fixes up the parsing of "[x] = y" set_location(@1, @5); - std::unique_ptr>> attrs{$7}; - $$ = new zeek::detail::TableConstructorExpr({AdoptRef{}, $4}, std::move(attrs)); + std::unique_ptr> attrs{$7}; + $$ = new zeek::detail::TableConstructorExpr({zeek::AdoptRef{}, $4}, std::move(attrs)); } | TOK_SET '(' opt_expr_list ')' opt_attr { set_location(@1, @4); - std::unique_ptr>> attrs{$5}; - $$ = new zeek::detail::SetConstructorExpr({AdoptRef{}, $3}, std::move(attrs)); + std::unique_ptr> attrs{$5}; + $$ = new zeek::detail::SetConstructorExpr({zeek::AdoptRef{}, $3}, std::move(attrs)); } | TOK_VECTOR '(' opt_expr_list ')' { set_location(@1, @4); - $$ = new zeek::detail::VectorConstructorExpr({AdoptRef{}, $3}); + $$ = new zeek::detail::VectorConstructorExpr({zeek::AdoptRef{}, $3}); } | expr '(' @@ -602,23 +601,23 @@ expr: switch ( ctor_type->Tag() ) { case zeek::TYPE_RECORD: { - auto rce = make_intrusive( - IntrusivePtr{AdoptRef{}, $4}); - auto rt = cast_intrusive(ctor_type); + auto rce = zeek::make_intrusive( + zeek::detail::ListExprPtr{zeek::AdoptRef{}, $4}); + auto rt = zeek::cast_intrusive(ctor_type); $$ = new zeek::detail::RecordCoerceExpr(std::move(rce), std::move(rt)); } break; case zeek::TYPE_TABLE: if ( ctor_type->IsTable() ) - $$ = new zeek::detail::TableConstructorExpr({AdoptRef{}, $4}, 0, ctor_type); + $$ = new zeek::detail::TableConstructorExpr({zeek::AdoptRef{}, $4}, 0, ctor_type); else - $$ = new zeek::detail::SetConstructorExpr({AdoptRef{}, $4}, 0, ctor_type); + $$ = new zeek::detail::SetConstructorExpr({zeek::AdoptRef{}, $4}, 0, ctor_type); break; case zeek::TYPE_VECTOR: - $$ = new zeek::detail::VectorConstructorExpr({AdoptRef{}, $4}, ctor_type); + $$ = new zeek::detail::VectorConstructorExpr({zeek::AdoptRef{}, $4}, ctor_type); break; default: @@ -628,7 +627,7 @@ expr: } else - $$ = new zeek::detail::CallExpr({AdoptRef{}, $1}, {AdoptRef{}, $4}, in_hook > 0); + $$ = new zeek::detail::CallExpr({zeek::AdoptRef{}, $1}, {zeek::AdoptRef{}, $4}, in_hook > 0); } | TOK_HOOK { ++in_hook; } expr @@ -643,7 +642,7 @@ expr: | expr TOK_HAS_FIELD TOK_ID { set_location(@1, @3); - $$ = new zeek::detail::HasFieldExpr({AdoptRef{}, $1}, $3); + $$ = new zeek::detail::HasFieldExpr({zeek::AdoptRef{}, $1}, $3); } | anonymous_function @@ -652,21 +651,21 @@ expr: | TOK_SCHEDULE expr '{' event '}' { set_location(@1, @5); - $$ = new zeek::detail::ScheduleExpr({AdoptRef{}, $2}, {AdoptRef{}, $4}); + $$ = new zeek::detail::ScheduleExpr({zeek::AdoptRef{}, $2}, {zeek::AdoptRef{}, $4}); } | TOK_ID { set_location(@1); - auto id = lookup_ID($1, current_module.c_str()); + auto id = zeek::detail::lookup_ID($1, zeek::detail::current_module.c_str()); if ( ! id ) { if ( ! in_debug ) { /* // CHECK THAT THIS IS NOT GLOBAL. - id = install_ID($1, current_module.c_str(), - false, is_export); + id = install_ID($1, zeek::detail::current_module.c_str(), + false, is_export); */ yyerror(fmt("unknown identifier %s", $1)); @@ -709,7 +708,7 @@ expr: | TOK_CONSTANT { set_location(@1); - $$ = new zeek::detail::ConstExpr({AdoptRef{}, $1}); + $$ = new zeek::detail::ConstExpr({zeek::AdoptRef{}, $1}); } | '/' { begin_RE(); } TOK_PATTERN_TEXT TOK_PATTERN_END @@ -723,16 +722,16 @@ expr: re->MakeCaseInsensitive(); re->Compile(); - $$ = new zeek::detail::ConstExpr(make_intrusive(re)); + $$ = new zeek::detail::ConstExpr(zeek::make_intrusive(re)); } | '|' expr '|' %prec '(' { set_location(@1, @3); - IntrusivePtr e{AdoptRef{}, $2}; + zeek::detail::ExprPtr e{zeek::AdoptRef{}, $2}; if ( zeek::IsIntegral(e->GetType()->Tag()) ) - e = make_intrusive(std::move(e), zeek::TYPE_INT); + e = zeek::make_intrusive(std::move(e), zeek::TYPE_INT); $$ = new zeek::detail::SizeExpr(std::move(e)); } @@ -740,13 +739,13 @@ expr: | expr TOK_AS type { set_location(@1, @3); - $$ = new zeek::detail::CastExpr({AdoptRef{}, $1}, {AdoptRef{}, $3}); + $$ = new zeek::detail::CastExpr({zeek::AdoptRef{}, $1}, {zeek::AdoptRef{}, $3}); } | expr TOK_IS type { set_location(@1, @3); - $$ = new zeek::detail::IsExpr({AdoptRef{}, $1}, {AdoptRef{}, $3}); + $$ = new zeek::detail::IsExpr({zeek::AdoptRef{}, $1}, {zeek::AdoptRef{}, $3}); } ; @@ -754,13 +753,13 @@ expr_list: expr_list ',' expr { set_location(@1, @3); - $1->Append({AdoptRef{}, $3}); + $1->Append({zeek::AdoptRef{}, $3}); } | expr { set_location(@1); - $$ = new zeek::detail::ListExpr({AdoptRef{}, $1}); + $$ = new zeek::detail::ListExpr({zeek::AdoptRef{}, $1}); } ; @@ -804,7 +803,7 @@ enum_body_elem: if ( $3->GetType()->Tag() != zeek::TYPE_COUNT ) reporter->Error("enumerator is not a count constant"); else - cur_enum_type->AddName(current_module, $1, + cur_enum_type->AddName(zeek::detail::current_module, $1, $3->InternalUnsigned(), is_export, $4); } @@ -821,7 +820,7 @@ enum_body_elem: { set_location(@1); assert(cur_enum_type); - cur_enum_type->AddName(current_module, $1, is_export, $2); + cur_enum_type->AddName(zeek::detail::current_module, $1, is_export, $2); } ; @@ -899,13 +898,13 @@ type: | TOK_TABLE '[' type_list ']' TOK_OF type { set_location(@1, @6); - $$ = new zeek::TableType({AdoptRef{}, $3}, {AdoptRef{}, $6}); + $$ = new zeek::TableType({zeek::AdoptRef{}, $3}, {zeek::AdoptRef{}, $6}); } | TOK_SET '[' type_list ']' { set_location(@1, @4); - $$ = new zeek::SetType({AdoptRef{}, $3}, nullptr); + $$ = new zeek::SetType({zeek::AdoptRef{}, $3}, nullptr); } | TOK_RECORD '{' @@ -951,7 +950,7 @@ type: | TOK_VECTOR TOK_OF type { set_location(@1, @3); - $$ = new zeek::VectorType({AdoptRef{}, $3}); + $$ = new zeek::VectorType({zeek::AdoptRef{}, $3}); } | TOK_FUNCTION func_params @@ -963,19 +962,19 @@ type: | TOK_EVENT '(' formal_args ')' { set_location(@1, @3); - $$ = new zeek::FuncType({AdoptRef{}, $3}, nullptr, zeek::FUNC_FLAVOR_EVENT); + $$ = new zeek::FuncType({zeek::AdoptRef{}, $3}, nullptr, zeek::FUNC_FLAVOR_EVENT); } | TOK_HOOK '(' formal_args ')' { set_location(@1, @3); - $$ = new zeek::FuncType({AdoptRef{}, $3}, zeek::base_type(zeek::TYPE_BOOL), zeek::FUNC_FLAVOR_HOOK); + $$ = new zeek::FuncType({zeek::AdoptRef{}, $3}, zeek::base_type(zeek::TYPE_BOOL), zeek::FUNC_FLAVOR_HOOK); } | TOK_FILE TOK_OF type { set_location(@1, @3); - $$ = new zeek::FileType({AdoptRef{}, $3}); + $$ = new zeek::FileType({zeek::AdoptRef{}, $3}); } | TOK_FILE @@ -1011,11 +1010,11 @@ type: type_list: type_list ',' type - { $1->AppendEvenIfNotPure({AdoptRef{}, $3}); } + { $1->AppendEvenIfNotPure({zeek::AdoptRef{}, $3}); } | type { - $$ = new zeek::TypeList({NewRef{}, $1}); - $$->Append({AdoptRef{}, $1}); + $$ = new zeek::TypeList({zeek::NewRef{}, $1}); + $$->Append({zeek::AdoptRef{}, $1}); } ; @@ -1034,8 +1033,8 @@ type_decl: TOK_ID ':' type opt_attr ';' { set_location(@1, @4); - auto attrs = make_attributes($4, {NewRef{}, $3}, in_record > 0, false); - $$ = new zeek::TypeDecl($1, {AdoptRef{}, $3}, std::move(attrs)); + auto attrs = make_attributes($4, {zeek::NewRef{}, $3}, in_record > 0, false); + $$ = new zeek::TypeDecl($1, {zeek::AdoptRef{}, $3}, std::move(attrs)); if ( in_record > 0 && cur_decl_type_id ) zeekygen_mgr->RecordField(cur_decl_type_id, $$, ::filename); @@ -1064,16 +1063,16 @@ formal_args_decl: TOK_ID ':' type opt_attr { set_location(@1, @4); - auto attrs = make_attributes($4, {NewRef{}, $3}, true, false); - $$ = new zeek::TypeDecl($1, {AdoptRef{}, $3}, std::move(attrs)); + auto attrs = make_attributes($4, {zeek::NewRef{}, $3}, true, false); + $$ = new zeek::TypeDecl($1, {zeek::AdoptRef{}, $3}, std::move(attrs)); } ; decl: TOK_MODULE TOK_ID ';' { - current_module = $2; - zeekygen_mgr->ModuleUsage(::filename, current_module); + zeek::detail::current_module = $2; + zeekygen_mgr->ModuleUsage(::filename, zeek::detail::current_module); } | TOK_EXPORT '{' { is_export = true; } decl_list '}' @@ -1081,37 +1080,37 @@ decl: | TOK_GLOBAL def_global_id opt_type init_class opt_init opt_attr ';' { - IntrusivePtr id{AdoptRef{}, $2}; - add_global(id, {AdoptRef{}, $3}, $4, {AdoptRef{}, $5}, - std::unique_ptr>>{$6}, + zeek::IntrusivePtr id{zeek::AdoptRef{}, $2}; + add_global(id, {zeek::AdoptRef{}, $3}, $4, {zeek::AdoptRef{}, $5}, + std::unique_ptr>{$6}, VAR_REGULAR); zeekygen_mgr->Identifier(std::move(id)); } | TOK_OPTION def_global_id opt_type init_class opt_init opt_attr ';' { - IntrusivePtr id{AdoptRef{}, $2}; - add_global(id, {AdoptRef{}, $3}, $4, {AdoptRef{}, $5}, - std::unique_ptr>>{$6}, + zeek::IntrusivePtr id{zeek::AdoptRef{}, $2}; + add_global(id, {zeek::AdoptRef{}, $3}, $4, {zeek::AdoptRef{}, $5}, + std::unique_ptr>{$6}, VAR_OPTION); zeekygen_mgr->Identifier(std::move(id)); } | TOK_CONST def_global_id opt_type init_class opt_init opt_attr ';' { - IntrusivePtr id{AdoptRef{}, $2}; - add_global(id, {AdoptRef{}, $3}, $4, {AdoptRef{}, $5}, - std::unique_ptr>>{$6}, + zeek::IntrusivePtr id{zeek::AdoptRef{}, $2}; + add_global(id, {zeek::AdoptRef{}, $3}, $4, {zeek::AdoptRef{}, $5}, + std::unique_ptr>{$6}, VAR_CONST); zeekygen_mgr->Identifier(std::move(id)); } | TOK_REDEF global_id opt_type init_class opt_init opt_attr ';' { - IntrusivePtr id{AdoptRef{}, $2}; - IntrusivePtr init{AdoptRef{}, $5}; - add_global(id, {AdoptRef{}, $3}, $4, init, - std::unique_ptr>>{$6}, + zeek::IntrusivePtr id{zeek::AdoptRef{}, $2}; + zeek::detail::ExprPtr init{zeek::AdoptRef{}, $5}; + add_global(id, {zeek::AdoptRef{}, $3}, $4, init, + std::unique_ptr>{$6}, VAR_REDEF); zeekygen_mgr->Redef(id.get(), ::filename, $4, std::move(init)); } @@ -1137,17 +1136,17 @@ decl: $3->Error("unknown identifier"); else extend_record($3, std::unique_ptr($8), - std::unique_ptr>>($11)); + std::unique_ptr>($11)); } | TOK_TYPE global_id ':' - { cur_decl_type_id = $2; zeekygen_mgr->StartType({NewRef{}, $2}); } + { cur_decl_type_id = $2; zeekygen_mgr->StartType({zeek::NewRef{}, $2}); } type opt_attr ';' { cur_decl_type_id = 0; - IntrusivePtr id{AdoptRef{}, $2}; - add_type(id.get(), {AdoptRef{}, $5}, - std::unique_ptr>>{$6}); + zeek::IntrusivePtr id{zeek::AdoptRef{}, $2}; + add_type(id.get(), {zeek::AdoptRef{}, $5}, + std::unique_ptr>{$6}); zeekygen_mgr->Identifier(std::move(id)); } @@ -1178,10 +1177,10 @@ conditional: func_hdr: TOK_FUNCTION def_global_id func_params opt_attr { - IntrusivePtr id{AdoptRef{}, $2}; - begin_func(id, current_module.c_str(), - zeek::FUNC_FLAVOR_FUNCTION, 0, {NewRef{}, $3}, - std::unique_ptr>>{$4}); + zeek::IntrusivePtr id{zeek::AdoptRef{}, $2}; + begin_func(id, zeek::detail::current_module.c_str(), + zeek::FUNC_FLAVOR_FUNCTION, 0, {zeek::NewRef{}, $3}, + std::unique_ptr>{$4}); $$ = $3; zeekygen_mgr->Identifier(std::move(id)); } @@ -1194,25 +1193,25 @@ func_hdr: reporter->Error("event %s() is no longer available, use zeek_%s() instead", name, base.c_str()); } - begin_func({NewRef{}, $2}, current_module.c_str(), - zeek::FUNC_FLAVOR_EVENT, 0, {NewRef{}, $3}, - std::unique_ptr>>{$4}); + begin_func({zeek::NewRef{}, $2}, zeek::detail::current_module.c_str(), + zeek::FUNC_FLAVOR_EVENT, 0, {zeek::NewRef{}, $3}, + std::unique_ptr>{$4}); $$ = $3; } | TOK_HOOK def_global_id func_params opt_attr { $3->ClearYieldType(zeek::FUNC_FLAVOR_HOOK); $3->SetYieldType(zeek::base_type(zeek::TYPE_BOOL)); - begin_func({NewRef{}, $2}, current_module.c_str(), - zeek::FUNC_FLAVOR_HOOK, 0, {NewRef{}, $3}, - std::unique_ptr>>{$4}); + begin_func({zeek::NewRef{}, $2}, zeek::detail::current_module.c_str(), + zeek::FUNC_FLAVOR_HOOK, 0, {zeek::NewRef{}, $3}, + std::unique_ptr>{$4}); $$ = $3; } | TOK_REDEF TOK_EVENT event_id func_params opt_attr { - begin_func({NewRef{}, $3}, current_module.c_str(), - zeek::FUNC_FLAVOR_EVENT, 1, {NewRef{}, $4}, - std::unique_ptr>>{$5}); + begin_func({zeek::NewRef{}, $3}, zeek::detail::current_module.c_str(), + zeek::FUNC_FLAVOR_EVENT, 1, {zeek::NewRef{}, $4}, + std::unique_ptr>{$5}); $$ = $4; } ; @@ -1233,7 +1232,7 @@ func_body: '}' { set_location(func_hdr_location, @5); - end_func({AdoptRef{}, $3}); + end_func({zeek::AdoptRef{}, $3}); } ; @@ -1259,8 +1258,10 @@ lambda_body: // a lambda expression. // Gather the ingredients for a BroFunc from the current scope - auto ingredients = std::make_unique(IntrusivePtr{NewRef{}, current_scope()}, IntrusivePtr{AdoptRef{}, $3}); - id_list outer_ids = gather_outer_ids(pop_scope().get(), ingredients->body.get()); + auto ingredients = std::make_unique( + zeek::IntrusivePtr{zeek::NewRef{}, zeek::detail::current_scope()}, + zeek::IntrusivePtr{zeek::AdoptRef{}, $3}); + id_list outer_ids = gather_outer_ids(zeek::detail::pop_scope().get(), ingredients->body.get()); $$ = new zeek::detail::LambdaExpr(std::move(ingredients), std::move(outer_ids)); } @@ -1274,17 +1275,17 @@ anonymous_function: begin_func: func_params { - auto id = current_scope()->GenerateTemporary("anonymous-function"); - begin_func(id, current_module.c_str(), zeek::FUNC_FLAVOR_FUNCTION, 0, {AdoptRef{}, $1}); + auto id = zeek::detail::current_scope()->GenerateTemporary("anonymous-function"); + begin_func(id, zeek::detail::current_module.c_str(), zeek::FUNC_FLAVOR_FUNCTION, 0, {zeek::AdoptRef{}, $1}); $$ = id.release(); } ; func_params: '(' formal_args ')' ':' type - { $$ = new zeek::FuncType({AdoptRef{}, $2}, {AdoptRef{}, $5}, zeek::FUNC_FLAVOR_FUNCTION); } + { $$ = new zeek::FuncType({zeek::AdoptRef{}, $2}, {zeek::AdoptRef{}, $5}, zeek::FUNC_FLAVOR_FUNCTION); } | '(' formal_args ')' - { $$ = new zeek::FuncType({AdoptRef{}, $2}, zeek::base_type(zeek::TYPE_VOID), zeek::FUNC_FLAVOR_FUNCTION); } + { $$ = new zeek::FuncType({zeek::AdoptRef{}, $2}, zeek::base_type(zeek::TYPE_VOID), zeek::FUNC_FLAVOR_FUNCTION); } ; opt_type: @@ -1321,19 +1322,19 @@ index_slice: { set_location(@1, @6); - auto low = $3 ? IntrusivePtr{AdoptRef{}, $3} : - make_intrusive(val_mgr->Count(0)); + auto low = $3 ? zeek::detail::ExprPtr{zeek::AdoptRef{}, $3} : + zeek::make_intrusive(zeek::val_mgr->Count(0)); - auto high = $5 ? IntrusivePtr{AdoptRef{}, $5} : - make_intrusive( - IntrusivePtr{NewRef{}, $1}); + auto high = $5 ? zeek::detail::ExprPtr{zeek::AdoptRef{}, $5} : + zeek::make_intrusive( + zeek::detail::ExprPtr{zeek::NewRef{}, $1}); if ( ! zeek::IsIntegral(low->GetType()->Tag()) || ! zeek::IsIntegral(high->GetType()->Tag()) ) reporter->Error("slice notation must have integral values as indexes"); - auto le = make_intrusive(std::move(low)); + auto le = zeek::make_intrusive(std::move(low)); le->Append(std::move(high)); - $$ = new zeek::detail::IndexExpr({AdoptRef{}, $1}, std::move(le), true); + $$ = new zeek::detail::IndexExpr({zeek::AdoptRef{}, $1}, std::move(le), true); } opt_attr: @@ -1344,41 +1345,41 @@ opt_attr: attr_list: attr_list attr - { $1->emplace_back(AdoptRef{}, $2); } + { $1->emplace_back(zeek::AdoptRef{}, $2); } | attr { - $$ = new std::vector>; - $$->emplace_back(AdoptRef{}, $1); + $$ = new std::vector; + $$->emplace_back(zeek::AdoptRef{}, $1); } ; attr: TOK_ATTR_DEFAULT '=' expr - { $$ = new zeek::detail::Attr(zeek::detail::ATTR_DEFAULT, {AdoptRef{}, $3}); } + { $$ = new zeek::detail::Attr(zeek::detail::ATTR_DEFAULT, {zeek::AdoptRef{}, $3}); } | TOK_ATTR_OPTIONAL { $$ = new zeek::detail::Attr(zeek::detail::ATTR_OPTIONAL); } | TOK_ATTR_REDEF { $$ = new zeek::detail::Attr(zeek::detail::ATTR_REDEF); } | TOK_ATTR_ADD_FUNC '=' expr - { $$ = new zeek::detail::Attr(zeek::detail::ATTR_ADD_FUNC, {AdoptRef{}, $3}); } + { $$ = new zeek::detail::Attr(zeek::detail::ATTR_ADD_FUNC, {zeek::AdoptRef{}, $3}); } | TOK_ATTR_DEL_FUNC '=' expr - { $$ = new zeek::detail::Attr(zeek::detail::ATTR_DEL_FUNC, {AdoptRef{}, $3}); } + { $$ = new zeek::detail::Attr(zeek::detail::ATTR_DEL_FUNC, {zeek::AdoptRef{}, $3}); } | TOK_ATTR_ON_CHANGE '=' expr - { $$ = new zeek::detail::Attr(zeek::detail::ATTR_ON_CHANGE, {AdoptRef{}, $3}); } + { $$ = new zeek::detail::Attr(zeek::detail::ATTR_ON_CHANGE, {zeek::AdoptRef{}, $3}); } | TOK_ATTR_EXPIRE_FUNC '=' expr - { $$ = new zeek::detail::Attr(zeek::detail::ATTR_EXPIRE_FUNC, {AdoptRef{}, $3}); } + { $$ = new zeek::detail::Attr(zeek::detail::ATTR_EXPIRE_FUNC, {zeek::AdoptRef{}, $3}); } | TOK_ATTR_EXPIRE_CREATE '=' expr - { $$ = new zeek::detail::Attr(zeek::detail::ATTR_EXPIRE_CREATE, {AdoptRef{}, $3}); } + { $$ = new zeek::detail::Attr(zeek::detail::ATTR_EXPIRE_CREATE, {zeek::AdoptRef{}, $3}); } | TOK_ATTR_EXPIRE_READ '=' expr - { $$ = new zeek::detail::Attr(zeek::detail::ATTR_EXPIRE_READ, {AdoptRef{}, $3}); } + { $$ = new zeek::detail::Attr(zeek::detail::ATTR_EXPIRE_READ, {zeek::AdoptRef{}, $3}); } | TOK_ATTR_EXPIRE_WRITE '=' expr - { $$ = new zeek::detail::Attr(zeek::detail::ATTR_EXPIRE_WRITE, {AdoptRef{}, $3}); } + { $$ = new zeek::detail::Attr(zeek::detail::ATTR_EXPIRE_WRITE, {zeek::AdoptRef{}, $3}); } | TOK_ATTR_RAW_OUTPUT { $$ = new zeek::detail::Attr(zeek::detail::ATTR_RAW_OUTPUT); } | TOK_ATTR_PRIORITY '=' expr - { $$ = new zeek::detail::Attr(zeek::detail::ATTR_PRIORITY, {AdoptRef{}, $3}); } + { $$ = new zeek::detail::Attr(zeek::detail::ATTR_PRIORITY, {zeek::AdoptRef{}, $3}); } | TOK_ATTR_TYPE_COLUMN '=' expr - { $$ = new zeek::detail::Attr(zeek::detail::ATTR_TYPE_COLUMN, {AdoptRef{}, $3}); } + { $$ = new zeek::detail::Attr(zeek::detail::ATTR_TYPE_COLUMN, {zeek::AdoptRef{}, $3}); } | TOK_ATTR_LOG { $$ = new zeek::detail::Attr(zeek::detail::ATTR_LOG); } | TOK_ATTR_ERROR_HANDLER @@ -1390,7 +1391,7 @@ attr: if ( zeek::IsString($3->GetType()->Tag()) ) $$ = new zeek::detail::Attr( zeek::detail::ATTR_DEPRECATED, - make_intrusive(IntrusivePtr{AdoptRef{}, $3})); + zeek::make_intrusive(zeek::IntrusivePtr{zeek::AdoptRef{}, $3})); else { ODesc d; @@ -1415,7 +1416,7 @@ stmt: | TOK_PRINT expr_list ';' opt_no_test { set_location(@1, @3); - $$ = new zeek::detail::PrintStmt(IntrusivePtr{AdoptRef{}, $2}); + $$ = new zeek::detail::PrintStmt(zeek::IntrusivePtr{zeek::AdoptRef{}, $2}); if ( ! $4 ) brofiler.AddStmt($$); } @@ -1423,7 +1424,7 @@ stmt: | TOK_EVENT event ';' opt_no_test { set_location(@1, @3); - $$ = new zeek::detail::EventStmt({AdoptRef{}, $2}); + $$ = new zeek::detail::EventStmt({zeek::AdoptRef{}, $2}); if ( ! $4 ) brofiler.AddStmt($$); } @@ -1431,29 +1432,29 @@ stmt: | TOK_IF '(' expr ')' stmt { set_location(@1, @4); - $$ = new zeek::detail::IfStmt({AdoptRef{}, $3}, {AdoptRef{}, $5}, make_intrusive()); + $$ = new zeek::detail::IfStmt({zeek::AdoptRef{}, $3}, {zeek::AdoptRef{}, $5}, zeek::make_intrusive()); } | TOK_IF '(' expr ')' stmt TOK_ELSE stmt { set_location(@1, @4); - $$ = new zeek::detail::IfStmt({AdoptRef{}, $3}, {AdoptRef{}, $5}, {AdoptRef{}, $7}); + $$ = new zeek::detail::IfStmt({zeek::AdoptRef{}, $3}, {zeek::AdoptRef{}, $5}, {zeek::AdoptRef{}, $7}); } | TOK_SWITCH expr '{' case_list '}' { set_location(@1, @2); - $$ = new zeek::detail::SwitchStmt({AdoptRef{}, $2}, $4); + $$ = new zeek::detail::SwitchStmt({zeek::AdoptRef{}, $2}, $4); } | for_head stmt { - $1->AsForStmt()->AddBody({AdoptRef{}, $2}); + $1->AsForStmt()->AddBody({zeek::AdoptRef{}, $2}); } | TOK_WHILE '(' expr ')' stmt { - $$ = new zeek::detail::WhileStmt({AdoptRef{}, $3}, {AdoptRef{}, $5}); + $$ = new zeek::detail::WhileStmt({zeek::AdoptRef{}, $3}, {zeek::AdoptRef{}, $5}); } | TOK_NEXT ';' opt_no_test @@ -1491,7 +1492,7 @@ stmt: | TOK_RETURN expr ';' opt_no_test { set_location(@1, @2); - $$ = new zeek::detail::ReturnStmt({AdoptRef{}, $2}); + $$ = new zeek::detail::ReturnStmt({zeek::AdoptRef{}, $2}); if ( ! $4 ) brofiler.AddStmt($$); } @@ -1499,7 +1500,7 @@ stmt: | TOK_ADD expr ';' opt_no_test { set_location(@1, @3); - $$ = new zeek::detail::AddStmt({AdoptRef{}, $2}); + $$ = new zeek::detail::AddStmt({zeek::AdoptRef{}, $2}); if ( ! $4 ) brofiler.AddStmt($$); } @@ -1507,7 +1508,7 @@ stmt: | TOK_DELETE expr ';' opt_no_test { set_location(@1, @3); - $$ = new zeek::detail::DelStmt({AdoptRef{}, $2}); + $$ = new zeek::detail::DelStmt({zeek::AdoptRef{}, $2}); if ( ! $4 ) brofiler.AddStmt($$); } @@ -1515,9 +1516,9 @@ stmt: | TOK_LOCAL local_id opt_type init_class opt_init opt_attr ';' opt_no_test { set_location(@1, @7); - $$ = add_local({AdoptRef{}, $2}, {AdoptRef{}, $3}, $4, - {AdoptRef{}, $5}, - std::unique_ptr>>{$6}, + $$ = add_local({zeek::AdoptRef{}, $2}, {zeek::AdoptRef{}, $3}, $4, + {zeek::AdoptRef{}, $5}, + std::unique_ptr>{$6}, VAR_REGULAR).release(); if ( ! $8 ) brofiler.AddStmt($$); @@ -1526,9 +1527,9 @@ stmt: | TOK_CONST local_id opt_type init_class opt_init opt_attr ';' opt_no_test { set_location(@1, @6); - $$ = add_local({AdoptRef{}, $2}, {AdoptRef{}, $3}, $4, - {AdoptRef{}, $5}, - std::unique_ptr>>{$6}, + $$ = add_local({zeek::AdoptRef{}, $2}, {zeek::AdoptRef{}, $3}, $4, + {zeek::AdoptRef{}, $5}, + std::unique_ptr>{$6}, VAR_CONST).release(); if ( ! $8 ) brofiler.AddStmt($$); @@ -1537,15 +1538,15 @@ stmt: | TOK_WHEN '(' expr ')' stmt { set_location(@3, @5); - $$ = new zeek::detail::WhenStmt({AdoptRef{}, $3}, {AdoptRef{}, $5}, + $$ = new zeek::detail::WhenStmt({zeek::AdoptRef{}, $3}, {zeek::AdoptRef{}, $5}, nullptr, nullptr, false); } | TOK_WHEN '(' expr ')' stmt TOK_TIMEOUT expr '{' opt_no_test_block stmt_list '}' { set_location(@3, @9); - $$ = new zeek::detail::WhenStmt({AdoptRef{}, $3}, {AdoptRef{}, $5}, - {AdoptRef{}, $10}, {AdoptRef{}, $7}, false); + $$ = new zeek::detail::WhenStmt({zeek::AdoptRef{}, $3}, {zeek::AdoptRef{}, $5}, + {zeek::AdoptRef{}, $10}, {zeek::AdoptRef{}, $7}, false); if ( $9 ) brofiler.DecIgnoreDepth(); } @@ -1554,15 +1555,15 @@ stmt: | TOK_RETURN TOK_WHEN '(' expr ')' stmt { set_location(@4, @6); - $$ = new zeek::detail::WhenStmt({AdoptRef{}, $4}, {AdoptRef{}, $6}, nullptr, + $$ = new zeek::detail::WhenStmt({zeek::AdoptRef{}, $4}, {zeek::AdoptRef{}, $6}, nullptr, nullptr, true); } | TOK_RETURN TOK_WHEN '(' expr ')' stmt TOK_TIMEOUT expr '{' opt_no_test_block stmt_list '}' { set_location(@4, @10); - $$ = new zeek::detail::WhenStmt({AdoptRef{}, $4}, {AdoptRef{}, $6}, - {AdoptRef{}, $11}, {AdoptRef{}, $8}, true); + $$ = new zeek::detail::WhenStmt({zeek::AdoptRef{}, $4}, {zeek::AdoptRef{}, $6}, + {zeek::AdoptRef{}, $11}, {zeek::AdoptRef{}, $8}, true); if ( $10 ) brofiler.DecIgnoreDepth(); } @@ -1570,8 +1571,8 @@ stmt: | index_slice '=' expr ';' opt_no_test { set_location(@1, @4); - $$ = new zeek::detail::ExprStmt(zeek::detail::get_assign_expr({AdoptRef{}, $1}, - {AdoptRef{}, $3}, in_init)); + $$ = new zeek::detail::ExprStmt(zeek::detail::get_assign_expr({zeek::AdoptRef{}, $1}, + {zeek::AdoptRef{}, $3}, in_init)); if ( ! $5 ) brofiler.AddStmt($$); @@ -1580,7 +1581,7 @@ stmt: | expr ';' opt_no_test { set_location(@1, @2); - $$ = new zeek::detail::ExprStmt({AdoptRef{}, $1}); + $$ = new zeek::detail::ExprStmt({zeek::AdoptRef{}, $1}); if ( ! $3 ) brofiler.AddStmt($$); } @@ -1610,7 +1611,7 @@ event: TOK_ID '(' opt_expr_list ')' { set_location(@1, @4); - const auto& id = lookup_ID($1, current_module.c_str()); + const auto& id = zeek::detail::lookup_ID($1, zeek::detail::current_module.c_str()); if ( id ) { @@ -1624,7 +1625,7 @@ event: reporter->Warning("%s", id->GetDeprecationWarning().c_str()); } - $$ = new zeek::detail::EventExpr($1, {AdoptRef{}, $3}); + $$ = new zeek::detail::EventExpr($1, {zeek::AdoptRef{}, $3}); } ; @@ -1637,13 +1638,13 @@ case_list: case: TOK_CASE expr_list ':' stmt_list - { $$ = new zeek::detail::Case({AdoptRef{}, $2}, 0, {AdoptRef{}, $4}); } + { $$ = new zeek::detail::Case({zeek::AdoptRef{}, $2}, 0, {zeek::AdoptRef{}, $4}); } | TOK_CASE case_type_list ':' stmt_list - { $$ = new zeek::detail::Case(nullptr, $2, {AdoptRef{}, $4}); } + { $$ = new zeek::detail::Case(nullptr, $2, {zeek::AdoptRef{}, $4}); } | TOK_DEFAULT ':' stmt_list - { $$ = new zeek::detail::Case(nullptr, 0, {AdoptRef{}, $3}); } + { $$ = new zeek::detail::Case(nullptr, 0, {zeek::AdoptRef{}, $3}); } ; case_type_list: @@ -1661,19 +1662,19 @@ case_type: TOK_TYPE type { $$ = new zeek::detail::ID(0, zeek::detail::SCOPE_FUNCTION, 0); - $$->SetType({AdoptRef{}, $2}); + $$->SetType({zeek::AdoptRef{}, $2}); } | TOK_TYPE type TOK_AS TOK_ID { const char* name = $4; - IntrusivePtr type{AdoptRef{}, $2}; - auto case_var = lookup_ID(name, current_module.c_str()); + zeek::TypePtr type{zeek::AdoptRef{}, $2}; + auto case_var = zeek::detail::lookup_ID(name, zeek::detail::current_module.c_str()); if ( case_var && case_var->IsGlobal() ) case_var->Error("already a global identifier"); else - case_var = install_ID(name, current_module.c_str(), false, false); + case_var = zeek::detail::install_ID(name, zeek::detail::current_module.c_str(), false, false); add_local(case_var, std::move(type), zeek::detail::INIT_NONE, nullptr, nullptr, VAR_REGULAR); @@ -1689,7 +1690,7 @@ for_head: // body so that we execute these actions - defining // the local variable - prior to parsing the body, // which might refer to the variable. - auto loop_var = lookup_ID($3, current_module.c_str()); + auto loop_var = zeek::detail::lookup_ID($3, zeek::detail::current_module.c_str()); if ( loop_var ) { @@ -1699,30 +1700,30 @@ for_head: else { - loop_var = install_ID($3, current_module.c_str(), - false, false); + loop_var = zeek::detail::install_ID($3, zeek::detail::current_module.c_str(), + false, false); } id_list* loop_vars = new id_list; loop_vars->push_back(loop_var.release()); - $$ = new zeek::detail::ForStmt(loop_vars, {AdoptRef{}, $5}); + $$ = new zeek::detail::ForStmt(loop_vars, {zeek::AdoptRef{}, $5}); } | TOK_FOR '(' '[' local_id_list ']' TOK_IN expr ')' { - $$ = new zeek::detail::ForStmt($4, {AdoptRef{}, $7}); + $$ = new zeek::detail::ForStmt($4, {zeek::AdoptRef{}, $7}); } | TOK_FOR '(' TOK_ID ',' TOK_ID TOK_IN expr ')' { set_location(@1, @8); - const char* module = current_module.c_str(); + const char* module = zeek::detail::current_module.c_str(); // Check for previous definitions of key and // value variables. - auto key_var = lookup_ID($3, module); - auto val_var = lookup_ID($5, module); + auto key_var = zeek::detail::lookup_ID($3, module); + auto val_var = zeek::detail::lookup_ID($5, module); // Validate previous definitions as needed. if ( key_var ) @@ -1731,7 +1732,7 @@ for_head: key_var->Error("global variable used in for loop"); } else - key_var = install_ID($3, module, false, false); + key_var = zeek::detail::install_ID($3, module, false, false); if ( val_var ) { @@ -1739,21 +1740,21 @@ for_head: val_var->Error("global variable used in for loop"); } else - val_var = install_ID($5, module, false, false); + val_var = zeek::detail::install_ID($5, module, false, false); id_list* loop_vars = new id_list; loop_vars->push_back(key_var.release()); - $$ = new zeek::detail::ForStmt(loop_vars, {AdoptRef{}, $7}, std::move(val_var)); + $$ = new zeek::detail::ForStmt(loop_vars, {zeek::AdoptRef{}, $7}, std::move(val_var)); } | TOK_FOR '(' '[' local_id_list ']' ',' TOK_ID TOK_IN expr ')' { set_location(@1, @10); - const char* module = current_module.c_str(); + const char* module = zeek::detail::current_module.c_str(); // Validate value variable - auto val_var = lookup_ID($7, module); + auto val_var = zeek::detail::lookup_ID($7, module); if ( val_var ) { @@ -1761,9 +1762,9 @@ for_head: val_var->Error("global variable used in for loop"); } else - val_var = install_ID($7, module, false, false); + val_var = zeek::detail::install_ID($7, module, false, false); - $$ = new zeek::detail::ForStmt($4, {AdoptRef{}, $9}, std::move(val_var)); + $$ = new zeek::detail::ForStmt($4, {zeek::AdoptRef{}, $9}, std::move(val_var)); } ; @@ -1781,7 +1782,7 @@ local_id: TOK_ID { set_location(@1); - auto id = lookup_ID($1, current_module.c_str()); + auto id = zeek::detail::lookup_ID($1, zeek::detail::current_module.c_str()); $$ = id.release(); if ( $$ ) @@ -1793,8 +1794,8 @@ local_id: else { - $$ = install_ID($1, current_module.c_str(), - false, is_export).release(); + $$ = zeek::detail::install_ID($1, zeek::detail::current_module.c_str(), + false, is_export).release(); } } ; @@ -1818,7 +1819,7 @@ global_or_event_id: TOK_ID { set_location(@1); - auto id = lookup_ID($1, current_module.c_str(), false, + auto id = zeek::detail::lookup_ID($1, zeek::detail::current_module.c_str(), false, defining_global_ID); $$ = id.release(); @@ -1843,10 +1844,10 @@ global_or_event_id: { const char* module_name = resolving_global_ID ? - current_module.c_str() : 0; + zeek::detail::current_module.c_str() : 0; - $$ = install_ID($1, module_name, - true, is_export).release(); + $$ = zeek::detail::install_ID($1, module_name, + true, is_export).release(); } } ; @@ -1856,7 +1857,7 @@ resolve_id: TOK_ID { set_location(@1); - auto id = lookup_ID($1, current_module.c_str()); + auto id = zeek::detail::lookup_ID($1, zeek::detail::current_module.c_str()); $$ = id.release(); if ( ! $$ ) @@ -1880,19 +1881,19 @@ opt_no_test_block: opt_deprecated: TOK_ATTR_DEPRECATED - { $$ = new zeek::detail::ConstExpr(make_intrusive("")); } + { $$ = new zeek::detail::ConstExpr(zeek::make_intrusive("")); } | TOK_ATTR_DEPRECATED '=' TOK_CONSTANT { if ( zeek::IsString($3->GetType()->Tag()) ) - $$ = new zeek::detail::ConstExpr({AdoptRef{}, $3}); + $$ = new zeek::detail::ConstExpr({zeek::AdoptRef{}, $3}); else { ODesc d; $3->Describe(&d); reporter->Error("'&deprecated=%s' must use a string literal", d.Description()); - $$ = new zeek::detail::ConstExpr(make_intrusive("")); + $$ = new zeek::detail::ConstExpr(zeek::make_intrusive("")); } } | diff --git a/src/plugin/ComponentManager.h b/src/plugin/ComponentManager.h index f503066a51..7d4d43533d 100644 --- a/src/plugin/ComponentManager.h +++ b/src/plugin/ComponentManager.h @@ -4,7 +4,6 @@ #include #include -#include "IntrusivePtr.h" #include "Type.h" #include "Var.h" // for add_type() #include "Val.h" @@ -52,7 +51,7 @@ public: /** * @return The enum type associated with the script-layer "Tag". */ - const IntrusivePtr& GetTagType() const; + const zeek::EnumTypePtr& GetTagType() const; [[deprecated("Remove in v4.1. Use GetTagType() instead.")]] zeek::EnumType* GetTagEnumType() const; @@ -71,7 +70,7 @@ public: * @param val A component's enum value. * @return The canonical component name. */ - const std::string& GetComponentName(IntrusivePtr val) const; + const std::string& GetComponentName(EnumValPtr val) const; [[deprecated("Remove in v4.1. Use IntrusivePtr argument instead.")]] const std::string& GetComponentName(Val* val) const; @@ -128,7 +127,7 @@ public: private: std::string module; /**< Script layer module in which component tags live. */ - IntrusivePtr tag_enum_type; /**< Enum type of component tags. */ + zeek::EnumTypePtr tag_enum_type; /**< Enum type of component tags. */ std::map components_by_name; std::map components_by_tag; std::map components_by_val; @@ -137,9 +136,9 @@ private: template ComponentManager::ComponentManager(const std::string& arg_module, const std::string& local_id) : module(arg_module), - tag_enum_type(make_intrusive(module + "::" + local_id)) + tag_enum_type(zeek::make_intrusive(module + "::" + local_id)) { - auto id = install_ID(local_id.c_str(), module.c_str(), true, true); + auto id = zeek::detail::install_ID(local_id.c_str(), module.c_str(), true, true); add_type(id.get(), tag_enum_type, nullptr); zeekygen_mgr->Identifier(std::move(id)); } @@ -163,7 +162,7 @@ std::list ComponentManager::GetComponents() const } template -const IntrusivePtr& ComponentManager::GetTagType() const +const zeek::EnumTypePtr& ComponentManager::GetTagType() const { return tag_enum_type; } @@ -193,7 +192,7 @@ const std::string& ComponentManager::GetComponentName(T tag) const } template -const std::string& ComponentManager::GetComponentName(IntrusivePtr val) const +const std::string& ComponentManager::GetComponentName(EnumValPtr val) const { return GetComponentName(T(std::move(val))); } @@ -201,7 +200,7 @@ const std::string& ComponentManager::GetComponentName(IntrusivePtr const std::string& ComponentManager::GetComponentName(Val* val) const { - return GetComponentName(T({NewRef{}, val->AsEnumVal()})); + return GetComponentName(T({zeek::NewRef{}, val->AsEnumVal()})); } template diff --git a/src/plugin/Manager.cc b/src/plugin/Manager.cc index 2c2abcd168..eaded40590 100644 --- a/src/plugin/Manager.cc +++ b/src/plugin/Manager.cc @@ -578,7 +578,7 @@ void Manager::RequestEvent(EventHandlerPtr handler, Plugin* plugin) handler->SetGenerateAlways(); } -void Manager::RequestBroObjDtor(BroObj* obj, Plugin* plugin) +void Manager::RequestBroObjDtor(Obj* obj, Plugin* plugin) { obj->NotifyPluginsOnDtor(); } @@ -616,8 +616,8 @@ int Manager::HookLoadFile(const Plugin::LoadType type, const string& file, const return rc; } -std::pair> -Manager::HookCallFunction(const Func* func, Frame* parent, +std::pair +Manager::HookCallFunction(const zeek::Func* func, zeek::detail::Frame* parent, zeek::Args* vecargs) const { HookArgumentList args; @@ -638,7 +638,7 @@ Manager::HookCallFunction(const Func* func, Frame* parent, hook_list* l = hooks[zeek::plugin::HOOK_CALL_FUNCTION]; - std::pair> rval{false, nullptr}; + std::pair rval{false, nullptr}; if ( l ) { @@ -865,9 +865,10 @@ bool Manager::HookLogWrite(const std::string& writer, } bool Manager::HookReporter(const std::string& prefix, const EventHandlerPtr event, - const Connection* conn, const val_list* addl, bool location, - const Location* location1, const Location* location2, - bool time, const std::string& message) + const Connection* conn, const val_list* addl, bool location, + const zeek::detail::Location* location1, + const zeek::detail::Location* location2, + bool time, const std::string& message) { HookArgumentList args; diff --git a/src/plugin/Manager.h b/src/plugin/Manager.h index 1831aa6710..bb3595d648 100644 --- a/src/plugin/Manager.h +++ b/src/plugin/Manager.h @@ -214,7 +214,7 @@ public: void RequestEvent(EventHandlerPtr handler, Plugin* plugin); /** - * Register interest in the destruction of a BroObj instance. When Bro's + * Register interest in the destruction of a Obj instance. When Bro's * reference counting triggers the objects destructor to run, the \a * HookBroObjDtor will be called. * @@ -222,7 +222,7 @@ public: * * @param plugin The plugin expressing interest. */ - void RequestBroObjDtor(BroObj* obj, Plugin* plugin); + void RequestBroObjDtor(Obj* obj, Plugin* plugin); // Hook entry functions. @@ -255,8 +255,8 @@ public: * it may be any Val and must be ignored). If no plugin handled the call, * the method returns null. */ - std::pair> - HookCallFunction(const Func* func, Frame* parent, zeek::Args* args) const; + std::pair + HookCallFunction(const zeek::Func* func, zeek::detail::Frame* parent, zeek::Args* args) const; /** * Hook that filters the queuing of an event. @@ -389,7 +389,7 @@ public: */ bool HookReporter(const std::string& prefix, const EventHandlerPtr event, const Connection* conn, const val_list* addl, bool location, - const Location* location1, const Location* location2, + const zeek::detail::Location* location1, const zeek::detail::Location* location2, bool time, const std::string& message); /** diff --git a/src/plugin/Plugin.cc b/src/plugin/Plugin.cc index 38da5d3767..a833637220 100644 --- a/src/plugin/Plugin.cc +++ b/src/plugin/Plugin.cc @@ -365,7 +365,7 @@ void Plugin::RequestEvent(EventHandlerPtr handler) plugin_mgr->RequestEvent(handler, this); } -void Plugin::RequestBroObjDtor(BroObj* obj) +void Plugin::RequestBroObjDtor(Obj* obj) { plugin_mgr->RequestBroObjDtor(obj, this); } @@ -375,8 +375,8 @@ int Plugin::HookLoadFile(const LoadType type, const std::string& file, const std return -1; } -std::pair> -Plugin::HookFunctionCall(const Func* func, Frame* parent, +std::pair +Plugin::HookFunctionCall(const zeek::Func* func, zeek::detail::Frame* parent, zeek::Args* args) { val_list vlargs(args->size()); @@ -390,14 +390,15 @@ Plugin::HookFunctionCall(const Func* func, Frame* parent, #pragma GCC diagnostic pop for ( auto i = 0u; i < args->size(); ++i ) - (*args)[i] = {AdoptRef{}, vlargs[i]}; + (*args)[i] = {zeek::AdoptRef{}, vlargs[i]}; - return {handled, {AdoptRef{}, result}}; + return {handled, {zeek::AdoptRef{}, result}}; } -std::pair Plugin::HookCallFunction(const Func* func, Frame *parent, val_list* args) +std::pair Plugin::HookCallFunction( + const zeek::Func* func, zeek::detail::Frame *parent, val_list* args) { - std::pair result(false, NULL); + std::pair result(false, NULL); return result; } @@ -440,7 +441,8 @@ bool Plugin::HookLogWrite(const std::string& writer, const std::string& filter, bool Plugin::HookReporter(const std::string& prefix, const EventHandlerPtr event, const Connection* conn, const val_list* addl, bool location, - const Location* location1, const Location* location2, + const zeek::detail::Location* location1, + const zeek::detail::Location* location2, bool time, const std::string& message) { return true; diff --git a/src/plugin/Plugin.h b/src/plugin/Plugin.h index 493fb21742..c0649c2b54 100644 --- a/src/plugin/Plugin.h +++ b/src/plugin/Plugin.h @@ -17,10 +17,18 @@ #define BRO_PLUGIN_BRO_VERSION BRO_VERSION_FUNCTION class ODesc; -class Frame; -class Func; class Event; + +ZEEK_FORWARD_DECLARE_NAMESPACED(Func, zeek); +ZEEK_FORWARD_DECLARE_NAMESPACED(Frame, zeek::detail); + +namespace zeek { template class IntrusivePtr; +using ValPtr = zeek::IntrusivePtr; +class Obj; +} + +using BroObj [[deprecated("Remove in v4.1. Use zeek::Obj instead.")]] = zeek::Obj; namespace threading { struct Field; @@ -196,7 +204,7 @@ public: /** * Constructor with a function argument. */ - explicit HookArgument(const Func* a) { type = FUNC; arg.func = a; } + explicit HookArgument(const zeek::Func* a) { type = FUNC; arg.func = a; } /** * Constructor with an integer argument. @@ -231,7 +239,7 @@ public: /** * Constructor with a Frame argument. */ - explicit HookArgument(Frame* f) { type = FRAME; arg.frame = f; } + explicit HookArgument(zeek::detail::Frame* f) { type = FRAME; arg.frame = f; } /** * Constructor with a WriterInfo argument. @@ -246,7 +254,7 @@ public: /** * Constructor with a location argument. */ - explicit HookArgument(const Location* location) { type = LOCATION; arg.loc = location; } + explicit HookArgument(const zeek::detail::Location* location) { type = LOCATION; arg.loc = location; } /** * Constructor with a zeek::Args argument. @@ -281,7 +289,7 @@ public: * Returns the value for a function argument. The argument's type must * match accordingly. */ - const Func* AsFunc() const { assert(type == FUNC); return arg.func; } + const zeek::Func* AsFunc() const { assert(type == FUNC); return arg.func; } /** * Returns the value for an integer argument. The argument's type must @@ -311,7 +319,7 @@ public: * Returns the value for a Bro frame argument. The argument's type must * match accordingly. */ - const Frame* AsFrame() const { assert(type == FRAME); return arg.frame; } + const zeek::detail::Frame* AsFrame() const { assert(type == FRAME); return arg.frame; } /** * Returns the value for a logging WriterInfo argument. The argument's type must @@ -361,15 +369,15 @@ private: double double_; const Event* event; const Connection* conn; - const Func* func; - const Frame* frame; + const zeek::Func* func; + const zeek::detail::Frame* frame; int int_; const Val* val; const val_list* vals; const zeek::Args* args; const void* voidp; const logging::WriterBackend::WriterInfo* winfo; - const Location* loc; + const zeek::detail::Location* loc; } arg; // Outside union because these have dtors. @@ -608,7 +616,7 @@ protected: void RequestEvent(EventHandlerPtr handler); /** - * Registers interest in the destruction of a BroObj instance. When + * Registers interest in the destruction of a Obj instance. When * Bro's reference counting triggers the objects destructor to run, * \a HookBroObjDtor will be called. * @@ -616,7 +624,7 @@ protected: * * @param handler The object being interested in. */ - void RequestBroObjDtor(BroObj* obj); + void RequestBroObjDtor(zeek::Obj* obj); // Hook functions. @@ -668,11 +676,11 @@ protected: * interpreter. If the plugin did not handle the call, it must return a * pair with the first member set to 'false' and null result value. */ - virtual std::pair> - HookFunctionCall(const Func* func, Frame* parent, zeek::Args* args); + virtual std::pair + HookFunctionCall(const zeek::Func* func, zeek::detail::Frame* parent, zeek::Args* args); [[deprecated("Remove in v4.1. Use HookFunctionCall()")]] - virtual std::pair HookCallFunction(const Func* func, Frame *parent, val_list* args); + virtual std::pair HookCallFunction(const zeek::Func* func, zeek::detail::Frame *parent, val_list* args); /** * Hook into raising events. Whenever the script interpreter is about @@ -824,7 +832,7 @@ protected: */ virtual bool HookReporter(const std::string& prefix, const EventHandlerPtr event, const Connection* conn, const val_list* addl, bool location, - const Location* location1, const Location* location2, + const zeek::detail::Location* location1, const zeek::detail::Location* location2, bool time, const std::string& message); // Meta hooks. diff --git a/src/probabilistic/Hasher.cc b/src/probabilistic/Hasher.cc index d1765c4fdf..835cb7e5d7 100644 --- a/src/probabilistic/Hasher.cc +++ b/src/probabilistic/Hasher.cc @@ -23,7 +23,7 @@ Hasher::seed_t Hasher::MakeSeed(const void* data, size_t size) assert(sizeof(tmpseed) == 16); - static auto global_hash_seed = zeek::id::find_val("global_hash_seed"); + static auto global_hash_seed = zeek::id::find_val("global_hash_seed"); if ( data ) hash_update(ctx, data, size); @@ -178,4 +178,3 @@ bool DoubleHasher::Equals(const Hasher* other) const const DoubleHasher* o = static_cast(other); return h1 == o->h1 && h2 == o->h2; } - diff --git a/src/probabilistic/Topk.cc b/src/probabilistic/Topk.cc index 1cd1027b1e..b09dafe54b 100644 --- a/src/probabilistic/Topk.cc +++ b/src/probabilistic/Topk.cc @@ -6,7 +6,6 @@ #include "broker/Data.h" #include "CompHash.h" -#include "IntrusivePtr.h" #include "Reporter.h" #include "Dict.h" @@ -18,11 +17,11 @@ static void topk_element_hash_delete_func(void* val) delete e; } -void TopkVal::Typify(IntrusivePtr t) +void TopkVal::Typify(zeek::TypePtr t) { assert(!hash && !type); type = std::move(t); - auto tl = make_intrusive(type); + auto tl = zeek::make_intrusive(type); tl->Append(type); hash = new CompositeHash(std::move(tl)); } @@ -36,7 +35,7 @@ HashKey* TopkVal::GetHash(Val* v) const TopkVal::TopkVal(uint64_t arg_size) : OpaqueVal(topk_type) { - elementDict = new PDict; + elementDict = new zeek::PDict; elementDict->SetDeleteFunc(topk_element_hash_delete_func); size = arg_size; numElements = 0; @@ -46,7 +45,7 @@ TopkVal::TopkVal(uint64_t arg_size) : OpaqueVal(topk_type) TopkVal::TopkVal() : OpaqueVal(topk_type) { - elementDict = new PDict; + elementDict = new zeek::PDict; elementDict->SetDeleteFunc(topk_element_hash_delete_func); size = 0; numElements = 0; @@ -176,14 +175,14 @@ void TopkVal::Merge(const TopkVal* value, bool doPrune) } } -IntrusivePtr TopkVal::DoClone(CloneState* state) +zeek::ValPtr TopkVal::DoClone(CloneState* state) { - auto clone = make_intrusive(size); + auto clone = zeek::make_intrusive(size); clone->Merge(this); return state->NewClone(this, std::move(clone)); } -IntrusivePtr TopkVal::GetTopK(int k) const // returns vector +zeek::VectorValPtr TopkVal::GetTopK(int k) const // returns vector { if ( numElements == 0 ) { @@ -191,8 +190,8 @@ IntrusivePtr TopkVal::GetTopK(int k) const // returns vector return nullptr; } - auto v = make_intrusive(type); - auto t = make_intrusive(std::move(v)); + auto v = zeek::make_intrusive(type); + auto t = zeek::make_intrusive(std::move(v)); // this does no estimation if the results is correct! // in any case - just to make this future-proof (and I am lazy) - this can return more than k. @@ -269,7 +268,7 @@ uint64_t TopkVal::GetSum() const return sum; } -void TopkVal::Encountered(IntrusivePtr encountered) +void TopkVal::Encountered(zeek::ValPtr encountered) { // ok, let's see if we already know this one. diff --git a/src/probabilistic/Topk.h b/src/probabilistic/Topk.h index 24db217a59..c3b47277e1 100644 --- a/src/probabilistic/Topk.h +++ b/src/probabilistic/Topk.h @@ -27,11 +27,11 @@ struct Bucket { struct Element { uint64_t epsilon; - IntrusivePtr value; + zeek::ValPtr value; Bucket* parent; }; -class TopkVal : public OpaqueVal { +class TopkVal : public zeek::OpaqueVal { public: /** @@ -55,7 +55,7 @@ public: * * @param value The encountered element */ - void Encountered(IntrusivePtr value); + void Encountered(zeek::ValPtr value); /** * Get the first *k* elements of the result vector. At the moment, @@ -66,7 +66,7 @@ public: * * @returns The top-k encountered elements */ - IntrusivePtr GetTopK(int k) const; + zeek::VectorValPtr GetTopK(int k) const; /** * Get the current count tracked in the top-k data structure for a @@ -125,7 +125,7 @@ public: * * @returns cloned TopkVal */ - IntrusivePtr DoClone(CloneState* state) override; + zeek::ValPtr DoClone(CloneState* state) override; DECLARE_OPAQUE_VALUE(TopkVal) @@ -153,7 +153,7 @@ private: * @returns HashKey for value */ HashKey* GetHash(Val* v) const; // this probably should go somewhere else. - HashKey* GetHash(const IntrusivePtr& v) const + HashKey* GetHash(const zeek::ValPtr& v) const { return GetHash(v.get()); } /** @@ -161,12 +161,12 @@ private: * * @param t type that is tracked */ - void Typify(IntrusivePtr t); + void Typify(zeek::TypePtr t); - IntrusivePtr type; + zeek::TypePtr type; CompositeHash* hash; std::list buckets; - PDict* elementDict; + zeek::PDict* elementDict; uint64_t size; // how many elements are we tracking? uint64_t numElements; // how many elements do we have at the moment bool pruned; // was this data structure pruned? diff --git a/src/probabilistic/bloom-filter.bif b/src/probabilistic/bloom-filter.bif index b8c4592c8d..1ca5a4fdbb 100644 --- a/src/probabilistic/bloom-filter.bif +++ b/src/probabilistic/bloom-filter.bif @@ -46,7 +46,7 @@ function bloomfilter_basic_init%(fp: double, capacity: count, name->Len()); const Hasher* h = new DoubleHasher(optimal_k, seed); - return make_intrusive(new BasicBloomFilter(h, cells)); + return zeek::make_intrusive(new BasicBloomFilter(h, cells)); %} ## Creates a basic Bloom filter. This function serves as a low-level @@ -86,7 +86,7 @@ function bloomfilter_basic_init2%(k: count, cells: count, name->Len()); const Hasher* h = new DoubleHasher(k, seed); - return make_intrusive(new BasicBloomFilter(h, cells)); + return zeek::make_intrusive(new BasicBloomFilter(h, cells)); %} ## Creates a counting Bloom filter. @@ -130,7 +130,7 @@ function bloomfilter_counting_init%(k: count, cells: count, max: count, while ( max >>= 1 ) ++width; - return make_intrusive(new CountingBloomFilter(h, cells, width)); + return zeek::make_intrusive(new CountingBloomFilter(h, cells, width)); %} ## Adds an element to a Bloom filter. @@ -139,8 +139,8 @@ function bloomfilter_counting_init%(k: count, cells: count, max: count, ## ## x: The element to add. ## -## .. zeek:see:: bloomfilter_basic_init bloomfilter_basic_init2 -## bloomfilter_counting_init bloomfilter_lookup bloomfilter_clear +## .. zeek:see:: bloomfilter_basic_init bloomfilter_basic_init2 +## bloomfilter_counting_init bloomfilter_lookup bloomfilter_clear ## bloomfilter_merge function bloomfilter_add%(bf: opaque of bloomfilter, x: any%): any %{ @@ -174,15 +174,15 @@ function bloomfilter_lookup%(bf: opaque of bloomfilter, x: any%): count const BloomFilterVal* bfv = static_cast(bf); if ( ! bfv->Type() ) - return val_mgr->Count(0); + return zeek::val_mgr->Count(0); else if ( ! same_type(bfv->Type(), x->GetType()) ) reporter->Error("incompatible Bloom filter types"); else - return val_mgr->Count(static_cast(bfv->Count(x))); + return zeek::val_mgr->Count(static_cast(bfv->Count(x))); - return val_mgr->Count(0); + return zeek::val_mgr->Count(0); %} ## Removes all elements from a Bloom filter. This function resets all bits in @@ -238,12 +238,12 @@ function bloomfilter_merge%(bf1: opaque of bloomfilter, ## Returns a string with a representation of a Bloom filter's internal ## state. This is for debugging/testing purposes only. -## +## ## bf: The Bloom filter handle. ## ## Returns: a string with a representation of a Bloom filter's internal state. function bloomfilter_internal_state%(bf: opaque of bloomfilter%): string %{ BloomFilterVal* bfv = static_cast(bf); - return make_intrusive(bfv->InternalState()); + return zeek::make_intrusive(bfv->InternalState()); %} diff --git a/src/probabilistic/cardinality-counter.bif b/src/probabilistic/cardinality-counter.bif index 6b4804b748..8069003c2b 100644 --- a/src/probabilistic/cardinality-counter.bif +++ b/src/probabilistic/cardinality-counter.bif @@ -23,7 +23,7 @@ module GLOBAL; function hll_cardinality_init%(err: double, confidence: double%): opaque of cardinality %{ CardinalityCounter* c = new CardinalityCounter(err, confidence); - auto cv = make_intrusive(c); + auto cv = zeek::make_intrusive(c); return cv; %} @@ -45,17 +45,17 @@ function hll_cardinality_add%(handle: opaque of cardinality, elem: any%): bool if ( ! cv->Type() && ! cv->Typify(elem->GetType()) ) { reporter->Error("failed to set HLL type"); - return val_mgr->False(); + return zeek::val_mgr->False(); } else if ( ! same_type(cv->Type(), elem->GetType()) ) { reporter->Error("incompatible HLL data type"); - return val_mgr->False(); + return zeek::val_mgr->False(); } cv->Add(elem); - return val_mgr->True(); + return zeek::val_mgr->True(); %} ## Merges a HLL cardinality counter into another. @@ -82,7 +82,7 @@ function hll_cardinality_merge_into%(handle1: opaque of cardinality, handle2: op ! same_type(v1->Type(), v2->Type()) ) { reporter->Error("incompatible HLL types"); - return val_mgr->False(); + return zeek::val_mgr->False(); } CardinalityCounter* h1 = v1->Get(); @@ -92,10 +92,10 @@ function hll_cardinality_merge_into%(handle1: opaque of cardinality, handle2: op if ( ! res ) { reporter->Error("Cardinality counters with different parameters cannot be merged"); - return val_mgr->False(); + return zeek::val_mgr->False(); } - return val_mgr->True(); + return zeek::val_mgr->True(); %} ## Estimate the current cardinality of an HLL cardinality counter. @@ -113,7 +113,7 @@ function hll_cardinality_estimate%(handle: opaque of cardinality%): double double estimate = h->Size(); - return make_intrusive(estimate); + return zeek::make_intrusive(estimate); %} ## Copy a HLL cardinality counter. @@ -129,7 +129,7 @@ function hll_cardinality_copy%(handle: opaque of cardinality%): opaque of cardin CardinalityVal* cv = static_cast(handle); CardinalityCounter* h = cv->Get(); CardinalityCounter* h2 = new CardinalityCounter(*h); - auto out = make_intrusive(h2); + auto out = zeek::make_intrusive(h2); return out; %} diff --git a/src/probabilistic/top-k.bif b/src/probabilistic/top-k.bif index 947b514c08..64faeaa31b 100644 --- a/src/probabilistic/top-k.bif +++ b/src/probabilistic/top-k.bif @@ -14,7 +14,7 @@ ## topk_size topk_sum topk_merge topk_merge_prune function topk_init%(size: count%): opaque of topk %{ - auto v = make_intrusive(size); + auto v = zeek::make_intrusive(size); return v; %} @@ -34,7 +34,7 @@ function topk_add%(handle: opaque of topk, value: any%): any %{ assert(handle); probabilistic::TopkVal* h = (probabilistic::TopkVal*) handle; - h->Encountered({NewRef{}, value}); + h->Encountered({zeek::NewRef{}, value}); return nullptr; %} @@ -74,7 +74,7 @@ function topk_count%(handle: opaque of topk, value: any%): count %{ assert(handle); probabilistic::TopkVal* h = (probabilistic::TopkVal*) handle; - return val_mgr->Count(h->GetCount(value)); + return zeek::val_mgr->Count(h->GetCount(value)); %} ## Get the maximal overestimation for count. @@ -94,7 +94,7 @@ function topk_epsilon%(handle: opaque of topk, value: any%): count %{ assert(handle); probabilistic::TopkVal* h = (probabilistic::TopkVal*) handle; - return val_mgr->Count(h->GetEpsilon(value)); + return zeek::val_mgr->Count(h->GetEpsilon(value)); %} ## Get the number of elements this data structure is supposed to track (given @@ -113,7 +113,7 @@ function topk_size%(handle: opaque of topk%): count %{ assert(handle); probabilistic::TopkVal* h = (probabilistic::TopkVal*) handle; - return val_mgr->Count(h->GetSize()); + return zeek::val_mgr->Count(h->GetSize()); %} ## Get the sum of all counts of all elements in the data structure. @@ -133,7 +133,7 @@ function topk_sum%(handle: opaque of topk%): count %{ assert(handle); probabilistic::TopkVal* h = (probabilistic::TopkVal*) handle; - return val_mgr->Count(h->GetSum()); + return zeek::val_mgr->Count(h->GetSum()); %} ## Merge the second top-k data structure into the first. diff --git a/src/reporter.bif b/src/reporter.bif index 2133bd7d00..00f9d5ad11 100644 --- a/src/reporter.bif +++ b/src/reporter.bif @@ -25,7 +25,7 @@ function Reporter::info%(msg: string%): bool reporter->PushLocation(frame->GetCall()->GetLocationInfo()); reporter->Info("%s", msg->CheckString()); reporter->PopLocation(); - return val_mgr->True(); + return zeek::val_mgr->True(); %} ## Generates a message that warns of a potential problem. @@ -40,7 +40,7 @@ function Reporter::warning%(msg: string%): bool reporter->PushLocation(frame->GetCall()->GetLocationInfo()); reporter->Warning("%s", msg->CheckString()); reporter->PopLocation(); - return val_mgr->True(); + return zeek::val_mgr->True(); %} ## Generates a non-fatal error indicative of a definite problem that should @@ -56,7 +56,7 @@ function Reporter::error%(msg: string%): bool reporter->PushLocation(frame->GetCall()->GetLocationInfo()); reporter->Error("%s", msg->CheckString()); reporter->PopLocation(); - return val_mgr->True(); + return zeek::val_mgr->True(); %} ## Generates a fatal error on stderr and terminates program execution. @@ -69,7 +69,7 @@ function Reporter::fatal%(msg: string%): bool reporter->PushLocation(frame->GetCall()->GetLocationInfo()); reporter->FatalError("%s", msg->CheckString()); reporter->PopLocation(); - return val_mgr->True(); + return zeek::val_mgr->True(); %} ## Generates a fatal error on stderr and terminates program execution @@ -83,7 +83,7 @@ function Reporter::fatal_error_with_core%(msg: string%): bool reporter->PushLocation(frame->GetCall()->GetLocationInfo()); reporter->FatalErrorWithCore("%s", msg->CheckString()); reporter->PopLocation(); - return val_mgr->True(); + return zeek::val_mgr->True(); %} ## Generates a "net" weird. @@ -94,7 +94,7 @@ function Reporter::fatal_error_with_core%(msg: string%): bool function Reporter::net_weird%(name: string%): bool %{ reporter->Weird(name->CheckString()); - return val_mgr->True(); + return zeek::val_mgr->True(); %} ## Generates a "flow" weird. @@ -109,7 +109,7 @@ function Reporter::net_weird%(name: string%): bool function Reporter::flow_weird%(name: string, orig: addr, resp: addr%): bool %{ reporter->Weird(orig->AsAddr(), resp->AsAddr(), name->CheckString()); - return val_mgr->True(); + return zeek::val_mgr->True(); %} ## Generates a "conn" weird. @@ -134,7 +134,7 @@ function Reporter::conn_weird%(name: string, c: connection, addl: string &defaul name->CheckString(), addl->CheckString()); } - return val_mgr->True(); + return zeek::val_mgr->True(); %} ## Generates a "file" weird. @@ -152,10 +152,10 @@ function Reporter::file_weird%(name: string, f: fa_file, addl: string &default=" auto file = file_mgr->LookupFile(fuid->CheckString()); if ( ! file ) - return val_mgr->False(); + return zeek::val_mgr->False(); reporter->Weird(file, name->CheckString(), addl->CheckString()); - return val_mgr->True(); + return zeek::val_mgr->True(); %} ## Gets the weird sampling whitelist @@ -163,10 +163,10 @@ function Reporter::file_weird%(name: string, f: fa_file, addl: string &default=" ## Returns: Current weird sampling whitelist function Reporter::get_weird_sampling_whitelist%(%): string_set %{ - auto set = make_intrusive(zeek::id::string_set); + auto set = zeek::make_intrusive(zeek::id::string_set); for ( auto el : reporter->GetWeirdSamplingWhitelist() ) { - auto idx = make_intrusive(el); + auto idx = zeek::make_intrusive(el); set->Assign(std::move(idx), nullptr); } return set; @@ -195,7 +195,7 @@ function Reporter::set_weird_sampling_whitelist%(weird_sampling_whitelist: strin delete k; } reporter->SetWeirdSamplingWhitelist(whitelist_set); - return val_mgr->True(); + return zeek::val_mgr->True(); %} ## Gets the current weird sampling threshold @@ -203,7 +203,7 @@ function Reporter::set_weird_sampling_whitelist%(weird_sampling_whitelist: strin ## Returns: current weird sampling threshold. function Reporter::get_weird_sampling_threshold%(%) : count %{ - return val_mgr->Count(reporter->GetWeirdSamplingThreshold()); + return zeek::val_mgr->Count(reporter->GetWeirdSamplingThreshold()); %} ## Sets the current weird sampling threshold @@ -214,7 +214,7 @@ function Reporter::get_weird_sampling_threshold%(%) : count function Reporter::set_weird_sampling_threshold%(weird_sampling_threshold: count%) : bool %{ reporter->SetWeirdSamplingThreshold(weird_sampling_threshold); - return val_mgr->True(); + return zeek::val_mgr->True(); %} @@ -223,7 +223,7 @@ function Reporter::set_weird_sampling_threshold%(weird_sampling_threshold: count ## Returns: weird sampling rate. function Reporter::get_weird_sampling_rate%(%) : count %{ - return val_mgr->Count(reporter->GetWeirdSamplingRate()); + return zeek::val_mgr->Count(reporter->GetWeirdSamplingRate()); %} ## Sets the weird sampling rate. @@ -234,7 +234,7 @@ function Reporter::get_weird_sampling_rate%(%) : count function Reporter::set_weird_sampling_rate%(weird_sampling_rate: count%) : bool %{ reporter->SetWeirdSamplingRate(weird_sampling_rate); - return val_mgr->True(); + return zeek::val_mgr->True(); %} ## Gets the current weird sampling duration. @@ -242,7 +242,7 @@ function Reporter::set_weird_sampling_rate%(weird_sampling_rate: count%) : bool ## Returns: weird sampling duration. function Reporter::get_weird_sampling_duration%(%) : interval %{ - return make_intrusive(reporter->GetWeirdSamplingDuration()); + return zeek::make_intrusive(reporter->GetWeirdSamplingDuration()); %} ## Sets the current weird sampling duration. Please note that @@ -254,5 +254,5 @@ function Reporter::get_weird_sampling_duration%(%) : interval function Reporter::set_weird_sampling_duration%(weird_sampling_duration: interval%) : bool %{ reporter->SetWeirdSamplingDuration(weird_sampling_duration); - return val_mgr->True(); + return zeek::val_mgr->True(); %} diff --git a/src/rule-parse.y b/src/rule-parse.y index 34199c1443..b15763614a 100644 --- a/src/rule-parse.y +++ b/src/rule-parse.y @@ -104,7 +104,7 @@ rule_list: rule: TOK_SIGNATURE TOK_IDENT { - Location l(current_rule_file, rules_line_number+1, 0, 0, 0); + zeek::detail::Location l(current_rule_file, rules_line_number+1, 0, 0, 0); current_rule = new Rule(yylval.str, l); } '{' rule_attr_list '}' @@ -440,7 +440,7 @@ void rules_error(const char* msg, const char* addl) void rules_error(Rule* r, const char* msg) { - const Location& l = r->GetLocation(); + const zeek::detail::Location& l = r->GetLocation(); reporter->Error("Error in signature %s (%s:%d): %s\n", r->ID(), l.filename, l.first_line, msg); rule_matcher->SetParseError(); diff --git a/src/scan.l b/src/scan.l index abc3247e71..c4fa68cd9b 100644 --- a/src/scan.l +++ b/src/scan.l @@ -15,7 +15,7 @@ #include "input.h" #include "util.h" #include "Scope.h" -#include "BroString.h" +#include "ZeekString.h" #include "DNS_Mgr.h" #include "Expr.h" #include "Func.h" @@ -139,7 +139,7 @@ public: // A stack of input buffers we're scanning. file_stack[len-1] is the // top of the stack. -static PList file_stack; +static zeek::PList file_stack; #define RET_CONST(v) \ { \ @@ -179,7 +179,7 @@ ESCSEQ (\\([^\n]|[0-7]+|x[[:xdigit:]]+)) ##<.* { std::string hint(cur_enum_type && last_id_tok ? - make_full_var_name(current_module.c_str(), last_id_tok) : ""); + make_full_var_name(zeek::detail::current_module.c_str(), last_id_tok) : ""); zeekygen_mgr->PostComment(yytext + 3, hint); } @@ -203,22 +203,22 @@ ESCSEQ (\\([^\n]|[0-7]+|x[[:xdigit:]]+)) /* IPv6 literal constant patterns */ {IP6} { - RET_CONST(new AddrVal(extract_ip(yytext))) + RET_CONST(new zeek::AddrVal(extract_ip(yytext))) } {IP6}{OWS}"/"{OWS}{D} { int len = 0; std::string ip = extract_ip_and_len(yytext, &len); - RET_CONST(new SubNetVal(IPPrefix(IPAddr(ip), len, true))) + RET_CONST(new zeek::SubNetVal(IPPrefix(IPAddr(ip), len, true))) } /* IPv4 literal constant patterns */ -({D}"."){3}{D} RET_CONST(new AddrVal(yytext)) +({D}"."){3}{D} RET_CONST(new zeek::AddrVal(yytext)) ({D}"."){3}{D}{OWS}"/"{OWS}{D} { int len = 0; std::string ip = extract_ip_and_len(yytext, &len); - RET_CONST(new SubNetVal(IPPrefix(IPAddr(ip), len))) + RET_CONST(new zeek::SubNetVal(IPPrefix(IPAddr(ip), len))) } [!%*/+\-,:;<=>?()\[\]{}~$|&^] return yytext[0]; @@ -346,11 +346,11 @@ when return TOK_WHEN; rval = std::string(path) + "/" + rval; } - RET_CONST(new StringVal(rval.c_str())); + RET_CONST(new zeek::StringVal(rval.c_str())); } @FILENAME { - RET_CONST(new StringVal(SafeBasename(::filename).result)); + RET_CONST(new zeek::StringVal(SafeBasename(::filename).result)); } @load{WS}{FILE} { @@ -468,8 +468,8 @@ when return TOK_WHEN; [^@\n]+ /* eat */ . /* eat */ -T RET_CONST(val_mgr->True()->Ref()) -F RET_CONST(val_mgr->False()->Ref()) +T RET_CONST(zeek::val_mgr->True()->Ref()) +F RET_CONST(zeek::val_mgr->False()->Ref()) {ID} { yylval.str = copy_string(yytext); @@ -478,9 +478,9 @@ F RET_CONST(val_mgr->False()->Ref()) } {D} { - RET_CONST(val_mgr->Count(static_cast(strtoull(yytext, (char**) NULL, 10))).release()) + RET_CONST(zeek::val_mgr->Count(static_cast(strtoull(yytext, (char**) NULL, 10))).release()) } -{FLOAT} RET_CONST(new DoubleVal(atof(yytext))) +{FLOAT} RET_CONST(new zeek::DoubleVal(atof(yytext))) {D}"/tcp" { uint32_t p = atoi(yytext); @@ -489,7 +489,7 @@ F RET_CONST(val_mgr->False()->Ref()) reporter->Error("bad port number - %s", yytext); p = 0; } - RET_CONST(val_mgr->Port(p, TRANSPORT_TCP)->Ref()) + RET_CONST(zeek::val_mgr->Port(p, TRANSPORT_TCP)->Ref()) } {D}"/udp" { uint32_t p = atoi(yytext); @@ -498,7 +498,7 @@ F RET_CONST(val_mgr->False()->Ref()) reporter->Error("bad port number - %s", yytext); p = 0; } - RET_CONST(val_mgr->Port(p, TRANSPORT_UDP)->Ref()) + RET_CONST(zeek::val_mgr->Port(p, TRANSPORT_UDP)->Ref()) } {D}"/icmp" { uint32_t p = atoi(yytext); @@ -507,7 +507,7 @@ F RET_CONST(val_mgr->False()->Ref()) reporter->Error("bad port number - %s", yytext); p = 0; } - RET_CONST(val_mgr->Port(p, TRANSPORT_ICMP)->Ref()) + RET_CONST(zeek::val_mgr->Port(p, TRANSPORT_ICMP)->Ref()) } {D}"/unknown" { uint32_t p = atoi(yytext); @@ -516,17 +516,17 @@ F RET_CONST(val_mgr->False()->Ref()) reporter->Error("bad port number - %s", yytext); p = 0; } - RET_CONST(val_mgr->Port(p, TRANSPORT_UNKNOWN)->Ref()) + RET_CONST(zeek::val_mgr->Port(p, TRANSPORT_UNKNOWN)->Ref()) } -{FLOAT}{OWS}day(s?) RET_CONST(new IntervalVal(atof(yytext),Days)) -{FLOAT}{OWS}hr(s?) RET_CONST(new IntervalVal(atof(yytext),Hours)) -{FLOAT}{OWS}min(s?) RET_CONST(new IntervalVal(atof(yytext),Minutes)) -{FLOAT}{OWS}sec(s?) RET_CONST(new IntervalVal(atof(yytext),Seconds)) -{FLOAT}{OWS}msec(s?) RET_CONST(new IntervalVal(atof(yytext),Milliseconds)) -{FLOAT}{OWS}usec(s?) RET_CONST(new IntervalVal(atof(yytext),Microseconds)) +{FLOAT}{OWS}day(s?) RET_CONST(new zeek::IntervalVal(atof(yytext),Days)) +{FLOAT}{OWS}hr(s?) RET_CONST(new zeek::IntervalVal(atof(yytext),Hours)) +{FLOAT}{OWS}min(s?) RET_CONST(new zeek::IntervalVal(atof(yytext),Minutes)) +{FLOAT}{OWS}sec(s?) RET_CONST(new zeek::IntervalVal(atof(yytext),Seconds)) +{FLOAT}{OWS}msec(s?) RET_CONST(new zeek::IntervalVal(atof(yytext),Milliseconds)) +{FLOAT}{OWS}usec(s?) RET_CONST(new zeek::IntervalVal(atof(yytext),Microseconds)) -"0x"{HEX}+ RET_CONST(val_mgr->Count(static_cast(strtoull(yytext, 0, 16))).release()) +"0x"{HEX}+ RET_CONST(zeek::val_mgr->Count(static_cast(strtoull(yytext, 0, 16))).release()) {H}("."{H})+ RET_CONST(dns_mgr->LookupHost(yytext).release()) @@ -560,7 +560,7 @@ F RET_CONST(val_mgr->False()->Ref()) s[i-1] = '\0'; - RET_CONST(new StringVal(new BroString(1, (byte_vec) s, i-1))) + RET_CONST(new zeek::StringVal(new zeek::String(1, (zeek::byte_vec) s, i-1))) } ([^/\\\n]|{ESCSEQ})+ { @@ -693,7 +693,7 @@ static int load_files(const char* orig_file) // was done when we're finished processing it. if ( ! did_module_restore ) { - file_stack.push_back(new FileInfo(current_module)); + file_stack.push_back(new FileInfo(zeek::detail::current_module)); did_module_restore = true; } else @@ -710,7 +710,7 @@ static int load_files(const char* orig_file) yylloc.first_line = yylloc.last_line = line_number = 1; // Don't delete the old filename - it's pointed to by - // every BroObj created when parsing it. + // every Obj created when parsing it. yylloc.filename = filename = copy_string(file_path.c_str()); return 1; @@ -749,7 +749,7 @@ void do_atif(zeek::detail::Expr* expr) LocalNameFinder cb; expr->Traverse(&cb); - IntrusivePtr val; + zeek::ValPtr val; if ( cb.local_names.empty() ) val = expr->Eval(nullptr); @@ -776,7 +776,7 @@ void do_atifdef(const char* id) { ++current_depth; - const auto& i = lookup_ID(id, current_module.c_str()); + const auto& i = zeek::detail::lookup_ID(id, zeek::detail::current_module.c_str()); if ( ! i ) { @@ -789,7 +789,7 @@ void do_atifndef(const char *id) { ++current_depth; - const auto& i = lookup_ID(id, current_module.c_str()); + const auto& i = zeek::detail::lookup_ID(id, zeek::detail::current_module.c_str()); if ( i ) { @@ -835,8 +835,8 @@ void do_atendif() // Be careful to never delete things from this list, as the strings // are referred to (in order to save the locations of tokens and statements, // for error reporting and debugging). -static name_list input_files; -static name_list essential_input_files; +static zeek::name_list input_files; +static zeek::name_list essential_input_files; void add_essential_input_file(const char* file) { @@ -871,7 +871,7 @@ void add_input_file_at_front(const char* file) input_files.push_front(copy_string(file)); } -void add_to_name_list(char* s, char delim, name_list& nl) +void add_to_name_list(char* s, char delim, zeek::name_list& nl) { while ( s ) { @@ -917,13 +917,13 @@ int yywrap() // Stack is now empty. while ( essential_input_files.length() > 0 || input_files.length() > 0 ) { - name_list& files = essential_input_files.length() > 0 ? + zeek::name_list& files = essential_input_files.length() > 0 ? essential_input_files : input_files; if ( load_files(files[0]) ) { // Don't delete the filename - it's pointed to by - // every BroObj created when parsing it. + // every Obj created when parsing it. (void) files.remove_nth(0); return 0; } @@ -1077,5 +1077,5 @@ FileInfo::~FileInfo() yylloc.first_line = yylloc.last_line = line_number = line; if ( restore_module != "" ) - current_module = restore_module; + zeek::detail::current_module = restore_module; } diff --git a/src/stats.bif b/src/stats.bif index 901f62a223..5aa667619e 100644 --- a/src/stats.bif +++ b/src/stats.bif @@ -4,19 +4,19 @@ #include "threading/Manager.h" #include "broker/Manager.h" -IntrusivePtr ProcStats; -IntrusivePtr NetStats; -IntrusivePtr MatcherStats; -IntrusivePtr ReassemblerStats; -IntrusivePtr DNSStats; -IntrusivePtr ConnStats; -IntrusivePtr GapStats; -IntrusivePtr EventStats; -IntrusivePtr ThreadStats; -IntrusivePtr TimerStats; -IntrusivePtr FileAnalysisStats; -IntrusivePtr BrokerStats; -IntrusivePtr ReporterStats; +zeek::RecordTypePtr ProcStats; +zeek::RecordTypePtr NetStats; +zeek::RecordTypePtr MatcherStats; +zeek::RecordTypePtr ReassemblerStats; +zeek::RecordTypePtr DNSStats; +zeek::RecordTypePtr ConnStats; +zeek::RecordTypePtr GapStats; +zeek::RecordTypePtr EventStats; +zeek::RecordTypePtr ThreadStats; +zeek::RecordTypePtr TimerStats; +zeek::RecordTypePtr FileAnalysisStats; +zeek::RecordTypePtr BrokerStats; +zeek::RecordTypePtr ReporterStats; %%} ## Returns packet capture statistics. Statistics include the number of @@ -54,13 +54,13 @@ function get_net_stats%(%): NetStats bytes_recv += stat.bytes_received; } - auto r = make_intrusive(NetStats); + auto r = zeek::make_intrusive(NetStats); int n = 0; - r->Assign(n++, val_mgr->Count(recv)); - r->Assign(n++, val_mgr->Count(drop)); - r->Assign(n++, val_mgr->Count(link)); - r->Assign(n++, val_mgr->Count(bytes_recv)); + r->Assign(n++, zeek::val_mgr->Count(recv)); + r->Assign(n++, zeek::val_mgr->Count(drop)); + r->Assign(n++, zeek::val_mgr->Count(link)); + r->Assign(n++, zeek::val_mgr->Count(bytes_recv)); return r; %} @@ -83,19 +83,19 @@ function get_net_stats%(%): NetStats ## get_reporter_stats function get_conn_stats%(%): ConnStats %{ - auto r = make_intrusive(ConnStats); + auto r = zeek::make_intrusive(ConnStats); int n = 0; - r->Assign(n++, val_mgr->Count(Connection::TotalConnections())); - r->Assign(n++, val_mgr->Count(Connection::CurrentConnections())); - r->Assign(n++, val_mgr->Count(sessions->CurrentConnections())); + r->Assign(n++, zeek::val_mgr->Count(Connection::TotalConnections())); + r->Assign(n++, zeek::val_mgr->Count(Connection::CurrentConnections())); + r->Assign(n++, zeek::val_mgr->Count(sessions->CurrentConnections())); SessionStats s; if ( sessions ) sessions->GetStats(s); #define ADD_STAT(x) \ - r->Assign(n++, val_mgr->Count(unsigned(sessions ? x : 0))); + r->Assign(n++, zeek::val_mgr->Count(unsigned(sessions ? x : 0))); ADD_STAT(s.num_packets); ADD_STAT(s.num_fragments); @@ -110,7 +110,7 @@ function get_conn_stats%(%): ConnStats ADD_STAT(s.max_ICMP_conns); ADD_STAT(s.cumulative_ICMP_conns); - r->Assign(n++, val_mgr->Count(killed_by_inactivity)); + r->Assign(n++, zeek::val_mgr->Count(killed_by_inactivity)); return r; %} @@ -137,7 +137,7 @@ function get_proc_stats%(%): ProcStats if ( getrusage(RUSAGE_SELF, &ru) < 0 ) reporter->InternalError("getrusage() failed in get_proc_stats()"); - auto r = make_intrusive(ProcStats); + auto r = zeek::make_intrusive(ProcStats); int n = 0; double elapsed_time = current_time() - bro_start_time; @@ -147,27 +147,27 @@ function get_proc_stats%(%): ProcStats double(ru.ru_stime.tv_sec) + double(ru.ru_stime.tv_usec) / 1e6; #ifdef DEBUG - r->Assign(n++, val_mgr->Count(1)); + r->Assign(n++, zeek::val_mgr->Count(1)); #else - r->Assign(n++, val_mgr->Count(0)); + r->Assign(n++, zeek::val_mgr->Count(0)); #endif - r->Assign(n++, make_intrusive(bro_start_time)); + r->Assign(n++, zeek::make_intrusive(bro_start_time)); - r->Assign(n++, make_intrusive(elapsed_time, Seconds)); - r->Assign(n++, make_intrusive(user_time, Seconds)); - r->Assign(n++, make_intrusive(system_time, Seconds)); + r->Assign(n++, zeek::make_intrusive(elapsed_time, Seconds)); + r->Assign(n++, zeek::make_intrusive(user_time, Seconds)); + r->Assign(n++, zeek::make_intrusive(system_time, Seconds)); uint64_t total_mem; get_memory_usage(&total_mem, NULL); - r->Assign(n++, val_mgr->Count(unsigned(total_mem))); + r->Assign(n++, zeek::val_mgr->Count(unsigned(total_mem))); - r->Assign(n++, val_mgr->Count(unsigned(ru.ru_minflt))); - r->Assign(n++, val_mgr->Count(unsigned(ru.ru_majflt))); - r->Assign(n++, val_mgr->Count(unsigned(ru.ru_nswap))); - r->Assign(n++, val_mgr->Count(unsigned(ru.ru_inblock))); - r->Assign(n++, val_mgr->Count(unsigned(ru.ru_oublock))); - r->Assign(n++, val_mgr->Count(unsigned(ru.ru_nivcsw))); + r->Assign(n++, zeek::val_mgr->Count(unsigned(ru.ru_minflt))); + r->Assign(n++, zeek::val_mgr->Count(unsigned(ru.ru_majflt))); + r->Assign(n++, zeek::val_mgr->Count(unsigned(ru.ru_nswap))); + r->Assign(n++, zeek::val_mgr->Count(unsigned(ru.ru_inblock))); + r->Assign(n++, zeek::val_mgr->Count(unsigned(ru.ru_oublock))); + r->Assign(n++, zeek::val_mgr->Count(unsigned(ru.ru_nivcsw))); return r; %} @@ -190,11 +190,11 @@ function get_proc_stats%(%): ProcStats ## get_reporter_stats function get_event_stats%(%): EventStats %{ - auto r = make_intrusive(EventStats); + auto r = zeek::make_intrusive(EventStats); int n = 0; - r->Assign(n++, val_mgr->Count(num_events_queued)); - r->Assign(n++, val_mgr->Count(num_events_dispatched)); + r->Assign(n++, zeek::val_mgr->Count(num_events_queued)); + r->Assign(n++, zeek::val_mgr->Count(num_events_dispatched)); return r; %} @@ -217,13 +217,13 @@ function get_event_stats%(%): EventStats ## get_reporter_stats function get_reassembler_stats%(%): ReassemblerStats %{ - auto r = make_intrusive(ReassemblerStats); + auto r = zeek::make_intrusive(ReassemblerStats); int n = 0; - r->Assign(n++, val_mgr->Count(Reassembler::MemoryAllocation(REASSEM_FILE))); - r->Assign(n++, val_mgr->Count(Reassembler::MemoryAllocation(REASSEM_FRAG))); - r->Assign(n++, val_mgr->Count(Reassembler::MemoryAllocation(REASSEM_TCP))); - r->Assign(n++, val_mgr->Count(Reassembler::MemoryAllocation(REASSEM_UNKNOWN))); + r->Assign(n++, zeek::val_mgr->Count(Reassembler::MemoryAllocation(REASSEM_FILE))); + r->Assign(n++, zeek::val_mgr->Count(Reassembler::MemoryAllocation(REASSEM_FRAG))); + r->Assign(n++, zeek::val_mgr->Count(Reassembler::MemoryAllocation(REASSEM_TCP))); + r->Assign(n++, zeek::val_mgr->Count(Reassembler::MemoryAllocation(REASSEM_UNKNOWN))); return r; %} @@ -246,18 +246,18 @@ function get_reassembler_stats%(%): ReassemblerStats ## get_reporter_stats function get_dns_stats%(%): DNSStats %{ - auto r = make_intrusive(DNSStats); + auto r = zeek::make_intrusive(DNSStats); int n = 0; DNS_Mgr::Stats dstats; dns_mgr->GetStats(&dstats); - r->Assign(n++, val_mgr->Count(unsigned(dstats.requests))); - r->Assign(n++, val_mgr->Count(unsigned(dstats.successful))); - r->Assign(n++, val_mgr->Count(unsigned(dstats.failed))); - r->Assign(n++, val_mgr->Count(unsigned(dstats.pending))); - r->Assign(n++, val_mgr->Count(unsigned(dstats.cached_hosts))); - r->Assign(n++, val_mgr->Count(unsigned(dstats.cached_addresses))); + r->Assign(n++, zeek::val_mgr->Count(unsigned(dstats.requests))); + r->Assign(n++, zeek::val_mgr->Count(unsigned(dstats.successful))); + r->Assign(n++, zeek::val_mgr->Count(unsigned(dstats.failed))); + r->Assign(n++, zeek::val_mgr->Count(unsigned(dstats.pending))); + r->Assign(n++, zeek::val_mgr->Count(unsigned(dstats.cached_hosts))); + r->Assign(n++, zeek::val_mgr->Count(unsigned(dstats.cached_addresses))); return r; %} @@ -280,12 +280,12 @@ function get_dns_stats%(%): DNSStats ## get_reporter_stats function get_timer_stats%(%): TimerStats %{ - auto r = make_intrusive(TimerStats); + auto r = zeek::make_intrusive(TimerStats); int n = 0; - r->Assign(n++, val_mgr->Count(unsigned(timer_mgr->Size()))); - r->Assign(n++, val_mgr->Count(unsigned(timer_mgr->PeakSize()))); - r->Assign(n++, val_mgr->Count(timer_mgr->CumulativeNum())); + r->Assign(n++, zeek::val_mgr->Count(unsigned(timer_mgr->Size()))); + r->Assign(n++, zeek::val_mgr->Count(unsigned(timer_mgr->PeakSize()))); + r->Assign(n++, zeek::val_mgr->Count(timer_mgr->CumulativeNum())); return r; %} @@ -308,12 +308,12 @@ function get_timer_stats%(%): TimerStats ## get_reporter_stats function get_file_analysis_stats%(%): FileAnalysisStats %{ - auto r = make_intrusive(FileAnalysisStats); + auto r = zeek::make_intrusive(FileAnalysisStats); int n = 0; - r->Assign(n++, val_mgr->Count(file_mgr->CurrentFiles())); - r->Assign(n++, val_mgr->Count(file_mgr->MaxFiles())); - r->Assign(n++, val_mgr->Count(file_mgr->CumulativeFiles())); + r->Assign(n++, zeek::val_mgr->Count(file_mgr->CurrentFiles())); + r->Assign(n++, zeek::val_mgr->Count(file_mgr->MaxFiles())); + r->Assign(n++, zeek::val_mgr->Count(file_mgr->CumulativeFiles())); return r; %} @@ -336,10 +336,10 @@ function get_file_analysis_stats%(%): FileAnalysisStats ## get_reporter_stats function get_thread_stats%(%): ThreadStats %{ - auto r = make_intrusive(ThreadStats); + auto r = zeek::make_intrusive(ThreadStats); int n = 0; - r->Assign(n++, val_mgr->Count(thread_mgr->NumThreads())); + r->Assign(n++, zeek::val_mgr->Count(thread_mgr->NumThreads())); return r; %} @@ -362,13 +362,13 @@ function get_thread_stats%(%): ThreadStats ## get_reporter_stats function get_gap_stats%(%): GapStats %{ - auto r = make_intrusive(GapStats); + auto r = zeek::make_intrusive(GapStats); int n = 0; - r->Assign(n++, val_mgr->Count(tot_ack_events)); - r->Assign(n++, val_mgr->Count(tot_ack_bytes)); - r->Assign(n++, val_mgr->Count(tot_gap_events)); - r->Assign(n++, val_mgr->Count(tot_gap_bytes)); + r->Assign(n++, zeek::val_mgr->Count(tot_ack_events)); + r->Assign(n++, zeek::val_mgr->Count(tot_ack_bytes)); + r->Assign(n++, zeek::val_mgr->Count(tot_gap_events)); + r->Assign(n++, zeek::val_mgr->Count(tot_gap_bytes)); return r; %} @@ -394,7 +394,7 @@ function get_gap_stats%(%): GapStats ## get_reporter_stats function get_matcher_stats%(%): MatcherStats %{ - auto r = make_intrusive(MatcherStats); + auto r = zeek::make_intrusive(MatcherStats); int n = 0; RuleMatcher::Stats s; @@ -402,13 +402,13 @@ function get_matcher_stats%(%): MatcherStats if ( rule_matcher ) rule_matcher->GetStats(&s); - r->Assign(n++, val_mgr->Count(s.matchers)); - r->Assign(n++, val_mgr->Count(s.nfa_states)); - r->Assign(n++, val_mgr->Count(s.dfa_states)); - r->Assign(n++, val_mgr->Count(s.computed)); - r->Assign(n++, val_mgr->Count(s.mem)); - r->Assign(n++, val_mgr->Count(s.hits)); - r->Assign(n++, val_mgr->Count(s.misses)); + r->Assign(n++, zeek::val_mgr->Count(s.matchers)); + r->Assign(n++, zeek::val_mgr->Count(s.nfa_states)); + r->Assign(n++, zeek::val_mgr->Count(s.dfa_states)); + r->Assign(n++, zeek::val_mgr->Count(s.computed)); + r->Assign(n++, zeek::val_mgr->Count(s.mem)); + r->Assign(n++, zeek::val_mgr->Count(s.hits)); + r->Assign(n++, zeek::val_mgr->Count(s.misses)); return r; %} @@ -432,19 +432,19 @@ function get_matcher_stats%(%): MatcherStats ## get_reporter_stats function get_broker_stats%(%): BrokerStats %{ - auto r = make_intrusive(BrokerStats); + auto r = zeek::make_intrusive(BrokerStats); int n = 0; auto cs = broker_mgr->GetStatistics(); - r->Assign(n++, val_mgr->Count(static_cast(cs.num_peers))); - r->Assign(n++, val_mgr->Count(static_cast(cs.num_stores))); - r->Assign(n++, val_mgr->Count(static_cast(cs.num_pending_queries))); - r->Assign(n++, val_mgr->Count(static_cast(cs.num_events_incoming))); - r->Assign(n++, val_mgr->Count(static_cast(cs.num_events_outgoing))); - r->Assign(n++, val_mgr->Count(static_cast(cs.num_logs_incoming))); - r->Assign(n++, val_mgr->Count(static_cast(cs.num_logs_outgoing))); - r->Assign(n++, val_mgr->Count(static_cast(cs.num_ids_incoming))); - r->Assign(n++, val_mgr->Count(static_cast(cs.num_ids_outgoing))); + r->Assign(n++, zeek::val_mgr->Count(static_cast(cs.num_peers))); + r->Assign(n++, zeek::val_mgr->Count(static_cast(cs.num_stores))); + r->Assign(n++, zeek::val_mgr->Count(static_cast(cs.num_pending_queries))); + r->Assign(n++, zeek::val_mgr->Count(static_cast(cs.num_events_incoming))); + r->Assign(n++, zeek::val_mgr->Count(static_cast(cs.num_events_outgoing))); + r->Assign(n++, zeek::val_mgr->Count(static_cast(cs.num_logs_incoming))); + r->Assign(n++, zeek::val_mgr->Count(static_cast(cs.num_logs_outgoing))); + r->Assign(n++, zeek::val_mgr->Count(static_cast(cs.num_ids_incoming))); + r->Assign(n++, zeek::val_mgr->Count(static_cast(cs.num_ids_outgoing))); return r; %} @@ -467,18 +467,18 @@ function get_broker_stats%(%): BrokerStats ## get_broker_stats function get_reporter_stats%(%): ReporterStats %{ - auto r = make_intrusive(ReporterStats); + auto r = zeek::make_intrusive(ReporterStats); int n = 0; - auto weirds_by_type = make_intrusive(zeek::id::find_type("table_string_of_count")); + auto weirds_by_type = zeek::make_intrusive(zeek::id::find_type("table_string_of_count")); for ( auto& kv : reporter->GetWeirdsByType() ) { - auto weird = make_intrusive(kv.first); - weirds_by_type->Assign(std::move(weird), val_mgr->Count(kv.second)); + auto weird = zeek::make_intrusive(kv.first); + weirds_by_type->Assign(std::move(weird), zeek::val_mgr->Count(kv.second)); } - r->Assign(n++, val_mgr->Count(reporter->GetWeirdCount())); + r->Assign(n++, zeek::val_mgr->Count(reporter->GetWeirdCount())); r->Assign(n++, std::move(weirds_by_type)); return r; diff --git a/src/strings.bif b/src/strings.bif index 909280b564..59369d8dd8 100644 --- a/src/strings.bif +++ b/src/strings.bif @@ -25,10 +25,10 @@ function levenshtein_distance%(s1: string, s2: string%): count unsigned int m = s2->Len(); if ( ! n ) - return val_mgr->Count(m); + return zeek::val_mgr->Count(m); if ( ! m ) - return val_mgr->Count(n); + return zeek::val_mgr->Count(n); vector > d(n + 1, vector(m + 1)); @@ -47,7 +47,7 @@ function levenshtein_distance%(s1: string, s2: string%): count d[i-1][j-1] + (s1->Bytes()[i-1] == s2->Bytes()[j-1] ? 0 : 1)); } - return val_mgr->Count(d[n][m]); + return zeek::val_mgr->Count(d[n][m]); %} ## Concatenates all arguments into a single string. The function takes a @@ -65,17 +65,17 @@ function string_cat%(...%): string n += a->AsString()->Len(); u_char* b = new u_char[n+1]; - BroString* s = new BroString(1, b, n); + zeek::String* s = new zeek::String(1, b, n); for ( const auto& a : @ARG@ ) { - const BroString* s = a->AsString(); + const zeek::String* s = a->AsString(); memcpy(b, s->Bytes(), s->Len()); b += s->Len(); } *b = 0; - return make_intrusive(s); + return zeek::make_intrusive(s); %} ## Joins all values in the given vector of strings with a separator placed @@ -95,7 +95,7 @@ function join_string_vec%(vec: string_vec, sep: string%): string ODesc d; d.SetStyle(RAW_STYLE); - VectorVal *v = vec->AsVectorVal(); + zeek::VectorVal *v = vec->AsVectorVal(); for ( unsigned i = 0; i < v->Size(); ++i ) { @@ -111,10 +111,10 @@ function join_string_vec%(vec: string_vec, sep: string%): string e->Describe(&d); } - BroString* s = new BroString(1, d.TakeBytes(), d.Len()); + zeek::String* s = new zeek::String(1, d.TakeBytes(), d.Len()); s->SetUseFreeToDelete(true); - return make_intrusive(s); + return zeek::make_intrusive(s); %} ## Returns an edited version of a string that applies a special @@ -138,7 +138,7 @@ function join_string_vec%(vec: string_vec, sep: string%): string function edit%(arg_s: string, arg_edit_char: string%): string %{ if ( arg_edit_char->Len() != 1 ) - builtin_error("not exactly one edit character", @ARG@[1]); + zeek::emit_builtin_error("not exactly one edit character", @ARG@[1]); const u_char* s = arg_s->Bytes(); const u_char* edit_s = arg_edit_char->Bytes(); @@ -162,7 +162,7 @@ function edit%(arg_s: string, arg_edit_char: string%): string new_s[ind] = '\0'; - return make_intrusive(new BroString(1, byte_vec(new_s), ind)); + return zeek::make_intrusive(new zeek::String(1, byte_vec(new_s), ind)); %} ## Get a substring from a string, given a starting position and length. @@ -180,12 +180,12 @@ function sub_bytes%(s: string, start: count, n: int%): string if ( start > 0 ) --start; // make it 0-based - BroString* ss = s->AsString()->GetSubstring(start, n); + zeek::String* ss = s->AsString()->GetSubstring(start, n); if ( ! ss ) - ss = new BroString(""); + ss = new zeek::String(""); - return make_intrusive(ss); + return zeek::make_intrusive(ss); %} %%{ @@ -199,12 +199,12 @@ static int match_prefix(int s_len, const char* s, int t_len, const char* t) return 1; } -static IntrusivePtr do_split_string(StringVal* str_val, - RE_Matcher* re, int incl_sep, - int max_num_sep) +static zeek::VectorValPtr do_split_string(zeek::StringVal* str_val, + RE_Matcher* re, int incl_sep, + int max_num_sep) { // string_vec is used early in the version script - do not use the NetVar. - auto rval = make_intrusive(zeek::id::find_type("string_vec")); + auto rval = zeek::make_intrusive(zeek::id::find_type("string_vec")); const u_char* s = str_val->Bytes(); int n = str_val->Len(); const u_char* end_of_s = s + n; @@ -231,7 +231,7 @@ static IntrusivePtr do_split_string(StringVal* str_val, n=0; } - rval->Assign(num++, make_intrusive(offset, (const char*) s)); + rval->Assign(num++, zeek::make_intrusive(offset, (const char*) s)); // No more separators will be needed if this is the end of string. if ( n <= 0 ) @@ -239,7 +239,7 @@ static IntrusivePtr do_split_string(StringVal* str_val, if ( incl_sep ) { // including the part that matches the pattern - rval->Assign(num++, make_intrusive(end_of_match, (const char*) s+offset)); + rval->Assign(num++, zeek::make_intrusive(end_of_match, (const char*) s+offset)); } if ( max_num_sep && num_sep >= max_num_sep ) @@ -257,9 +257,9 @@ static IntrusivePtr do_split_string(StringVal* str_val, return rval; } -Val* do_split(StringVal* str_val, RE_Matcher* re, int incl_sep, int max_num_sep) +zeek::Val* do_split(zeek::StringVal* str_val, RE_Matcher* re, int incl_sep, int max_num_sep) { - TableVal* a = new TableVal(zeek::id::string_array); + auto* a = new zeek::TableVal(zeek::id::string_array); const u_char* s = str_val->Bytes(); int n = str_val->Len(); const u_char* end_of_s = s + n; @@ -286,8 +286,8 @@ Val* do_split(StringVal* str_val, RE_Matcher* re, int incl_sep, int max_num_sep) n=0; } - auto ind = val_mgr->Count(++num); - a->Assign(std::move(ind), make_intrusive(offset, (const char*) s)); + auto ind = zeek::val_mgr->Count(++num); + a->Assign(std::move(ind), zeek::make_intrusive(offset, (const char*) s)); // No more separators will be needed if this is the end of string. if ( n <= 0 ) @@ -295,8 +295,8 @@ Val* do_split(StringVal* str_val, RE_Matcher* re, int incl_sep, int max_num_sep) if ( incl_sep ) { // including the part that matches the pattern - ind = val_mgr->Count(++num); - a->Assign(std::move(ind), make_intrusive(end_of_match, (const char*) s+offset)); + ind = zeek::val_mgr->Count(++num); + a->Assign(std::move(ind), zeek::make_intrusive(end_of_match, (const char*) s+offset)); } if ( max_num_sep && num_sep >= max_num_sep ) @@ -443,7 +443,7 @@ function gsub%(str: string, re: pattern, repl: string%): string ## *s1* is greater than, equal to, or less than *s2*. function strcmp%(s1: string, s2: string%): int %{ - return val_mgr->Int(Bstr_cmp(s1->AsString(), s2->AsString())); + return zeek::val_mgr->Int(Bstr_cmp(s1->AsString(), s2->AsString())); %} ## Locates the first occurrence of one string in another. @@ -458,7 +458,7 @@ function strcmp%(s1: string, s2: string%): int ## .. zeek:see:: find_all find_last function strstr%(big: string, little: string%): count %{ - return val_mgr->Count( + return zeek::val_mgr->Count( 1 + big->AsString()->FindSubstring(little->AsString())); %} @@ -477,7 +477,7 @@ function subst_string%(s: string, from: string, to: string%): string %{ const int little_len = from->Len(); if ( little_len == 0 ) - return IntrusivePtr{NewRef{}, s}; + return IntrusivePtr{zeek::NewRef{}, s}; int big_len = s->Len(); const u_char* big = s->Bytes(); @@ -512,7 +512,7 @@ function subst_string%(s: string, from: string, to: string%): string vs.push_back(dc); } - return make_intrusive(concatenate(vs)); + return zeek::make_intrusive(concatenate(vs)); %} ## Replaces all uppercase letters in a string with their lowercase counterpart. @@ -541,7 +541,7 @@ function to_lower%(str: string%): string *ls++ = '\0'; - return make_intrusive(new BroString(1, lower_s, n)); + return zeek::make_intrusive(new zeek::String(1, lower_s, n)); %} ## Replaces all lowercase letters in a string with their uppercase counterpart. @@ -570,7 +570,7 @@ function to_upper%(str: string%): string *us++ = '\0'; - return make_intrusive(new BroString(1, upper_s, n)); + return zeek::make_intrusive(new zeek::String(1, upper_s, n)); %} ## Replaces non-printable characters in a string with escaped sequences. The @@ -590,7 +590,7 @@ function to_upper%(str: string%): string function clean%(str: string%): string %{ char* s = str->AsString()->Render(); - return make_intrusive(new BroString(1, byte_vec(s), strlen(s))); + return zeek::make_intrusive(new zeek::String(1, byte_vec(s), strlen(s))); %} ## Replaces non-printable characters in a string with escaped sequences. The @@ -607,8 +607,8 @@ function clean%(str: string%): string ## .. zeek:see:: clean escape_string function to_string_literal%(str: string%): string %{ - char* s = str->AsString()->Render(BroString::BRO_STRING_LITERAL); - return make_intrusive(new BroString(1, byte_vec(s), strlen(s))); + char* s = str->AsString()->Render(zeek::String::BRO_STRING_LITERAL); + return zeek::make_intrusive(new zeek::String(1, byte_vec(s), strlen(s))); %} ## Determines whether a given string contains only ASCII characters. @@ -626,9 +626,9 @@ function is_ascii%(str: string%): bool for ( int i = 0; i < n; ++i ) if ( s[i] > 127 ) - return val_mgr->False(); + return zeek::val_mgr->False(); - return val_mgr->True(); + return zeek::val_mgr->True(); %} ## Replaces non-printable characters in a string with escaped sequences. The @@ -646,8 +646,8 @@ function is_ascii%(str: string%): bool ## .. zeek:see:: clean to_string_literal function escape_string%(s: string%): string %{ - char* escstr = s->AsString()->Render(BroString::ESC_HEX | BroString::ESC_ESC); - auto val = make_intrusive(escstr); + char* escstr = s->AsString()->Render(zeek::String::ESC_HEX | zeek::String::ESC_ESC); + auto val = zeek::make_intrusive(escstr); delete [] escstr; return val; %} @@ -666,7 +666,7 @@ function string_to_ascii_hex%(s: string%): string for ( int i = 0; i < s->Len(); ++i ) sprintf(x + i * 2, "%02x", sp[i]); - return make_intrusive(new BroString(1, (u_char*) x, s->Len() * 2)); + return zeek::make_intrusive(new zeek::String(1, (u_char*) x, s->Len() * 2)); %} ## Uses the Smith-Waterman algorithm to find similar/overlapping substrings. @@ -686,7 +686,7 @@ function str_smith_waterman%(s1: string, s2: string, params: sw_params%) : sw_su BroSubstring::Vec* subseq = smith_waterman(s1->AsString(), s2->AsString(), sw_params); - auto result = IntrusivePtr{AdoptRef{}, BroSubstring::VecToPolicy(subseq)}; + auto result = zeek::VectorValPtr{zeek::AdoptRef{}, BroSubstring::VecToPolicy(subseq)}; delete_each(subseq); delete subseq; @@ -706,22 +706,22 @@ function str_smith_waterman%(s1: string, s2: string, params: sw_params%) : sw_su function str_split%(s: string, idx: index_vec%): string_vec %{ auto idx_v = idx->AsVector(); - BroString::IdxVec indices(idx_v->size()); + zeek::String::IdxVec indices(idx_v->size()); unsigned int i; for ( i = 0; i < idx_v->size(); i++ ) indices[i] = (*idx_v)[i]->AsCount(); - BroString::Vec* result = s->AsString()->Split(indices); - auto result_v = make_intrusive(zeek::id::string_vec); + zeek::String::Vec* result = s->AsString()->Split(indices); + auto result_v = zeek::make_intrusive(zeek::id::string_vec); if ( result ) { i = 1; - for ( BroString::VecIt it = result->begin(); + for ( zeek::String::VecIt it = result->begin(); it != result->end(); ++it, ++i ) - result_v->Assign(i, make_intrusive(*it)); + result_v->Assign(i, zeek::make_intrusive(*it)); // StringVal now possesses string. delete result; @@ -744,7 +744,7 @@ function strip%(str: string%): string if ( n == 0 ) // Empty string. - return make_intrusive(new BroString(s, n, 1)); + return zeek::make_intrusive(new zeek::String(s, n, 1)); const u_char* sp = s; @@ -757,11 +757,11 @@ function strip%(str: string%): string while ( isspace(*sp) && sp <= e ) ++sp; - return make_intrusive(new BroString(sp, (e - sp + 1), 1)); + return zeek::make_intrusive(new zeek::String(sp, (e - sp + 1), 1)); %} %%{ -static bool should_strip(u_char c, const BroString* strip_chars) +static bool should_strip(u_char c, const zeek::String* strip_chars) { auto strip_bytes = strip_chars->Bytes(); @@ -792,7 +792,7 @@ function lstrip%(str: string, chars: string &default=" \t\n\r\v\f"%): string // empty input string if ( n == 0 ) - return make_intrusive(new BroString(s, n, 1)); + return zeek::make_intrusive(new zeek::String(s, n, 1)); int i; auto bs_chars = chars->AsString(); @@ -801,7 +801,7 @@ function lstrip%(str: string, chars: string &default=" \t\n\r\v\f"%): string if ( ! should_strip(s[i], bs_chars) ) break; - return make_intrusive(new BroString(s + i, n - i, 1)); + return zeek::make_intrusive(new zeek::String(s + i, n - i, 1)); %} ## Removes all combinations of characters in the *chars* argument @@ -823,7 +823,7 @@ function rstrip%(str: string, chars: string &default=" \t\n\r\v\f"%): string // empty input string if ( n == 0 ) - return make_intrusive(new BroString(s, n, 1)); + return zeek::make_intrusive(new zeek::String(s, n, 1)); int n_to_remove; auto bs_chars = chars->AsString(); @@ -832,7 +832,7 @@ function rstrip%(str: string, chars: string &default=" \t\n\r\v\f"%): string if ( ! should_strip(s[n - n_to_remove - 1], bs_chars) ) break; - return make_intrusive(new BroString(s, n - n_to_remove, 1)); + return zeek::make_intrusive(new zeek::String(s, n - n_to_remove, 1)); %} ## Generates a string of a given size and fills it with repetitions of a source @@ -854,7 +854,7 @@ function string_fill%(len: int, source: string%): string dst[len - 1] = 0; - return make_intrusive(new BroString(1, byte_vec(dst), len)); + return zeek::make_intrusive(new zeek::String(1, byte_vec(dst), len)); %} ## Takes a string and escapes characters that would allow execution of @@ -894,7 +894,7 @@ function safe_shell_quote%(source: string%): string dst[j++] = '"'; dst[j] = '\0'; - return make_intrusive(new BroString(1, dst, j)); + return zeek::make_intrusive(new zeek::String(1, dst, j)); %} ## Finds all occurrences of a pattern in a string. @@ -908,7 +908,7 @@ function safe_shell_quote%(source: string%): string ## .. zeek:see: find_last strstr function find_all%(str: string, re: pattern%) : string_set %{ - auto a = make_intrusive(zeek::id::string_set); + auto a = zeek::make_intrusive(zeek::id::string_set); const u_char* s = str->Bytes(); const u_char* e = s + str->Len(); @@ -918,7 +918,7 @@ function find_all%(str: string, re: pattern%) : string_set int n = re->MatchPrefix(t, e - t); if ( n >= 0 ) { - auto idx = make_intrusive(n, (const char*) t); + auto idx = zeek::make_intrusive(n, (const char*) t); a->Assign(std::move(idx), 0); t += n - 1; } @@ -948,10 +948,10 @@ function find_last%(str: string, re: pattern%) : string { int n = re->MatchPrefix(t, e - t); if ( n >= 0 ) - return make_intrusive(n, (const char*) t); + return zeek::make_intrusive(n, (const char*) t); } - return val_mgr->EmptyString(); + return zeek::val_mgr->EmptyString(); %} ## Returns a hex dump for given input data. The hex dump renders 16 bytes per @@ -996,13 +996,13 @@ function hexdump%(data_str: string%) : string unsigned data_size = data_str->Len(); if ( ! data ) - return val_mgr->EmptyString(); + return zeek::val_mgr->EmptyString(); int num_lines = (data_size / 16) + 1; int len = num_lines * HEX_LINE_WIDTH; u_char* hex_data = new u_char[len + 1]; if ( ! hex_data ) - return val_mgr->EmptyString(); + return zeek::val_mgr->EmptyString(); memset(hex_data, ' ', len); @@ -1066,7 +1066,7 @@ function hexdump%(data_str: string%) : string *ascii_ptr++ = '\n'; *ascii_ptr = 0; - auto result = make_intrusive((const char*) hex_data); + auto result = zeek::make_intrusive((const char*) hex_data); delete [] hex_data; return result; @@ -1082,5 +1082,5 @@ function reverse%(str: string%) : string %{ string s = string((const char*)str->Bytes(), str->Len()); reverse(s.begin(), s.end()); - return make_intrusive(s.length(), (const char*)s.c_str()); + return zeek::make_intrusive(s.length(), (const char*)s.c_str()); %} diff --git a/src/supervisor/Supervisor.cc b/src/supervisor/Supervisor.cc index bcf9a1c9f6..01b086608b 100644 --- a/src/supervisor/Supervisor.cc +++ b/src/supervisor/Supervisor.cc @@ -13,7 +13,7 @@ #include #include "iosource/Manager.h" -#include "BroString.h" +#include "ZeekString.h" #include "Dict.h" #include "RE.h" #include "Reporter.h" @@ -1102,53 +1102,53 @@ std::string Supervisor::NodeConfig::ToJSON() const return ToRecord()->ToJSON(false, re.get())->ToStdString(); } -IntrusivePtr Supervisor::NodeConfig::ToRecord() const +RecordValPtr Supervisor::NodeConfig::ToRecord() const { const auto& rt = zeek::BifType::Record::Supervisor::NodeConfig; - auto rval = make_intrusive(rt); - rval->Assign(rt->FieldOffset("name"), make_intrusive(name)); + auto rval = zeek::make_intrusive(rt); + rval->Assign(rt->FieldOffset("name"), zeek::make_intrusive(name)); if ( interface ) - rval->Assign(rt->FieldOffset("interface"), make_intrusive(*interface)); + rval->Assign(rt->FieldOffset("interface"), zeek::make_intrusive(*interface)); if ( directory ) - rval->Assign(rt->FieldOffset("directory"), make_intrusive(*directory)); + rval->Assign(rt->FieldOffset("directory"), zeek::make_intrusive(*directory)); if ( stdout_file ) - rval->Assign(rt->FieldOffset("stdout_file"), make_intrusive(*stdout_file)); + rval->Assign(rt->FieldOffset("stdout_file"), zeek::make_intrusive(*stdout_file)); if ( stderr_file ) - rval->Assign(rt->FieldOffset("stderr_file"), make_intrusive(*stderr_file)); + rval->Assign(rt->FieldOffset("stderr_file"), zeek::make_intrusive(*stderr_file)); if ( cpu_affinity ) - rval->Assign(rt->FieldOffset("cpu_affinity"), val_mgr->Int(*cpu_affinity)); + rval->Assign(rt->FieldOffset("cpu_affinity"), zeek::val_mgr->Int(*cpu_affinity)); auto st = rt->GetFieldType("scripts"); - auto scripts_val = make_intrusive(std::move(st)); + auto scripts_val = zeek::make_intrusive(std::move(st)); for ( const auto& s : scripts ) - scripts_val->Assign(scripts_val->Size(), make_intrusive(s)); + scripts_val->Assign(scripts_val->Size(), zeek::make_intrusive(s)); rval->Assign(rt->FieldOffset("scripts"), std::move(scripts_val)); auto tt = rt->GetFieldType("cluster"); - auto cluster_val = make_intrusive(std::move(tt)); + auto cluster_val = zeek::make_intrusive(std::move(tt)); rval->Assign(rt->FieldOffset("cluster"), cluster_val); for ( const auto& e : cluster ) { auto& name = e.first; auto& ep = e.second; - auto key = make_intrusive(name); + auto key = zeek::make_intrusive(name); const auto& ept = zeek::BifType::Record::Supervisor::ClusterEndpoint; - auto val = make_intrusive(ept); + auto val = zeek::make_intrusive(ept); val->Assign(ept->FieldOffset("role"), zeek::BifType::Enum::Supervisor::ClusterRole->GetVal(ep.role)); - val->Assign(ept->FieldOffset("host"), make_intrusive(ep.host)); - val->Assign(ept->FieldOffset("p"), val_mgr->Port(ep.port, TRANSPORT_TCP)); + val->Assign(ept->FieldOffset("host"), zeek::make_intrusive(ep.host)); + val->Assign(ept->FieldOffset("p"), zeek::val_mgr->Port(ep.port, TRANSPORT_TCP)); if ( ep.interface ) - val->Assign(ept->FieldOffset("interface"), make_intrusive(*ep.interface)); + val->Assign(ept->FieldOffset("interface"), zeek::make_intrusive(*ep.interface)); cluster_val->Assign(std::move(key), std::move(val)); } @@ -1156,21 +1156,21 @@ IntrusivePtr Supervisor::NodeConfig::ToRecord() const return rval; } -IntrusivePtr Supervisor::Node::ToRecord() const +RecordValPtr Supervisor::Node::ToRecord() const { const auto& rt = zeek::BifType::Record::Supervisor::NodeStatus; - auto rval = make_intrusive(rt); + auto rval = zeek::make_intrusive(rt); rval->Assign(rt->FieldOffset("node"), config.ToRecord()); if ( pid ) - rval->Assign(rt->FieldOffset("pid"), val_mgr->Int(pid)); + rval->Assign(rt->FieldOffset("pid"), zeek::val_mgr->Int(pid)); return rval; } -static IntrusivePtr supervisor_role_to_cluster_node_type(BifEnum::Supervisor::ClusterRole role) +static ValPtr supervisor_role_to_cluster_node_type(BifEnum::Supervisor::ClusterRole role) { static auto node_type = zeek::id::find_type("Cluster::NodeType"); @@ -1212,26 +1212,26 @@ bool Supervisor::SupervisedNode::InitCluster() const { const auto& node_name = e.first; const auto& ep = e.second; - auto key = make_intrusive(node_name); - auto val = make_intrusive(cluster_node_type); + auto key = zeek::make_intrusive(node_name); + auto val = zeek::make_intrusive(cluster_node_type); auto node_type = supervisor_role_to_cluster_node_type(ep.role); val->Assign(cluster_node_type->FieldOffset("node_type"), std::move(node_type)); - val->Assign(cluster_node_type->FieldOffset("ip"), make_intrusive(ep.host)); - val->Assign(cluster_node_type->FieldOffset("p"), val_mgr->Port(ep.port, TRANSPORT_TCP)); + val->Assign(cluster_node_type->FieldOffset("ip"), zeek::make_intrusive(ep.host)); + val->Assign(cluster_node_type->FieldOffset("p"), zeek::val_mgr->Port(ep.port, TRANSPORT_TCP)); if ( ep.interface ) val->Assign(cluster_node_type->FieldOffset("interface"), - make_intrusive(*ep.interface)); + zeek::make_intrusive(*ep.interface)); if ( manager_name && ep.role != BifEnum::Supervisor::MANAGER ) val->Assign(cluster_node_type->FieldOffset("manager"), - make_intrusive(*manager_name)); + zeek::make_intrusive(*manager_name)); cluster_nodes->Assign(std::move(key), std::move(val)); } - cluster_manager_is_logger_id->SetVal(val_mgr->Bool(! has_logger)); + cluster_manager_is_logger_id->SetVal(zeek::val_mgr->Bool(! has_logger)); return true; } @@ -1312,11 +1312,11 @@ void Supervisor::SupervisedNode::Init(zeek::Options* options) const options->scripts_to_load.emplace_back(s); } -IntrusivePtr Supervisor::Status(std::string_view node_name) +RecordValPtr Supervisor::Status(std::string_view node_name) { - auto rval = make_intrusive(zeek::BifType::Record::Supervisor::Status); + auto rval = zeek::make_intrusive(zeek::BifType::Record::Supervisor::Status); const auto& tt = zeek::BifType::Record::Supervisor::Status->GetFieldType("nodes"); - auto node_table_val = make_intrusive(cast_intrusive(tt)); + auto node_table_val = zeek::make_intrusive(zeek::cast_intrusive(tt)); rval->Assign(0, node_table_val); if ( node_name.empty() ) @@ -1325,7 +1325,7 @@ IntrusivePtr Supervisor::Status(std::string_view node_name) { const auto& name = n.first; const auto& node = n.second; - auto key = make_intrusive(name); + auto key = zeek::make_intrusive(name); auto val = node.ToRecord(); node_table_val->Assign(std::move(key), std::move(val)); } @@ -1339,7 +1339,7 @@ IntrusivePtr Supervisor::Status(std::string_view node_name) const auto& name = it->first; const auto& node = it->second; - auto key = make_intrusive(name); + auto key = zeek::make_intrusive(name); auto val = node.ToRecord(); node_table_val->Assign(std::move(key), std::move(val)); } diff --git a/src/supervisor/Supervisor.h b/src/supervisor/Supervisor.h index ba381ad6dd..114385366b 100644 --- a/src/supervisor/Supervisor.h +++ b/src/supervisor/Supervisor.h @@ -103,7 +103,7 @@ public: * Convert his object into script-layer record value. * @return the script-layer record value representing the node config. */ - IntrusivePtr ToRecord() const; + RecordValPtr ToRecord() const; /** * The name of the supervised Zeek node. These are unique within @@ -183,7 +183,7 @@ public: * Convert the node into script-layer Supervisor::NodeStatus record * representation. */ - IntrusivePtr ToRecord() const; + RecordValPtr ToRecord() const; /** * @return the name of the node. @@ -311,7 +311,7 @@ public: * @return script-layer Supervisor::Status record value describing the * status of a node or set of nodes. */ - IntrusivePtr Status(std::string_view node_name); + RecordValPtr Status(std::string_view node_name); /** * Create a new supervised node. diff --git a/src/supervisor/supervisor.bif b/src/supervisor/supervisor.bif index e0dd3dce3b..9782b446c4 100644 --- a/src/supervisor/supervisor.bif +++ b/src/supervisor/supervisor.bif @@ -23,8 +23,8 @@ function Supervisor::__status%(node: string%): Supervisor::Status %{ if ( ! zeek::supervisor_mgr ) { - builtin_error("supervisor mode not enabled"); - return make_intrusive(zeek::BifType::Record::Supervisor::Status); + zeek::emit_builtin_error("supervisor mode not enabled"); + return zeek::make_intrusive(zeek::BifType::Record::Supervisor::Status); } return zeek::supervisor_mgr->Status(node->CheckString()); @@ -34,59 +34,59 @@ function Supervisor::__create%(node: Supervisor::NodeConfig%): string %{ if ( ! zeek::supervisor_mgr ) { - builtin_error("supervisor mode not enabled"); - return make_intrusive("supervisor mode not enabled"); + zeek::emit_builtin_error("supervisor mode not enabled"); + return zeek::make_intrusive("supervisor mode not enabled"); } auto rval = zeek::supervisor_mgr->Create(node->AsRecordVal()); - return make_intrusive(rval); + return zeek::make_intrusive(rval); %} function Supervisor::__destroy%(node: string%): bool %{ if ( ! zeek::supervisor_mgr ) { - builtin_error("supervisor mode not enabled"); - return val_mgr->Bool(false); + zeek::emit_builtin_error("supervisor mode not enabled"); + return zeek::val_mgr->Bool(false); } auto rval = zeek::supervisor_mgr->Destroy(node->CheckString()); - return val_mgr->Bool(rval); + return zeek::val_mgr->Bool(rval); %} function Supervisor::__restart%(node: string%): bool %{ if ( ! zeek::supervisor_mgr ) { - builtin_error("supervisor mode not enabled"); - return val_mgr->Bool(false); + zeek::emit_builtin_error("supervisor mode not enabled"); + return zeek::val_mgr->Bool(false); } auto rval = zeek::supervisor_mgr->Restart(node->CheckString()); - return val_mgr->Bool(rval); + return zeek::val_mgr->Bool(rval); %} function Supervisor::__init_cluster%(%): bool %{ if ( zeek::Supervisor::ThisNode() ) - return val_mgr->Bool(zeek::Supervisor::ThisNode()->InitCluster()); + return zeek::val_mgr->Bool(zeek::Supervisor::ThisNode()->InitCluster()); - return val_mgr->Bool(false); + return zeek::val_mgr->Bool(false); %} function Supervisor::__is_supervised%(%): bool %{ - return val_mgr->Bool(zeek::Supervisor::ThisNode().has_value()); + return zeek::val_mgr->Bool(zeek::Supervisor::ThisNode().has_value()); %} function Supervisor::__node%(%): Supervisor::NodeConfig %{ if ( ! zeek::Supervisor::ThisNode() ) { - builtin_error("not a supervised process"); + zeek::emit_builtin_error("not a supervised process"); const auto& rt = zeek::BifType::Record::Supervisor::NodeConfig; - auto rval = make_intrusive(rt); - rval->Assign(rt->FieldOffset("name"), ""); + auto rval = zeek::make_intrusive(rt); + rval->Assign(rt->FieldOffset("name"), ""); return rval; } @@ -96,17 +96,17 @@ function Supervisor::__node%(%): Supervisor::NodeConfig function Supervisor::__is_supervisor%(%): bool %{ - return val_mgr->Bool(zeek::supervisor_mgr != nullptr); + return zeek::val_mgr->Bool(zeek::supervisor_mgr != nullptr); %} function Supervisor::__stem_pid%(%): int %{ if ( zeek::supervisor_mgr ) - return val_mgr->Int(zeek::supervisor_mgr->StemPID()); + return zeek::val_mgr->Int(zeek::supervisor_mgr->StemPID()); if ( zeek::Supervisor::ThisNode() ) - return val_mgr->Int(zeek::Supervisor::ThisNode()->parent_pid); + return zeek::val_mgr->Int(zeek::Supervisor::ThisNode()->parent_pid); - builtin_error("supervisor mode not enabled and not a supervised node"); - return val_mgr->Int(-1); + zeek::emit_builtin_error("supervisor mode not enabled and not a supervised node"); + return zeek::val_mgr->Int(-1); %} diff --git a/src/threading/Manager.cc b/src/threading/Manager.cc index 58d6c30dea..416716d02c 100644 --- a/src/threading/Manager.cc +++ b/src/threading/Manager.cc @@ -164,8 +164,8 @@ bool Manager::SendEvent(MsgThread* thread, const std::string& name, const int nu for ( int j = 0; j < num_vals; j++) { - Val* v = Value::ValueToVal(std::string("thread ") + thread->Name(), vals[j], convert_error); - vl.emplace_back(AdoptRef{}, v); + zeek::Val* v = Value::ValueToVal(std::string("thread ") + thread->Name(), vals[j], convert_error); + vl.emplace_back(zeek::AdoptRef{}, v); if ( v && ! convert_error && ! same_type(type->GetFieldType(j), v->GetType()) ) { diff --git a/src/threading/MsgThread.h b/src/threading/MsgThread.h index c95a424777..ede4332a77 100644 --- a/src/threading/MsgThread.h +++ b/src/threading/MsgThread.h @@ -8,8 +8,6 @@ #include "iosource/IOSource.h" #include "Flare.h" -class BroObj; - namespace threading { class BasicInputMessage; diff --git a/src/threading/SerialTypes.cc b/src/threading/SerialTypes.cc index c2a0610561..8fcc3f3a10 100644 --- a/src/threading/SerialTypes.cc +++ b/src/threading/SerialTypes.cc @@ -6,7 +6,7 @@ #include "Reporter.h" // The following are required for ValueToVal. #include "Val.h" -#include "BroString.h" +#include "ZeekString.h" #include "RE.h" #include "module_util.h" #include "ID.h" @@ -436,7 +436,7 @@ void Value::delete_value_ptr_array(Value** vals, int num_fields) delete [] vals; } -Val* Value::ValueToVal(const std::string& source, const Value* val, bool& have_error) +zeek::Val* Value::ValueToVal(const std::string& source, const Value* val, bool& have_error) { if ( have_error ) return nullptr; @@ -446,32 +446,32 @@ Val* Value::ValueToVal(const std::string& source, const Value* val, bool& have_e switch ( val->type ) { case zeek::TYPE_BOOL: - return val_mgr->Bool(val->val.int_val)->Ref(); + return zeek::val_mgr->Bool(val->val.int_val)->Ref(); case zeek::TYPE_INT: - return val_mgr->Int(val->val.int_val).release(); + return zeek::val_mgr->Int(val->val.int_val).release(); case zeek::TYPE_COUNT: case zeek::TYPE_COUNTER: - return val_mgr->Count(val->val.int_val).release(); + return zeek::val_mgr->Count(val->val.int_val).release(); case zeek::TYPE_DOUBLE: - return new DoubleVal(val->val.double_val); + return new zeek::DoubleVal(val->val.double_val); case zeek::TYPE_TIME: - return new TimeVal(val->val.double_val); + return new zeek::TimeVal(val->val.double_val); case zeek::TYPE_INTERVAL: - return new IntervalVal(val->val.double_val); + return new zeek::IntervalVal(val->val.double_val); case zeek::TYPE_STRING: { - BroString *s = new BroString((const u_char*)val->val.string_val.data, val->val.string_val.length, true); - return new StringVal(s); + auto* s = new zeek::String((const u_char*)val->val.string_val.data, val->val.string_val.length, true); + return new zeek::StringVal(s); } case zeek::TYPE_PORT: - return val_mgr->Port(val->val.port_val.port, val->val.port_val.proto)->Ref(); + return zeek::val_mgr->Port(val->val.port_val.port, val->val.port_val.proto)->Ref(); case zeek::TYPE_ADDR: { @@ -489,7 +489,7 @@ Val* Value::ValueToVal(const std::string& source, const Value* val, bool& have_e assert(false); } - AddrVal* addrval = new AddrVal(*addr); + auto* addrval = new zeek::AddrVal(*addr); delete addr; return addrval; } @@ -510,7 +510,7 @@ Val* Value::ValueToVal(const std::string& source, const Value* val, bool& have_e assert(false); } - SubNetVal* subnetval = new SubNetVal(*addr, val->val.subnet_val.length); + auto* subnetval = new zeek::SubNetVal(*addr, val->val.subnet_val.length); delete addr; return subnetval; } @@ -519,15 +519,15 @@ Val* Value::ValueToVal(const std::string& source, const Value* val, bool& have_e { RE_Matcher* re = new RE_Matcher(val->val.pattern_text_val); re->Compile(); - return new PatternVal(re); + return new zeek::PatternVal(re); } case zeek::TYPE_TABLE: { - IntrusivePtr set_index; + zeek::TypeListPtr set_index; if ( val->val.set_val.size == 0 && val->subtype == zeek::TYPE_VOID ) // don't know type - unspecified table. - set_index = make_intrusive(); + set_index = zeek::make_intrusive(); else { // all entries have to have the same type... @@ -535,14 +535,14 @@ Val* Value::ValueToVal(const std::string& source, const Value* val, bool& have_e if ( stag == zeek::TYPE_VOID ) stag = val->val.set_val.vals[0]->type; - IntrusivePtr index_type; + zeek::TypePtr index_type; if ( stag == zeek::TYPE_ENUM ) { // Enums are not a base-type, so need to look it up. const auto& sv = val->val.set_val.vals[0]->val.string_val; std::string enum_name(sv.data, sv.length); - const auto& enum_id = global_scope()->Find(enum_name); + const auto& enum_id = zeek::detail::global_scope()->Find(enum_name); if ( ! enum_id ) { @@ -558,16 +558,16 @@ Val* Value::ValueToVal(const std::string& source, const Value* val, bool& have_e else index_type = zeek::base_type(stag); - set_index = make_intrusive(index_type); + set_index = zeek::make_intrusive(index_type); set_index->Append(std::move(index_type)); } - auto s = make_intrusive(std::move(set_index), nullptr); - TableVal* t = new TableVal(std::move(s)); + auto s = zeek::make_intrusive(std::move(set_index), nullptr); + auto* t = new zeek::TableVal(std::move(s)); for ( int j = 0; j < val->val.set_val.size; j++ ) { - Val* assignval = ValueToVal(source, val->val.set_val.vals[j], have_error); - t->Assign({AdoptRef{}, assignval}, nullptr); + zeek::Val* assignval = ValueToVal(source, val->val.set_val.vals[j], have_error); + t->Assign({zeek::AdoptRef{}, assignval}, nullptr); } return t; @@ -575,7 +575,7 @@ Val* Value::ValueToVal(const std::string& source, const Value* val, bool& have_e case zeek::TYPE_VECTOR: { - IntrusivePtr type; + zeek::TypePtr type; if ( val->val.vector_val.size == 0 && val->subtype == zeek::TYPE_VOID ) // don't know type - unspecified table. @@ -589,13 +589,13 @@ Val* Value::ValueToVal(const std::string& source, const Value* val, bool& have_e type = zeek::base_type(val->subtype); } - auto vt = make_intrusive(std::move(type)); - auto v = make_intrusive(std::move(vt)); + auto vt = zeek::make_intrusive(std::move(type)); + auto v = zeek::make_intrusive(std::move(vt)); for ( int j = 0; j < val->val.vector_val.size; j++ ) { auto el = ValueToVal(source, val->val.vector_val.vals[j], have_error); - v->Assign(j, {AdoptRef{}, el}); + v->Assign(j, {zeek::AdoptRef{}, el}); } return v.release(); @@ -607,7 +607,7 @@ Val* Value::ValueToVal(const std::string& source, const Value* val, bool& have_e std::string enum_string(val->val.string_val.data, val->val.string_val.length); // let's try looking it up by global ID. - const auto& id = lookup_ID(enum_string.c_str(), GLOBAL_MODULE_NAME); + const auto& id = zeek::detail::lookup_ID(enum_string.c_str(), GLOBAL_MODULE_NAME); if ( ! id || ! id->IsEnumConst() ) { diff --git a/src/threading/SerialTypes.h b/src/threading/SerialTypes.h index 954ed1e26f..87d4f70505 100644 --- a/src/threading/SerialTypes.h +++ b/src/threading/SerialTypes.h @@ -207,7 +207,7 @@ struct Value { * immediately aborts. * @return Val representation of the threading::Value. nullptr on error. */ - static Val* ValueToVal(const std::string& source, const threading::Value* val, bool& have_error); + static zeek::Val* ValueToVal(const std::string& source, const threading::Value* val, bool& have_error); private: friend class ::IPAddr; diff --git a/src/util.cc b/src/util.cc index 1273b047df..b54f9d5ade 100644 --- a/src/util.cc +++ b/src/util.cc @@ -1813,7 +1813,7 @@ string find_script_file(const string& filename, const string& path_set) return string(); } -FILE* rotate_file(const char* name, RecordVal* rotate_info) +FILE* rotate_file(const char* name, zeek::RecordVal* rotate_info) { // Build file names. const int buflen = strlen(name) + 128; @@ -1859,10 +1859,10 @@ FILE* rotate_file(const char* name, RecordVal* rotate_info) // Init rotate_info. if ( rotate_info ) { - rotate_info->Assign(0, name); - rotate_info->Assign(1, newname); - rotate_info->Assign(2, network_time); - rotate_info->Assign(3, network_time); + rotate_info->Assign(0, name); + rotate_info->Assign(1, newname); + rotate_info->Assign(2, network_time); + rotate_info->Assign(3, network_time); } return newf; diff --git a/src/util.h b/src/util.h index 045db03b5d..3bfee23e6e 100644 --- a/src/util.h +++ b/src/util.h @@ -61,11 +61,6 @@ extern HeapLeakChecker* heap_checker; #include #endif -// Note: macro for internal use only during deprecation/namespacing process. -#define ZEEK_FORWARD_DECLARE_NAMESPACED(cls, ns) \ - namespace ns { class cls; } \ - using cls [[deprecated("Remove in v4.1. Use " #ns "::" #cls " instead.")]] = ns::cls; - [[deprecated("Remove in v4.1. Use uint64_t instead.")]] typedef uint64_t uint64; [[deprecated("Remove in v4.1. Use uint32_t instead.")]] @@ -386,8 +381,8 @@ FILE* open_package(std::string& path, const std::string& mode = "r"); // Renames the given file to a new temporary name, and opens a new file with // the original name. Returns new file or NULL on error. Inits rotate_info if // given (open time is set network time). -class RecordVal; -extern FILE* rotate_file(const char* name, RecordVal* rotate_info); +ZEEK_FORWARD_DECLARE_NAMESPACED(RecordVal, zeek); +extern FILE* rotate_file(const char* name, zeek::RecordVal* rotate_info); // This mimics the script-level function with the same name. const char* log_file_name(const char* tag); diff --git a/src/zeek-setup.cc b/src/zeek-setup.cc index 0563f5ef7d..15c9e5b9d9 100644 --- a/src/zeek-setup.cc +++ b/src/zeek-setup.cc @@ -87,7 +87,8 @@ int perftools_profile = 0; DNS_Mgr* dns_mgr; TimerMgr* timer_mgr; -ValManager* val_mgr = nullptr; +zeek::ValManager* zeek::val_mgr = nullptr; +zeek::ValManager*& val_mgr = zeek::val_mgr; logging::Manager* log_mgr = nullptr; threading::Manager* thread_mgr = nullptr; input::Manager* input_mgr = nullptr; @@ -114,16 +115,16 @@ vector params; set requested_plugins; const char* proc_status_file = nullptr; -IntrusivePtr md5_type; -IntrusivePtr sha1_type; -IntrusivePtr sha256_type; -IntrusivePtr entropy_type; -IntrusivePtr cardinality_type; -IntrusivePtr topk_type; -IntrusivePtr bloomfilter_type; -IntrusivePtr x509_opaque_type; -IntrusivePtr ocsp_resp_opaque_type; -IntrusivePtr paraglob_type; +zeek::OpaqueTypePtr md5_type; +zeek::OpaqueTypePtr sha1_type; +zeek::OpaqueTypePtr sha256_type; +zeek::OpaqueTypePtr entropy_type; +zeek::OpaqueTypePtr cardinality_type; +zeek::OpaqueTypePtr topk_type; +zeek::OpaqueTypePtr bloomfilter_type; +zeek::OpaqueTypePtr x509_opaque_type; +zeek::OpaqueTypePtr ocsp_resp_opaque_type; +zeek::OpaqueTypePtr paraglob_type; // Keep copy of command line int bro_argc; @@ -220,7 +221,7 @@ void done_with_network() mgr.Drain(); // Don't propagate this event to remote clients. mgr.Dispatch(new Event(net_done, - {make_intrusive(timer_mgr->Time())}), + {zeek::make_intrusive(timer_mgr->Time())}), true); } @@ -307,10 +308,10 @@ void terminate_bro() delete log_mgr; delete reporter; delete plugin_mgr; - delete val_mgr; + delete zeek::val_mgr; // free the global scope - pop_scope(); + zeek::detail::pop_scope(); reporter = nullptr; } @@ -464,7 +465,7 @@ zeek::detail::SetupResult zeek::detail::setup(int argc, char** argv, bro_start_time = current_time(true); - val_mgr = new ValManager(); + zeek::val_mgr = new ValManager(); reporter = new Reporter(options.abort_on_scripting_errors); thread_mgr = new threading::Manager(); plugin_mgr = new zeek::plugin::Manager(); @@ -593,16 +594,16 @@ zeek::detail::SetupResult zeek::detail::setup(int argc, char** argv, init_event_handlers(); - md5_type = make_intrusive("md5"); - sha1_type = make_intrusive("sha1"); - sha256_type = make_intrusive("sha256"); - entropy_type = make_intrusive("entropy"); - cardinality_type = make_intrusive("cardinality"); - topk_type = make_intrusive("topk"); - bloomfilter_type = make_intrusive("bloomfilter"); - x509_opaque_type = make_intrusive("x509"); - ocsp_resp_opaque_type = make_intrusive("ocsp_resp"); - paraglob_type = make_intrusive("paraglob"); + md5_type = zeek::make_intrusive("md5"); + sha1_type = zeek::make_intrusive("sha1"); + sha256_type = zeek::make_intrusive("sha256"); + entropy_type = zeek::make_intrusive("entropy"); + cardinality_type = zeek::make_intrusive("cardinality"); + topk_type = zeek::make_intrusive("topk"); + bloomfilter_type = zeek::make_intrusive("bloomfilter"); + x509_opaque_type = zeek::make_intrusive("x509"); + ocsp_resp_opaque_type = zeek::make_intrusive("ocsp_resp"); + paraglob_type = zeek::make_intrusive("paraglob"); // The leak-checker tends to produce some false // positives (memory which had already been @@ -689,7 +690,7 @@ zeek::detail::SetupResult zeek::detail::setup(int argc, char** argv, if ( ! id ) reporter->InternalError("global cmd_line_bpf_filter not defined"); - id->SetVal(make_intrusive(*options.pcap_filter)); + id->SetVal(zeek::make_intrusive(*options.pcap_filter)); } auto all_signature_files = options.signature_files; @@ -843,9 +844,8 @@ zeek::detail::SetupResult zeek::detail::setup(int argc, char** argv, continue; mgr.Enqueue(zeek_script_loaded, - make_intrusive(i->name.c_str()), - val_mgr->Count(i->include_level) - ); + zeek::make_intrusive(i->name.c_str()), + zeek::val_mgr->Count(i->include_level)); } } diff --git a/src/zeek.bif b/src/zeek.bif index d63bf1453f..a390bae068 100644 --- a/src/zeek.bif +++ b/src/zeek.bif @@ -66,7 +66,7 @@ static int check_fmt_type(zeek::TypeTag t, zeek::TypeTag ok[]) return 0; } -static void do_fmt(const char*& fmt, Val* v, ODesc* d) +static void do_fmt(const char*& fmt, zeek::Val* v, ODesc* d) { zeek::TypeTag t = v->GetType()->Tag(); zeek::InternalTypeTag it = v->GetType()->InternalType(); @@ -104,7 +104,7 @@ static void do_fmt(const char*& fmt, Val* v, ODesc* d) if ( field_width > 128 || precision > 128 ) { - builtin_error("excessive field width or precision"); + zeek::emit_builtin_error("excessive field width or precision"); return; } @@ -130,7 +130,7 @@ static void do_fmt(const char*& fmt, Val* v, ODesc* d) s.SetStyle(RAW_STYLE); if ( precision >= 0 && *fmt != 'e' && *fmt != 'f' && *fmt != 'g' ) - builtin_error("precision specified for non-floating point"); + zeek::emit_builtin_error("precision specified for non-floating point"); switch ( *fmt ) { case 'D': @@ -138,7 +138,7 @@ static void do_fmt(const char*& fmt, Val* v, ODesc* d) { if ( t != zeek::TYPE_TIME ) { - builtin_error("bad type for Date/Time format", v); + zeek::emit_builtin_error("bad type for Date/Time format", v); break; } @@ -190,7 +190,7 @@ static void do_fmt(const char*& fmt, Val* v, ODesc* d) else if ( ! check_fmt_type(t, ok_d_fmt) ) { - builtin_error("bad type for %d/%x format", v); + zeek::emit_builtin_error("bad type for %d/%x format", v); break; } @@ -233,7 +233,7 @@ static void do_fmt(const char*& fmt, Val* v, ODesc* d) { if ( ! check_fmt_type(t, ok_f_fmt) ) { - builtin_error("bad type for floating-point format", v); + zeek::emit_builtin_error("bad type for floating-point format", v); break; } @@ -244,7 +244,7 @@ static void do_fmt(const char*& fmt, Val* v, ODesc* d) break; default: - builtin_error("bad format"); + zeek::emit_builtin_error("bad format"); } // Left-padding with whitespace, if any. @@ -319,7 +319,7 @@ static int next_fmt(const char*& fmt, const zeek::Args* args, ODesc* d, int& n) ## .. zeek:see:: network_time function current_time%(%): time %{ - return make_intrusive(current_time()); + return zeek::make_intrusive(current_time()); %} ## Returns the timestamp of the last packet processed. This function returns @@ -331,7 +331,7 @@ function current_time%(%): time ## .. zeek:see:: current_time function network_time%(%): time %{ - return make_intrusive(network_time); + return zeek::make_intrusive(network_time); %} ## Returns a system environment variable. @@ -347,7 +347,7 @@ function getenv%(var: string%): string const char* env_val = zeekenv(var->CheckString()); if ( ! env_val ) env_val = ""; // ### - return make_intrusive(env_val); + return zeek::make_intrusive(env_val); %} ## Sets a system environment variable. @@ -365,8 +365,8 @@ function setenv%(var: string, val: string%): bool val->AsString()->CheckString(), 1); if ( result < 0 ) - return val_mgr->False(); - return val_mgr->True(); + return zeek::val_mgr->False(); + return zeek::val_mgr->True(); %} ## Shuts down the Zeek process immediately. @@ -389,17 +389,17 @@ function exit%(code: int%): any function terminate%(%): bool %{ if ( terminating ) - return val_mgr->False(); + return zeek::val_mgr->False(); terminate_processing(); - return val_mgr->True(); + return zeek::val_mgr->True(); %} %%{ // Turns the table into environment variables (if 'set' is true) or removes // all environment variables previously generated from this table (if 'set' // is false). -static bool prepare_environment(TableVal* tbl, bool set) +static bool prepare_environment(zeek::TableVal* tbl, bool set) { auto idxs = tbl->ToPureListVal(); @@ -411,7 +411,7 @@ static bool prepare_environment(TableVal* tbl, bool set) if ( key->GetType()->Tag() != zeek::TYPE_STRING || val->GetType()->Tag() != zeek::TYPE_STRING ) { - builtin_error("system_env() needs a table[string] of string"); + zeek::emit_builtin_error("system_env() needs a table[string] of string"); return false; } @@ -469,7 +469,7 @@ static int do_system(const char* s) function system%(str: string%): int %{ int result = do_system(str->CheckString()); - return val_mgr->Int(result); + return zeek::val_mgr->Int(result); %} ## Invokes a command via the ``system`` function of the OS with a prepared @@ -489,18 +489,18 @@ function system_env%(str: string, env: table_string_of_string%): int %{ if ( env->GetType()->Tag() != zeek::TYPE_TABLE ) { - builtin_error("system_env() requires a table argument"); - return val_mgr->Int(-1); + zeek::emit_builtin_error("system_env() requires a table argument"); + return zeek::val_mgr->Int(-1); } if ( ! prepare_environment(env->AsTableVal(), true) ) - return val_mgr->Int(-1); + return zeek::val_mgr->Int(-1); int result = do_system(str->CheckString()); prepare_environment(env->AsTableVal(), false); - return val_mgr->Int(result); + return zeek::val_mgr->Int(result); %} ## Opens a program with ``popen`` and writes a given string to the returned @@ -521,7 +521,7 @@ function piped_exec%(program: string, to_write: string%): bool if ( ! f ) { reporter->Error("Failed to popen %s", prog); - return val_mgr->False(); + return zeek::val_mgr->False(); } const u_char* input_data = to_write->Bytes(); @@ -534,10 +534,10 @@ function piped_exec%(program: string, to_write: string%): bool if ( bytes_written != input_data_len ) { reporter->Error("Failed to write all given data to %s", prog); - return val_mgr->False(); + return zeek::val_mgr->False(); } - return val_mgr->True(); + return zeek::val_mgr->True(); %} %%{ @@ -561,7 +561,7 @@ function md5_hash%(...%): string %{ unsigned char digest[MD5_DIGEST_LENGTH]; MD5Val::digest(@ARG@, digest); - return make_intrusive(md5_digest_print(digest)); + return zeek::make_intrusive(md5_digest_print(digest)); %} ## Computes the SHA1 hash value of the provided list of arguments. @@ -581,7 +581,7 @@ function sha1_hash%(...%): string %{ unsigned char digest[SHA_DIGEST_LENGTH]; SHA1Val::digest(@ARG@, digest); - return make_intrusive(sha1_digest_print(digest)); + return zeek::make_intrusive(sha1_digest_print(digest)); %} ## Computes the SHA256 hash value of the provided list of arguments. @@ -601,7 +601,7 @@ function sha256_hash%(...%): string %{ unsigned char digest[SHA256_DIGEST_LENGTH]; SHA256Val::digest(@ARG@, digest); - return make_intrusive(sha256_digest_print(digest)); + return zeek::make_intrusive(sha256_digest_print(digest)); %} ## Computes an HMAC-MD5 hash value of the provided list of arguments. The HMAC @@ -617,7 +617,7 @@ function md5_hmac%(...%): string %{ unsigned char hmac[MD5_DIGEST_LENGTH]; MD5Val::hmac(@ARG@, KeyedHash::shared_hmac_md5_key, hmac); - return make_intrusive(md5_digest_print(hmac)); + return zeek::make_intrusive(md5_digest_print(hmac)); %} ## Constructs an MD5 handle to enable incremental hash computation. You can @@ -640,7 +640,7 @@ function md5_hmac%(...%): string ## sha256_hash sha256_hash_init sha256_hash_update sha256_hash_finish function md5_hash_init%(%): opaque of md5 %{ - auto digest = make_intrusive(); + auto digest = zeek::make_intrusive(); digest->Init(); return digest; %} @@ -665,7 +665,7 @@ function md5_hash_init%(%): opaque of md5 ## sha256_hash sha256_hash_init sha256_hash_update sha256_hash_finish function sha1_hash_init%(%): opaque of sha1 %{ - auto digest = make_intrusive(); + auto digest = zeek::make_intrusive(); digest->Init(); return digest; %} @@ -690,7 +690,7 @@ function sha1_hash_init%(%): opaque of sha1 ## sha256_hash sha256_hash_update sha256_hash_finish function sha256_hash_init%(%): opaque of sha256 %{ - auto digest = make_intrusive(); + auto digest = zeek::make_intrusive(); digest->Init(); return digest; %} @@ -711,7 +711,7 @@ function sha256_hash_init%(%): opaque of sha256 function md5_hash_update%(handle: opaque of md5, data: string%): bool %{ bool rc = static_cast(handle)->Feed(data->Bytes(), data->Len()); - return val_mgr->Bool(rc); + return zeek::val_mgr->Bool(rc); %} ## Updates the SHA1 value associated with a given index. It is required to @@ -730,7 +730,7 @@ function md5_hash_update%(handle: opaque of md5, data: string%): bool function sha1_hash_update%(handle: opaque of sha1, data: string%): bool %{ bool rc = static_cast(handle)->Feed(data->Bytes(), data->Len()); - return val_mgr->Bool(rc); + return zeek::val_mgr->Bool(rc); %} ## Updates the SHA256 value associated with a given index. It is required to @@ -749,7 +749,7 @@ function sha1_hash_update%(handle: opaque of sha1, data: string%): bool function sha256_hash_update%(handle: opaque of sha256, data: string%): bool %{ bool rc = static_cast(handle)->Feed(data->Bytes(), data->Len()); - return val_mgr->Bool(rc); + return zeek::val_mgr->Bool(rc); %} ## Returns the final MD5 digest of an incremental hash computation. @@ -815,14 +815,14 @@ function paraglob_init%(v: any%) : opaque of paraglob VectorVal* vv = v->AsVectorVal(); for ( unsigned int i = 0; i < vv->Size(); ++i ) { - const BroString* s = vv->At(i)->AsString(); + const String* s = vv->At(i)->AsString(); patterns.push_back(std::string(reinterpret_cast(s->Bytes()), s->Len())); } try { std::unique_ptr p (new paraglob::Paraglob(patterns)); - return make_intrusive(std::move(p)); + return zeek::make_intrusive(std::move(p)); } // Thrown if paraglob fails to add a pattern. catch (const paraglob::add_error& e) @@ -857,7 +857,7 @@ function paraglob_match%(handle: opaque of paraglob, match: string%): string_vec ## ## .. zeek:see::paraglob_add paraglob_match paraglob_init function paraglob_equals%(p_one: opaque of paraglob, p_two: opaque of paraglob%) : bool %{ - return val_mgr->Bool( + return zeek::val_mgr->Bool( *(static_cast(p_one)) == *(static_cast(p_two)) ); %} @@ -886,7 +886,7 @@ function fnv1a32%(input: any%): count rval *= prime32; } - return val_mgr->Count(rval); + return zeek::val_mgr->Count(rval); %} ## Calculates a weight value for use in a Rendezvous Hashing algorithm. @@ -913,7 +913,7 @@ function hrw_weight%(key_digest: count, site_id: count%): count uint32_t rval = (a * ((a * si + b) ^ d) + b) % m; - return val_mgr->Count(rval); + return zeek::val_mgr->Count(rval); %} ## Generates a random number. @@ -931,7 +931,7 @@ function hrw_weight%(key_digest: count, site_id: count%): count function rand%(max: count%): count %{ auto result = bro_uint_t(double(max) * double(bro_random()) / (RAND_MAX + 1.0)); - return val_mgr->Count(result); + return zeek::val_mgr->Count(result); %} ## Sets the seed for subsequent :zeek:id:`rand` calls. @@ -983,9 +983,9 @@ function identify_data%(data: string, return_mime: bool &default=T%): string string strongest_match = file_mgr->DetectMIME(data->Bytes(), data->Len()); if ( strongest_match.empty() ) - return make_intrusive(""); + return zeek::make_intrusive(""); - return make_intrusive(strongest_match); + return zeek::make_intrusive(strongest_match); %} ## Determines the MIME type of a piece of data using Zeek's file magic @@ -1052,12 +1052,12 @@ function find_entropy%(data: string%): entropy_test_result e.Get(&ent, &chisq, &mean, &montepi, &scc); static auto entropy_test_result = zeek::id::find_type("entropy_test_result"); - auto ent_result = make_intrusive(entropy_test_result); - ent_result->Assign(0, make_intrusive(ent)); - ent_result->Assign(1, make_intrusive(chisq)); - ent_result->Assign(2, make_intrusive(mean)); - ent_result->Assign(3, make_intrusive(montepi)); - ent_result->Assign(4, make_intrusive(scc)); + auto ent_result = zeek::make_intrusive(entropy_test_result); + ent_result->Assign(0, zeek::make_intrusive(ent)); + ent_result->Assign(1, zeek::make_intrusive(chisq)); + ent_result->Assign(2, zeek::make_intrusive(mean)); + ent_result->Assign(3, zeek::make_intrusive(montepi)); + ent_result->Assign(4, zeek::make_intrusive(scc)); return ent_result; %} @@ -1068,7 +1068,7 @@ function find_entropy%(data: string%): entropy_test_result ## .. zeek:see:: find_entropy entropy_test_add entropy_test_finish function entropy_test_init%(%): opaque of entropy %{ - return make_intrusive(); + return zeek::make_intrusive(); %} ## Adds data to an incremental entropy calculation. @@ -1084,7 +1084,7 @@ function entropy_test_add%(handle: opaque of entropy, data: string%): bool %{ bool status = static_cast(handle)->Feed(data->Bytes(), data->Len()); - return val_mgr->Bool(status); + return zeek::val_mgr->Bool(status); %} ## Finishes an incremental entropy calculation. Before using this function, @@ -1104,12 +1104,12 @@ function entropy_test_finish%(handle: opaque of entropy%): entropy_test_result static_cast(handle)->Get(&ent, &chisq, &mean, &montepi, &scc); static auto entropy_test_result = zeek::id::find_type("entropy_test_result"); - auto ent_result = make_intrusive(entropy_test_result); - ent_result->Assign(0, make_intrusive(ent)); - ent_result->Assign(1, make_intrusive(chisq)); - ent_result->Assign(2, make_intrusive(mean)); - ent_result->Assign(3, make_intrusive(montepi)); - ent_result->Assign(4, make_intrusive(scc)); + auto ent_result = zeek::make_intrusive(entropy_test_result); + ent_result->Assign(0, zeek::make_intrusive(ent)); + ent_result->Assign(1, zeek::make_intrusive(chisq)); + ent_result->Assign(2, zeek::make_intrusive(mean)); + ent_result->Assign(3, zeek::make_intrusive(montepi)); + ent_result->Assign(4, zeek::make_intrusive(scc)); return ent_result; %} @@ -1124,7 +1124,7 @@ function unique_id%(prefix: string%) : string %{ char tmp[20]; uint64_t uid = calculate_unique_id(UID_POOL_DEFAULT_SCRIPT); - return make_intrusive(uitoa_n(uid, tmp, sizeof(tmp), 62, prefix->CheckString())); + return zeek::make_intrusive(uitoa_n(uid, tmp, sizeof(tmp), 62, prefix->CheckString())); %} ## Creates an identifier that is unique with high probability. @@ -1142,7 +1142,7 @@ function unique_id_from%(pool: int, prefix: string%) : string char tmp[20]; uint64_t uid = calculate_unique_id(pool); - return make_intrusive(uitoa_n(uid, tmp, sizeof(tmp), 62, prefix->CheckString())); + return zeek::make_intrusive(uitoa_n(uid, tmp, sizeof(tmp), 62, prefix->CheckString())); %} # =========================================================================== @@ -1159,7 +1159,7 @@ function clear_table%(v: any%): any if ( v->GetType()->Tag() == zeek::TYPE_TABLE ) v->AsTableVal()->RemoveAll(); else - builtin_error("clear_table() requires a table/set argument"); + zeek::emit_builtin_error("clear_table() requires a table/set argument"); return nullptr; %} @@ -1227,7 +1227,7 @@ function check_subnet%(search: subnet, t: any%): bool void* res = pt->Lookup(search, true); - return val_mgr->Bool(res != nullptr); + return zeek::val_mgr->Bool(res != nullptr); %} ## Checks whether two objects reference the same internal object. This function @@ -1241,7 +1241,7 @@ function check_subnet%(search: subnet, t: any%): bool ## Returns: True if *o1* and *o2* are equal. function same_object%(o1: any, o2: any%): bool %{ - return val_mgr->Bool(o1 == o2); + return zeek::val_mgr->Bool(o1 == o2); %} ## Returns the number of bytes that a value occupies in memory. @@ -1251,7 +1251,7 @@ function same_object%(o1: any, o2: any%): bool ## Returns: The number of bytes that *v* occupies. function val_size%(v: any%): count %{ - return val_mgr->Count(v->MemoryAllocation()); + return zeek::val_mgr->Count(v->MemoryAllocation()); %} ## Resizes a vector. @@ -1265,11 +1265,11 @@ function resize%(aggr: any, newsize: count%) : count %{ if ( aggr->GetType()->Tag() != zeek::TYPE_VECTOR ) { - builtin_error("resize() operates on vectors"); + zeek::emit_builtin_error("resize() operates on vectors"); return nullptr; } - return val_mgr->Count(aggr->AsVectorVal()->Resize(newsize)); + return zeek::val_mgr->Count(aggr->AsVectorVal()->Resize(newsize)); %} ## Tests whether a boolean vector (``vector of bool``) has *any* true @@ -1285,16 +1285,16 @@ function any_set%(v: any%) : bool if ( v->GetType()->Tag() != zeek::TYPE_VECTOR || v->GetType()->Yield()->Tag() != zeek::TYPE_BOOL ) { - builtin_error("any_set() requires vector of bool"); - return val_mgr->False(); + zeek::emit_builtin_error("any_set() requires vector of bool"); + return zeek::val_mgr->False(); } VectorVal* vv = v->AsVectorVal(); for ( unsigned int i = 0; i < vv->Size(); ++i ) if ( vv->At(i) && vv->At(i)->AsBool() ) - return val_mgr->True(); + return zeek::val_mgr->True(); - return val_mgr->False(); + return zeek::val_mgr->False(); %} ## Tests whether *all* elements of a boolean vector (``vector of bool``) are @@ -1314,23 +1314,23 @@ function all_set%(v: any%) : bool if ( v->GetType()->Tag() != zeek::TYPE_VECTOR || v->GetType()->Yield()->Tag() != zeek::TYPE_BOOL ) { - builtin_error("all_set() requires vector of bool"); - return val_mgr->False(); + zeek::emit_builtin_error("all_set() requires vector of bool"); + return zeek::val_mgr->False(); } VectorVal* vv = v->AsVectorVal(); for ( unsigned int i = 0; i < vv->Size(); ++i ) if ( ! vv->At(i) || ! vv->At(i)->AsBool() ) - return val_mgr->False(); + return zeek::val_mgr->False(); - return val_mgr->True(); + return zeek::val_mgr->True(); %} %%{ -static Func* sort_function_comp = nullptr; -static std::vector*> index_map; // used for indirect sorting to support order() +static zeek::Func* sort_function_comp = nullptr; +static std::vector index_map; // used for indirect sorting to support order() -bool sort_function(const IntrusivePtr& a, const IntrusivePtr& b) +bool sort_function(const zeek::ValPtr& a, const zeek::ValPtr& b) { // Sort missing values as "high". if ( ! a ) @@ -1349,7 +1349,7 @@ bool indirect_sort_function(size_t a, size_t b) return sort_function(*index_map[a], *index_map[b]); } -bool signed_sort_function (const IntrusivePtr& a, const IntrusivePtr& b) +bool signed_sort_function (const zeek::ValPtr& a, const zeek::ValPtr& b) { if ( ! a ) return 0; @@ -1362,7 +1362,7 @@ bool signed_sort_function (const IntrusivePtr& a, const IntrusivePtr& return ia < ib; } -bool unsigned_sort_function (const IntrusivePtr& a, const IntrusivePtr& b) +bool unsigned_sort_function (const zeek::ValPtr& a, const zeek::ValPtr& b) { if ( ! a ) return 0; @@ -1401,26 +1401,26 @@ bool indirect_unsigned_sort_function(size_t a, size_t b) ## .. zeek:see:: order function sort%(v: any, ...%) : any %{ - IntrusivePtr rval{NewRef{}, v}; + zeek::ValPtr rval{zeek::NewRef{}, v}; if ( v->GetType()->Tag() != zeek::TYPE_VECTOR ) { - builtin_error("sort() requires vector"); + zeek::emit_builtin_error("sort() requires vector"); return rval; } const auto& elt_type = v->GetType()->Yield(); - Func* comp = 0; + zeek::Func* comp = nullptr; if ( @ARG@.size() > 2 ) - builtin_error("sort() called with extraneous argument"); + zeek::emit_builtin_error("sort() called with extraneous argument"); if ( @ARG@.size() == 2 ) { Val* comp_val = @ARG@[1].get(); if ( ! IsFunc(comp_val->GetType()->Tag()) ) { - builtin_error("second argument to sort() needs to be comparison function"); + zeek::emit_builtin_error("second argument to sort() needs to be comparison function"); return rval; } @@ -1428,7 +1428,7 @@ function sort%(v: any, ...%) : any } if ( ! comp && ! IsIntegral(elt_type->Tag()) ) - builtin_error("comparison function required for sort() with non-integral types"); + zeek::emit_builtin_error("comparison function required for sort() with non-integral types"); auto& vv = *v->AsVector(); @@ -1439,7 +1439,7 @@ function sort%(v: any, ...%) : any if ( comp_type->Yield()->Tag() != zeek::TYPE_INT || ! comp_type->ParamList()->AllMatch(elt_type, 0) ) { - builtin_error("invalid comparison function in call to sort()"); + zeek::emit_builtin_error("invalid comparison function in call to sort()"); return rval; } @@ -1471,34 +1471,34 @@ function sort%(v: any, ...%) : any ## .. zeek:see:: sort function order%(v: any, ...%) : index_vec %{ - auto result_v = make_intrusive(zeek::id::index_vec); + auto result_v = zeek::make_intrusive(zeek::id::index_vec); if ( v->GetType()->Tag() != zeek::TYPE_VECTOR ) { - builtin_error("order() requires vector"); + zeek::emit_builtin_error("order() requires vector"); return result_v; } const auto& elt_type = v->GetType()->Yield(); - Func* comp = 0; + zeek::Func* comp = nullptr; if ( @ARG@.size() > 2 ) - builtin_error("order() called with extraneous argument"); + zeek::emit_builtin_error("order() called with extraneous argument"); if ( @ARG@.size() == 2 ) { Val* comp_val = @ARG@[1].get(); if ( ! IsFunc(comp_val->GetType()->Tag()) ) { - builtin_error("second argument to order() needs to be comparison function"); - return IntrusivePtr{NewRef{}, v}; + zeek::emit_builtin_error("second argument to order() needs to be comparison function"); + return zeek::ValPtr{zeek::NewRef{}, v}; } comp = comp_val->AsFunc(); } if ( ! comp && ! IsIntegral(elt_type->Tag()) ) - builtin_error("comparison function required for order() with non-integral types"); + zeek::emit_builtin_error("comparison function required for order() with non-integral types"); auto& vv = *v->AsVector(); auto n = vv.size(); @@ -1520,8 +1520,8 @@ function order%(v: any, ...%) : index_vec if ( comp_type->Yield()->Tag() != zeek::TYPE_INT || ! comp_type->ParamList()->AllMatch(elt_type, 0) ) { - builtin_error("invalid comparison function in call to order()"); - return IntrusivePtr{NewRef{}, v}; + zeek::emit_builtin_error("invalid comparison function in call to order()"); + return zeek::ValPtr{zeek::NewRef{}, v}; } sort_function_comp = comp; @@ -1542,7 +1542,7 @@ function order%(v: any, ...%) : index_vec for ( i = 0; i < n; ++i ) { int ind = ind_vv[i]; - result_v->Assign(i, val_mgr->Count(ind)); + result_v->Assign(i, zeek::val_mgr->Count(ind)); } return result_v; @@ -1567,10 +1567,10 @@ function cat%(...%): string for ( const auto& a : @ARG@ ) a->Describe(&d); - BroString* s = new BroString(1, d.TakeBytes(), d.Len()); + String* s = new String(1, d.TakeBytes(), d.Len()); s->SetUseFreeToDelete(true); - return make_intrusive(s); + return zeek::make_intrusive(s); %} ## Concatenates all arguments, with a separator placed between each one. This @@ -1609,10 +1609,10 @@ function cat_sep%(sep: string, def: string, ...%): string v->Describe(&d); } - BroString* s = new BroString(1, d.TakeBytes(), d.Len()); + String* s = new String(1, d.TakeBytes(), d.Len()); s->SetUseFreeToDelete(true); - return make_intrusive(s); + return zeek::make_intrusive(s); %} ## Produces a formatted string à la ``printf``. The first argument is the @@ -1656,7 +1656,7 @@ function cat_sep%(sep: string, def: string, ...%): string function fmt%(...%): string %{ if ( @ARGC@ == 0 ) - return val_mgr->EmptyString(); + return zeek::val_mgr->EmptyString(); Val* fmt_v = @ARG@[0].get(); @@ -1674,20 +1674,20 @@ function fmt%(...%): string if ( n < static_cast(@ARGC@) - 1 ) { - builtin_error("too many arguments for format", fmt_v); - return val_mgr->EmptyString(); + zeek::emit_builtin_error("too many arguments for format", fmt_v); + return zeek::val_mgr->EmptyString(); } else if ( n >= static_cast(@ARGC@) ) { - builtin_error("too few arguments for format", fmt_v); - return val_mgr->EmptyString(); + zeek::emit_builtin_error("too few arguments for format", fmt_v); + return zeek::val_mgr->EmptyString(); } - BroString* s = new BroString(1, d.TakeBytes(), d.Len()); + String* s = new String(1, d.TakeBytes(), d.Len()); s->SetUseFreeToDelete(true); - return make_intrusive(s); + return zeek::make_intrusive(s); %} ## Renders a sequence of values to a string of bytes and outputs them directly @@ -1703,7 +1703,7 @@ function print_raw%(...%): bool d.SetStyle(RAW_STYLE); describe_vals(@ARG@, &d, 0); printf("%.*s", d.Len(), d.Description()); - return val_mgr->Bool(true); + return zeek::val_mgr->Bool(true); %} # =========================================================================== @@ -1723,7 +1723,7 @@ function print_raw%(...%): bool ## .. zeek:see:: sqrt exp ln log10 function floor%(d: double%): double %{ - return make_intrusive(floor(d)); + return zeek::make_intrusive(floor(d)); %} ## Computes the square root of a :zeek:type:`double`. @@ -1738,10 +1738,10 @@ function sqrt%(x: double%): double if ( x < 0 ) { reporter->Error("negative sqrt argument"); - return make_intrusive(-1.0); + return zeek::make_intrusive(-1.0); } - return make_intrusive(sqrt(x)); + return zeek::make_intrusive(sqrt(x)); %} ## Computes the exponential function. @@ -1753,7 +1753,7 @@ function sqrt%(x: double%): double ## .. zeek:see:: floor sqrt ln log10 function exp%(d: double%): double %{ - return make_intrusive(exp(d)); + return zeek::make_intrusive(exp(d)); %} ## Computes the natural logarithm of a number. @@ -1765,7 +1765,7 @@ function exp%(d: double%): double ## .. zeek:see:: exp floor sqrt log10 function ln%(d: double%): double %{ - return make_intrusive(log(d)); + return zeek::make_intrusive(log(d)); %} ## Computes the common logarithm of a number. @@ -1777,7 +1777,7 @@ function ln%(d: double%): double ## .. zeek:see:: exp floor sqrt ln function log10%(d: double%): double %{ - return make_intrusive(log10(d)); + return zeek::make_intrusive(log10(d)); %} # =========================================================================== @@ -1792,7 +1792,7 @@ function log10%(d: double%): double ## none. function current_analyzer%(%) : count %{ - return val_mgr->Count(mgr.CurrentAnalyzer()); + return zeek::val_mgr->Count(mgr.CurrentAnalyzer()); %} ## Returns Zeek's process ID. @@ -1800,7 +1800,7 @@ function current_analyzer%(%) : count ## Returns: Zeek's process ID. function getpid%(%) : count %{ - return val_mgr->Count(getpid()); + return zeek::val_mgr->Count(getpid()); %} %%{ @@ -1812,7 +1812,7 @@ extern const char* zeek_version(); ## Returns: Zeek's version, e.g., 2.0-beta-47-debug. function zeek_version%(%): string %{ - return make_intrusive(zeek_version()); + return zeek::make_intrusive(zeek_version()); %} ## Converts a record type name to a vector of strings, where each element is @@ -1823,12 +1823,12 @@ function zeek_version%(%): string ## Returns: A string vector with the field names of *rt*. function record_type_to_vector%(rt: string%): string_vec %{ - auto result = make_intrusive(zeek::id::string_vec); + auto result = zeek::make_intrusive(zeek::id::string_vec); zeek::RecordType* type = zeek::id::find_type(rt->CheckString())->AsRecordType(); for ( int i = 0; i < type->NumFields(); ++i ) - result->Assign(i+1, make_intrusive(type->FieldName(i))); + result->Assign(i+1, zeek::make_intrusive(type->FieldName(i))); return result; %} @@ -1843,20 +1843,20 @@ function type_name%(t: any%): string ODesc d; t->GetType()->Describe(&d); - BroString* s = new BroString(1, d.TakeBytes(), d.Len()); + String* s = new String(1, d.TakeBytes(), d.Len()); s->SetUseFreeToDelete(true); - return make_intrusive(s); + return zeek::make_intrusive(s); %} ## Returns: list of command-line arguments (``argv``) used to run Zeek. function zeek_args%(%): string_vec %{ auto sv = zeek::id::string_vec; - auto rval = make_intrusive(std::move(sv)); + auto rval = zeek::make_intrusive(std::move(sv)); for ( auto i = 0; i < bro_argc; ++i ) - rval->Assign(rval->Size(), make_intrusive(bro_argv[i])); + rval->Assign(rval->Size(), zeek::make_intrusive(bro_argv[i])); return rval; %} @@ -1871,7 +1871,7 @@ function zeek_args%(%): string_vec ## .. zeek:see:: reading_traces packet_source function reading_live_traffic%(%): bool %{ - return val_mgr->Bool(reading_live); + return zeek::val_mgr->Bool(reading_live); %} ## Checks whether Zeek reads traffic from a trace file (as opposed to from a @@ -1882,7 +1882,7 @@ function reading_live_traffic%(%): bool ## .. zeek:see:: reading_live_traffic packet_source function reading_traces%(%): bool %{ - return val_mgr->Bool(reading_traces); + return zeek::val_mgr->Bool(reading_traces); %} ## Returns: the packet source being read by Zeek. @@ -1892,14 +1892,14 @@ function packet_source%(%): PacketSource %{ static auto ps_type = zeek::id::find_type("PacketSource"); auto ps = iosource_mgr->GetPktSrc(); - auto r = make_intrusive(ps_type); + auto r = zeek::make_intrusive(ps_type); if ( ps ) { - r->Assign(0, val_mgr->Bool(ps->IsLive())); - r->Assign(1, make_intrusive(ps->Path())); - r->Assign(2, val_mgr->Int(ps->LinkType())); - r->Assign(3, val_mgr->Count(ps->Netmask())); + r->Assign(0, zeek::val_mgr->Bool(ps->IsLive())); + r->Assign(1, zeek::make_intrusive(ps->Path())); + r->Assign(2, zeek::val_mgr->Int(ps->LinkType())); + r->Assign(3, zeek::val_mgr->Count(ps->Netmask())); } return r; @@ -1913,16 +1913,16 @@ function packet_source%(%): PacketSource ## .. zeek:see:: global_ids function global_sizes%(%): var_sizes %{ - auto sizes = make_intrusive(IntrusivePtr{NewRef{}, var_sizes}); - const auto& globals = global_scope()->Vars(); + auto sizes = zeek::make_intrusive(IntrusivePtr{zeek::NewRef{}, var_sizes}); + const auto& globals = zeek::detail::global_scope()->Vars(); for ( const auto& global : globals ) { auto& id = global.second; if ( id->HasVal() ) { - auto id_name = make_intrusive(id->Name()); - auto id_size = val_mgr->Count(id->GetVal()->MemoryAllocation()); + auto id_name = zeek::make_intrusive(id->Name()); + auto id_size = zeek::val_mgr->Count(id->GetVal()->MemoryAllocation()); sizes->Assign(std::move(id_name), std::move(id_size)); } } @@ -1941,25 +1941,25 @@ function global_sizes%(%): var_sizes function global_ids%(%): id_table %{ static auto id_table = zeek::id::find_type("id_table"); - auto ids = make_intrusive(id_table); - const auto& globals = global_scope()->Vars(); + auto ids = zeek::make_intrusive(id_table); + const auto& globals = zeek::detail::global_scope()->Vars(); for ( const auto& global : globals ) { const auto& id = global.second; static auto script_id = zeek::id::find_type("script_id"); - auto rec = make_intrusive(script_id); - rec->Assign(0, make_intrusive(type_name(id->GetType()->Tag()))); - rec->Assign(1, val_mgr->Bool(id->IsExport())); - rec->Assign(2, val_mgr->Bool(id->IsConst())); - rec->Assign(3, val_mgr->Bool(id->IsEnumConst())); - rec->Assign(4, val_mgr->Bool(id->IsOption())); - rec->Assign(5, val_mgr->Bool(id->IsRedefinable())); + auto rec = zeek::make_intrusive(script_id); + rec->Assign(0, zeek::make_intrusive(type_name(id->GetType()->Tag()))); + rec->Assign(1, zeek::val_mgr->Bool(id->IsExport())); + rec->Assign(2, zeek::val_mgr->Bool(id->IsConst())); + rec->Assign(3, zeek::val_mgr->Bool(id->IsEnumConst())); + rec->Assign(4, zeek::val_mgr->Bool(id->IsOption())); + rec->Assign(5, zeek::val_mgr->Bool(id->IsRedefinable())); if ( id->HasVal() ) rec->Assign(6, id->GetVal()); - auto id_name = make_intrusive(id->Name()); + auto id_name = zeek::make_intrusive(id->Name()); ids->Assign(std::move(id_name), std::move(rec)); } @@ -1974,12 +1974,12 @@ function global_ids%(%): id_table ## the string ``""`` or ``""`` is returned. function lookup_ID%(id: string%) : any %{ - const auto& i = global_scope()->Find(id->CheckString()); + const auto& i = zeek::detail::global_scope()->Find(id->CheckString()); if ( ! i ) - return make_intrusive(""); + return zeek::make_intrusive(""); if ( ! i->GetVal() ) - return make_intrusive(""); + return zeek::make_intrusive(""); return i->GetVal(); %} @@ -1997,12 +1997,12 @@ function record_fields%(rec: any%): record_field_table if ( rec->GetType()->Tag() == zeek::TYPE_STRING ) { - const auto& id = global_scope()->Find(rec->AsStringVal()->ToStdString()); + const auto& id = zeek::detail::global_scope()->Find(rec->AsStringVal()->ToStdString()); if ( ! id || ! id->IsType() || id->GetType()->Tag() != zeek::TYPE_RECORD ) { reporter->Error("record_fields string argument does not name a record type"); - return make_intrusive(record_field_table); + return zeek::make_intrusive(record_field_table); } return id->GetType()->AsRecordType()->GetRecordFieldsVal(); @@ -2043,7 +2043,7 @@ function do_profiling%(%) : any function is_local_interface%(ip: addr%) : bool %{ if ( ip->AsAddr().IsLoopback() ) - return val_mgr->True(); + return zeek::val_mgr->True(); list addrs; @@ -2075,10 +2075,10 @@ function is_local_interface%(ip: addr%) : bool for ( it = addrs.begin(); it != addrs.end(); ++it ) { if ( *it == ip->AsAddr() ) - return val_mgr->True(); + return zeek::val_mgr->True(); } - return val_mgr->False(); + return zeek::val_mgr->False(); %} ## Write rule matcher statistics (DFA states, transitions, memory usage, cache @@ -2094,7 +2094,7 @@ function dump_rule_stats%(f: file%): bool if ( rule_matcher ) rule_matcher->DumpStats(f); - return val_mgr->True(); + return zeek::val_mgr->True(); %} ## Checks if Zeek is terminating. @@ -2104,7 +2104,7 @@ function dump_rule_stats%(f: file%): bool ## .. zeek:see:: terminate function zeek_is_terminating%(%): bool %{ - return val_mgr->Bool(terminating); + return zeek::val_mgr->Bool(terminating); %} ## Returns the hostname of the machine Zeek runs on. @@ -2117,7 +2117,7 @@ function gethostname%(%) : string strcpy(buffer, ""); buffer[MAXHOSTNAMELEN-1] = '\0'; - return make_intrusive(buffer); + return zeek::make_intrusive(buffer); %} ## Returns whether an address is IPv4 or not. @@ -2128,9 +2128,9 @@ function gethostname%(%) : string function is_v4_addr%(a: addr%): bool %{ if ( a->AsAddr().GetFamily() == IPv4 ) - return val_mgr->True(); + return zeek::val_mgr->True(); else - return val_mgr->False(); + return zeek::val_mgr->False(); %} ## Returns whether an address is IPv6 or not. @@ -2141,9 +2141,9 @@ function is_v4_addr%(a: addr%): bool function is_v6_addr%(a: addr%): bool %{ if ( a->AsAddr().GetFamily() == IPv6 ) - return val_mgr->True(); + return zeek::val_mgr->True(); else - return val_mgr->False(); + return zeek::val_mgr->False(); %} ## Returns whether a subnet specification is IPv4 or not. @@ -2154,9 +2154,9 @@ function is_v6_addr%(a: addr%): bool function is_v4_subnet%(s: subnet%): bool %{ if ( s->AsSubNet().Prefix().GetFamily() == IPv4 ) - return val_mgr->True(); + return zeek::val_mgr->True(); else - return val_mgr->False(); + return zeek::val_mgr->False(); %} ## Returns whether a subnet specification is IPv6 or not. @@ -2167,9 +2167,9 @@ function is_v4_subnet%(s: subnet%): bool function is_v6_subnet%(s: subnet%): bool %{ if ( s->AsSubNet().Prefix().GetFamily() == IPv6 ) - return val_mgr->True(); + return zeek::val_mgr->True(); else - return val_mgr->False(); + return zeek::val_mgr->False(); %} @@ -2188,7 +2188,7 @@ function is_v6_subnet%(s: subnet%): bool ## Returns: The vector of addresses contained in the routing header data. function routing0_data_to_addrs%(s: string%): addr_vec %{ - auto rval = make_intrusive(zeek::id::find_type("addr_vec")); + auto rval = zeek::make_intrusive(zeek::id::find_type("addr_vec")); int len = s->Len(); const u_char* bytes = s->Bytes(); @@ -2201,7 +2201,7 @@ function routing0_data_to_addrs%(s: string%): addr_vec while ( len > 0 ) { IPAddr a(IPv6, (const uint32_t*) bytes, IPAddr::Network); - rval->Assign(rval->Size(), make_intrusive(a)); + rval->Assign(rval->Size(), zeek::make_intrusive(a)); bytes += 16; len -= 16; } @@ -2219,12 +2219,12 @@ function routing0_data_to_addrs%(s: string%): addr_vec ## .. zeek:see:: counts_to_addr function addr_to_counts%(a: addr%): index_vec %{ - auto rval = make_intrusive(zeek::id::index_vec); + auto rval = zeek::make_intrusive(zeek::id::index_vec); const uint32_t* bytes; int len = a->AsAddr().GetBytes(&bytes); for ( int i = 0; i < len; ++i ) - rval->Assign(i, val_mgr->Count(ntohl(bytes[i]))); + rval->Assign(i, zeek::val_mgr->Count(ntohl(bytes[i]))); return rval; %} @@ -2241,21 +2241,21 @@ function counts_to_addr%(v: index_vec%): addr %{ if ( v->AsVector()->size() == 1 ) { - return make_intrusive(htonl((*v->AsVector())[0]->AsCount())); + return zeek::make_intrusive(htonl((*v->AsVector())[0]->AsCount())); } else if ( v->AsVector()->size() == 4 ) { uint32_t bytes[4]; for ( int i = 0; i < 4; ++i ) bytes[i] = htonl((*v->AsVector())[i]->AsCount()); - return make_intrusive(bytes); + return zeek::make_intrusive(bytes); } else { - builtin_error("invalid vector size", @ARG@[0]); + zeek::emit_builtin_error("invalid vector size", @ARG@[0]); uint32_t bytes[4]; memset(bytes, 0, sizeof(bytes)); - return make_intrusive(bytes); + return zeek::make_intrusive(bytes); } %} @@ -2268,11 +2268,11 @@ function enum_to_int%(e: any%): int %{ if ( e->GetType()->Tag() != zeek::TYPE_ENUM ) { - builtin_error("enum_to_int() requires enum value"); - return val_mgr->Int(-1); + zeek::emit_builtin_error("enum_to_int() requires enum value"); + return zeek::val_mgr->Int(-1); } - return val_mgr->Int(e->AsEnum()); + return zeek::val_mgr->Int(e->AsEnum()); %} ## Converts a :zeek:type:`string` to an :zeek:type:`int`. @@ -2293,10 +2293,10 @@ function to_int%(str: string%): int // Not clear we should complain. For example, is " 205 " // a legal conversion? if ( s[0] == '\0' || end_s[0] != '\0' ) - builtin_error("bad conversion to integer", @ARG@[0]); + zeek::emit_builtin_error("bad conversion to integer", @ARG@[0]); #endif - return val_mgr->Int(i); + return zeek::val_mgr->Int(i); %} @@ -2309,10 +2309,10 @@ function int_to_count%(n: int%): count %{ if ( n < 0 ) { - builtin_error("bad conversion to count", @ARG@[0]); + zeek::emit_builtin_error("bad conversion to count", @ARG@[0]); n = 0; } - return val_mgr->Count(n); + return zeek::val_mgr->Count(n); %} ## Converts a :zeek:type:`double` to a :zeek:type:`count`. @@ -2325,9 +2325,9 @@ function int_to_count%(n: int%): count function double_to_count%(d: double%): count %{ if ( d < 0.0 ) - builtin_error("bad conversion to count", @ARG@[0]); + zeek::emit_builtin_error("bad conversion to count", @ARG@[0]); - return val_mgr->Count(bro_uint_t(rint(d))); + return zeek::val_mgr->Count(bro_uint_t(rint(d))); %} ## Converts a :zeek:type:`string` to a :zeek:type:`count`. @@ -2347,11 +2347,11 @@ function to_count%(str: string%): count if ( s[0] == '\0' || end_s[0] != '\0' ) { - builtin_error("bad conversion to count", @ARG@[0]); + zeek::emit_builtin_error("bad conversion to count", @ARG@[0]); u = 0; } - return val_mgr->Count(u); + return zeek::val_mgr->Count(u); %} ## Converts an :zeek:type:`interval` to a :zeek:type:`double`. @@ -2363,7 +2363,7 @@ function to_count%(str: string%): count ## .. zeek:see:: double_to_interval function interval_to_double%(i: interval%): double %{ - return make_intrusive(i); + return zeek::make_intrusive(i); %} ## Converts a :zeek:type:`time` value to a :zeek:type:`double`. @@ -2375,7 +2375,7 @@ function interval_to_double%(i: interval%): double ## .. zeek:see:: double_to_time function time_to_double%(t: time%): double %{ - return make_intrusive(t); + return zeek::make_intrusive(t); %} ## Converts a :zeek:type:`double` value to a :zeek:type:`time`. @@ -2387,7 +2387,7 @@ function time_to_double%(t: time%): double ## .. zeek:see:: time_to_double double_to_count function double_to_time%(d: double%): time %{ - return make_intrusive(d); + return zeek::make_intrusive(d); %} ## Converts a :zeek:type:`double` to an :zeek:type:`interval`. @@ -2399,7 +2399,7 @@ function double_to_time%(d: double%): time ## .. zeek:see:: interval_to_double function double_to_interval%(d: double%): interval %{ - return make_intrusive(d); + return zeek::make_intrusive(d); %} ## Converts a :zeek:type:`port` to a :zeek:type:`count`. @@ -2411,7 +2411,7 @@ function double_to_interval%(d: double%): interval ## .. zeek:see:: count_to_port function port_to_count%(p: port%): count %{ - return val_mgr->Count(p->Port()); + return zeek::val_mgr->Count(p->Port()); %} ## Converts a :zeek:type:`count` and ``transport_proto`` to a :zeek:type:`port`. @@ -2425,7 +2425,7 @@ function port_to_count%(p: port%): count ## .. zeek:see:: port_to_count function count_to_port%(num: count, proto: transport_proto%): port %{ - return val_mgr->Port(num, (TransportProto)proto->AsEnum()); + return zeek::val_mgr->Port(num, (TransportProto)proto->AsEnum()); %} ## Converts a :zeek:type:`string` to an :zeek:type:`addr`. @@ -2440,15 +2440,15 @@ function count_to_port%(num: count, proto: transport_proto%): port function to_addr%(ip: string%): addr %{ char* s = ip->AsString()->Render(); - IntrusivePtr ret; + zeek::ValPtr ret; in6_addr tmp; if ( IPAddr::ConvertString(s, &tmp) ) - ret = make_intrusive(IPAddr(tmp)); + ret = zeek::make_intrusive(IPAddr(tmp)); else { - ret = make_intrusive(IPAddr()); - builtin_error("failed converting string to IP address", ip); + ret = zeek::make_intrusive(IPAddr()); + zeek::emit_builtin_error("failed converting string to IP address", ip); } delete [] s; @@ -2465,7 +2465,7 @@ function is_valid_ip%(ip: string%): bool char* s = ip->AsString()->Render(); auto rval = IPAddr::IsValid(s); delete [] s; - return val_mgr->Bool(rval); + return zeek::val_mgr->Bool(rval); %} ## Converts a :zeek:type:`string` to a :zeek:type:`subnet`. @@ -2483,9 +2483,9 @@ function to_subnet%(sn: string%): subnet IPPrefix tmp; if ( ! IPPrefix::ConvertString(s, &tmp) ) - builtin_error("failed converting string to IP prefix", sn); + zeek::emit_builtin_error("failed converting string to IP prefix", sn); - auto ret = make_intrusive(tmp); + auto ret = zeek::make_intrusive(tmp); delete [] s; return ret; %} @@ -2500,7 +2500,7 @@ function to_subnet%(sn: string%): subnet function addr_to_subnet%(a: addr%): subnet %{ int width = (a->AsAddr().GetFamily() == IPv4 ? 32 : 128); - return make_intrusive(a->AsAddr(), width); + return zeek::make_intrusive(a->AsAddr(), width); %} ## Converts a :zeek:type:`subnet` to an :zeek:type:`addr` by @@ -2513,7 +2513,7 @@ function addr_to_subnet%(a: addr%): subnet ## .. zeek:see:: to_subnet function subnet_to_addr%(sn: subnet%): addr %{ - return make_intrusive(sn->Prefix()); + return zeek::make_intrusive(sn->Prefix()); %} ## Returns the width of a :zeek:type:`subnet`. @@ -2525,7 +2525,7 @@ function subnet_to_addr%(sn: subnet%): addr ## .. zeek:see:: to_subnet function subnet_width%(sn: subnet%): count %{ - return val_mgr->Count(sn->Width()); + return zeek::val_mgr->Count(sn->Width()); %} ## Converts a :zeek:type:`string` to a :zeek:type:`double`. @@ -2544,11 +2544,11 @@ function to_double%(str: string%): double if ( s[0] == '\0' || end_s[0] != '\0' ) { - builtin_error("bad conversion to double", @ARG@[0]); + zeek::emit_builtin_error("bad conversion to double", @ARG@[0]); d = 0; } - return make_intrusive(d); + return zeek::make_intrusive(d); %} ## Converts a :zeek:type:`count` to an :zeek:type:`addr`. @@ -2562,11 +2562,11 @@ function count_to_v4_addr%(ip: count%): addr %{ if ( ip > 4294967295LU ) { - builtin_error("conversion of non-IPv4 count to addr", @ARG@[0]); - return make_intrusive(uint32_t(0)); + zeek::emit_builtin_error("conversion of non-IPv4 count to addr", @ARG@[0]); + return zeek::make_intrusive(uint32_t(0)); } - return make_intrusive(htonl(uint32_t(ip))); + return zeek::make_intrusive(htonl(uint32_t(ip))); %} ## Converts a :zeek:type:`string` of bytes into an IPv4 address. In particular, @@ -2583,7 +2583,7 @@ function raw_bytes_to_v4_addr%(b: string%): addr uint32_t a = 0; if ( b->Len() < 4 ) - builtin_error("too short a string as input to raw_bytes_to_v4_addr()"); + zeek::emit_builtin_error("too short a string as input to raw_bytes_to_v4_addr()"); else { @@ -2591,7 +2591,7 @@ function raw_bytes_to_v4_addr%(b: string%): addr a = (bp[0] << 24) | (bp[1] << 16) | (bp[2] << 8) | bp[3]; } - return make_intrusive(htonl(a)); + return zeek::make_intrusive(htonl(a)); %} ## Converts a :zeek:type:`string` to a :zeek:type:`port`. @@ -2613,16 +2613,16 @@ function to_port%(s: string%): port { ++slash; if ( streq(slash, "tcp") ) - return val_mgr->Port(port, TRANSPORT_TCP); + return zeek::val_mgr->Port(port, TRANSPORT_TCP); else if ( streq(slash, "udp") ) - return val_mgr->Port(port, TRANSPORT_UDP); + return zeek::val_mgr->Port(port, TRANSPORT_UDP); else if ( streq(slash, "icmp") ) - return val_mgr->Port(port, TRANSPORT_ICMP); + return zeek::val_mgr->Port(port, TRANSPORT_ICMP); } } - builtin_error("wrong port format, must be /[0-9]{1,5}\\/(tcp|udp|icmp)/"); - return val_mgr->Port(port, TRANSPORT_UNKNOWN); + zeek::emit_builtin_error("wrong port format, must be /[0-9]{1,5}\\/(tcp|udp|icmp)/"); + return zeek::val_mgr->Port(port, TRANSPORT_UNKNOWN); %} ## Converts a string of bytes (in network byte order) to a :zeek:type:`double`. @@ -2636,14 +2636,14 @@ function bytestring_to_double%(s: string%): double %{ if ( s->Len() != sizeof(double) ) { - builtin_error("bad conversion to double"); - return make_intrusive(0.0); + zeek::emit_builtin_error("bad conversion to double"); + return zeek::make_intrusive(0.0); } // See #908 for a discussion of portability. double d; memcpy(&d, s->Bytes(), sizeof(double)); - return make_intrusive(ntohd(d)); + return zeek::make_intrusive(ntohd(d)); %} ## Converts a string of bytes to a :zeek:type:`count`. @@ -2669,7 +2669,7 @@ function bytestring_to_count%(s: string, is_le: bool &default=F%): count { uint8_t value = 0; memcpy(&value, p, sizeof(uint8_t)); - return val_mgr->Count(value); + return zeek::val_mgr->Count(value); } case sizeof(uint16_t): @@ -2689,7 +2689,7 @@ function bytestring_to_count%(s: string, is_le: bool &default=F%): count else memcpy(&value, p, sizeof(uint16_t)); - return val_mgr->Count(value); + return zeek::val_mgr->Count(value); } case sizeof(uint32_t): @@ -2709,7 +2709,7 @@ function bytestring_to_count%(s: string, is_le: bool &default=F%): count else memcpy(&value, p, sizeof(uint32_t)); - return val_mgr->Count(value); + return zeek::val_mgr->Count(value); } case sizeof(uint64_t): @@ -2729,12 +2729,12 @@ function bytestring_to_count%(s: string, is_le: bool &default=F%): count else memcpy(&value, p, sizeof(uint64_t)); - return val_mgr->Count(value); + return zeek::val_mgr->Count(value); } } - builtin_error("unsupported byte length for bytestring_to_count"); - return val_mgr->Count(0); + zeek::emit_builtin_error("unsupported byte length for bytestring_to_count"); + return zeek::val_mgr->Count(0); %} ## Converts a reverse pointer name to an address. For example, @@ -2758,13 +2758,13 @@ function ptr_name_to_addr%(s: string%): addr a, a+1, a+2, a+3, ss) != 5 || strcmp(ss, "in-addr.arpa") != 0 ) { - builtin_error("bad PTR name", @ARG@[0]); + zeek::emit_builtin_error("bad PTR name", @ARG@[0]); addr = 0; } else addr = (a[3] << 24) | (a[2] << 16) | (a[1] << 8) | a[0]; - return make_intrusive(htonl(addr)); + return zeek::make_intrusive(htonl(addr)); } else { @@ -2782,7 +2782,7 @@ function ptr_name_to_addr%(s: string%): addr b+7, b+6, b+5, b+4, b+3, b+2, b+1, b, ss) != 33 || strcmp(ss, "ip6.arpa") != 0 ) { - builtin_error("bad PTR name", @ARG@[0]); + zeek::emit_builtin_error("bad PTR name", @ARG@[0]); memset(addr6, 0, sizeof addr6); } else @@ -2797,7 +2797,7 @@ function ptr_name_to_addr%(s: string%): addr } } - return make_intrusive(addr6); + return zeek::make_intrusive(addr6); } %} @@ -2811,7 +2811,7 @@ function ptr_name_to_addr%(s: string%): addr ## .. zeek:see:: ptr_name_to_addr to_addr function addr_to_ptr_name%(a: addr%): string %{ - return make_intrusive(a->AsAddr().PtrName().c_str()); + return zeek::make_intrusive(a->AsAddr().PtrName().c_str()); %} ## Converts a string of bytes into its hexadecimal representation. @@ -2833,7 +2833,7 @@ function bytestring_to_hexstr%(bytestring: string%): string for ( bro_uint_t i = 0; i < len; ++i ) snprintf(hexstr + (2 * i), 3, "%.2hhx", bytes[i]); - return make_intrusive(hexstr); + return zeek::make_intrusive(hexstr); %} ## Converts a hex-string into its binary representation. @@ -2853,7 +2853,7 @@ function hexstr_to_bytestring%(hexstr: string%): string if ( len % 2 != 0 ) { reporter->Error("Hex string '%s' has invalid length (not divisible by 2)", hexstr->CheckString()); - return val_mgr->EmptyString(); + return zeek::val_mgr->EmptyString(); } const char* bytes = hexstr->AsString()->CheckString(); @@ -2869,18 +2869,18 @@ function hexstr_to_bytestring%(hexstr: string%): string if ( res == EOF ) { reporter->Error("Hex string %s contains invalid input: %s", hexstr->CheckString(), strerror(errno)); - return val_mgr->EmptyString(); + return zeek::val_mgr->EmptyString(); } else if ( res != 1 ) { reporter->Error("Could not read hex element from input %s", hexstr->CheckString()); - return val_mgr->EmptyString(); + return zeek::val_mgr->EmptyString(); } } - return make_intrusive(outlen, bytestring); + return zeek::make_intrusive(outlen, bytestring); %} ## Encodes a Base64-encoded string. @@ -2895,13 +2895,13 @@ function hexstr_to_bytestring%(hexstr: string%): string ## .. zeek:see:: decode_base64 function encode_base64%(s: string, a: string &default=""%): string %{ - BroString* t = encode_base64(s->AsString(), a->AsString()); + String* t = encode_base64(s->AsString(), a->AsString()); if ( t ) - return make_intrusive(t); + return zeek::make_intrusive(t); else { reporter->Error("Broker query has an invalid data store"); - return val_mgr->EmptyString(); + return zeek::val_mgr->EmptyString(); } %} @@ -2917,13 +2917,13 @@ function encode_base64%(s: string, a: string &default=""%): string ## .. zeek:see:: decode_base64_conn encode_base64 function decode_base64%(s: string, a: string &default=""%): string %{ - BroString* t = decode_base64(s->AsString(), a->AsString()); + String* t = decode_base64(s->AsString(), a->AsString()); if ( t ) - return make_intrusive(t); + return zeek::make_intrusive(t); else { reporter->Error("error in decoding string %s", s->CheckString()); - return val_mgr->EmptyString(); + return zeek::val_mgr->EmptyString(); } %} @@ -2946,17 +2946,17 @@ function decode_base64_conn%(cid: conn_id, s: string, a: string &default=""%): s Connection* conn = sessions->FindConnection(cid); if ( ! conn ) { - builtin_error("connection ID not a known connection", cid); - return val_mgr->EmptyString(); + zeek::emit_builtin_error("connection ID not a known connection", cid); + return zeek::val_mgr->EmptyString(); } - BroString* t = decode_base64(s->AsString(), a->AsString(), conn); + String* t = decode_base64(s->AsString(), a->AsString(), conn); if ( t ) - return make_intrusive(t); + return zeek::make_intrusive(t); else { reporter->Error("error in decoding string %s", s->CheckString()); - return val_mgr->EmptyString(); + return zeek::val_mgr->EmptyString(); } %} @@ -2982,7 +2982,7 @@ typedef struct { function uuid_to_string%(uuid: string%): string %{ if ( uuid->Len() != 16 ) - return make_intrusive(""); + return zeek::make_intrusive(""); bro_uuid_t* id = (bro_uuid_t*) uuid->Bytes(); @@ -3000,7 +3000,7 @@ function uuid_to_string%(uuid: string%): string id->node[4], id->node[5]); - return make_intrusive(s); + return zeek::make_intrusive(s); %} %%{ @@ -3040,7 +3040,7 @@ char* to_pat_str(int sn, const char* ss) function convert_for_pattern%(s: string%): string %{ char* t = to_pat_str(s->Len(), (const char*)(s->Bytes())); - auto ret = make_intrusive(t); + auto ret = zeek::make_intrusive(t); delete [] t; return ret; %} @@ -3074,7 +3074,7 @@ function string_to_pattern%(s: string, convert: bool%): pattern RE_Matcher* re = new RE_Matcher(pat); delete [] pat; re->Compile(); - return make_intrusive(re); + return zeek::make_intrusive(re); %} ## Formats a given time value according to a format string. @@ -3093,9 +3093,9 @@ function strftime%(fmt: string, d: time%) : string if ( ! localtime_r(&timeval, &t) || ! strftime(buffer, 128, fmt->CheckString(), &t) ) - return make_intrusive(""); + return zeek::make_intrusive(""); - return make_intrusive(buffer); + return zeek::make_intrusive(buffer); %} @@ -3116,11 +3116,11 @@ function strptime%(fmt: string, d: string%) : time ! strptime(d->CheckString(), fmt->CheckString(), &t) ) { reporter->Warning("strptime conversion failed: fmt:%s d:%s", fmt->CheckString(), d->CheckString()); - return make_intrusive(0.0); + return zeek::make_intrusive(0.0); } double ret = mktime(&t); - return make_intrusive(ret); + return zeek::make_intrusive(ret); %} @@ -3143,7 +3143,7 @@ function strptime%(fmt: string, d: string%) : time ## .. zeek:see:: remask_addr function mask_addr%(a: addr, top_bits_to_keep: count%): subnet %{ - return make_intrusive(a->AsAddr(), top_bits_to_keep); + return zeek::make_intrusive(a->AsAddr(), top_bits_to_keep); %} ## Takes some top bits (such as a subnet address) from one address and the other @@ -3169,7 +3169,7 @@ function remask_addr%(a1: addr, a2: addr, top_bits_from_a1: count%): addr addr1.Mask(top_bits_from_a1); IPAddr addr2(a2->AsAddr()); addr2.ReverseMask(top_bits_from_a1); - return make_intrusive(addr1|addr2); + return zeek::make_intrusive(addr1|addr2); %} ## Checks whether a given :zeek:type:`port` has TCP as transport protocol. @@ -3181,7 +3181,7 @@ function remask_addr%(a1: addr, a2: addr, top_bits_from_a1: count%): addr ## .. zeek:see:: is_udp_port is_icmp_port function is_tcp_port%(p: port%): bool %{ - return val_mgr->Bool(p->IsTCP()); + return zeek::val_mgr->Bool(p->IsTCP()); %} ## Checks whether a given :zeek:type:`port` has UDP as transport protocol. @@ -3193,7 +3193,7 @@ function is_tcp_port%(p: port%): bool ## .. zeek:see:: is_icmp_port is_tcp_port function is_udp_port%(p: port%): bool %{ - return val_mgr->Bool(p->IsUDP()); + return zeek::val_mgr->Bool(p->IsUDP()); %} ## Checks whether a given :zeek:type:`port` has ICMP as transport protocol. @@ -3205,11 +3205,11 @@ function is_udp_port%(p: port%): bool ## .. zeek:see:: is_tcp_port is_udp_port function is_icmp_port%(p: port%): bool %{ - return val_mgr->Bool(p->IsICMP()); + return zeek::val_mgr->Bool(p->IsICMP()); %} %%{ -static IntrusivePtr map_conn_type(TransportProto tp) +static zeek::EnumValPtr map_conn_type(TransportProto tp) { switch ( tp ) { case TRANSPORT_UNKNOWN: @@ -3247,7 +3247,7 @@ function get_conn_transport_proto%(cid: conn_id%): transport_proto Connection* c = sessions->FindConnection(cid); if ( ! c ) { - builtin_error("unknown connection id in get_conn_transport_proto()", cid); + zeek::emit_builtin_error("unknown connection id in get_conn_transport_proto()", cid); return zeek::id::transport_proto->GetVal(0); } @@ -3277,9 +3277,9 @@ function get_port_transport_proto%(p: port%): transport_proto function connection_exists%(c: conn_id%): bool %{ if ( sessions->FindConnection(c) ) - return val_mgr->True(); + return zeek::val_mgr->True(); else - return val_mgr->False(); + return zeek::val_mgr->False(); %} ## Returns the :zeek:type:`connection` record for a given connection identifier. @@ -3297,39 +3297,39 @@ function lookup_connection%(cid: conn_id%): connection if ( conn ) return conn->ConnVal(); - builtin_error("connection ID not a known connection", cid); + zeek::emit_builtin_error("connection ID not a known connection", cid); // Return a dummy connection record. - auto c = make_intrusive(zeek::id::connection); + auto c = zeek::make_intrusive(zeek::id::connection); - auto id_val = make_intrusive(zeek::id::conn_id); - id_val->Assign(0, make_intrusive((unsigned int) 0)); - id_val->Assign(1, val_mgr->Port(ntohs(0), TRANSPORT_UDP)); - id_val->Assign(2, make_intrusive((unsigned int) 0)); - id_val->Assign(3, val_mgr->Port(ntohs(0), TRANSPORT_UDP)); + auto id_val = zeek::make_intrusive(zeek::id::conn_id); + id_val->Assign(0, zeek::make_intrusive((unsigned int) 0)); + id_val->Assign(1, zeek::val_mgr->Port(ntohs(0), TRANSPORT_UDP)); + id_val->Assign(2, zeek::make_intrusive((unsigned int) 0)); + id_val->Assign(3, zeek::val_mgr->Port(ntohs(0), TRANSPORT_UDP)); c->Assign(0, std::move(id_val)); - auto orig_endp = make_intrusive(zeek::id::endpoint); - orig_endp->Assign(0, val_mgr->Count(0)); - orig_endp->Assign(1, val_mgr->Count(int(0))); + auto orig_endp = zeek::make_intrusive(zeek::id::endpoint); + orig_endp->Assign(0, zeek::val_mgr->Count(0)); + orig_endp->Assign(1, zeek::val_mgr->Count(int(0))); - auto resp_endp = make_intrusive(zeek::id::endpoint); - resp_endp->Assign(0, val_mgr->Count(0)); - resp_endp->Assign(1, val_mgr->Count(int(0))); + auto resp_endp = zeek::make_intrusive(zeek::id::endpoint); + resp_endp->Assign(0, zeek::val_mgr->Count(0)); + resp_endp->Assign(1, zeek::val_mgr->Count(int(0))); c->Assign(1, std::move(orig_endp)); c->Assign(2, std::move(resp_endp)); - c->Assign(3, make_intrusive(network_time)); - c->Assign(4, make_intrusive(0.0)); - c->Assign(5, make_intrusive(zeek::id::string_set)); // service - c->Assign(6, val_mgr->EmptyString()); // history + c->Assign(3, zeek::make_intrusive(network_time)); + c->Assign(4, zeek::make_intrusive(0.0)); + c->Assign(5, zeek::make_intrusive(zeek::id::string_set)); // service + c->Assign(6, zeek::val_mgr->EmptyString()); // history return c; %} %%{ -const char* conn_id_string(Val* c) +const char* conn_id_string(zeek::Val* c) { const auto& id = (*(c->AsRecord()))[0]; auto vl = id->AsRecord(); @@ -3357,7 +3357,7 @@ function dump_current_packet%(file_name: string%) : bool if ( ! current_pktsrc || ! current_pktsrc->GetCurrentPacket(&pkt) ) - return val_mgr->False(); + return zeek::val_mgr->False(); if ( addl_pkt_dumper && addl_pkt_dumper->Path() != file_name->CheckString()) { @@ -3373,7 +3373,7 @@ function dump_current_packet%(file_name: string%) : bool addl_pkt_dumper->Dump(pkt); } - return val_mgr->Bool( addl_pkt_dumper && ! addl_pkt_dumper->IsError()); + return zeek::val_mgr->Bool( addl_pkt_dumper && ! addl_pkt_dumper->IsError()); %} ## Returns the currently processed PCAP packet. @@ -3386,25 +3386,25 @@ function get_current_packet%(%) : pcap_packet %{ static auto pcap_packet = zeek::id::find_type("pcap_packet"); const Packet* p; - auto pkt = make_intrusive(pcap_packet); + auto pkt = zeek::make_intrusive(pcap_packet); if ( ! current_pktsrc || ! current_pktsrc->GetCurrentPacket(&p) ) { - pkt->Assign(0, val_mgr->Count(0)); - pkt->Assign(1, val_mgr->Count(0)); - pkt->Assign(2, val_mgr->Count(0)); - pkt->Assign(3, val_mgr->Count(0)); - pkt->Assign(4, val_mgr->EmptyString()); + pkt->Assign(0, zeek::val_mgr->Count(0)); + pkt->Assign(1, zeek::val_mgr->Count(0)); + pkt->Assign(2, zeek::val_mgr->Count(0)); + pkt->Assign(3, zeek::val_mgr->Count(0)); + pkt->Assign(4, zeek::val_mgr->EmptyString()); pkt->Assign(5, zeek::BifType::Enum::link_encap->GetVal(BifEnum::LINK_UNKNOWN)); return pkt; } - pkt->Assign(0, val_mgr->Count(uint32_t(p->ts.tv_sec))); - pkt->Assign(1, val_mgr->Count(uint32_t(p->ts.tv_usec))); - pkt->Assign(2, val_mgr->Count(p->cap_len)); - pkt->Assign(3, val_mgr->Count(p->len)); - pkt->Assign(4, make_intrusive(p->cap_len, (const char*)p->data)); + pkt->Assign(0, zeek::val_mgr->Count(uint32_t(p->ts.tv_sec))); + pkt->Assign(1, zeek::val_mgr->Count(uint32_t(p->ts.tv_usec))); + pkt->Assign(2, zeek::val_mgr->Count(p->cap_len)); + pkt->Assign(3, zeek::val_mgr->Count(p->len)); + pkt->Assign(4, zeek::make_intrusive(p->cap_len, (const char*)p->data)); pkt->Assign(5, zeek::BifType::Enum::link_encap->GetVal(p->link_type)); return pkt; @@ -3427,7 +3427,7 @@ function get_current_packet_header%(%) : raw_pkt_hdr } static auto raw_pkt_hdr_type = zeek::id::find_type("raw_pkt_hdr"); - auto hdr = make_intrusive(raw_pkt_hdr_type); + auto hdr = zeek::make_intrusive(raw_pkt_hdr_type); return hdr; %} @@ -3470,7 +3470,7 @@ function dump_packet%(pkt: pcap_packet, file_name: string%) : bool addl_pkt_dumper->Dump(&p); } - return val_mgr->Bool(addl_pkt_dumper && ! addl_pkt_dumper->IsError()); + return zeek::val_mgr->Bool(addl_pkt_dumper && ! addl_pkt_dumper->IsError()); %} %%{ @@ -3496,13 +3496,13 @@ public: // Overridden from DNS_Mgr:Lookup:Callback. virtual void Resolved(const char* name) { - Val* result = new StringVal(name); + zeek::Val* result = new zeek::StringVal(name); trigger->Cache(call, result); Unref(result); trigger->Release(); } - virtual void Resolved(TableVal* addrs) + virtual void Resolved(zeek::TableVal* addrs) { // No Ref() for addrs. trigger->Cache(call, addrs); @@ -3513,15 +3513,15 @@ public: { if ( lookup_name ) { - Val* result = new StringVal("<\?\?\?>"); + zeek::Val* result = new zeek::StringVal("<\?\?\?>"); trigger->Cache(call, result); Unref(result); } else { - ListVal* lv = new ListVal(zeek::TYPE_ADDR); - lv->Append(make_intrusive("0.0.0.0")); + auto* lv = new zeek::ListVal(zeek::TYPE_ADDR); + lv->Append(zeek::make_intrusive("0.0.0.0")); auto result = lv->ToSetVal(); trigger->Cache(call, result.get()); Unref(lv); @@ -3554,8 +3554,8 @@ function lookup_addr%(host: addr%) : string if ( ! trigger) { - builtin_error("lookup_addr() can only be called inside a when-condition"); - return make_intrusive(""); + zeek::emit_builtin_error("lookup_addr() can only be called inside a when-condition"); + return zeek::make_intrusive(""); } frame->SetDelayed(); @@ -3583,8 +3583,8 @@ function lookup_hostname_txt%(host: string%) : string if ( ! trigger) { - builtin_error("lookup_hostname_txt() can only be called inside a when-condition"); - return make_intrusive(""); + zeek::emit_builtin_error("lookup_hostname_txt() can only be called inside a when-condition"); + return zeek::make_intrusive(""); } frame->SetDelayed(); @@ -3612,8 +3612,8 @@ function lookup_hostname%(host: string%) : addr_set if ( ! trigger) { - builtin_error("lookup_hostname() can only be called inside a when-condition"); - return make_intrusive(""); + zeek::emit_builtin_error("lookup_hostname() can only be called inside a when-condition"); + return zeek::make_intrusive(""); } frame->SetDelayed(); @@ -3862,8 +3862,8 @@ static bool mmdb_lookup_asn(const IPAddr& addr, MMDB_lookup_result_s& result) return mmdb_lookup(addr, result, true); } -static IntrusivePtr mmdb_getvalue(MMDB_entry_data_s* entry_data, int status, - int data_type ) +static zeek::ValPtr mmdb_getvalue(MMDB_entry_data_s* entry_data, int status, + int data_type ) { switch (status) { @@ -3873,16 +3873,16 @@ static IntrusivePtr mmdb_getvalue(MMDB_entry_data_s* entry_data, int status switch (data_type) { case MMDB_DATA_TYPE_UTF8_STRING: - return make_intrusive(entry_data->data_size, - entry_data->utf8_string); + return zeek::make_intrusive( + entry_data->data_size, entry_data->utf8_string); break; case MMDB_DATA_TYPE_DOUBLE: - return make_intrusive(entry_data->double_value); + return zeek::make_intrusive(entry_data->double_value); break; case MMDB_DATA_TYPE_UINT32: - return val_mgr->Count(entry_data->uint32); + return zeek::val_mgr->Count(entry_data->uint32); default: break; @@ -3905,7 +3905,7 @@ static IntrusivePtr mmdb_getvalue(MMDB_entry_data_s* entry_data, int status static bool mmdb_try_open_loc () { // City database is always preferred over Country database. - const auto& mmdb_dir_val = global_scope()->Find("mmdb_dir")->GetVal(); + const auto& mmdb_dir_val = zeek::detail::global_scope()->Find("mmdb_dir")->GetVal(); std::string mmdb_dir = mmdb_dir_val->AsString()->CheckString(); if ( ! mmdb_dir.empty() ) @@ -3933,7 +3933,7 @@ static bool mmdb_try_open_loc () static bool mmdb_try_open_asn () { - const auto& mmdb_dir_val = global_scope()->Find("mmdb_dir")->GetVal(); + const auto& mmdb_dir_val = zeek::detail::global_scope()->Find("mmdb_dir")->GetVal(); std::string mmdb_dir = mmdb_dir_val->AsString()->CheckString(); if ( ! mmdb_dir.empty() ) @@ -3964,9 +3964,9 @@ static bool mmdb_try_open_asn () function mmdb_open_location_db%(f: string%) : bool %{ #ifdef USE_GEOIP - return val_mgr->Bool(mmdb_open_loc(f->CheckString())); + return zeek::val_mgr->Bool(mmdb_open_loc(f->CheckString())); #else - return val_mgr->False(); + return zeek::val_mgr->False(); #endif %} @@ -3981,9 +3981,9 @@ function mmdb_open_location_db%(f: string%) : bool function mmdb_open_asn_db%(f: string%) : bool %{ #ifdef USE_GEOIP - return val_mgr->Bool(mmdb_open_asn(f->CheckString())); + return zeek::val_mgr->Bool(mmdb_open_asn(f->CheckString())); #else - return val_mgr->False(); + return zeek::val_mgr->False(); #endif %} @@ -3998,7 +3998,7 @@ function mmdb_open_asn_db%(f: string%) : bool function lookup_location%(a: addr%) : geo_location %{ static auto geo_location = zeek::id::find_type("geo_location"); - auto location = make_intrusive(geo_location); + auto location = zeek::make_intrusive(geo_location); #ifdef USE_GEOIP mmdb_check_loc(); @@ -4009,7 +4009,7 @@ function lookup_location%(a: addr%) : geo_location if ( ! did_mmdb_loc_db_error ) { did_mmdb_loc_db_error = true; - builtin_error("Failed to open GeoIP location database"); + zeek::emit_builtin_error("Failed to open GeoIP location database"); } return location; @@ -4061,7 +4061,7 @@ function lookup_location%(a: addr%) : geo_location if ( ! missing_geoip_reported ) { - builtin_error("Zeek was not configured for GeoIP support"); + zeek::emit_builtin_error("Zeek was not configured for GeoIP support"); missing_geoip_reported = 1; } #endif @@ -4092,10 +4092,10 @@ function lookup_asn%(a: addr%) : count if ( ! did_mmdb_asn_db_error ) { did_mmdb_asn_db_error = true; - builtin_error("Failed to open GeoIP ASN database"); + zeek::emit_builtin_error("Failed to open GeoIP ASN database"); } - return val_mgr->Count(0); + return zeek::val_mgr->Count(0); } } @@ -4110,7 +4110,7 @@ function lookup_asn%(a: addr%) : count status = MMDB_get_value(&result.entry, &entry_data, "autonomous_system_number", nullptr); auto asn = mmdb_getvalue(&entry_data, status, MMDB_DATA_TYPE_UINT32); - return asn == nullptr ? val_mgr->Count(0) : asn; + return asn == nullptr ? zeek::val_mgr->Count(0) : asn; } #else // not USE_GEOIP @@ -4118,7 +4118,7 @@ function lookup_asn%(a: addr%) : count if ( ! missing_geoip_reported ) { - builtin_error("Zeek was not configured for GeoIP ASN support"); + zeek::emit_builtin_error("Zeek was not configured for GeoIP ASN support"); missing_geoip_reported = 1; } #endif @@ -4126,7 +4126,7 @@ function lookup_asn%(a: addr%) : count // We can get here even if we have GeoIP support, if we weren't // able to initialize it or it didn't return any information for // the address. - return val_mgr->Count(0); + return zeek::val_mgr->Count(0); %} ## Calculates distance between two geographic locations using the haversine @@ -4155,7 +4155,7 @@ function haversine_distance%(lat1: double, long1: double, lat2: double, long2: d double a = s1 * s1 + cos(lat1 * PI/180) * cos(lat2 * PI/180) * s2 * s2; double distance = 2 * RADIUS * asin(sqrt(a)); - return make_intrusive(distance); + return zeek::make_intrusive(distance); %} ## Converts UNIX file permissions given by a mode to an ASCII string. @@ -4247,7 +4247,7 @@ function file_mode%(mode: count%): string *p = '\0'; - return make_intrusive(str); + return zeek::make_intrusive(str); %} # =========================================================================== @@ -4284,7 +4284,7 @@ function disable_analyzer%(cid: conn_id, aid: count, err_if_no_conn: bool &defau if ( ! c ) { reporter->Error("cannot find connection"); - return val_mgr->False(); + return zeek::val_mgr->False(); } analyzer::Analyzer* a = c->FindAnalyzer(aid); @@ -4292,14 +4292,14 @@ function disable_analyzer%(cid: conn_id, aid: count, err_if_no_conn: bool &defau { if ( err_if_no_conn ) reporter->Error("connection does not have analyzer specified to disable"); - return val_mgr->False(); + return zeek::val_mgr->False(); } if ( prevent ) a->Parent()->PreventChildren(a->GetAnalyzerTag()); auto rval = a->Remove(); - return val_mgr->Bool(rval); + return zeek::val_mgr->Bool(rval); %} ## Informs Zeek that it should skip any further processing of the contents of @@ -4320,10 +4320,10 @@ function skip_further_processing%(cid: conn_id%): bool %{ Connection* c = sessions->FindConnection(cid); if ( ! c ) - return val_mgr->False(); + return zeek::val_mgr->False(); c->SetSkip(1); - return val_mgr->True(); + return zeek::val_mgr->True(); %} ## Controls whether packet contents belonging to a connection should be @@ -4350,10 +4350,10 @@ function set_record_packets%(cid: conn_id, do_record: bool%): bool %{ Connection* c = sessions->FindConnection(cid); if ( ! c ) - return val_mgr->False(); + return zeek::val_mgr->False(); c->SetRecordPackets(do_record); - return val_mgr->True(); + return zeek::val_mgr->True(); %} ## Sets an individual inactivity timeout for a connection and thus @@ -4368,12 +4368,12 @@ function set_inactivity_timeout%(cid: conn_id, t: interval%): interval %{ Connection* c = sessions->FindConnection(cid); if ( ! c ) - return make_intrusive(0.0); + return zeek::make_intrusive(0.0); double old_timeout = c->InactivityTimeout(); c->SetInactivityTimeout(t); - return make_intrusive(old_timeout); + return zeek::make_intrusive(old_timeout); %} # =========================================================================== @@ -4397,9 +4397,9 @@ function open%(f: string%): file const char* file = f->CheckString(); if ( streq(file, "-") ) - return make_intrusive(make_intrusive(stdout, "-", "w")); + return zeek::make_intrusive(zeek::make_intrusive(stdout, "-", "w")); else - return make_intrusive(make_intrusive(file, "w")); + return zeek::make_intrusive(zeek::make_intrusive(file, "w")); %} ## Opens a file for writing or appending. If a file with the same name already @@ -4414,7 +4414,7 @@ function open%(f: string%): file ## rmdir unlink rename function open_for_append%(f: string%): file %{ - return make_intrusive(make_intrusive(f->CheckString(), "a")); + return zeek::make_intrusive(zeek::make_intrusive(f->CheckString(), "a")); %} ## Closes an open file and flushes any buffered content. @@ -4428,7 +4428,7 @@ function open_for_append%(f: string%): file ## rmdir unlink rename function close%(f: file%): bool %{ - return val_mgr->Bool(f->Close()); + return zeek::val_mgr->Bool(f->Close()); %} ## Writes data to an open file. @@ -4445,9 +4445,9 @@ function close%(f: file%): bool function write_file%(f: file, data: string%): bool %{ if ( ! f ) - return val_mgr->False(); + return zeek::val_mgr->False(); - return val_mgr->Bool(f->Write((const char*) data->Bytes(), data->Len())); + return zeek::val_mgr->Bool(f->Write((const char*) data->Bytes(), data->Len())); %} ## Alters the buffering behavior of a file. @@ -4465,7 +4465,7 @@ function write_file%(f: file, data: string%): bool function set_buf%(f: file, buffered: bool%): any %{ f->SetBuf(buffered); - return val_mgr->True(); + return zeek::val_mgr->True(); %} ## Flushes all open files to disk. @@ -4477,7 +4477,7 @@ function set_buf%(f: file, buffered: bool%): any ## rmdir unlink rename function flush_all%(%): bool %{ - return val_mgr->Bool(fflush(0) == 0); + return zeek::val_mgr->Bool(fflush(0) == 0); %} ## Creates a new directory. @@ -4501,14 +4501,14 @@ function mkdir%(f: string%): bool // check if already exists and is directory. if ( errno == EEXIST && stat(filename, &filestat) == 0 && S_ISDIR(filestat.st_mode) ) - return val_mgr->True(); + return zeek::val_mgr->True(); - builtin_error(fmt("cannot create directory '%s': %s", filename, - strerror(error))); - return val_mgr->False(); + zeek::emit_builtin_error(fmt("cannot create directory '%s': %s", filename, + strerror(error))); + return zeek::val_mgr->False(); } else - return val_mgr->True(); + return zeek::val_mgr->True(); %} @@ -4528,12 +4528,12 @@ function rmdir%(d: string%): bool if ( rmdir(dirname) < 0 ) { - builtin_error(fmt("cannot remove directory '%s': %s", dirname, - strerror(errno))); - return val_mgr->False(); + zeek::emit_builtin_error(fmt("cannot remove directory '%s': %s", dirname, + strerror(errno))); + return zeek::val_mgr->False(); } else - return val_mgr->True(); + return zeek::val_mgr->True(); %} ## Removes a file from a directory. @@ -4552,12 +4552,12 @@ function unlink%(f: string%): bool if ( unlink(filename) < 0 ) { - builtin_error(fmt("cannot unlink file '%s': %s", filename, - strerror(errno))); - return val_mgr->False(); + zeek::emit_builtin_error(fmt("cannot unlink file '%s': %s", filename, + strerror(errno))); + return zeek::val_mgr->False(); } else - return val_mgr->True(); + return zeek::val_mgr->True(); %} ## Renames a file from src_f to dst_f. @@ -4578,12 +4578,12 @@ function rename%(src_f: string, dst_f: string%): bool if ( rename(src_filename, dst_filename) < 0 ) { - builtin_error(fmt("cannot rename file '%s' to '%s': %s", src_filename, - dst_filename, strerror(errno))); - return val_mgr->False(); + zeek::emit_builtin_error(fmt("cannot rename file '%s' to '%s': %s", src_filename, + dst_filename, strerror(errno))); + return zeek::val_mgr->False(); } else - return val_mgr->True(); + return zeek::val_mgr->True(); %} ## Checks whether a given file is open. @@ -4595,7 +4595,7 @@ function rename%(src_f: string, dst_f: string%): bool ## .. todo:: Rename to ``is_open``. function active_file%(f: file%): bool %{ - return val_mgr->Bool(f->IsOpen()); + return zeek::val_mgr->Bool(f->IsOpen()); %} ## Gets the filename associated with a file handle. @@ -4608,9 +4608,9 @@ function active_file%(f: file%): bool function get_file_name%(f: file%): string %{ if ( ! f ) - return val_mgr->EmptyString(); + return zeek::val_mgr->EmptyString(); - return make_intrusive(f->Name()); + return zeek::make_intrusive(f->Name()); %} ## Rotates a file. @@ -4623,18 +4623,18 @@ function get_file_name%(f: file%): string ## .. zeek:see:: rotate_file_by_name calc_next_rotate function rotate_file%(f: file%): rotate_info %{ - IntrusivePtr info{AdoptRef{}, f->Rotate()}; + zeek::RecordValPtr info{zeek::AdoptRef{}, f->Rotate()}; if ( info ) return info; // Record indicating error. static auto rotate_info = zeek::id::find_type("rotate_info"); - info = make_intrusive(rotate_info); - info->Assign(0, val_mgr->EmptyString()); - info->Assign(1, val_mgr->EmptyString()); - info->Assign(2, make_intrusive(0.0)); - info->Assign(3, make_intrusive(0.0)); + info = zeek::make_intrusive(rotate_info); + info->Assign(0, zeek::val_mgr->EmptyString()); + info->Assign(1, zeek::val_mgr->EmptyString()); + info->Assign(2, zeek::make_intrusive(0.0)); + info->Assign(3, zeek::make_intrusive(0.0)); return info; %} @@ -4650,7 +4650,7 @@ function rotate_file%(f: file%): rotate_info function rotate_file_by_name%(f: string%): rotate_info %{ static auto rotate_info = zeek::id::find_type("rotate_info"); - auto info = make_intrusive(rotate_info); + auto info = zeek::make_intrusive(rotate_info); bool is_pkt_dumper = false; bool is_addl_pkt_dumper = false; @@ -4673,10 +4673,10 @@ function rotate_file_by_name%(f: string%): rotate_info if ( ! file ) { // Record indicating error. - info->Assign(0, val_mgr->EmptyString()); - info->Assign(1, val_mgr->EmptyString()); - info->Assign(2, make_intrusive(0.0)); - info->Assign(3, make_intrusive(0.0)); + info->Assign(0, zeek::val_mgr->EmptyString()); + info->Assign(1, zeek::val_mgr->EmptyString()); + info->Assign(2, zeek::make_intrusive(0.0)); + info->Assign(3, zeek::make_intrusive(0.0)); return info; } @@ -4684,12 +4684,12 @@ function rotate_file_by_name%(f: string%): rotate_info if ( is_pkt_dumper ) { - info->Assign(2, make_intrusive(pkt_dumper->OpenTime())); + info->Assign(2, zeek::make_intrusive(pkt_dumper->OpenTime())); pkt_dumper->Open(); } if ( is_addl_pkt_dumper ) - info->Assign(2, make_intrusive(addl_pkt_dumper->OpenTime())); + info->Assign(2, zeek::make_intrusive(addl_pkt_dumper->OpenTime())); return info; %} @@ -4704,11 +4704,11 @@ function rotate_file_by_name%(f: string%): rotate_info ## .. zeek:see:: rotate_file rotate_file_by_name function calc_next_rotate%(i: interval%) : interval %{ - static auto log_rotate_base_time = zeek::id::find_val("log_rotate_base_time"); + static auto log_rotate_base_time = zeek::id::find_val("log_rotate_base_time"); static auto base_time = log_rotate_base_time->AsString()->CheckString(); double base = parse_rotate_base_time(base_time); - return make_intrusive(calc_next_rotate(network_time, i, base)); + return zeek::make_intrusive(calc_next_rotate(network_time, i, base)); %} ## Returns the size of a given file. @@ -4721,9 +4721,9 @@ function file_size%(f: string%) : double struct stat s; if ( stat(f->CheckString(), &s) < 0 ) - return make_intrusive(-1.0); + return zeek::make_intrusive(-1.0); - return make_intrusive(double(s.st_size)); + return zeek::make_intrusive(double(s.st_size)); %} ## Prevents escaping of non-ASCII characters when writing to a file. @@ -4771,7 +4771,7 @@ function enable_raw_output%(f: file%): any function install_src_addr_filter%(ip: addr, tcp_flags: count, prob: double%) : bool %{ sessions->GetPacketFilter()->AddSrc(ip->AsAddr(), tcp_flags, prob); - return val_mgr->True(); + return zeek::val_mgr->True(); %} ## Installs a filter to drop packets originating from a given subnet with @@ -4801,7 +4801,7 @@ function install_src_addr_filter%(ip: addr, tcp_flags: count, prob: double%) : b function install_src_net_filter%(snet: subnet, tcp_flags: count, prob: double%) : bool %{ sessions->GetPacketFilter()->AddSrc(snet, tcp_flags, prob); - return val_mgr->True(); + return zeek::val_mgr->True(); %} ## Removes a source address filter. @@ -4822,7 +4822,7 @@ function install_src_net_filter%(snet: subnet, tcp_flags: count, prob: double%) ## Pcap::error function uninstall_src_addr_filter%(ip: addr%) : bool %{ - return val_mgr->Bool(sessions->GetPacketFilter()->RemoveSrc(ip->AsAddr())); + return zeek::val_mgr->Bool(sessions->GetPacketFilter()->RemoveSrc(ip->AsAddr())); %} ## Removes a source subnet filter. @@ -4843,7 +4843,7 @@ function uninstall_src_addr_filter%(ip: addr%) : bool ## Pcap::error function uninstall_src_net_filter%(snet: subnet%) : bool %{ - return val_mgr->Bool(sessions->GetPacketFilter()->RemoveSrc(snet)); + return zeek::val_mgr->Bool(sessions->GetPacketFilter()->RemoveSrc(snet)); %} ## Installs a filter to drop packets destined to a given IP address with @@ -4876,7 +4876,7 @@ function uninstall_src_net_filter%(snet: subnet%) : bool function install_dst_addr_filter%(ip: addr, tcp_flags: count, prob: double%) : bool %{ sessions->GetPacketFilter()->AddDst(ip->AsAddr(), tcp_flags, prob); - return val_mgr->True(); + return zeek::val_mgr->True(); %} ## Installs a filter to drop packets destined to a given subnet with @@ -4906,7 +4906,7 @@ function install_dst_addr_filter%(ip: addr, tcp_flags: count, prob: double%) : b function install_dst_net_filter%(snet: subnet, tcp_flags: count, prob: double%) : bool %{ sessions->GetPacketFilter()->AddDst(snet, tcp_flags, prob); - return val_mgr->True(); + return zeek::val_mgr->True(); %} ## Removes a destination address filter. @@ -4927,7 +4927,7 @@ function install_dst_net_filter%(snet: subnet, tcp_flags: count, prob: double%) ## Pcap::error function uninstall_dst_addr_filter%(ip: addr%) : bool %{ - return val_mgr->Bool(sessions->GetPacketFilter()->RemoveDst(ip->AsAddr())); + return zeek::val_mgr->Bool(sessions->GetPacketFilter()->RemoveDst(ip->AsAddr())); %} ## Removes a destination subnet filter. @@ -4948,7 +4948,7 @@ function uninstall_dst_addr_filter%(ip: addr%) : bool ## Pcap::error function uninstall_dst_net_filter%(snet: subnet%) : bool %{ - return val_mgr->Bool(sessions->GetPacketFilter()->RemoveDst(snet)); + return zeek::val_mgr->Bool(sessions->GetPacketFilter()->RemoveDst(snet)); %} ## Checks whether the last raised event came from a remote peer. @@ -4956,7 +4956,7 @@ function uninstall_dst_net_filter%(snet: subnet%) : bool ## Returns: True if the last raised event came from a remote peer. function is_remote_event%(%) : bool %{ - return val_mgr->Bool(mgr.CurrentSource() != SOURCE_LOCAL); + return zeek::val_mgr->Bool(mgr.CurrentSource() != SOURCE_LOCAL); %} ## Stops Zeek's packet processing. This function is used to synchronize @@ -4992,12 +4992,12 @@ function match_signatures%(c: connection, pattern_type: int, s: string, from_orig: bool, clear: bool%) : bool %{ if ( ! rule_matcher ) - return val_mgr->False(); + return zeek::val_mgr->False(); c->Match((Rule::PatternType) pattern_type, s->Bytes(), s->Len(), from_orig, bol, eol, clear); - return val_mgr->True(); + return zeek::val_mgr->True(); %} # =========================================================================== @@ -5028,7 +5028,7 @@ function preserve_prefix%(a: addr, width: count%): any if ( ip_anon ) { if ( a->AsAddr().GetFamily() == IPv6 ) - builtin_error("preserve_prefix() not supported for IPv6 addresses"); + zeek::emit_builtin_error("preserve_prefix() not supported for IPv6 addresses"); else { const uint32_t* bytes; @@ -5054,7 +5054,7 @@ function preserve_subnet%(a: subnet%): any if ( ip_anon ) { if ( a->AsSubNet().Prefix().GetFamily() == IPv6 ) - builtin_error("preserve_subnet() not supported for IPv6 addresses"); + zeek::emit_builtin_error("preserve_subnet() not supported for IPv6 addresses"); else { const uint32_t* bytes; @@ -5087,18 +5087,18 @@ function anonymize_addr%(a: addr, cl: IPAddrAnonymizationClass%): addr %{ int anon_class = cl->InternalInt(); if ( anon_class < 0 || anon_class >= zeek::detail::NUM_ADDR_ANONYMIZATION_CLASSES ) - builtin_error("anonymize_addr(): invalid ip addr anonymization class"); + zeek::emit_builtin_error("anonymize_addr(): invalid ip addr anonymization class"); if ( a->AsAddr().GetFamily() == IPv6 ) { - builtin_error("anonymize_addr() not supported for IPv6 addresses"); + zeek::emit_builtin_error("anonymize_addr() not supported for IPv6 addresses"); return nullptr; } else { const uint32_t* bytes; a->AsAddr().GetBytes(&bytes); - return make_intrusive(zeek::detail::anonymize_ip(*bytes, + return zeek::make_intrusive(zeek::detail::anonymize_ip(*bytes, static_cast(anon_class))); } %} diff --git a/src/zeekygen/IdentifierInfo.cc b/src/zeekygen/IdentifierInfo.cc index ff0b994f73..46ee45dbe3 100644 --- a/src/zeekygen/IdentifierInfo.cc +++ b/src/zeekygen/IdentifierInfo.cc @@ -11,7 +11,7 @@ using namespace std; using namespace zeekygen; -IdentifierInfo::IdentifierInfo(IntrusivePtr arg_id, ScriptInfo* script) +IdentifierInfo::IdentifierInfo(zeek::detail::IDPtr arg_id, ScriptInfo* script) : Info(), comments(), id(std::move(arg_id)), initial_val(), redefs(), fields(), last_field_seen(), declaring_script(script) @@ -32,7 +32,7 @@ IdentifierInfo::~IdentifierInfo() } void IdentifierInfo::AddRedef(const string& script, zeek::detail::InitClass ic, - IntrusivePtr init_expr, const vector& comments) + zeek::detail::ExprPtr init_expr, const vector& comments) { Redefinition* redef = new Redefinition(script, ic, std::move(init_expr), comments); redefs.push_back(redef); @@ -139,11 +139,10 @@ time_t IdentifierInfo::DoGetModificationTime() const return declaring_script->GetModificationTime(); } -IdentifierInfo::Redefinition::Redefinition( - std::string arg_script, - zeek::detail::InitClass arg_ic, - IntrusivePtr arg_expr, - std::vector arg_comments) +IdentifierInfo::Redefinition::Redefinition(std::string arg_script, + zeek::detail::InitClass arg_ic, + zeek::detail::ExprPtr arg_expr, + std::vector arg_comments) : from_script(std::move(arg_script)), ic(arg_ic), init_expr(std::move(arg_expr)), diff --git a/src/zeekygen/IdentifierInfo.h b/src/zeekygen/IdentifierInfo.h index 06d90897a9..9e5819b84e 100644 --- a/src/zeekygen/IdentifierInfo.h +++ b/src/zeekygen/IdentifierInfo.h @@ -32,7 +32,7 @@ public: * @param script The info object associated with the script in which \a id * is declared. */ - IdentifierInfo(IntrusivePtr id, ScriptInfo* script); + IdentifierInfo(zeek::detail::IDPtr id, ScriptInfo* script); /** * Dtor. Releases any references to script-level objects. @@ -42,7 +42,7 @@ public: /** * Returns the initial value of the identifier. */ - const IntrusivePtr& InitialVal() const + const zeek::ValPtr& InitialVal() const { return initial_val; } /** @@ -71,7 +71,7 @@ public: * @param comments Comments associated with the redef statement. */ void AddRedef(const std::string& from_script, zeek::detail::InitClass ic, - IntrusivePtr init_expr, + zeek::detail::ExprPtr init_expr, const std::vector& comments); /** @@ -128,11 +128,11 @@ public: struct Redefinition { std::string from_script; /**< Name of script doing the redef. */ zeek::detail::InitClass ic; - IntrusivePtr init_expr; + zeek::detail::ExprPtr init_expr; std::vector comments; /**< Zeekygen comments on redef. */ Redefinition(std::string arg_script, zeek::detail::InitClass arg_ic, - IntrusivePtr arg_expr, + zeek::detail::ExprPtr arg_expr, std::vector arg_comments); ~Redefinition(); @@ -174,8 +174,8 @@ private: typedef std::map record_field_map; std::vector comments; - IntrusivePtr id; - IntrusivePtr initial_val; + zeek::detail::IDPtr id; + zeek::ValPtr initial_val; redef_list redefs; record_field_map fields; RecordField* last_field_seen; diff --git a/src/zeekygen/Manager.cc b/src/zeekygen/Manager.cc index c114983f26..a0a08ff27e 100644 --- a/src/zeekygen/Manager.cc +++ b/src/zeekygen/Manager.cc @@ -216,7 +216,7 @@ void Manager::ModuleUsage(const string& path, const string& module) module.c_str(), name.c_str()); } -IdentifierInfo* Manager::CreateIdentifierInfo(IntrusivePtr id, ScriptInfo* script) +IdentifierInfo* Manager::CreateIdentifierInfo(zeek::detail::IDPtr id, ScriptInfo* script) { const auto& id_name = id->Name(); auto prev = identifiers.GetInfo(id_name); @@ -247,12 +247,12 @@ IdentifierInfo* Manager::CreateIdentifierInfo(IntrusivePtr id, return rval; } -void Manager::StartType(IntrusivePtr id) +void Manager::StartType(zeek::detail::IDPtr id) { if ( disabled ) return; - if ( id->GetLocationInfo() == &no_location ) + if ( id->GetLocationInfo() == &zeek::detail::no_location ) { DbgAndWarn(fmt("Can't generate zeekygen doumentation for %s, " "no location available", id->Name())); @@ -278,7 +278,7 @@ static bool IsEnumType(zeek::detail::ID* id) return id->IsType() ? id->GetType()->Tag() == zeek::TYPE_ENUM : false; } -void Manager::Identifier(IntrusivePtr id) +void Manager::Identifier(zeek::detail::IDPtr id) { if ( disabled ) return; @@ -313,7 +313,7 @@ void Manager::Identifier(IntrusivePtr id) return; } - if ( id->GetLocationInfo() == &no_location ) + if ( id->GetLocationInfo() == &zeek::detail::no_location ) { // Internally-created identifier (e.g. file/proto analyzer enum tags). // Handled specially since they don't have a script location. @@ -361,7 +361,8 @@ void Manager::RecordField(const zeek::detail::ID* id, const zeek::TypeDecl* fiel } void Manager::Redef(const zeek::detail::ID* id, const string& path, - zeek::detail::InitClass ic, IntrusivePtr init_expr) + zeek::detail::InitClass ic, + zeek::detail::ExprPtr init_expr) { if ( disabled ) return; diff --git a/src/zeekygen/Manager.h b/src/zeekygen/Manager.h index cd7eefca50..f5162131ea 100644 --- a/src/zeekygen/Manager.h +++ b/src/zeekygen/Manager.h @@ -15,7 +15,6 @@ #include "ID.h" #include "util.h" -template class IntrusivePtr; ZEEK_FORWARD_DECLARE_NAMESPACED(TypeDecl, zeek); namespace zeekygen { @@ -111,14 +110,14 @@ public: * Signal that a record or enum type is now being parsed. * @param id The record or enum type identifier. */ - void StartType(IntrusivePtr id); + void StartType(zeek::detail::IDPtr id); /** * Register a script-level identifier for which information/documentation * will be gathered. * @param id The script-level identifier. */ - void Identifier(IntrusivePtr id); + void Identifier(zeek::detail::IDPtr id); /** * Register a record-field for which information/documentation will be @@ -140,7 +139,7 @@ public: * @param init_expr The intiialization expression that was used. */ void Redef(const zeek::detail::ID* id, const std::string& path, - zeek::detail::InitClass ic, IntrusivePtr init_expr); + zeek::detail::InitClass ic, zeek::detail::ExprPtr init_expr); void Redef(const zeek::detail::ID* id, const std::string& path, zeek::detail::InitClass ic = zeek::detail::INIT_NONE); @@ -218,7 +217,7 @@ private: typedef std::vector comment_buffer_t; typedef std::map comment_buffer_map_t; - IdentifierInfo* CreateIdentifierInfo(IntrusivePtr id, ScriptInfo* script); + IdentifierInfo* CreateIdentifierInfo(zeek::detail::IDPtr id, ScriptInfo* script); bool disabled; comment_buffer_t comment_buffer; // For whatever next identifier comes in. diff --git a/src/zeekygen/ScriptInfo.cc b/src/zeekygen/ScriptInfo.cc index 0bbd64ad66..9f16010fbc 100644 --- a/src/zeekygen/ScriptInfo.cc +++ b/src/zeekygen/ScriptInfo.cc @@ -258,12 +258,12 @@ void ScriptInfo::DoInitPostScript() // so just manually associating them with scripts for now. if ( name == "base/frameworks/input/main.zeek" ) { - const auto& id = global_scope()->Find("Input::Reader"); + const auto& id = zeek::detail::global_scope()->Find("Input::Reader"); types.push_back(new IdentifierInfo(id, this)); } else if ( name == "base/frameworks/logging/main.zeek" ) { - const auto& id = global_scope()->Find("Log::Writer"); + const auto& id = zeek::detail::global_scope()->Find("Log::Writer"); types.push_back(new IdentifierInfo(id, this)); } } diff --git a/src/zeekygen/zeekygen.bif b/src/zeekygen/zeekygen.bif index beaff682b0..1287905418 100644 --- a/src/zeekygen/zeekygen.bif +++ b/src/zeekygen/zeekygen.bif @@ -9,9 +9,9 @@ #include "zeekygen/ScriptInfo.h" #include "util.h" -static IntrusivePtr comments_to_val(const vector& comments) +static zeek::StringValPtr comments_to_val(const vector& comments) { - return make_intrusive(implode_string_vector(comments)); + return zeek::make_intrusive(implode_string_vector(comments)); } %%} @@ -28,7 +28,7 @@ function get_identifier_comments%(name: string%): string IdentifierInfo* d = zeekygen_mgr->GetIdentifierInfo(name->CheckString()); if ( ! d ) - return val_mgr->EmptyString(); + return zeek::val_mgr->EmptyString(); return comments_to_val(d->GetComments()); %} @@ -48,7 +48,7 @@ function get_script_comments%(name: string%): string ScriptInfo* d = zeekygen_mgr->GetScriptInfo(name->CheckString()); if ( ! d ) - return val_mgr->EmptyString(); + return zeek::val_mgr->EmptyString(); return comments_to_val(d->GetComments()); %} @@ -66,7 +66,7 @@ function get_package_readme%(name: string%): string PackageInfo* d = zeekygen_mgr->GetPackageInfo(name->CheckString()); if ( ! d ) - return val_mgr->EmptyString(); + return zeek::val_mgr->EmptyString(); return comments_to_val(d->GetReadme()); %} @@ -86,14 +86,14 @@ function get_record_field_comments%(name: string%): string size_t i = accessor.find('$'); if ( i > accessor.size() - 2 ) - return val_mgr->EmptyString(); + return zeek::val_mgr->EmptyString(); string id = accessor.substr(0, i); IdentifierInfo* d = zeekygen_mgr->GetIdentifierInfo(id); if ( ! d ) - return val_mgr->EmptyString(); + return zeek::val_mgr->EmptyString(); string field = accessor.substr(i + 1); return comments_to_val(d->GetFieldComments(field)); diff --git a/testing/btest/plugins/func-hook-plugin/src/Plugin.cc b/testing/btest/plugins/func-hook-plugin/src/Plugin.cc index c71788fa86..99348affe3 100644 --- a/testing/btest/plugins/func-hook-plugin/src/Plugin.cc +++ b/testing/btest/plugins/func-hook-plugin/src/Plugin.cc @@ -41,9 +41,8 @@ static void describe_hook_args(const plugin::HookArgumentList& args, ODesc* d) } } -std::pair> Plugin::HookFunctionCall(const Func* func, - Frame* frame, - zeek::Args* args) +std::pair> Plugin::HookFunctionCall( + const Func* func, Frame* frame, zeek::Args* args) { ODesc d; d.SetShort(); diff --git a/testing/btest/plugins/func-hook-plugin/src/Plugin.h b/testing/btest/plugins/func-hook-plugin/src/Plugin.h index d437213719..19bccd4386 100644 --- a/testing/btest/plugins/func-hook-plugin/src/Plugin.h +++ b/testing/btest/plugins/func-hook-plugin/src/Plugin.h @@ -10,9 +10,8 @@ class Plugin : public zeek::plugin::Plugin { protected: - std::pair> HookFunctionCall(const Func* func, - Frame* frame, - zeek::Args* args) override; + std::pair> HookFunctionCall( + const Func* func, Frame* frame, zeek::Args* args) override; void MetaHookPre(zeek::plugin::HookType hook, const zeek::plugin::HookArgumentList& args) override; diff --git a/testing/btest/plugins/protocol-plugin/src/foo-analyzer.pac b/testing/btest/plugins/protocol-plugin/src/foo-analyzer.pac index 0c1fdbfa1a..051ffaff7c 100644 --- a/testing/btest/plugins/protocol-plugin/src/foo-analyzer.pac +++ b/testing/btest/plugins/protocol-plugin/src/foo-analyzer.pac @@ -3,7 +3,7 @@ refine connection Foo_Conn += { function Foo_data(msg: Foo_Message): bool %{ - auto data = make_intrusive(${msg.data}.length(), (const char*) ${msg.data}.data()); + auto data = zeek::make_intrusive(${msg.data}.length(), (const char*) ${msg.data}.data()); zeek::BifEvent::enqueue_foo_message(bro_analyzer(), bro_analyzer()->Conn(), std::move(data)); return true; %} diff --git a/zeek-config.h.in b/zeek-config.h.in index 5f5497f8a5..46971ac5a4 100644 --- a/zeek-config.h.in +++ b/zeek-config.h.in @@ -274,3 +274,8 @@ extern const char* BRO_VERSION_FUNCTION(); #define ZEEK_LSAN_DISABLE(x) #define ZEEK_LSAN_DISABLE_SCOPE(x) #endif + +// Note: macro for internal use only during deprecation/namespacing process. +#define ZEEK_FORWARD_DECLARE_NAMESPACED(cls, ns) \ + namespace ns { class cls; } \ + using cls [[deprecated("Remove in v4.1. Use " #ns "::" #cls " instead.")]] = ns::cls;