Various code optimizations and cleanup

This commit is contained in:
Luca Deri 2015-08-08 11:05:00 +02:00
parent 7619e57136
commit 4c35559151
27 changed files with 166 additions and 209 deletions

View file

@ -233,7 +233,7 @@ Makefile: @GIT_INDEX@
./configure
cppcheck:
cppcheck --template='{file}:{line}:{severity}:{message}' --quiet --enable=all --force @HIREDIS_INC@ $(MONGOOSE_INC) $(JSON_INC) $(NDPI_INC) $(LUAJIT_INC) $(LIBRRDTOOL_INC) $(ZEROMQ_INC) -I$(EWH_INC) *.cpp
cppcheck --template='{file}:{line}:{severity}:{message}' --quiet --enable=all --force -I include/ @HIREDIS_INC@ $(MONGOOSE_INC) $(JSON_INC) $(NDPI_INC) $(LUAJIT_INC) $(LIBRRDTOOL_INC) $(ZEROMQ_INC) -I$(EWH_INC) src/*.cpp
test: test_version

View file

@ -33,7 +33,7 @@ private:
patricia_tree_t *findCommunityById(int community_id);
patricia_tree_t *getCommunity(int community_id, string community_name);
string getCommunityName(int community_id);
string getCommunityName(int community_id); /* NOTUSED */
void addNetwork(int community_id, string community_name, char *_net);
public:

View file

