Merge remote-tracking branch 'origin/develop' into ent-2076-ue-mejoras-en-gestion-de-politicas-desde-metaconsola

This commit is contained in:
daniel 2018-07-12 14:49:59 +02:00
commit 23ef9c8f53
58 changed files with 324 additions and 1162 deletions

View File

@ -58,7 +58,7 @@ PERL_PLUGIN_FILES="$PANDHOME_ENT/pandora_server/util/plugin/vmware-plugin.pl \
$PANDHOME_ENT/pandora_plugins/NGINX/nginx_requests_queued.pl \
$PANDHOME_ENT/pandora_plugins/Sybase/sybase_plugin.pl \
$PANDHOME_ENT/pandora_plugins/SNMP/dynamic_snmp.pl \
$PANDHOME_ENT/pandora_plugins/SNMP/snmp_bandwith.pl \
$PANDHOME_ENT/pandora_plugins/SNMP/snmp_bandwidth.pl \
$PANDHOME_ENT/pandora_plugins/laboratory/cacti/cacti2pandora.pl \
$PANDHOME_ENT/pandora_plugins/MarkLogic/pandora_marklogic.pl \
$PANDHOME_ENT/pandora_plugins/MySQL/pandora_mysql.pl \

View File

@ -1,5 +1,5 @@
package: pandorafms-agent-unix
Version: 7.0NG.724-180706
Version: 7.0NG.724-180712
Architecture: all
Priority: optional
Section: admin

View File

@ -14,7 +14,7 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
pandora_version="7.0NG.724-180706"
pandora_version="7.0NG.724-180712"
echo "Test if you has the tools for to make the packages."
whereis dpkg-deb | cut -d":" -f2 | grep dpkg-deb > /dev/null

View File

@ -42,7 +42,7 @@ my $Sem = undef;
my $ThreadSem = undef;
use constant AGENT_VERSION => '7.0NG.724';
use constant AGENT_BUILD => '180706';
use constant AGENT_BUILD => '180712';
# Agent log default file size maximum and instances
use constant DEFAULT_MAX_LOG_SIZE => 600000;

View File

@ -3,7 +3,7 @@
#
%define name pandorafms_agent_unix
%define version 7.0NG.724
%define release 180706
%define release 180712
Summary: Pandora FMS Linux agent, PERL version
Name: %{name}

View File

@ -3,7 +3,7 @@
#
%define name pandorafms_agent_unix
%define version 7.0NG.724
%define release 180706
%define release 180712
Summary: Pandora FMS Linux agent, PERL version
Name: %{name}

View File

@ -10,7 +10,7 @@
# **********************************************************************
PI_VERSION="7.0NG.724"
PI_BUILD="180706"
PI_BUILD="180712"
OS_NAME=`uname -s`
FORCE=0

View File

@ -186,7 +186,7 @@ UpgradeApplicationID
{}
Version
{180706}
{180712}
ViewReadme
{Yes}

View File

@ -30,7 +30,7 @@ using namespace Pandora;
using namespace Pandora_Strutils;
#define PATH_SIZE _MAX_PATH+1
#define PANDORA_VERSION ("7.0NG.724(Build 180706)")
#define PANDORA_VERSION ("7.0NG.724(Build 180712)")
string pandora_path;
string pandora_dir;

View File

@ -11,7 +11,7 @@ BEGIN
VALUE "LegalCopyright", "Artica ST"
VALUE "OriginalFilename", "PandoraAgent.exe"
VALUE "ProductName", "Pandora FMS Windows Agent"
VALUE "ProductVersion", "(7.0NG.724(Build 180706))"
VALUE "ProductVersion", "(7.0NG.724(Build 180712))"
VALUE "FileVersion", "1.0.0.0"
END
END

View File

@ -1,5 +1,5 @@
package: pandorafms-console
Version: 7.0NG.724-180706
Version: 7.0NG.724-180712
Architecture: all
Priority: optional
Section: admin

View File

@ -14,7 +14,7 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
pandora_version="7.0NG.724-180706"
pandora_version="7.0NG.724-180712"
package_pear=0
package_pandora=1

View File

@ -10,4 +10,8 @@ ALTER TABLE `tmetaconsole_agent` ADD COLUMN `cps` int NOT NULL DEFAULT '0';
ALTER TABLE `tagente_modulo` ADD COLUMN `cps` int NOT NULL DEFAULT '0';
ALTER TABLE `tservice` ADD COLUMN `evaluate_sla` int(1) NOT NULL DEFAULT '0';
ALTER TABLE `tpolicy_modules` ADD COLUMN `cps` int NOT NULL DEFAULT '0';
COMMIT;

View File

@ -1269,6 +1269,7 @@ UPDATE tagente SET tagente.alias = tagente.nombre;
ALTER TABLE `tservice` ADD COLUMN `quiet` tinyint(1) NOT NULL default 0;
ALTER TABLE `tservice` ADD COLUMN `cps` int NOT NULL default 0;
ALTER TABLE `tservice` ADD COLUMN `cascade_protection` tinyint(1) NOT NULL default 0;
ALTER TABLE `tservice` ADD COLUMN `evaluate_sla` int(1) NOT NULL default 0;
-- ---------------------------------------------------------------------
-- Table `tlayout`
@ -1353,6 +1354,7 @@ ALTER TABLE tlocal_component ADD COLUMN `dynamic_two_tailed` tinyint(1) unsigned
ALTER TABLE tpolicy_modules ADD COLUMN `ip_target`varchar(100) default '';
ALTER TABLE tpolicy_modules ADD COLUMN `dynamic_next` bigint(20) NOT NULL default '0';
ALTER TABLE tpolicy_modules ADD COLUMN `dynamic_two_tailed` tinyint(1) unsigned default '0';
ALTER TABLE `tpolicy_modules` ADD COLUMN `cps` int NOT NULL DEFAULT 0;
-- ---------------------------------------------------------------------
-- Table `tmetaconsole_agent`

View File

@ -119,9 +119,9 @@ $own_info = get_user_info ($config['id_user']);
echo "<td><b>".__('Group')."</b></td><td>";
if (check_acl ($config['id_user'], 0, "RW"))
echo html_print_select_groups($config['id_user'], 'RW', $display_all_group, 'graph_id_group', $id_group, '', '', '', true);
echo html_print_select_groups($config['id_user'], 'RW', true, 'graph_id_group', $id_group, '', '', '', true);
elseif (check_acl ($config['id_user'], 0, "RM"))
echo html_print_select_groups($config['id_user'], 'RM', $display_all_group, 'graph_id_group', $id_group, '', '', '', true);
echo html_print_select_groups($config['id_user'], 'RM', true, 'graph_id_group', $id_group, '', '', '', true);
echo "</td></tr>";
echo "<tr>";
echo "<td class='datos2'><b>".__('Description')."</b></td>";

View File

@ -67,12 +67,11 @@ $table->data['name'][1] = html_print_input_text('name', $reportName,
__('Name'), 80, 100, true, false, true);
$table->data['group'][0] = __('Group');
$display_all_group = (users_is_admin() || users_can_manage_group_all("AR"));
$write_groups = users_get_groups_for_select(false, "AR", $display_all_group, true, false, 'id_grupo');
$write_groups = users_get_groups_for_select(false, "AR", true, true, false, 'id_grupo');
html_print_select_groups($config['id_user'], "AR",
$display_all_group, 'id_group', $idGroup, '', '', '', true);
true, 'id_group', $idGroup, '', '', '', true);
// If the report group is not among the RW groups (special permission) we add it

View File

