Main Page | Namespace List | Class Hierarchy | Alphabetical List | Class List | File List | Namespace Members | Class Members | File Members

util.h File Reference

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include "config.h"

Include dependency graph for util.h:

Include dependency graph

This graph shows which files directly or indirectly include this file:

Included by dependency graph

Go to the source code of this file.

Classes

struct  ltstr

Defines

#define myattribute(x)
#define ASSERT(x)
#define DEBUG_MSG(x...)
#define DEBUG_fputs(x...)
#define UHASH_KEY_SIZE   32
#define short_memcpy(a, b, c)
#define padded_sizeof(x)   (pad_size(sizeof(x)))

Typedefs

typedef unsigned long long int uint64
typedef unsigned int uint32
typedef unsigned short uint16
typedef unsigned char uint8
typedef long long int int64
typedef int bro_int_t
typedef uint32 bro_uint_t
typedef ptr_compat_uint SourceID

Functions

char * copy_string (const char *s)
int streq (const char *s1, const char *s2)
int expand_escape (const char *&s)
char * skip_whitespace (char *s)
const char * skip_whitespace (const char *s)
char * skip_whitespace (char *s, char *end_of_s)
const char * skip_whitespace (const char *s, const char *end_of_s)
char * skip_digits (char *s)
char * get_word (char *&s)
void get_word (int length, const char *s, int &pwlen, const char *&pw)
void to_upper (char *s)
const char * strchr_n (const char *s, const char *end_of_s, char ch)
const char * strrchr_n (const char *s, const char *end_of_s, char ch)
int decode_hex (char ch)
unsigned char encode_hex (int h)
int strcasecmp_n (int s_len, const char *s, const char *t)
const char * strpbrk_n (size_t len, const char *s, const char *charset)
int atoi_n (int len, const char *s, const char **end, int base, int &result)
int strstr_n (const int big_len, const unsigned char *big, const int little_len, const unsigned char *little)
int fputs (int len, const char *s, FILE *fp)
bool is_printable (const char *s, int len)
const char * fmt_bytes (const char *data, int len)
const char * fmt (const char *format,...) myattribute((format(printf
void fmt (int &len, const char *&b, const char *format,...) myattribute((format(printf
const char * fmt_access_time (double time)
void hash_md5 (size_t size, const unsigned char *bytes, unsigned char digest[16])
void hmac_md5 (size_t size, const unsigned char *bytes, unsigned char digest[16])
const char * md5_digest_print (const unsigned char digest[16])
void init_random_seed ()
uint64 rand64bit ()
void message (const char *msg)
void warn (const char *msg)
void warn (const char *msg, const char *addl)
void error (const char *msg)
void error (const char *msg, const char *addl)
void error (const char *msg, uint32 addl)
void run_time (const char *msg)
void run_time (const char *fmt, BroObj *obj)
void run_time (const char *fmt, const char *arg)
void run_time (const char *fmt, const char *arg1, const char *arg2)
void internal_error (const char *fmt,...) myattribute((volatile
void format (printf, 1, 2)))
void pinpoint ()
int int_list_cmp (const void *v1, const void *v2)
const char * bro_path ()
const char * bro_prefixes ()
FILE * search_for_file (const char *filename, const char *ext, const char **full_filename)
FILE * rotate_file (const char *name, RecordVal *rotate_info)
double current_time ()
int min (int a, int b)
int max (int a, int b)
size_t pad_size (size_t size)
void out_of_memory (const char *where)
void * safe_realloc (void *ptr, size_t size)
void * safe_malloc (size_t size)
char * safe_strncpy (char *dest, const char *src, size_t n)
int safe_snprintf (char *str, size_t size, const char *format,...)
int safe_vsnprintf (char *str, size_t size, const char *format, va_list al)
void get_memory_usage (unsigned int *total, unsigned int *malloced)

Variables

uint8 shared_hmac_md5_key [16]
int hmac_key_set
uint8 uhash_key [UHASH_KEY_SIZE]
const SourceID SOURCE_LOCAL = 0
double network_time


Define Documentation

#define ASSERT  ) 
 

Definition at line 49 of file util.h.

#define DEBUG_fputs x...   ) 
 

Definition at line 51 of file util.h.

Referenced by MIME_Entity::DebugPrintHeaders().

#define DEBUG_MSG x...   ) 
 

Definition at line 50 of file util.h.

#define myattribute  ) 
 

Definition at line 36 of file util.h.

#define padded_sizeof  )     (pad_size(sizeof(x)))
 

Definition at line 251 of file util.h.

Referenced by DataBlock::DataBlock(), ConnCompressor::DoExpire(), DFA_State_Cache::GetStats(), ProfileLogger::Log(), ConnCompressor::MakeNewState(), SubNetVal::MemoryAllocation(), RecordVal::MemoryAllocation(), TableVal::MemoryAllocation(), ListVal::MemoryAllocation(), PatternVal::MemoryAllocation(), StringVal::MemoryAllocation(), AddrVal::MemoryAllocation(), Val::MemoryAllocation(), UDP_Connection::MemoryAllocation(), TypeList::MemoryAllocation(), BroType::MemoryAllocation(), TCP_Connection::MemoryAllocation(), NetSessions::MemoryAllocation(), RE_Matcher::MemoryAllocation(), Specific_RE_Matcher::MemoryAllocation(), NFA_Machine::MemoryAllocation(), BaseList::MemoryAllocation(), ICMP_Connection::MemoryAllocation(), HashKey::MemoryAllocation(), Dictionary::MemoryAllocation(), DFA_Machine::MemoryAllocation(), Connection::MemoryAllocation(), CompositeHash::MemoryAllocation(), CCL::MemoryAllocation(), BroString::MemoryAllocation(), EquivClass::Size(), DFA_State::Size(), NFA_State::TotalMemoryAllocation(), and DataBlock::~DataBlock().

#define short_memcpy a,
b,
 ) 
 

Value:

if ( c < 40 ) \
                { \
                char* dst= (char*) a; \
                const char* src = (const char*) b; \
                for ( int i = c; i--; *dst++ = *src++ ); \
            } \
        else \
                memcpy(a, b, c);

Definition at line 225 of file util.h.

Referenced by ChunkedIOFd::ChunkAvailable(), ChunkedIOFd::ConcatChunks(), SerializationFormat::EndWrite(), ChunkedIOFd::ExtractChunk(), ChunkedIOFd::PutIntoWriteBuffer(), SerializationFormat::ReadData(), ChunkedIOFd::Write(), and SerializationFormat::WriteData().

#define UHASH_KEY_SIZE   32
 

Definition at line 144 of file util.h.

Referenced by HashKey::HashBytes(), and init_hash_function().


Typedef Documentation

typedef int bro_int_t
 

Definition at line 65 of file util.h.

Referenced by ODesc::AddCount(), Val::CoerceToInt(), ArithCoerceExpr::DoSimplify(), IncrExpr::DoSingleEval(), BinaryExpr::Fold(), Val::ForceAsInt(), HashKey::HashKey(), Val::InternalInt(), opt_internal_int(), recover_val(), CompositeHash::RecoverOneVal(), StateAccess::Replay(), CompositeHash::SingleTypeKeySize(), CompositeHash::SingleValHash(), TCP_Endpoint::Size(), and UDP_Connection::UpdateEndpointVal().

typedef uint32 bro_uint_t
 

Definition at line 66 of file util.h.

Referenced by SSLv3_Interpreter::analyzeCiphers(), SSLv2_Interpreter::analyzeCiphers(), SSL_ConnectionProxy::BuildCipherDict(), Val::CoerceToUnsigned(), ArithCoerceExpr::DoSimplify(), BinaryExpr::Fold(), Val::ForceAsUInt(), HashKey::HashKey(), Val::InternalUnsigned(), recover_val(), and CompositeHash::RecoverOneVal().

typedef long long int int64
 

Definition at line 59 of file util.h.

typedef ptr_compat_uint SourceID
 

Definition at line 155 of file util.h.

Referenced by EventHandler::AddRemoteHandler(), EventMgr::CurrentSource(), Event::Event(), EventMgr::QueueEvent(), EventHandler::RemoveRemoteHandler(), PersistenceSerializer::SendConfig(), PersistenceSerializer::SendState(), and Event::Source().

typedef unsigned short uint16
 

Definition at line 57 of file util.h.

Referenced by RemoteSerializer::AddPeer(), SSL_Interpreter::analyzeCertificate(), SSLv3_Interpreter::analyzeCiphers(), SSL_RecordBuilder::analyzeSSLRecordFormat(), TCP_Connection::BuildOSVal(), SSLv3_HandshakeRecord::checkClientHello(), SSLv3_HandshakeRecord::checkServerHello(), SSLv2_Interpreter::ClientHelloRecord(), SSLv2_Interpreter::ClientMasterKeyRecord(), RemoteSerializer::Connect(), SSLv3_Endpoint::Deliver(), SSLv3_Interpreter::DeliverSSLv3_Record(), SerialObj::DoSerialize(), ConnCompressor::DstPort(), SMB_Session::ExtractString(), SSLv3_Endpoint::ExtractVersion(), OSFingerprint::FindMatch(), SSL_Interpreter::fire_ssl_conn_alert(), SSL_Interpreter::fire_ssl_conn_attempt(), SSL_Interpreter::fire_ssl_conn_established(), SSL_Interpreter::fire_ssl_conn_server_reply(), IP_Hdr::FragField(), NetSessions::Get_OS_From_SYN(), getval(), HashKey::HashBytes(), IP_Hdr::HdrLen(), IP_Hdr::ID4(), IP_Hdr::IP_ID(), SocketComm::Listen(), RemoteSerializer::Listen(), SSL_ConnectionProxy::NewSSLRecord(), NextIP_ID(), TCP_Connection::NextPacket(), TCP_Connection::operator new(), IP_Hdr::PayloadLen(), FileSerializer::PrepareForWriting(), RemoteSerializer::ProcessConnected(), SocketComm::ProcessListen(), XMLSerializationFormat::Read(), BinarySerializationFormat::Read(), FileSerializer::ReadHeader(), SSLv2_Interpreter::ServerHelloRecord(), ConnCompressor::SrcPort(), SSLv3_AlertRecord::SSLv3_AlertRecord(), SSLv3_ApplicationRecord::SSLv3_ApplicationRecord(), SSLv3_ChangeCipherRecord::SSLv3_ChangeCipherRecord(), SSLv3_HandshakeRecord::SSLv3_HandshakeRecord(), SSLv3_Record::SSLv3_Record(), IP_Hdr::TotalLen(), SerialObj::Unserialize(), NetSessions::WantTCPConnection(), XMLSerializationFormat::Write(), and BinarySerializationFormat::Write().

typedef unsigned int uint32
 

Definition at line 56 of file util.h.

typedef unsigned long long int uint64
 

Definition at line 55 of file util.h.

Referenced by HashKey::HashBytes(), rand64bit(), TCP_Endpoint::Size(), and TwoWise::TwoWise().

typedef unsigned char uint8
 

Definition at line 58 of file util.h.

Referenced by SSL_RecordBuilder::addSegment(), SSL_Interpreter::analyzeCertificate(), SSL_RecordBuilder::analyzeSSLRecordFormat(), AnonymizeIPAddr_PrefixMD5::anonymize(), AnonymizeIPAddr_RandomMD5::anonymize(), bi_ffs(), TCP_Connection::BuildOSVal(), SSLv3_HandshakeRecord::checkClientHello(), SSLv3_HandshakeRecord::checkServerHello(), SSLv3_Interpreter::DeliverSSLv3_Record(), SSLv3_Endpoint::ExtractContentType(), OSFingerprint::FindMatch(), NetSessions::Get_OS_From_SYN(), getval(), TwoWise::Hash(), HashKey::HashBytes(), OSFingerprint::load_config(), ConnCompressor::MakeFlags(), SSLv2_Interpreter::NewSSLRecord(), SSLv3_AlertRecord::SSLv3_AlertRecord(), SSLv3_ChangeCipherRecord::SSLv3_ChangeCipherRecord(), SSLv3_HandshakeRecord::SSLv3_HandshakeRecord(), and NetSessions::WantTCPConnection().


Function Documentation

int atoi_n int  len,
const char *  s,
const char **  end,
int  base,
int &  result
 

Definition at line 285 of file util.cc.

References len.

Referenced by HTTP_Entity::Deliver(), and HTTP_Entity::SubmitHeader().

00286         {
00287         int n = 0;
00288         int neg = 0;
00289 
00290         if ( len > 0 && *s == '-' )
00291                 {
00292                 neg = 1;
00293                 --len; ++s;
00294                 }
00295 
00296         int i;
00297         for ( i = 0; i < len; ++i )
00298                 {
00299                 unsigned int d;
00300 
00301                 if ( isdigit(s[i]) )
00302                         d = s[i] - '0';
00303 
00304                 else if ( s[i] >= 'a' && s[i] < 'a' - 10 + base )
00305                         d = s[i] - 'a' + 10;
00306 
00307                 else if ( s[i] >= 'A' && s[i] < 'A' - 10 + base )
00308                         d = s[i] - 'A' + 10;
00309 
00310                 else if ( i > 0 )
00311                         break;
00312 
00313                 else
00314                         return 0;
00315 
00316                 n = n * base + d;
00317                 }
00318 
00319         if ( neg )
00320                 result = -n;
00321         else
00322                 result = n;
00323 
00324         if ( end )
00325                 *end = s + i;
00326 
00327         return 1;
00328         }

const char* bro_path  ) 
 

Definition at line 628 of file util.cc.

Referenced by search_for_file(), and usage().

00629         {
00630         const char* path = getenv("BROPATH");
00631         if ( ! path )
00632                 path = ".:policy:policy/local:policy/sigs:" LIBDEST;
00633 
00634         return path;
00635         }

const char* bro_prefixes  ) 
 

Definition at line 637 of file util.cc.

References len, loop_over_list, p, and prefixes.

Referenced by usage().

00638         {
00639         int len = 1;    // room for \0
00640         loop_over_list(prefixes, i)
00641                 len += strlen(prefixes[i]) + 1;
00642 
00643         char* p = new char[len];
00644 
00645         loop_over_list(prefixes, j)
00646                 if ( j == 0 )
00647                         strcpy(p, prefixes[j]);
00648                 else
00649                         {
00650                         strcat(p, ":");
00651                         strcat(p, prefixes[j]);
00652                         }
00653 
00654         return p;
00655         }

char* copy_string const char *  s  ) 
 

Definition at line 446 of file bif_lex.cc.

Referenced by add_input_file(), add_to_name_list(), EnumType::AddName(), EnumType::AddNamesFrom(), Rule::AddPattern(), Rule::AddRequires(), LoginConn::AddUserText(), begin_func(), BroFile::BroFile(), BuiltinFunc::BuiltinFunc(), check_c_mode(), PersistenceSerializer::CheckForFile(), dbg_execute_command(), DNS_Mapping::DNS_Mapping(), DNS_Mgr_Request::DNS_Mgr_Request(), SocketComm::Error(), EventHandler::EventHandler(), FieldExpr::FieldExpr(), Scope::GenerateTemporary(), ID::ID(), id_to_str(), DNS_Mapping::Init(), install_ID(), AssignExpr::IsRecordElement(), main(), merge_types(), nfmt(), open_file(), FileSerializer::OpenFile(), OSFingerprint::OSFingerprint(), OutputException::OutputException(), PktFileSrc::PktFileSrc(), PktInterfaceSrc::PktInterfaceSrc(), RecordConstructorExpr::RecordConstructorExpr(), Rule::Rule(), RuleActionEvent::RuleActionEvent(), RuleHdrTest::RuleHdrTest(), search_for_file(), SecondaryPath::SecondaryPath(), RemoteSerializer::SendCaptureFilter(), SocketComm::SendToParent(), SocketComm::SendToPeer(), PersistenceSerializer::SetDir(), DNS_Mgr::SetDir(), Serializer::SetErrorDescr(), and Specific_RE_Matcher::SetPat().

00447         {
00448         char* c = new char[strlen(s)+1];
00449         strcpy(c, s);
00450         return c;
00451         }

double current_time  ) 
 

Definition at line 759 of file util.cc.

References double, gettimeofday(), and internal_error().

Referenced by PktSrc::CheckPseudoTime(), ChunkedIOFd::ChunkedIOFd(), DNS_Mapping::Init(), ProfileLogger::Log(), main(), net_run(), RemoteSerializer::PeerConnected(), SocketComm::ProcessParentMessage(), RemoteSerializer::ProcessPongMsg(), SocketComm::ProcessRemoteMessage(), RemoteSerializer::SendPing(), TwoWise::TestSpeed(), and watchdog().

00760         {
00761         struct timeval tv;
00762         if ( gettimeofday(&tv, 0) < 0 )
00763                 internal_error("gettimeofday failed in current_time()");
00764 
00765         return double(tv.tv_sec) + double(tv.tv_usec) / 1e6;
00766         }

int decode_hex char  ch  ) 
 

