Reformat the world

This commit is contained in:
Tim Wojtulewicz 2021-09-16 15:35:39 -07:00
parent 194cb24547
commit b2f171ec69
714 changed files with 35149 additions and 35203 deletions

View file

@ -1,95 +1,93 @@
// See the file "COPYING" in the main distribution directory for copyright.
#include "zeek/zeek-config.h"
#include "zeek/iosource/BPF_Program.h"
#include <string.h>
#include "zeek/zeek-config.h"
#ifdef DONT_HAVE_LIBPCAP_PCAP_FREECODE
extern "C" {
extern "C"
{
#include <pcap-int.h>
int pcap_freecode(pcap_t* unused, struct bpf_program* program)
{
program->bf_len = 0;
if ( program->bf_insns )
int pcap_freecode(pcap_t* unused, struct bpf_program* program)
{
free((char*) program->bf_insns); // copied from libpcap
program->bf_insns = 0;
program->bf_len = 0;
if ( program->bf_insns )
{
free((char*)program->bf_insns); // copied from libpcap
program->bf_insns = 0;
}
return 0;
}
return 0;
pcap_t* pcap_open_dead(int linktype, int snaplen)
{
pcap_t* p;
p = (pcap_t*)malloc(sizeof(*p));
if ( ! p )
return 0;
memset(p, 0, sizeof(*p));
p->fd = -1;
p->snapshot = snaplen;
p->linktype = linktype;
return p;
}
int pcap_compile_nopcap(int snaplen_arg, int linktype_arg, struct bpf_program* program,
char* buf, int optimize, bpf_u_int32 mask)
{
pcap_t* p;
int ret;
p = pcap_open_dead(linktype_arg, snaplen_arg);
if ( ! p )
return -1;
ret = pcap_compile(p, program, buf, optimize, mask);
pcap_close(p);
return ret;
}
}
pcap_t* pcap_open_dead(int linktype, int snaplen)
{
pcap_t* p;
p = (pcap_t*) malloc(sizeof(*p));
if ( ! p )
return 0;
memset(p, 0, sizeof(*p));
p->fd = -1;
p->snapshot = snaplen;
p->linktype = linktype;
return p;
}
int pcap_compile_nopcap(int snaplen_arg, int linktype_arg,
struct bpf_program* program, char* buf,
int optimize, bpf_u_int32 mask)
{
pcap_t* p;
int ret;
p = pcap_open_dead(linktype_arg, snaplen_arg);
if ( ! p )
return -1;
ret = pcap_compile(p, program, buf, optimize, mask);
pcap_close(p);
return ret;
}
}
#endif
namespace zeek::iosource::detail {
namespace zeek::iosource::detail
{
// Simple heuristic to identify filters that always match, so that we can
// skip the filtering in that case. "ip or not ip" is Bro's default filter.
static bool filter_matches_anything(const char *filter)
static bool filter_matches_anything(const char* filter)
{
return (! filter) || strlen(filter) == 0 || strcmp(filter, "ip or not ip") == 0;
}
BPF_Program::BPF_Program() : m_compiled(), m_matches_anything(false), m_program()
{
}
BPF_Program::BPF_Program() : m_compiled(), m_matches_anything(false), m_program() { }
BPF_Program::~BPF_Program()
{
FreeCode();
}
bool BPF_Program::Compile(pcap_t* pcap, const char* filter, uint32_t netmask,
char* errbuf, unsigned int errbuf_len, bool optimize)
bool BPF_Program::Compile(pcap_t* pcap, const char* filter, uint32_t netmask, char* errbuf,
unsigned int errbuf_len, bool optimize)
{
if ( ! pcap )
return false;
FreeCode();
if ( pcap_compile(pcap, &m_program, (char *) filter, optimize, netmask) < 0 )
if ( pcap_compile(pcap, &m_program, (char*)filter, optimize, netmask) < 0 )
{
if ( errbuf )
snprintf(errbuf, errbuf_len,
"pcap_compile(%s): %s", filter,
pcap_geterr(pcap));
snprintf(errbuf, errbuf_len, "pcap_compile(%s): %s", filter, pcap_geterr(pcap));
return false;
}
@ -100,9 +98,8 @@ bool BPF_Program::Compile(pcap_t* pcap, const char* filter, uint32_t netmask,
return true;
}
bool BPF_Program::Compile(int snaplen, int linktype, const char* filter,
uint32_t netmask, char* errbuf, unsigned int errbuf_len,
bool optimize)
bool BPF_Program::Compile(int snaplen, int linktype, const char* filter, uint32_t netmask,
char* errbuf, unsigned int errbuf_len, bool optimize)
{
FreeCode();
@ -120,14 +117,13 @@ bool BPF_Program::Compile(int snaplen, int linktype, const char* filter,
#ifdef LIBPCAP_PCAP_COMPILE_NOPCAP_HAS_ERROR_PARAMETER
char my_error[PCAP_ERRBUF_SIZE];
int err = pcap_compile_nopcap(snaplen, linktype, &m_program,
(char *) filter, optimize, netmask, my_error);
int err = pcap_compile_nopcap(snaplen, linktype, &m_program, (char*)filter, optimize, netmask,
my_error);
if ( err < 0 && errbuf )
safe_strncpy(errbuf, my_error, errbuf_len);
*errbuf = '\0';
*errbuf = '\0';
#else
int err = pcap_compile_nopcap(snaplen, linktype, &m_program,
(char*) filter, optimize, netmask);
int err = pcap_compile_nopcap(snaplen, linktype, &m_program, (char*)filter, optimize, netmask);
if ( err < 0 && errbuf && errbuf_len )
*errbuf = '\0';
@ -160,4 +156,4 @@ void BPF_Program::FreeCode()
}
}
} // namespace zeek::iosource::detail
} // namespace zeek::iosource::detail

View file

@ -4,17 +4,20 @@
#include <stdint.h>
extern "C" {
extern "C"
{
#include <pcap.h>
}
}
namespace zeek::iosource::detail {
namespace zeek::iosource::detail
{
// BPF_Programs are an abstraction around struct bpf_program,
// to create a clean facility for creating, compiling, and
// freeing such programs.
class BPF_Program {
class BPF_Program
{
public:
// Creates an empty, uncompiled BPF program.
BPF_Program();
@ -23,24 +26,22 @@ public:
// Creates a BPF program for the given pcap handle.
// Parameters are like in pcap_compile(). Returns true
// for successful compilation, false otherwise.
bool Compile(pcap_t* pcap, const char* filter, uint32_t netmask,
char* errbuf = nullptr, unsigned int errbuf_len = 0,
bool optimize = true);
bool Compile(pcap_t* pcap, const char* filter, uint32_t netmask, char* errbuf = nullptr,
unsigned int errbuf_len = 0, bool optimize = true);
// Creates a BPF program when no pcap handle is around,
// similarly to pcap_compile_nopcap(). Parameters are
// similar. Returns true on success.
bool Compile(int snaplen, int linktype, const char* filter,
uint32_t netmask, char* errbuf = nullptr, unsigned int errbuf_len = 0,
bool optimize = true);
bool Compile(int snaplen, int linktype, const char* filter, uint32_t netmask,
char* errbuf = nullptr, unsigned int errbuf_len = 0, bool optimize = true);
// Returns true if this program currently contains compiled
// code, false otherwise.
bool IsCompiled() { return m_compiled; }
bool IsCompiled() { return m_compiled; }
// Returns true if this program matches any packets. This is not
// comprehensive, but can identify a few cases where it does.
bool MatchesAnything() { return m_matches_anything; }
bool MatchesAnything() { return m_matches_anything; }
// Accessor to the compiled program. Returns nil when
// no program is currently compiled.
@ -54,6 +55,6 @@ protected:
bool m_compiled;
bool m_matches_anything;
struct bpf_program m_program;
};
};
} // namespace zeek::iosource::detail
} // namespace zeek::iosource::detail

View file

@ -5,10 +5,10 @@
#include "zeek/Desc.h"
#include "zeek/Reporter.h"
namespace zeek::iosource {
namespace zeek::iosource
{
Component::Component(const std::string& name)
: plugin::Component(plugin::component::IOSOURCE, name)
Component::Component(const std::string& name) : plugin::Component(plugin::component::IOSOURCE, name)
{
}
@ -17,11 +17,10 @@ Component::Component(plugin::component::Type type, const std::string& name)
{
}
Component::~Component()
{
}
Component::~Component() { }
PktSrcComponent::PktSrcComponent(const std::string& arg_name, const std::string& arg_prefix, InputType arg_type, factory_callback arg_factory)
PktSrcComponent::PktSrcComponent(const std::string& arg_name, const std::string& arg_prefix,
InputType arg_type, factory_callback arg_factory)
: Component(plugin::component::PKTSRC, arg_name)
{
util::tokenize_string(arg_prefix, ":", &prefixes);
@ -29,9 +28,7 @@ PktSrcComponent::PktSrcComponent(const std::string& arg_name, const std::string&
factory = arg_factory;
}
PktSrcComponent::~PktSrcComponent()
{
}
PktSrcComponent::~PktSrcComponent() { }
const std::vector<std::string>& PktSrcComponent::Prefixes() const
{
@ -40,8 +37,7 @@ const std::vector<std::string>& PktSrcComponent::Prefixes() const
bool PktSrcComponent::HandlesPrefix(const std::string& prefix) const
{
for ( std::vector<std::string>::const_iterator i = prefixes.begin();
i != prefixes.end(); i++ )
for ( std::vector<std::string>::const_iterator i = prefixes.begin(); i != prefixes.end(); i++ )
{
if ( *i == prefix )
return true;
@ -71,8 +67,7 @@ void PktSrcComponent::DoDescribe(ODesc* d) const
std::string prefs;
for ( std::vector<std::string>::const_iterator i = prefixes.begin();
i != prefixes.end(); i++ )
for ( std::vector<std::string>::const_iterator i = prefixes.begin(); i != prefixes.end(); i++ )
{
if ( prefs.size() )
prefs += ", ";
@ -88,35 +83,34 @@ void PktSrcComponent::DoDescribe(ODesc* d) const
d->Add(prefs);
d->Add("; supports ");
switch ( type ) {
case LIVE:
d->Add("live input");
break;
switch ( type )
{
case LIVE:
d->Add("live input");
break;
case TRACE:
d->Add("trace input");
break;
case TRACE:
d->Add("trace input");
break;
case BOTH:
d->Add("live and trace input");
break;
case BOTH:
d->Add("live and trace input");
break;
default:
reporter->InternalError("unknown PkrSrc type");
default:
reporter->InternalError("unknown PkrSrc type");
}
}
}
PktDumperComponent::PktDumperComponent(const std::string& name, const std::string& arg_prefix, factory_callback arg_factory)
PktDumperComponent::PktDumperComponent(const std::string& name, const std::string& arg_prefix,
factory_callback arg_factory)
: plugin::Component(plugin::component::PKTDUMPER, name)
{
util::tokenize_string(arg_prefix, ":", &prefixes);
factory = arg_factory;
}
PktDumperComponent::~PktDumperComponent()
{
}
PktDumperComponent::~PktDumperComponent() { }
PktDumperComponent::factory_callback PktDumperComponent::Factory() const
{
@ -130,8 +124,7 @@ const std::vector<std::string>& PktDumperComponent::Prefixes() const
bool PktDumperComponent::HandlesPrefix(const std::string& prefix) const
{
for ( std::vector<std::string>::const_iterator i = prefixes.begin();
i != prefixes.end(); i++ )
for ( std::vector<std::string>::const_iterator i = prefixes.begin(); i != prefixes.end(); i++ )
{
if ( *i == prefix )
return true;
@ -146,8 +139,7 @@ void PktDumperComponent::DoDescribe(ODesc* d) const
std::string prefs;
for ( std::vector<std::string>::const_iterator i = prefixes.begin();
i != prefixes.end(); i++ )
for ( std::vector<std::string>::const_iterator i = prefixes.begin(); i != prefixes.end(); i++ )
{
if ( prefs.size() )
prefs += ", ";
@ -164,4 +156,4 @@ void PktDumperComponent::DoDescribe(ODesc* d) const
d->Add(prefs);
}
} // namespace zeek::iosource
} // namespace zeek::iosource

View file

@ -7,7 +7,8 @@
#include "zeek/plugin/Component.h"
namespace zeek::iosource {
namespace zeek::iosource
{
class IOSource;
class PktSrc;
@ -16,7 +17,8 @@ class PktDumper;
/**
* Component description for plugins providing IOSources.
*/
class Component : public plugin::Component {
class Component : public plugin::Component
{
public:
typedef IOSource* (*factory_callback)();
@ -34,7 +36,6 @@ public:
~Component() override;
protected:
/**
* Constructor to use by derived classes.
*
@ -44,21 +45,23 @@ protected:
* be unique across all components of this type.
*/
Component(plugin::component::Type type, const std::string& name);
};
};
/**
* Component description for plugins providing a PktSrc for packet input.
*/
class PktSrcComponent : public Component {
class PktSrcComponent : public Component
{
public:
/**
* Type of input a packet source supports.
*/
enum InputType {
LIVE, ///< Live input.
TRACE, ///< Offline input from trace file.
BOTH ///< Live input as well as offline.
};
enum InputType
{
LIVE, ///< Live input.
TRACE, ///< Offline input from trace file.
BOTH ///< Live input as well as offline.
};
typedef PktSrc* (*factory_callback)(const std::string& path, bool is_live);
@ -75,7 +78,8 @@ public:
*
* @param factor Factory function to instantiate component.
*/
PktSrcComponent(const std::string& name, const std::string& prefixes, InputType type, factory_callback factory);
PktSrcComponent(const std::string& name, const std::string& prefixes, InputType type,
factory_callback factory);
/**
* Destructor.
@ -119,7 +123,7 @@ private:
std::vector<std::string> prefixes;
InputType type;
factory_callback factory;
};
};
/**
* Component description for plugins providing a PktDumper for packet output.
@ -127,14 +131,16 @@ private:
* PktDumpers aren't IOSurces but we locate them here to keep them along with
* the PktSrc.
*/
class PktDumperComponent : public plugin::Component {
class PktDumperComponent : public plugin::Component
{
public:
typedef PktDumper* (*factory_callback)(const std::string& path, bool append);
/**
* XXX
*/
PktDumperComponent(const std::string& name, const std::string& prefixes, factory_callback factory);
PktDumperComponent(const std::string& name, const std::string& prefixes,
factory_callback factory);
/**
* Destructor.
@ -165,6 +171,6 @@ public:
private:
std::vector<std::string> prefixes;
factory_callback factory;
};
};
} // namespace zeek::iosource
} // namespace zeek::iosource

View file

@ -2,29 +2,31 @@
#pragma once
namespace zeek::iosource {
namespace zeek::iosource
{
/**
* Interface class for components providing/consuming data inside Bro's main
* loop.
*/
class IOSource {
class IOSource
{
public:
/**
* Constructor.
*/
IOSource() { closed = false; }
IOSource() { closed = false; }
/**
* Destructor.
*/
virtual ~IOSource() {}
virtual ~IOSource() { }
/**
* Returns true if more data is to be expected in the future.
* Otherwise, source may be removed.
*/
bool IsOpen() const { return ! closed; }
bool IsOpen() const { return ! closed; }
/**
* Returns true if this is a packet source.
@ -34,13 +36,13 @@ public:
/**
* Initializes the source. Can be overwritten by derived classes.
*/
virtual void InitSource() { }
virtual void InitSource() { }
/**
* Finalizes the source when it's being closed. Can be overwritten by
* derived classes.
*/
virtual void Done() { }
virtual void Done() { }
/**
* Return the next timeout value for this source. This should be
@ -74,16 +76,15 @@ public:
virtual const char* Tag() = 0;
protected:
/*
* Callback for derived class to call when they have shutdown.
*
* @param is_closed True if the source is now closed.
*/
void SetClosed(bool is_closed) { closed = is_closed; }
void SetClosed(bool is_closed) { closed = is_closed; }
private:
bool closed;
};
};
} // namespace zeek::iosource
} // namespace zeek::iosource

View file

@ -2,25 +2,26 @@
#include "zeek/iosource/Manager.h"
#include <sys/types.h>
#include <assert.h>
#include <sys/event.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <assert.h>
#include "zeek/iosource/Component.h"
#include "zeek/iosource/IOSource.h"
#include "zeek/iosource/PktSrc.h"
#include "zeek/iosource/PktDumper.h"
#include "zeek/plugin/Manager.h"
#include "zeek/broker/Manager.h"
#include "zeek/NetVar.h"
#include "zeek/RunState.h"
#include "zeek/broker/Manager.h"
#include "zeek/iosource/Component.h"
#include "zeek/iosource/IOSource.h"
#include "zeek/iosource/PktDumper.h"
#include "zeek/iosource/PktSrc.h"
#include "zeek/plugin/Manager.h"
#include "zeek/util.h"
#define DEFAULT_PREFIX "pcap"
namespace zeek::iosource {
namespace zeek::iosource
{
Manager::WakeupHandler::WakeupHandler()
{
@ -115,7 +116,7 @@ void Manager::FindReadySources(std::vector<IOSource*>* ready)
// If there aren't any sources and exit_only_after_terminate is false, just
// return an empty set of sources. We want the main loop to end.
if ( Size() == 0 && ( ! BifConst::exit_only_after_terminate || run_state::terminating ) )
if ( Size() == 0 && (! BifConst::exit_only_after_terminate || run_state::terminating) )
return;
double timeout = -1;
@ -138,7 +139,7 @@ void Manager::FindReadySources(std::vector<IOSource*>* ready)
double next = iosource->GetNextTimeout();
bool added = false;
if ( timeout == -1 || ( next >= 0.0 && next < timeout ) )
if ( timeout == -1 || (next >= 0.0 && next < timeout) )
{
timeout = next;
timeout_src = iosource;
@ -174,8 +175,8 @@ void Manager::FindReadySources(std::vector<IOSource*>* ready)
}
}
DBG_LOG(DBG_MAINLOOP, "timeout: %f ready size: %zu time_to_poll: %d\n",
timeout, ready->size(), time_to_poll);
DBG_LOG(DBG_MAINLOOP, "timeout: %f ready size: %zu time_to_poll: %d\n", timeout,
ready->size(), time_to_poll);
// If we didn't find any IOSources with zero timeouts or it's time to
// force a poll, do that and return. Otherwise return the set of ready
@ -273,7 +274,8 @@ bool Manager::UnregisterFd(int fd, IOSource* src)
}
else
{
reporter->Error("Attempted to unregister an unknown file descriptor %d from %s", fd, src->Tag());
reporter->Error("Attempted to unregister an unknown file descriptor %d from %s", fd,
src->Tag());
return false;
}
}
@ -335,7 +337,7 @@ static std::pair<std::string, std::string> split_prefix(std::string path)
}
else
prefix= DEFAULT_PREFIX;
prefix = DEFAULT_PREFIX;
return std::make_pair(prefix, path);
}
@ -354,30 +356,29 @@ PktSrc* Manager::OpenPktSrc(const std::string& path, bool is_live)
for ( const auto& c : all_components )
{
if ( c->HandlesPrefix(prefix) &&
(( is_live && c->DoesLive() ) ||
(! is_live && c->DoesTrace())) )
((is_live && c->DoesLive()) || (! is_live && c->DoesTrace())) )
{
component = c;
break;
}
}
if ( ! component )
reporter->FatalError("type of packet source '%s' not recognized, or mode not supported", prefix.c_str());
reporter->FatalError("type of packet source '%s' not recognized, or mode not supported",
prefix.c_str());
// Instantiate packet source.
PktSrc* ps = (*component->Factory())(npath, is_live);
assert(ps);
DBG_LOG(DBG_PKTIO, "Created packet source of type %s for %s", component->Name().c_str(), npath.c_str());
DBG_LOG(DBG_PKTIO, "Created packet source of type %s for %s", component->Name().c_str(),
npath.c_str());
Register(ps);
return ps;
}
PktDumper* Manager::OpenPktDumper(const std::string& path, bool append)
{
std::pair<std::string, std::string> t = split_prefix(path);
@ -410,7 +411,8 @@ PktDumper* Manager::OpenPktDumper(const std::string& path, bool append)
// Set an error message if it didn't open successfully.
pd->Error("could not open");
DBG_LOG(DBG_PKTIO, "Created packer dumper of type %s for %s", component->Name().c_str(), npath.c_str());
DBG_LOG(DBG_PKTIO, "Created packer dumper of type %s for %s", component->Name().c_str(),
npath.c_str());
pd->Init();
pkt_dumpers.push_back(pd);
@ -418,4 +420,4 @@ PktDumper* Manager::OpenPktDumper(const std::string& path, bool append)
return pd;
}
} // namespace zeek::iosource
} // namespace zeek::iosource

View file

@ -2,20 +2,21 @@
#pragma once
#include "zeek/zeek-config.h"
#include <map>
#include <string>
#include <vector>
#include <map>
#include "zeek/iosource/IOSource.h"
#include "zeek/Flare.h"
#include "zeek/iosource/IOSource.h"
#include "zeek/zeek-config.h"
struct timespec;
struct kevent;
namespace zeek {
namespace iosource {
namespace zeek
{
namespace iosource
{
class PktSrc;
class PktDumper;
@ -24,7 +25,8 @@ class PktDumper;
* Manager class for IO sources. This handles all of the polling of sources
* in the main loop.
*/
class Manager {
class Manager
{
public:
/**
* Constructor.
@ -60,24 +62,24 @@ public:
* Returns the number of registered and still active sources,
* excluding those that are registered as \a dont_count.
*/
int Size() const { return sources.size() - dont_counts; }
int Size() const { return sources.size() - dont_counts; }
/**
* Returns total number of sources including dont_counts;
*/
int TotalSize() const { return sources.size(); }
int TotalSize() const { return sources.size(); }
/**
* Returns the registered PktSrc. If not source is registered yet,
* returns a nullptr.
*/
PktSrc* GetPktSrc() const { return pkt_src; }
PktSrc* GetPktSrc() const { return pkt_src; }
/**
* Terminate all processing immediately by removing all sources (and
* therefore now returning a Size() of zero).
*/
void Terminate() { RemoveAll(); }
void Terminate() { RemoveAll(); }
/**
* Opens a new packet source.
@ -97,7 +99,7 @@ public:
* @param path The file name to dump into.
*
* @param append True to append if \a path already exists.
*
*
* @return The new packet dumper, or null if an error occured.
*/
PktDumper* OpenPktDumper(const std::string& path, bool append);
@ -132,7 +134,6 @@ public:
void Wakeup(const std::string& where);
private:
/**
* Calls the appropriate poll method to gather a set of IOSources that are
* ready for processing.
@ -160,7 +161,8 @@ private:
void RemoveAll();
class WakeupHandler final : public IOSource {
class WakeupHandler final : public IOSource
{
public:
WakeupHandler();
~WakeupHandler();
@ -175,18 +177,19 @@ private:
// IOSource API methods
void Process() override;
const char* Tag() override { return "WakeupHandler"; }
double GetNextTimeout() override { return -1; }
const char* Tag() override { return "WakeupHandler"; }
double GetNextTimeout() override { return -1; }
private:
zeek::detail::Flare flare;
};
struct Source {
struct Source
{
IOSource* src = nullptr;
bool dont_count = false;
bool manage_lifetime = false;
};
};
using SourceList = std::vector<Source*>;
SourceList sources;
@ -208,10 +211,10 @@ private:
// This is only used for the output of the call to kqueue in FindReadySources().
// The actual events are stored as part of the queue.
std::vector<struct kevent> events;
};
};
} // namespace iosource
} // namespace iosource
extern iosource::Manager* iosource_mgr;
} // namespace zeek
} // namespace zeek

View file

@ -1,6 +1,7 @@
#include "zeek/iosource/Packet.h"
extern "C" {
extern "C"
{
#include <pcap.h>
#ifdef HAVE_NET_ETHERNET_H
#include <net/ethernet.h>
@ -12,23 +13,23 @@ extern "C" {
#elif defined(HAVE_NET_ETHERTYPES_H)
#include <net/ethertypes.h>
#endif
}
}
#include "zeek/Desc.h"
#include "zeek/IP.h"
#include "zeek/TunnelEncapsulation.h"
#include "zeek/Var.h"
#include "zeek/iosource/Manager.h"
#include "zeek/packet_analysis/Manager.h"
#include "zeek/Var.h"
#include "zeek/TunnelEncapsulation.h"
namespace zeek {
namespace zeek
{
void Packet::Init(int arg_link_type, pkt_timeval *arg_ts, uint32_t arg_caplen,
uint32_t arg_len, const u_char *arg_data, bool arg_copy,
std::string arg_tag)
void Packet::Init(int arg_link_type, pkt_timeval* arg_ts, uint32_t arg_caplen, uint32_t arg_len,
const u_char* arg_data, bool arg_copy, std::string arg_tag)
{
if ( data && copy )
delete [] data;
delete[] data;
link_type = arg_link_type;
ts = *arg_ts;
@ -41,7 +42,7 @@ void Packet::Init(int arg_link_type, pkt_timeval *arg_ts, uint32_t arg_caplen,
if ( arg_data && arg_copy )
{
data = new u_char[arg_caplen];
memcpy(const_cast<u_char *>(data), arg_data, arg_caplen);
memcpy(const_cast<u_char*>(data), arg_data, arg_caplen);
}
else
data = arg_data;
@ -72,7 +73,7 @@ void Packet::Init(int arg_link_type, pkt_timeval *arg_ts, uint32_t arg_caplen,
Packet::~Packet()
{
if ( copy )
delete [] data;
delete[] data;
}
RecordValPtr Packet::ToRawPktHdrVal() const
@ -112,8 +113,8 @@ RecordValPtr Packet::ToRawPktHdrVal() const
// Ethernet header layout is:
// dst[6bytes] src[6bytes] ethertype[2bytes]...
l2_hdr->Assign(0, BifType::Enum::link_encap->GetEnumVal(BifEnum::LINK_ETHERNET));
l2_hdr->Assign(3, FmtEUI48(data + 6)); // src
l2_hdr->Assign(4, FmtEUI48(data)); // dst
l2_hdr->Assign(3, FmtEUI48(data + 6)); // src
l2_hdr->Assign(4, FmtEUI48(data)); // dst
if ( vlan )
l2_hdr->Assign(5, vlan);
@ -148,9 +149,9 @@ RecordValPtr Packet::ToRawPktHdrVal() const
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]);
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<StringVal>(buf);
}
} // namespace zeek
} // namespace zeek

View file

@ -1,11 +1,11 @@
#pragma once
#include "zeek/zeek-config.h"
#include <stdint.h>
#include <sys/types.h> // for u_char
#include <string>
#include "zeek/zeek-config.h"
#if defined(__OpenBSD__)
#include <net/bpf.h>
typedef struct bpf_timeval pkt_timeval;
@ -15,11 +15,12 @@ typedef struct timeval pkt_timeval;
#include <pcap.h> // For DLT_ constants
#include "zeek/IP.h"
#include "zeek/NetVar.h" // For BifEnum::Tunnel
#include "zeek/TunnelEncapsulation.h"
#include "zeek/IP.h"
namespace zeek {
namespace zeek
{
class ODesc;
class Val;
@ -34,17 +35,19 @@ using RecordValPtr = IntrusivePtr<RecordVal>;
* This enum is sized as an int32_t to make the Packet structure align
* correctly.
*/
enum Layer3Proto : int32_t {
L3_UNKNOWN = -1, /// Layer 3 type could not be determined.
L3_IPV4 = 1, /// Layer 3 is IPv4.
L3_IPV6 = 2, /// Layer 3 is IPv6.
L3_ARP = 3, /// Layer 3 is ARP.
};
enum Layer3Proto : int32_t
{
L3_UNKNOWN = -1, /// Layer 3 type could not be determined.
L3_IPV4 = 1, /// Layer 3 is IPv4.
L3_IPV6 = 2, /// Layer 3 is IPv6.
L3_ARP = 3, /// Layer 3 is ARP.
};
/**
* A link-layer packet.
*/
class Packet {
class Packet
{
public:
/**
* Construct and initialize from packet data.
@ -68,12 +71,11 @@ public:
* @param tag A textual tag to associate with the packet for
* differentiating the input streams.
*/
Packet(int link_type, pkt_timeval *ts, uint32_t caplen,
uint32_t len, const u_char *data, bool copy = false,
std::string tag = "")
{
Init(link_type, ts, caplen, len, data, copy, tag);
}
Packet(int link_type, pkt_timeval* ts, uint32_t caplen, uint32_t len, const u_char* data,
bool copy = false, std::string tag = "")
{
Init(link_type, ts, caplen, len, data, copy, tag);
}
/**
* Default constructor. For internal use only.
@ -111,9 +113,8 @@ public:
* @param tag A textual tag to associate with the packet for
* differentiating the input streams.
*/
void Init(int link_type, pkt_timeval *ts, uint32_t caplen,
uint32_t len, const u_char *data, bool copy = false,
std::string tag = "");
void Init(int link_type, pkt_timeval* ts, uint32_t caplen, uint32_t len, const u_char* data,
bool copy = false, std::string tag = "");
/**
* Returns a \c raw_pkt_hdr RecordVal, which includes layer 2 and
@ -131,16 +132,16 @@ public:
* LinuxSLL packet analyzer doesn't have a destination address in the
* header and thus sets it to this default address.
*/
static constexpr const u_char L2_EMPTY_ADDR[L2_ADDR_LEN] = { 0 };
static constexpr const u_char L2_EMPTY_ADDR[L2_ADDR_LEN] = {0};
// These are passed in through the constructor.
std::string tag; /// Used in serialization
double time; /// Timestamp reconstituted as float
pkt_timeval ts; /// Capture timestamp
const u_char* data = nullptr; /// Packet data.
uint32_t len; /// Actual length on wire
uint32_t cap_len; /// Captured packet length
uint32_t link_type; /// pcap link_type (DLT_EN10MB, DLT_RAW, etc)
std::string tag; /// Used in serialization
double time; /// Timestamp reconstituted as float
pkt_timeval ts; /// Capture timestamp
const u_char* data = nullptr; /// Packet data.
uint32_t len; /// Actual length on wire
uint32_t cap_len; /// Captured packet length
uint32_t link_type; /// pcap link_type (DLT_EN10MB, DLT_RAW, etc)
/**
* Layer 3 protocol identified (if any).
@ -247,6 +248,6 @@ private:
// True if we need to delete associated packet memory upon
// destruction.
bool copy;
};
};
} // namespace zeek
} // namespace zeek

View file

@ -1,12 +1,13 @@
// See the file "COPYING" in the main distribution directory for copyright.
#include "zeek/iosource/PktDumper.h"
#include "zeek/DebugLogger.h"
#include "zeek/zeek-config.h"
#include "zeek/iosource/PktDumper.h"
#include "zeek/DebugLogger.h"
namespace zeek::iosource {
namespace zeek::iosource
{
PktDumper::PktDumper()
{
@ -14,9 +15,7 @@ PktDumper::PktDumper()
errmsg = "";
}
PktDumper::~PktDumper()
{
}
PktDumper::~PktDumper() { }
void PktDumper::Init()
{
@ -71,9 +70,8 @@ void PktDumper::Error(const std::string& msg)
{
errmsg = msg;
DBG_LOG(DBG_PKTIO, "Error with dumper %s: %s",
IsOpen() ? props.path.c_str() : "<not open>",
msg.c_str());
DBG_LOG(DBG_PKTIO, "Error with dumper %s: %s", IsOpen() ? props.path.c_str() : "<not open>",
msg.c_str());
}
} // namespace zeek::iosource
} // namespace zeek::iosource

View file

@ -2,19 +2,23 @@
#pragma once
#include "zeek/zeek-config.h"
#include <string>
namespace zeek {
#include "zeek/zeek-config.h"
namespace zeek
{
class Packet;
namespace iosource {
namespace iosource
{
/**
* Base class for packet dumpers.
*/
class PktDumper {
class PktDumper
{
public:
/**
* Constructor.
@ -92,10 +96,11 @@ protected:
* Structure to pass back information about the packet dumper to the
* base class. Derived class pass an instance of this to \a Opened().
*/
struct Properties {
struct Properties
{
std::string path;
double open_time;
};
};
/**
* Called from the implementations of \a Open() to signal that the
@ -133,7 +138,7 @@ private:
Properties props;
std::string errmsg;
};
};
} // namespace iosource
} // namespace zeek
} // namespace iosource
} // namespace zeek

View file

@ -1,22 +1,22 @@
// See the file "COPYING" in the main distribution directory for copyright.
#include "zeek/zeek-config.h"
#include "zeek/iosource/PktSrc.h"
#include <sys/stat.h>
#include "zeek/util.h"
#include "zeek/Hash.h"
#include "zeek/RunState.h"
#include "zeek/session/Manager.h"
#include "zeek/broker/Manager.h"
#include "zeek/iosource/Manager.h"
#include "zeek/packet_analysis/Manager.h"
#include "zeek/iosource/BPF_Program.h"
#include "zeek/iosource/Manager.h"
#include "zeek/iosource/pcap/pcap.bif.h"
#include "zeek/packet_analysis/Manager.h"
#include "zeek/session/Manager.h"
#include "zeek/util.h"
#include "zeek/zeek-config.h"
namespace zeek::iosource {
namespace zeek::iosource
{
PktSrc::Properties::Properties()
{
@ -81,7 +81,6 @@ void PktSrc::Opened(const Properties& arg_props)
return;
}
if ( props.is_live )
{
Info(util::fmt("listening on %s\n", props.path.c_str()));
@ -113,9 +112,8 @@ void PktSrc::Error(const std::string& msg)
// We don't report this immediately, Bro will ask us for the error
// once it notices we aren't open.
errbuf = msg;
DBG_LOG(DBG_PKTIO, "Error with source %s: %s",
IsOpen() ? props.path.c_str() : "<not open>",
msg.c_str());
DBG_LOG(DBG_PKTIO, "Error with source %s: %s", IsOpen() ? props.path.c_str() : "<not open>",
msg.c_str());
}
void PktSrc::Info(const std::string& msg)
@ -212,7 +210,8 @@ bool PktSrc::PrecompileBPFFilter(int index, const std::string& filter)
// Compile filter.
auto* code = new detail::BPF_Program();
if ( ! code->Compile(BifConst::Pcap::snaplen, LinkType(), filter.c_str(), Netmask(), errbuf, sizeof(errbuf)) )
if ( ! code->Compile(BifConst::Pcap::snaplen, LinkType(), filter.c_str(), Netmask(), errbuf,
sizeof(errbuf)) )
{
std::string msg = util::fmt("cannot compile BPF filter \"%s\"", filter.c_str());
@ -245,7 +244,7 @@ detail::BPF_Program* PktSrc::GetBPFFilter(int index)
return (static_cast<int>(filters.size()) > index ? filters[index] : nullptr);
}
bool PktSrc::ApplyBPFFilter(int index, const struct pcap_pkthdr *hdr, const u_char *pkt)
bool PktSrc::ApplyBPFFilter(int index, const struct pcap_pkthdr* hdr, const u_char* pkt)
{
detail::BPF_Program* code = GetBPFFilter(index);
@ -295,8 +294,9 @@ double PktSrc::GetNextTimeout()
// This duplicates the calculation used in run_state::check_pseudo_time().
double pseudo_time = current_packet.time - run_state::detail::first_timestamp;
double ct = (util::current_time(true) - run_state::detail::first_wallclock) * run_state::pseudo_realtime;
double ct = (util::current_time(true) - run_state::detail::first_wallclock) *
run_state::pseudo_realtime;
return std::max(0.0, pseudo_time - ct);
}
} // namespace zeek::iosource
} // namespace zeek::iosource

View file

@ -10,21 +10,27 @@
struct pcap_pkthdr;
namespace zeek::iosource {
namespace zeek::iosource
{
namespace detail { class BPF_Program; }
namespace detail
{
class BPF_Program;
}
/**
* Base class for packet sources.
*/
class PktSrc : public IOSource {
class PktSrc : public IOSource
{
public:
static const int NETMASK_UNKNOWN = 0xffffffff;
/**
* Struct for returning statistics on a packet source.
*/
struct Stats {
struct Stats
{
/**
* Packets received by source after filtering (w/o drops).
*/
@ -33,7 +39,7 @@ public:
/**
* Packets dropped by source.
*/
uint64_t dropped; // pkts dropped
uint64_t dropped; // pkts dropped
/**
* Total number of packets on link before filtering.
@ -42,12 +48,12 @@ public:
uint64_t link;
/**
* Bytes received by source after filtering (w/o drops).
*/
* Bytes received by source after filtering (w/o drops).
*/
uint64_t bytes_received;
Stats() { received = dropped = link = bytes_received = 0; }
};
Stats() { received = dropped = link = bytes_received = 0; }
};
/**
* Constructor.
@ -134,7 +140,7 @@ public:
* @param pkt The content of the packet to filter.
*
* @return True if it maches. */
bool ApplyBPFFilter(int index, const struct pcap_pkthdr *hdr, const u_char *pkt);
bool ApplyBPFFilter(int index, const struct pcap_pkthdr* hdr, const u_char* pkt);
/**
* Returns the packet currently being processed, if available.
@ -209,7 +215,8 @@ protected:
* Structure to pass back information about the packet source to the
* base class. Derived class pass an instance of this to \a Opened().
*/
struct Properties {
struct Properties
{
/**
* The path associated with the source. This is the interface
* name for live source, and a filename for offline sources.
@ -240,7 +247,7 @@ protected:
bool is_live;
Properties();
};
};
/**
* Called from the implementations of \a Open() to signal that the
@ -330,7 +337,6 @@ protected:
virtual void DoneWithPacket() = 0;
private:
// Internal helper for ExtractNextPacket().
bool ExtractNextPacketInternal();
@ -346,9 +352,9 @@ private:
Packet current_packet;
// For BPF filtering support.
std::vector<detail::BPF_Program *> filters;
std::vector<detail::BPF_Program*> filters;
std::string errbuf;
};
};
} // namespace zeek::iosource
} // namespace zeek::iosource

View file

@ -2,15 +2,15 @@
#include "zeek/iosource/pcap/Dumper.h"
#include <sys/stat.h>
#include <errno.h>
#include <sys/stat.h>
#include "zeek/iosource/PktSrc.h"
#include "zeek/RunState.h"
#include "zeek/iosource/PktSrc.h"
#include "zeek/iosource/pcap/pcap.bif.h"
namespace zeek::iosource::pcap {
namespace zeek::iosource::pcap
{
PcapDumper::PcapDumper(const std::string& path, bool arg_append)
{
@ -20,9 +20,7 @@ PcapDumper::PcapDumper(const std::string& path, bool arg_append)
pd = nullptr;
}
PcapDumper::~PcapDumper()
{
}
PcapDumper::~PcapDumper() { }
void PcapDumper::Open()
{
@ -74,7 +72,7 @@ void PcapDumper::Open()
// is not supported by libpcap. So, we have to hack a
// little bit, knowing that pcap_dumpter_t is, in fact,
// a FILE ... :-(
dumper = (pcap_dumper_t*) fopen(props.path.c_str(), "a");
dumper = (pcap_dumper_t*)fopen(props.path.c_str(), "a");
if ( ! dumper )
{
Error(util::fmt("can't open dump %s: %s", props.path.c_str(), strerror(errno)));
@ -105,11 +103,9 @@ bool PcapDumper::Dump(const Packet* pkt)
return false;
// Reconstitute the pcap_pkthdr.
const struct pcap_pkthdr phdr = {
.ts = pkt->ts, .caplen = pkt->cap_len, .len = pkt->len
};
const struct pcap_pkthdr phdr = {.ts = pkt->ts, .caplen = pkt->cap_len, .len = pkt->len};
pcap_dump((u_char*) dumper, &phdr, pkt->data);
pcap_dump((u_char*)dumper, &phdr, pkt->data);
return true;
}
@ -118,4 +114,4 @@ iosource::PktDumper* PcapDumper::Instantiate(const std::string& path, bool appen
return new PcapDumper(path, append);
}
} // namespace zeek::iosource::pcap
} // namespace zeek::iosource::pcap

View file

@ -2,15 +2,18 @@
#pragma once
extern "C" {
extern "C"
{
#include <pcap.h>
}
}
#include "zeek/iosource/PktDumper.h"
namespace zeek::iosource::pcap {
namespace zeek::iosource::pcap
{
class PcapDumper : public PktDumper {
class PcapDumper : public PktDumper
{
public:
PcapDumper(const std::string& path, bool append);
~PcapDumper() override;
@ -29,6 +32,6 @@ private:
bool append;
pcap_dumper_t* dumper;
pcap_t* pd;
};
};
} // namespace zeek::iosource::pcap
} // namespace zeek::iosource::pcap

View file

@ -1,27 +1,30 @@
// See the file in the main distribution directory for copyright.
#include "zeek/plugin/Plugin.h"
#include "zeek/iosource/Component.h"
#include "zeek/iosource/pcap/Source.h"
#include "zeek/iosource/pcap/Dumper.h"
#include "zeek/iosource/pcap/Source.h"
namespace zeek::plugin::detail::Zeek_Pcap {
namespace zeek::plugin::detail::Zeek_Pcap
{
class Plugin : public plugin::Plugin {
class Plugin : public plugin::Plugin
{
public:
plugin::Configuration Configure() override
{
AddComponent(new iosource::PktSrcComponent(
"PcapReader", "pcap", iosource::PktSrcComponent::BOTH,
iosource::pcap::PcapSource::Instantiate));
AddComponent(new iosource::PktDumperComponent(
"PcapWriter", "pcap", iosource::pcap::PcapDumper::Instantiate));
AddComponent(new iosource::PktSrcComponent("PcapReader", "pcap",
iosource::PktSrcComponent::BOTH,
iosource::pcap::PcapSource::Instantiate));
AddComponent(new iosource::PktDumperComponent("PcapWriter", "pcap",
iosource::pcap::PcapDumper::Instantiate));
plugin::Configuration config;
config.name = "Zeek::Pcap";
config.description = "Packet acquisition via libpcap";
return config;
}
} plugin;
} plugin;
} // namespace zeek::plugin::detail::Zeek_Pcap
} // namespace zeek::plugin::detail::Zeek_Pcap

View file

@ -1,19 +1,20 @@
// See the file in the main distribution directory for copyright.
#include "zeek/zeek-config.h"
#include "zeek/iosource/pcap/Source.h"
#include "zeek/zeek-config.h"
#ifdef HAVE_PCAP_INT_H
#include <pcap-int.h>
#endif
#include "zeek/iosource/Packet.h"
#include "zeek/iosource/BPF_Program.h"
#include "zeek/Event.h"
#include "zeek/iosource/BPF_Program.h"
#include "zeek/iosource/Packet.h"
#include "zeek/iosource/pcap/pcap.bif.h"
namespace zeek::iosource::pcap {
namespace zeek::iosource::pcap
{
PcapSource::~PcapSource()
{
@ -156,7 +157,7 @@ void PcapSource::OpenLive()
#endif
#ifdef HAVE_PCAP_INT_H
Info(util::fmt("pcap bufsize = %d\n", ((struct pcap *) pd)->bufsize));
Info(util::fmt("pcap bufsize = %d\n", ((struct pcap*)pd)->bufsize));
#endif
props.selectable_fd = pcap_get_selectable_fd(pd);
@ -200,39 +201,40 @@ bool PcapSource::ExtractNextPacket(Packet* pkt)
int res = pcap_next_ex(pd, &header, &data);
switch ( res ) {
case PCAP_ERROR_BREAK: // -2
// Exhausted pcap file, no more packets to read.
assert(! props.is_live);
Close();
return false;
case PCAP_ERROR: // -1
// Error occurred while reading the packet.
if ( props.is_live )
reporter->Error("failed to read a packet from %s: %s",
props.path.data(), pcap_geterr(pd));
else
reporter->FatalError("failed to read a packet from %s: %s",
props.path.data(), pcap_geterr(pd));
return false;
case 0:
// Read from live interface timed out (ok).
return false;
case 1:
// Read a packet without problem.
// Although, some libpcaps may claim to have read a packet, but either did
// not really read a packet or at least provide no way to access its
// contents, so the following check for null-data helps handle those cases.
if ( ! data )
{
reporter->Weird("pcap_null_data_packet");
switch ( res )
{
case PCAP_ERROR_BREAK: // -2
// Exhausted pcap file, no more packets to read.
assert(! props.is_live);
Close();
return false;
}
break;
default:
reporter->InternalError("unhandled pcap_next_ex return value: %d", res);
return false;
}
case PCAP_ERROR: // -1
// Error occurred while reading the packet.
if ( props.is_live )
reporter->Error("failed to read a packet from %s: %s", props.path.data(),
pcap_geterr(pd));
else
reporter->FatalError("failed to read a packet from %s: %s", props.path.data(),
pcap_geterr(pd));
return false;
case 0:
// Read from live interface timed out (ok).
return false;
case 1:
// Read a packet without problem.
// Although, some libpcaps may claim to have read a packet, but either did
// not really read a packet or at least provide no way to access its
// contents, so the following check for null-data helps handle those cases.
if ( ! data )
{
reporter->Weird("pcap_null_data_packet");
return false;
}
break;
default:
reporter->InternalError("unhandled pcap_next_ex return value: %d", res);
return false;
}
pkt->Init(props.link_type, &header->ts, header->caplen, header->len, data);
@ -269,9 +271,7 @@ bool PcapSource::SetFilter(int index)
if ( ! code )
{
snprintf(errbuf, sizeof(errbuf),
"No precompiled pcap filter for index %d",
index);
snprintf(errbuf, sizeof(errbuf), "No precompiled pcap filter for index %d", index);
Error(errbuf);
return false;
}
@ -350,4 +350,4 @@ iosource::PktSrc* PcapSource::Instantiate(const std::string& path, bool is_live)
return new PcapSource(path, is_live);
}
} // namespace zeek::iosource::pcap
} // namespace zeek::iosource::pcap

View file

@ -4,15 +4,18 @@
#include <sys/types.h> // for u_char
extern "C" {
extern "C"
{
#include <pcap.h>
}
}
#include "zeek/iosource/PktSrc.h"
namespace zeek::iosource::pcap {
namespace zeek::iosource::pcap
{
class PcapSource : public PktSrc {
class PcapSource : public PktSrc
{
public:
PcapSource(const std::string& path, bool is_live);
~PcapSource() override;
@ -37,7 +40,7 @@ private:
Properties props;
Stats stats;
pcap_t *pd;
};
pcap_t* pd;
};
} // namespace zeek::iosource::pcap
} // namespace zeek::iosource::pcap