@ -127,12 +127,9 @@ else {
$table->data[1][0] = __('Group:');
// Only display group "All" if user is administrator
// or has "RW" privileges
$display_all_group = (users_is_admin() || users_can_manage_group_all("RW"));
$table->data[1][1] = html_print_select_groups($config['id_user'], "RW",
$display_all_group, 'id_group', $idGroup, '', '', '', true);
true, 'id_group', $idGroup, '', '', '', true);
$backgrounds_list = list_files(
$config['homedir'] . '/images/console/background/', "jpg", 1, 0);
$backgrounds_list = array_merge($backgrounds_list,

View File

@ -22,7 +22,7 @@
/**
* Pandora build version and version
*/
$build_version = 'PC180706';
$build_version = 'PC180712';
$pandora_version = 'v7.0NG.724';
// Do not overwrite default timezone set if defined.

View File

@ -3118,29 +3118,25 @@ function series_type_graph_array($data, $show_elements_graph){
}
}
if(($show_elements_graph['fullscale'] ||
$show_elements_graph['type_mode_graph'] ) &&
strpos($key, 'baseline') === false ){
$data_return['legend'][$key] .=
__('Min:') . remove_right_zeros(
number_format(
$value['min'],
$config['graph_precision']
)
) . ' ' .
__('Max:') . remove_right_zeros(
number_format(
$value['max'],
$config['graph_precision']
)
) . ' ' .
_('Avg:') . remove_right_zeros(
number_format(
$value['avg'],
$config['graph_precision']
)
) . ' ' . $str;
}
$data_return['legend'][$key] .=
__('Min:') . remove_right_zeros(
number_format(
$value['min'],
$config['graph_precision']
)
) . ' ' .
__('Max:') . remove_right_zeros(
number_format(
$value['max'],
$config['graph_precision']
)
) . ' ' .
_('Avg:') . remove_right_zeros(
number_format(
$value['avg'],
$config['graph_precision']
)
) . ' ' . $str;
if($show_elements_graph['compare'] == 'overlapped' && $key == 'sum2'){
$data_return['color'][$key] = $color_series['overlapped'];

View File

@ -10345,10 +10345,11 @@ function api_set_create_special_day($thrash1, $thrash2, $other, $thrash3) {
*
* @param $thrash1 Don't use.
* @param $thrash2 Don't use.
* @param array $other it's array, $other as param is <description>;<id_group>;<critical>;
* @param array $other it's array, $other as param is <description>;<id_group>;<critical>;
* <warning>;<id_agent>;<sla_interval>;<sla_limit>;<id_warning_module_template_alert>;
* <id_critical_module_template_alert>;<id_critical_module_sla_template_alert>;
* in this order and separator char (after text ; ) and separator
* <id_critical_module_template_alert>;<id_critical_module_sla_template_alert>;<quiet>;
* <cascade_protection>;<evaluate_sla>;
* in this order and separator char (after text ; ) and separator
* (pass in param othermode as othermode=url_encode_separator_<separator>)
* @param $thrash3 Don't use
*
@ -10376,6 +10377,7 @@ function api_set_create_service($thrash1, $thrash2, $other, $thrash3) {
$id_critical_module_sla = $other['data'][10];
$quiet = $other['data'][11];
$cascade_protection = $other['data'][12];
$evaluate_sla = $other['data'][13];
if(empty($name)){
returnError('error_create_service', __('Error in creation service. No name'));
@ -10425,6 +10427,9 @@ function api_set_create_service($thrash1, $thrash2, $other, $thrash3) {
if(empty($cascade_protection)){
$cascade_protection = 0;
}
if(empty($evaluate_sla)){
$evaluate_sla = 0;
}
$result = services_create_service (
$name, $description, $id_group,
@ -10432,7 +10437,7 @@ function api_set_create_service($thrash1, $thrash2, $other, $thrash3) {
$mode, $id_agent, $sla_interval, $sla_limit,
$id_warning_module_template, $id_critical_module_template,
$id_unknown_module_template, $id_critical_module_sla,
$quiet, $cascade_protection
$quiet, $cascade_protection, $evaluate_sla
);
if($result){
@ -10447,10 +10452,11 @@ function api_set_create_service($thrash1, $thrash2, $other, $thrash3) {
*
* @param $thrash1 service id.
* @param $thrash2 Don't use.
* @param array $other it's array, $other as param is <name>;<description>;<id_group>;<critical>;
* @param array $other it's array, $other as param is <name>;<description>;<id_group>;<critical>;
* <warning>;<id_agent>;<sla_interval>;<sla_limit>;<id_warning_module_template_alert>;
* <id_critical_module_template_alert>;<id_critical_module_sla_template_alert>;
* in this order and separator char (after text ; ) and separator
* <id_critical_module_template_alert>;<id_critical_module_sla_template_alert>;<quiet>;
* <cascade_protection>;<evaluate_sla>;
* in this order and separator char (after text ; ) and separator
* (pass in param othermode as othermode=url_encode_separator_<separator>)
* @param $thrash3 Don't use
*
@ -10548,6 +10554,11 @@ function api_set_update_service($thrash1, $thrash2, $other, $thrash3) {
$cascade_protection = $service['cascade_protection'];
}
$evaluate_sla = $other['data'][13];
if(empty($evaluate_sla)){
$evaluate_sla = $service['evaluate_sla'];
}
$result = services_update_service (
$id_service, $name,$description, $id_group,
$critical, $warning, SECONDS_5MINUTES, $mode,
@ -10556,7 +10567,8 @@ function api_set_update_service($thrash1, $thrash2, $other, $thrash3) {
$id_critical_module_template,
$id_unknown_module_template,
$id_critical_module_sla,
$quiet, $cascade_protection
$quiet, $cascade_protection,
$evaluate_sla
);
if($result){
@ -10571,10 +10583,10 @@ function api_set_update_service($thrash1, $thrash2, $other, $thrash3) {
*
* @param $thrash1 service id.
* @param $thrash2 Don't use.
* @param array $other it's a json, $other as param is <description>;<id_group>;<critical>;
* @param array $other it's a json, $other as param is <description>;<id_group>;<critical>;
* <warning>;<id_agent>;<sla_interval>;<sla_limit>;<id_warning_module_template_alert>;
* <id_critical_module_template_alert>;<id_critical_module_sla_template_alert>;
* in this order and separator char (after text ; ) and separator
* <id_critical_module_template_alert>;<id_critical_module_sla_template_alert>;
* in this order and separator char (after text ; ) and separator
* (pass in param othermode as othermode=url_encode_separator_<separator>)
* @param $thrash3 Don't use
*
@ -10590,7 +10602,7 @@ function api_set_add_element_service($thrash1, $thrash2, $other, $thrash3) {
if (is_metaconsole()) return;
$id = $thrash1;
if(empty($id)){
returnError('error_add_service_element', __('Error adding elements to service. No service id'));
return;
@ -10619,7 +10631,7 @@ function api_set_add_element_service($thrash1, $thrash2, $other, $thrash3) {
continue;
}
break;
case 'module':
$agent_id = 0;
$id_service_child = 0;
@ -10628,7 +10640,7 @@ function api_set_add_element_service($thrash1, $thrash2, $other, $thrash3) {
continue;
}
break;
case 'service':
$agent_id = 0;
$id_agente_modulo = 0;
@ -10641,7 +10653,7 @@ function api_set_add_element_service($thrash1, $thrash2, $other, $thrash3) {
}
break;
}
$values = array(
'id_agente_modulo' => $id_agente_modulo,
'description' => $element['description'],
@ -10653,20 +10665,20 @@ function api_set_add_element_service($thrash1, $thrash2, $other, $thrash3) {
'id_agent' => $agent_id,
'id_service_child' => $id_service_child,
'id_server_meta' => 0);
$result = db_process_sql_insert('tservice_element',$values);
if($result && !$results){
$results = $result;
}
}
}
if($results){
returnData('string', array('type' => 'string', 'data' => 1));
} else {
returnError('error_add_service_element', __('Error adding elements to service'));
}
}
/**
* Update a special day. And return a message with the result of the operation.

View File

@ -264,7 +264,9 @@ function grafico_modulo_sparse_data_chart (
$data_module_graph['id_module_type'] == 18 ||
$data_module_graph['id_module_type'] == 9 ||
$data_module_graph['id_module_type'] == 31 ||
$data_module_graph['id_module_type'] == 100 ){
$data_module_graph['id_module_type'] == 100 ||
$params['baseline'] || $params['projection']
){
$data = db_get_all_rows_filter (
'tagente_datos',
@ -419,8 +421,8 @@ function grafico_modulo_sparse_data(
$data_module_graph['id_module_type'] == 18 ||
$data_module_graph['id_module_type'] == 9 ||
$data_module_graph['id_module_type'] == 31 ||
$data_module_graph['id_module_type'] == 100 ){
html_debug_prinbt('entra');
$data_module_graph['id_module_type'] == 100 ||
$params['projection'] ){
$array_data = grafico_modulo_sparse_data_chart (
$agent_module_id,
$date_array,
@ -898,6 +900,10 @@ function grafico_modulo_sparse ($params) {
$params['type_mode_graph'] = $config['type_mode_graph'];
}
if(!isset($params['projection'])){
$params['projection'] = false;
}
//XXXX Configurable
$params['grid_color'] = '#C1C1C1';
$params['legend_color'] = '#636363';
@ -1213,6 +1219,7 @@ function graphic_combined_module (
}
else{
$params['stacked'] = 'area';
$params['projection'] = $params_combined['projection'];
}
if(!isset($params_combined['labels'])){
@ -4084,21 +4091,32 @@ function fullscale_data (
$data["sum" . $series_suffix]['data'][] = array($real_date , $sum_data/$count_data);
if($type_mode_graph && !$params['baseline']){
$data["min" . $series_suffix]['data'][] = array($real_date , $min_value);
$data["max" . $series_suffix]['data'][] = array($real_date , $max_value);
if($min_value != PHP_INT_MAX) {
$data["min" . $series_suffix]['data'][] = array($real_date , $min_value);
}
if($max_value != -PHP_INT_MAX) {
$data["max" . $series_suffix]['data'][] = array($real_date , $max_value);
}
}
else{
$data["sum" . $series_suffix]['slice_data'][$real_date]['min'] = $min_value;
if($min_value != PHP_INT_MAX) {
$data["sum" . $series_suffix]['slice_data'][$real_date]['min'] = $min_value;
}
$data["sum" . $series_suffix]['slice_data'][$real_date]['avg'] = $sum_data/$count_data;
$data["sum" . $series_suffix]['slice_data'][$real_date]['max'] = $max_value;
if($max_value != -PHP_INT_MAX) {
$data["sum" . $series_suffix]['slice_data'][$real_date]['max'] = $max_value;
}
}
//max_total
if($max_value >= $max_value_total){
if($max_value >= $max_value_total && $max_value != -PHP_INT_MAX){
$max_value_total = $max_value;
}
//min_total
if($min_value <= $min_value_total){
if($min_value <= $min_value_total && $min_value != PHP_INT_MAX){
$min_value_total = $min_value;
}
//avg sum_total
@ -4110,27 +4128,31 @@ function fullscale_data (
if($type_mode_graph && !$params['baseline']){
/*MIN*/
//max_min
if($min_value >= $min_value_max){
if($min_value >= $min_value_max && $min_value != PHP_INT_MAX){
$min_value_max = $min_value;
}
//min_min
if($min_value <= $min_value_min){
if($min_value <= $min_value_min && $min_value != PHP_INT_MAX){
$min_value_min = $min_value;
}
//avg sum_min
$sum_data_min += $min_value;
if ($min_value != PHP_INT_MAX) {
$sum_data_min += $min_value;
}
/*MAX*/
//max_max
if($max_value >= $max_value_max){
if($max_value >= $max_value_max && $max_value != -PHP_INT_MAX){
$max_value_max = $max_value;
}
//min_max
if($max_value <= $max_value_min){
if($max_value <= $max_value_min && $max_value != -PHP_INT_MAX){
$max_value_min = $max_value;
}
//avg sum_max
$sum_data_max += $max_value;
if ($max_value != -PHP_INT_MAX) {
$sum_data_max += $max_value;
}
/*AVG*/
//max_max

View File

@ -1685,17 +1685,22 @@ function modules_get_previous_data ($id_agent_module, $utimestamp = 0, $string =
$table = 'tagente_datos';
}
$sql = sprintf ('SELECT *
FROM ' . $table . '
WHERE id_agente_modulo = %d
AND utimestamp <= %d
ORDER BY utimestamp DESC',
$id_agent_module, $utimestamp,
$utimestamp - SECONDS_2DAY
$sql = sprintf (
"SELECT * FROM %s
WHERE id_agente_modulo = %d
AND utimestamp = ( SELECT max(utimestamp)
FROM tagente_datos
WHERE id_agente_modulo = %d
AND utimestamp <= %d )",
$table,
$id_agent_module,
$id_agent_module,
$utimestamp
);
$search_in_history_db = db_search_in_history_db($utimestamp);
return db_get_row_sql ($sql, $search_in_history_db);
return db_get_row_sql($sql, $search_in_history_db);
}
/**

View File

@ -2026,13 +2026,13 @@ function pandoraFlotArea( graph_id, values, legend,
avg_bigger = "";
}
data_legend[index] =
data_legend[index] =
' Min: ' + (short_data ? number_format(min_y, 0, "", short_data) : parseFloat(min_y)) + min_bigger
+ ' Max: ' + (short_data ? number_format(max_y, 0, "", short_data) : parseFloat(max_y)) + max_bigger
+ ' Avg: ' + (short_data ? number_format(avg_y, 0, "", short_data) : parseFloat(avg_y)) + avg_bigger;
});
var label_aux = legend[series.label] + data_legend[series.label];
var label_aux = legend[series.label].split(":")[0] + data_legend[series.label];
$('#legend_' + graph_id + ' .legendLabel').eq(i).html(label_aux);
}
}

View File

@ -90,6 +90,7 @@ Apart from the defined module macros, the following macros are also available:
<li>_plugin_parameters_: Module plugin parameters.</li>
<li>_policy_: Name of the policy that the module belongs to (if applies).</li>
<li>_prevdata_: Module previous data before the alert has been triggered.</li>
<li>_rca_: Root cause analysis chain (only for services).</li>
<li>_server_ip_: Ip of server assigned to agent. </li>
<li>_server_name_: Name of server assigned to agent. </li>
<li>_target_ip_: IP address for the modules target.</li>

View File

@ -75,6 +75,7 @@ Besides the defined module macros, the following macros are available:
<li>_plugin_parameters_: Module plugin parameters.</li>
<li>_policy_: Name of the policy that the module belongs to (if applies).</li>
<li>_prevdata_: Module previous data before the alert has been triggered.</li>
<li>_rca_: Root cause analysis chain (only for services).</li>
<li>_server_ip_: Ip of server assigned to agent. </li>
<li>_server_name_: Name of server assigned to agent. </li>
<li>_target_ip_: IP address for the modules target.</li>

View File

@ -92,6 +92,7 @@ Además de las macros de módulo definidas, las siguientes macros están disponi
<li>_plugin_parameters_: Parámetros del plugin del módulo.</li>
<li>_policy_: Nombre de la política a la que pertenece el módulo (si aplica).</li>
<li>_prevdata_: Dato previo antes de disparase la alerta.</li>
<li>_rca_: Cadena de análasis de causa raíz (sólo para servicios).</li>
<li>_server_ip_: Ip del servidor al que el agente está asignado. </li>
<li>_server_name_: Nombre del servidor al que el agente está asignado. </li>
<li>_target_ip_: Dirección IP del objetivo del módulo.</li>

View File

@ -75,6 +75,7 @@ Además de las macros de módulo definidas, las siguientes macros están disponi
<li>_plugin_parameters_: Parámetros del plugin del módulo.</li>
<li>_policy_: Nombre de la política a la que pertenece el módulo (si aplica).</li>
<li>_prevdata_: Dato previo antes de disparase la alerta.</li>
<li>_rca_: Cadena de análasis de causa raíz (sólo para servicios).</li>
<li>_server_ip_: Ip del servidor al que el agente está asignado. </li>
<li>_server_name_: Nombre del servidor al que el agente está asignado. </li>
<li>_target_ip_: Dirección IP del objetivo del módulo.</li>

View File

@ -91,6 +91,7 @@ email アクションを設定するには、_field1_ (送信先アドレス)、
<li>_plugin_parameters_ : モジュールのプラグインパラメータ</li>
<li>_policy_ : モジュールが属するポリシー名 (存在する場合)</li>
<li>_prevdata_ : アラートを発報する前のモジュールデータ</li>
<li>_rca_: Root cause analysis chain (only for services).</li>
<li>_server_ip_ : エージェントが割り当てられているサーバ IP。</li>
<li>_server_name_ : エージェントが割り当てられているサーバ名。 </li>
<li>_target_ip_ : モジュールの対象IPアドレス</li>

View File

@ -75,6 +75,7 @@
<li>_plugin_parameters_ : モジュールのプラグインパラメータ</li>
<li>_policy_ : モジュールが属するポリシー名 (存在する場合)</li>
<li>_prevdata_ : アラートを発報する前のモジュールデータ</li>
<li>_rca_: Root cause analysis chain (only for services).</li>
<li>_server_ip_ : エージェントが割り当てられているサーバ IP。</li>
<li>_server_name_ : エージェントが割り当てられているサーバ名。 </li>
<li>_target_ip_ : モジュールの対象IPアドレス</li>

View File

@ -71,7 +71,7 @@
<div style='height: 10px'>
<?php
$version = '7.0NG.724';
$build = '180706';
$build = '180712';
$banner = "v$version Build $build";
error_reporting(0);

View File

@ -244,7 +244,7 @@ if (empty($export_btn) || $show_form) {
$groups = users_get_groups ($config['id_user'], "RR", users_can_manage_group_all());
$table->data[0][1] = html_print_select_groups($config['id_user'],
"RR", users_can_manage_group_all(), "group", $group, '', '', 0, true, false, true,
"RR", true, "group", $group, '', '', 0, true, false, true,
'', false);
//Agent selector

View File

@ -223,13 +223,9 @@ else {
100,true);
$table->data[1][0] = __('Group');
// Only display group "All" if user is administrator
// or has "AR" privileges
$display_all_group = (users_is_admin() || users_can_manage_group_all("AR"));
$table->data[1][1] = html_print_select_groups($config['id_user'], "AR",
$display_all_group, 'id_group', $idGroup, '', '', '', true);
true, 'id_group', $idGroup, '', '', '', true);
$table->data[2][0] = __('Node radius');
$table->data[2][1] = html_print_input_text ('node_radius', $node_radius, '', 2,

View File

@ -3,7 +3,7 @@
#
%define name pandorafms_console
%define version 7.0NG.724
%define release 180706
%define release 180712
# User and Group under which Apache is running
%define httpd_name httpd

View File

@ -3,7 +3,7 @@
#
%define name pandorafms_console
%define version 7.0NG.724
%define release 180706
%define release 180712
%define httpd_name httpd
# User and Group under which Apache is running
%define httpd_name apache2

View File

@ -2158,6 +2158,7 @@ CREATE TABLE IF NOT EXISTS `tpolicy_modules` (
`prediction_sample_window` int(10) default 0,
`prediction_samples` int(4) default 0,
`prediction_threshold` int(4) default 0,
`cps` int NOT NULL DEFAULT 0,
PRIMARY KEY (`id`),
KEY `main_idx` (`id_policy`),
UNIQUE (`id_policy`, `name`)
@ -2429,6 +2430,7 @@ CREATE TABLE IF NOT EXISTS `tservice` (
`quiet` tinyint(1) NOT NULL default 0,
`cps` int NOT NULL default 0,
`cascade_protection` tinyint(1) NOT NULL default 0,
`evaluate_sla` int(1) NOT NULL default 0,
PRIMARY KEY (`id`)
) ENGINE=InnoDB
COMMENT = 'Table to define services to monitor'

View File

@ -1,10 +1,10 @@
package: pandorafms-server
Version: 7.0NG.724-180706
Version: 7.0NG.724-180712
Architecture: all
Priority: optional
Section: admin
Installed-Size: 640
Maintainer: Miguel de Dios <miguel.dedios@artica.es>
Homepage: http://pandorafms.org/
Depends: perl (>= 5.8), libdbi-perl, libdbd-mysql-perl, libtime-format-perl, libnetaddr-ip-perl, libtime-format-perl, libxml-simple-perl, libxml-twig-perl, libhtml-parser-perl, snmp, snmpd, traceroute, xprobe2, nmap, sudo, libwww-perl, libsocket6-perl, libio-socket-inet6-perl, snmp-mibs-downloader, libjson-perl, libnet-telnet-perl, libencode-locale-perl
Depends: perl (>= 5.8), libdbi-perl, libdbd-mysql-perl, libtime-format-perl, libnetaddr-ip-perl, libtime-format-perl, libxml-simple-perl, libxml-twig-perl, libhtml-parser-perl, snmp, snmpd, traceroute, xprobe2, nmap, sudo, libwww-perl, libsocket6-perl, libio-socket-inet6-perl, snmp-mibs-downloader, libjson-perl, libnet-telnet-perl, libencode-locale-perl, libgeo-ip-perl
Description: Pandora FMS is a monitoring system for big IT environments. It uses remote tests, or local agents to grab information. Pandora supports all standard OS (Linux, AIX, HP-UX, Solaris and Windows XP,2000/2003), and support multiple setups in HA enviroments. This is the server package. Server makes the remote checks and process information transfer by Pandora FMS agents to the server.

View File

@ -14,7 +14,7 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
pandora_version="7.0NG.724-180706"
pandora_version="7.0NG.724-180712"
package_cpan=0
package_pandora=1

View File

@ -330,18 +330,9 @@ restart_delay 60
#location_error 50
# Recon reverse geolocation mode [disabled, sql, file]
# disabled The recon task doesn't try to geolocate the ip discovered.
# sql The recon task trys to query the SQL database to geolocate the
# ip discovered
# file The recon task trys to find the geolocation information of the
# ip discovered in the file indicated in the
# recon_reverse_geolocation_file parameter
# recon_reverse_geolocation_mode disabled
# Recon reverse geolocation file. This is the database with the reverse
# geolocation information using MaxMind GPL GeoLiteCity.dat format).
# Comment it to disable the IP geolocation on agent creation.
#recon_reverse_geolocation_file /usr/local/share/GeoIP/GeoIPCity.dat

View File

@ -31,6 +31,7 @@ WriteMakefile(
HTML::Entities => 0,
IO::Socket::INET6 => 0,
JSON => 0,
Geo::IP => 0,
},
EXE_FILES => [ @exe_files ],
PMLIBDIRS => [ 'lib' ],

View File

@ -325,18 +325,9 @@ restart_delay 60
#location_error 50
# Recon reverse geolocation mode [disabled, sql, file]
# disabled The recon task doesn't try to geolocate the ip discovered.
# sql The recon task trys to query the SQL database to geolocate the
# ip discovered
# file The recon task trys to find the geolocation information of the
# ip discovered in the file indicated in the
# recon_reverse_geolocation_file parameter
# recon_reverse_geolocation_mode disabled
# Recon reverse geolocation file. This is the database with the reverse
# geolocation information using MaxMind GPL GeoLiteCity.dat format).
# Comment it to disable the IP geolocation on agent creation.
#recon_reverse_geolocation_file /usr/local/share/GeoIP/GeoIPCity.dat

View File

@ -342,18 +342,9 @@ restart_delay 60
#location_error 50
# Recon reverse geolocation mode [disabled, sql, file]
# disabled The recon task doesn't try to geolocate the ip discovered.
# sql The recon task trys to query the SQL database to geolocate the
# ip discovered
# file The recon task trys to find the geolocation information of the
# ip discovered in the file indicated in the
# recon_reverse_geolocation_file parameter
# recon_reverse_geolocation_mode disabled
# Recon reverse geolocation file. This is the database with the reverse
# geolocation information using MaxMind GPL GeoLiteCity.dat format).
# Comment it to disable the IP geolocation on agent creation.
#recon_reverse_geolocation_file /usr/local/share/GeoIP/GeoIPCity.dat

View File

@ -301,18 +301,9 @@ restart_delay 60
#location_error 50
# Recon reverse geolocation mode [disabled, sql, file]
# disabled The recon task doesn't try to geolocate the ip discovered.
# sql The recon task trys to query the SQL database to geolocate the
# ip discovered
# file The recon task trys to find the geolocation information of the
# ip discovered in the file indicated in the
# recon_reverse_geolocation_file parameter
# recon_reverse_geolocation_mode disabled
# Recon reverse geolocation file. This is the database with the reverse
# geolocation information using MaxMind GPL GeoLiteCity.dat format).
# Comment it to disable the IP geolocation on agent creation.
#recon_reverse_geolocation_file /usr/local/share/GeoIP/GeoIPCity.dat

View File

@ -45,7 +45,7 @@ our @EXPORT = qw(
# version: Defines actual version of Pandora Server for this module only
my $pandora_version = "7.0NG.724";
my $pandora_build = "180706";
my $pandora_build = "180712";
our $VERSION = $pandora_version." ".$pandora_build;
# Setup hash
@ -266,8 +266,7 @@ sub pandora_load_config {
$pa_config->{"web_engine"} = 'lwp'; # 5.1
$pa_config->{"activate_gis"} = 0; # 3.1
$pa_config->{"location_error"} = 50; # 3.1
$pa_config->{"recon_reverse_geolocation_mode"} = 'disabled'; # 3.1
$pa_config->{"recon_reverse_geolocation_file"} = '/usr/local/share/GeoIP/GeoIPCity.dat'; # 3.1
$pa_config->{"recon_reverse_geolocation_file"} = ''; # 3.1
$pa_config->{"recon_location_scatter_radius"} = 50; # 3.1
$pa_config->{"update_parent"} = 0; # 3.1
$pa_config->{"google_maps_description"} = 0;
@ -863,12 +862,13 @@ sub pandora_load_config {
}
elsif ($parametro =~ m/^location_error\s+(\d+)/i) {
$pa_config->{'location_error'} = clean_blank($1);
}
elsif ($parametro =~ m/^recon_reverse_geolocation_mode\s+(\w+)/i) {
$pa_config->{'recon_reverse_geolocation_mode'} = clean_blank($1);
} #FIXME: Find a better regexp to validate the path
elsif ($parametro =~ m/^recon_reverse_geolocation_file\s+(.*)/i) {
$pa_config->{'recon_reverse_geolocation_file'} = clean_blank($1);
if ( ! -r $pa_config->{'recon_reverse_geolocation_file'} ) {
print "[WARN] Invalid recon_reverse_geolocation_file.\n";
$pa_config->{'recon_reverse_geolocation_file'} = '';
}
}
elsif ($parametro =~ m/^recon_location_scatter_radius\s+(\d+)/i) {
$pa_config->{'recon_location_scatter_radius'} = clean_blank($1);

View File

@ -352,16 +352,6 @@ sub pandora_generate_alerts ($$$$$$$$;$$$) {
return;
}
if ($agent->{'cps'} > 0) {
logger($pa_config, "Generate Alert. The agent '" . $agent->{'nombre'} . "' is in quiet mode by cascade protection services.", 10);
return;
}
if ($module->{'cps'} > 0) {
logger($pa_config, "Generate Alert. The module '" . $module->{'nombre'} . "' is in quiet mode by cascade protection services.", 10);
return;
}
# Do not generate alerts for disabled groups
if (is_group_disabled ($dbh, $agent->{'id_grupo'})) {
return;
@ -1649,7 +1639,7 @@ sub pandora_process_module ($$$$$$$$$;$) {
}
# Generate alerts
if (pandora_inhibit_alerts ($pa_config, $agent, $dbh, 0) == 0) {
if (pandora_inhibit_alerts ($pa_config, $agent, $dbh, 0) == 0 && pandora_cps_enabled($agent, $module) == 0) {
pandora_generate_alerts ($pa_config, $processed_data, $status, $agent, $module, $utimestamp, $dbh, $timestamp, $extra_macros, $last_data_value);
}
else {
@ -3140,11 +3130,6 @@ sub pandora_event ($$$$$$$$$$;$$$$$$$$$) {
logger($pa_config, "Generate Event. The agent '" . $agent->{'nombre'} . "' is in quiet mode.", 10);
return;
}
if (defined ($agent) && $agent->{'cps'} > 0) {
logger($pa_config, "Generate Event. The agent '" . $agent->{'nombre'} . "' is in quiet mode by cascade protection services.", 10);
return;
}
}
my $module = undef;
@ -3154,11 +3139,6 @@ sub pandora_event ($$$$$$$$$$;$$$$$$$$$) {
logger($pa_config, "Generate Event. The module '" . $module->{'nombre'} . "' is in quiet mode.", 10);
return;
}
if (defined ($module) && $module->{'cps'} > 0) {
logger($pa_config, "Generate Event. The module '" . $module->{'nombre'} . "' is in quiet mode by cascade protection services.", 10);
return;
}
}
# Get module tags
@ -4289,6 +4269,20 @@ sub pandora_inhibit_alerts {
return pandora_inhibit_alerts ($pa_config, $agent, $dbh, $depth + 1);
}
##########################################################################
# Returns 1 if service cascade protection is enabled for the given
# agent/module, 0 otherwise.
##########################################################################
sub pandora_cps_enabled($$) {
my ($agent, $module) = @_;
return 1 if ($agent->{'cps'} > 0);
return 1 if ($module->{'cps'} > 0);
return 0;
}
##########################################################################
=head2 C<< save_agent_position (I<$pa_config>, I<$current_longitude>, I<$current_latitude>,
I<$current_altitude>, I<$agent_id>, I<$dbh>, [I<$start_timestamp>], [I<$description>]) >>
@ -4925,7 +4919,7 @@ sub pandora_module_unknown ($$) {
pandora_mark_agent_for_module_update ($dbh, $module->{'id_agente'});
# Generate alerts
if (pandora_inhibit_alerts ($pa_config, $agent, $dbh, 0) == 0) {
if (pandora_inhibit_alerts ($pa_config, $agent, $dbh, 0) == 0 && pandora_cps_enabled($agent, $module) == 0) {
pandora_generate_alerts ($pa_config, 0, 3, $agent, $module, time (), $dbh, undef, undef, 0, 'unknown');
}
else {
@ -4969,7 +4963,7 @@ sub pandora_module_unknown ($$) {
pandora_mark_agent_for_module_update ($dbh, $module->{'id_agente'});
# Generate alerts
if (pandora_inhibit_alerts ($pa_config, $agent, $dbh, 0) == 0) {
if (pandora_inhibit_alerts ($pa_config, $agent, $dbh, 0) == 0 && pandora_cps_enabled($agent, $module) == 0) {
pandora_generate_alerts ($pa_config, 0, 3, $agent, $module, time (), $dbh, undef, undef, 0, 'unknown');
}
else {

View File

@ -39,6 +39,7 @@ use PandoraFMS::Tools;
use PandoraFMS::DB;
use PandoraFMS::Core;
use PandoraFMS::ProducerConsumerServer;
use PandoraFMS::GIS;
# Inherits from PandoraFMS::ProducerConsumerServer
our @ISA = qw(PandoraFMS::ProducerConsumerServer);
@ -362,10 +363,13 @@ sub process_xml_data ($$$$$) {
my $description = '';
$description = $data->{'description'} if (defined ($data->{'description'}));
my $alias = (defined ($data->{'agent_alias'}) && $data->{'agent_alias'} ne '') ? $data->{'agent_alias'} : $data->{'agent_name'};
$agent_id = pandora_create_agent($pa_config, $pa_config->{'servername'}, $agent_name, $address, $group_id, $parent_id, $os,
$description, $interval, $dbh, $timezone_offset, undef, undef, undef, undef, $custom_id, $url_address, $agent_mode, $alias);
my $location = get_geoip_info($pa_config, $address);
$agent_id = pandora_create_agent($pa_config, $pa_config->{'servername'}, $agent_name, $address,
$group_id, $parent_id, $os,
$description, $interval, $dbh, $timezone_offset,
$location->{'longitude'}, $location->{'latitude'}, undef, undef,
$custom_id, $url_address, $agent_mode, $alias
);
if (! defined ($agent_id)) {
return;
}

View File

@ -40,11 +40,7 @@ Exported Functions:
=item * C<distance_moved>
=item * C<get_reverse_geoip_sql>
=item * C<get_reverse_geoip_file>
=item * C<get_random_close_point>
=item * C<get_geoip_info>
=back
@ -54,15 +50,13 @@ Exported Functions:
use strict;
use warnings;
use Geo::IP;
# Default lib dir for RPM and DEB packages
use lib '/usr/lib/perl5';
use PandoraFMS::DB;
use PandoraFMS::Tools;
# TODO:Test if is instaled
my $geoIPPurePerlavilable= (eval 'use PandoraFMS::GeoIP; 1') ? 1 : 0;
require Exporter;
@ -72,9 +66,7 @@ our %EXPORT_TAGS = ( 'all' => [ qw( ) ] );
our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );
our @EXPORT = qw(
distance_moved
get_reverse_geoip_sql
get_reverse_geoip_file
get_random_close_point
get_geoip_info
);
# Some intenrnal constants
@ -137,84 +129,43 @@ sub distance_moved ($$$$$$$) {
}
##########################################################################
=head2 C<< get_revesrse_geoip_sql (I<$pa_config>, I<$ip_addr>, I<$dbh>) >>
=head2 C<< get_geoip_info (I<$pa_config>, I<$address>, I<$dispersion>) >>
Gets the GIS information obtained from the B<SQL> Database:
Get GIS information from the MaxMind GeoIP database on file using Geo::IP module
B<Returns>: I<undef> if there is not information available or a B<hash> with:
* I<country_code>
* I<country_code3>
* I<country_name>
* I<region>
* I<city>
* I<postal_code>
B<Returns>: I<undef> if there is not information available or a B<hash ref> with:
* I<longitude>
* I<latitude>
* I<metro_code>
* I<area_code>
=cut
##########################################################################
sub get_reverse_geoip_sql($$$) {
my ($pa_config,$ip_addr, $dbh) = @_;
my $id_range = get_db_value($dbh,
'SELECT ' . $RDBMS_QUOTE . 'id_range' . $RDBMS_QUOTE . '
FROM tgis_reverse_geoip_ranges
WHERE INET_ATON(?) >= ' . $RDBMS_QUOTE . 'first_IP_decimal' . $RDBMS_QUOTE . '
AND INET_ATON(?) <= ' . $RDBMS_QUOTE . 'last_IP_decimal ' . $RDBMS_QUOTE . '
LIMIT 1', $ip_addr, $ip_addr);
if (defined($id_range)) {
logger($pa_config,"Range id of '$ip_addr' is '$id_range'", 8);
my $region_info = get_db_single_row($dbh,
'SELECT *
FROM tgis_reverse_geoip_info
WHERE ' . $RDBMS_QUOTE . 'id_range ' . $RDBMS_QUOTE . ' = ?',
$id_range);
logger($pa_config, "region info of id_range '$id_range' is: country:".$region_info->{'country_name'}." region:".$region_info->{'region'}." city:".$region_info->{'city'}." longitude:".$region_info->{'longitude'}." latitude:".$region_info->{'longitude'}, 8);
return $region_info;
sub get_geoip_info {
my ($pa_config, $address) = @_;
# Return undef if feature is not activated
return undef unless ($pa_config->{'activate_gis'} && $pa_config->{'recon_reverse_geolocation_file'} ne '');
my $record = undef;
eval {
local $SIG{__DIE__};
my $gi = Geo::IP->open($pa_config->{'recon_reverse_geolocation_file'}, GEOIP_STANDARD);
die("Cannot load the geoip file \"" . $pa_config->{'recon_reverse_geolocation_file'} . "\".\n") unless defined($gi);
$record = $gi->record_by_addr($address);
};
if ($@) {
logger($pa_config, "Error giving coordinates to IP: $address. $@", 8);
}
return undef;
}
return undef unless defined($record);
##########################################################################
=head2 C<< get_reverse_geoip_file (I<$pa_config>, I<$ip_addr>) >>
# Fuzzy position filter
my ($longitude, $latitude) = get_random_close_point (
$pa_config, $record->longitude, $record->latitude
);
Gets GIS information from the MaxMind GeooIP database on file using the
GPL perl API from MaxMindGeoIP
B<Returns>: I<undef> if there is not information available or a B<hash> with:
* I<country_code>
* I<country_code3>
* I<country_name>
* I<region>
* I<city>
* I<postal_code>
* I<longitude>
* I<latitude>
* I<metro_code>
* I<area_code>
=cut
##########################################################################
sub get_reverse_geoip_file($$) {
my ($pa_config,$ip_addr) = @_;
if ($geoIPPurePerlavilable == 1) {
my $geoipdb = PandoraFMS::GeoIP->open( $pa_config->{'recon_reverse_geolocation_file'});
if (defined($geoipdb)) {
my $region_info = $geoipdb->get_city_record_as_hash($ip_addr);
logger($pa_config, "Region info found for IP '$ip_addr' is: country:".$region_info->{'country_name'}." region:".$region_info->{'region'}." city:".$region_info->{'city'}." longitude:".$region_info->{'longitude'}." latitude:".$region_info->{'latitude'}, 8);
return $region_info;
}
else {
logger($pa_config, "WARNING: Can't open reverse geolocation file ($pa_config->{'recon_reverse_geolocation_file'}) :$!",8);
}
}
return undef;
return {
"longitude" => $longitude,
"latitude" => $latitude
};
}
##########################################################################
@ -228,7 +179,9 @@ Returns C<< (I<$longitude>, I<$laitiutde>) >>
##########################################################################
sub get_random_close_point ($$$) {
my ($pa_config, $center_longitude, $center_latitude) = @_;
return ($center_longitude, $center_latitude) if ($pa_config->{'recon_location_scatter_radius'} == 0);
my $sign = int rand(2);
my $longitude = ($sign*(-1)+(1-$sign)) * rand($pa_config->{'recon_location_scatter_radius'}/$earth_radius_in_meters)*$to_degrees;
logger($pa_config,"Longitude random offset '$longitude' ", 8);
@ -250,7 +203,7 @@ __END__
=head1 DEPENDENCIES
L<PandoraFMS::DB>, L<PandoraFMS::Tools> (Optional L<Geo::IP::PurePerl> to use file reverse geolocation database that is faster than the SQL)
L<PandoraFMS::DB>, L<PandoraFMS::Tools>, L<Geo::IP>
=head1 LICENSE
@ -262,6 +215,6 @@ L<PandoraFMS::DB>, L<PandoraFMS::Tools>
=head1 COPYRIGHT
Copyright (c) 2005-2010 Artica Soluciones Tecnologicas S.L
Copyright (c) 2005-2018 Artica Soluciones Tecnologicas S.L
=cut

View File

@ -1,891 +0,0 @@
package PandoraFMS::GeoIP;
use strict;
use FileHandle;
use File::Spec;
BEGIN {
if ( $] >= 5.008 ) {
require Encode;
Encode->import(qw/ decode /);
}
else {
*decode = sub {
local $_ = $_[1];
use bytes;
s/([\x80-\xff])/my $c = ord($1);
my $p = $c >= 192 ? 1 : 0;
pack ( 'CC' => 0xc2 + $p , $c & ~0x40 ); /ge;
return $_;
};
}
};
use vars qw( @ISA $VERSION @EXPORT $OPEN_TYPE_PATH );
use constant GEOIP_CHARSET_ISO_8859_1 => 0;
use constant GEOIP_CHARSET_UTF8 => 1;
use constant FULL_RECORD_LENGTH => 50;
use constant GEOIP_COUNTRY_BEGIN => 16776960;
use constant RECORD_LENGTH => 3;
use constant GEOIP_STATE_BEGIN_REV0 => 16700000;
use constant GEOIP_STATE_BEGIN_REV1 => 16000000;
use constant STRUCTURE_INFO_MAX_SIZE => 20;
use constant DATABASE_INFO_MAX_SIZE => 100;
use constant GEOIP_COUNTRY_EDITION => 1;
use constant GEOIP_REGION_EDITION_REV0 => 7;
use constant GEOIP_REGION_EDITION_REV1 => 3;
use constant GEOIP_CITY_EDITION_REV0 => 6;
use constant GEOIP_CITY_EDITION_REV1 => 2;
use constant GEOIP_ORG_EDITION => 5;
use constant GEOIP_ISP_EDITION => 4;
use constant GEOIP_PROXY_EDITION => 8;
use constant GEOIP_ASNUM_EDITION => 9;
use constant GEOIP_NETSPEED_EDITION => 10;
use constant GEOIP_DOMAIN_EDITION => 11;
use constant SEGMENT_RECORD_LENGTH => 3;
use constant STANDARD_RECORD_LENGTH => 3;
use constant ORG_RECORD_LENGTH => 4;
use constant MAX_RECORD_LENGTH => 4;
use constant MAX_ORG_RECORD_LENGTH => 300;
use constant US_OFFSET => 1;
use constant CANADA_OFFSET => 677;
use constant WORLD_OFFSET => 1353;
use constant FIPS_RANGE => 360;
$VERSION = '1.24';
require Exporter;
@ISA = qw(Exporter);
# cheat --- try to load Sys::Mmap
BEGIN {
eval {
# wrap into eval again, as workaround for centos / mod_perl issue
# seems they use $@ without eval somewhere
eval "require Sys::Mmap"
? Sys::Mmap->import
: do {
for (qw/ PROT_READ MAP_PRIVATE MAP_SHARED /) {
no strict 'refs';
my $unused_stub = $_; # we must use a copy
*$unused_stub = sub { die 'Sys::Mmap required for mmap support' };
} # for
}; # do
1;
}; # eval
} # begin
sub GEOIP_STANDARD(){0;}
sub GEOIP_MEMORY_CACHE(){1;}
#sub GEOIP_CHECK_CACHE(){2;}
#sub GEOIP_INDEX_CACHE(){4;}
sub GEOIP_MMAP_CACHE(){8;}
sub GEOIP_UNKNOWN_SPEED(){0;}
sub GEOIP_DIALUP_SPEED(){1;}
sub GEOIP_CABLEDSL_SPEED(){2;}
sub GEOIP_CORPORATE_SPEED(){3;}
@EXPORT = qw( GEOIP_STANDARD GEOIP_MEMORY_CACHE GEOIP_MMAP_CACHE
GEOIP_UNKNOWN_SPEED GEOIP_DIALUP_SPEED GEOIP_CABLEDSL_SPEED GEOIP_CORPORATE_SPEED );
my @countries =
(undef,"AP","EU","AD","AE","AF","AG","AI","AL","AM","AN","AO","AQ","AR","AS","AT","AU","AW","AZ","BA","BB","BD","BE","BF","BG","BH","BI","BJ","BM","BN","BO","BR","BS","BT","BV","BW","BY","BZ","CA","CC","CD","CF","CG","CH","CI","CK","CL","CM","CN","CO","CR","CU","CV","CX","CY","CZ","DE","DJ","DK","DM","DO","DZ","EC","EE","EG","EH","ER","ES","ET","FI","FJ","FK","FM","FO","FR","FX","GA","GB","GD","GE","GF","GH","GI","GL","GM","GN","GP","GQ","GR","GS","GT","GU","GW","GY","HK","HM","HN","HR","HT","HU","ID","IE","IL","IN","IO","IQ","IR","IS","IT","JM","JO","JP","KE","KG","KH","KI","KM","KN","KP","KR","KW","KY","KZ","LA","LB","LC","LI","LK","LR","LS","LT","LU","LV","LY","MA","MC","MD","MG","MH","MK","ML","MM","MN","MO","MP","MQ","MR","MS","MT","MU","MV","MW","MX","MY","MZ","NA","NC","NE","NF","NG","NI","NL","NO","NP","NR","NU","NZ","OM","PA","PE","PF","PG","PH","PK","PL","PM","PN","PR","PS","PT","PW","PY","QA","RE","RO","RU","RW","SA","SB","SC","SD","SE","SG","SH","SI","SJ","SK","SL","SM","SN","SO","SR","ST","SV","SY","SZ","TC","TD","TF","TG","TH","TJ","TK","TM","TN","TO","TL","TR","TT","TV","TW","TZ","UA","UG","UM","US","UY","UZ","VA","VC","VE","VG","VI","VN","VU","WF","WS","YE","YT","RS","ZA","ZM","ME","ZW","A1","A2","O1","AX","GG","IM","JE","BL","MF");
my @code3s = ( undef,"AP","EU","AND","ARE","AFG","ATG","AIA","ALB","ARM","ANT","AGO","AQ","ARG","ASM","AUT","AUS","ABW","AZE","BIH","BRB","BGD","BEL","BFA","BGR","BHR","BDI","BEN","BMU","BRN","BOL","BRA","BHS","BTN","BV","BWA","BLR","BLZ","CAN","CC","COD","CAF","COG","CHE","CIV","COK","CHL","CMR","CHN","COL","CRI","CUB","CPV","CX","CYP","CZE","DEU","DJI","DNK","DMA","DOM","DZA","ECU","EST","EGY","ESH","ERI","ESP","ETH","FIN","FJI","FLK","FSM","FRO","FRA","FX","GAB","GBR","GRD","GEO","GUF","GHA","GIB","GRL","GMB","GIN","GLP","GNQ","GRC","GS","GTM","GUM","GNB","GUY","HKG","HM","HND","HRV","HTI","HUN","IDN","IRL","ISR","IND","IO","IRQ","IRN","ISL","ITA","JAM","JOR","JPN","KEN","KGZ","KHM","KIR","COM","KNA","PRK","KOR","KWT","CYM","KAZ","LAO","LBN","LCA","LIE","LKA","LBR","LSO","LTU","LUX","LVA","LBY","MAR","MCO","MDA","MDG","MHL","MKD","MLI","MMR","MNG","MAC","MNP","MTQ","MRT","MSR","MLT","MUS","MDV","MWI","MEX","MYS","MOZ","NAM","NCL","NER","NFK","NGA","NIC","NLD","NOR","NPL","NRU","NIU","NZL","OMN","PAN","PER","PYF","PNG","PHL","PAK","POL","SPM","PCN","PRI","PSE","PRT","PLW","PRY","QAT","REU","ROU","RUS","RWA","SAU","SLB","SYC","SDN","SWE","SGP","SHN","SVN","SJM","SVK","SLE","SMR","SEN","SOM","SUR","STP","SLV","SYR","SWZ","TCA","TCD","TF","TGO","THA","TJK","TKL","TKM","TUN","TON","TLS","TUR","TTO","TUV","TWN","TZA","UKR","UGA","UM","USA","URY","UZB","VAT","VCT","VEN","VGB","VIR","VNM","VUT","WLF","WSM","YEM","YT","SRB","ZAF","ZMB","MNE","ZWE","A1","A2","O1","ALA","GGY","IMN","JEY","BLM","MAF");
my @names = (undef,"Asia/Pacific Region","Europe","Andorra","United Arab Emirates","Afghanistan","Antigua and Barbuda",
"Anguilla","Albania","Armenia","Netherlands Antilles","Angola","Antarctica","Argentina","American Samoa",
"Austria","Australia","Aruba","Azerbaijan","Bosnia and Herzegovina","Barbados","Bangladesh","Belgium","Burkina Faso",
"Bulgaria","Bahrain","Burundi","Benin","Bermuda","Brunei Darussalam","Bolivia","Brazil","Bahamas","Bhutan","Bouvet Island",
"Botswana","Belarus","Belize","Canada","Cocos (Keeling) Islands","Congo, The Democratic Republic of the","Central African Republic",
"Congo","Switzerland","Cote D'Ivoire","Cook Islands","Chile","Cameroon","China","Colombia","Costa Rica","Cuba","Cape Verde",
"Christmas Island","Cyprus","Czech Republic","Germany","Djibouti","Denmark","Dominica","Dominican Republic","Algeria","Ecuador",
"Estonia","Egypt","Western Sahara","Eritrea","Spain","Ethiopia","Finland","Fiji","Falkland Islands (Malvinas)",
"Micronesia, Federated States of","Faroe Islands","France","France, Metropolitan","Gabon","United Kingdom","Grenada","Georgia",
"French Guiana","Ghana","Gibraltar","Greenland","Gambia","Guinea","Guadeloupe","Equatorial Guinea","Greece",
"South Georgia and the South Sandwich Islands","Guatemala","Guam","Guinea-Bissau","Guyana","Hong Kong",
"Heard Island and McDonald Islands","Honduras","Croatia","Haiti","Hungary","Indonesia","Ireland","Israel","India",
"British Indian Ocean Territory","Iraq","Iran, Islamic Republic of","Iceland","Italy","Jamaica","Jordan","Japan","Kenya",
"Kyrgyzstan","Cambodia","Kiribati","Comoros","Saint Kitts and Nevis","Korea, Democratic People's Republic of","Korea, Republic of",
"Kuwait","Cayman Islands","Kazakhstan","Lao People's Democratic Republic","Lebanon","Saint Lucia","Liechtenstein","Sri Lanka",
"Liberia","Lesotho","Lithuania","Luxembourg","Latvia","Libyan Arab Jamahiriya","Morocco","Monaco","Moldova, Republic of",
"Madagascar","Marshall Islands","Macedonia","Mali","Myanmar","Mongolia","Macau","Northern Mariana Islands","Martinique",
"Mauritania","Montserrat","Malta","Mauritius","Maldives","Malawi","Mexico","Malaysia","Mozambique","Namibia","New Caledonia",
"Niger","Norfolk Island","Nigeria","Nicaragua","Netherlands","Norway","Nepal","Nauru","Niue","New Zealand","Oman","Panama","Peru",
"French Polynesia","Papua New Guinea","Philippines","Pakistan","Poland","Saint Pierre and Miquelon","Pitcairn Islands","Puerto Rico",
"Palestinian Territory","Portugal","Palau","Paraguay","Qatar","Reunion","Romania","Russian Federation","Rwanda","Saudi Arabia",
"Solomon Islands","Seychelles","Sudan","Sweden","Singapore","Saint Helena","Slovenia","Svalbard and Jan Mayen","Slovakia","Sierra Leone",
"San Marino","Senegal","Somalia","Suriname","Sao Tome and Principe","El Salvador","Syrian Arab Republic","Swaziland",
"Turks and Caicos Islands","Chad","French Southern Territories","Togo","Thailand","Tajikistan","Tokelau","Turkmenistan","Tunisia",
"Tonga","Timor-Leste","Turkey","Trinidad and Tobago","Tuvalu","Taiwan","Tanzania, United Republic of","Ukraine","Uganda",
"United States Minor Outlying Islands","United States","Uruguay","Uzbekistan","Holy See (Vatican City State)",
"Saint Vincent and the Grenadines","Venezuela","Virgin Islands, British","Virgin Islands, U.S.","Vietnam","Vanuatu",
"Wallis and Futuna","Samoa","Yemen","Mayotte","Serbia","South Africa","Zambia","Montenegro","Zimbabwe","Anonymous Proxy",
"Satellite Provider","Other","Aland Islands","Guernsey","Isle of Man","Jersey","Saint Barthelemy","Saint Martin");
# --- unfortunately we do not know the path so we assume the
# default path /usr/local/share/GeoIP
# if thats not true, you can set $Geo::IP::PurePerl::OPEN_TYPE_PATH
#
sub open_type {
my ( $class, $type, $flags ) = @_;
my %type_dat_name_mapper = (
GEOIP_COUNTRY_EDITION() => 'GeoIP',
GEOIP_REGION_EDITION_REV0() => 'GeoIPRegion',
GEOIP_REGION_EDITION_REV1() => 'GeoIPRegion',
GEOIP_CITY_EDITION_REV0() => 'GeoIPCity',
GEOIP_CITY_EDITION_REV1() => 'GeoIPCity',
GEOIP_ISP_EDITION() => 'GeoIPISP',
GEOIP_ORG_EDITION() => 'GeoIPOrg',
GEOIP_PROXY_EDITION() => 'GeoIPProxy',
GEOIP_ASNUM_EDITION() => 'GeoIPASNum',
GEOIP_NETSPEED_EDITION() => 'GeoIPNetSpeed',
GEOIP_DOMAIN_EDITION() => 'GeoIPDomain',
);
# backward compatibility for 2003 databases.
$type -= 105 if $type >= 106;
my $name = $type_dat_name_mapper{$type};
die("Invalid database type $type\n") unless $name;
my $mkpath = sub { File::Spec->catfile( File::Spec->rootdir, @_ ) };
my $path =
defined $Geo::IP::PurePerl::OPEN_TYPE_PATH
? $Geo::IP::PurePerl::OPEN_TYPE_PATH
: do {
$^O eq 'NetWare'
? $mkpath->(qw/ etc GeoIP /)
: do {
$^O eq 'MSWin32'
? $mkpath->(qw/ GeoIP /)
: $mkpath->(qw/ usr local share GeoIP /);
}
};
my $filename = File::Spec->catfile( $path, $name . '.dat' );
return $class->open( $filename, $flags );
}
sub open {
die "Geo::IP::PurePerl::open() requires a path name"
unless( @_ > 1 and $_[1] );
my ($class, $db_file, $flags) = @_;
my $fh = FileHandle->new;
my $gi;
CORE::open $fh, $db_file or die "Error opening $db_file";
binmode($fh);
if ( $flags && ( $flags & ( GEOIP_MEMORY_CACHE | GEOIP_MMAP_CACHE ) ) ) {
my %self;
if ( $flags & GEOIP_MMAP_CACHE ) {
die "Sys::Mmap required for MMAP support"
unless defined $Sys::Mmap::VERSION;
mmap( $self{buf} = undef, 0, PROT_READ, MAP_PRIVATE, $fh )
or die "mmap: $!";
}
else {
local $/ = undef;
$self{buf} = <$fh>;
}
$self{fh} = $fh;
$gi = bless \%self, $class;
}
else {
$gi = bless { fh => $fh }, $class;
}
$gi->_setup_segments();
return $gi;
}
sub new {
my ($class, $db_file, $flags) = @_;
# this will be less messy once deprecated new( $path, [$flags] )
# is no longer supported (that's what open() is for)
my $def_db_file = '/usr/local/share/GeoIP/GeoIP.dat';
if ($^O eq 'NetWare') {
$def_db_file = 'sys:/etc/GeoIP/GeoIP.dat';
} elsif ($^O eq 'MSWin32') {
$def_db_file = 'c:/GeoIP/GeoIP.dat';
}
if ( !defined $db_file ) {
# called as new()
$db_file = $def_db_file;
} elsif ( $db_file =~ /^\d+$/ ) {
# db_file is GEOIP_MEMORY_CACHE or GEOIP_STANDARD
# called as new( $flags )
$flags = $db_file;
$db_file = $def_db_file;
} # else called as new( $database_filename, [$flags] );
$class->open( $db_file, $flags );
}
#this function setups the database segments
sub _setup_segments {
my ($gi) = @_;
my $a = 0;
my $i = 0;
my $j = 0;
my $delim;
my $buf;
$gi->{_charset} = GEOIP_CHARSET_ISO_8859_1;
$gi->{"databaseType"} = GEOIP_COUNTRY_EDITION;
$gi->{"record_length"} = STANDARD_RECORD_LENGTH;
my $filepos = tell($gi->{fh});
seek($gi->{fh}, -3, 2);
for ($i = 0; $i < STRUCTURE_INFO_MAX_SIZE; $i++) {
read($gi->{fh},$delim,3);
#find the delim
if ($delim eq (chr(255).chr(255).chr(255))) {
read($gi->{fh},$a,1);
#read the databasetype
$gi->{"databaseType"} = ord($a);
# backward compatibility for 2003 databases.
$gi->{databaseType} -= 105 if $gi->{databaseType} >= 106;
#chose the database segment for the database type
#if database Type is GEOIP_REGION_EDITION then use database segment GEOIP_STATE_BEGIN
if ($gi->{"databaseType"} == GEOIP_REGION_EDITION_REV0) {
$gi->{"databaseSegments"} = GEOIP_STATE_BEGIN_REV0;
} elsif ($gi->{"databaseType"} == GEOIP_REGION_EDITION_REV1) {
$gi->{"databaseSegments"} = GEOIP_STATE_BEGIN_REV1;
}
#if database Type is GEOIP_CITY_EDITION, GEOIP_ISP_EDITION or GEOIP_ORG_EDITION then
#read in the database segment
elsif (($gi->{"databaseType"} == GEOIP_CITY_EDITION_REV0) ||
($gi->{"databaseType"} == GEOIP_CITY_EDITION_REV1) ||
($gi->{"databaseType"} == GEOIP_ORG_EDITION) ||
($gi->{"databaseType"} == GEOIP_ASNUM_EDITION) ||
($gi->{"databaseType"} == GEOIP_ISP_EDITION)) {
$gi->{"databaseSegments"} = 0;
#read in the database segment for the database type
read($gi->{fh},$buf,SEGMENT_RECORD_LENGTH);
for ($j = 0;$j < SEGMENT_RECORD_LENGTH;$j++) {
$gi->{"databaseSegments"} += (ord(substr($buf,$j,1)) << ($j * 8));
}
#record length is four for ISP databases and ORG databases
#record length is three for country databases, region database and city databases
if ($gi->{"databaseType"} == GEOIP_ORG_EDITION ||
$gi->{"databaseType"} == GEOIP_ISP_EDITION) {
$gi->{"record_length"} = ORG_RECORD_LENGTH;
}
}
last;
} else {
seek($gi->{fh}, -4 , 1);
}
}
#if database Type is GEOIP_COUNTY_EDITION then use database segment GEOIP_COUNTRY_BEGIN
if ($gi->{"databaseType"} == GEOIP_COUNTRY_EDITION ||
$gi->{"databaseType"} == GEOIP_NETSPEED_EDITION) {
$gi->{"databaseSegments"} = GEOIP_COUNTRY_BEGIN;
}
seek($gi->{fh},$filepos,0);
return $gi;
}
sub _seek_country {
my ($gi, $ipnum) = @_;
my $fh = $gi->{fh};
my $offset = 0;
my ($x0, $x1);
my $reclen = $gi->{"record_length"};
for (my $depth = 31; $depth >= 0; $depth--) {
unless ( exists $gi->{buf} ) {
seek $fh, $offset * 2 * $reclen, 0;
read $fh, $x0, $reclen;
read $fh, $x1, $reclen;
} else {
$x0 = substr($gi->{buf}, $offset * 2 * $reclen, $reclen);
$x1 = substr($gi->{buf}, $offset * 2 * $reclen + $reclen, $reclen);
}
$x0 = unpack("V1", $x0."\0");
$x1 = unpack("V1", $x1."\0");
if ($ipnum & (1 << $depth)) {
if ($x1 >= $gi->{"databaseSegments"}) {
$gi->{last_netmask} = 32 - $depth;
return $x1;
}
$offset = $x1;
} else {
if ($x0 >= $gi->{"databaseSegments"}) {
$gi->{last_netmask} = 32 - $depth;
return $x0;
}
$offset = $x0;
}
}
print STDERR "Error Traversing Database for ipnum = $ipnum - Perhaps database is corrupt?";
}
sub charset {
return $_[0]->{_charset};
}
sub set_charset{
my ( $gi, $charset ) = @_;
my $old_charset = $gi->{_charset};
$gi->{_charset} = $charset;
return $old_charset;
}
#this function returns the country code of ip address
sub country_code_by_addr {
my ($gi, $ip_address) = @_;
return unless $ip_address =~ m!^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$!;
return $countries[$gi->id_by_addr($ip_address)];
}
#this function returns the country code3 of ip address
sub country_code3_by_addr {
my ($gi, $ip_address) = @_;
return unless $ip_address =~ m!^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$!;
return $code3s[$gi->id_by_addr($ip_address)];
}
#this function returns the name of ip address
sub country_name_by_addr {
my ($gi, $ip_address) = @_;
return unless $ip_address =~ m!^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$!;
return $names[$gi->id_by_addr($ip_address)];
}
sub id_by_addr {
my ($gi, $ip_address) = @_;
return unless $ip_address =~ m!^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$!;
return $gi->_seek_country(addr_to_num($ip_address)) - GEOIP_COUNTRY_BEGIN;
}
#this function returns the country code of domain name
sub country_code_by_name {
my ($gi, $host) = @_;
my $country_id = $gi->id_by_name($host);
return $countries[$country_id];
}
#this function returns the country code3 of domain name
sub country_code3_by_name {
my ($gi, $host) = @_;
my $country_id = $gi->id_by_name($host);
return $code3s[$country_id];
}
#this function returns the country name of domain name
sub country_name_by_name {
my ($gi, $host) = @_;
my $country_id = $gi->id_by_name($host);
return $names[$country_id];
}
sub id_by_name {
my ($gi, $host) = @_;
my $ip_address;
if ($host =~ m!^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$!) {
$ip_address = $host;
} else {
$ip_address = join('.',unpack('C4',(gethostbyname($host))[4]));
}
return unless $ip_address;
return $gi->_seek_country(addr_to_num($ip_address)) - GEOIP_COUNTRY_BEGIN;
}
#this function returns the city record as a array
sub get_city_record {
my ($gi, $host) = @_;
my $ip_address = $gi->get_ip_address($host);
return unless $ip_address;
my $record_buf;
my $record_buf_pos;
my $char;
my $metroarea_combo;
my $record_country_code = "";
my $record_country_code3 = "";
my $record_country_name = "";
my $record_region = "";
my $record_city = "";
my $record_postal_code = "";
my $record_latitude = "";
my $record_longitude = "";
my $record_metro_code = "";
my $record_area_code = "";
my $str_length = 0;
my $i;
my $j;
#lookup the city
my $seek_country = $gi->_seek_country(addr_to_num($ip_address));
if ($seek_country == $gi->{"databaseSegments"}) {
return;
}
#set the record pointer to location of the city record
my $record_pointer = $seek_country + (2 * $gi->{"record_length"} - 1) * $gi->{"databaseSegments"};
unless ( exists $gi->{buf} ) {
seek( $gi->{"fh"}, $record_pointer, 0 );
read( $gi->{"fh"}, $record_buf, FULL_RECORD_LENGTH );
$record_buf_pos = 0;
}
else {
$record_buf = substr($gi->{buf}, $record_pointer, FULL_RECORD_LENGTH);
$record_buf_pos = 0;
}
#get the country
$char = ord(substr($record_buf,$record_buf_pos,1));
$record_country_code = $countries[$char];#get the country code
$record_country_code3 = $code3s[$char];#get the country code with 3 letters
$record_country_name = $names[$char];#get the country name
$record_buf_pos++;
#get the region
$char = ord(substr($record_buf,$record_buf_pos+$str_length,1));
while ($char != 0) {
$str_length++;#get the length of string
$char = ord(substr($record_buf,$record_buf_pos+$str_length,1));
}
if ($str_length > 0) {
$record_region = substr($record_buf,$record_buf_pos,$str_length);
}
$record_buf_pos += $str_length + 1;
$str_length = 0;
#get the city
$char = ord(substr($record_buf,$record_buf_pos+$str_length,1));
while ($char != 0) {
$str_length++;#get the length of string
$char = ord(substr($record_buf,$record_buf_pos+$str_length,1));
}
if ($str_length > 0) {
$record_city = substr($record_buf,$record_buf_pos,$str_length);
}
$record_buf_pos += $str_length + 1;
$str_length = 0;
#get the postal code
$char = ord(substr($record_buf,$record_buf_pos+$str_length,1));
while ($char != 0) {
$str_length++;#get the length of string
$char = ord(substr($record_buf,$record_buf_pos+$str_length,1));
}
if ($str_length > 0) {
$record_postal_code = substr($record_buf,$record_buf_pos,$str_length);
}
$record_buf_pos += $str_length + 1;
$str_length = 0;
my $latitude = 0;
my $longitude = 0;
#get the latitude
for ($j = 0;$j < 3; ++$j) {
$char = ord(substr($record_buf,$record_buf_pos++,1));
$latitude += ($char << ($j * 8));
}
$record_latitude = ($latitude/10000) - 180;
#get the longitude
for ($j = 0;$j < 3; ++$j) {
$char = ord(substr($record_buf,$record_buf_pos++,1));
$longitude += ($char << ($j * 8));
}
$record_longitude = ($longitude/10000) - 180;
#get the metro code and the area code
if (GEOIP_CITY_EDITION_REV1 == $gi->{"databaseType"}) {
$metroarea_combo = 0;
if ($record_country_code eq "US") {
#if the country is US then read the metro area combo
for ($j = 0;$j < 3;++$j) {
$char = ord(substr($record_buf,$record_buf_pos++,1));
$metroarea_combo += ($char << ($j * 8));
}
#split the metro area combo into the metro code and the area code
$record_metro_code = int($metroarea_combo/1000);
$record_area_code = $metroarea_combo%1000;
}
}
# the pureperl API must convert the string by themself to UTF8
# using Encode for perl >= 5.008 otherwise use it's own iso-8859-1 to utf8 converter
$record_city = decode( 'iso-8859-1' => $record_city )
if $gi->charset == GEOIP_CHARSET_UTF8;
return ($record_country_code,$record_country_code3,$record_country_name,$record_region,$record_city,$record_postal_code,$record_latitude,$record_longitude,$record_metro_code,$record_area_code);
}
#this function returns the city record as a hash ref
sub get_city_record_as_hash {
my ($gi, $host) = @_;
my %h;
@h{qw/ country_code country_code3 country_name
region city postal_code
latitude longitude metro_code
area_code /}
= $gi->get_city_record($host);
$h{dma_code} = $h{metro_code}; # alias for depreciated dma_code
return \%h;
}
#this function returns isp or org of the domain name
sub org_by_name {
my ($gi, $host) = @_;
my $ip_address = $gi->get_ip_address($host);
my $seek_org = $gi->_seek_country(addr_to_num($ip_address));
my $char;
my $org_buf;
my $org_buf_length = 0;
my $record_pointer;
if ($seek_org == $gi->{"databaseSegments"}) {
return undef;
}
$record_pointer = $seek_org + (2 * $gi->{"record_length"} - 1) * $gi->{"databaseSegments"};
unless ( exists $gi->{buf} ) {
seek( $gi->{"fh"}, $record_pointer, 0 );
read( $gi->{"fh"}, $org_buf, MAX_ORG_RECORD_LENGTH );
}
else {
$org_buf = substr($gi->{buf}, $record_pointer, MAX_ORG_RECORD_LENGTH );
}
$char = ord(substr($org_buf,0,1));
while ($char != 0) {
$org_buf_length++;
$char = ord(substr($org_buf,$org_buf_length,1));
}
$org_buf = substr($org_buf, 0, $org_buf_length);
return $org_buf;
}
#this function returns isp or org of the domain name
*isp_by_name = \*org_by_name;
*org_by_addr = \*org_by_name;
*isp_by_addr = \*org_by_name;
#this function returns the region
sub region_by_name {
my ($gi, $host) = @_;
my $ip_address = $gi->get_ip_address($host);
return unless $ip_address;
if ($gi->{"databaseType"} == GEOIP_REGION_EDITION_REV0) {
my $seek_region = $gi->_seek_country(addr_to_num($ip_address)) - GEOIP_STATE_BEGIN_REV0;
if ($seek_region >= 1000) {
return ("US",chr(($seek_region - 1000)/26 + 65) . chr(($seek_region - 1000)%26 + 65));
} else {
return ($countries[$seek_region],"");
}
} elsif ($gi->{"databaseType"} == GEOIP_REGION_EDITION_REV1) {
my $seek_region = $gi->_seek_country(addr_to_num($ip_address)) - GEOIP_STATE_BEGIN_REV1;
if ($seek_region < US_OFFSET) {
return ("","");
} elsif ($seek_region < CANADA_OFFSET) {
# return a us state
return ("US",chr(($seek_region - US_OFFSET)/26 + 65) . chr(($seek_region - US_OFFSET)%26 + 65));
} elsif ($seek_region < WORLD_OFFSET) {
# return a canada province
return ("CA",chr(($seek_region - CANADA_OFFSET)/26 + 65) . chr(($seek_region - CANADA_OFFSET)%26 + 65));
} else {
# return a country of the world
my $c = $countries[($seek_region - WORLD_OFFSET) / FIPS_RANGE];
my $a2 = ($seek_region - WORLD_OFFSET) % FIPS_RANGE;
my $r = chr(($a2 / 100)+48) . chr((($a2 / 10) % 10)+48) . chr(($a2 % 10)+48);
return ($c,$r);
}
}
}
sub get_ip_address {
my ($gi, $host) = @_;
my $ip_address;
#check if host is ip address
if ($host =~ m!^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$!) {
#host is ip address
$ip_address = $host;
} else {
#host is domain name do a dns lookup
$ip_address = join('.',unpack('C4',(gethostbyname($host))[4]));
}
return $ip_address;
}
sub addr_to_num { unpack( N => pack( C4 => split( /\./, $_[0] ) ) ) }
sub num_to_addr { join q{.}, unpack( C4 => pack( N => $_[0] ) ) }
sub database_info {
my $gi = shift;
my $i = 0;
my $buf;
my $retval;
my $hasStructureInfo;
seek($gi->{fh},-3,2);
for (my $i = 0;$i < STRUCTURE_INFO_MAX_SIZE;$i++) {
read($gi->{fh},$buf,3);
if ($buf eq (chr(255) . chr(255) . chr(255))) {
$hasStructureInfo = 1;
last;
}
seek($gi->{fh},-4,1);
}
if ($hasStructureInfo == 1) {
seek($gi->{fh},-6,1);
} else {
# no structure info, must be pre Sep 2002 database, go back to
seek($gi->{fh},-3,2);
}
for (my $i = 0;$i < DATABASE_INFO_MAX_SIZE;$i++){
read($gi->{fh},$buf,3);
if ($buf eq (chr(0). chr(0). chr(0))){
read($gi->{fh},$retval,$i);
return $retval;
}
seek($gi->{fh},-4,1);
}
return "";
}
sub range_by_ip {
my $gi = shift;
my $ipnum = addr_to_num( shift );
my $c = $gi->_seek_country( $ipnum );
my $nm = $gi->last_netmask;
my $m = 0xffffffff << 32 - $nm;
my $left_seek_num = $ipnum & $m;
my $right_seek_num = $left_seek_num + ( 0xffffffff & ~$m );
while ( $left_seek_num != 0
and $c == $gi->_seek_country( $left_seek_num - 1) ) {
my $lm = 0xffffffff << 32 - $gi->last_netmask;
$left_seek_num = ( $left_seek_num - 1 ) & $lm;
}
while ( $right_seek_num != 0xffffffff
and $c == $gi->_seek_country( $right_seek_num + 1 ) ) {
my $rm = 0xffffffff << 32 - $gi->last_netmask;
$right_seek_num = ( $right_seek_num + 1 ) & $rm;
$right_seek_num += ( 0xffffffff & ~$rm );
}
return ( num_to_addr($left_seek_num), num_to_addr($right_seek_num) );
}
sub netmask { $_[0]->{last_netmask} = $_[1] }
sub last_netmask {
return $_[0]->{last_netmask};
}
sub DESTROY {
my $gi = shift;
if ( exists $gi->{buf} && $gi->{flags} && ( $gi->{flags} & GEOIP_MMAP_CACHE ) ) {
munmap( $gi->{buf} ) or die "munmap: $!";
delete $gi->{buf};
}
}
1;
__END__
=head1 NAME
Geo::IP::PurePerl - Look up country by IP Address
=head1 SYNOPSIS
use Geo::IP::PurePerl;
my $gi = Geo::IP::PurePerl->new(GEOIP_STANDARD);
# look up IP address '24.24.24.24'
my $country = $gi->country_code_by_addr('24.24.24.24');
$country = $gi->country_code_by_name('yahoo.com');
# $country is equal to "US"
=head1 DESCRIPTION
This module uses a file based database. This database simply contains
IP blocks as keys, and countries as values. This database is more
complete and accurate than reverse DNS lookups.
This module can be used to automatically select the geographically closest mirror,
to analyze your web server logs
to determine the countries of your visiters, for credit card fraud
detection, and for software export controls.
=head1 IP ADDRESS TO COUNTRY DATABASES
The database is available for free, updated monthly:
http://www.maxmind.com/download/geoip/database/
This free database is similar to the database contained in IP::Country,
as well as many paid databases. It uses ARIN, RIPE, APNIC, and LACNIC
whois to obtain the IP->Country mappings.
If you require greater accuracy, MaxMind offers a paid database
on a paid subscription basis from http://www.maxmind.com/app/country
=head1 CLASS METHODS
=over 4
=item $gi = Geo::IP->new( [$flags] );
Constructs a new Geo::IP object with the default database located inside your system's
I<datadir>, typically I</usr/local/share/GeoIP/GeoIP.dat>.
Flags can be set to either GEOIP_STANDARD, or for faster performance
(at a cost of using more memory), GEOIP_MEMORY_CACHE.
The default flag is GEOIP_STANDARD (uses less memory, but runs slower).
=item $gi = Geo::IP->new( $database_filename );
Calling the C<new> constructor in this fashion was was deprecated after version
0.26 in order to make the XS and pure perl interfaces more similar. Use the
C<open> constructor (below) if you need to specify a path. Eventually, this
means of calling C<new> will no longer be supported.
Flags can be set to either GEOIP_STANDARD, or for faster performance
(at a cost of using more memory), GEOIP_MEMORY_CACHE.
=item $gi = Geo::IP->open( $database_filename, [$flags] );
Constructs a new Geo::IP object with the database located at C<$database_filename>.
The default flag is GEOIP_STANDARD (uses less memory, but runs slower).
=back
=head1 OBJECT METHODS
=over 4
=item $code = $gi->country_code_by_addr( $ipaddr );
Returns the ISO 3166 country code for an IP address.
=item $code = $gi->country_code_by_name( $ipname );
Returns the ISO 3166 country code for a hostname.
=item $code = $gi->country_code3_by_addr( $ipaddr );
Returns the 3 letter country code for an IP address.
=item $code = $gi->country_code3_by_name( $ipname );
Returns the 3 letter country code for a hostname.
=item $name = $gi->country_name_by_addr( $ipaddr );
Returns the full country name for an IP address.
=item $name = $gi->country_name_by_name( $ipname );
Returns the full country name for a hostname.
=item $info = $gi->database_info;
Returns database string, includes version, date, build number and copyright notice.
=item $old_charset = $gi->set_charset( $charset );
Set the charset for the city name - defaults to GEOIP_CHARSET_ISO_8859_1. To
set UTF8, pass GEOIP_CHARSET_UTF8 to set_charset.
=item $charset = $gi->charset;
Gets the currently used charset.
=item $netmask = $gi->last_netmask;
Gets netmask of network block from last lookup.
=item $gi->netmask(12);
Sets netmask for the last lookup
=item my ( $from, $to ) = $gi->range_by_ip('24.24.24.24');
Returns the start and end of the current network block. The method tries to join several continous netblocks.
=item @data = $gi->get_city_record( $addr );
Returns a array filled with information about the city.
my ($country_code,$country_code3,$country_name,$region,$city,$postal_code,$latitude,$longitude,$metro_code,$area_code ) = $gi->get_city_record($addr);
=item $href = get_city_record_as_hash( $addr );
Returns a hashref filled with information about the city.
my $href = $gi->get_city_record_as_hash($addr);
The hash include the following keys:
country_code, country_code3, country_name, region, city, postal_code, latitude, longitude, metro_code, area_code
=item $gi->isp_by_addr($addr)
Returns the isp name for an ipaddress
=item $gi->isp_by_name($name)
Returns the isp name for a hostname
=item $gi->org_by_addr($addr)
Returns the organisation name for an ipaddress
=item $gi->org_by_name($name)
Returns the organisation name for a hostname
=back
=head1 MAILING LISTS AND CVS
Are available from SourceForge, see
http://sourceforge.net/projects/geoip/
=head1 VERSION
1.23
=head1 SEE ALSO
Geo::IP - this now has the PurePerl code merged it, so it supports
both XS and Pure Perl implementations. The XS implementation is
a wrapper around the GeoIP C API, which is much faster than the
Pure Perl API.
=head1 AUTHOR
Copyright (c) 2008 MaxMind Inc
All rights reserved. This package is free software; it is licensed
under the GPL.
=cut

View File

@ -32,7 +32,7 @@ our @ISA = qw(Exporter);
# version: Defines actual version of Pandora Server for this module only
my $pandora_version = "7.0NG.724";
my $pandora_build = "180706";
my $pandora_build = "180712";
our $VERSION = $pandora_version." ".$pandora_build;
our %EXPORT_TAGS = ( 'all' => [ qw() ] );

View File

@ -176,7 +176,7 @@ sub exec_prediction_module ($$$$) {
logger ($pa_config, "Executing service module " .
$agent_module->{'id_agente_modulo'} . " " .
$agent_module->{'nombre'}, 10);
enterprise_hook ('exec_service_module', [$pa_config, $agent_module, $server_id, $dbh]);
enterprise_hook ('exec_service_module', [$pa_config, $agent_module, undef, $server_id, $dbh]);
}
return;

View File

@ -36,7 +36,7 @@ use PandoraFMS::Tools;
use PandoraFMS::DB;
use PandoraFMS::Core;
use PandoraFMS::ProducerConsumerServer;
use PandoraFMS::GIS qw(get_reverse_geoip_sql get_reverse_geoip_file get_random_close_point);
use PandoraFMS::GIS;
use PandoraFMS::Recon::Base;
# Patched Nmap::Parser. See http://search.cpan.org/dist/Nmap-Parser/.
@ -418,8 +418,12 @@ sub PandoraFMS::Recon::Base::create_agent($$) {
# Are we filtering hosts by TCP port?
return if ($self->{'recon_ports'} ne '' && $self->tcp_scan($device) == 0);
$agent_id = pandora_create_agent($self->{'pa_config'}, $self->{'pa_config'}->{'servername'}, $host_name, $device, $self->{'group_id'}, 0, $id_os, '', 300, $self->{'dbh'});
my $location = get_geoip_info($self->{'pa_config'}, $device);
$agent_id = pandora_create_agent($self->{'pa_config'}, $self->{'pa_config'}->{'servername'}, $host_name, $device,
$self->{'group_id'}, 0, $id_os,
'', 300, $self->{'dbh'}, undef,
$location->{'longitude'}, $location->{'latitude'}
);
return undef unless defined ($agent_id) and ($agent_id > 0);
pandora_event($self->{'pa_config'}, "[RECON] New " . safe_output($self->get_device_type($device)) . " found (" . join(',', safe_output($self->get_addresses($device))) . ").", $self->{'group_id'}, $agent_id, 2, 0, 0, 'recon_host_detected', 0, $self->{'dbh'});
$agent_learning = 1;

View File

@ -3,7 +3,7 @@
#
%define name pandorafms_server
%define version 7.0NG.724
%define release 180706
%define release 180712
Summary: Pandora FMS Server
Name: %{name}
@ -30,7 +30,7 @@ Requires: perl(NetAddr::IP) net-snmp net-tools
Requires: perl(IO::Socket::INET6) perl(Net::Telnet)
Requires: nmap sudo perl(JSON)
Requires: perl(Time::HiRes) perl(Encode::Locale)
Requires: perl perl(Sys::Syslog) perl(HTML::Entities)
Requires: perl perl(Sys::Syslog) perl(HTML::Entities) perl(Geo::IP)
%description
Pandora FMS is a monitoring system for big IT environments. It uses remote tests, or local agents to grab information. Pandora supports all standard OS (Linux, AIX, HP-UX, Solaris and Windows XP,2000/2003), and support multiple setups in HA enviroments.

View File

@ -3,7 +3,7 @@
#
%define name pandorafms_server
%define version 7.0NG.724
%define release 180706
%define release 180712
Summary: Pandora FMS Server
Name: %{name}
@ -25,7 +25,7 @@ Requires: perl-DBI perl-DBD-mysql perl-libwww-perl
Requires: perl-NetAddr-IP net-snmp net-tools perl-XML-Twig
Requires: nmap sudo perl-HTML-Tree perl-XML-Simple perl-Net-Telnet
Requires: perl-IO-Socket-INET6 perl-Socket6 snmp-mibs perl-JSON
Requires: perl-Encode-Locale
Requires: perl-Encode-Locale perl-Geo-IP
%description

View File

@ -9,7 +9,7 @@
# **********************************************************************
PI_VERSION="7.0NG.724"
PI_BUILD="180706"
PI_BUILD="180712"
MODE=$1
if [ $# -gt 1 ]; then

View File

@ -0,0 +1,92 @@
#!/usr/bin/perl
###############################################################################
# Pandora FMS DB Management
###############################################################################
# Copyright (c) 2005-2018 Artica Soluciones Tecnologicas S.L
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; version 2
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,USA
###############################################################################
# Includes list
use strict;
use warnings;
use Time::Local; # DateTime basic manipulation
use DBI; # DB interface with MySQL
use POSIX qw(strftime);
use Time::HiRes qw(usleep);
# Default lib dir for RPM and DEB packages
use lib '/usr/lib/perl5';
use PandoraFMS::Core;
use PandoraFMS::Config;
use PandoraFMS::DB;
use PandoraFMS::GIS;
# Pandora server configuration
my %conf;
# Pandora db handler
my $dbh;
# FLUSH in each IO
$| = 1;
sub print_agent_gis_update_help() {
print "Usage: $0 <path to pandora_server.conf>\n";
}
# Get options
my ($configuration_file) = @ARGV;
if (!defined($configuration_file) || $configuration_file eq '-h' || $configuration_file eq '--help') {
print_agent_gis_update_help();
exit defined($configuration_file) ? 0 : 1;
}
# Load configuration file
$conf{'pandora_path'} = $configuration_file;
$conf{'quiet'} = 0;
pandora_load_config(\%conf);
use Data::Dumper;
#print Dumper(\%conf);
if (!$conf{'activate_gis'} || $conf{'recon_reverse_geolocation_file'} eq '') {
print "Geolocation feature es blocked.\n";
exit 0;
}
# Connect to the DB
$dbh = db_connect ('mysql', $conf{'dbname'}, $conf{'dbhost'}, $conf{'dbport'}, $conf{'dbuser'}, $conf{'dbpass'});
if (!defined($dbh)){
print "Cannot connect to database\n";
exit 1;
}
# Get all agents with IP assigned
my @agents = get_db_rows($dbh,
"SELECT id_agente, direccion, alias FROM tagente WHERE disabled = 0 AND direccion <> ''"
);
my $c_time = strftime ("%Y/%m/%d %H:%M:%S", localtime());
foreach my $agent (@agents) {
my $location = get_geoip_info (\%conf, $agent->{'direccion'});
if (defined($location)) {
pandora_update_gis_data(\%conf, $dbh, $agent->{'id_agente'}, $agent->{'id_agente'}, $location->{'longitude'}, $location->{'latitude'}, undef, undef, $c_time);
}
}
print "Successfull relocation\n";
db_disconnect($dbh);
exit 0;

View File

@ -5,8 +5,6 @@ In order to be able to use GeoIP/GIS features of the Pandora FMS reconserver, yo
http://www.maxmind.com/app/geoip_resources
http://www.maxmind.com/app/installation
http://www.maxmind.com/app/geolitecity
Install manually Geo-IP-PurePerl-1.24.tar.gz
This database will be used with Pandora FMS recon server for positioning detected host Systems. Check Pandora FMS documentacion for more information.
@ -15,7 +13,6 @@ Prior to use this database you need to decompress it with gzip -d and edit your
activate_gis 1
recon_reverse_geolocation_file /usr/share/pandora_server/util/GeoLiteCity.dat
location_error 50
recon_reverse_geolocation_mode file
recon_location_scatter_radius 1000
Get a new version at:

View File

@ -34,7 +34,7 @@ use PandoraFMS::Config;
use PandoraFMS::DB;
# version: define current version
my $version = "7.0NG.724 PS180706";
my $version = "7.0NG.724 PS180712";
# Pandora server configuration
my %conf;

View File

@ -36,7 +36,7 @@ use Encode::Locale;
Encode::Locale::decode_argv;
# version: define current version
my $version = "7.0NG.724 PS180706";
my $version = "7.0NG.724 PS180712";
# save program name for logging
my $progname = basename($0);

View File

@ -104,7 +104,10 @@ RUN yum install -y \
RUN wget http://rpmfind.net/linux/centos/6.9/os/i386/Packages/gettext-0.17-18.el6.i686.rpm; \
yum localinstall -y gettext-0.17-18.el6.i686.rpm; \
rm -rf gettext-0.17-18.el6.i686.rpm;
rm -rf gettext-0.17-18.el6.i686.rpm; \
wget http://ftp.tu-chemnitz.de/pub/linux/dag/redhat/el6/en/x86_64/rpmforge/RPMS/perl-Geo-IP-1.38-1.el6.rf.x86_64.rpm; \
yum localinstall -y perl-Geo-IP-1.38-1.el6.rf.x86_64.rpm; \
rm -rf perl-Geo-IP-1.38-1.el6.rf.x86_64.rpm;
#Install phantomjs required for export graph pdf.
RUN mkdir -p /opt/phantomjs/bin && cd /opt/phantomjs/bin; \