Definition at line 223 of file util.cc.

Referenced by MIME_Entity::DecodeQuotedPrintable(), unescape_URI(), and UUID::UUID().

00224         {
00225         if ( ch >= '0' && ch <= '9' )
00226                 return ch - '0';
00227 
00228         if ( ch >= 'A' && ch <= 'F' )
00229                 return ch - 'A' + 10;
00230 
00231         if ( ch >= 'a' && ch <= 'f' )
00232                 return ch - 'a' + 10;
00233 
00234         return -1;
00235         }

unsigned char encode_hex int  h  ) 
 

Definition at line 237 of file util.cc.

References internal_error().

Referenced by escape_URI_char().

00238         {
00239         static const char hex[16] = {
00240                 '0', '1', '2', '3', '4', '5', '6', '7', '8',
00241                 '9', 'A', 'B', 'C', 'D', 'E', 'F'
00242         };
00243 
00244         if  ( h < 0 || h >= 16 )
00245                 {
00246                 internal_error("illegal value for encode_hex: %d", h);
00247                 return 'X';
00248                 }
00249 
00250         return hex[h];
00251         }

void error const char *  msg,
uint32  addl
 

Definition at line 548 of file util.cc.

References nerr, pinpoint(), and uint32.

Referenced by AddrVal::AddrVal(), BroFile::BroFile(), dotted_to_addr(), OSFingerprint::Error(), RecordType::Init(), RemoteSerializer::Init(), initdevice(), BroFile::InitEncrypt(), is_assignable(), load_mapping_table(), lookup_ID(), mask_addr(), NetVal::NetVal(), parse_dotted(), BinarySerializationFormat::Read(), SerializationFormat::ReadData(), RuleMatcher::ReadFiles(), same_stmt(), same_type(), TypeDecl::TypeDecl(), and yyparse().