@ -94,7 +94,6 @@ class Host : public GenericHost {
char* getJSON();
inline void setOS(char *_os) { if(os[0] == '\0') snprintf(os, sizeof(os), "%s", _os); }
inline IpAddress* get_ip() { return(ip); }
void set_antenna_mac(char *m);
void set_mac(char *m);
inline bool is_blacklisted() { return(blacklisted_host); }
inline u_int8_t* get_mac() { return(mac_address); }

View file

@ -53,9 +53,6 @@ class NetworkInterfaceView {
inline int get_id() { return id; }
inline char *get_descr(void);
bool hasNamesAs(const char *names);
bool hasIdsAs(const char *names);
void getnDPIStats(NdpiStats *stats);
void getActiveHostsList(lua_State* vm, patricia_tree_t *allowed_hosts, bool host_details, bool local_only);
void getCommunityHostsList(lua_State* vm, patricia_tree_t *allowed_hosts, bool host_details, int community_id);

View file

@ -40,7 +40,7 @@ class Prefs {
Ntop *ntop;
bool enable_dns_resolution, sniff_dns_responses, disable_host_persistency,
categorization_enabled, httpbl_enabled, resolve_all_host_ip, change_user, daemonize,
dump_timeline, enable_auto_logout, use_promiscuous_mode,
enable_auto_logout, use_promiscuous_mode,
disable_alerts, enable_ixia_timestamps, enable_vss_apcon_timestamps,
enable_users_login, disable_localhost_login;
LocationPolicy dump_hosts_to_db, sticky_hosts;
@ -106,7 +106,6 @@ class Prefs {
inline char* get_local_networks() { if (!local_networks_set) return NULL; return(local_networks); };
inline FILE* get_log_fd() { return(logFd); };
inline LocationPolicy get_host_stickness() { return(sticky_hosts); };
inline bool do_dump_timeline() { return(dump_timeline); };
inline void disable_dns_resolution() { enable_dns_resolution = false; };
inline void resolve_all_hosts() { resolve_all_host_ip = true; };
inline bool is_dns_resolution_enabled_for_all_hosts() { return(resolve_all_host_ip); };

View file

@ -97,13 +97,6 @@ class RuntimePrefs {
* @param use_bps Preference boolean value.
*/
void set_throughput_unit(bool use_bps);
/**
* @brief Test if the throughput preference is set to "bps".
* @details Read for Redis the preference, if it doesn't exist
* the preference will be set to default value (bps).
* @return True if the preference is "pps", false if it is "bps"
*/
bool use_bps_as_set_throughput_unit();
};
#endif /* _RUNTIME_PREFS_H_ */

View file

@ -245,7 +245,7 @@ void AddressResolution::resolveHostName(char *_numeric_ip, char *symbolic, u_int
numeric_ip_len = strlen(numeric_ip)-1;
if((symbolic != NULL) && (symbolic_len > 0)) symbolic[0] = '\0';
if((numeric_ip == NULL) || (numeric_ip[0] == '\0')) return;
if(numeric_ip[0] == '\0') return;
if(ntop->getRedis()->getAddress(numeric_ip, rsp, sizeof(rsp), false) < 0) {
char hostname[NI_MAXHOST];

View file

@ -49,6 +49,7 @@ CollectorInterface::CollectorInterface(const char *_endpoint, const char *_topic
zmq_close(subscriber[num_subscribers].socket);
zmq_ctx_destroy(context);
ntop->getTrace()->traceEvent(TRACE_ERROR, "Unable to connect to ZMQ endpoint %s", e);
free(tmp);
throw("Unable to connect to the specified ZMQ endpoint");
}

View file

@ -1,6 +1,6 @@
/*
*
* (C) 2013-15 - ntop.org
* (C) 2015 - ntop.org
*
*
* This program is free software; you can redistribute it and/or modify
@ -23,31 +23,44 @@
#include <iostream>
#include <vector>
/* ************************************************ */
CommunitiesManager::CommunitiesManager() {
num_communities = 0;
}
/* ************************************************ */
CommunitiesManager::~CommunitiesManager() {
}
/* ************************************************ */
patricia_tree_t *CommunitiesManager::findCommunityById(int community_id) {
return communities.at(community_id);
}
/* ************************************************ */
patricia_tree_t *CommunitiesManager::getCommunity(int community_id, string community_name) {
patricia_tree_t *ptree;
if ((ptree = findCommunityById(community_id)))
return ptree;
ptree = New_Patricia(128);
communities.at(community_id) = ptree;
community_names.at(community_id) = community_name;
return ptree;
}
/* ************************************************ */
string CommunitiesManager::getCommunityName(int community_id) {
return community_names.at(community_id);
}
/* ************************************************ */
void CommunitiesManager::addNetwork(int community_id, string community_name, char *_net) {
patricia_node_t *node;
patricia_tree_t *community = NULL;
@ -72,6 +85,8 @@ void CommunitiesManager::addNetwork(int community_id, string community_name, cha
num_communities++;
}
/* ************************************************ */
int CommunitiesManager::findAddress(int community_id, int family, void *addr) {
patricia_node_t *node = NULL;
@ -84,12 +99,14 @@ int CommunitiesManager::findAddress(int community_id, int family, void *addr) {
return node->user_data;
}
/* ************************************************ */
void CommunitiesManager::listAddressCommunitiesLua(lua_State* vm, int family, void *addr) {
int i = 0;
int num_communities = 0;
for (std::vector<patricia_tree_t *>::iterator it = communities.begin() ; it != communities.end(); ++it)
if (community_names.at(i) != "" && findAddress(i, family, addr) != -1) num_communities++;
if (community_names.at(i) != "" && findAddress(i, family, addr) != -1) num_communities++;
if (num_communities == 0) {
lua_pushnil(vm);
@ -106,6 +123,8 @@ void CommunitiesManager::listAddressCommunitiesLua(lua_State* vm, int family, vo
}
}
/* ************************************************ */
void CommunitiesManager::listCommunitiesLua(lua_State* vm) {
int i = 0;
int num_communities = 0;
@ -113,11 +132,11 @@ void CommunitiesManager::listCommunitiesLua(lua_State* vm) {
lua_newtable(vm);
for (std::vector<patricia_tree_t *>::iterator it = communities.begin() ; it != communities.end(); ++it) {
if (community_names.at(i) != "") {
lua_push_int_table_entry(vm, community_names.at(i).c_str(), i);
num_communities++;
}
i++;
if (community_names.at(i) != "") {
lua_push_int_table_entry(vm, community_names.at(i).c_str(), i);
num_communities++;
}
i++;
}
if (num_communities == 0) {
@ -125,11 +144,12 @@ void CommunitiesManager::listCommunitiesLua(lua_State* vm) {
return;
}
}
/* ************************************************ */
/* Format:
communityX@id1=net1,net2,net3
communityY@id2=net4,net5,net6
*/
*/
void CommunitiesManager::parseCommunitiesFile(char *fname) {
char *tok = NULL, community_name[MAX_PATH];
string st;
@ -160,7 +180,7 @@ void CommunitiesManager::parseCommunitiesFile(char *fname) {
return;
error:
error:
ntop->getTrace()->traceEvent(TRACE_ERROR, "Parsing error in file %s at line %d", fname, line);
}

View file

@ -71,13 +71,13 @@ void DB::initSQLiteDB(time_t when, const char *create_sql_string) {
when -= when % dir_duration;
strftime(path, sizeof(path), "%Y/%m/%d/%H", localtime(&when));
snprintf(db_path, sizeof(db_path), "%s/%u/flows/%s",
snprintf(db_path, sizeof(db_path), "%s/%d/flows/%s",
ntop->get_working_dir(), iface->get_id(), path);
ntop->fixPath(db_path);
if(Utils::mkdir_tree(db_path)) {
strftime(path, sizeof(path), "%Y/%m/%d/%H/%M", localtime(&when));
snprintf(db_path, sizeof(db_path), "%s/%u/flows/%s.sqlite",
snprintf(db_path, sizeof(db_path), "%s/%d/flows/%s.sqlite",
ntop->get_working_dir(), iface->get_id(), path);
end_dump = when + dir_duration;

View file

@ -34,7 +34,8 @@ Flow::Flow(NetworkInterface *_iface,
time_t _first_seen, time_t _last_seen) : GenericHashEntry(_iface) {
vlanId = _vlanId, protocol = _protocol, cli_port = _cli_port, srv_port = _srv_port;
cli2srv_packets = 0, cli2srv_bytes = 0, srv2cli_packets = 0, srv2cli_bytes = 0, cli2srv_last_packets = 0,
cli2srv_last_bytes = 0, srv2cli_last_packets = 0, srv2cli_last_bytes = 0;
cli2srv_last_bytes = 0, srv2cli_last_packets = 0, srv2cli_last_bytes = 0,
cli_host = srv_host = NULL, ndpi_flow= NULL;
l7_protocol_guessed = detection_completed = false;
dump_flow_traffic = false, ndpi_proto_name = NULL,
@ -1132,11 +1133,9 @@ char* Flow::serialize(bool partial_dump, bool es_json) {
char *rsp;
if(es_json) {
json_object *es_object;
ntop->getPrefs()->set_json_symbolic_labels_format(true);
if((my_object = flow2json(partial_dump)) != NULL) {
es_object = flow2es(my_object);
json_object *es_object = flow2es(my_object);
/* JSON string */
rsp = strdup(json_object_to_json_string(es_object));
@ -1653,7 +1652,7 @@ void Flow::dissectHTTP(bool src2dst_direction, char *payload, u_int payload_len)
}
} else {
if(dissect_next_http_packet) {
char *space, tmp[32];
char *space;
// payload[10]=0; ntop->getTrace()->traceEvent(TRACE_WARNING, "[len: %u][%s]", payload_len, payload);
h = cli_host->getHTTPStats(); if(h) h->incResponse(payload); /* Rcvd */
@ -1663,6 +1662,7 @@ void Flow::dissectHTTP(bool src2dst_direction, char *payload, u_int payload_len)
if((space = strchr(payload, ' ')) != NULL) {
payload = &space[1];
if((space = strchr(payload, ' ')) != NULL) {
char tmp[32];
int l = min_val((int)(space-payload), (int)(sizeof(tmp)-1));
strncpy(tmp, payload, l);

View file

@ -31,7 +31,7 @@ GenericHost::GenericHost(NetworkInterface *_iface) : GenericHashEntry(_iface) {
systemHost = false, localHost = false, last_activity_update = 0, host_serial = 0;
last_bytes = 0, last_bytes_thpt = bytes_thpt = 0, bytes_thpt_trend = trend_unknown;
last_bytes_periodic = 0;
last_bytes_periodic = 0, bytes_thpt_diff = 0;
last_packets = 0, last_pkts_thpt = pkts_thpt = 0, pkts_thpt_trend = trend_unknown;
last_update_time.tv_sec = 0, last_update_time.tv_usec = 0, vlan_id = 0;
num_alerts_detected = 0, source_id = 0;
@ -48,12 +48,10 @@ GenericHost::~GenericHost() {
/* *************************************** */
void GenericHost::readStats() {
if(!ntop->getPrefs()->do_dump_timeline())
return;
else {
if(localHost) {
char buf[64], *host_key, dump_path[MAX_PATH], daybuf[64];
time_t when = activityStats.get_wrap_time()-(86400/2) /* sec */;
host_key = get_string_key(buf, sizeof(buf));
strftime(daybuf, sizeof(daybuf), "%y/%m/%d", localtime(&when));
snprintf(dump_path, sizeof(dump_path), "%s/%s/activities/%s/%s",
@ -68,8 +66,6 @@ void GenericHost::readStats() {
/* *************************************** */
void GenericHost::dumpStats(bool forceDump) {
if(!ntop->getPrefs()->do_dump_timeline()) return;
if(localHost || forceDump) {
/* (Daily) Wrap */
char buf[64], *host_key;

View file

@ -173,7 +173,7 @@ static int is_authorized(const struct mg_connection *conn,
istringstream iss(auth_header);
getline(iss, auth_type, ' ');
if (auth_type == "Basic") {
string decoded_auth = "", user_s = "", pword_s = "";
string decoded_auth, user_s = "", pword_s = "";
/* In case auth type is Basic, info are encoded in base64 */
getline(iss, auth_string, ' ');
decoded_auth = Utils::base64_decode(auth_string);

View file

@ -152,7 +152,7 @@ int HistoricalInterface::loadData() {
memset(db_path, 0, sizeof(db_path));
strftime(path, sizeof(path), "%Y/%m/%d/%H/%M", localtime(&actual_epoch));
snprintf(db_path, sizeof(db_path), "%s/%u/flows/%s.sqlite",
snprintf(db_path, sizeof(db_path), "%s/%d/flows/%s.sqlite",
ntop->get_working_dir(), iface_dump_id , path);
loadData(db_path, limit);

View file

@ -54,8 +54,6 @@ Host::Host(NetworkInterface *_iface, u_int8_t mac[6],
/* *************************************** */
Host::~Host() {
char key[128];
if(num_uses > 0)
ntop->getTrace()->traceEvent(TRACE_WARNING, "Internal error: num_uses=%u", num_uses);
@ -66,7 +64,7 @@ Host::~Host() {
if((localHost || systemHost)
&& ntop->getPrefs()->is_host_persistency_enabled()) {
char *json = serialize();
char host_key[128];
char host_key[128], key[128];
char *k = get_string_key(host_key, sizeof(host_key));
snprintf(key, sizeof(key), "%s.%d.json", k, vlan_id);
@ -395,31 +393,20 @@ void Host::set_mac(char *m) {
/* *************************************** */
void Host::set_antenna_mac(char *m) {
u_int32_t mac[6] = { 0 };
sscanf(m, "%u:%u:%u:%u:%u:%u",
&mac[0], &mac[1], &mac[2], &mac[3], &mac[4], &mac[5]);
antenna_mac_address[0] = mac[0], antenna_mac_address[1] = mac[1],
antenna_mac_address[2] = mac[2], antenna_mac_address[3] = mac[3],
antenna_mac_address[4] = mac[4], antenna_mac_address[5] = mac[5];
}
/* *************************************** */
void Host::lua(lua_State* vm, patricia_tree_t *ptree,
bool host_details, bool verbose, bool returnHost) {
char buf[64], ip_buf[64];
char buf[64];
char buf_id[64];
char *ipaddr = NULL;
if(!match(ptree)) return;
lua_newtable(vm);
if(ip)
if(ip) {
char ip_buf[64];
lua_push_str_table_entry(vm, "ip", (ipaddr = ip->print(ip_buf, sizeof(ip_buf))));
else
} else
lua_push_nil_table_entry(vm, "ip");
if((antenna_mac_address[0] != 0)
@ -1230,10 +1217,11 @@ void Host::readAlertPrefs() {
if(ip && (!ip->isEmpty())) {
if(!ntop->getPrefs()->are_alerts_disabled()) {
char *key, ip_buf[48], rsp[32];
char *key, ip_buf[48];
key = get_string_key(ip_buf, sizeof(ip_buf));
if(key) {
char rsp[32];
ntop->getRedis()->hashGet((char*)CONST_ALERT_PREFS, key, rsp, sizeof(rsp));
trigger_host_alerts = ((strcmp(rsp, "false") == 0) ? 0 : 1);

View file

@ -456,7 +456,7 @@ static int ntop_get_interface_host_communities(lua_State* vm) {
if(lua_type(vm, 2) == LUA_TSTRING)
host = (char*)lua_tostring(vm, 2);
if (cm) cm->listAddressCommunitiesLua(vm, family, host);
if(cm) cm->listAddressCommunitiesLua(vm, family, host);
else return(CONST_LUA_ERROR);
return(CONST_LUA_OK);
}
@ -473,7 +473,7 @@ static int ntop_get_interface_communities(lua_State* vm) {
ntop->getTrace()->traceEvent(TRACE_INFO, "%s() called", __FUNCTION__);
if (cm) cm->listCommunitiesLua(vm);
if(cm) cm->listCommunitiesLua(vm);
else return(CONST_LUA_ERROR);
return(CONST_LUA_OK);
}
@ -699,10 +699,10 @@ static int ntop_has_communities(lua_State* vm) {
ntop->getTrace()->traceEvent(TRACE_INFO, "%s() called", __FUNCTION__);
if (cm)
lua_pushboolean(vm, 1);
if(cm)
lua_pushboolean(vm, 1);
else
lua_pushboolean(vm, 0);
lua_pushboolean(vm, 0);
return(CONST_LUA_OK);
}
@ -1168,19 +1168,20 @@ static int ntop_get_interface_flows_info(lua_State* vm) {
if(lua_type(vm, 2) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 2);
}
if (lua_type(vm, 3) == LUA_TSTRING)
if(lua_type(vm, 3) == LUA_TSTRING)
key = (char*)lua_tostring(vm, 3);
if (host_ip) {
if(host_ip) {
char ip[64];
strncpy(ip, host_ip, 64); /* don't rely on host_ip as strtok_r() doesn't always behave correctly */
snprintf(ip, sizeof(ip), "%s", host_ip); /* don't rely on host_ip as strtok_r() doesn't always behave correctly */
snprintf(SQL, sizeof(SQL), "SELECT %s FROM FLOWS WHERE host = %s AND vlan = %u", key ? : "*", ip, vlan_id);
} else {
snprintf(SQL, sizeof(SQL), "SELECT %s FROM FLOWS", key ? : "*");
}
if(ntop_interface) {
if (ntop_interface->retrieve(vm, get_allowed_nets(vm), SQL))
if(ntop_interface->retrieve(vm, get_allowed_nets(vm), SQL))
return CONST_LUA_ERROR;
}
@ -1208,7 +1209,7 @@ static int ntop_query_interface_flows_info(lua_State* vm) {
SQL = (char*)lua_tostring(vm, 1);
if(ntop_interface || !SQL) {
if (ntop_interface->retrieve(vm, get_allowed_nets(vm), SQL))
if(ntop_interface->retrieve(vm, get_allowed_nets(vm), SQL))
return CONST_LUA_ERROR;
}
@ -1874,7 +1875,7 @@ static int ntop_get_interface_pkts_dumped_file(lua_State* vm) {
return(CONST_LUA_ERROR);
PacketDumper *dumper = ntop_interface->getPacketDumper();
if (!dumper)
if(!dumper)
return CONST_LUA_ERROR;
num_pkts = dumper->get_num_dumped_packets();
@ -1894,7 +1895,7 @@ static int ntop_get_interface_pkts_dumped_tap(lua_State* vm) {
return(CONST_LUA_ERROR);
PacketDumperTuntap *dumper = ntop_interface->getPacketDumperTap();
if (!dumper)
if(!dumper)
return CONST_LUA_ERROR;
num_pkts = dumper->get_num_dumped_packets();
@ -2032,8 +2033,8 @@ static const char **make_argv(lua_State * vm, u_int offset) {
/* accepts string or number */
if(lua_isstring(vm, idx) || lua_isnumber(vm, idx)) {
if(!(argv[i] = (char*)lua_tostring (vm, idx))) {
/* raise an error and never return */
luaL_error(vm, "Error duplicating string area for arg #%d", i);
/* raise an error and never return */
luaL_error(vm, "Error duplicating string area for arg #%d", i);
}
} else {
/* raise an error and never return */
@ -2116,7 +2117,7 @@ static int ntop_rrd_fetch(lua_State* vm) {
unsigned long i, j, step = 0, ds_cnt = 0;
rrd_value_t *data, *p;
char **names, *err;
const char *filename, *cf, *start_s, *end_s;
const char *filename, *cf;
time_t t, start, end;
rrd_time_value_t start_tv, end_tv;
int status;
@ -2132,8 +2133,10 @@ static int ntop_rrd_fetch(lua_State* vm) {
if((lua_type(vm, 3) == LUA_TNUMBER) && (lua_type(vm, 4) == LUA_TNUMBER))
start = (time_t)lua_tonumber(vm, 3), end = (time_t)lua_tonumber(vm, 4);
else {
char *start_s, *end_s;
if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((start_s = (const char*)lua_tostring(vm, 3)) == NULL) return(CONST_LUA_PARAM_ERROR);
if((start_s = (char*)lua_tostring(vm, 3)) == NULL) return(CONST_LUA_PARAM_ERROR);
if((err = rrd_parsetime(start_s, &start_tv)) != NULL) {
luaL_error(vm, err);
@ -2141,7 +2144,7 @@ static int ntop_rrd_fetch(lua_State* vm) {
}
if(ntop_lua_check(vm, __FUNCTION__, 4, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR);
if((end_s = (const char*)lua_tostring(vm, 4)) == NULL) return(CONST_LUA_PARAM_ERROR);
if((end_s = (char*)lua_tostring(vm, 4)) == NULL) return(CONST_LUA_PARAM_ERROR);
if((err = rrd_parsetime(end_s, &end_tv)) != NULL) {
luaL_error(vm, err);
@ -2728,7 +2731,6 @@ static int ntop_check_license(lua_State* vm) {
static int ntop_get_info(lua_State* vm) {
char rsp[256], tmp[256];
int major, minor, patch;
bool svn;
ntop->getTrace()->traceEvent(TRACE_INFO, "%s() called", __FUNCTION__);
@ -2739,12 +2741,9 @@ static int ntop_get_info(lua_State* vm) {
lua_push_str_table_entry(vm, "license", (char*)"GNU GPLv3");
snprintf(tmp, sizeof(tmp), "r%s", PACKAGE_VERSION);
svn = !strncmp(rsp, tmp, sizeof(rsp));
snprintf(rsp, sizeof(rsp), "%s %s%s%s",
PACKAGE_VERSION,
svn ? "(" : "",
svn ? NTOPNG_GIT_RELEASE : "",
svn ? ")" : "");
snprintf(rsp, sizeof(rsp), "%s (%s)",
PACKAGE_VERSION, NTOPNG_GIT_RELEASE);
lua_push_str_table_entry(vm, "version", rsp);
snprintf(rsp, sizeof(rsp), "%s (%s)", PACKAGE_OSNAME, PACKAGE_MACHINE);
lua_push_str_table_entry(vm, "platform", rsp);
@ -3076,7 +3075,7 @@ static int ntop_stats_insert_minute_sampling(lua_State *vm) {
time(&rawtime);
if (sm->insertMinuteSampling(rawtime, sampling))
if(sm->insertMinuteSampling(rawtime, sampling))
return(CONST_LUA_ERROR);
return(CONST_LUA_OK);
@ -3114,7 +3113,7 @@ static int ntop_stats_insert_hour_sampling(lua_State *vm) {
time(&rawtime);
rawtime -= (rawtime % 60);
if (sm->insertHourSampling(rawtime, sampling))
if(sm->insertHourSampling(rawtime, sampling))
return(CONST_LUA_ERROR);
return(CONST_LUA_OK);
@ -3152,7 +3151,7 @@ static int ntop_stats_insert_day_sampling(lua_State *vm) {
time(&rawtime);
rawtime -= (rawtime % 60);
if (sm->insertDaySampling(rawtime, sampling))
if(sm->insertDaySampling(rawtime, sampling))
return(CONST_LUA_ERROR);
return(CONST_LUA_OK);
@ -3243,7 +3242,6 @@ static int ntop_stats_get_minute_real_epoch(lua_State *vm) {
*/
static int ntop_stats_delete_minute_older_than(lua_State *vm) {
int num_days;
string sampling;
int ifid;
NetworkInterface* iface;
StatsManager *sm;
@ -3282,7 +3280,6 @@ static int ntop_stats_delete_minute_older_than(lua_State *vm) {
*/
static int ntop_stats_delete_hour_older_than(lua_State *vm) {
int num_days;
string sampling;
int ifid;
NetworkInterface* iface;
StatsManager *sm;
@ -3321,7 +3318,6 @@ static int ntop_stats_delete_hour_older_than(lua_State *vm) {
*/
static int ntop_stats_delete_day_older_than(lua_State *vm) {
int num_days;
string sampling;
int ifid;
NetworkInterface* iface;
StatsManager *sm;
@ -3374,11 +3370,11 @@ static int ntop_stats_get_minute_samplings_interval(lua_State *vm) {
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR);
epoch_start = lua_tointeger(vm, 2);
if (epoch_start < 0)
if(epoch_start < 0)
return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TNUMBER)) return(CONST_LUA_ERROR);
epoch_end = lua_tointeger(vm, 3);
if (epoch_end < 0)
if(epoch_end < 0)
return(CONST_LUA_ERROR);
if(!(iface = ntop->getInterfaceById(ifid)) ||
@ -3424,11 +3420,11 @@ static int ntop_stats_get_samplings_of_minutes_from_epoch(lua_State *vm) {
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR);
epoch_end = lua_tointeger(vm, 2);
epoch_end -= (epoch_end % 60);
if (epoch_end < 0)
if(epoch_end < 0)
return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TNUMBER)) return(CONST_LUA_ERROR);
num_minutes = lua_tointeger(vm, 3);
if (num_minutes < 0)
if(num_minutes < 0)
return(CONST_LUA_ERROR);
if(!(iface = ntop->getInterfaceById(ifid)) ||
@ -3476,11 +3472,11 @@ static int ntop_stats_get_samplings_of_hours_from_epoch(lua_State *vm) {
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR);
epoch_end = lua_tointeger(vm, 2);
epoch_end -= (epoch_end % 60);
if (epoch_end < 0)
if(epoch_end < 0)
return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TNUMBER)) return(CONST_LUA_ERROR);
num_hours = lua_tointeger(vm, 3);
if (num_hours < 0)
if(num_hours < 0)
return(CONST_LUA_ERROR);
if(!(iface = ntop->getInterfaceById(ifid)) ||
@ -3528,11 +3524,11 @@ static int ntop_stats_get_samplings_of_days_from_epoch(lua_State *vm) {
if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR);
epoch_end = lua_tointeger(vm, 2);
epoch_end -= (epoch_end % 60);
if (epoch_end < 0)
if(epoch_end < 0)
return(CONST_LUA_ERROR);
if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TNUMBER)) return(CONST_LUA_ERROR);
num_days = lua_tointeger(vm, 3);
if (num_days < 0)
if(num_days < 0)
return(CONST_LUA_ERROR);
if(!(iface = ntop->getInterfaceById(ifid)) ||
@ -3567,13 +3563,13 @@ static int ntop_delete_dump_files(lua_State *vm) {
NetworkInterface *iface = ntop->getInterfaceById(ifid);
if (!iface) return CONST_LUA_ERROR;
if(!iface) return CONST_LUA_ERROR;
snprintf(pcap_path, sizeof(pcap_path), "%s/%u/pcap/",
ntop->get_working_dir(), ifid);
snprintf(pcap_path, sizeof(pcap_path), "%s/%d/pcap/",
ntop->get_working_dir(), ifid);
ntop->fixPath(pcap_path);
if (Utils::discardOldFilesExceeding(pcap_path, iface->getDumpTrafficMaxFiles()))
if(Utils::discardOldFilesExceeding(pcap_path, iface->getDumpTrafficMaxFiles()))
return(CONST_LUA_ERROR);
return(CONST_LUA_OK);
@ -3597,7 +3593,6 @@ static int ntop_mkdir_tree(lua_State* vm) {
static int ntop_list_reports(lua_State* vm) {
DIR *dir;
struct dirent *ent;
char fullpath[MAX_PATH];
ntop->getTrace()->traceEvent(TRACE_INFO, "%s() called", __FUNCTION__);
@ -3605,14 +3600,16 @@ static int ntop_list_reports(lua_State* vm) {
lua_newtable(vm);
snprintf(fullpath, sizeof(fullpath), "%s/%s", ntop->get_working_dir(), "reports");
ntop->fixPath(fullpath);
if ((dir = opendir(fullpath)) != NULL) {
if((dir = opendir(fullpath)) != NULL) {
struct dirent *ent;
while ((ent = readdir(dir)) != NULL) {
char filepath[MAX_PATH];
snprintf(filepath, sizeof(filepath), "%s/%s", fullpath, ent->d_name);
ntop->fixPath(filepath);
struct stat buf;
if (!stat(filepath, &buf) && !S_ISDIR(buf.st_mode))
lua_push_str_table_entry(vm, ent->d_name, (char*)"");
if(!stat(filepath, &buf) && !S_ISDIR(buf.st_mode))
lua_push_str_table_entry(vm, ent->d_name, (char*)"");
}
closedir(dir);
}
@ -3929,14 +3926,19 @@ static int ntop_lua_http_print(lua_State* vm) {
/* Handle binary blob */
if(lua_type(vm, 2) == LUA_TSTRING &&
(printtype = (char*)lua_tostring(vm, 2)) != NULL)
if (!strncmp(printtype, "blob", 4)) {
if(!strncmp(printtype, "blob", 4)) {
char *str = NULL;
int len;
if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return (CONST_LUA_ERROR);
str = (char*)lua_tostring(vm, 1);
len = strlen(str);
if (str && (len <= 1)) mg_printf(conn, "%c", str[0]);
else return (CONST_LUA_PARAM_ERROR);
if((str = (char*)lua_tostring(vm, 1)) != NULL) {
int len = strlen(str);
if(len <= 1)
mg_printf(conn, "%c", str[0]);
else
return (CONST_LUA_PARAM_ERROR);
}
return (CONST_LUA_OK);
}
@ -4028,8 +4030,8 @@ static int ntop_lua_require(lua_State* L)
{
char *script_name;
if (lua_type(L, 1) != LUA_TSTRING ||
(script_name = (char*)lua_tostring(L, 1)) == NULL)
if(lua_type(L, 1) != LUA_TSTRING ||
(script_name = (char*)lua_tostring(L, 1)) == NULL)
return 0;
lua_getglobal( L, "package" );
@ -4040,17 +4042,17 @@ static int ntop_lua_require(lua_State* L)
while(getline(input_stringstream, parsed, ';')) {
/* Example: package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path */
unsigned found = parsed.find_last_of("?");
if (found) {
if(found) {
string s = parsed.substr(0, found) + script_name + ".lua";
if (Utils::file_exists(s.c_str())) {
script_path = s;
break;
if(Utils::file_exists(s.c_str())) {
script_path = s;
break;
}
}
}
if (script_path == "" ||
__ntop_lua_handlefile(L, (char *)script_path.c_str(), false))
if(script_path == "" ||
__ntop_lua_handlefile(L, (char *)script_path.c_str(), false))
return 0;
return 1;
@ -4060,9 +4062,9 @@ static int ntop_lua_dofile(lua_State* L)
{
char *script_path;
if (lua_type(L, 1) != LUA_TSTRING ||
(script_path = (char*)lua_tostring(L, 1)) == NULL ||
__ntop_lua_handlefile(L, script_path, true))
if(lua_type(L, 1) != LUA_TSTRING ||
(script_path = (char*)lua_tostring(L, 1)) == NULL ||
__ntop_lua_handlefile(L, script_path, true))
return 0;
return 1;
@ -4341,7 +4343,7 @@ static const luaL_Reg ntop_interface_reg[] = {
{ "reloadL7Rules", ntop_reload_l7_rules },
{ "reloadShapers", ntop_reload_shapers },
{ NULL, NULL }
{ NULL, NULL }
};
/* **************************************************************** */
@ -4594,9 +4596,9 @@ int Lua::run_script(char *script_path, char *ifname) {
lua_pushstring(L, ifname);
lua_setglobal(L, "ifname");
}
if (strstr(script_path, "nv_graph"))
ntop->getTrace()->traceEvent(TRACE_NORMAL, "%s", script_path);
if(strstr(script_path, "nv_graph"))
ntop->getTrace()->traceEvent(TRACE_NORMAL, "%s", script_path);
#ifndef NTOPNG_PRO
rc = luaL_dofile(L, script_path);
@ -4717,7 +4719,7 @@ int Lua::handle_script_request(struct mg_connection *conn,
char *_equal = strchr(tok, '=');
if(_equal) {
char *decoded_buf, *equal, *ampercent;
char *equal, *ampercent;
int len;
_equal[0] = '\0';
@ -4728,6 +4730,8 @@ int Lua::handle_script_request(struct mg_connection *conn,
ampercent = strchr(_equal, '%'); if(ampercent != NULL) ampercent[0] = '\0';
if((equal = (char*)malloc(len+1)) != NULL) {
char *decoded_buf;
Utils::urlDecode(_equal, equal, len+1);
if((decoded_buf = http_decode(equal)) != NULL) {
@ -4787,13 +4791,15 @@ int Lua::handle_script_request(struct mg_connection *conn,
lua_newtable(L);
if((_cookies = (char*)mg_get_header(conn, "Cookie")) != NULL) {
char *cookies = strdup(_cookies);
char *tok, *val, *where;
char *tok, *where;
// ntop->getTrace()->traceEvent(TRACE_WARNING, "=> '%s'", cookies);
tok = strtok_r(cookies, "=", &where);
while(tok != NULL) {
while(tok[0] == ' ') tok++;
char *val;
while(tok[0] == ' ') tok++;
if((val = strtok_r(NULL, ";", &where)) != NULL) {
lua_push_str_table_entry(L, tok, val);
// ntop->getTrace()->traceEvent(TRACE_WARNING, "'%s'='%s'", tok, val);

View file

@ -83,7 +83,7 @@ void NdpiStats::lua(NetworkInterfaceView *iface, lua_State* vm) {
lua_newtable(vm);
list<NetworkInterface *>::iterator p;
for (p = iface->intfBegin() ; p != iface->intfEnd() ; p++) {
for(p = iface->intfBegin() ; p != iface->intfEnd() ; p++) {
for(int i=0; i<MAX_NDPI_PROTOS; i++)
if(counters[i] != NULL) {
char *name = (*p)->get_ndpi_proto_name(i);

View file

@ -65,6 +65,10 @@ NetworkInterface::NetworkInterface() {
else
pkt_dumper_tap = NULL;
has_mesh_networks_traffic = false,
pcap_datalink_type = 0, cpu_affinity = -1,
pkt_dumper = NULL, antenna_mac = NULL;
db = new DB(this);
#ifdef NTOPNG_PRO
@ -171,7 +175,6 @@ NetworkInterface::NetworkInterface(const char *name) {
if(ntop->getPrefs()->are_taps_enabled())
pkt_dumper_tap = new PacketDumperTuntap(this);
running = false, sprobe_interface = false, inline_interface = false;
db = new DB(this);
@ -499,6 +502,7 @@ static bool node_proto_guess_walker(GenericHashEntry *node, void *user_data) {
/* **************************************************** */
void NetworkInterface::dumpFlows() {
/* NOTUSED */
flows_hash->walk(node_proto_guess_walker, NULL);
}
@ -1788,7 +1792,7 @@ void NetworkInterface::getnDPIProtocols(lua_State *vm) {
for(i=0; i<(int)ndpi_struct->ndpi_num_supported_protocols; i++) {
char buf[8];
snprintf(buf, sizeof(buf), "%u", i);
snprintf(buf, sizeof(buf), "%d", i);
lua_push_str_table_entry(vm, ndpi_struct->proto_defaults[i].protoName, buf);
}
}

View file

@ -80,47 +80,6 @@ NetworkInterfaceView::~NetworkInterfaceView() {
/* **************************************************** */
/* FIXME: slow */
bool NetworkInterfaceView::hasNamesAs(const char *names) {
istringstream ss(names);
string ifname;
list<string> _names;
list<string> thisNames = list<string>(physNames.begin(), physNames.end());
list<string> res;
list<string>::iterator i;
while (std::getline(ss, ifname, ',')) _names.push_back(ifname);
set_difference(_names.begin(), _names.end(),
thisNames.begin(), thisNames.end(),
std::inserter(res, res.begin()));
return res.empty();
}
/* **************************************************** */
/* FIXME: slow */
bool NetworkInterfaceView::hasIdsAs(const char *names) {
istringstream ss(names);
stringstream idss;
string ifid;
list<string> _ids;
list<string> thisIds;
list<string> res;
list<NetworkInterface *>::iterator p;
while (std::getline(ss, ifid, ',')) _ids.push_back(ifid);
for(p = physIntf.begin() ; p != physIntf.end() ; p++) {
stringstream idss; idss << (*p)->get_id();
thisIds.push_back(idss.str());
}
set_difference(_ids.begin(), _ids.end(),
thisIds.begin(), thisIds.end(),
std::inserter(res, res.begin()));
return res.empty();
}
/* **************************************************** */
void NetworkInterfaceView::loadDumpPrefs() {
list<NetworkInterface *>::iterator p;
@ -514,10 +473,10 @@ void NetworkInterfaceView::getnDPIFlowsCount(lua_State *vm) {
int NetworkInterfaceView::getDumpTrafficMaxPktsPerFile(void) {
list<NetworkInterface *>::iterator p;
int max_pkts = 0, temp_num_pkts;
int max_pkts = 0;
for(p = physIntf.begin() ; p != physIntf.end() ; p++) {
temp_num_pkts = (*p)->getDumpTrafficMaxPktsPerFile();
int temp_num_pkts = (*p)->getDumpTrafficMaxPktsPerFile();
if (temp_num_pkts > max_pkts)
max_pkts = temp_num_pkts;
}

View file

@ -251,6 +251,8 @@ void Ntop::registerNagios(void) {
/* ******************************************* */
void Ntop::initRedis() {
if(redis) delete(redis);
redis = new Redis(prefs->get_redis_host(), prefs->get_redis_port(), prefs->get_redis_db_id());
}
@ -383,7 +385,7 @@ void Ntop::loadLocalInterfaceAddress() {
int l = strlen(buf);
strncpy(buf_orig, buf, bufsize);
snprintf(&buf[l], sizeof(buf)-l, "/%u", cidr);
snprintf(&buf[l], sizeof(buf)-l, "/%d", cidr);
ntop->getTrace()->traceEvent(TRACE_INFO, "Adding %s as IPv4 interface address", buf);
strncpy(buf2, buf, bufsize);
ptree_add_rule(local_interface_addresses, buf_orig);
@ -408,7 +410,7 @@ void Ntop::loadLocalInterfaceAddress() {
int l = strlen(buf);
strncpy(buf_orig, buf, bufsize);
snprintf(&buf[l], sizeof(buf)-l, "/%u", cidr);
snprintf(&buf[l], sizeof(buf)-l, "/%d", cidr);
ntop->getTrace()->traceEvent(TRACE_INFO, "Adding %s as IPv6 interface address for %s", buf, ifr.ifr_name);
strncpy(buf2, buf, bufsize);
ptree_add_rule(local_interface_addresses, buf_orig);
@ -601,9 +603,9 @@ bool Ntop::resetUserPassword(char *username, char *old_password, char *new_passw
/* ******************************************* */
bool Ntop::changeUserRole(char *username, char *usertype) const {
char key[64];
if(usertype != NULL) {
char key[64];
snprintf(key, sizeof(key), CONST_STR_USER_GROUP, username);
if(ntop->getRedis()->set(key, usertype, 0) < 0)
@ -616,9 +618,9 @@ bool Ntop::changeUserRole(char *username, char *usertype) const {
/* ******************************************* */
bool Ntop::changeAllowedNets(char *username, char *allowed_nets) const {
char key[64];
if(allowed_nets != NULL) {
char key[64];
snprintf(key, sizeof(key), CONST_STR_USER_NETS, username);
if(ntop->getRedis()->set(key, allowed_nets, 0) < 0)
@ -808,7 +810,7 @@ NetworkInterface* Ntop::getNetworkInterface(const char *name) {
int if_id = atoi(name);
char str[8];
snprintf(str, sizeof(str), "%u", if_id);
snprintf(str, sizeof(str), "%d", if_id);
if(strcmp(name, str) == 0) {
/* name is a number */
@ -949,6 +951,7 @@ NetworkInterfaceView* Ntop::getInterfaceView(char *name) {
/* ******************************************* */
/* NOTUSED */
int Ntop::getInterfaceIdByName(char *name) {
/* This method accepts both interface names or Ids */
int if_id = atoi(name);

View file

@ -26,7 +26,7 @@
PacketDumper::PacketDumper(NetworkInterface *i) {
char *name = i->get_name();
iface = i, file_id = 1;
iface = i, file_id = 1, sampling_rate = 1;
dump_end = 0, dumper = NULL, num_dumped_packets = 0;
if((name[0] == 'l') && (name[1] == 'o'))
@ -84,7 +84,7 @@ void PacketDumper::openDump(time_t when, int sampling_rate,
this->max_sec_per_file = iface->getDumpTrafficMaxSecPerFile();
when -= when % 3600; /* Hourly directories */
strftime(hour_path, sizeof(hour_path), "%Y/%m/%d/%H", localtime(&when));
snprintf(pcap_path, sizeof(pcap_path), "%s/%u/pcap/%s",
snprintf(pcap_path, sizeof(pcap_path), "%s/%d/pcap/%s",
ntop->get_working_dir(), iface->get_id(), hour_path);
ntop->fixPath(pcap_path);

View file

@ -191,6 +191,8 @@ int PacketDumperTuntap::readTap(unsigned char *buf, int len) {
return 0;
}
/* ********************************************* */
int PacketDumperTuntap::writeTap(unsigned char *buf, int len,
dump_reason reason, unsigned int sampling_rate) {
if(init_ok) {

View file

@ -28,9 +28,8 @@ ParserInterface::ParserInterface(const char *endpoint) : NetworkInterface(endpoi
/* **************************************************** */
u_int8_t ParserInterface::parse_flows(char *payload, int payload_size, u_int8_t source_id, void *data) {
json_object *o, *additional_o;
json_object *o;
ZMQ_Flow flow;
HistoricalInterface * iface = (HistoricalInterface*) data;
// payload[payload_size] = '\0';
@ -54,13 +53,13 @@ ParserInterface::ParserInterface(const char *endpoint) : NetworkInterface(endpoi
if((key != NULL) && (value != NULL)) {
u_int key_id;
json_object *additional_o = json_tokener_parse(value);
/* FIX: the key can either be numeric of a string */
key_id = atoi(key);
switch(key_id) {
case 0: //json additional object added by Flow::serialize()
additional_o = json_tokener_parse(value);
if( (additional_o != NULL) && (strcmp(key,"json") == 0) ) {
struct json_object_iterator additional_it = json_object_iter_begin(additional_o);
struct json_object_iterator additional_itEnd = json_object_iter_end(additional_o);
@ -213,8 +212,8 @@ ParserInterface::ParserInterface(const char *endpoint) : NetworkInterface(endpoi
ntop->getTrace()->traceEvent(TRACE_INFO, "Not handled ZMQ field %u", key_id);
json_object_object_add(flow.additional_fields, key, json_object_new_string(value));
break;
}
}
} /* switch */
} /* if */
/* Move to the next element */
json_object_iter_next(&it);

View file

@ -100,15 +100,3 @@ void RuntimePrefs::set_throughput_unit(bool use_bps) {
use_bps ? (char*)"bps" : (char*)"pps", 0);
}
/* ******************************************* */
bool RuntimePrefs::use_bps_as_set_throughput_unit() {
char rsp[32];
if(ntop->getRedis()->get((char*)CONST_RUNTIME_PREFS_THPT_CONTENT,
rsp, sizeof(rsp)) < 0) {
set_throughput_unit(true);
return(true);
} else
return((strcmp(rsp, "pps") == 0) ? true : false);
}

View file

@ -212,12 +212,14 @@ bool Utils::file_exists(const char *path) {
/* ****************************************************** */
bool Utils::mkdir_tree(char *path) {
int permission = 0777, rc;
int rc;
struct stat s;
ntop->fixPath(path);
if(stat(path, &s) != 0) {
int permission = 0777;
/* Start at 1 to skip the root */
for(int i=1; path[i] != '\0'; i++)
if(path[i] == CONST_PATH_SEP) {
@ -703,11 +705,12 @@ bool Utils::postHTTPJsonData(char *username, char *password, char *url, char *js
if(curl) {
CURLcode res;
struct curl_slist* headers = NULL;
char auth[64];
curl_easy_setopt(curl, CURLOPT_URL, url);
if(username || password) {
char auth[64];
snprintf(auth, sizeof(auth), "%s:%s",
username ? username : "",
password ? password : "");
@ -781,11 +784,13 @@ bool Utils::httpGet(lua_State* vm, char *url, char *username,
DownloadState *state = NULL;
long response_code;
char *content_type, *redirection;
char ua[64], auth[64];
char ua[64];
curl_easy_setopt(curl, CURLOPT_URL, url);
if(username || password) {
char auth[64];
snprintf(auth, sizeof(auth), "%s:%s",
username ? username : "",
password ? password : "");

View file

@ -139,8 +139,7 @@ int main(int argc, char *argv[])
continue;
/* [ zmq-collector.lua@tcp://127.0.0.1:5556 ] */
if(ifName && (strstr(ifName, "tcp://")
|| strstr(ifName, "ipc://"))
if((strstr(ifName, "tcp://") || strstr(ifName, "ipc://"))
) {
char *at = strchr(ifName, '@');
char *topic = (char*)"flow", *endpoint;

View file

@ -268,7 +268,6 @@ GeoBoxDimension geohash_dimensions_for_precision(int precision) {
GeoBoxDimension dimensions = {0.0, 0.0};
if(precision > 0) {
int lat_times_to_cut = precision * 5 / 2;
int lng_times_to_cut = precision * 5 / 2 + (precision % 2 ? 1 : 0);