00549         {
00550         pinpoint();
00551         fprintf(stderr, "error: %s - %u\n", msg, addl);
00552         ++nerr;
00553         }

void error const char *  msg,
const char *  addl
 

Definition at line 541 of file util.cc.

References nerr, and pinpoint().

00542         {
00543         pinpoint();
00544         fprintf(stderr, "error: %s %s\n", msg, addl);
00545         ++nerr;
00546         }

void error const char *  msg  ) 
 

Definition at line 534 of file util.cc.

References nerr, and pinpoint().

00535         {
00536         pinpoint();
00537         fprintf(stderr, "error: %s\n", msg);
00538         ++nerr;
00539         }

int expand_escape const char *&  s  ) 
 

Definition at line 69 of file util.cc.

References len, sscanf(), and warn().

00070         {
00071         switch ( *(s++) ) {
00072         case 'b': return '\b';
00073         case 'f': return '\f';
00074         case 'n': return '\n';
00075         case 'r': return '\r';
00076         case 't': return '\t';
00077         case 'a': return '\a';
00078         case 'v': return '\v';
00079 
00080         case '0': case '1': case '2': case '3': case '4':
00081         case '5': case '6': case '7':
00082                 { // <octal>{1,3}
00083                 --s;    // put back the first octal digit
00084                 const char* start = s;
00085 
00086                 // Don't increment inside loop control
00087                 // because if isdigit() is a macro it might
00088                 // expand into multiple increments ...
00089 
00090                 // Here we define a maximum length for escape sequence
00091                 // to allow easy handling of string like: "^H0" as
00092                 // "\0100".
00093 
00094                 for ( int len = 0; len < 3 && isascii(*s) && isdigit(*s);
00095                       ++s, ++len)
00096                         ;
00097 
00098                 int result;
00099                 if ( sscanf(start, "%3o", &result) != 1 )
00100                         {
00101                         warn("bad octal escape: ", start);
00102                         result = 0;
00103                         }
00104 
00105                 return result;
00106                 }
00107 
00108         case 'x':
00109                 { /* \x<hex> */
00110                 const char* start = s;
00111 
00112                 // Look at most 2 characters, so that "\x0ddir" -> "^Mdir".
00113                 for ( int len = 0; len < 2 && isascii(*s) && isxdigit(*s);
00114                       ++s, ++len);
00115 
00116                 int result;
00117                 if ( sscanf(start, "%2x", &result) != 1 )
00118                         {
00119                         warn("bad hexadecimal escape: ", start);
00120                         result = 0;
00121                         }
00122 
00123                 return result;
00124                 }
00125 
00126         default:
00127                 return s[-1];
00128         }
00129         }

void fmt int &  len,
const char *&  b,
const char *  format,
... 
 

Referenced by SocketComm::AcceptConnection(), Type::AddSizeVar(), SSL_Interpreter::analyzeCertificate(), VectorVal::Assign(), BroFile::BroFile(), PersistenceSerializer::CheckDir(), DNS_Mgr::CheckDir(), PersistenceSerializer::CheckForFile(), StateAccess::CheckOld(), StateAccess::CheckOldSet(), ChunkedIOFd::ChunkedIOFd(), SerialObj::ClassName(), OSFingerprint::collide(), compile(), RemoteSerializer::CompleteHandshake(), SocketComm::Connect(), DataPtr::DataPtr(), Base64Decoder::Decode(), MIME_Entity::DecodeQuotedPrintable(), SMB_Session::Deliver(), DCE_RPC_Session::DeliverBind(), TCP_Contents_SMB::DeliverSMB(), StateAccess::Describe(), DNS_Mgr::DNS_Mgr(), Base64Decoder::Done(), NetSessions::DoNextPacket(), RuleMatcher::DumpStateStats(), RuleMatcher::DumpStats(), ExceptionCyclicDependence::ExceptionCyclicDependence(), ExceptionIDNotField::ExceptionIDNotField(), ExceptionIDNotFound::ExceptionIDNotFound(), ExceptionIDRedefinition::ExceptionIDRedefinition(), ExceptionNonConstExpr::ExceptionNonConstExpr(), SMB_Session::ExtractString(), RemoteSerializer::FatalError(), BroFile::FinishEncrypt(), RemoteSerializer::Fork(), SocketComm::ForwardChunkToPeer(), TCP_Rewriter::Funeral(), Field::getFieldEnd(), RemoteSerializer::HandshakeDone(), HTTP_Conn::HTTP_Reply(), HTTP_Conn::HTTP_Request(), RemoteSerializer::Init(), SerialObj::Instantiate(), SocketComm::Listen(), ProfileLogger::Log(), SocketComm::Log(), RemoteSerializer::Log(), Logger::Log(), RemoteSerializer::LogStats(), PrefixTable::Lookup(), PersistenceSerializer::MoveFileUp(), UDP_Connection::NextPacket(), PktDumper::Open(), FileSerializer::OpenFile(), SMB_Session::ParseMessage(), RemoteSerializer::Poll(), CaseIndex::Prepare(), PaddingField::Prepare(), ArrayType::Prepare(), FileSerializer::PrepareForWriting(), AnonymizeIPAddr_A50::PreservePrefix(), SocketComm::ProcessParentCompress(), SocketComm::ProcessParentMessage(), SocketComm::ProcessRemoteMessage(), RemoteSerializer::ProcessRequestEventsMsg(), RemoteSerializer::ProcessStatsMsg(), SMB_Session::ProcessTransactionData(), RemoteSerializer::ProcessVersionMsg(), PacketProfiler::ProfilePkt(), TCP_RewriterEndpoint::PushPacket(), PersistenceSerializer::ReadAll(), FileSerializer::ReadHeader(), TCP_Reassembler::RecordGap(), SerialObj::Register(), TCP_Rewriter::ReleaseSlot(), NetSessions::Remove(), StateAccess::Replay(), EventPlayer::Replay(), UDP_NetbiosNS::Request(), RemoteSerializer::RequestEvents(), RemoteSerializer::RequestSync(), rotate_file(), NFS_Interp::RPC_BuildCall(), PersistenceSerializer::RunSerialization(), IDRecord::RValue(), ProfileLogger::SegmentProfile(), RemoteSerializer::SendCapabilities(), RemoteSerializer::SendCaptureFilter(), RemoteSerializer::SendToChild(), sendToIO(), SocketComm::SendToParent(), SocketComm::SendToPeer(), Serializer::StartSerialization(), PaddingField::StaticSize(), HTTP_Conn::Undelivered(), SerialObj::Unserialize(), Serializer::Unserialize(), Func::Unserialize(), BroFile::Unserialize(), Serializer::UnserializeCall(), BroFile::UpdateFileSize(), UUID::UUID(), XMLSerializationFormat::Write(), BroFile::Write(), ChunkedIOFd::WriteChunk(), TCP_RewriteSlot::WriteData(), TCP_RewriterEndpoint::WriteData(), XMLSerializationFormat::WriteEncodedString(), yyparse(), and TCP_RewriterEndpoint::~TCP_RewriterEndpoint().

const char* fmt const char *  format,
... 
 

Definition at line 23 of file pac_utils.cc.

References do_fmt(), and format().

00024         {
00025         va_list ap;
00026         va_start(ap, format);
00027         const char* r = do_fmt(format, ap);
00028         va_end(ap);
00029         return r;
00030         }

const char* fmt_access_time double  time  ) 
 

Definition at line 410 of file util.cc.

References strftime(), and time().

Referenced by Stmt::AccessStats(), and TableVal::Describe().

00411         {
00412         static char buf[256];
00413         time_t time = (time_t) t;
00414         strftime(buf, sizeof(buf), "%d/%m-%H:%M", localtime(&time));
00415         return buf;
00416         }

const char* fmt_bytes const char *  data,
int  len
 

Definition at line 361 of file util.cc.

References int, len, p, and snprintf().

Referenced by ChunkedIOFd::Read(), BinarySerializationFormat::Read(), ChunkedIOFd::Write(), and BinarySerializationFormat::Write().

00362         {
00363         static char buf[1024];
00364         char* p = buf;
00365 
00366         for ( int i = 0; i < len && p - buf < int(sizeof(buf)); ++i )
00367                 {
00368                 if ( isprint(data[i]) )
00369                         *p++ = data[i];
00370                 else
00371                         p += snprintf(p, sizeof(buf) - (p - buf),
00372                                         "\\x%02x", data[i]);
00373                 }
00374 
00375         if ( p - buf < int(sizeof(buf)) )
00376                 *p = '\0';
00377         else
00378                 buf[sizeof(buf) - 1] = '\0';
00379 
00380         return buf;
00381         }

void format printf  ,
,
 

Referenced by do_fmt(), BinPAC::do_fmt(), BroString::ExpandedString(), FileSerializer::FileSerializer(), fmt(), BinPAC::fmt(), nfmt(), safe_snprintf(), and safe_vsnprintf().

int fputs int  len,
const char *  s,
FILE *  fp
 

Definition at line 345 of file util.cc.

References len.

Referenced by convert(), cryptcat(), doone(), history_save(), main(), Rule::PrintDebug(), printIPAddr(), and Serializer::Warning().

00346         {
00347         for ( int i = 0; i < len; ++i )
00348                 if ( fputc(s[i], fp) == EOF )
00349                         return EOF;
00350         return 0;
00351         }

void get_memory_usage unsigned int *  total,
unsigned int *  malloced
 

Definition at line 774 of file util.cc.

Referenced by ProfileLogger::Log(), and PacketProfiler::ProfilePkt().

00775         {
00776 #ifdef HAVE_MALLINFO
00777         // For memory, getrusage() gives bogus results on Linux. Grmpf.
00778         const struct mallinfo& mi = mallinfo();
00779 
00780         if ( malloced )
00781                 *malloced = mi.uordblks;
00782 
00783         if ( total )
00784                 *total = mi.arena;
00785 #else
00786         struct rusage r;
00787         getrusage(RUSAGE_SELF, &r);
00788 
00789         if ( malloced )
00790                 *malloced = 0;
00791 
00792         if ( total )
00793                 // At least on FreeBSD it's in KB.
00794                 *total = r.ru_maxrss * 1024;
00795 #endif
00796         }

void get_word int  length,
const char *  s,
int &  pwlen,
const char *&  pw
 

Definition at line 181 of file util.cc.

References len.

Referenced by FTP_Conn::NewLine().

00182         {
00183         pw = s;
00184 
00185         int len = 0;
00186         while ( len < length && *s && ! isspace(*s) )
00187                 {
00188                 ++s;
00189                 ++len;
00190                 }
00191 
00192         pwlen = len;
00193         }

char* get_word char *&  s  ) 
 

Definition at line 166 of file util.cc.

References skip_whitespace().

00167         {
00168         char* w = s;
00169         while ( *s && ! isspace(*s) )
00170                 ++s;
00171 
00172         if ( *s )
00173                 {
00174                 *s = '\0';      // terminate the word
00175                 s = skip_whitespace(s+1);
00176                 }
00177 
00178         return w;
00179         }

void hash_md5 size_t  size,
const unsigned char *  bytes,
unsigned char  digest[16]
 

Definition at line 418 of file util.cc.

References md5_append(), md5_finish(), md5_init(), and size.

Referenced by hmac_md5(), init_random_seed(), and main().

00419         {
00420         md5_state_s h;
00421         md5_init(&h);
00422         md5_append(&h, bytes, size);
00423         md5_finish(&h, digest);
00424         }

void hmac_md5 size_t  size,
const unsigned char *  bytes,
unsigned char  digest[16]
 

Definition at line 439 of file util.cc.

References hash_md5(), hmac_key_set, internal_error(), shared_hmac_md5_key, and size.

Referenced by AnonymizeIPAddr_PrefixMD5::anonymize(), AnonymizeIPAddr_RandomMD5::anonymize(), HashKey::HashBytes(), and init_hash_function().

00440         {
00441         if ( ! hmac_key_set )
00442                 internal_error("HMAC-MD5 invoked before the HMAC key is set");
00443 
00444         hash_md5(size, bytes, digest);
00445 
00446         for ( int i = 0; i < 16; ++i )
00447                 digest[i] ^= shared_hmac_md5_key[i];
00448 
00449         hash_md5(16, digest, digest);
00450         }

void init_random_seed  ) 
 

Definition at line 452 of file util.cc.

References close(), gettimeofday(), hash_md5(), hmac_key_set, read(), shared_hmac_md5_key, srandom(), and uint32.

Referenced by main().

00453         {
00454         static const int bufsiz = 16;
00455         uint32 buf[bufsiz];
00456         int pos = 0;    // accumulates entropy
00457 
00458         // Gather up some entropy.
00459         gettimeofday((struct timeval *)(buf + pos), 0);
00460         pos += sizeof(struct timeval) / sizeof(uint32);
00461 
00462 #if defined(O_NONBLOCK)
00463         int fd = open("/dev/random", O_RDONLY | O_NONBLOCK);
00464 #elif defined(O_NDELAY)
00465         int fd = open("/dev/random", O_RDONLY | O_NDELAY);
00466 #else
00467         int fd = open("/dev/random", O_RDONLY);
00468 #endif
00469 
00470         if ( fd >= 0 )
00471                 {
00472                 int amt = read(fd, buf + pos, sizeof(uint32) * (bufsiz - pos));
00473                 close(fd);
00474 
00475                 if ( amt > 0 )
00476                         pos += (amt / sizeof(uint32));
00477                 }
00478 
00479         if ( pos < bufsiz )
00480                 {
00481                 buf[pos++] = getpid();
00482 
00483                 if ( pos < bufsiz )
00484                         buf[pos++] = getuid();
00485                 }
00486 
00487         uint32 result = 0;
00488         for ( int i = 0; i < pos; ++i )
00489                 {
00490                 result ^= buf[i];
00491                 result = (result << 1) | (result >> 31);
00492                 }
00493         srandom(result);
00494 
00495         if ( ! hmac_key_set )
00496                 {
00497                 hash_md5(sizeof(buf), (u_char*) buf, shared_hmac_md5_key);
00498                 hmac_key_set = 1;
00499                 }
00500         }

int int_list_cmp const void *  v1,
const void *  v2
 

Definition at line 615 of file util.cc.

References v1.

Referenced by CCL::Sort(), and DFA_Machine::StateSetToDFA_State().

00616         {
00617         ptr_compat_int i1 = *(ptr_compat_int*) v1;
00618         ptr_compat_int i2 = *(ptr_compat_int*) v2;
00619 
00620         if ( i1 < i2 )
00621                 return -1;
00622         else if ( i1 == i2 )
00623                 return 0;
00624         else
00625                 return 1;
00626         }

void internal_error const char *  fmt,
... 
volatile
 

Referenced by CQ_TimerMgr::Add(), PQ_TimerMgr::Add(), add_input_file(), ODesc::AddBytes(), anonymize_ip(), TypeList::Append(), TCP_TracePacket::AppendIPHeader(), TCP_TracePacket::AppendLinkHeader(), TCP_TracePacket::AppendTCPHeader(), bad_ref(), BroFile::BringIntoCache(), BuiltinFunc::BuiltinFunc(), check_and_promote(), TCP_Rewriter::CleanUpEmptyPlaceHolders(), RshConn::ClientUserName(), RloginConn::ClientUserName(), DNS_Mgr::CompareMappings(), Specific_RE_Matcher::CompileSet(), CompositeHash::ComputeSingletonHash(), RemoteSerializer::Connect(), ConversionSerializer::Convert(), CQ_TimerMgr::CQ_TimerMgr(), current_time(), DataBlock::DataBlock(), TCP_Endpoint::DataSent(), dbg_backtrace_internal(), dbg_cmd_break(), dbg_cmd_break_set_state(), dbg_cmd_frame(), dbg_eval_expr(), dbg_execute_command(), dbg_handle_debug_input(), DbgWatch::DbgWatch(), Base64Decoder::Decode(), MIME_Entity::DecodeBase64(), Stmt::DecrBPCount(), TableVal::Delete(), TCP_ContentLine::Deliver(), TCP_Contents_RPC::Deliver(), RPC_Interpreter::DeliverRPC(), TableVal::Describe(), StateAccess::Describe(), FragTimer::Dispatch(), EventMgr::Dispatch(), ConnectionTimer::Dispatch(), PersistenceSerializer::DoConnSerialization(), RshEndpoint::DoDeliver(), RloginEndpoint::DoDeliver(), TableVal::DoExpire(), PersistenceSerializer::DoIDSerialization(), RuleConditionPayloadSize::DoMatch(), NetSessions::DoNextPacket(), TCP_Rewriter::DumpPacket(), PacketDumper::DumpPacket(), NetSessions::DumpPacket(), encode_hex(), TableVal::ExpandAndInit(), BroObj::Fatal(), RecordType::FieldDecl(), AnonymizeIPAddr_A50::find_node(), NetSessions::FindConnection(), PacketSortGlobalPQ::FindConnPQ(), Dictionary::FinishChangeSize(), MIME_Entity::FinishDecodeBase64(), flatten_type(), TCP_RewriterEn