Index: NetBSD/pandora_server.conf.new
===================================================================
--- NetBSD/pandora_server.conf.new	(revision 0)
+++ NetBSD/pandora_server.conf.new	(revision 10417)
@@ -0,0 +1,443 @@
+#############################################################################
+# Pandora FMS Server Parameters
+# Pandora FMS, the Flexible Monitoring System.
+# Version 5.1BETA1
+# Licensed under GPL license v2,
+# (c) 2003-2014 Artica Soluciones Tecnologicas
+# http://www.pandorafms.com
+# Please change it for your setup needs
+#############################################################################
+
+# Servername: Name of this server
+# if not given, it takes hostname. It's preferable to setup one
+# because machine name could change by some reason.
+
+#servername greystone
+
+# incomingdir:  Defines directory where incoming data packets are stored
+# You could set directory relative to base path or absolute, starting with /
+
+incomingdir /var/spool/pandora/data_in
+
+# log_file: Main logfile for pandora_server
+# You could set file relative to base path or absolute, starting with /
+
+log_file /var/log/pandora/pandora_server.log
+
+# Log file for Pandora FMS SNMP console. Its generated by NetSNMP Trap daemon
+
+snmp_logfile /var/log/pandora/pandora_snmptrap.log
+
+# Error logfile: aux logfile for pandora_server errors (in Daemon mode)
+# You could set file relative to base path or absolute, starting with /
+
+errorlog_file /var/log/pandora/pandora_server.error
+
+# daemon: Runs in daemon mode (background) if 1, if 0 runs in foreground 
+# this could be also configured on commandline with -D option
+
+# daemon 1
+
+# dbengine: mysql, postgresql or oracle (mysql by default)
+
+dbengine mysql
+
+# Database credentials. A VERY important configuration.
+# This must be the same credentials used by your Pandora FMS Console
+# but could be different if your console is not running in the same
+# host than the server. Check your console setup in /include/config.php
+
+# dbname: Database name (pandora by default)
+
+dbname pandora
+
+# dbuser:  Database user name (pandora by default)
+
+dbuser pandora
+
+# dbpass: Database password
+
+dbpass pandora
+
+# dbhost: Database hostname or IP address
+
+dbhost 127.0.0.1
+
+# dbport: Database port number
+# Default value depends on the dbengine (mysql: 3306, postgresql: 5432, oracle: 1521)
+
+#dbport 3306
+
+# By default, parent agent will not be updated
+
+#update_parent 0
+
+# verbosity: level of detail on errors/messages (0 default, 1 verbose, 2 debug.... 10 noisy)
+# -v in command line (verbose) or -d (debug). Set this to 10 when try to locate problems and
+# set to 0 or 1 on production enviroments.
+
+verbosity 1
+
+# Master Server, 1 if master server (normal mode), 0 for slave mode (slave in multi-server setup)
+
+master 1
+
+# Activate Pandora SNMP console (depending on snmptrapd)
+
+snmpconsole 0
+
+# snmptrapd will ignore authenticationFailure traps if set to 1.
+
+snmp_ignore_authfailure 1
+
+# snmptrapd will read the PDU source address instead of the agent-addr field is set to 1.
+
+snmp_pdu_address 0
+
+# Activate (1) Pandora Network Server 
+
+networkserver 1
+
+# Activate (1) Pandora Data Server
+
+dataserver 1
+
+# Activate (1) Pandora FMS Recon server
+
+reconserver 1
+
+# pluginserver : 1 or 0. Set to 1 to activate plugin server with this setup
+
+pluginserver 1
+
+# Pandora FMS Plugin exec tool filepath (by default at /usr/local/bin)
+
+plugin_exec /usr/local/bin/gtimeout
+
+# predictionserver : 1 or 0. Set to 1 to activate prediction server with this setup
+# DISABLED BY DEFAULT 
+
+predictionserver 0
+
+# wmiserver : 1 or 0. Set to 1 to activate WMI server with this setup
+# DISABLED BY DEFAULT
+
+wmiserver 1
+
+# wmic: Needed by Pandora FMS wmi server.
+
+wmi_client /usr/local/bin/wmic
+
+# Network timeout (in seconds) for timeout in network connections for Network agents
+
+network_timeout 4
+
+# Server keepalive (in seconds)
+
+server_keepalive 45
+
+# Server Threshold: defines number of seconds of main loop (in sec)
+
+server_threshold 5
+
+# Network threads: Do not set too high (~40). Each threads make a network module check.
+
+network_threads 4
+
+# icmp_checks x : defines number of pings for each icmp_proc module type. at least one of 
+# that ping should be 1 to report 1. Values of 1 have more performance, but are more feasible
+# to produce false positives. 
+
+icmp_checks 3
+
+# tcp specific options :
+# tcp_checks: number of tcp retries if first attempt fails.
+# tcp_timeout: specific timeout for tcp connections
+
+tcp_checks 1
+tcp_timeout 10
+
+# snmp specific options :
+# snmp_checks: number of snmp request retries if first attempt fails.
+# snmp_timeout: specific timeout for snmp request.
+
+snmp_checks 1
+snmp_timeout 4
+
+# snmp_proc_deadresponse 1 (default): Return DOWN if cannot contact 
+# or receive NULL from a SNMP PROC module.
+
+snmp_proc_deadresponse 1
+
+# plugin_threads: Specify number of plugin server threads for processing plugin calls
+
+plugin_threads 1
+
+# plugin_timeout: Specify number of seconds calling plugin exec waiting for response
+# after this time, call is aborted and result is "unknown".
+
+plugin_timeout 12
+
+# wmi_timeout : specific timeout for wmi request.
+
+wmi_timeout 7
+
+# wmi_threads: Specify number of WMI server threads for processing WMI remote calls
+
+wmi_threads 1
+
+# recon_threads. Each thread will scan a different scantask.
+
+recon_threads 1
+
+# dataserver_threads: Number of threads for data server (XML processing threads)
+
+dataserver_threads 1
+
+# mta_address: External Mailer (MTA) IP Address to be used by Pandora FMS internal email capabilities
+
+mta_address localhost
+
+# mta_port, this is the mail server port (default 25)
+
+#mta_port 25
+
+# mta_user MTA User (if needed for auth, FQD or simple user, depending on your server)
+
+#mta_user myuser@mydomain.com
+
+# mta_pass MTA Pass (if needed for auth)
+
+#mta_pass mypassword
+
+# mta_auth MTA Auth system (if needed, it supports LOGIN, PLAIN, CRAM-MD5, DIGEST-MD)
+
+#mta_auth LOGIN
+
+# mta_from Email address that sends the mail, by default is pandora@localhost 
+#           probably you need to change it to avoid problems with your antispam
+
+#mta_from Pandora FMS <pandora@mydomain.com>
+
+# Set 1 if want eMail deliver alert in separate mail  (default).
+# Set 0 if want eMail deliver shared mail by all destination.
+mail_in_separate 1
+
+
+# xprobe2: Optional package to detect OS types using advanced TCP/IP 
+# fingerprinting tecniques, much more accurates than stadard nmap.
+# If not provided, nmap is used insted xprobe2
+
+xprobe2 /usr/local/bin/xprobe2
+
+# nmap: If provided, is used to detect OS type with recon server using 
+# advanded OS fingerprint technique. Xprobe2 gives more accurate results
+# Nmap is also used to do TCP port scanning in detected host.
+
+nmap /usr/pkg/bin/nmap
+
+# snmpget: Needed to do SNMP checks. By default is on /usr/local/bin/snmpget
+
+snmpget /usr/pkg/bin/snmpget
+
+# snmp_trapd: Needed by Pandora FMS SNMP console.
+
+snmp_trapd /usr/pkg/sbin/snmptrapd
+
+# Location of the braa binary needed by the Enterprise SNMP Server (/usr/local/bin/braa by default) (PANDORA FMS ENTERPRISE ONLY).
+
+braa /usr/local/bin/braa
+
+# Number of retries before braa hands a module over to the Network Server (PANDORA FMS ENTERPRISE ONLY).
+
+braa_retries 3
+
+# Default group id for new agents created with Pandora FMS Data Server
+
+autocreate_group 2
+
+# Set to 1 if want to autocreate agents with Pandora FMS Data Server, 
+# set to 0 to disable (for security purposes, for example).
+
+autocreate 1
+
+# max_log_size: Specify max size of Pandora FMS server log file (1MB by default). If
+# log file grows above this limit, is renamed to "pandora_server.log.old".
+
+max_log_size 65536
+
+# max_queue_files (500 by default)
+# When server have more than max_queue_files in incoming directory, skips the read   
+# the directory to avoid filesystem overhead.
+
+max_queue_files 500
+
+# Use the XML file last modification time as timestamp.
+# use_xml_timestamp 1
+
+# Pandora FMS will autorestart itself each XXX seconds, use this if you experience problems with 
+# shutting down threads, or other stability problems.
+
+# auto_restart 86400
+
+# Pandora FMS will restart after restart_delay seconds on critical errors.
+
+restart 1
+restart_delay 60
+
+# More information about GIS Setup in /usr/share/pandora_server/util/gis.README
+# Flag to activate GIS (positional information for agents and maps) 
+# by default it is desactivated
+
+#activate_gis 0
+
+# Radius of error in meters to consider two gis locations as the same location.
+
+#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).
+
+#recon_reverse_geolocation_file /usr/local/share/GeoIP/GeoIPCity.dat
+
+# Radius (in meters) of the circle in where the agents will be place randomly 
+# when finded by a recon task. Center of the circle is guessed 
+# by geolocating the IP.
+#recon_location_scatter_radius 1000
+
+# Pandora Server self-monitoring (embedded agent) (by default enabled)
+
+self_monitoring 1
+
+# Update parent from the agent xml
+
+#update_parent 1
+#
+#
+# This enable realtime reverse geocoding using Google Maps public api.
+# This requires internet access, and could have performance penalties processing GIS
+# information due the connetion needed to resolve all GIS input.
+# NOTE: If you dont pay the service to google, they will ban your IP in a few days.
+
+# google_maps_description 1
+
+# This enable realtime reverse geocoding using Openstreet Maps public api.
+# This requires internet access, and could have performance penalties processing GIS
+# information due the connetion needed to resolve all GIS input.
+# You can alter the code to use a local (your own) openstreet maps server.
+
+# openstreetmaps_description 1
+
+# Enable (1) or disable (0) Pandora FMS Event Web Server (PANDORA FMS ENTERPRISE ONLY).
+
+webserver 1
+
+# Number of threads for the Web Server (PANDORA FMS ENTERPRISE ONLY).
+
+web_threads 1
+
+# Enable (1) or disable (0) Pandora FMS Inventory Server (PANDORA FMS ENTERPRISE ONLY).
+
+inventoryserver 1
+
+# Number of threads for the Web Server (PANDORA FMS ENTERPRISE ONLY).
+
+inventory_threads 1
+
+# Enable (1) or disable (0) Pandora FMS Export Server (PANDORA FMS ENTERPRISE ONLY).
+
+exportserver 0
+
+# Number of threads for the Export Server (PANDORA FMS ENTERPRISE ONLY).
+
+export_threads 1
+
+# Enable (1) or disable (0) Pandora FMS Event Server (PANDORA FMS ENTERPRISE ONLY).
+
+eventserver 0
+
+# Event Server event window in seconds (3600 by default) (PANDORA FMS ENTERPRISE ONLY).
+
+event_window 3600
+
+# Enable (1) or disable (0) Pandora FMS Enterprise ICMP Server (PANDORA FMS ENTERPRISE ONLY).
+# You need nmap 5.20 or higher in order to use this !
+
+icmpserver 1
+
+# Number of threads for the Enterprise ICMP Server (PANDORA FMS ENTERPRISE ONLY).
+
+icmp_threads 1
+
+# Enable (1) or disable (0) Pandora FMS Enterprise SNMP Server (PANDORA FMS ENTERPRISE ONLY).
+# Check braa tool is running and operative.
+
+snmpserver 1
+
+# Number of threads for the Enterprise SNMP Server (PANDORA FMS ENTERPRISE ONLY).
+
+snmp_threads 1
+
+# Block size for block producer/consumer servers, that is, the number of modules
+# per block (20 by default) (PANDORA FMS ENTERPRISE ONLY).
+
+block_size 20
+
+# Path to the netflow daemon nfcapd.
+
+netflow_daemon /usr/pkg/bin/nfcapd
+
+# If set to 1, process XML data files in a stack instead of a queue. 0 by default.
+# WARNING: Incremental modules will not work properly if dataserver_lifo is set to 1!!!
+
+dataserver_lifo 0
+
+# If set to 1, the policy manager is enabled and the server is listening the policy queue. 
+# 0 by default (PANDORA FMS ENTERPRISE ONLY) 
+
+policy_manager 1
+
+# If set to 1, the event replicate process is enabled. 0 by default. (PANDORA FMS ENTERPRISE ONLY) 
+# WARNING: This process doesn't do anything if is not properly configured from the console setup 
+
+event_replication 0
+
+# If set to 1, new events validate older event for the same module. This will
+# affect the performance of the server. This was the "normal behaviour" on previous (4.x) versions.
+# disable only if you really know what you are doing !!.
+
+event_auto_validation 1
+
+# If defined, events generated by Pandora FMS will be written to the specified text file.
+#event_file /var/log/pandora/pandora_events.txt
+
+# Set the maximum number of traps that will be processed from a single source in a
+# configured time interval.
+snmp_storm_protection 25
+
+# Time interval for snmp_storm protection (in seconds).
+snmp_storm_timeout 10
+
+# Default texts for some events. The macros _module_ and _data_ are supported.
+#text_going_down_normal Module '_module_' is going to NORMAL (_data_)
+#text_going_up_critical Module '_module_' is going to CRITICAL (_data_)
+#text_going_up_warning Module '_module_' is going to WARNING (_data_)
+#text_going_down_warning Module '_module_' is going to WARNING (_data_)
+#text_going_unknown Module '_module_' is going to UNKNOWN
+
+# Events older that the specified time (in seconds) will be auto-validated. Set to 0 to disable this feature.
+event_expiry_time 0
+
+# Only events more recent than the specified time window (in seconds) will be auto-validated. This value must
+# be greater than event_expiry_time.
+#event_expiry_window 86400
Index: NetBSD/pandora_server.conf
===================================================================
--- NetBSD/pandora_server.conf	(revision 10314)
+++ NetBSD/pandora_server.conf	(working copy)
@@ -1,442 +0,0 @@
-#############################################################################
-# Pandora FMS Server Parameters
-# Pandora FMS, the Flexible Monitoring System.
-# Version 5.1BETA1
-# Licensed under GPL license v2,
-# (c) 2003-2014 Artica Soluciones Tecnologicas
-# http://www.pandorafms.com
-# Please change it for your setup needs
-#############################################################################
-
-# Servername: Name of this server
-# if not given, it takes hostname. It's preferable to setup one
-# because machine name could change by some reason.
-
-#servername greystone
-
-# incomingdir:  Defines directory where incoming data packets are stored
-# You could set directory relative to base path or absolute, starting with /
-
-incomingdir /var/spool/pandora/data_in
-
-# log_file: Main logfile for pandora_server
-# You could set file relative to base path or absolute, starting with /
-
-log_file /var/log/pandora/pandora_server.log
-
-# Log file for Pandora FMS SNMP console. Its generated by NetSNMP Trap daemon
-
-snmp_logfile /var/log/pandora/pandora_snmptrap.log
-
-# Error logfile: aux logfile for pandora_server errors (in Daemon mode)
-# You could set file relative to base path or absolute, starting with /
-
-errorlog_file /var/log/pandora/pandora_server.error
-
-# daemon: Runs in daemon mode (background) if 1, if 0 runs in foreground 
-# this could be also configured on commandline with -D option
-
-# daemon 1
-
-# dbengine: mysql, postgresql or oracle (mysql by default)
-
-dbengine mysql
-
-# Database credentials. A VERY important configuration.
-# This must be the same credentials used by your Pandora FMS Console
-# but could be different if your console is not running in the same
-# host than the server. Check your console setup in /include/config.php
-
-# dbname: Database name (pandora by default)
-
-dbname pandora
-
-# dbuser:  Database user name (pandora by default)
-
-dbuser pandora
-
-# dbpass: Database password
-
-dbpass pandora
-
-# dbhost: Database hostname or IP address
-
-dbhost 127.0.0.1
-
-# dbport: Database port number
-# Default value depends on the dbengine (mysql: 3306, postgresql: 5432, oracle: 1521)
-
-#dbport 3306
-
-# By default, parent agent will not be updated
-
-#update_parent 0
-
-# verbosity: level of detail on errors/messages (0 default, 1 verbose, 2 debug.... 10 noisy)
-# -v in command line (verbose) or -d (debug). Set this to 10 when try to locate problems and
-# set to 0 or 1 on production enviroments.
-
-verbosity 1
-
-# Master Server, 1 if master server (normal mode), 0 for slave mode (slave in multi-server setup)
-
-master 1
-
-# Activate Pandora SNMP console (depending on snmptrapd)
-
-snmpconsole 0
-
-# snmptrapd will ignore authenticationFailure traps if set to 1.
-
-snmp_ignore_authfailure 1
-
-# snmptrapd will read the PDU source address instead of the agent-addr field is set to 1.
-
-snmp_pdu_address 0
-
-# Activate (1) Pandora Network Server 
-
-networkserver 1
-
-# Activate (1) Pandora Data Server
-
-dataserver 1
-
-# Activate (1) Pandora FMS Recon server
-
-reconserver 1
-
-# pluginserver : 1 or 0. Set to 1 to activate plugin server with this setup
-
-pluginserver 1
-
-# Pandora FMS Plugin exec tool filepath (by default at /usr/local/bin)
-
-plugin_exec /usr/local/bin/gtimeout
-
-# predictionserver : 1 or 0. Set to 1 to activate prediction server with this setup
-# DISABLED BY DEFAULT 
-
-predictionserver 0
-
-# wmiserver : 1 or 0. Set to 1 to activate WMI server with this setup
-# DISABLED BY DEFAULT
-
-wmiserver 1
-
-# wmic: Needed by Pandora FMS wmi server.
-
-wmi_client /usr/local/bin/wmic
-
-# Network timeout (in seconds) for timeout in network connections for Network agents
-
-network_timeout 4
-
-# Server keepalive (in seconds)
-
-server_keepalive 45
-
-# Server Threshold: defines number of seconds of main loop (in sec)
-
-server_threshold 5
-
-# Network threads: Do not set too high (~40). Each threads make a network module check.
-
-network_threads 4
-
-# icmp_checks x : defines number of pings for each icmp_proc module type. at least one of 
-# that ping should be 1 to report 1
-
-icmp_checks 1
-
-# tcp specific options :
-# tcp_checks: number of tcp retries if first attempt fails.
-# tcp_timeout: specific timeout for tcp connections
-
-tcp_checks 1
-tcp_timeout 10
-
-# snmp specific options :
-# snmp_checks: number of snmp request retries if first attempt fails.
-# snmp_timeout: specific timeout for snmp request.
-
-snmp_checks 1
-snmp_timeout 4
-
-# snmp_proc_deadresponse 1 (default): Return DOWN if cannot contact 
-# or receive NULL from a SNMP PROC module.
-
-snmp_proc_deadresponse 1
-
-# plugin_threads: Specify number of plugin server threads for processing plugin calls
-
-plugin_threads 1
-
-# plugin_timeout: Specify number of seconds calling plugin exec waiting for response
-# after this time, call is aborted and result is "unknown".
-
-plugin_timeout 12
-
-# wmi_timeout : specific timeout for wmi request.
-
-wmi_timeout 7
-
-# wmi_threads: Specify number of WMI server threads for processing WMI remote calls
-
-wmi_threads 1
-
-# recon_threads. Each thread will scan a different scantask.
-
-recon_threads 1
-
-# dataserver_threads: Number of threads for data server (XML processing threads)
-
-dataserver_threads 1
-
-# mta_address: External Mailer (MTA) IP Address to be used by Pandora FMS internal email capabilities
-
-mta_address localhost
-
-# mta_port, this is the mail server port (default 25)
-
-#mta_port 25
-
-# mta_user MTA User (if needed for auth, FQD or simple user, depending on your server)
-
-#mta_user myuser@mydomain.com
-
-# mta_pass MTA Pass (if needed for auth)
-
-#mta_pass mypassword
-
-# mta_auth MTA Auth system (if needed, it supports LOGIN, PLAIN, CRAM-MD5, DIGEST-MD)
-
-#mta_auth LOGIN
-
-# mta_from Email address that sends the mail, by default is pandora@localhost 
-#           probably you need to change it to avoid problems with your antispam
-
-#mta_from Pandora FMS <pandora@mydomain.com>
-
-# Set 1 if want eMail deliver alert in separate mail  (default).
-# Set 0 if want eMail deliver shared mail by all destination.
-mail_in_separate 1
-
-
-# xprobe2: Optional package to detect OS types using advanced TCP/IP 
-# fingerprinting tecniques, much more accurates than stadard nmap.
-# If not provided, nmap is used insted xprobe2
-
-xprobe2 /usr/local/bin/xprobe2
-
-# nmap: If provided, is used to detect OS type with recon server using 
-# advanded OS fingerprint technique. Xprobe2 gives more accurate results
-# Nmap is also used to do TCP port scanning in detected host.
-
-nmap /usr/pkg/bin/nmap
-
-# snmpget: Needed to do SNMP checks. By default is on /usr/local/bin/snmpget
-
-snmpget /usr/pkg/bin/snmpget
-
-# snmp_trapd: Needed by Pandora FMS SNMP console.
-
-snmp_trapd /usr/pkg/sbin/snmptrapd
-
-# Location of the braa binary needed by the Enterprise SNMP Server (/usr/local/bin/braa by default) (PANDORA FMS ENTERPRISE ONLY).
-
-braa /usr/local/bin/braa
-
-# Number of retries before braa hands a module over to the Network Server (PANDORA FMS ENTERPRISE ONLY).
-
-braa_retries 3
-
-# Default group id for new agents created with Pandora FMS Data Server
-
-autocreate_group 2
-
-# Set to 1 if want to autocreate agents with Pandora FMS Data Server, 
-# set to 0 to disable (for security purposes, for example).
-
-autocreate 1
-
-# max_log_size: Specify max size of Pandora FMS server log file (1MB by default). If
-# log file grows above this limit, is renamed to "pandora_server.log.old".
-
-max_log_size 65536
-
-# max_queue_files (500 by default)
-# When server have more than max_queue_files in incoming directory, skips the read   
-# the directory to avoid filesystem overhead.
-
-max_queue_files 500
-
-# Use the XML file last modification time as timestamp.
-# use_xml_timestamp 1
-
-# Pandora FMS will autorestart itself each XXX seconds, use this if you experience problems with 
-# shutting down threads, or other stability problems.
-
-# auto_restart 86400
-
-# Pandora FMS will restart after restart_delay seconds on critical errors.
-
-restart 1
-restart_delay 60
-
-# More information about GIS Setup in /usr/share/pandora_server/util/gis.README
-# Flag to activate GIS (positional information for agents and maps) 
-# by default it is desactivated
-
-#activate_gis 0
-
-# Radius of error in meters to consider two gis locations as the same location.
-
-#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).
-
-#recon_reverse_geolocation_file /usr/local/share/GeoIP/GeoIPCity.dat
-
-# Radius (in meters) of the circle in where the agents will be place randomly 
-# when finded by a recon task. Center of the circle is guessed 
-# by geolocating the IP.
-#recon_location_scatter_radius 1000
-
-# Pandora Server self-monitoring (embedded agent) (by default enabled)
-
-self_monitoring 1
-
-# Update parent from the agent xml
-
-#update_parent 1
-#
-#
-# This enable realtime reverse geocoding using Google Maps public api.
-# This requires internet access, and could have performance penalties processing GIS
-# information due the connetion needed to resolve all GIS input.
-# NOTE: If you dont pay the service to google, they will ban your IP in a few days.
-
-# google_maps_description 1
-
-# This enable realtime reverse geocoding using Openstreet Maps public api.
-# This requires internet access, and could have performance penalties processing GIS
-# information due the connetion needed to resolve all GIS input.
-# You can alter the code to use a local (your own) openstreet maps server.
-
-# openstreetmaps_description 1
-
-# Enable (1) or disable (0) Pandora FMS Event Web Server (PANDORA FMS ENTERPRISE ONLY).
-
-webserver 1
-
-# Number of threads for the Web Server (PANDORA FMS ENTERPRISE ONLY).
-
-web_threads 1
-
-# Enable (1) or disable (0) Pandora FMS Inventory Server (PANDORA FMS ENTERPRISE ONLY).
-
-inventoryserver 1
-
-# Number of threads for the Web Server (PANDORA FMS ENTERPRISE ONLY).
-
-inventory_threads 1
-
-# Enable (1) or disable (0) Pandora FMS Export Server (PANDORA FMS ENTERPRISE ONLY).
-
-exportserver 0
-
-# Number of threads for the Export Server (PANDORA FMS ENTERPRISE ONLY).
-
-export_threads 1
-
-# Enable (1) or disable (0) Pandora FMS Event Server (PANDORA FMS ENTERPRISE ONLY).
-
-eventserver 0
-
-# Event Server event window in seconds (3600 by default) (PANDORA FMS ENTERPRISE ONLY).
-
-event_window 3600
-
-# Enable (1) or disable (0) Pandora FMS Enterprise ICMP Server (PANDORA FMS ENTERPRISE ONLY).
-# You need nmap 5.20 or higher in order to use this !
-
-icmpserver 1
-
-# Number of threads for the Enterprise ICMP Server (PANDORA FMS ENTERPRISE ONLY).
-
-icmp_threads 1
-
-# Enable (1) or disable (0) Pandora FMS Enterprise SNMP Server (PANDORA FMS ENTERPRISE ONLY).
-# Check braa tool is running and operative.
-
-snmpserver 1
-
-# Number of threads for the Enterprise SNMP Server (PANDORA FMS ENTERPRISE ONLY).
-
-snmp_threads 1
-
-# Block size for block producer/consumer servers, that is, the number of modules
-# per block (20 by default) (PANDORA FMS ENTERPRISE ONLY).
-
-block_size 20
-
-# Path to the netflow daemon nfcapd.
-
-netflow_daemon /usr/pkg/bin/nfcapd
-
-# If set to 1, process XML data files in a stack instead of a queue. 0 by default.
-# WARNING: Incremental modules will not work properly if dataserver_lifo is set to 1!!!
-
-dataserver_lifo 0
-
-# If set to 1, the policy manager is enabled and the server is listening the policy queue. 
-# 0 by default (PANDORA FMS ENTERPRISE ONLY) 
-
-policy_manager 1
-
-# If set to 1, the event replicate process is enabled. 0 by default. (PANDORA FMS ENTERPRISE ONLY) 
-# WARNING: This process doesn't do anything if is not properly configured from the console setup 
-
-event_replication 0
-
-# If set to 1, new events validate older event for the same module. This will
-# affect the performance of the server. This was the "normal behaviour" on previous (4.x) versions.
-# disable only if you really know what you are doing !!.
-
-event_auto_validation 1
-
-# If defined, events generated by Pandora FMS will be written to the specified text file.
-#event_file /var/log/pandora/pandora_events.txt
-
-# Set the maximum number of traps that will be processed from a single source in a
-# configured time interval.
-snmp_storm_protection 25
-
-# Time interval for snmp_storm protection (in seconds).
-snmp_storm_timeout 10
-
-# Default texts for some events. The macros _module_ and _data_ are supported.
-#text_going_down_normal Module '_module_' is going to NORMAL (_data_)
-#text_going_up_critical Module '_module_' is going to CRITICAL (_data_)
-#text_going_up_warning Module '_module_' is going to WARNING (_data_)
-#text_going_down_warning Module '_module_' is going to WARNING (_data_)
-#text_going_unknown Module '_module_' is going to UNKNOWN
-
-# Events older that the specified time (in seconds) will be auto-validated. Set to 0 to disable this feature.
-event_expiry_time 0
-
-# Only events more recent than the specified time window (in seconds) will be auto-validated. This value must
-# be greater than event_expiry_time.
-#event_expiry_window 86400
Index: conf/pandora_server.conf.new
===================================================================
--- conf/pandora_server.conf.new	(revision 10314)
+++ conf/pandora_server.conf.new	(working copy)
@@ -86,6 +86,18 @@
 
 snmpconsole 0
 
+# snmpconsole_threads: number of SNMP console threads for processing SNMP traps.
+
+snmpconsole_threads 1
+
+# Attempt to translate variable bindings when processing SNMP traps. 1 enabled, 0 disabled. 0 by default. (ENTERPRISE ONLY).
+
+translate_variable_bindings 0
+
+# Attempt to translate enterprise strings when processing SNMP traps. 1 enabled, 0 disabled. 1 by default. (ENTERPRISE ONLY).
+
+translate_enterprise_strings 0
+
 # snmptrapd will ignore authenticationFailure traps if set to 1.
 
 snmp_ignore_authfailure 1
@@ -141,9 +153,10 @@
 network_threads 4
 
 # icmp_checks x : defines number of pings for each icmp_proc module type. at least one of 
-# that ping should be 1 to report 1
+# that ping should be 1 to report 1. Setting this to 1 will make all icmp montioring faster but
+# with more probability of failure. 
 
-icmp_checks 1
+icmp_checks 3
 
 # tcp specific options :
 # tcp_checks: number of tcp retries if first attempt fails.
@@ -231,6 +244,9 @@
 
 nmap /usr/bin/nmap
 
+# A value that specifies how aggressive nmap should be from 1 to 5. 1 means slower but more reliable, 5 means faster but less reliable. 2 by default.
+nmap_timing_template 2
+
 # snmpget: Needed to do SNMP checks. By default is on /usr/bin/snmpget
 
 snmpget /usr/bin/snmpget
Index: ChangeLog
===================================================================
--- ChangeLog	(revision 10314)
+++ ChangeLog	(working copy)
@@ -1,3 +1,160 @@
+2014-08-14  Koichiro Kikuchi <koichiro@rworks.jp>
+
+	* FreeBSD/tentacle_server: Set rcvar statically.
+
+2014-08-13  Ramon Novoa  <rnovoa@artica.es>
+
+	* pandora_server.redhat.spec: Fixed some typos (packages were not
+	  being built).
+
+2014-08-12  Koichiro Kikuchi <koichiro@rworks.jp>
+
+	* bin/pandora_server: Fixed issue that pandora_server failed to
+	 shut down properly on non-Linux systems.
+
+	Merged r10335 from branch 5.0.
+
+2014-08-12  Koichiro Kikuchi <koichiro@rworks.jp>
+
+	* pandora_server_installer: Refactord implementation, added
+	"fakeroot" installation support, small bug fixes and improvements:
+	fixed processing arguments, replace "test -e" with "test -f" for portability
+	(solaris' /bin/sh doesn't support "test -e").
+
+	* Makefile.PL: Install bin/tentacle_server if WITHOUT_TENTACLE=0 so that
+	MakeMaker can fix perl path in the shebang line.
+
+	* pandora_server.redhat.spec: Added missing dependency.
+
+	* FreeBSD/pandora_server.conf -> FreeBSD/pandora_server.conf.new: Renamed
+	* NetBSD/pandora_server.conf  -> NetBSD/pandora_server.conf.new: Rename
+
+	* FreeBSD/tentacle_server: Small bug fix and improvements. Fixed
+	"tentacle_server_flags" and modified code to use proper variables and
+	to get pid more strictly.
+
+	* FreeBSD/pandora_server: Added support to start multiple pandora_server
+	instances.
+
+2014-08-12  Junichi Satoh <junichi@rworks.jp>
+
+	* lib/PandoraFMS/Core.pm, lib/PandoraFMS/DataServer.pm: Fixed sql
+	error with MySQL 5.6 and its default sql_mode.
+
+2014-08-11 Hirofumi Kosaka <kosaka@rworks.jp>
+
+	* lib/PandoraFMS/Core.pm: Fixed modules would have ignored
+	ff_threshold when the module shifted from normal to critical
+	while its status remained unknown.
+
+2014-08-07  Ramon Novoa  <rnovoa@artica.es>
+
+	* util/recon_scripts/snmp-recon.pl,
+	  util/recon_scripts/wmi-recon.pl: Set a default value
+	  for nmap_timing_template.
+
+2014-08-07  Ramon Novoa  <rnovoa@artica.es>
+
+	* conf/pandora_server.conf.new,
+	  lib/PandoraFMS/Config.pm,
+	  lib/PandoraFMS/ReconServer.pm,
+	  util/recon_scripts/snmp-recon.pl,
+	  util/recon_scripts/wmi-recon.pl: Added a new parameter to control how
+	  aggressive nmap should be.
+
+2014-08-06  Sancho Lerena <slerena@artica.es>
+
+	* NetBSD/pandora_server.conf,
+	conf/pandora_server.conf.new,
+	conf/pandora_server.conf.windows: New default value for icmp_retries
+	to have default setup more realiable but a bit slower. 
+
+2014-08-06  Alejandro Gallardo <alejandro.gallardo@artica.es>
+
+	* lib/PandoraFMS/NetworkServer.pm: Little syntax fix.
+
+	* util/pandora_revent_create.pl: Changed the url encode
+	separator of the api call from "," to "|".
+
+2014-08-06  Ramon Novoa  <rnovoa@artica.es>
+
+	* lib/PandoraFMS/NetworkServer.pm: Rewrote TCP module socket code for
+	  sending data (tcp_send). Fixes ticket #1096.
+
+2014-08-05 Hirofumi Kosaka <kosaka@rworks.jp>
+
+	* lib/PandoraFMS/Core.pm: Suppress "going to normal (warning,
+	critical)" events from "unknown" status, if you disable "Throw
+	unknown events" at the Console.
+
+2014-08-05 Hirofumi Kosaka <kosaka@rworks.jp>
+
+	* lib/PandoraFMS/Core.pm: Fixed that unknown modules would be
+	set to normal if its status is not normal, when new data
+	arrives but ff_threshold is greater than 0.
+
+2014-07-30  Ramon Novoa  <rnovoa@artica.es>
+
+	* util/trap_rate.sh: Added to repository. Script to calculate the rate of
+	  SNMP traps received by snmptrapd.
+
+2014-07-30  Ramon Novoa  <rnovoa@artica.es>
+
+	* lib/PandoraFMS/Core.pm: Set unknown modules to normal if new data
+	  arrives but ff_threshold is greater than 0.
+
+2014-07-28  Ramon Novoa  <rnovoa@artica.es>
+
+	* conf/pandora_server.conf.new,
+	  lib/PandoraFMS/Config.pm: Added configuration tokens to disable the
+	  translation of enterprise strings and variable bindings (SNMP console).
+
+	* lib/PandoraFMS/SNMPServer.pm: Added thread support to the SNMP console.
+
+	* lib/PandoraFMS/DB.pm: Fixed a warning.
+
+2014-07-25  Miguel de Dios <miguel.dedios@artica.es>
+	
+	* lib/PandoraFMS/GIS.pm, lib/PandoraFMS/DB.pm,
+	lib/PandoraFMS/Core.pm, lib/PandoraFMS/ReconServer.pm,
+	lib/PandoraFMS/DataServer.pm: tiny fixes for to improve the support
+	of PostgreSQL.
+
+2014-07-25  Junichi Satoh <junichi@rworks.jp>
+
+	* util/pandora_db.pl: Fixed error when 'dbengine' token is not defined
+	in pandora_server.conf with enterprise installed.
+
+2014-07-23  Miguel de Dios <miguel.dedios@artica.es>
+	
+	* util/plugin/snmp_remote.pl: some fixed for the snmp v3.
+
+2014-06-17  Vanessa Gil <vanessa.gil@artica.es>
+
+	* lib/PandoraFMS/Core.pm: Added macros
+	'_alert_critical_instructions_' and
+	'_alert_warning_instructions_'.
+
+2014-07-11 Hirofumi Kosaka <kosaka@rworks.jp>
+
+	* util/pandora_manage.pl: To handle multi-byte strings in
+	command line arguments (assumes utf-8).
+
+2014-07-08 Vanessa Gil <vanessa.gil@artica.es>
+	
+	* util/pandora_manage.pl: Fixed problem
+	with entities.
+
+2014-07-08 Vanessa Gil <vanessa.gil@artica.es>
+	
+	* util/pandora_manage.pl: Fixed help screen.
+
+2014-07-08 Vanessa Gil <vanessa.gil@artica.es>
+	
+	* util/pandora_manage.pl
+	  lib/PandoraFMS/Core.pm: Added 'create_data_module_from_local_component'
+	and 'create_local_component' functions to CLI.
+
 2014-06-26  Ramon Novoa  <rnovoa@artica.es>
 
 	* util/pandora_xml_stress.pl: Remove new line and carriage return
Index: Makefile.PL
===================================================================
--- Makefile.PL	(revision 10314)
+++ Makefile.PL	(working copy)
@@ -1,6 +1,12 @@
 use 5.000;
 use ExtUtils::MakeMaker;
 
+my %ARGV = map { my @r = split /=/,$_; defined $r[1] or $r[1]=1; @r } @ARGV;
+
+my @exe_files = qw(bin/pandora_server bin/pandora_exec);
+
+$ARGV{WITHOUT_TENTACLE} or push @exe_files, 'bin/tentacle_server';
+
 WriteMakefile(
 	INSTALLSITELIB  => '/usr/lib/perl5',
 	(($^O eq 'freebsd')
@@ -27,10 +33,9 @@
 		HTML::Entities => 0,
 		IO::Socket::INET6 => 0,
 		JSON => 0,
-    },
-    EXE_FILES 		=> [ 'bin/pandora_server', 'bin/pandora_exec'],
-    PMLIBDIRS  		=> [ 'lib' ],
-    'dist'		=> { 'TAR' => 'tar', 'TARFLAGS' => 'cvfz', 'SUFFIX'
-=> '.gz', 'COMPRESS' => 'gzip'}
+	},
+	EXE_FILES 		=> [ @exe_files ],
+	PMLIBDIRS  		=> [ 'lib' ],
+	'dist'		=> { 'TAR' => 'tar', 'TARFLAGS' => 'cvfz', 'SUFFIX' => '.gz', 'COMPRESS' => 'gzip'}
 );
 
Index: pandora_server_installer
===================================================================
--- pandora_server_installer	(revision 10314)
+++ pandora_server_installer	(working copy)
@@ -10,97 +10,177 @@
 
 
 MODE=$1
-SECOPT=$2
+shift
+
+# Defaults
+PREFIX=/usr
 PANDORA_SPOOL=/var/spool/pandora
-PANDORA_HOME=/usr/share/pandora_server
+PANDORA_HOME=$PREFIX/share/pandora_server
 PANDORA_CFG_DIR=/etc/pandora
 PANDORA_LOG=/var/log/pandora
 PANDORA_SERVER=/etc/init.d/pandora_server
 TENTACLE_SERVER=/etc/init.d/tentacle_serverd
-PANDORA_CFG_FILE=/etc/pandora/pandora_server.conf
+PANDORA_CFG_FILE=$PANDORA_CFG_DIR/pandora_server.conf
+PANDORA_CFG_FILE_DIST=conf/pandora_server.conf.new
+PANDORA_INIT_SCRIPT=util/pandora_server
+TENTACLE_INIT_SCRIPT=util/tentacle_serverd
+PERL=perl
+MANDIR=$PREFIX/share/man/man1
+INITDIR=/etc/init.d
+WITHOUT_TENTACLE=0
 
+#
+# set_global_vars
+#	Check platform and set DISTRO, OS_VERSION and LINUX.
+#	Also, define some platform sepcific variables (e.g. PANDORA_RC_VAR for (Free|Net)BSD) 
+#	and override some of defaults defined above if needed.
+#
+set_global_vars () {
+	# Default
+	LINUX=NO
+	OS_VERSION=`uname -r`
+	DISTRO=`uname -s`
 
-get_distro () {
-	# Get Linux Distro type and version
-	# We assume we are on Linux unless told otherwise
-	LINUX=YES
-	if [ -f "/etc/SuSE-release" ]
-	then
-		OS_VERSION=`cat /etc/SuSE-release | grep VERSION | cut -f 3 -d " "`
-		LINUX_DISTRO=SUSE
-	elif [ -f "/etc/lsb-release" ] && [ ! -f "/etc/redhat-release" ]
-	then
-		OS_VERSION=`cat /etc/lsb-release | grep DISTRIB_RELEASE | cut -f 2 -d "="`
-		LINUX_DISTRO=UBUNTU
-		OS_VERSION="UBUNTU $OS_VERSION"
-	elif [ -f "/etc/debian_version" ]
-	then
-		OS_VERSION=`cat /etc/debian_version`
-		OS_VERSION="DEBIAN $OS_VERSION"
-		LINUX_DISTRO=DEBIAN
-	elif [ -f "/etc/fedora-release" ]
-	then
-		OS_VERSION=`cat /etc/fedora-release | cut -f 4 -d " "`
-		OS_VERSION="FEDORA $OS_VERSION"
-		LINUX_DISTRO=FEDORA
-	elif [ `uname -s` = "Darwin" ]
-	then
-		# For future reference, Darwin doesn't have /etc/init.d but uses LaunchDaemons
-		LINUX_DISTRO="Darwin"
-		OS_VERSION=`uname -r`
-		LINUX=NO
-	elif [ `uname -s` = "AIX" ]
-	then
-		# For future reference, AIX doesn't have /etc/init.d
-		LINUX_DISTRO="AIX"
-		OS_VERSION=`uname -r`
-		LINUX=NO
-	elif [ `uname -s` = "SunOS" ]
-	then
+	# set corret value for LINUX_DISTRO
+	case $DISTRO in
+	Linux)
+		# Default for Linux
+		LINUX=YES
+		DISTRO="GENERIC"
+		# Get Linux Distro type and version
+		# We assume we are on Linux unless told otherwise
+		if [ -f "/etc/SuSE-release" ]
+		then
+			OS_VERSION=`cat /etc/SuSE-release | grep VERSION | cut -f 3 -d " "`
+			DISTRO=SUSE
+		elif [ -f "/etc/lsb-release" ] && [ ! -f "/etc/redhat-release" ]
+		then
+			OS_VERSION=`cat /etc/lsb-release | grep DISTRIB_RELEASE | cut -f 2 -d "="`
+			DISTRO=UBUNTU
+			OS_VERSION="UBUNTU $OS_VERSION"
+		elif [ -f "/etc/debian_version" ]
+		then
+			OS_VERSION=`cat /etc/debian_version`
+			OS_VERSION="DEBIAN $OS_VERSION"
+			DISTRO=DEBIAN
+		elif [ -f "/etc/fedora-release" ]
+		then
+			OS_VERSION=`cat /etc/fedora-release | cut -f 4 -d " "`
+			OS_VERSION="FEDORA $OS_VERSION"
+			DISTRO=FEDORA
+		fi
+		;;
+	Darwin|AIX)
+		# For future reference, Darwin doesn't have /etc/init.d but uses LaunchDaemons.
+		# AIX doesn't have /etc/init.d
+		;;
+	SunOS)
 		# Some Solaris and other Unices don't have /etc/init.d, some have /usr/spool instead of /var/spool
-		LINUX_DISTRO="Solaris"
-		OS_VERSION=`uname -r`
-		LINUX=NO
-	elif [ `uname -s` = "Linux" ]
+		DISTRO="Solaris"
+		;;
+	FreeBSD)
+		PREFIX=/usr/local
+		PANDORA_HOME=$PREFIX/share/pandora_server
+		PANDORA_CFG_DIR=$PREFIX/etc/pandora
+		PANDORA_SERVER=$PREFIX/etc/rc.d/pandora_server
+		TENTACLE_SERVER=$PREFIX/etc/rc.d/tentacle_server
+		PANDORA_CFG_FILE=$PANDORA_CFG_DIR/pandora_server.conf
+		PANDORA_CFG_FILE_DIST=$DISTRO/pandora_server.conf.new
+		PANDORA_INIT_SCRIPT=$DISTRO/pandora_server
+		TENTACLE_INIT_SCRIPT=$DISTRO/tentacle_server
+		MANDIR=$PREFIX/man/man1
+		INITDIR=$PREFIX/etc/rc.d
+		PERL=/usr/local/bin/perl
+		PANDORA_RC_VAR="pandora_server_enable"
+		TENTACLE_RC_VAR="tentacle_server_enable"
+		;;
+	NetBSD)
+		PREFIX=/usr/local
+		PANDORA_HOME=$PREFIX/share/pandora_server
+		PANDORA_CFG_DIR=$PREFIX/etc/pandora
+		PANDORA_SERVER=/etc/rc.d/pandora_server
+		TENTACLE_SERVER=/etc/rc.d/tentacle_server
+		PANDORA_CFG_FILE=$PANDORA_CFG_DIR/pandora_server.conf
+		PANDORA_CFG_FILE_DIST=$DISTRO/pandora_server.conf.new
+		PANDORA_INIT_SCRIPT=$DISTRO/pandora_server
+		TENTACLE_INIT_SCRIPT=$DISTRO/tentacle_server
+		PERL=/usr/pkg/bin/perl
+		INITDIR=/etc/rc.d
+		PANDORA_RC_VAR="pandora_server"
+		TENTACLE_RC_VAR="tentacle_server"
+		;;
+	esac
+}
+
+#
+# install_startup_script [options...] SRC
+#	copy SRC into the $INITDIR and do additional required operation according to $DISTRO
+#	if $INITDIR is not set or empty, do nothing.
+#	If $DESTDIR is set, skip enabling service
+#	OPTIONS:
+#		-s SPRIO  specify startup priority for service
+#
+install_startup_script () {
+	[ "$INITDIR" ] || return 1
+	if [ "$1" = "-s" ]
 	then
-		# Test for Linux to make sure we're on Linux
-		LINUX_DISTRO="GENERIC"
-		OS_VERSION=`uname -r`
-	elif [ `uname -s` = "FreeBSD" ]
-	then
-		LINUX_DISTRO="FreeBSD"
-		OS_VERSION=`uname -r`
-		LINUX=NO
-	elif [ `uname -s` = "NetBSD" ]
-	then
-		LINUX_DISTRO="NetBSD"
-		OS_VERSION=`uname -r`
-		LINUX=NO
-	else
-		# Default to Linux is false, test for real Linux above - that way we don't assume we can just plunk down files everywhere
-		LINUX_DISTRO=`uname -s`
-		OS_VERSION=`uname -r`
-		LINUX=NO
+		SPRIO=$2
+		shift;shift
 	fi
-	echo "$LINUX_DISTRO:$OS_VERSION:$LINUX"
+	SRC=$1
+	SCRIPT_NAME=`basename $SRC`
+
+	echo "Copying the daemon script into $INITDIR"
+	cp $SRC $DESTDIR$INITDIR
+
+	[ "$DESTDIR" ] && return
+
+	case $DISTRO in
+	UBUNTU|DEBIAN)
+		echo "Linking startup script to /etc/rc2.d"
+		update-rc.d $SCRIPT_NAME defaults
+		;;
+	SUSE)
+		echo "Creating startup daemons"
+		insserv $SCRIPT_NAME
+		;;
+	FeeBSD|NetBSD)
+		chmod 555 $DESTDIR$INITDIR/$SCRIPT_NAME
+		;;
+	*)
+		if [ "$LINUX" = YES ]
+		then
+			# Pandora FMS Server install (Other Distros)
+			INITLV=`grep '[0-9]:initdefault' /etc/inittab | cut -f 2 -d ':'`
+			: ${INITLV:=2}
+			echo "Linking startup script to /etc/rc.d/rc$INITLV.d/S$SPRIO$SCRIPT_NAME"
+			ln -s $INITDIR/$SCRIPT_NAME /etc/rc.d/rc$INITLV.d/S$SPRIO$SCRIPT_NAME
+		fi
+		;;
+	esac
 }
 
-
 install () {
+	set_global_vars
 
-	perl Makefile.PL > output 2>&1 #&& sleep 2 && cat output | grep "found" | wc -l 
+	FORCE=0
+
+	# parse options
+	while :
+	do
+		case $1 in
+		--force) FORCE=1;;
+		--no-tentacle) WITHOUT_TENTALCE=1;;
+		--destdir) DESTDIR=$2;shift;;
+		*) break;;
+		esac
+		shift
+	done
+
+	$PERL Makefile.PL INSTALLMAN1DIR=none WITHOUT_TENTACLE=$WITHOUT_TENTACLE > output 2>&1
+	#&& sleep 2 && cat output | grep "found" | wc -l 
 	DEPENDENCIAS=`cat output | grep "found" | wc -l`
 
-	FORCE=0
-
-	if [ ! -z "$SECOPT" ]
-	then
-		if [ "$SECOPT" = "--force" ]
-		then
-			FORCE=1
-		fi
-	fi
-			
 	if [ $DEPENDENCIAS -gt 0 ] && [ $FORCE -eq 0 ]
 	then
 		echo "You are missing the following dependencies"
@@ -142,448 +222,251 @@
 		echo "	$ cpan Time::Local DBI Socket6 XML::Simple XML::Twig IO::Socket Time::HiRes NetAddr::IP HTML::Entities IO::Socket::INET6 JSON"
 		echo " "
 		rm output
-	else
+		exit 1
+	fi
+	rm output
 
-		# This returns a multiple value string, separated with ":" -> $LINUX_DISTRO:$OS_VERSION:$LINUX	
-		GET_DISTRO="`get_distro`"
-		DISTRO=`echo $GET_DISTRO | cut -f 1 -d ":"`
-		OS_VERSION=`echo $GET_DISTRO | cut -f 2 -d ":"`
-		LINUX=`echo $GET_DISTRO | cut -f 3 -d ":"`	
-	
-		if [ "$DISTRO" = "UBUNTU" ]
-		then
-			echo "UBUNTU distribution detected"
-		elif [ "$DISTRO" = "SUSE" ]
-		then
-			echo "SUSE distribution detected"
-		elif [ "$DISTRO" = "FreeBSD" ]
-                then
-			echo "FreeBSD detected"
-			PANDORA_SPOOL=/var/spool/pandora
-			PANDORA_HOME=/usr/local/share/pandora_server
-			PANDORA_CFG_DIR=/usr/local/etc/pandora
-			PANDORA_LOG=/var/log/pandora
-			PANDORA_SERVER=/usr/local/etc/rc.d/pandora_server
-			TENTACLE_SERVER=/usr/local/etc/rc.d/tentacle_server
-			PANDORA_CFG_FILE=/usr/local/etc/pandora/pandora_server.conf
-		elif [ "$DISTRO" = "NetBSD" ]
-		then
-			echo "NetBSD detected"
-			PANDORA_SPOOL=/var/spool/pandora
-			PANDORA_HOME=/usr/local/share/pandora_server
-			PANDORA_CFG_DIR=/usr/local/etc/pandora
-			PANDORA_LOG=/var/log/pandora
-			PANDORA_SERVER=/etc/rc.d/pandora_server
-			TENTACLE_SERVER=/etc/rc.d/tentacle_server
-			PANDORA_CFG_FILE=/usr/local/etc/pandora/pandora_server.conf
-                
-			sed s:/usr/bin/perl:/usr/pkg/bin/perl: bin/pandora_server > bin/tmp
-			mv bin/tmp bin/pandora_server
-			sed s:/usr/bin/perl:/usr/pkg/bin/perl: bin/pandora_exec > bin/tmp
-			mv bin/tmp bin/pandora_exec
-			sed s:/usr/bin/perl:/usr/pkg/bin/perl: bin/tentacle_server > bin/tmp
-			mv bin/tmp bin/tentacle_server
-
-		fi
+	if [ "$LINUX" = YES ]
+	then
+		echo "$DISTRO distribution detected"
+	else 
+		echo "$DISTRO detected"
+	fi
 		
-		echo "Installing binaries and libraries"
-		make
-		make install
+	echo "Installing binaries and libraries"
+	make
+	make DESTDIR=$DESTDIR install
 		
-	    echo "Checking binaries at /usr/local/bin -> /usr/bin"
-		if [ ! -e "/usr/bin/pandora_server" ]
+	echo "Checking binaries at /usr/local/bin -> /usr/bin"
+	if [ ! -f "$DESTDIR/usr/bin/pandora_server" ] 
+	then
+		if [ ! -f "$DESTDIR/usr/local/bin/pandora_server" ]
 		then
-			if [ ! -e "/usr/local/bin/pandora_server" ]
-			then
-				echo "ERROR compiling Pandora FMS Server from sources. Aborting"
-				exit 1
-			fi
-			if [ "$DISTRO" != "FreeBSD" -a "$DISTRO" != "NetBSD" ]
-			then
-				ln -s /usr/local/bin/pandora_server /usr/bin
-				ln -s /usr/local/bin/pandora_exec /usr/bin		
-			fi
+			echo "ERROR compiling Pandora FMS Server from sources. Aborting"
+			exit 1
 		fi
-
-		echo "Creating common Pandora FMS directories"
-		id pandora 2> /dev/null
-		if [ $? -eq 0 ]; then
-			echo " "
-			echo "User pandora does exist, make sure the SSH directories are correct"
-		else
-			echo "Are you sure we can create a standard 'pandora' user locally? [y/N]"
-			read AREYOUSURE
-			if [ "$AREYOUSURE" = "y" ]; then
-				if [ "$DISTRO" = "FreeBSD" ]
-				then
-					echo "pandora:41121:::::Pandora FMS:/home/pandora:/usr/sbin/nologin:" | adduser -f - -w no 2> /dev/null
-				else
-					useradd pandora 
-					mkdir /home/pandora 2> /dev/null
-					mkdir /home/pandora/.ssh 2> /dev/null
-					chown -R pandora /home/pandora 
-				fi
-			else
-				echo "Please create the 'pandora' user manually according to your authentication scheme, then start again the installation"
-				echo "Aborting..."
-				exit 1
-			fi
+		if [ "$DISTRO" != "FreeBSD" ] && [ "$DISTRO" != "NetBSD" ]
+		then
+			ln -s /usr/local/bin/pandora_server $DESTDIR$PREFIX
+			ln -s /usr/local/bin/pandora_exec $DESTDIR$PREFIX
 		fi
+	fi
 
-		mkdir $PANDORA_SPOOL 2> /dev/null
-		mkdir $PANDORA_SPOOL/data_in 2> /dev/null
-		chmod 770 $PANDORA_SPOOL/data_in
-		mkdir $PANDORA_SPOOL/data_in/conf 2> /dev/null
-		chmod 770 $PANDORA_SPOOL/data_in/conf
-		mkdir $PANDORA_SPOOL/data_in/md5 2> /dev/null
-		chmod 770 $PANDORA_SPOOL/data_in/md5
-		mkdir $PANDORA_SPOOL/data_in/collections 2> /dev/null
-		chmod 770 $PANDORA_SPOOL/data_in/collections
-		mkdir $PANDORA_SPOOL/data_in/netflow 2> /dev/null
-		chmod 770 $PANDORA_SPOOL/data_in/netflow
-		mkdir $PANDORA_LOG 2> /dev/null	
-
-		echo "Giving proper permission to /var/spool/pandora"
-		IDGROUP=`id -g www-data 2> /dev/null`
-		if [ $? -eq 0 ]
-		then
-			GROUPNAME=`cat /etc/group | grep ":$IDGROUP:" | awk -F":" '{print $1}'`
-			chown -R pandora:$GROUPNAME $PANDORA_SPOOL
-		else
-			IDGROUP=`id -g wwwrun 2> /dev/null`
-			if [ $? -eq 0 ]
+	echo "Creating common Pandora FMS directories"
+	id pandora 2> /dev/null
+	if [ $? -eq 0 ]; then
+		echo " "
+		echo "User pandora does exist, make sure the SSH directories are correct"
+	elif [ "$DESTDIR" ]
+	then
+		# chown can fail with fakeroot installation
+		echo "User 'pandora' does not exist. All chown operations may fail."
+		echo "You should manualy set proper ownership to $DESTDIR$PANDORA_SPOOL if needed."
+		echo
+	else
+		echo "Are you sure we can create a standard 'pandora' user locally? [y/N]"
+		read AREYOUSURE
+		if [ "$AREYOUSURE" = "y" ]; then
+			if [ "$DISTRO" = "FreeBSD" ]
 			then
-				GROUPNAME=`cat /etc/group | grep ":$IDGROUP:" | awk -F":" '{print $1}'`
-				chown -R pandora:$GROUPNAME $PANDORA_SPOOL
+				echo "pandora:41121:::::Pandora FMS:/home/pandora:/usr/sbin/nologin:" | adduser -f - -w no 2> /dev/null
 			else
-				IDGROUP=`id -g www 2> /dev/null`
-				if [ $? -eq 0 ]
-				then
-					GROUPNAME=`cat /etc/group | grep ":$IDGROUP:" | awk -F":" '{print $1}'`
-					chown -R pandora:$GROUPNAME $PANDORA_SPOOL
-				else
-					IDGROUP=`id -g apache 2> /dev/null`
-					if [ $? -eq 0 ]
-					then
-						GROUPNAME=`cat /etc/group | grep ":$IDGROUP:" | awk -F":" '{print $1}'`
-						chown -R pandora:$GROUPNAME $PANDORA_SPOOL
-					else
-						echo "No web server user found, some functionality might not perform correctly"
-						chown -R pandora:root $PANDORA_SPOOL
-					fi
-				fi
+				useradd pandora 
+				mkdir /home/pandora 2> /dev/null
+				mkdir /home/pandora/.ssh 2> /dev/null
+				chown -R pandora /home/pandora 
 			fi
-		fi
-		
-		
-		echo "Creating setup directory in $PANDORA_CFG_DIR"
-		mkdir $PANDORA_CFG_DIR 2> /dev/null
-		if [ "$DISTRO" = "FreeBSD" ]
-		then
-			if [ -e $PANDORA_CFG_FILE ]
-			then
-				OLDFILENAMETMP=`date +"%Y-%m-%d"`
-				echo "Old installation detected, backing up pandora_server.conf.$ODFILENAMETMP"
-				mv $PANDORA_CFG_FILE $PANDORA_CFG_FILE.$OLDFILENAMETMP
-			fi
-			echo cp FreeBSD/pandora_server.conf $PANDORA_CFG_DIR
-                	cp FreeBSD/pandora_server.conf $PANDORA_CFG_DIR
-		elif [ "$DISTRO" = "NetBSD" ]
-		then
-			if [ ! -d $PANDORA_CFG_DIR ]
-			then
-				mkdir -p $PANDORA_CFG_DIR
-			fi
-			if [ -e $PANDORA_CFG_FILE ]
-			then
-				OLDFILENAMETMP=`date +"%Y-%m-%d"`
-				echo "Old installation detected, backing up pandora_server.conf.$ODFILENAMETMP"
-				mv $PANDORA_CFG_FILE $PANDORA_CFG_FILE.$OLDFILENAMETMP
-			fi
-			echo cp NetBSD/pandora_server.conf $PANDORA_CFG_DIR
-			cp NetBSD/pandora_server.conf $PANDORA_CFG_DIR     
 		else
-			if [ -f "$PANDORA_CFG_FILE" ]
-			then
-				echo cp conf/pandora_server.conf.new $PANDORA_CFG_DIR
-				cp conf/pandora_server.conf.new $PANDORA_CFG_DIR
-			else
-			echo cp conf/pandora_server.conf.new $PANDORA_CFG_FILE
-				cp conf/pandora_server.conf.new $PANDORA_CFG_FILE
-			fi
+			echo "Please create the 'pandora' user manually according to your authentication scheme, then start again the installation"
+			echo "Aborting..."
+			exit 1
 		fi
-		chmod 770 $PANDORA_CFG_FILE
+	fi
 
-		echo "Installing Pandora Server manual"
-		if [ "$DISTRO" = "FreeBSD" ]
+	mkdir -p $DESTDIR$PANDORA_SPOOL/data_in 2> /dev/null
+	chmod 770 $DESTDIR$PANDORA_SPOOL/data_in
+	mkdir $DESTDIR$PANDORA_SPOOL/data_in/conf 2> /dev/null
+	chmod 770 $DESTDIR$PANDORA_SPOOL/data_in/conf
+	mkdir $DESTDIR$PANDORA_SPOOL/data_in/md5 2> /dev/null
+	chmod 770 $DESTDIR$PANDORA_SPOOL/data_in/md5
+	mkdir $DESTDIR$PANDORA_SPOOL/data_in/collections 2> /dev/null
+	chmod 770 $DESTDIR$PANDORA_SPOOL/data_in/collections
+	mkdir $DESTDIR$PANDORA_SPOOL/data_in/netflow 2> /dev/null
+	chmod 770 $DESTDIR$PANDORA_SPOOL/data_in/netflow
+	mkdir -p $DESTDIR$PANDORA_LOG 2> /dev/null	
+
+	echo "Giving proper permission to /var/spool/pandora"
+	for group in "www-data" wwwrun www apache
+	do
+		IDGROUP=`id -g "$group" 2> /dev/null`
+		if [ $? -eq 0 ]
 		then
-			cp man/man1/pandora_server.1.gz /usr/local/man/man1
-		else
-			cp man/man1/pandora_server.1.gz /usr/share/man/man1
+			GROUPNAME=`grep ":$IDGROUP:" /etc/group | awk -F":" '{print $1}'`
+			break
 		fi
+	done
+	if [ -z "$GROUPNAME" ]
+	then
+		echo "No web server user found, some functionality might not perform correctly"
+		GROUPNAME=0
+	fi
+	# when fakeroot installation, this can fail
+	chown -R pandora:$GROUPNAME $DESTDIR$PANDORA_SPOOL 2>/dev/null
 		
-		if [ "$LINUX" = "YES" ]
-		then
-			echo "Copying the daemon script into /etc/init.d/pandora_server"
-			cp util/pandora_server /etc/init.d/		
-			
-			if [ "$DISTRO" = "UBUNTU" ] || [ "$DISTRO" = "DEBIAN" ]
-			then
-			
-				echo "Linking startup script to /etc/rc2.d"
-				update-rc.d pandora_server defaults
-			else
-				if [ "$DISTRO" = "SUSE" ]
-				then
-					echo "Creating startup daemons"
-					insserv pandora_server
-				else
-					# Pandora FMS Server install (Other Distros)
-					INITLV=`cat /etc/inittab | grep "[0-9]\:initdefault" | cut -f 2 -d ":"`
-					if [ -z "$INITLV" ]
-					then
-						INITLV=2
-					fi
-					echo "Linking startup script to /etc/rc.d/rc$INITLV.d"
-					ln -s $PANDORA_SERVER /etc/rc.d/rc$INITLV.d/S90pandora_server
-				fi
-			fi
-		else
-			if [ "$DISTRO" = "FreeBSD" ]
-			then
-				echo "Copying the daemon script into $PANDORA_SERVER"
-				cp FreeBSD/pandora_server $PANDORA_SERVER 
-				chmod 555 $PANDORA_SERVER
-                        fi
-			if [ "$DISTRO" = "NetBSD" ]
-			then
-				echo "Copying the daemon script into $PANDORA_SERVER"
-				cp NetBSD/pandora_server $PANDORA_SERVER 
-				chmod 555 $PANDORA_SERVER
-			fi
-		fi
+	echo "Creating setup directory in $PANDORA_CFG_DIR"
+	mkdir -p $DESTDIR$PANDORA_CFG_DIR 2> /dev/null
+	if [ -f "$DESTDIR$PANDORA_CFG_FILE" ]
+	then
+		echo cp $PANDORA_CFG_FILE_DIST $DESTDIR$PANDORA_CFG_DIR
+		cp $PANDORA_CFG_FILE_DIST $DESTDIR$PANDORA_CFG_DIR
+	else
+		echo cp $PANDORA_CFG_FILE_DIST $DESTDIR$PANDORA_CFG_FILE
+		cp $PANDORA_CFG_FILE_DIST $DESTDIR$PANDORA_CFG_FILE
+		chmod 770 $DESTDIR$PANDORA_CFG_FILE
+	fi
 
-		if [ -d /etc/logrotate.d ]; then
-			echo "Creating logrotate.d entry for Pandora FMS log management"
-			cp util/pandora_logrotate /etc/logrotate.d/pandora
-		else
-			echo "Please add a log rotation schedule manually to your log rotation daemon (if any)"
-		fi
+	echo "Installing Pandora Server manual"
+	cp man/man1/pandora_server.1.gz $DESTDIR$MANDIR
+
+	install_startup_script -s 90 $PANDORA_INIT_SCRIPT
+
+	if [ -d /etc/logrotate.d ]
+	then
+		[ -d $DESTDIR/etc/logrotate.d ] && mkdir -p $DESTDIR/etc/logrotate.d
+		echo "Creating logrotate.d entry for Pandora FMS log management"
+		cp util/pandora_logrotate $DESTDIR/etc/logrotate.d/pandora
+	else
+		echo "Please add a log rotation schedule manually to your log rotation daemon (if any)"
+	fi
 	
-		if [ "$LINUX" = "YES" ]
-		then
-			if [ "$SECOPT" != "--no-tentacle" ]
-			then
-				if [ "$DISTRO" = "UBUNTU" ] || [ "$DISTRO" = "DEBIAN" ]
-				then
-					# Tentacle server install (Ubuntu)
-					echo "Installing tentacle server"
-					cp bin/tentacle_server /usr/bin
-					chown pandora /usr/bin/tentacle_server
-					cp util/tentacle_serverd $TENTACLE_SERVER
-   					update-rc.d tentacle_serverd defaults
-				else
-					if [ "$DISTRO" = "SUSE" ]
-					then
-						echo "Creating Tentacle startup daemon"
-						cp bin/tentacle_server /usr/bin
-						chown pandora /usr/bin/tentacle_server
-						cp util/tentacle_serverd /etc/init.d/tentacle_serverd
-						insserv tentacle_serverd
-					else
-						# Tentacle server install (Other Distros)
-						echo "Installing tentacle server in /etc/rc.d/rc$INITLV.d/S80tentacle_serverd"
-						cp bin/tentacle_server /usr/bin
-						chown pandora /usr/bin/tentacle_server
-						cp util/tentacle_serverd /etc/init.d/tentacle_serverd
-						ln -s $TENTACLE_SERVER /etc/rc.d/rc$INITLV.d/S80tentacle_serverd
-					fi
-				fi
+	if [ $WITHOUT_TENTACLE -eq 0 ]
+	then
+		# tentacle_server is already installed by "make install"
+		install_startup_script -s 80 $TENTACLE_INIT_SCRIPT
+		
+		echo "Installing Tentacle Server manual"
+		cp man/man1/tentacle_server.1.gz $DESTDIR$MANDIR
+	fi
 
-				echo "Installing Tentacle Server manual"
-				cp man/man1/tentacle_server.1.gz /usr/share/man/man1
-			fi
-		else
-			if [ "$SECOPT" != "--no-tentacle" ]
-			then
-				if [ "$DISTRO" = "FreeBSD" ]
-				then
-					echo "Installing tentacle server"
-					cp bin/tentacle_server /usr/local/bin
-					chown pandora /usr/local/bin/tentacle_server
-					chmod 555 /usr/local/bin/tentacle_server
-					cp FreeBSD/tentacle_server $TENTACLE_SERVER
-					chmod 555 $TENTACLE_SERVER
-					echo "Installing Tentacle Server manual"
-					cp man/man1/tentacle_server.1.gz /usr/local/man/man1
-				fi
-				if [ "$DISTRO" = "NetBSD" ]
-				then
-					echo "Installing tentacle server"
-					cp bin/tentacle_server /usr/local/bin
-					chown pandora /usr/local/bin/tentacle_server
-					chmod 555 /usr/local/bin/tentacle_server
-					cp NetBSD/tentacle_server $TENTACLE_SERVER
-					chmod 555 $TENTACLE_SERVER
-					echo "Installing Tentacle Server manual"
-					cp man/man1/tentacle_server.1.gz /usr/share/man/man1
-				fi
-			fi
-		fi
+	echo "Creating Pandora FMS distribution directory in $PANDORA_HOME"
+	mkdir -p $DESTDIR$PANDORA_HOME 2> /dev/null
+	cp -R util $DESTDIR$PANDORA_HOME
+	find $DESTDIR$PANDORA_HOME -type l -delete
 
-		echo "Creating Pandora FMS distribution directory in $PANDORA_HOME"
-		mkdir $PANDORA_HOME 2> /dev/null
-		if [ ! -d $PANDORA_HOME ]
+	# install cron job
+	if [ -d /etc/cron.hourly ]
+	then
+		[ ! -d $DESTDIR/etc/cron.hourly ] && mkdir -p $DESTDIR/etc/cron.hourly
+		echo "Creating the Cron script to run Pandora DB tool each hour"
+		echo "#!/bin/bash" > $DESTDIR/etc/cron.hourly/pandora_db	
+		echo "perl $PANDORA_HOME/util/pandora_db.pl /etc/pandora/pandora_server.conf" >> /etc/cron.hourly/pandora_db	
+		chmod +x /etc/cron.hourly/pandora_db
+	elif [ "$DISTRO" = "FreeBSD" ] || [ "$DISTRO" = "NetBSD" ]
+	then
+		if [ "$DESTDIR" ]
 		then
-			mkdir -p $PANDORA_HOME
-		fi
-		cp -R util $PANDORA_HOME
-		
-		if [ -d /etc/cron.hourly ]
-		then
-			echo "Creating the Cron script to run Pandora DB tool each hour"
-			echo "#!/bin/bash" > /etc/cron.hourly/pandora_db	
-			echo "perl /usr/share/pandora_server/util/pandora_db.pl /etc/pandora/pandora_server.conf" >> /etc/cron.hourly/pandora_db	
-			chmod +x /etc/cron.hourly/pandora_db
+			echo "Skip adding cron entry for pandora_db.pl when performing fakeroot installation."
 		else
-			if [ "$DISTRO" = "FreeBSD" -o "$DISTRO" = "NetBSD" ]
+			grep pandora_db.pl /etc/crontab > /dev/null 2>&1
+			if [ $? -ne 0 ]
 			then
-				grep pandora_db.pl /etc/crontab > /dev/null 2>&1
-				if [ $? -ne 0 ]
-				then
-					echo "# Pandora FMS" >> /etc/crontab
-					echo "2	*	*	*	*	root	perl /usr/local/share/pandora_server/util/pandora_db.pl /usr/local/etc/pandora/pandora_server.conf" >> /etc/crontab
-				else
-					echo "The crontab for pandora_db.pl is already configured."
-				fi
+				echo "# Pandora FMS" >> /etc/crontab
+				echo "2	*	*	*	*	root	perl $PANDORA_HOME/util/pandora_db.pl $PANDORA_CFG_FILE" >> /etc/crontab
 			else
-				echo "You're probably not using cron for automatic scheduling. You should schedule the following command to run frequently (hourly) on your master server:"
-				echo "	perl /usr/share/pandora_server/util/pandora_db.pl /etc/pandora/pandora_server.conf"
+				echo "The crontab for pandora_db.pl is already configured."
 			fi
 		fi
-		echo
-		echo "Now you have to edit your $PANDORA_CFG_FILE file to change the database password (default is pandora) with the one set in include/config.php of your Pandora FMS Console."
-		echo "After setting password you can start your Pandora FMS Server!!"
-		rm output
+	else
+		echo "You're probably not using cron for automatic scheduling. You should schedule the following command to run frequently (hourly) on your master server:"
+		echo "	perl $PANDORA_HOME/util/pandora_db.pl $PANDORA_CFG_FILE"
+	fi
+	echo
+	echo "Now you have to edit your $PANDORA_CFG_FILE file to change the database password (default is pandora) with the one set in include/config.php of your Pandora FMS Console."
+	echo "After setting password you can start your Pandora FMS Server!!"
 
-		if [ -d "/etc/logrotate.d" ]
-		then
-			echo "Managing Pandora FMS logs with logrotate (Distro independent)"
-			cp -aRf util/pandora_logrotate /etc/logrotate.d/pandora
-		fi
+	if [ "$DISTRO" = "FreeBSD" ] || [ "$DISTRO" = "NetBSD" ]
+	then
+		echo " "
+		echo "Define '$PANDORA_RC_VAR=\"YES\"' in /etc/rc.conf to enable pandora server daemon."
+		[ "$WITHOUT_TENTACLE" = 0 ] && \
+			echo "Define '$TENTACLE_RC_VAR=\"YES\"' in /etc/rc.conf to enable tentacle server daemon."
+    fi
+}
 
-		if [ "$DISTRO" = "FreeBSD" ]
-		then
-			echo " "
-			echo "Define 'pandora_server_enable=\"YES\"' in /etc/rc.conf to enable pandora server daemon."
-			echo "Define 'tentacle_server_enable=\"YES\"' in /etc/rc.conf to enable tentacle server daemon."
-		fi
+uninstall () {
+	set_global_vars
 
-		if [ "$DISTRO" = "NetBSD" ]
-		then
-			echo " "
-			echo "Define 'pandora_server=\"YES\"' in /etc/rc.conf to enable pandora server daemon."
-			echo "Define 'tentacle_server=\"YES\"' in /etc/rc.conf to enable tentacle server daemon."
-                fi
-
+	if [ "$LINUX" != NO ] || [ "$DISTRO" != "FreeBSD" ] || [ "$DISTRO" != "NetBSD" ]
+	then
+		echo "This is not a Linux-based distro. Uninstaller is currently not working for your OS"
+		exit 1
 	fi
 
-}
-
-uninstall_bsd () {
-	if [ "$DISTRO" = "FreeBSD" ]
+	echo "Removing PERL libs and man files"
+	
+	PERL_SITELIB=/usr/lib/perl5
+	if [ "$DISTRO" != "FreeBSD" ] || [ "$DISTRO" != "NetBSD" ]
 	then
-		PANDORA_SPOOL=/var/spool/pandora
-		PANDORA_HOME=/usr/local/share/pandora_server
-		PANDORA_CFG_DIR=/usr/local/etc/pandora
-		PANDORA_LOG=/var/log/pandora
-		PANDORA_SERVER=/usr/local/etc/rc.d/pandora_server
-		TENTACLE_SERVER=/usr/local/etc/rc.d/tentacle_server
-		PANDORA_CFG_FILE=/usr/local/etc/pandora/pandora_server.conf
-		TMP_CRONTAB=/tmp/crontab.tmp
-	else
-		PANDORA_SPOOL=/var/spool/pandora
-		PANDORA_HOME=/usr/local/share/pandora_server
-		PANDORA_CFG_DIR=/usr/local/etc/pandora
-		PANDORA_LOG=/var/log/pandora
-		PANDORA_SERVER=/etc/rc.d/pandora_server
-		TENTACLE_SERVER=/etc/rc.d/tentacle_server
-		PANDORA_CFG_FILE=/usr/local/etc/pandora/pandora_server.conf
-		TMP_CRONTAB=/tmp/crontab.tmp
-        fi
+		PERL_SITELIB=$(eval $($PERL -V:sitelib);echo $sitelib);
+	fi
+	PERL_SITEMAN3DIR=`eval \`$PERL -V:siteman3dir\`;echo $siteman3dir`;
 
-	echo "Removing PERL libs"
-	rm -rf /usr/lib/perl5/PandoraFMS/
+	[ -d $DESTDIR/$PERL_SITELIB/PandoraFMS ] && rm -rf $DESTDIR/$PERL_SITELIB/PandoraFMS
+	rm -f $DESTDIR/$PERL_SITEMAN3DIR/PandoraFMS::* 2>/dev/null
 
-	echo "Removing Pandora Servers"
-	rm -Rf $PANDORA_SPOOL/data_in/
 
-	echo "If the user Pandora is not being used for any other operations, please delete using the following commands:"
-	echo "  rmuser pandora"
-
-	rm -Rf $PANDORA_LOG 2> /dev/null
-	rm -Rf $PANDORA_CFG_FILE 2> /dev/null
-	rm -Rf $PANDORA_SERVER 2> /dev/null
-	rm -Rf $PANDORA_HOME
-	rm -Rf $PANDORA_SERVER
-	rm -Rf $TENTACLE_SERVER
-
-	cat /etc/crontab | grep -v "Pandora FMS" | grep -v "pandora_db.pl" > $TMP_CRONTAB
-	cp $TMP_CRONTAB /etc/crontab
-	rm $TMP_CRONTAB
-
-	echo "Done"
-	exit
-}
-
-uninstall () {
-	GET_DISTRO="`get_distro`"
-	DISTRO=`echo $GET_DISTRO | cut -f 1 -d ":"`
-	if [ "`uname -s`" != "Linux" ]; then
-		if [ "$DISTRO" = "FreeBSD" -o "$DISTRO" = "NetBSD" ]
-		then
-			uninstall_bsd
-		else
-			echo "This is not a Linux-based distro. Uninstaller is currently not working for your OS"
-		fi
-	fi
-
-	echo "Removing PERL libs"
-	rm -rf /usr/lib/perl5/PandoraFMS/
-
 	echo "Removing Pandora Servers"
-	if [ -d $PANDORA_SPOOL/data_out ]; then
-		rm -Rf $PANDORA_SPOOL/data_in
+	if [ -d $DESTDIR$PANDORA_SPOOL/data_out ]; then
+		rm -Rf $DESTDIR$PANDORA_SPOOL/data_in
 	else
-		rm -Rf $PANDORA_SPOOL
+		rm -Rf $DESTDIR$PANDORA_SPOOL
 	fi
 
 	echo "If the user Pandora is not being used for any other operations, please delete using the following commands:"
-	echo "	userdel pandora"
-	echo "	rm -Rf /home/pandora/"
+	if [ "$DISTRO" != "FreeBSD" ] || [ "$DISTRO" != "NetBSD" ]
+	then
+		echo "  rmuser pandora"
+	else
+		echo "	userdel pandora"
+		echo "	rm -Rf /home/pandora/"
+	fi
 
 	## Just to clarify here. Some people (like me) are using the pandora user 
 	## for other purposes and/or using an LDAP-based user management
 	## I would hate to have a script clear out this users' information without any notification
 
-	rm -Rf $PANDORA_LOG 2> /dev/null 
-	rm -Rf $PANDORA_CFG_FILE 2> /dev/null
-	rm -Rf "$PANDORA_CFG_FILE.new" 2> /dev/null
-	rm -Rf $PANDORA_SERVER 2> /dev/null 
-	rm -Rf /usr/bin/pandora_server 2> /dev/null
-	rm -Rf /usr/bin/pandora_exec 2> /dev/null
-	rm -Rf $PANDORA_HOME
-	rm -Rf /etc/cron.hourly/pandora_db
-	rm -Rf /etc/logrotate.d/pandora
-	if [ "$DISTRO" = "UBUNTU" ] || [ "$DISTRO" = "DEBIAN" ]
+
+	rm -Rf $DESTDIR$PANDORA_LOG 2> /dev/null 
+	rm -f  $DESTDIR$PANDORA_CFG_FILE 2> /dev/null
+	rm -f  "$DESTDIR$PANDORA_CFG_FILE.new" 2> /dev/null
+	rm -f  $DESTDIR$PANDORA_SERVER 2> /dev/null 
+	rm -f  $DESTDIR$PREFIX/bin/pandora_server 2> /dev/null
+	rm -f  $DESTDIR$PREFIX/bin/pandora_exec 2> /dev/null
+	rm -f  $DESTDIR$PREFIX/bin/tentacle_server 2> /dev/null
+	rm -Rf $DESTDIR$PANDORA_HOME
+	rm -f  $DESTDIR/etc/cron.hourly/pandora_db
+	rm -f  $DESTDIR/etc/logrotate.d/pandora
+	if [ "$DESTDIR" ]
 	then
+		# do nothing with "fakeroot" uninstallation
+		:
+	elif [ "$DISTRO" = "UBUNTU" ] || [ "$DISTRO" = "DEBIAN" ]
+	then
 		update-rc.d -f pandora_server remove
 		update-rc.d -f tentacle_serverd remove
+	elif  [ "$DISTRO" != "FreeBSD" ] || [ "$DISTRO" != "NetBSD" ]
+	then
+		TMP_CRONTAB=/tmp/crontab.tmp
+		egrep -v "Pandora FMS|pandora_db.pl" /etc/crontab > $TMP_CRONTAB
+		cp $TMP_CRONTAB /etc/crontab
+		rm $TMP_CRONTAB
 	fi
-	rm -Rf /etc/rc2.d/S90pandora_server 2> /dev/null 
-	rm -Rf /etc/rc.d/rc3.d/S90pandora_server 2> /dev/null 
-	rm -Rf /usr/share/man/man1/pandora_server.1.gz 2>/dev/null
-	rm -Rf /usr/share/man/man1/tentacle_server.1.gz 2>/dev/null
+	rm -f $DESTDIR/etc/rc2.d/S90pandora_server 2> /dev/null 
+	rm -f $DESTDIR/etc/rc.d/rc3.d/S90pandora_server 2> /dev/null 
+	rm -f $DESTDIR/etc/rc2.d/S80tentacle_serverd 2> /dev/null 
+	rm -f $DESTDIR/etc/rc.d/rc3.d/S80tentacle_serverd 2> /dev/null 
+	rm -f $DESTDIR$MANDIR/pandora_server.1.gz 2>/dev/null
+	rm -f $DESTDIR$MANDIR/tentacle_server.1.gz 2>/dev/null
 	echo "Done"
 }
 
@@ -595,24 +478,25 @@
 	echo " "
 	echo "  --force         Ignore dependency problems and do the install"
 	echo "	--no-tentacle	Skip tentacle server installation (by default tentacle server installed)"
+	echo "	--destdir DIR	Specify root directory for \"fakeroot\" installation"
 	echo " "
 }
 
 # Script banner at start
 echo " "
-echo "Pandora FMS 5.0 Server Installer (c) 2008-2013 Artica ST"
+echo "Pandora FMS 5.1 Server Installer (c) 2008-2014 Artica ST"
 echo "This program is licensed under GPL2 Terms. http://pandorafms.com"
 echo " "
 
 case "$MODE" in
 
 '--install')
-	install
+	install "$@"
 	exit
 	;;
 
 '--uninstall')
-	uninstall
+	uninstall "$@"
 	exit
 	;;
 
Index: lib/PandoraFMS/SNMPServer.pm
===================================================================
--- lib/PandoraFMS/SNMPServer.pm	(revision 10314)
+++ lib/PandoraFMS/SNMPServer.pm	(working copy)
@@ -25,6 +25,7 @@
 use Thread::Semaphore;
 
 use Time::Local;
+use Time::HiRes qw(usleep);
 use XML::Simple;
 
 # Default lib dir for RPM and DEB packages
@@ -33,21 +34,27 @@
 use PandoraFMS::Tools;
 use PandoraFMS::DB;
 use PandoraFMS::Core;
-use PandoraFMS::Server;
+use PandoraFMS::ProducerConsumerServer;
 
-# Inherits from PandoraFMS::Server
-our @ISA = qw(PandoraFMS::Server);
+# Inherits from PandoraFMS::ProducerConsumerServer
+our @ISA = qw(PandoraFMS::ProducerConsumerServer);
 
-# Tells the server to keep running
-my $RUN :shared;
+# Global variables
+my @TaskQueue :shared;
+my %PendingTasks :shared;
+my $Sem :shared;
+my $TaskSem :shared;
 
 # Trap statistics by agent
 my %AGENTS = ();
 
+# Index file management
+my ($IDX_FILE, $LAST_LINE, $LAST_SIZE) = ();
+
 ########################################################################################
 # SNMP Server class constructor.
 ########################################################################################
-sub new ($$;$) {
+sub new ($$$) {
 	my ($class, $config, $dbh) = @_;
 
 	return undef unless $config->{'snmpconsole'} == 1;
@@ -57,15 +64,46 @@
 		return undef;
 	}
 	
+	# Wait for the SNMP log file to be available
+	my $log_file = $config->{'snmp_logfile'};
+	sleep ($config->{'server_threshold'}) if (! -e $log_file);
+	if (!open (SNMPLOGFILE, $log_file)) {
+		logger ($config, ' [E] Could not open the SNMP log file ' . $config->{'snmp_logfile'} . ".", 1);
+		print_message ($config, ' [E] Could not open the SNMP log file ' . $config->{'snmp_logfile'} . ".", 1);
+		return 1;
+	}
+
+	# Process index file, if available
+	($IDX_FILE, $LAST_LINE, $LAST_SIZE) = ($log_file . '.index', 0, 0);
+	if (-e  $IDX_FILE) {
+		open (INDEXFILE, $IDX_FILE) or return;
+		my $idx_data = <INDEXFILE>;
+		close INDEXFILE;
+		($LAST_LINE, $LAST_SIZE) = split(/\s+/, $idx_data);
+	}
+	my $log_size = (stat ($log_file))[7];
+
+	# New SNMP log file found
+	if ($log_size < $LAST_SIZE) {
+		unlink ($IDX_FILE);
+		($LAST_LINE, $LAST_SIZE) = (0, 0);
+	}
+
+	# Skip already processed lines
+	readline SNMPLOGFILE for (1..$LAST_LINE);
+	
+	# Initialize semaphores and queues
+	@TaskQueue = ();
+	%PendingTasks = ();
+	$Sem = Thread::Semaphore->new;
+	$TaskSem = Thread::Semaphore->new (0);
+
 	# Call the constructor of the parent class
-	my $self = $class->SUPER::new($config, 2, $dbh);
+	my $self = $class->SUPER::new($config, 2, \&PandoraFMS::SNMPServer::data_producer, \&PandoraFMS::SNMPServer::data_consumer, $dbh);
 
 	# Save the path of snmptrapd
 	$self->{'snmp_trapd'} = $config->{'snmp_trapd'};
 
-	# Run!
-	$RUN = 1;
-
     bless $self, $class;
     return $self;
 }
@@ -77,242 +115,219 @@
 	my $self = shift;
 	my $pa_config = $self->getConfig ();
 
-	print_message ($pa_config, " [*] Starting Pandora FMS SNMP Console.", 1);
-	$self->SUPER::run (\&PandoraFMS::SNMPServer::pandora_snmptrapd);
+	print_message ($pa_config, " [*] Starting Pandora FMS SNMP Console.", 2);
+	
+	# Set the initial date for storm protection.
+	$pa_config->{"__storm_ref__"} = time();
+
+	# This is the only server that reads from disk instead of from the DB. No need for a higher server threshold.
+	$pa_config->{'server_threshold'} = 1;
+
+	$self->setNumThreads ($pa_config->{'snmpconsole_threads'});
+	$self->SUPER::run (\@TaskQueue, \%PendingTasks, $Sem, $TaskSem);
 }
 
-##########################################################################
-# Process SNMP log file.
-##########################################################################
-sub pandora_snmptrapd {
+###############################################################################
+# Data producer.
+###############################################################################
+sub data_producer ($) {
 	my $self = shift;
-	my $pa_config = $self->getConfig ();
+	my ($pa_config, $dbh) = ($self->getConfig (), $self->getDBH ());
 
-	my $dbh;
-	eval {
-		# Connect to the DB
-		$dbh = db_connect ($pa_config->{'dbengine'}, $pa_config->{'dbname'}, $pa_config->{'dbhost'},
-							  $pa_config->{'dbport'}, $pa_config->{'dbuser'}, $pa_config->{'dbpass'});
-		$self->setDBH ($dbh);
+	my @tasks;
+	
+	# Slave server
+	if ($pa_config->{'pandora_master'} == 0 && get_db_value ($dbh, 'SELECT name FROM tserver WHERE name = ANY(SELECT name FROM tserver WHERE status = 0)') == undef) {
+		return @tasks;
+	}
 
-		# Wait for the SNMP log file to be available
-		my $log_file = $pa_config->{'snmp_logfile'};
-		sleep ($pa_config->{'server_threshold'}) while (! -e $log_file);	
-		open (SNMPLOGFILE, $log_file) or return;
+	# Reset storm protection counters
+	my $curr_time = time ();
+	if ($pa_config->{"__storm_ref__"} + $pa_config->{"snmp_storm_timeout"} < $curr_time) {
+		$pa_config->{"__storm_ref__"} = $curr_time;
+		%AGENTS = ();
+	}
 
-		# Process index file, if available
-		my ($idx_file, $last_line, $last_size) = ($log_file . '.index', 0, 0);
-		if (-e  $idx_file) {
-			open (INDEXFILE, $idx_file) or return;
-			my $idx_data = <INDEXFILE>;
-			close INDEXFILE;
-			($last_line, $last_size) = split(/\s+/, $idx_data);
-		}
+	while (my $line = <SNMPLOGFILE>) {
+		$LAST_LINE++;
+		$LAST_SIZE = (stat ($pa_config->{'snmp_logfile'}))[7];
+		chomp ($line);
 
-		my $log_size = (stat ($log_file))[7];
+		# Update index file
+		open INDEXFILE, '>' . $IDX_FILE;
+		print INDEXFILE $LAST_LINE . ' ' . $LAST_SIZE;
+		close INDEXFILE;
 
-		# New SNMP log file found
-		if ($log_size < $last_size) {
-			unlink ($idx_file);
-			($last_line, $last_size) = (0, 0);
+		# Skip lines other than SNMP Trap logs
+		next unless ($line =~ m/^SNMPv[12]\[\*\*\]/);
+
+		# Storm protection.
+		my ($ver, $date, $time, $source, $null) = split(/\[\*\*\]/, $line, 5);
+		next unless defined ($source);
+		if (! defined ($AGENTS{$source})) {
+			$AGENTS{$source}{'count'} = 1;
+			$AGENTS{$source}{'event'} = 0;
+		} else {
+			$AGENTS{$source}{'count'} += 1;
 		}
-
-		# Skip already processed lines
-		readline SNMPLOGFILE for (1..$last_line);
-
-		# Main loop
-		my $storm_ref = time ();
-		while ($RUN == 1) {
-			
-			# Reset storm protection counters
-			my $curr_time = time ();
-			if ($storm_ref + $pa_config->{"snmp_storm_timeout"} < $curr_time) {
-				$storm_ref = $curr_time;
-				%AGENTS = ();
+		if ($pa_config->{'snmp_storm_protection'} > 0 && $AGENTS{$source}{'count'} > $pa_config->{'snmp_storm_protection'}) {
+			if ($AGENTS{$source}{'event'} == 0) {
+				pandora_event ($pa_config, "Too many traps coming from $source. Silenced for " . int ($pa_config->{"snmp_storm_timeout"} / 60) . " minutes.", 0, 0, 4, 0, 0, 'system', 0, $dbh);
 			}
+			$AGENTS{$source}{'event'} = 1;
+			next;
+		}
 
-			while (my $line = <SNMPLOGFILE>) {
-				$last_line++;
-				$last_size = (stat ($log_file))[7];
-				chomp ($line);
+		push (@tasks, $line);
+	}
 
-				# Update index file
-				open INDEXFILE, '>' . $idx_file;
-				print INDEXFILE $last_line . ' ' . $last_size;
-				close INDEXFILE;
+	return @tasks;
+}
 
-				# Skip lines other than SNMP Trap logs
-				next unless ($line =~ m/^SNMPv[12]\[\*\*\]/);
+###############################################################################
+# Data consumer.
+###############################################################################
+sub data_consumer ($$) {
+	my ($self, $task) = @_;
 
-				(my $trap_ver, $line) = split(/\[\*\*\]/, $line, 2);
+	pandora_snmptrapd ($self->getConfig (), $task, $self->getServerID (), $self->getDBH ());
+}
 
-				# Process SNMP filter
-				next if (matches_filter ($dbh, $pa_config, $line) == 1);
+##########################################################################
+# Process SNMP log file.
+##########################################################################
+sub pandora_snmptrapd {
+	my ($pa_config, $line, $server_id, $dbh) = @_;
 
-				logger($pa_config, "Reading trap '$line'", 10);
-				my ($date, $time, $source, $oid, $type, $type_desc, $value, $data) = ('', '', '', '', '', '', '', '');
+	(my $trap_ver, $line) = split(/\[\*\*\]/, $line, 2);
 
-				if ($trap_ver eq "SNMPv1") {
-					($date, $time, $source, $oid, $type, $type_desc, $value, $data) = split(/\[\*\*\]/, $line, 8);
+	# Process SNMP filter
+	next if (matches_filter ($dbh, $pa_config, $line) == 1);
 
-					$value = limpia_cadena ($value);
+	logger($pa_config, "Reading trap '$line'", 10);
+	my ($date, $time, $source, $oid, $type, $type_desc, $value, $data) = ('', '', '', '', '', '', '', '');
 
-					# Try to save as much information as possible if the trap could not be parsed
-					$oid = $type_desc if ($oid eq '' || $oid eq '.');
+	if ($trap_ver eq "SNMPv1") {
+		($date, $time, $source, $oid, $type, $type_desc, $value, $data) = split(/\[\*\*\]/, $line, 8);
 
-				} elsif ($trap_ver eq "SNMPv2") {
-					($date, $time, $source, $data) = split(/\[\*\*\]/, $line, 4);
-					my @data = split(/\t/, $data);
+		$value = limpia_cadena ($value);
 
-					shift @data; # Drop unused 1st data.
-					$oid = shift @data;
+		# Try to save as much information as possible if the trap could not be parsed
+		$oid = $type_desc if ($oid eq '' || $oid eq '.');
 
-					if (!defined($oid)) {
-						logger($pa_config, "[W] snmpTrapOID not found (Illegal SNMPv2 trap?)", 1);
-						next;
-					}
-					$oid =~ s/.* = OID: //;
-					$data = join("\t", @data);
-				}
+	} elsif ($trap_ver eq "SNMPv2") {
+		($date, $time, $source, $data) = split(/\[\*\*\]/, $line, 4);
+		my @data = split(/\t/, $data);
 
-				if ($trap_ver eq "SNMPv2" || $pa_config->{'snmp_pdu_address'} eq '1' ) {
-					# extract IP address from %b part:
-					#  * destination part (->[dest_ip]:dest_port) appears in Net-SNMP > 5.3
-					#  * protocol name (TCP: or UDP:) and bracketted IP addr w/ port number appear in
-					#    Net-SNMP > 5.1 (Net-SNMP 5.1 has IP addr only).
-					#  * port number is signed (often negative) in Net-SNMP 5.2
-					$source =~ s/(?:(?:TCP|UDP):\s*)?\[?([^] ]+)\]?(?::-?\d+)?(?:\s*->.*)?$/$1/;
-				}
+		shift @data; # Drop unused 1st data.
+		$oid = shift @data;
 
-				my $timestamp = $date . ' ' . $time;
-				my ($custom_oid, $custom_type, $custom_value) = ('', '', '');
+		if (!defined($oid)) {
+			logger($pa_config, "[W] snmpTrapOID not found (Illegal SNMPv2 trap?)", 1);
+			next;
+		}
+		$oid =~ s/.* = OID: //;
+		$data = join("\t", @data);
+	}
 
-				# custom_type, custom_value is not used since 4.0 version, all custom data goes on custom_oid
-				$custom_oid = $data;
+	if ($trap_ver eq "SNMPv2" || $pa_config->{'snmp_pdu_address'} eq '1' ) {
+		# extract IP address from %b part:
+		#  * destination part (->[dest_ip]:dest_port) appears in Net-SNMP > 5.3
+		#  * protocol name (TCP: or UDP:) and bracketted IP addr w/ port number appear in
+		#    Net-SNMP > 5.1 (Net-SNMP 5.1 has IP addr only).
+		#  * port number is signed (often negative) in Net-SNMP 5.2
+		$source =~ s/(?:(?:TCP|UDP):\s*)?\[?([^] ]+)\]?(?::-?\d+)?(?:\s*->.*)?$/$1/;
+	}
 
-				# Storm protection
-				if (! defined ($AGENTS{$source})) {
-					$AGENTS{$source}{'count'} = 1;
-					$AGENTS{$source}{'event'} = 0;
-				} else {
-					$AGENTS{$source}{'count'} += 1;
-				}
-				if ($pa_config->{'snmp_storm_protection'} > 0 && $AGENTS{$source}{'count'} > $pa_config->{'snmp_storm_protection'}) {
-					if ($AGENTS{$source}{'event'} == 0) {
-						pandora_event ($pa_config, "Too many traps coming from $source. Silenced for " . int ($pa_config->{"snmp_storm_timeout"} / 60) . " minutes.", 0, 0, 4, 0, 0, 'system', 0, $dbh);
-					}
-					$AGENTS{$source}{'event'} = 1;
-					next;
-				}
+	my $timestamp = $date . ' ' . $time;
+	my ($custom_oid, $custom_type, $custom_value) = ('', '', '');
 
-				#Trap forwarding
-				if ($pa_config->{'snmp_forward_trap'}==1) {
-					my $trap_data_string = "";
+	# custom_type, custom_value is not used since 4.0 version, all custom data goes on custom_oid
+	$custom_oid = $data;
 
-					#We loop through all the custom data of the received trap, creating the $trap_data_string string to forward the trap properly
-					while ($data =~ /([\.\d]+)\s=\s([^:]+):\s([\S ]+)/g) {
-						my ($trap_data, $trap_type, $trap_value) = ($1, $2, $3);
-						if ($trap_type eq "INTEGER") {
-							#FIX for translated traps from IF-MIB.txt MIB
-							$trap_value =~ s/\D//g;
-							$trap_data_string = $trap_data_string . "$trap_data i $trap_value ";
-						}
-						elsif ($trap_type eq "UNSIGNED"){
-							$trap_data_string = $trap_data_string . "$trap_data u $trap_value ";
-						}
-                                                elsif ($trap_type eq "COUNTER32"){
-                                                        $trap_data_string = $trap_data_string . "$trap_data c $trap_value ";
-                                                }
-                                                elsif ($trap_type eq "STRING"){
-                                                        $trap_data_string = $trap_data_string . "$trap_data s $trap_value ";
-                                                }
-                                                elsif ($trap_type eq "HEX STRING"){
-                                                        $trap_data_string = $trap_data_string . "$trap_data x $trap_value ";
-                                                }
-                                                elsif ($trap_type eq "DECIMAL STRING"){
-                                                        $trap_data_string = $trap_data_string . "$trap_data d $trap_value ";
-                                                }
-                                                elsif ($trap_type eq "NULLOBJ"){
-                                                        $trap_data_string = $trap_data_string . "$trap_data n $trap_value ";
-                                                }
-                                                elsif ($trap_type eq "OBJID"){
-                                                        $trap_data_string = $trap_data_string . "$trap_data o $trap_value ";
-                                                }
-                                                elsif ($trap_type eq "TIMETICKS"){
-                                                        $trap_data_string = $trap_data_string . "$trap_data t $trap_value ";
-                                                }
-                                                elsif ($trap_type eq "IPADDRESS"){
-                                                        $trap_data_string = $trap_data_string . "$trap_data a $trap_value ";
-                                                }
-						elsif ($trap_type eq "BITS"){
-                                                        $trap_data_string = $trap_data_string . "$trap_data b $trap_value ";
-                                                }
-					}
+	#Trap forwarding
+	if ($pa_config->{'snmp_forward_trap'}==1) {
+		my $trap_data_string = "";
 
-					#We distinguish between the three different kinds of SNMP forwarding
-					if ($pa_config->{'snmp_forward_version'} eq '3') {
-						system("snmptrap -v $pa_config->{'snmp_forward_version'} -n \"\" -a $pa_config->{'snmp_forward_authProtocol'} -A $pa_config->{'snmp_forward_authPassword'} -x $pa_config->{'snmp_forward_privProtocol'} -X $pa_config->{'snmp_forward_privPassword'} -l $pa_config->{'snmp_forward_secLevel'} -u $pa_config->{'snmp_forward_secName'} -e $pa_config->{'snmp_forward_engineid'} $pa_config->{'snmp_forward_ip'} '' $oid $trap_data_string");
-					}
-					elsif ($pa_config->{'snmp_forward_version'} eq '2' || $pa_config->{'snmp_forward_version'} eq '2c') {
-						system("snmptrap -v 2c -n \"\" -c $pa_config->{'snmp_forward_community'} $pa_config->{'snmp_forward_ip'} '' $oid $trap_data_string");
-					}
-					elsif ($pa_config->{'snmp_forward_version'} eq '1') {
-						#Because of tne SNMP v1 protocol, we must perform additional steps for creating the trap
-						my $value_sending = "";
-						my $type_sending = "";
+		#We loop through all the custom data of the received trap, creating the $trap_data_string string to forward the trap properly
+		while ($data =~ /([\.\d]+)\s=\s([^:]+):\s([\S ]+)/g) {
+			my ($trap_data, $trap_type, $trap_value) = ($1, $2, $3);
+			if ($trap_type eq "INTEGER") {
+				#FIX for translated traps from IF-MIB.txt MIB
+				$trap_value =~ s/\D//g;
+				$trap_data_string = $trap_data_string . "$trap_data i $trap_value ";
+			}
+			elsif ($trap_type eq "UNSIGNED"){
+				$trap_data_string = $trap_data_string . "$trap_data u $trap_value ";
+			}
+			elsif ($trap_type eq "COUNTER32"){
+			        $trap_data_string = $trap_data_string . "$trap_data c $trap_value ";
+			}
+			elsif ($trap_type eq "STRING"){
+			        $trap_data_string = $trap_data_string . "$trap_data s $trap_value ";
+			}
+			elsif ($trap_type eq "HEX STRING"){
+			        $trap_data_string = $trap_data_string . "$trap_data x $trap_value ";
+			}
+			elsif ($trap_type eq "DECIMAL STRING"){
+			        $trap_data_string = $trap_data_string . "$trap_data d $trap_value ";
+			}
+			elsif ($trap_type eq "NULLOBJ"){
+			        $trap_data_string = $trap_data_string . "$trap_data n $trap_value ";
+			}
+			elsif ($trap_type eq "OBJID"){
+			        $trap_data_string = $trap_data_string . "$trap_data o $trap_value ";
+			}
+			elsif ($trap_type eq "TIMETICKS"){
+			        $trap_data_string = $trap_data_string . "$trap_data t $trap_value ";
+			}
+			elsif ($trap_type eq "IPADDRESS"){
+			        $trap_data_string = $trap_data_string . "$trap_data a $trap_value ";
+			}
+			elsif ($trap_type eq "BITS"){
+			        $trap_data_string = $trap_data_string . "$trap_data b $trap_value ";
+			}
+		}
 
-						if ($value eq ''){
-							$value_sending = "\"\"";
-						}
-						else {
-							$value_sending = $value;
-							$value_sending =~ s/[\$#@~!&*()\[\];.,:?^ `\\\/]+//g;
-						}
-						if ($type eq ''){
-							$type_sending = "\"\"";
-						}
-						else{
-							$type_sending = $type;
-						}
+		#We distinguish between the three different kinds of SNMP forwarding
+		if ($pa_config->{'snmp_forward_version'} eq '3') {
+			system("snmptrap -v $pa_config->{'snmp_forward_version'} -n \"\" -a $pa_config->{'snmp_forward_authProtocol'} -A $pa_config->{'snmp_forward_authPassword'} -x $pa_config->{'snmp_forward_privProtocol'} -X $pa_config->{'snmp_forward_privPassword'} -l $pa_config->{'snmp_forward_secLevel'} -u $pa_config->{'snmp_forward_secName'} -e $pa_config->{'snmp_forward_engineid'} $pa_config->{'snmp_forward_ip'} '' $oid $trap_data_string");
+		}
+		elsif ($pa_config->{'snmp_forward_version'} eq '2' || $pa_config->{'snmp_forward_version'} eq '2c') {
+			system("snmptrap -v 2c -n \"\" -c $pa_config->{'snmp_forward_community'} $pa_config->{'snmp_forward_ip'} '' $oid $trap_data_string");
+		}
+		elsif ($pa_config->{'snmp_forward_version'} eq '1') {
+			#Because of tne SNMP v1 protocol, we must perform additional steps for creating the trap
+			my $value_sending = "";
+			my $type_sending = "";
 
-						system("snmptrap -v 1 -c $pa_config->{'snmp_forward_community'} $pa_config->{'snmp_forward_ip'} $oid \"\" $type_sending $value_sending \"\" $trap_data_string");
-					}
-				}
+			if ($value eq ''){
+				$value_sending = "\"\"";
+			}
+			else {
+				$value_sending = $value;
+				$value_sending =~ s/[\$#@~!&*()\[\];.,:?^ `\\\/]+//g;
+			}
+			if ($type eq ''){
+				$type_sending = "\"\"";
+			}
+			else{
+				$type_sending = $type;
+			}
 
-				# Insert the trap into the DB
-				if (! defined(enterprise_hook ('snmp_insert_trap', [$pa_config, $source, $oid, $type, $value, $custom_oid, $custom_value, $custom_type, $timestamp, $self->getServerID (), $dbh]))) {
-					my $trap_id = db_insert ($dbh, 'id_trap', 'INSERT INTO ttrap (timestamp, source, oid, type, value, oid_custom, value_custom,  type_custom) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
-											 $timestamp, $source, $oid, $type, $value, $custom_oid, $custom_value, $custom_type);
-					logger ($pa_config, "Received SNMP Trap from $source", 4);
-
-					# Evaluate alerts for this trap
-					pandora_evaluate_snmp_alerts ($pa_config, $trap_id, $source, $oid, $type, $oid, $value, $custom_oid, $dbh);
-				}
-			}
-			
-			sleep ($pa_config->{'server_threshold'});
+			system("snmptrap -v 1 -c $pa_config->{'snmp_forward_community'} $pa_config->{'snmp_forward_ip'} $oid \"\" $type_sending $value_sending \"\" $trap_data_string");
 		}
-	};
-
-	if ($@) {
-		$self->setErrStr ($@);
 	}
 
-	db_disconnect ($dbh);
-}
+	# Insert the trap into the DB
+	if (! defined(enterprise_hook ('snmp_insert_trap', [$pa_config, $source, $oid, $type, $value, $custom_oid, $custom_value, $custom_type, $timestamp, $server_id, $dbh]))) {
+		my $trap_id = db_insert ($dbh, 'id_trap', 'INSERT INTO ttrap (timestamp, source, oid, type, value, oid_custom, value_custom,  type_custom) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
+								 $timestamp, $source, $oid, $type, $value, $custom_oid, $custom_value, $custom_type);
+		logger ($pa_config, "Received SNMP Trap from $source", 4);
 
-########################################################################################
-# Stop the server, killing snmptrapd before.
-########################################################################################
-sub stop () {
-	my $self = shift;
-
-	if ($self->{'snmp_trapd'} ne 'manual') {
-		system ("kill -9 `cat /var/run/pandora_snmptrapd.pid 2>$DEVNULL`");
-		unlink ('/var/run/pandora_snmptrapd.pid');
+		# Evaluate alerts for this trap
+		pandora_evaluate_snmp_alerts ($pa_config, $trap_id, $source, $oid, $type, $oid, $value, $custom_oid, $dbh);
 	}
-	
-	$self->SUPER::stop ();
 }
 
 ########################################################################################
@@ -328,14 +343,14 @@
 		my $eval_result;
 
 		# eval protects against server down (by invalid regular expressions)
-                $eval_result = eval {
+	    $eval_result = eval {
 		     $string =~ m/$regexp/i ;
      	        };
 
-                if ($eval_result) {
-                        logger($pa_config, "Trap '$string' matches filter '$regexp'. Discarding...", 10);
-                        return 1;
-                }
+	    if ($eval_result) {
+		logger($pa_config, "Trap '$string' matches filter '$regexp'. Discarding...", 10);
+		return 1;
+	    }
 
 	}
 	
@@ -393,7 +408,7 @@
 		print_message ($config, " [E] Could not start snmptrapd.", 1);
 		return 1;
 	}
-	
+
 	return 0;
 }
 
@@ -403,7 +418,10 @@
 sub DESTROY {
 	my $self = shift;
 	
-	$RUN = 0;
+	if ($self->{'snmp_trapd'} ne 'manual') {
+		system ("kill -9 `cat /var/run/pandora_snmptrapd.pid 2>$DEVNULL`");
+		unlink ('/var/run/pandora_snmptrapd.pid');
+	}
 }
 
 1;
Index: lib/PandoraFMS/Config.pm
===================================================================
--- lib/PandoraFMS/Config.pm	(revision 10314)
+++ lib/PandoraFMS/Config.pm	(working copy)
@@ -248,6 +248,9 @@
 	$pa_config->{"snmp_pdu_address"} = 0; # 5.0
 	$pa_config->{"snmp_storm_protection"} = 0; # 5.0
 	$pa_config->{"snmp_storm_timeout"} = 600; # 5.0
+	$pa_config->{"snmpconsole_threads"} = 1; # 5.1
+	$pa_config->{"translate_variable_bindings"} = 0; # 5.1
+	$pa_config->{"translate_enterprise_strings"} = 1; # 5.1
 	
 	# Internal MTA for alerts, each server need its own config.
 	$pa_config->{"mta_address"} = '127.0.0.1'; # Introduced on 2.0
@@ -261,6 +264,7 @@
 
 	# nmap for recon OS fingerprinting and tcpscan (optional)
 	$pa_config->{"nmap"} = "/usr/bin/nmap";
+	$pa_config->{"nmap_timing_template"} = 2; # > 5.1
 
 	# braa for enterprise snmp server
 	$pa_config->{"braa"} = "/usr/bin/braa";
@@ -465,6 +469,15 @@
 		elsif ($parametro =~ m/^snmp_storm_timeout\s+(\d+)/i) { 
 			$pa_config->{'snmp_storm_timeout'}= clean_blank($1); 
 		}
+		elsif ($parametro =~ m/^snmpconsole_threads\s+(\d+)/i) { 
+			$pa_config->{'snmpconsole_threads'}= clean_blank($1); 
+		}
+		elsif ($parametro =~ m/^translate_variable_bindings\s+([0-1])/i) { 
+			$pa_config->{'translate_variable_bindings'}= clean_blank($1); 
+		}
+		elsif ($parametro =~ m/^translate_enterprise_strings\s+([0-1])/i) { 
+			$pa_config->{'translate_enterprise_strings'}= clean_blank($1); 
+		}
 		elsif ($parametro =~ m/^dbengine\s(.*)/i) { 
 			$pa_config->{'dbengine'}= clean_blank($1); 
 		}
@@ -595,6 +608,9 @@
 		elsif ($parametro =~ m/^nmap\s(.*)/i) {
 			$pa_config->{'nmap'}= clean_blank($1); 
 		}
+		elsif ($parametro =~ m/^nmap_timing_template\s([0-9]*)/i) {
+			$pa_config->{'nmap_timing_template'}= clean_blank($1); 
+		}
 		elsif ($parametro =~ m/^braa\s(.*)/i) {
 			$pa_config->{'braa'}= clean_blank($1); 
 		}
Index: lib/PandoraFMS/NetworkServer.pm
===================================================================
--- lib/PandoraFMS/NetworkServer.pm	(revision 10314)
+++ lib/PandoraFMS/NetworkServer.pm	(working copy)
@@ -25,6 +25,7 @@
 use Thread::Semaphore;
 
 use IO::Socket::INET6;
+use IO::Select;
 use HTML::Entities;
 use POSIX qw(strftime);
 
@@ -170,100 +171,103 @@
 		$retries = $pa_config->{'tcp_checks'};
 	}
 	
-    $tcp_send = decode_entities($tcp_send);
-    $tcp_rcv = decode_entities($tcp_rcv);
+	$tcp_send = decode_entities($tcp_send);
+	$tcp_rcv = decode_entities($tcp_rcv);
 
-        my $counter; 
-        for ($counter =0; $counter < $retries; $counter++){
-	        my $temp; my $temp2;
-	        my $tam;
-	        my $handle=IO::Socket::INET6->new(
-		        Proto=>"tcp",
-		        PeerAddr=>$ip_target,
-		        Timeout=>$timeout,
-		        PeerPort=>$tcp_port,
+	my $counter; 
+	for ($counter =0; $counter < $retries; $counter++){
+		my $temp; my $temp2;
+		my $tam;
+		my $handle=IO::Socket::INET6->new(
+			Proto=>"tcp",
+			PeerAddr=>$ip_target,
+			Timeout=>$timeout,
+			PeerPort=>$tcp_port,
 			Multihomed=>1,
-		        Blocking=>0 ); # Non blocking !!, very important !
-		        
-	        if (defined ($handle)){
+			Blocking=>0 ); # Non blocking !!, very important !
+			
+		if (defined ($handle)){
 			# Multi request patch, submitted by Glen Eustace (new zealand)
 			my @tcp_send = split( /\|/, $tcp_send );
 			my @tcp_rcv  = split( /\|/, $tcp_rcv );
 
+			# Add server socket to select queue
+			my $select = IO::Select->new ();
+			$select->add ($handle);
+
 next_pair:
 			$tcp_send = shift( @tcp_send );
 			$tcp_rcv  = shift( @tcp_rcv );
 
-		        if  ((defined ($tcp_send)) && ($tcp_send ne "")){ # its Expected to sending data ?
-			        # Send data
-			        $handle->autoflush(1);
-			        $tcp_send =~ s/\^M/\r\n/g;
-			        # Replace Carriage rerturn and line feed
-			        $handle->send($tcp_send);
-		        }
-		        # we expect to receive data ? (non proc types)
-		        if ((defined ($tcp_rcv) && $tcp_rcv ne "") || (($id_tipo_modulo == 10) || ($id_tipo_modulo ==8) || ($id_tipo_modulo == 11))) {
-			        # Receive data, non-blocking !!!! (VERY IMPORTANT!)
-			        $temp2 = "";
-			        for ($tam=0; $tam<$timeout; $tam++){
-				        $handle->recv($temp,16000,0x40);
-				        $temp2 = $temp2.$temp;
-				        if ($temp ne ""){
-					        $tam++; # If doesnt receive data, increase counter
-				        }
-				        sleep(1);
-			        }
-			        if ($id_tipo_modulo == 9){ # only for TCP Proc
-				        if ($temp2 =~ /$tcp_rcv/i){ # String match !
+			if  ((defined ($tcp_send)) && ($tcp_send ne "")){ # its Expected to sending data ?
+				# Send data
+				$handle->autoflush(1);
+				$tcp_send =~ s/\^M/\r\n/g;
+				# Replace Carriage rerturn and line feed
+				$handle->send($tcp_send);
+			}
+			# we expect to receive data ? (non proc types)
+			if ((defined ($tcp_rcv) && $tcp_rcv ne "") || (($id_tipo_modulo == 10) || ($id_tipo_modulo ==8) || ($id_tipo_modulo == 11))) {
+				# Receive data, non-blocking !!!! (VERY IMPORTANT!)
+				$temp2 = "";
+				for ($tam = 0; $tam < $timeout; $tam ++) {
+					if ($select->can_read (1)) {
+						my $read = sysread ($handle, $temp, 16000);
+						last if (! defined ($read) || $read == 0); # No more data or something went wrong
+						$temp2 = $temp2.$temp;
+					}
+				}
+				if ($id_tipo_modulo == 9){ # only for TCP Proc
+					if ($temp2 =~ /$tcp_rcv/i){ # String match !
 						if ( @tcp_send ) { # still more pairs
 							goto next_pair;
 						}
- 					        $$module_data = 1;
-					        $$module_result = 0;
-					        $counter = $retries;
-				        } else {
-					        $$module_data = 0;
-					        $$module_result = 0;
-					        $counter = $retries;
-				        }
-			        } elsif ($id_tipo_modulo == 10 ){ # TCP String (no int conversion)!
-				        $$module_data = $temp2;
-				        $$module_result =0;
-			        } else { # TCP Data numeric (inc or data)
-				        if ($temp2 ne ""){
-					        if ($temp2 =~ /[A-Za-z\.\,\-\/\\\(\)\[\]]/){
-						        $$module_result = 1;
-						        $$module_data = 0; # invalid data
-						        $counter = $retries;
-					        } else {
-						        $$module_data = int($temp2);
-						        $$module_result = 0; # Successful
-						        $counter = $retries;
-					        }
-				        } else {
-						        $$module_result = 1; 
-						        $$module_data = 0; # invalid data
-						        $counter = $retries;
-					        }
-			        }
-		        } else { # No expected data to receive, if connected and tcp_proc type successful
-			        if ($id_tipo_modulo == 9){ # TCP Proc
-				        $$module_result = 0;
-				        $$module_data = 1;
-				        $counter = $retries;
-			        }
-		        }
-		        $handle->close();
-		        undef ($handle);
-	        } else { # Cannot connect (open sock failed)
-		        $$module_result = 1; # Fail
-		        if ($id_tipo_modulo == 9){ # TCP Proc
-			        $$module_result = 0;
-			        $$module_data = 0; # Failed, but data exists
-			        $counter = $retries;
-		        }
-	        }
-        }
+						$$module_data = 1;
+						$$module_result = 0;
+						$counter = $retries;
+					} else {
+						$$module_data = 0;
+						$$module_result = 0;
+						$counter = $retries;
+					}
+				} elsif ($id_tipo_modulo == 10 ){ # TCP String (no int conversion)!
+					$$module_data = $temp2;
+					$$module_result =0;
+				} else { # TCP Data numeric (inc or data)
+					if ($temp2 ne ""){
+						if ($temp2 =~ /[A-Za-z\.\,\-\/\\\(\)\[\]]/){
+							$$module_result = 1;
+							$$module_data = 0; # invalid data
+							$counter = $retries;
+						} else {
+							$$module_data = int($temp2);
+							$$module_result = 0; # Successful
+							$counter = $retries;
+						}
+					} else {
+						$$module_result = 1; 
+						$$module_data = 0; # invalid data
+						$counter = $retries;
+					}
+				}
+			} else { # No expected data to receive, if connected and tcp_proc type successful
+				if ($id_tipo_modulo == 9){ # TCP Proc
+					$$module_result = 0;
+					$$module_data = 1;
+					$counter = $retries;
+				}
+			}
+			$handle->close();
+			undef ($handle);
+		} else { # Cannot connect (open sock failed)
+			$$module_result = 1; # Fail
+			if ($id_tipo_modulo == 9){ # TCP Proc
+				$$module_result = 0;
+				$$module_data = 0; # Failed, but data exists
+				$counter = $retries;
+			}
+		}
+	}
 }
 
 ###############################################################################
@@ -352,7 +356,7 @@
 
 	return (undef, 0) unless ($snmp_oid ne '');
 	if ($snmp_oid =~ m/[a-zA-Z]/) {
-		$snmp_oid = translate_obj ($pa_config, $dbh, $snmp_oid, );
+		$snmp_oid = translate_obj ($pa_config, $dbh, $snmp_oid);
 		
 		# Could not translate OID, disable the module
 		if (! defined ($snmp_oid) || $snmp_oid eq '') {
Index: lib/PandoraFMS/GIS.pm
===================================================================
--- lib/PandoraFMS/GIS.pm	(revision 10314)
+++ lib/PandoraFMS/GIS.pm	(working copy)
@@ -146,12 +146,24 @@
 ##########################################################################
 sub get_reverse_geoip_sql($$$) {
 	my ($pa_config,$ip_addr, $dbh) = @_;
-
-	my $id_range =  get_db_value($dbh, 'SELECT `id_range` FROM tgis_reverse_geoip_ranges WHERE INET_ATON(?) >= `first_IP_decimal` AND INET_ATON(?) <= `last_IP_decimal` 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 `id_range` = ?',$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);
+	
+	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;
 	}
 	return undef;
Index: lib/PandoraFMS/DB.pm
===================================================================
--- lib/PandoraFMS/DB.pm	(revision 10314)
+++ lib/PandoraFMS/DB.pm	(working copy)
@@ -86,14 +86,18 @@
 		get_agentmodule_data
 		$RDBMS
 		$RDBMS_QUOTE
+		$RDBMS_QUOTE_STRING
 	);
 
 # Relational database management system in use
 our $RDBMS = '';
 
-# Character used to quote reserved words in the current RDBMS
+# For fields, character used to quote reserved words in the current RDBMS
 our $RDBMS_QUOTE = '';
 
+# For strings, Character used to quote in the current RDBMS
+our $RDBMS_QUOTE_STRING = '';
+
 ##########################################################################
 ## Connect to the DB.
 ##########################################################################
@@ -103,7 +107,8 @@
 	if ($rdbms eq 'mysql') {
 		$RDBMS = 'mysql';
 		$RDBMS_QUOTE = '`';
-	
+		$RDBMS_QUOTE_STRING = '"';
+		
 		# Connect to MySQL
 		my $dbh = DBI->connect("DBI:mysql:$db_name:$db_host:$db_port", $db_user, $db_pass, { RaiseError => 1, AutoCommit => 1 });
 		return undef unless defined ($dbh);
@@ -119,15 +124,18 @@
 	elsif ($rdbms eq 'postgresql') {
 		$RDBMS = 'postgresql';
 		$RDBMS_QUOTE = '"';
+		$RDBMS_QUOTE_STRING = "'";
 		
 		# Connect to PostgreSQL
 		my $dbh = DBI->connect("DBI:Pg:dbname=$db_name;host=$db_host;port=$db_port", $db_user, $db_pass, { RaiseError => 1, AutoCommit => 1 });
 		return undef unless defined ($dbh);
 		
 		return $dbh;
-	} elsif ($rdbms eq 'oracle') {
+	}
+	elsif ($rdbms eq 'oracle') {
 		$RDBMS = 'oracle';
 		$RDBMS_QUOTE = '"';
+		$RDBMS_QUOTE_STRING = '"';
 		
 		# Connect to Oracle
 		my $dbh = DBI->connect("DBI:Oracle:dbname=$db_name;host=$db_host;port=$db_port;sid=pandora", $db_user, $db_pass, { RaiseError => 1, AutoCommit => 1 });
@@ -641,6 +649,7 @@
 	my ($dbh, $index, $query, @values) = @_;
 	my $insert_id = undef;
 	
+	
 	# MySQL
 	if ($RDBMS eq 'mysql') {
 		$dbh->do($query, undef, @values);
@@ -684,9 +693,9 @@
 	return defined ($rc) ? $rc : -1;
 }
 
-##########################################################################
+########################################################################
 ## SQL insert. Returns the ID of the inserted row.
-##########################################################################
+########################################################################
 sub db_process_insert($$$$;@) {
 	my ($dbh, $index, $table, $parameters, @values) = @_;
 	
@@ -711,10 +720,14 @@
 	}
 	$wildcards = '('.$wildcards.')';
 	
-	my $columns_string = join('`,`',@columns_array);
+	my $columns_string = join($RDBMS_QUOTE . ',' . $RDBMS_QUOTE,
+		@columns_array);
 	
-	my $res = db_insert ($dbh, $index, "INSERT INTO $table (`".$columns_string."`) VALUES ".$wildcards, @values_array);
+	my $res = db_insert ($dbh,
+		$index,
+		"INSERT INTO $table (" . $RDBMS_QUOTE . $columns_string . $RDBMS_QUOTE . ") VALUES " . $wildcards, @values_array);
 	
+	
 	return $res;
 }
 
@@ -740,7 +753,8 @@
 		if ($i > 0 && $i <= $#values_array) {
 			$fields = $fields.',';
 		}
-		$fields = $fields." `$columns_array[$i]` = ?";
+		$fields = $fields .
+			" " . $RDBMS_QUOTE . "$columns_array[$i]" . $RDBMS_QUOTE . " = ?";
 	}
 	
 	push(@values_array, $where_value);
@@ -752,28 +766,30 @@
 	return $res;
 }
 
-##########################################################################
+########################################################################
 # Add the given address to taddress.
-##########################################################################
+########################################################################
 sub add_address ($$) {
 	my ($dbh, $ip_address) = @_;
-
+	
 	return db_insert ($dbh, 'id_a', 'INSERT INTO taddress (ip) VALUES (?)', $ip_address);
 }
 
-##########################################################################
+########################################################################
 # Assign the new address to the agent
-##########################################################################
+########################################################################
 sub add_new_address_agent ($$$) {
 	my ($dbh, $addr_id, $agent_id) = @_;
 	
-	db_do ($dbh, 'INSERT INTO taddress_agent (`id_a`, `id_agent`)
+	db_do ($dbh, 'INSERT INTO taddress_agent (' .
+		$RDBMS_QUOTE . 'id_a' . $RDBMS_QUOTE . ', ' .
+		$RDBMS_QUOTE. 'id_agent' . $RDBMS_QUOTE. ')
 		VALUES (?, ?)', $addr_id, $agent_id);
 }
 
-##########################################################################
+########################################################################
 # Return the ID of the given address, -1 if it does not exist.
-##########################################################################
+########################################################################
 sub get_addr_id ($$) {
 	my ($dbh, $addr) = @_;
 	
@@ -825,9 +841,9 @@
 	return (defined ($id_ag)) ? $id_ag : 0;
 }
 
-##########################################################################
+########################################################################
 ## Quote the given string. 
-##########################################################################
+########################################################################
 sub db_string ($) {
 	my $string = shift;
 	
@@ -856,7 +872,10 @@
 sub get_alert_template_name ($$) {
 	my ($dbh, $alert_id) = @_;
 	
-	return get_db_value ($dbh, "SELECT name FROM talert_templates, talert_template_modules WHERE talert_templates.id = talert_template_modules.id_alert_template AND talert_template_modules.id = ?", $alert_id);
+	return get_db_value ($dbh, "SELECT name
+		FROM talert_templates, talert_template_modules
+		WHERE talert_templates.id = talert_template_modules.id_alert_template
+			AND talert_template_modules.id = ?", $alert_id);
 }
 
 ########################################################################
@@ -865,9 +884,8 @@
 sub db_concat ($$) {
 	my ($element1, $element2) = @_;
 	
-	return " concat(" . $element1 . ", ' '," . $element2 . ") " if ($RDBMS eq 'mysql');
-	
 	return " " . $element1 . " || ' ' || " . $element2 . " " if ($RDBMS eq 'oracle' or $RDBMS eq 'postgresql');
+	return " concat(" . $element1 . ", ' '," . $element2 . ") ";
 }
 
 ########################################################################
@@ -906,18 +924,18 @@
 ########################################################################
 sub db_update_get_values ($) {
 	my ($set_ref) = @_;
-
+	
 	my $set = '';
 	my @values;
 	while (my ($key, $value) = each (%{$set_ref})) {
-
-			# Not value for the given column
-			next if (! defined ($value));
-
-			$set .= "$key = ?,";
-			push (@values, $value);
+		
+		# Not value for the given column
+		next if (! defined ($value));
+		
+		$set .= "$key = ?,";
+		push (@values, $value);
 	}
-
+	
 	# Remove the last ,
 	chop ($set);
 	
@@ -929,34 +947,34 @@
 ########################################################################
 sub db_insert_get_values ($) {
 	my ($insert_ref) = @_;
-
+	
 	my $columns = '(';
 	my @values;
 	while (my ($key, $value) = each (%{$insert_ref})) {
-
-			# Not value for the given column
-			next if (! defined ($value));
-
-			$columns .= $PandoraFMS::DB::RDBMS_QUOTE . "$key" . $PandoraFMS::DB::RDBMS_QUOTE . ",";
-			push (@values, $value);
+		
+		# Not value for the given column
+		next if (! defined ($value));
+		
+		$columns .= $PandoraFMS::DB::RDBMS_QUOTE . "$key" . $PandoraFMS::DB::RDBMS_QUOTE . ",";
+		push (@values, $value);
 	}
-
+	
 	# Remove the last , and close the parentheses
 	chop ($columns);
 	$columns .= ')';
 	
-	# No columns		
+	# No columns
 	if ($columns eq '()') {
 		return;
 	}
-
+	
 	# Add placeholders for the values
 	$columns .= ' VALUES (' . ("?," x ($#values + 1));
-
+	
 	# Remove the last , and close the parentheses
 	chop ($columns);
 	$columns .= ')';
-		
+	
 	return ($columns, \@values);
 }
 
@@ -973,7 +991,7 @@
 	my $sth = $dbh->prepare('SELECT GET_LOCK(?, ?)');
 	$sth->execute($lock_name, $lock_timeout);
 	my ($lock) = $sth->fetchrow;
-
+	
 	# Something went wrong
 	return 0 if (! defined ($lock));
 	
Index: lib/PandoraFMS/Core.pm
===================================================================
--- lib/PandoraFMS/Core.pm	(revision 10314)
+++ lib/PandoraFMS/Core.pm	(working copy)
@@ -511,6 +511,9 @@
 		my $critical_instructions = get_db_value ($dbh, 'SELECT critical_instructions FROM tagente_modulo WHERE id_agente_modulo = ?', $alert->{'id_agent_module'});
 		my $warning_instructions = get_db_value ($dbh, 'SELECT warning_instructions FROM tagente_modulo WHERE id_agente_modulo = ?', $alert->{'id_agent_module'});
 		my $unknown_instructions = get_db_value ($dbh, 'SELECT unknown_instructions FROM tagente_modulo WHERE id_agente_modulo = ?', $alert->{'id_agent_module'});
+
+		$alert->{'critical_instructions'} = $critical_instructions;
+		$alert->{'warning_instructions'} = $warning_instructions;
 		
 		# Generate an event
 		if ($table eq 'tevent_alert') {
@@ -666,6 +669,14 @@
 		return;
 	}
 
+	# Critical_instructions, warning_instructions, unknown_instructions
+	my $critical_instructions = get_db_value ($dbh, 'SELECT critical_instructions FROM tagente_modulo WHERE id_agente_modulo = ?', $alert->{'id_agent_module'});
+	my $warning_instructions = get_db_value ($dbh, 'SELECT warning_instructions FROM tagente_modulo WHERE id_agente_modulo = ?', $alert->{'id_agent_module'});
+	my $unknown_instructions = get_db_value ($dbh, 'SELECT unknown_instructions FROM tagente_modulo WHERE id_agente_modulo = ?', $alert->{'id_agent_module'});
+
+	$alert->{'critical_instructions'} = $critical_instructions;
+	$alert->{'warning_instructions'} = $warning_instructions;
+
 	# Execute actions
 	my $event_generated = 0;
 	foreach my $action (@actions) {
@@ -692,11 +703,6 @@
 		}
 	}
 	
-	# Critical_instructions, warning_instructions, unknown_instructions
-	my $critical_instructions = get_db_value ($dbh, 'SELECT critical_instructions FROM tagente_modulo WHERE id_agente_modulo = ?', $alert->{'id_agent_module'});
-	my $warning_instructions = get_db_value ($dbh, 'SELECT warning_instructions FROM tagente_modulo WHERE id_agente_modulo = ?', $alert->{'id_agent_module'});
-	my $unknown_instructions = get_db_value ($dbh, 'SELECT unknown_instructions FROM tagente_modulo WHERE id_agente_modulo = ?', $alert->{'id_agent_module'});
-	
 	# Generate an event	only if an event has not already been generated by an alert action
 	if ($event_generated == 0) {
 
@@ -840,6 +846,8 @@
 				_alert_times_fired_ => $alert->{'times_fired'},
 				_alert_priority_ => $alert->{'priority'},
 				_alert_text_severity_ => get_priority_name($alert->{'priority'}),
+				_alert_critical_instructions_ => $alert->{'critical_instructions'},
+				_alert_warning_instructions_ => $alert->{'warning_instructions'},
 				_groupcontact_ => (defined ($group)) ? $group->{'contact'} : '',
 				_groupother_ => (defined ($group)) ? $group->{'other'} : '',
 				_module_ => (defined ($module)) ? $module->{'nombre'} : '',
@@ -1095,6 +1103,11 @@
 		$min_ff_event = $module->{'min_ff_event_warning'} if ($new_status == 2);
 	}
 	
+	# replace $new_status with $last_known_status when recovering from 'unknown'
+	if ($status == 3) {
+		$new_status = $last_known_status;
+	}
+
 	if ($last_status == $new_status) {
 		
 		# Avoid overflows
@@ -1124,17 +1137,24 @@
 		# Update module status count
 		pandora_mark_agent_for_module_update ($dbh, $agent->{'id_agente'});
 	}
-	# Set not-init modules to normal even if min_ff_event is not matched the first time they receive data
+	# Set not-init modules to normal status even if min_ff_event is not matched the first time they receive data.
+	# if critical or warning status, just pass through here and wait the time min_ff_event will be matched.
 	elsif ($status == 4) {
-		$new_status = 0;
-		
+		generate_status_event ($pa_config, $processed_data, $agent, $module, 0, $status, $last_known_status, $dbh);
+		$status = 0;
+
+		# Update module status count
+		pandora_mark_agent_for_module_update ($dbh, $agent->{'id_agente'});
+	}
+	# If unknown modules receive data, restore status even if min_ff_event is not matched.
+	elsif ($status == 3) {
 		generate_status_event ($pa_config, $processed_data, $agent, $module, $new_status, $status, $last_known_status, $dbh);
 		$status = $new_status;
 
 		# Update module status count
 		pandora_mark_agent_for_module_update ($dbh, $agent->{'id_agente'});
 	}
-		
+
 	$last_status = $new_status;
 		
 	# tagente_estado.last_try defaults to NULL, should default to '1970-01-01 00:00:00'
@@ -1193,8 +1213,10 @@
 	# Stop executed downtimes (enable agents and disable_agents_alerts)
 	my @downtimes = get_db_rows($dbh, 'SELECT *
 		FROM tplanned_downtime
-		WHERE type_downtime != "quiet" AND type_execution="once"
-			AND executed = 1 AND date_to <= ?', $utimestamp);
+		WHERE type_downtime != ' . $RDBMS_QUOTE_STRING. 'quiet' . $RDBMS_QUOTE_STRING. '
+			AND type_execution = ' . $RDBMS_QUOTE_STRING. 'once' . $RDBMS_QUOTE_STRING. '
+			AND executed = 1
+			AND date_to <= ?', $utimestamp);
 	
 	foreach my $downtime (@downtimes) {
 		
@@ -1226,7 +1248,8 @@
 	# Start pending downtimes (disable agents and disable_agents_alerts)
 	my @downtimes = get_db_rows($dbh, 'SELECT *
 		FROM tplanned_downtime
-		WHERE type_downtime != "quiet" AND type_execution="once"
+		WHERE type_downtime != ' . $RDBMS_QUOTE_STRING . 'quiet' . $RDBMS_QUOTE_STRING . '
+			AND type_execution = ' . $RDBMS_QUOTE_STRING . 'once' . $RDBMS_QUOTE_STRING . '
 			AND executed = 0 AND date_from <= ?
 			AND date_to >= ?', $utimestamp, $utimestamp);
 	
@@ -1423,7 +1446,8 @@
 	# Stop pending downtimes
 	my @downtimes = get_db_rows($dbh, 'SELECT *
 		FROM tplanned_downtime
-		WHERE type_downtime = "quiet" AND type_execution="once"
+		WHERE type_downtime = ' . $RDBMS_QUOTE_STRING . 'quiet' . $RDBMS_QUOTE_STRING . '
+			AND type_execution = ' . $RDBMS_QUOTE_STRING. 'once' . $RDBMS_QUOTE_STRING . '
 			AND executed = 1 AND date_to <= ?', $utimestamp);
 	
 	foreach my $downtime (@downtimes) {
@@ -1463,7 +1487,8 @@
 	# Start pending downtimes
 	my @downtimes = get_db_rows($dbh, 'SELECT *
 		FROM tplanned_downtime
-		WHERE type_downtime = "quiet" AND type_execution="once"
+		WHERE type_downtime = ' . $RDBMS_QUOTE_STRING . 'quiet' . $RDBMS_QUOTE_STRING . '
+			AND type_execution = ' . $RDBMS_QUOTE_STRING . 'once' . $RDBMS_QUOTE_STRING . '
 			AND executed = 0 AND date_from <= ?
 			AND date_to >= ?', $utimestamp, $utimestamp);
 	
@@ -1517,7 +1542,7 @@
 	# Start pending downtimes
 	my @downtimes = get_db_rows($dbh, 'SELECT *
 		FROM tplanned_downtime
-		WHERE type_periodicity="monthly"
+		WHERE type_periodicity = ' . $RDBMS_QUOTE_STRING . 'monthly' . $RDBMS_QUOTE_STRING . '
 			AND executed = 0
 			AND periodically_day_from <= ?
 			AND periodically_day_to >= ?', 
@@ -1619,9 +1644,9 @@
 	# Start pending downtimes
 	my @downtimes = get_db_rows($dbh, 'SELECT *
 		FROM tplanned_downtime
-		WHERE type_periodicity = "monthly"
+		WHERE type_periodicity = ' . $RDBMS_QUOTE_STRING . 'monthly' . $RDBMS_QUOTE_STRING . '
 			AND executed = 1
-			AND type_execution <> "once"');
+			AND type_execution <> ' . $RDBMS_QUOTE_STRING . 'once' . $RDBMS_QUOTE_STRING);
 	
 	foreach my $downtime (@downtimes) {
 		#Convert to identical type.
@@ -1695,18 +1720,18 @@
 	# Start pending downtimes
 	my @downtimes = get_db_rows($dbh, 'SELECT *
 		FROM tplanned_downtime
-		WHERE type_periodicity="weekly"
+		WHERE type_periodicity = ' . $RDBMS_QUOTE_STRING . 'weekly' . $RDBMS_QUOTE_STRING . '
 			AND executed = 0');
 	
 	foreach my $downtime (@downtimes) {
 		my $across_date = $downtime->{'periodically_time_from'} gt $downtime->{'periodically_time_to'} ? 1 : 0 ;
 		$found = 0;
-
+		
 		if ($across_date && ($time lt $downtime->{'periodically_time_to'})) {
-                        $number_day_week--;
-                        $number_day_week = 6 if ($number_day_week == -1);
-                }
-
+			$number_day_week--;
+			$number_day_week = 6 if ($number_day_week == -1);
+		}
+		
 		if (($number_day_week == 1) &&
 			($downtime->{'monday'})) {
 				$found = 1;
@@ -1817,8 +1842,8 @@
 	# Start pending downtimes
 	my @downtimes = get_db_rows($dbh, 'SELECT *
 		FROM tplanned_downtime
-		WHERE type_periodicity = "weekly"
-			AND type_execution <> "once"
+		WHERE type_periodicity = ' . $RDBMS_QUOTE_STRING . 'weekly' . $RDBMS_QUOTE_STRING . '
+			AND type_execution <> ' . $RDBMS_QUOTE_STRING . 'once' . $RDBMS_QUOTE_STRING . '
 			AND executed = 1');
 	
 	foreach my $downtime (@downtimes) {
@@ -2137,7 +2162,7 @@
 Create a template module.
 
 =cut
-##########################################################################
+########################################################################
 sub pandora_create_template_module ($$$$;$$$) {
 	my ($pa_config, $dbh, $id_agent_module, $id_alert_template, $id_policy_alerts, $disabled, $standby) = @_;
 	
@@ -2146,16 +2171,27 @@
 	$standby = 0 unless defined $standby;
 	
 	my $module_name = get_module_name($dbh, $id_agent_module);
-	return db_insert ($dbh, 'id', "INSERT INTO talert_template_modules (`id_agent_module`, `id_alert_template`, `id_policy_alerts`, `disabled`, `standby`, `last_reference`) VALUES (?, ?, ?, ?, ?, ?)", $id_agent_module, $id_alert_template, $id_policy_alerts, $disabled, $standby, time);
+	
+	return db_insert ($dbh,
+		'id',
+		"INSERT INTO talert_template_modules(
+			" . $RDBMS_QUOTE . "id_agent_module" . $RDBMS_QUOTE . ",
+			" . $RDBMS_QUOTE . "id_alert_template" . $RDBMS_QUOTE . ",
+			" . $RDBMS_QUOTE . "id_policy_alerts" . $RDBMS_QUOTE . ",
+			" . $RDBMS_QUOTE . "disabled" . $RDBMS_QUOTE . ",
+			" . $RDBMS_QUOTE . "standby" . $RDBMS_QUOTE . ",
+			" . $RDBMS_QUOTE . "last_reference" . $RDBMS_QUOTE . ")
+		VALUES (?, ?, ?, ?, ?, ?)",
+		$id_agent_module, $id_alert_template, $id_policy_alerts, $disabled, $standby, time);
 }
 
-##########################################################################
+########################################################################
 =head2 C<< pandora_update_template_module(I<$pa_config>, I<$dbh>, I<$id_alert>, I<$id_policy_alerts>, I<$disabled>, I<$standby>) >>
 
 Update a template module.
 
 =cut
-##########################################################################
+########################################################################
 
 sub pandora_update_template_module ($$$;$$$) {
 	my ($pa_config, $dbh, $id_alert, $id_policy_alerts, $disabled, $standby) = @_;
@@ -2164,16 +2200,22 @@
 	$disabled = 0 unless defined $disabled;
 	$standby = 0 unless defined $standby;
 	
-	db_do ($dbh, "UPDATE talert_template_modules SET `id_policy_alerts` = ?, `disabled` =  ?, `standby` = ? WHERE id = ?", $id_policy_alerts, $disabled, $standby, $id_alert);
+	db_do ($dbh,
+		"UPDATE talert_template_modules
+		SET " . $RDBMS_QUOTE . "id_policy_alerts" . $RDBMS_QUOTE . " = ?,
+			" . $RDBMS_QUOTE . "disabled" . $RDBMS_QUOTE . " =  ?,
+			" . $RDBMS_QUOTE . "standby" . $RDBMS_QUOTE . " = ?
+		WHERE id = ?",
+		$id_policy_alerts, $disabled, $standby, $id_alert);
 }
 
-##########################################################################
+########################################################################
 =head2 C<< pandora_create_template_module_action(I<$pa_config>, I<$parameters>, I<$dbh>) >>
 
 Create a template action.
 
 =cut
-##########################################################################
+########################################################################
 sub pandora_create_template_module_action ($$$) {
 	my ($pa_config, $parameters, $dbh) = @_;
 	
@@ -2184,26 +2226,26 @@
 	return $action_id;
 }
 
-##########################################################################
+########################################################################
 =head2 C<< pandora_delete_all_template_module_actions(I<$dbh>, I<$template_module_id>) >>
 
 Delete all actions of policy template module.
 
 =cut
-##########################################################################
+########################################################################
 sub pandora_delete_all_template_module_actions ($$) {
 	my ($dbh, $template_module_id) = @_;
 	
 	return db_do ($dbh, 'DELETE FROM talert_template_module_actions WHERE id_alert_template_module = ?', $template_module_id);
 }
 
-##########################################################################
+########################################################################
 =head2 C<< pandora_update_agent_address(I<$pa_config>, I<$agent_id>, I<$address>, I<$dbh>) >>
 
 Update the address of an agent.
 
 =cut
-##########################################################################
+########################################################################
 sub pandora_update_agent_address ($$$$$) {
 	my ($pa_config, $agent_id, $agent_name, $address, $dbh) = @_;
 	
@@ -2298,9 +2340,13 @@
 		$status = 0;
 	}
 	
-	my $module_id = db_insert($dbh, 'id_agente_modulo', 'INSERT INTO tagente_modulo (id_agente, id_tipo_modulo, nombre, max, min, post_process, descripcion, module_interval, id_modulo)
-		VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1)', $agent_id, $module_type_id, safe_input($module_name), $max, $min, $post_process, $description, $interval);
-	db_do ($dbh, 'INSERT INTO tagente_estado (id_agente_modulo, id_agente, estado, last_status, last_known_status, last_try) VALUES (?, ?, ?, ?, ?, \'1970-01-01 00:00:00\')', $module_id, $agent_id, $status, $status, $status);
+	my $module_id = db_insert($dbh, 'id_agente_modulo',
+		'INSERT INTO tagente_modulo (id_agente, id_tipo_modulo, nombre, max, min, post_process, descripcion, module_interval, id_modulo, critical_instructions, warning_instructions, unknown_instructions, disabled_types_event, module_macros)
+		VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, \'\', \'\', \'\', \'\', \'\')',
+		$agent_id, $module_type_id, safe_input($module_name), $max, $min, $post_process, $description, $interval);
+	db_do ($dbh, 'INSERT INTO tagente_estado (id_agente_modulo, id_agente, estado, last_status, last_known_status, last_try, datos)
+		VALUES (?, ?, ?, ?, ?, \'1970-01-01 00:00:00\', \'\')',
+		$module_id, $agent_id, $status, $status, $status);
 	
 	# Update the module status count. When the module is created disabled dont do it
 	pandora_mark_agent_for_module_update ($dbh, $agent_id);
@@ -2400,7 +2446,18 @@
 	delete $parameters->{'type'};
 	delete $parameters->{'datalist'};
 	delete $parameters->{'status'};
-	
+	if (defined $parameters->{'id_os'}) {
+		delete $parameters->{'id_os'};
+	}
+	if (defined $parameters->{'os_version'}) {
+		delete $parameters->{'os_version'};
+	}
+	if (defined $parameters->{'id_os'}) {
+		delete $parameters->{'id'};
+	}
+	if (defined $parameters->{'id_network_component_group'}) {
+		delete $parameters->{'id_network_component_group'};
+	}
 	my $module_id = db_process_insert($dbh, 'id_agente_modulo',
 		'tagente_modulo', $parameters);
 	
@@ -2409,7 +2466,7 @@
 		$status = 0;
 	}
 	
-	db_do ($dbh, 'INSERT INTO tagente_estado (id_agente_modulo, id_agente, estado, last_status, last_known_status, last_try) VALUES (?, ?, ?, ?, ?, \'1970-01-01 00:00:00\')', $module_id, $parameters->{'id_agente'}, $status, $status, $status);
+	db_do ($dbh, 'INSERT INTO tagente_estado (id_agente_modulo, id_agente, estado, last_status, last_known_status, last_try, datos) VALUES (?, ?, ?, ?, ?, \'1970-01-01 00:00:00\', \'\')', $module_id, $parameters->{'id_agente'}, $status, $status, $status);
 	
 	# Update the module status count. When the module is created disabled dont do it
 	pandora_mark_agent_for_module_update ($dbh, $parameters->{'id_agente'});
@@ -2495,8 +2552,16 @@
 	}
 	
 	foreach my $tag_name (split (',', $serialized_tags)) {
-		my $tag_id = get_db_value ($dbh, "SELECT id_tag FROM ttag WHERE name = ?", $tag_name);
-		db_insert ($dbh, 'id_tag', "INSERT INTO ttag_module (`id_tag`, `id_agente_modulo`) VALUES (?, ?)", $tag_id, $id_agent_module);
+		my $tag_id = get_db_value ($dbh,
+			"SELECT id_tag FROM ttag WHERE name = ?", $tag_name);
+		
+		db_insert ($dbh,
+			'id_tag',
+			"INSERT INTO ttag_module(
+				" . $RDBMS_QUOTE . "id_tag" . $RDBMS_QUOTE . ",
+				" . $RDBMS_QUOTE . "id_agente_modulo" . $RDBMS_QUOTE . ")
+			VALUES (?, ?)",
+			$tag_id, $id_agent_module);
 	}
 }
 
@@ -3385,6 +3450,19 @@
 		return;
 	}
 
+	# disable event just recovering from 'Unknown' without status change
+	if($last_status == 3 && $status == $last_known_status && $module->{'disabled_types_event'} ) {
+		my $disabled_types_event;
+		eval {
+			local $SIG{__DIE__};
+			$disabled_types_event = decode_json($module->{'disabled_types_event'});
+		};
+		
+		if ($disabled_types_event->{'going_unknown'}) {
+			return;
+		}
+	}
+
 	# Mark as "validated" any previous event for this module
 	pandora_validate_event ($pa_config, $module->{'id_agente_modulo'}, $dbh);
 	
@@ -3968,33 +4046,46 @@
 		                                       AND estado = 3");
 		$agents_unknown = 0 if (!defined($agents_unknown));
 	}
-
+	
 	my $queued_modules = get_db_value ($dbh, "SELECT SUM(queued_modules) FROM tserver WHERE name = '".$pa_config->{"servername"}."'");
-
-	if (!defined($queued_modules)){
+	
+	if (!defined($queued_modules)) {
 		$queued_modules = 0;
 	}
-
-	my $dbmaintance = get_db_value ($dbh, "SELECT COUNT(*) FROM tconfig WHERE token = 'db_maintance' AND value > UNIX_TIMESTAMP() - 86400");
-
+	
+	my $dbmaintance;
+	if ($RDBMS eq 'postgresql') {
+		$dbmaintance = get_db_value ($dbh,
+			"SELECT COUNT(*)
+			FROM tconfig
+			WHERE token = 'db_maintance'
+				AND NULLIF(value, '')::int > UNIX_TIMESTAMP() - 86400");
+	}
+	else {
+		$dbmaintance = get_db_value ($dbh,
+			"SELECT COUNT(*)
+			FROM tconfig
+			WHERE token = 'db_maintance' AND value > UNIX_TIMESTAMP() - 86400");
+	}
+	
 	$xml_output .=" <module>";
 	$xml_output .=" <name>Database Maintenance</name>";
 	$xml_output .=" <type>generic_proc</type>";
 	$xml_output .=" <data>$dbmaintance</data>";
 	$xml_output .=" </module>";
-
+	
 	$xml_output .=" <module>";
 	$xml_output .=" <name>Queued_Modules</name>";
 	$xml_output .=" <type>generic_data</type>";
 	$xml_output .=" <data>$queued_modules</data>";
 	$xml_output .=" </module>";
-
+	
 	$xml_output .=" <module>";
 	$xml_output .=" <name>Agents_Unknown</name>";
 	$xml_output .=" <type>generic_data</type>";
 	$xml_output .=" <data>$agents_unknown</data>";
 	$xml_output .=" </module>";
-
+	
 	$xml_output .=" <module>";
 	$xml_output .=" <name>System_Load_AVG</name>";
 	$xml_output .=" <type>generic_data</type>";
Index: lib/PandoraFMS/ReconServer.pm
===================================================================
--- lib/PandoraFMS/ReconServer.pm	(revision 10314)
+++ lib/PandoraFMS/ReconServer.pm	(working copy)
@@ -141,9 +141,11 @@
 	}
 
 	# Call nmap
+	my $timeout = $pa_config->{'networktimeout'}*1000;
+	my $nmap_args  = '-nsP -PE --max-retries '.$pa_config->{'icmp_checks'}.' --host-timeout '.$timeout.' -T'.$pa_config->{'nmap_timing_template'};
 	my $np = new PandoraFMS::NmapParser;
 	eval {
-		$np->parsescan($pa_config->{'nmap'},'-nsP', ($task->{'subnet'}));
+		$np->parsescan($pa_config->{'nmap'}, $nmap_args, ($task->{'subnet'}));
 	};
 	if ($@) {
 		update_recon_task ($dbh, $task_id, -1);
@@ -262,7 +264,7 @@
 			}
 		}
 		# End of GIS code -----------------------------      
-		else {	
+		else {
 			# Create a new agent
 			$agent_id = pandora_create_agent ($pa_config, $pa_config->{'servername'},
 					                                  $host_name, $addr, $task->{'id_group'},
@@ -274,7 +276,7 @@
 			logger($pa_config, "Error creating agent '$host_name'.", 3);
 			next;
 		}
-
+		
 		# Add the new address if it does not exist
 		my $addr_id = get_addr_id ($dbh, $addr);
 		$addr_id = add_address ($dbh, $addr) unless ($addr_id > 0);
@@ -282,14 +284,15 @@
 			logger($pa_config, "Could not add address '$addr' for host '$host_name'.", 3);
 			next;
 		}
-
+		
 		# Assign the new address to the agent
 		my $agent_addr_id = get_agent_addr_id ($dbh, $addr_id, $agent_id);
 		if ($agent_addr_id <= 0) {
-			db_do ($dbh, 'INSERT INTO taddress_agent (`id_a`, `id_agent`)
-		                  VALUES (?, ?)', $addr_id, $agent_id);
+			db_do ($dbh, 'INSERT INTO taddress_agent (' . $RDBMS_QUOTE . 'id_a' . $RDBMS_QUOTE . ', ' .
+				$RDBMS_QUOTE . 'id_agent' . $RDBMS_QUOTE . ')
+				VALUES (?, ?)', $addr_id, $agent_id);
 		}
-
+		
 		# Create network profile modules for the agent
 		create_network_profile_modules ($pa_config, $dbh, $agent_id, $task->{'id_network_profile'}, $addr, $task->{'snmp_community'});
 		
@@ -309,9 +312,9 @@
 		$text .= "\n\nThis is the list of IP addresses found: \n\n$added_hosts";
 		pandora_create_incident ($pa_config, $dbh, "[RECON] New hosts detected", $text, 0, 0, 'Pandora FMS Recon Server', $task->{'id_group'});
 	}
-
+	
 	logger($pa_config, "Finished recon task for net " . $task->{'subnet'} . ".", 10);
-
+	
 	# Mark recon task as done
 	update_recon_task ($dbh, $task_id, -1);
 }
@@ -324,9 +327,11 @@
 	my ($pa_config, $host, $dbh, $group, $max_depth, $resolve, $os_detect) = @_;
 	
 	# Call nmap
+	my $timeout = $pa_config->{'networktimeout'}*1000;
+	my $nmap_args  = '-nsP -PE --traceroute --max-retries '.$pa_config->{'icmp_checks'}.' --host-timeout '.$timeout.' -T'.$pa_config->{'nmap_timing_template'};
 	my $np = new PandoraFMS::NmapParser;
 	eval {
-		$np->parsescan($pa_config->{'nmap'},'-nsP --traceroute', ($host));
+		$np->parsescan($pa_config->{'nmap'}, $nmap_args, ($host));
 	};
 	if ($@) {
 		return 0;
@@ -388,12 +393,13 @@
 		if ($os_detect == 1) {
 			$id_os = guess_os ($pa_config, $dbh, $host_addr);
 		}
-	
+		
 		# Create the host
 		my $agent_id = pandora_create_agent ($pa_config, $pa_config->{'servername'}, $host_name, $host_addr, $group, $parent_id, $id_os, '', 300, $dbh);
 		$agent_id = 0 unless defined ($parent_id);
-		db_do ($dbh, 'INSERT INTO taddress_agent (`id_a`, `id_agent`)
-			          VALUES (?, ?)', $addr_id, $agent_id);
+		db_do ($dbh, 'INSERT INTO taddress_agent (' . $RDBMS_QUOTE . 'id_a' . $RDBMS_QUOTE . ',' .
+			$RDBMS_QUOTE . 'id_agent' . $RDBMS_QUOTE . ')
+			VALUES (?, ?)', $addr_id, $agent_id);
 		
 		# Move to the next host
 		$parent_id = $agent_id;
@@ -417,9 +423,9 @@
 # Guess OS using xprobe2.
 ##########################################################################
 sub guess_os {
-    my ($pa_config, $dbh, $host) = @_;
-    
-    # Use xprobe2 if available
+	my ($pa_config, $dbh, $host) = @_;
+	
+	# Use xprobe2 if available
 	my $xprobe = $pa_config->{'xprobe2'};
 	if (-e $xprobe){
 			my $output = `$xprobe $host 2>$DEVNULL | grep 'Running OS' | head -1`;
Index: lib/PandoraFMS/DataServer.pm
===================================================================
--- lib/PandoraFMS/DataServer.pm	(revision 10314)
+++ lib/PandoraFMS/DataServer.pm	(working copy)
@@ -528,7 +528,7 @@
 	            'str_warning' => '', 'str_critical' => '', 'critical_instructions' => '', 'warning_instructions' => '',
 	            'unknown_instructions' => '', 'tags' => '', 'critical_inverse' => 0, 'warning_inverse' => 0, 'quiet' => 0,
 	            'module_ff_interval' => 0};
-
+	
 	# Other tags will be saved here
 	$module_conf->{'extended_info'} = '';
 	
@@ -539,8 +539,8 @@
 		} else {
 			$module_conf->{'extended_info'} .= "$tag: " . get_tag_value ($data, $tag, '') . '<br/>';
 		}
-	}	
-		
+	}
+	
 	# Description XML tag and column name don't match
 	$module_conf->{'descripcion'} = $module_conf->{'description'};
 	$module_conf->{'descripcion'} = '' unless defined ($module_conf->{'descripcion'});
@@ -549,14 +549,21 @@
 	# Name XML tag and column name don't match
 	$module_conf->{'nombre'} = safe_input($module_name);
 	delete $module_conf->{'name'};
-
+	
 	# Calculate the module interval in seconds
 	$module_conf->{'module_interval'} = 1 unless defined ($module_conf->{'module_interval'});
 	$module_conf->{'module_interval'} *= $interval if (defined ($module_conf->{'module_interval'}));
-
+	
 	# Allow , as a decimal separator
 	$module_conf->{'post_process'} =~ s/,/./ if (defined ($module_conf->{'post_process'}));
 
+	# avoid NULL columns
+	$module_conf->{'critical_instructions'} = '' unless defined ($module_conf->{'critical_instructions'});
+	$module_conf->{'warning_instructions'} = '' unless defined ($module_conf->{'warning_instructions'});
+	$module_conf->{'unknown_instructions'} = '' unless defined ($module_conf->{'unknown_instructions'});
+	$module_conf->{'disabled_types_event'} = '' unless defined ($module_conf->{'disabled_types_event'});
+	$module_conf->{'module_macros'} = '' unless defined ($module_conf->{'module_macros'});
+	
 	# Get module data or create it if it does not exist
 	$ModuleSem->down ();
 	my $module = get_db_single_row ($dbh, 'SELECT * FROM tagente_modulo WHERE id_agente = ? AND ' . db_text ('nombre') . ' = ?', $agent->{'id_agente'}, safe_input($module_name));
@@ -568,14 +575,14 @@
 			$ModuleSem->up ();
 			return;
 		}
-
+		
 		# Is the agent learning?
 		if ($agent->{'modo'} ne '1') {
 			logger($pa_config, "Learning mode disabled. Skipping module '$module_name' agent '$agent_name'.", 10);
 			$ModuleSem->up ();
 			return;
 		}
-
+		
 		# Get the module type
 		$module_conf->{'id_tipo_modulo'} = get_module_id ($dbh, $module_type);
 		if ($module_conf->{'id_tipo_modulo'} <= 0) {
@@ -583,16 +590,16 @@
 			$ModuleSem->up ();
 			return;
 		}
-	
+		
 		# The group name has to be translated to a group ID
 		if (defined $module_conf->{'module_group'}) {
 			$module_conf->{'id_module_group'} = get_module_group_id ($dbh, $module_conf->{'module_group'});
 			delete $module_conf->{'module_group'};
 		}
-
+		
 		$module_conf->{'id_modulo'} = 1;
 		$module_conf->{'id_agente'} = $agent->{'id_agente'};
-
+		
 		my $module_tags = undef;
 		if(defined ($module_conf->{'tags'})) {
 			$module_tags = $module_conf->{'tags'};
@@ -601,7 +608,7 @@
 		
 		# Create the module
 		my $module_id = pandora_create_module_from_hash ($pa_config, $module_conf, $dbh);
-
+		
 		$module = get_db_single_row ($dbh, 'SELECT * FROM tagente_modulo WHERE id_agente = ? AND ' . db_text('nombre') . ' = ?', $agent->{'id_agente'}, safe_input($module_name));
 		if (! defined ($module)) {
 			logger($pa_config, "Could not create module '$module_name' for agent '$agent_name'.", 3);
@@ -626,7 +633,8 @@
 			}
 		}
 		
-	} else {
+	}
+	else {
 		# Control NULL columns
 		$module->{'descripcion'} = '' unless defined ($module->{'descripcion'});
 		$module->{'extended_info'} = '' unless defined ($module->{'extended_info'});
@@ -649,15 +657,15 @@
 	if ($agent->{'modo'} eq '1' && $policy_linked == 0) {
 		update_module_configuration ($pa_config, $dbh, $module, $module_conf);
 	}
-
+	
 	$ModuleSem->up ();
-
+	
 	# Module disabled!
 	if ($module->{'disabled'} eq '1') {
 		logger($pa_config, "Skipping disabled module '$module_name' agent '$agent_name'.", 10);
 		return;
 	}
-
+	
 	# Parse the timestamp and process the module
 	if ($timestamp !~ /(\d+)\/(\d+)\/(\d+) +(\d+):(\d+):(\d+)/ &&
 		$timestamp !~ /(\d+)\-(\d+)\-(\d+) +(\d+):(\d+):(\d+)/) {
Index: bin/pandora_server
===================================================================
--- bin/pandora_server	(revision 10314)
+++ bin/pandora_server	(working copy)
@@ -47,11 +47,22 @@
 my @Servers;
 my $DBH;
 my $RUN :shared = 1;
+my $MainThread = threads->self;
 
 ########################################################################################
 # Server shutdown. Handler to do a controlled shutdown.
 ########################################################################################
 sub pandora_shutdown () {
+	my $signal = shift;
+
+	logger (\%Config, 'Pandora FMS Server \'' . $Config{'servername'} . '\' Caught SIG' . $signal . ' by thread(' . threads->self()->tid() . ')', 10);
+
+	if (!threads->self->equal($MainThread)) {
+		# deliver signal to the main thread since no other threads than main thread
+		# could disconnet $DBH properly
+		$MainThread->kill($signal);
+		return;
+	}
 	logger (\%Config, 'Pandora FMS Server \'' . $Config{'servername'} . '\' Shutdown by signal ', 1);
 	
 	# Stop servers
Index: pandora_server.redhat.spec
===================================================================
--- pandora_server.redhat.spec	(revision 10314)
+++ pandora_server.redhat.spec	(working copy)
@@ -28,6 +28,7 @@
 Requires:           perl-NetAddr-IP net-snmp net-tools
 Requires:           perl-IO-Socket-INET6 perl-Socket6 perl-Net-Telnet
 Requires:           nmap wmic sudo perl-JSON
+Requires:           perl-Time-HiRes
 
 %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.
Index: FreeBSD/pandora_server.conf.new
===================================================================
--- FreeBSD/pandora_server.conf.new	(revision 0)
+++ FreeBSD/pandora_server.conf.new	(revision 10417)
@@ -0,0 +1,442 @@
+#############################################################################
+# Pandora FMS Server Parameters
+# Pandora FMS, the Flexible Monitoring System.
+# Version 5.1BETA1
+# Licensed under GPL license v2,
+# (c) 2003-2014 Artica Soluciones Tecnologicas
+# http://www.pandorafms.com
+# Please change it for your setup needs
+#############################################################################
+
+# Servername: Name of this server
+# if not given, it takes hostname. It's preferable to setup one
+# because machine name could change by some reason.
+
+#servername greystone
+
+# incomingdir:  Defines directory where incoming data packets are stored
+# You could set directory relative to base path or absolute, starting with /
+
+incomingdir /var/spool/pandora/data_in
+
+# log_file: Main logfile for pandora_server
+# You could set file relative to base path or absolute, starting with /
+
+log_file /var/log/pandora/pandora_server.log
+
+# Log file for Pandora FMS SNMP console. Its generated by NetSNMP Trap daemon
+
+snmp_logfile /var/log/pandora/pandora_snmptrap.log
+
+# Error logfile: aux logfile for pandora_server errors (in Daemon mode)
+# You could set file relative to base path or absolute, starting with /
+
+errorlog_file /var/log/pandora/pandora_server.error
+
+# daemon: Runs in daemon mode (background) if 1, if 0 runs in foreground 
+# this could be also configured on commandline with -D option
+
+# daemon 1
+
+# dbengine: mysql, postgresql or oracle (mysql by default)
+
+dbengine mysql
+
+# Database credentials. A VERY important configuration.
+# This must be the same credentials used by your Pandora FMS Console
+# but could be different if your console is not running in the same
+# host than the server. Check your console setup in /include/config.php
+
+# dbname: Database name (pandora by default)
+
+dbname pandora
+
+# dbuser:  Database user name (pandora by default)
+
+dbuser pandora
+
+# dbpass: Database password
+
+dbpass pandora
+
+# dbhost: Database hostname or IP address
+
+dbhost 127.0.0.1
+
+# dbport: Database port number
+# Default value depends on the dbengine (mysql: 3306, postgresql: 5432, oracle: 1521)
+
+#dbport 3306
+
+# By default, parent agent will not be updated
+
+#update_parent 0
+
+# verbosity: level of detail on errors/messages (0 default, 1 verbose, 2 debug.... 10 noisy)
+# -v in command line (verbose) or -d (debug). Set this to 10 when try to locate problems and
+# set to 0 or 1 on production enviroments.
+
+verbosity 1
+
+# Master Server, 1 if master server (normal mode), 0 for slave mode (slave in multi-server setup)
+
+master 1
+
+# Activate Pandora SNMP console (depending on snmptrapd)
+
+snmpconsole 0
+
+# snmptrapd will ignore authenticationFailure traps if set to 1.
+
+snmp_ignore_authfailure 1
+
+# snmptrapd will read the PDU source address instead of the agent-addr field is set to 1.
+
+snmp_pdu_address 0
+
+# Activate (1) Pandora Network Server 
+
+networkserver 1
+
+# Activate (1) Pandora Data Server
+
+dataserver 1
+
+# Activate (1) Pandora FMS Recon server
+
+reconserver 1
+
+# pluginserver : 1 or 0. Set to 1 to activate plugin server with this setup
+
+pluginserver 1 
+
+# Pandora FMS Plugin exec tool filepath (by default at /usr/local/bin)
+
+plugin_exec /usr/local/bin/gtimeout
+
+# predictionserver : 1 or 0. Set to 1 to activate prediction server with this setup
+# DISABLED BY DEFAULT 
+
+predictionserver 0
+
+# wmiserver : 1 or 0. Set to 1 to activate WMI server with this setup
+# DISABLED BY DEFAULT
+
+wmiserver 1
+
+# wmic: Needed by Pandora FMS wmi server.
+
+wmi_client /usr/local/bin/wmic
+
+# Network timeout (in seconds) for timeout in network connections for Network agents
+
+network_timeout 4
+
+# Server keepalive (in seconds)
+
+server_keepalive 45
+
+# Server Threshold: defines number of seconds of main loop (in sec)
+
+server_threshold 5
+
+# Network threads: Do not set too high (~40). Each threads make a network module check.
+
+network_threads 4
+
+# icmp_checks x : defines number of pings for each icmp_proc module type. at least one of 
+# that ping should be 1 to report 1
+
+icmp_checks 1
+
+# tcp specific options :
+# tcp_checks: number of tcp retries if first attempt fails.
+# tcp_timeout: specific timeout for tcp connections
+
+tcp_checks 1
+tcp_timeout 10
+
+# snmp specific options :
+# snmp_checks: number of snmp request retries if first attempt fails.
+# snmp_timeout: specific timeout for snmp request.
+
+snmp_checks 1
+snmp_timeout 4
+
+# snmp_proc_deadresponse 1 (default): Return DOWN if cannot contact 
+# or receive NULL from a SNMP PROC module.
+
+snmp_proc_deadresponse 1
+
+# plugin_threads: Specify number of plugin server threads for processing plugin calls
+
+plugin_threads 1
+
+# plugin_timeout: Specify number of seconds calling plugin exec waiting for response
+# after this time, call is aborted and result is "unknown".
+
+plugin_timeout 12
+
+# wmi_timeout : specific timeout for wmi request.
+
+wmi_timeout 7
+
+# wmi_threads: Specify number of WMI server threads for processing WMI remote calls
+
+wmi_threads 1
+
+# recon_threads. Each thread will scan a different scantask.
+
+recon_threads 1
+
+# dataserver_threads: Number of threads for data server (XML processing threads)
+
+dataserver_threads 1
+
+# mta_address: External Mailer (MTA) IP Address to be used by Pandora FMS internal email capabilities
+
+mta_address localhost
+
+# mta_port, this is the mail server port (default 25)
+
+#mta_port 25
+
+# mta_user MTA User (if needed for auth, FQD or simple user, depending on your server)
+
+#mta_user myuser@mydomain.com
+
+# mta_pass MTA Pass (if needed for auth)
+
+#mta_pass mypassword
+
+# mta_auth MTA Auth system (if needed, it supports LOGIN, PLAIN, CRAM-MD5, DIGEST-MD)
+
+#mta_auth LOGIN
+
+# mta_from Email address that sends the mail, by default is pandora@localhost 
+#           probably you need to change it to avoid problems with your antispam
+
+#mta_from Pandora FMS <pandora@mydomain.com>
+
+# Set 1 if want eMail deliver alert in separate mail  (default). 
+# Set 0 if want eMail deliver shared mail by all destination.
+mail_in_separate 1
+
+
+# xprobe2: Optional package to detect OS types using advanced TCP/IP 
+# fingerprinting tecniques, much more accurates than stadard nmap.
+# If not provided, nmap is used insted xprobe2
+
+xprobe2 /usr/local/bin/xprobe2
+
+# nmap: If provided, is used to detect OS type with recon server using 
+# advanded OS fingerprint technique. Xprobe2 gives more accurate results
+# Nmap is also used to do TCP port scanning in detected host.
+
+nmap /usr/local/bin/nmap
+
+# snmpget: Needed to do SNMP checks. By default is on /usr/local/bin/snmpget
+
+snmpget /usr/local/bin/snmpget
+
+# snmp_trapd: Needed by Pandora FMS SNMP console.
+
+snmp_trapd /usr/local/sbin/snmptrapd
+
+# Location of the braa binary needed by the Enterprise SNMP Server (/usr/local/bin/braa by default) (PANDORA FMS ENTERPRISE ONLY).
+
+braa /usr/local/bin/braa
+
+# Number of retries before braa hands a module over to the Network Server (PANDORA FMS ENTERPRISE ONLY).
+
+braa_retries 3
+
+# Default group id for new agents created with Pandora FMS Data Server
+
+autocreate_group 2
+
+# Set to 1 if want to autocreate agents with Pandora FMS Data Server, 
+# set to 0 to disable (for security purposes, for example).
+
+autocreate 1
+
+# max_log_size: Specify max size of Pandora FMS server log file (1MB by default). If
+# log file grows above this limit, is renamed to "pandora_server.log.old".
+
+max_log_size 65536
+
+# max_queue_files (500 by default)
+# When server have more than max_queue_files in incoming directory, skips the read   
+# the directory to avoid filesystem overhead.
+
+max_queue_files 500
+
+# Use the XML file last modification time as timestamp.
+# use_xml_timestamp 1
+
+# Pandora FMS will autorestart itself each XXX seconds, use this if you experience problems with 
+# shutting down threads, or other stability problems.
+
+# auto_restart 86400
+
+# Pandora FMS will restart after restart_delay seconds on critical errors.
+
+restart 1
+restart_delay 60
+
+# More information about GIS Setup in /usr/share/pandora_server/util/gis.README
+# Flag to activate GIS (positional information for agents and maps) 
+# by default it is desactivated
+
+#activate_gis 0
+
+# Radius of error in meters to consider two gis locations as the same location.
+
+#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).
+
+#recon_reverse_geolocation_file /usr/local/share/GeoIP/GeoIPCity.dat
+
+# Radius (in meters) of the circle in where the agents will be place randomly 
+# when finded by a recon task. Center of the circle is guessed 
+# by geolocating the IP.
+#recon_location_scatter_radius 1000
+
+# Pandora Server self-monitoring (embedded agent) (by default enabled)
+
+self_monitoring 1
+
+# Update parent from the agent xml
+
+#update_parent 1
+#
+#
+# This enable realtime reverse geocoding using Google Maps public api.
+# This requires internet access, and could have performance penalties processing GIS
+# information due the connetion needed to resolve all GIS input.
+# NOTE: If you dont pay the service to google, they will ban your IP in a few days.
+
+# google_maps_description 1
+
+# This enable realtime reverse geocoding using Openstreet Maps public api.
+# This requires internet access, and could have performance penalties processing GIS
+# information due the connetion needed to resolve all GIS input.
+# You can alter the code to use a local (your own) openstreet maps server.
+
+# openstreetmaps_description 1
+
+# Enable (1) or disable (0) Pandora FMS Event Web Server (PANDORA FMS ENTERPRISE ONLY).
+
+webserver 1
+
+# Number of threads for the Web Server (PANDORA FMS ENTERPRISE ONLY).
+
+web_threads 1
+
+# Enable (1) or disable (0) Pandora FMS Inventory Server (PANDORA FMS ENTERPRISE ONLY).
+
+inventoryserver 1
+
+# Number of threads for the Web Server (PANDORA FMS ENTERPRISE ONLY).
+
+inventory_threads 1
+
+# Enable (1) or disable (0) Pandora FMS Export Server (PANDORA FMS ENTERPRISE ONLY).
+
+exportserver 0
+
+# Number of threads for the Export Server (PANDORA FMS ENTERPRISE ONLY).
+
+export_threads 1
+
+# Enable (1) or disable (0) Pandora FMS Event Server (PANDORA FMS ENTERPRISE ONLY).
+
+eventserver 0
+
+# Event Server event window in seconds (3600 by default) (PANDORA FMS ENTERPRISE ONLY).
+
+event_window 3600
+
+# Enable (1) or disable (0) Pandora FMS Enterprise ICMP Server (PANDORA FMS ENTERPRISE ONLY).
+# You need nmap 5.20 or higher in order to use this !
+
+icmpserver 1
+
+# Number of threads for the Enterprise ICMP Server (PANDORA FMS ENTERPRISE ONLY).
+
+icmp_threads 1
+
+# Enable (1) or disable (0) Pandora FMS Enterprise SNMP Server (PANDORA FMS ENTERPRISE ONLY).
+# Check braa tool is running and operative.
+
+snmpserver 1
+
+# Number of threads for the Enterprise SNMP Server (PANDORA FMS ENTERPRISE ONLY).
+
+snmp_threads 1
+
+# Block size for block producer/consumer servers, that is, the number of modules
+# per block (20 by default) (PANDORA FMS ENTERPRISE ONLY).
+
+block_size 20
+
+# Path to the netflow daemon nfcapd.
+
+netflow_daemon /usr/local/bin/nfcapd
+
+# If set to 1, process XML data files in a stack instead of a queue. 0 by default.
+# WARNING: Incremental modules will not work properly if dataserver_lifo is set to 1!!!
+
+dataserver_lifo 0
+
+# If set to 1, the policy manager is enabled and the server is listening the policy queue. 
+# 0 by default (PANDORA FMS ENTERPRISE ONLY) 
+
+policy_manager 1
+
+# If set to 1, the event replicate process is enabled. 0 by default. (PANDORA FMS ENTERPRISE ONLY) 
+# WARNING: This process doesn't do anything if is not properly configured from the console setup 
+
+event_replication 0
+
+# If set to 1, new events validate older event for the same module. This will
+# affect the performance of the server. This was the "normal behaviour" on previous (4.x) versions.
+# disable only if you really know what you are doing !!.
+
+event_auto_validation 1
+
+# If defined, events generated by Pandora FMS will be written to the specified text file.
+#event_file /var/log/pandora/pandora_events.txt
+
+# Set the maximum number of traps that will be processed from a single source in a
+# configured time interval.
+snmp_storm_protection 25
+
+# Time interval for snmp_storm protection (in seconds).
+snmp_storm_timeout 10
+
+# Default texts for some events. The macros _module_ and _data_ are supported.
+#text_going_down_normal Module '_module_' is going to NORMAL (_data_)
+#text_going_up_critical Module '_module_' is going to CRITICAL (_data_)
+#text_going_up_warning Module '_module_' is going to WARNING (_data_)
+#text_going_down_warning Module '_module_' is going to WARNING (_data_)
+#text_going_unknown Module '_module_' is going to UNKNOWN
+
+# Events older that the specified time (in seconds) will be auto-validated. Set to 0 to disable this feature.
+event_expiry_time 0
+
+# Only events more recent than the specified time window (in seconds) will be auto-validated. This value must
+# be greater than event_expiry_time.
+#event_expiry_window 86400
Index: FreeBSD/tentacle_server
===================================================================
--- FreeBSD/tentacle_server	(revision 10314)
+++ FreeBSD/tentacle_server	(working copy)
@@ -18,28 +18,27 @@
 . "/etc/rc.subr"
 
 name="tentacle_server"
-rcvar=`set_rcvar`
+rcvar=tentacle_server_enable
 
 # read configuration and set defaults
 tentacle_server_enable=${tentacle_server_enable:-"NO"}
-tentacle_server_flags=${tentacle_server_flags:-"-a 0.0.0.0 -p 41121 -s /var/spool/pandora/data_in -i.*\.conf:conf\;.*\.md5:md5\;.*\.zip:collections -d"}
+tentacle_server_flags=${tentacle_server_flags:-'-a 0.0.0.0 -p 41121 -s /var/spool/pandora/data_in -i.*\.conf:conf\;.*\.md5:md5\;.*\.zip:collections -d'}
 tentacle_server_user=${tentacle_server_user:-"pandora"}
 load_rc_config $name
 
 PATH=/bin:/usr/bin:/sbin:/usr/sbin:/usr/local/bin
 
 command=/usr/local/bin/${name}
+command_interpreter=/usr/local/bin/perl
+procname=$command
+pidfile=/var/run/$name.pid
 
-pidfile=/var/run/$name.pid
 start_postcmd=start_postcmd
 stop_postcmd=stop_postcmd
 
-procname="/usr/bin/perl"
-
 start_postcmd()
 {
-	TENTACLE_PID=`pgrep -f -j none "$procname $command"`
-	echo $TENTACLE_PID > $pidfile
+	pgrep -f -j none "^$command_interpreter $command" > $pidfile
 }
 
 stop_postcmd()
Index: FreeBSD/pandora_server
===================================================================
--- FreeBSD/pandora_server	(revision 10314)
+++ FreeBSD/pandora_server	(working copy)
@@ -3,6 +3,7 @@
 # **********************************************************************
 # Pandora FMS Server Daemon launcher for FreeBSD
 # (c) 2010 Junichi Satoh <junichi@rworks.jp>
+# (c) 2014 Koichiro Kikuchi <koichiro@rworks.jp>
 #
 # **********************************************************************
 
@@ -10,27 +11,65 @@
 # REQUIRE: LOGIN mysql
 # KEYWORD: shutdown
 
-# Add the following line to /etc/rc.conf to enable `pandora_server':
+# Add the following lines to /etc/rc.conf to enable pandora_server:
+# pandora_server_enable (bool):  Set to "YES" to enable pandora_server (default: NO)
+# pandora_server_profiles (str): Define your profiles here (default: "")
 #
-# pandora_server_enable="YES"
-#
 
 . "/etc/rc.subr"
 
+PATH=/bin:/usr/bin:/sbin:/usr/sbin:/usr/local/bin
+
 name="pandora_server"
-rcvar=`set_rcvar`
+rcvar=pandora_server_enable
 
-# read configuration and set defaults
-pandora_server_enable=${pandora_server_enable:-"NO"}
+: ${pandora_server_enable:=NO}
+: ${pandora_server_configfile:=/usr/local/etc/pandora/pandora_server.conf}
+
+command=/usr/local/bin/${name}
+command_args="-D"
+command_interpreter=/usr/local/bin/perl
+_pidprefix=/var/run/$name
+pidfile=${_pidprefix}.pid
+required_files="$pandora_server_configfile"
+
 load_rc_config $name
 
-PATH=/bin:/usr/bin:/sbin:/usr/sbin:/usr/local/bin
+if [ "$2" ]; then
+	profile="$2"
+	if [ "$pandora_server_profiles" ]; then
+		pidfile="${_pidprefix}.${profile}.pid"
+		eval pandora_server_configfile="\${pandora_server_${profile}_configfile:-}"
+		if [ -z "$pandora_server_configfile" ]; then
+			echo "You must define a configuration file (pandora_server_${profile}_configfile)"
+			exit 1
+		fi
+		required_files="$pandora_server_configfile"
+		eval pandora_server_enable="\${pandora_server_${profile}_enable:-$pandora_server_enable}"
+		eval pandora_server_flags="\${pandora_server_${profile}_flags:-$pandora_server_flags}"
+		eval pidfile="\${pandora_server_${profile}_pidfile:-$pidfile}"
+	else
+		echo "$0: extra argument ignored"
+	fi
+elif [ "${pandora_server_profiles}" ] && [ "$1" ]; then
+	for profile in ${pandora_server_profiles}; do
+		eval _enable="\${pandora_server_${profile}_enable}"
+		case "${_enable:-${pandora_server_enable}}" in
+		[Yy][Ee][Ss]);;
+		*) continue;;
+		esac
+		echo "===> pandora_server profile: ${profile}"
+		/usr/local/etc/rc.d/pandora_server $1 ${profile}
+		retcode="$?"
+		if [ "0${retcode}" -ne 0 ]; then
+			failed="${profile} (${retcode}) ${failed:-}"
+		else
+			success="${profile} ${success:-}"
+		fi
+	done
+	exit 0
+fi
 
-pidfile=/var/run/$name.pid
-command=/usr/local/bin/${name}
-command_args="-D -P ${pidfile} /usr/local/etc/pandora/pandora_server.conf"
-required_files="/usr/local/etc/pandora/pandora_server.conf"
+pandora_server_flags="$pandora_server_flags -P $pidfile $pandora_server_configfile"
 
-procname="/usr/local/bin/perl"
-
 run_rc_command "$1"
Index: FreeBSD/pandora_server.conf
===================================================================
--- FreeBSD/pandora_server.conf	(revision 10314)
+++ FreeBSD/pandora_server.conf	(working copy)
@@ -1,442 +0,0 @@
-#############################################################################
-# Pandora FMS Server Parameters
-# Pandora FMS, the Flexible Monitoring System.
-# Version 5.1BETA1
-# Licensed under GPL license v2,
-# (c) 2003-2014 Artica Soluciones Tecnologicas
-# http://www.pandorafms.com
-# Please change it for your setup needs
-#############################################################################
-
-# Servername: Name of this server
-# if not given, it takes hostname. It's preferable to setup one
-# because machine name could change by some reason.
-
-#servername greystone
-
-# incomingdir:  Defines directory where incoming data packets are stored
-# You could set directory relative to base path or absolute, starting with /
-
-incomingdir /var/spool/pandora/data_in
-
-# log_file: Main logfile for pandora_server
-# You could set file relative to base path or absolute, starting with /
-
-log_file /var/log/pandora/pandora_server.log
-
-# Log file for Pandora FMS SNMP console. Its generated by NetSNMP Trap daemon
-
-snmp_logfile /var/log/pandora/pandora_snmptrap.log
-
-# Error logfile: aux logfile for pandora_server errors (in Daemon mode)
-# You could set file relative to base path or absolute, starting with /
-
-errorlog_file /var/log/pandora/pandora_server.error
-
-# daemon: Runs in daemon mode (background) if 1, if 0 runs in foreground 
-# this could be also configured on commandline with -D option
-
-# daemon 1
-
-# dbengine: mysql, postgresql or oracle (mysql by default)
-
-dbengine mysql
-
-# Database credentials. A VERY important configuration.
-# This must be the same credentials used by your Pandora FMS Console
-# but could be different if your console is not running in the same
-# host than the server. Check your console setup in /include/config.php
-
-# dbname: Database name (pandora by default)
-
-dbname pandora
-
-# dbuser:  Database user name (pandora by default)
-
-dbuser pandora
-
-# dbpass: Database password
-
-dbpass pandora
-
-# dbhost: Database hostname or IP address
-
-dbhost 127.0.0.1
-
-# dbport: Database port number
-# Default value depends on the dbengine (mysql: 3306, postgresql: 5432, oracle: 1521)
-
-#dbport 3306
-
-# By default, parent agent will not be updated
-
-#update_parent 0
-
-# verbosity: level of detail on errors/messages (0 default, 1 verbose, 2 debug.... 10 noisy)
-# -v in command line (verbose) or -d (debug). Set this to 10 when try to locate problems and
-# set to 0 or 1 on production enviroments.
-
-verbosity 1
-
-# Master Server, 1 if master server (normal mode), 0 for slave mode (slave in multi-server setup)
-
-master 1
-
-# Activate Pandora SNMP console (depending on snmptrapd)
-
-snmpconsole 0
-
-# snmptrapd will ignore authenticationFailure traps if set to 1.
-
-snmp_ignore_authfailure 1
-
-# snmptrapd will read the PDU source address instead of the agent-addr field is set to 1.
-
-snmp_pdu_address 0
-
-# Activate (1) Pandora Network Server 
-
-networkserver 1
-
-# Activate (1) Pandora Data Server
-
-dataserver 1
-
-# Activate (1) Pandora FMS Recon server
-
-reconserver 1
-
-# pluginserver : 1 or 0. Set to 1 to activate plugin server with this setup
-
-pluginserver 1 
-
-# Pandora FMS Plugin exec tool filepath (by default at /usr/local/bin)
-
-plugin_exec /usr/local/bin/gtimeout
-
-# predictionserver : 1 or 0. Set to 1 to activate prediction server with this setup
-# DISABLED BY DEFAULT 
-
-predictionserver 0
-
-# wmiserver : 1 or 0. Set to 1 to activate WMI server with this setup
-# DISABLED BY DEFAULT
-
-wmiserver 1
-
-# wmic: Needed by Pandora FMS wmi server.
-
-wmi_client /usr/local/bin/wmic
-
-# Network timeout (in seconds) for timeout in network connections for Network agents
-
-network_timeout 4
-
-# Server keepalive (in seconds)
-
-server_keepalive 45
-
-# Server Threshold: defines number of seconds of main loop (in sec)
-
-server_threshold 5
-
-# Network threads: Do not set too high (~40). Each threads make a network module check.
-
-network_threads 4
-
-# icmp_checks x : defines number of pings for each icmp_proc module type. at least one of 
-# that ping should be 1 to report 1
-
-icmp_checks 1
-
-# tcp specific options :
-# tcp_checks: number of tcp retries if first attempt fails.
-# tcp_timeout: specific timeout for tcp connections
-
-tcp_checks 1
-tcp_timeout 10
-
-# snmp specific options :
-# snmp_checks: number of snmp request retries if first attempt fails.
-# snmp_timeout: specific timeout for snmp request.
-
-snmp_checks 1
-snmp_timeout 4
-
-# snmp_proc_deadresponse 1 (default): Return DOWN if cannot contact 
-# or receive NULL from a SNMP PROC module.
-
-snmp_proc_deadresponse 1
-
-# plugin_threads: Specify number of plugin server threads for processing plugin calls
-
-plugin_threads 1
-
-# plugin_timeout: Specify number of seconds calling plugin exec waiting for response
-# after this time, call is aborted and result is "unknown".
-
-plugin_timeout 12
-
-# wmi_timeout : specific timeout for wmi request.
-
-wmi_timeout 7
-
-# wmi_threads: Specify number of WMI server threads for processing WMI remote calls
-
-wmi_threads 1
-
-# recon_threads. Each thread will scan a different scantask.
-
-recon_threads 1
-
-# dataserver_threads: Number of threads for data server (XML processing threads)
-
-dataserver_threads 1
-
-# mta_address: External Mailer (MTA) IP Address to be used by Pandora FMS internal email capabilities
-
-mta_address localhost
-
-# mta_port, this is the mail server port (default 25)
-
-#mta_port 25
-
-# mta_user MTA User (if needed for auth, FQD or simple user, depending on your server)
-
-#mta_user myuser@mydomain.com
-
-# mta_pass MTA Pass (if needed for auth)
-
-#mta_pass mypassword
-
-# mta_auth MTA Auth system (if needed, it supports LOGIN, PLAIN, CRAM-MD5, DIGEST-MD)
-
-#mta_auth LOGIN
-
-# mta_from Email address that sends the mail, by default is pandora@localhost 
-#           probably you need to change it to avoid problems with your antispam
-
-#mta_from Pandora FMS <pandora@mydomain.com>
-
-# Set 1 if want eMail deliver alert in separate mail  (default). 
-# Set 0 if want eMail deliver shared mail by all destination.
-mail_in_separate 1
-
-
-# xprobe2: Optional package to detect OS types using advanced TCP/IP 
-# fingerprinting tecniques, much more accurates than stadard nmap.
-# If not provided, nmap is used insted xprobe2
-
-xprobe2 /usr/local/bin/xprobe2
-
-# nmap: If provided, is used to detect OS type with recon server using 
-# advanded OS fingerprint technique. Xprobe2 gives more accurate results
-# Nmap is also used to do TCP port scanning in detected host.
-
-nmap /usr/local/bin/nmap
-
-# snmpget: Needed to do SNMP checks. By default is on /usr/local/bin/snmpget
-
-snmpget /usr/local/bin/snmpget
-
-# snmp_trapd: Needed by Pandora FMS SNMP console.
-
-snmp_trapd /usr/local/sbin/snmptrapd
-
-# Location of the braa binary needed by the Enterprise SNMP Server (/usr/local/bin/braa by default) (PANDORA FMS ENTERPRISE ONLY).
-
-braa /usr/local/bin/braa
-
-# Number of retries before braa hands a module over to the Network Server (PANDORA FMS ENTERPRISE ONLY).
-
-braa_retries 3
-
-# Default group id for new agents created with Pandora FMS Data Server
-
-autocreate_group 2
-
-# Set to 1 if want to autocreate agents with Pandora FMS Data Server, 
-# set to 0 to disable (for security purposes, for example).
-
-autocreate 1
-
-# max_log_size: Specify max size of Pandora FMS server log file (1MB by default). If
-# log file grows above this limit, is renamed to "pandora_server.log.old".
-
-max_log_size 65536
-
-# max_queue_files (500 by default)
-# When server have more than max_queue_files in incoming directory, skips the read   
-# the directory to avoid filesystem overhead.
-
-max_queue_files 500
-
-# Use the XML file last modification time as timestamp.
-# use_xml_timestamp 1
-
-# Pandora FMS will autorestart itself each XXX seconds, use this if you experience problems with 
-# shutting down threads, or other stability problems.
-
-# auto_restart 86400
-
-# Pandora FMS will restart after restart_delay seconds on critical errors.
-
-restart 1
-restart_delay 60
-
-# More information about GIS Setup in /usr/share/pandora_server/util/gis.README
-# Flag to activate GIS (positional information for agents and maps) 
-# by default it is desactivated
-
-#activate_gis 0
-
-# Radius of error in meters to consider two gis locations as the same location.
-
-#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).
-
-#recon_reverse_geolocation_file /usr/local/share/GeoIP/GeoIPCity.dat
-
-# Radius (in meters) of the circle in where the agents will be place randomly 
-# when finded by a recon task. Center of the circle is guessed 
-# by geolocating the IP.
-#recon_location_scatter_radius 1000
-
-# Pandora Server self-monitoring (embedded agent) (by default enabled)
-
-self_monitoring 1
-
-# Update parent from the agent xml
-
-#update_parent 1
-#
-#
-# This enable realtime reverse geocoding using Google Maps public api.
-# This requires internet access, and could have performance penalties processing GIS
-# information due the connetion needed to resolve all GIS input.
-# NOTE: If you dont pay the service to google, they will ban your IP in a few days.
-
-# google_maps_description 1
-
-# This enable realtime reverse geocoding using Openstreet Maps public api.
-# This requires internet access, and could have performance penalties processing GIS
-# information due the connetion needed to resolve all GIS input.
-# You can alter the code to use a local (your own) openstreet maps server.
-
-# openstreetmaps_description 1
-
-# Enable (1) or disable (0) Pandora FMS Event Web Server (PANDORA FMS ENTERPRISE ONLY).
-
-webserver 1
-
-# Number of threads for the Web Server (PANDORA FMS ENTERPRISE ONLY).
-
-web_threads 1
-
-# Enable (1) or disable (0) Pandora FMS Inventory Server (PANDORA FMS ENTERPRISE ONLY).
-
-inventoryserver 1
-
-# Number of threads for the Web Server (PANDORA FMS ENTERPRISE ONLY).
-
-inventory_threads 1
-
-# Enable (1) or disable (0) Pandora FMS Export Server (PANDORA FMS ENTERPRISE ONLY).
-
-exportserver 0
-
-# Number of threads for the Export Server (PANDORA FMS ENTERPRISE ONLY).
-
-export_threads 1
-
-# Enable (1) or disable (0) Pandora FMS Event Server (PANDORA FMS ENTERPRISE ONLY).
-
-eventserver 0
-
-# Event Server event window in seconds (3600 by default) (PANDORA FMS ENTERPRISE ONLY).
-
-event_window 3600
-
-# Enable (1) or disable (0) Pandora FMS Enterprise ICMP Server (PANDORA FMS ENTERPRISE ONLY).
-# You need nmap 5.20 or higher in order to use this !
-
-icmpserver 1
-
-# Number of threads for the Enterprise ICMP Server (PANDORA FMS ENTERPRISE ONLY).
-
-icmp_threads 1
-
-# Enable (1) or disable (0) Pandora FMS Enterprise SNMP Server (PANDORA FMS ENTERPRISE ONLY).
-# Check braa tool is running and operative.
-
-snmpserver 1
-
-# Number of threads for the Enterprise SNMP Server (PANDORA FMS ENTERPRISE ONLY).
-
-snmp_threads 1
-
-# Block size for block producer/consumer servers, that is, the number of modules
-# per block (20 by default) (PANDORA FMS ENTERPRISE ONLY).
-
-block_size 20
-
-# Path to the netflow daemon nfcapd.
-
-netflow_daemon /usr/local/bin/nfcapd
-
-# If set to 1, process XML data files in a stack instead of a queue. 0 by default.
-# WARNING: Incremental modules will not work properly if dataserver_lifo is set to 1!!!
-
-dataserver_lifo 0
-
-# If set to 1, the policy manager is enabled and the server is listening the policy queue. 
-# 0 by default (PANDORA FMS ENTERPRISE ONLY) 
-
-policy_manager 1
-
-# If set to 1, the event replicate process is enabled. 0 by default. (PANDORA FMS ENTERPRISE ONLY) 
-# WARNING: This process doesn't do anything if is not properly configured from the console setup 
-
-event_replication 0
-
-# If set to 1, new events validate older event for the same module. This will
-# affect the performance of the server. This was the "normal behaviour" on previous (4.x) versions.
-# disable only if you really know what you are doing !!.
-
-event_auto_validation 1
-
-# If defined, events generated by Pandora FMS will be written to the specified text file.
-#event_file /var/log/pandora/pandora_events.txt
-
-# Set the maximum number of traps that will be processed from a single source in a
-# configured time interval.
-snmp_storm_protection 25
-
-# Time interval for snmp_storm protection (in seconds).
-snmp_storm_timeout 10
-
-# Default texts for some events. The macros _module_ and _data_ are supported.
-#text_going_down_normal Module '_module_' is going to NORMAL (_data_)
-#text_going_up_critical Module '_module_' is going to CRITICAL (_data_)
-#text_going_up_warning Module '_module_' is going to WARNING (_data_)
-#text_going_down_warning Module '_module_' is going to WARNING (_data_)
-#text_going_unknown Module '_module_' is going to UNKNOWN
-
-# Events older that the specified time (in seconds) will be auto-validated. Set to 0 to disable this feature.
-event_expiry_time 0
-
-# Only events more recent than the specified time window (in seconds) will be auto-validated. This value must
-# be greater than event_expiry_time.
-#event_expiry_window 86400
Index: util/trap_rate.sh
===================================================================
--- util/trap_rate.sh	(revision 0)
+++ util/trap_rate.sh	(revision 10417)
@@ -0,0 +1,49 @@
+#!/bin/bash
+# Calculate the rate of SNMP traps received by snmptrapd.
+TEMP_FILE="/tmp/trap_rate.tmp"
+COUNT="100"
+
+# Parse command line arguments
+if [ "$1" == "" ]; then
+	echo "Usage: $0 <path to pandora_server.conf> [trap count]"
+	exit 1
+fi
+
+if [ "$2" != "" ]; then
+        COUNT="$2"
+fi
+
+# Read the SNMP log file and generate the temporary file
+SNMP_LOG=`grep snmp_logfile $1 | cut -d' ' -f2`
+if [ ! -f "$SNMP_LOG" ]; then
+	echo "SNMP log file $SNMP_LOG does not exists or is not readable."
+	exit 1
+fi
+grep "SNMPv" "$SNMP_LOG" | tail -$COUNT | cut -d']' -f 3 | cut -d'[' -f 1 > "$TEMP_FILE"
+
+# Get the newest trap
+START=`head -1 "$TEMP_FILE"`
+if [ "$START" == "" ]; then
+	echo "START: 0 END: 0 TRAPS RECEIVED: 0 RATE: 0 traps/s"
+	exit 0
+fi
+
+# Get the oldest trap
+END=`tail -1 "$TEMP_FILE"`
+if [ "$END" == "" ]; then
+	echo "START: 0 END: 0 TRAPS RECEIVED: 0 RATE: 0 traps/s"
+	exit 0
+fi
+
+# Get the trap count
+COUNT=`cat "$SNMP_LOG" | wc -l`
+
+# Calculate the trap rate
+START_UTIME=`date +"%s" -d"$START"`
+END_UTIME=`date +"%s" -d"$END"`
+ELAPSED=$(($END_UTIME - $START_UTIME))
+RATE=`bc -l <<< "$COUNT / $ELAPSED"`
+
+echo "START: $START END: $END TRAPS RECEIVED: $COUNT RATE: $RATE traps/s"
+rm -f "$TEMP_FILE"
+

Property changes on: util/trap_rate.sh
___________________________________________________________________
Added: svn:executable
## -0,0 +1 ##
+*
\ No newline at end of property
Index: util/plugin/snmp_remote.pl
===================================================================
--- util/plugin/snmp_remote.pl	(revision 10314)
+++ util/plugin/snmp_remote.pl	(working copy)
@@ -1,5 +1,5 @@
 #!/usr/bin/perl
-#---------------------------------------------------------------------------
+#-----------------------------------------------------------------------
 # SNMP remote plugin 
 # Depending on the configuration returns the result of these modules:
 # - % Memory Use
@@ -11,7 +11,7 @@
 # Copyright (C) 2013 mario.pulido@artica.es
 #
 # License: GPLv2+
-#---------------------------------------------------------------------------
+#-----------------------------------------------------------------------
 # 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; either version 2
@@ -23,111 +23,249 @@
 # GNU General Public License for more details.
 #
 # GPL License: http://www.gnu.org/licenses/gpl.txt
-#---------------------------------------------------------------------------
+#-----------------------------------------------------------------------
 
 use strict;
 use Getopt::Std;
 
 my $VERSION = 'v1r1';
 
-#-----------------------------------------------------------------------------
+#-----------------------------------------------------------------------
 # HELP
-#-----------------------------------------------------------------------------
+#-----------------------------------------------------------------------
 
-if ($#ARGV == -1 )
-{
-		print "-H, --host=STRING\n";
-		print "\tHost IP\n";
-		print "-c, --community=STRING\n";
-		print "\tSnmp Community\n";
-		print "-m, --module=STRING\n";
-		print "\tDefine module (memuse|diskuse|process|cpuload) \n";
-		print "-d, --disk=STRING\n";
-		print "\tDefine disk name (C:, D: in Windows) or mount point (Linux)(only in diskuse module)\n";
-		print "-p, --process=STRING\n";
-		print "\tProcess or service name (only in process module)\n";
-		print "\n";
-        print "Example of use \n";
-        print "perl snmp_remoto.pl -H host -c community -m (memuse|diskuse|process|cpuload) [-p process -d disk] \n";
-        print "Version=$VERSION";
-        exit;
+if ($#ARGV == -1 ) {
+	print "-H, --host=STRING\n";
+	print "\tHost IP\n";
+	
+	print "-c, --community=STRING\n";
+	print "\tSnmp Community\n";
+	
+	print "-m, --module=STRING\n";
+	print "\tDefine module (memuse|diskuse|process|cpuload) \n";
+	
+	print "-d, --disk=STRING\n";
+	print "\tDefine disk name (C:, D: in Windows) or mount point (Linux)(only in diskuse module)\n";
+	
+	print "-p, --process=STRING\n";
+	print "\tProcess or service name (only in process module)\n";
+	
+	print "-v, --version=NUMBER\n";
+	print "\tVersion of protocol\n";
+	
+	print "-u, --user=STRING\n";
+	print "\tAuth user\n";
+	
+	print "-A, --auth=STRING\n";
+	print "\tAuth pass\n";
+	
+	print "-l, --level=STRING\n";
+	print "\tSecurity level\n";
+	
+	print "-a STRING\n";
+	print "\tAuth method\n";
+	
+	print "-x STRING\n";
+	print "\tPrivacy method\n";
+	
+	print "-X STRING\n";
+	print "\tPrivacy pass\n";
+	
+	print "\n";
+	print "Example of use \n";
+	print "perl snmp_remoto.pl -H host -c community -m (memuse|diskuse|process|cpuload) [-p process -d disk] \n";
+	print "Version=$VERSION";
+	exit;
 }
 
-my ( $host, $community, $module, $disk, $process ) = &options;
+my ($host,
+	$community,
+	$module,
+	$disk,
+	$process,
+	$version,
+	$user,
+	$pass,
+	$auth_method,
+	$privacy_method,
+	$privacy_pass ) = &options;
 
-#-------------------------------------------------------------------------------------
+#-----------------------------------------------------------------------
 # OPTIONS
-#-------------------------------------------------------------------------------------
-
+#-----------------------------------------------------------------------
 sub options {
-
-    # Get and check args
-    my %opts;
-    getopt( 'Hcmdp', \%opts );
-
-	$opts{"H"} = 0   unless ( exists( $opts{"H"} ) );
-	$opts{"c"} = 0   unless ( exists( $opts{"c"} ) );
-	$opts{"m"} = 0   unless ( exists( $opts{"m"} ) );
-	$opts{"d"} = "/"   unless ( exists( $opts{"d"} ) );
-	$opts{"p"} = 0   unless ( exists( $opts{"p"} ) );
-    return ( $opts{"H"}, $opts{"c"}, $opts{"m"}, $opts{"d"}, $opts {"p"});
+	
+	# Get and check args
+	my %opts;
+	getopt( 'HcmdpvuAlaxX', \%opts );
+	
+	#~ ' -u ' . $snmp3_auth_user .
+	#~ ' -A ' . $snmp3_auth_pass .
+	#~ ' -l ' . $snmp3_security_level .
+	#~ ' -a ' . $snmp3_auth_method .
+	#~ ' -x ' . $snmp3_privacy_method .
+	#~ ' -X' $snmp3_privacy_pass;
+	
+	$opts{"H"} = 0		unless ( exists( $opts{"H"} ) );
+	$opts{"c"} = 0		unless ( exists( $opts{"c"} ) );
+	$opts{"m"} = 0		unless ( exists( $opts{"m"} ) );
+	$opts{"d"} = "/"	unless ( exists( $opts{"d"} ) );
+	$opts{"p"} = 0		unless ( exists( $opts{"p"} ) );
+	$opts{"p"} = 0		unless ( exists( $opts{"p"} ) );
+	$opts{"v"} = 2		unless ( exists( $opts{"v"} ) );
+	$opts{"u"} = ""		unless ( exists( $opts{"u"} ) );
+	$opts{"A"} = ""		unless ( exists( $opts{"A"} ) );
+	$opts{"l"} = "noAuthNoPriv"		unless ( exists( $opts{"l"} ) );
+	$opts{"a"} = ""		unless ( exists( $opts{"a"} ) );
+	$opts{"x"} = ""		unless ( exists( $opts{"x"} ) );
+	$opts{"X"} = ""		unless ( exists( $opts{"X"} ) );
+	
+	return ( $opts{"H"},
+		$opts{"c"},
+		$opts{"m"},
+		$opts{"d"},
+		$opts {"p"},
+		$opts{"v"},
+		$opts{"u"},
+		$opts{"A"},
+		$opts{"l"},
+		$opts{"a"},
+		$opts{"x"},
+		$opts{"X"});
 }
 
-#--------------------------------------------------------------------------------------------------
+#-----------------------------------------------------------------------
 # Module % Memory use
-#--------------------------------------------------------------------------------------------------
+#-----------------------------------------------------------------------
+if ($module eq "memuse") {
+	my $memuse = 0;
+	my $command_line_parammeters;
+	
+	if ($version == 3) {
+		if ($auth_method eq 'authNoPriv') {
+			$command_line_parammeters = "-v 3 -u $user -a $privacy_method -A $pass -l $auth_method $host";
+		}
+		elsif  ($auth_method eq "noAuthNoPriv") {
+			$command_line_parammeters = "-v 3 -u $user -l $auth_method $host";
+		}
+		else {
+			$command_line_parammeters = "-v 3 -u $user -a $privacy_method -A $pass -l $auth_method -x $privacy_method -X $privacy_pass $host";
+		}
+	}
+	else {
+		$command_line_parammeters = "-v 1 -c $community $host";
+	}
+	
+	my $memid = `snmpwalk -On $command_line_parammeters  .1.3.6.1.2.1.25.2.3.1.3 | grep Physical | head -1 | gawk '{print \$1}' | gawk -F "." '{print \$13}' | tr -d "\r"`;
+	my $memtot = `snmpget $command_line_parammeters  .1.3.6.1.2.1.25.2.3.1.5.$memid ` ;
+	my $memtot2 = `echo "$memtot" | gawk '{print \$4}'`;
+	my $memfree = `snmpget $command_line_parammeters  .1.3.6.1.2.1.25.2.3.1.6.$memid` ;
+	my $memfree2 = `echo "$memfree" | gawk '{print \$4}'`;
+	
+	$memuse = ($memfree2) * 100 / $memtot2;
+	
+	printf("%.2f", $memuse);
+}
 
-if ($module eq "memuse"){ 
-						my $memid = `snmpwalk -On -v 1 -c $community $host .1.3.6.1.2.1.25.2.3.1.3 | grep Physical | head -1 | gawk '{print \$1}' | gawk -F "." '{print \$13}' | tr -d "\r"`;
-						my $memtot = `snmpget -v 1 -c $community $host .1.3.6.1.2.1.25.2.3.1.5.$memid ` ;
-						my $memtot2 = `echo "$memtot" | gawk '{print \$4}'`;
-						my $memfree = `snmpget -v 1 -c $community $host .1.3.6.1.2.1.25.2.3.1.6.$memid` ;
-						my $memfree2 = `echo "$memfree" | gawk '{print \$4}'`;
-						my $memuse = ($memfree2)*100/$memtot2;
-						printf("%.2f", $memuse);
-					    }
-#--------------------------------------------------------------------------------------------------
+#-----------------------------------------------------------------------
 # Module % Disk use
-#-------------------------------------------------------------------------------------------------- 					  
-if ($module eq "diskuse"){
-						my $diskid = `snmpwalk -On -v 1 -c $community $host .1.3.6.1.2.1.25.2.3.1.3 | grep "$disk" | head -1 | gawk '{print \$1}' | gawk -F "." '{print \$13}' | tr -d "\r"`;
-						my $disktot = `snmpget -v 1 -c $community $host .1.3.6.1.2.1.25.2.3.1.5.$diskid ` ;
-						my $disktot2 = `echo "$disktot" | gawk '{print \$4}'`;
-						
-						if($disktot2 == 0) {
-							print 0;
-						}
-						else {
-							my $diskfree = `snmpget -v 1 -c $community $host .1.3.6.1.2.1.25.2.3.1.6.$diskid` ;
-							my $diskfree2 = `echo "$diskfree" | gawk '{print \$4}'`;
-							my $diskuse = ($disktot2 - $diskfree2)*100/$disktot2;
-							printf("%.2f", $diskuse);
-						}
-					    }
-					    
-#--------------------------------------------------------------------------------------------------
+#-----------------------------------------------------------------------
+if ($module eq "diskuse") {
+	my $diskuse = 0;
+	my $command_line_parammeters;
+	
+	if ($version == 3) {
+		if ($auth_method eq 'authNoPriv') {
+			$command_line_parammeters = "-v 3 -u $user -a $privacy_method -A $pass -l $auth_method $host";
+		}
+		elsif  ($auth_method eq "noAuthNoPriv") {
+			$command_line_parammeters = "-v 3 -u $user -l $auth_method $host";
+		}
+		else {
+			$command_line_parammeters = "-v 3 -u $user -a $privacy_method -A $pass -l $auth_method -x $privacy_method -X $privacy_pass $host";
+		}
+	}
+	else {
+		$command_line_parammeters = "-v 1 -c $community $host";
+	}
+	
+	my $diskid = `snmpwalk -On $command_line_parammeters .1.3.6.1.2.1.25.2.3.1.3 | grep "$disk" | head -1 | gawk '{print \$1}' | gawk -F "." '{print \$13}' | tr -d "\r"`;
+	my $disktot = `snmpget $command_line_parammeters .1.3.6.1.2.1.25.2.3.1.5.$diskid ` ;
+	my $disktot2 = `echo "$disktot" | gawk '{print \$4}'`;
+	
+	if ($disktot2 == 0) {
+		$diskuse = 0;
+	}
+	else {
+		my $diskfree = `snmpget $command_line_parammeters .1.3.6.1.2.1.25.2.3.1.6.$diskid` ;
+		my $diskfree2 = `echo "$diskfree" | gawk '{print \$4}'`;
+		
+		$diskuse = ($disktot2 - $diskfree2) * 100 / $disktot2;
+	}
+	
+	printf("%.2f", $diskuse);
+}
+
+#-----------------------------------------------------------------------
 # Module Process Status
-#--------------------------------------------------------------------------------------------------	
-				    
-if ($module eq "process"){
-						my $status = `snmpwalk -v 2c -c $community $host  1.3.6.1.2.1.25.4.2.1.2 | grep "$process" | head -1 | wc -l`;
-						print $status;
-					    }
-#--------------------------------------------------------------------------------------------------
+#-----------------------------------------------------------------------
+if ($module eq "process") {
+	my $status = 0;
+	my $command_line_parammeters;
+	
+	if ($version == 3) {
+		if ($auth_method eq 'authNoPriv') {
+			$command_line_parammeters = "-v 3 -u $user -a $privacy_method -A $pass -l $auth_method $host";
+		}
+		elsif  ($auth_method eq "noAuthNoPriv") {
+			$command_line_parammeters = "-v 3 -u $user -l $auth_method $host";
+		}
+		else {
+			$command_line_parammeters = "-v 3 -u $user -a $privacy_method -A $pass -l $auth_method -x $privacy_method -X $privacy_pass $host";
+		}
+	}
+	else {
+		$command_line_parammeters = "-v 2c -c $community $host";
+	}
+	
+	$status = `snmpwalk $command_line_parammeters  1.3.6.1.2.1.25.4.2.1.2 | grep "$process" | head -1 | wc -l`;
+	
+	print $status;
+}
+
+#-----------------------------------------------------------------------
 # Module % Cpu Load
-#--------------------------------------------------------------------------------------------------
+#-----------------------------------------------------------------------
+if ($module eq "cpuload") {
+	my $cputotal = 0;
+	my $command_line_parammeters;
+	
+	if ($version == 3) {
+		if ($auth_method eq 'authNoPriv') {
+			$command_line_parammeters = "-v 3 -u $user -a $privacy_method -A $pass -l $auth_method $host";
+		}
+		elsif  ($auth_method eq "noAuthNoPriv") {
+			$command_line_parammeters = "-v 3 -u $user -l $auth_method $host";
+		}
+		else {
+			$command_line_parammeters = "-v 3 -u $user -a $privacy_method -A $pass -l $auth_method -x $privacy_method -X $privacy_pass $host";
+		}
+	}
+	else {
+		$command_line_parammeters = "-v 1 -c $community $host";
+	}
+	
+	my $cpuload = `snmpwalk $command_line_parammeters .1.3.6.1.2.1.25.3.3.1.2 | gawk '{print \$4}' `;
+	my @cpuload = split(/\n/, $cpuload);
+	my $sum;
+	my $counter = 0;
+	foreach my $val(@cpuload) {
+		$sum = $sum + $val;
+		$counter++;
+	}
+	
+	$cputotal = $sum/$counter;
+	
+	print $cputotal;
+}
 
-if ($module eq "cpuload"){
-						my $cpuload = `snmpwalk -v 1 -c $community $host .1.3.6.1.2.1.25.3.3.1.2 | gawk '{print \$4}' `;
-						my @cpuload = split(/\n/, $cpuload);
-						my $sum;
-						my $counter = 0;
-						foreach my $val(@cpuload){
-												$sum = $sum+$val;
-												$counter ++;
-					                             }
-						my $cputotal = $sum/$counter;
-						print $cputotal;
-							
-					    }
-
Index: util/pandora_db.pl
===================================================================
--- util/pandora_db.pl	(revision 10314)
+++ util/pandora_db.pl	(working copy)
@@ -547,7 +547,9 @@
  	foreach my $param ('dbuser', 'dbpass', 'dbname', 'dbhost', 'log_file') {
 		die ("[ERROR] Bad config values. Make sure " . $conf->{'_pandora_path'} . " is a valid config file.\n\n") unless defined ($conf->{$param});
  	}
+	$conf->{'dbengine'} = 'mysql' unless defined ($conf->{'dbengine'});
 	$conf->{'dbport'} = '3306' unless defined ($conf->{'dbport'});
+	$conf->{'claim_back_snmp_modules'} = '1' unless defined ($conf->{'claim_back_snmp_modules'});
 
 	# Read additional tokens from the DB
 	my $dbh = db_connect ('mysql', $conf->{'dbname'}, $conf->{'dbhost'}, $conf->{'dbport'}, $conf->{'dbuser'}, $conf->{'dbpass'});
Index: util/pandora_revent_create.pl
===================================================================
--- util/pandora_revent_create.pl	(revision 10314)
+++ util/pandora_revent_create.pl	(working copy)
@@ -232,9 +232,9 @@
 			$i++;
 		}
 
-		$data_event = $event_name.",".$id_group.",".$id_agent.",".$status.",".$id_user.",".$event_type.",".$criticity.",".$id_agent_module.",".$id_alert_am.",".$critical_instructions.",".$warning_instructions.",".$unknown_instructions.",".$user_comment.",".$owner_user.",".$source.",".$tags;
+		$data_event = $event_name."|".$id_group."|".$id_agent."|".$status."|".$id_user."|".$event_type."|".$criticity."|".$id_agent_module."|".$id_alert_am."|".$critical_instructions."|".$warning_instructions."|".$unknown_instructions."|".$user_comment."|".$owner_user."|".$source."|".$tags;
 
-		$call_api = $api_path.'?op=set&op2=create_event&id='.$event_name.'&other='.$data_event.'&other_mode=url_encode_separator_,&apipass='.$api_pass.'&user='.$db_user.'&pass='.$db_pass;
+		$call_api = $api_path.'?op=set&op2=create_event&id='.$event_name.'&other='.$data_event.'&other_mode=url_encode_separator_|&apipass='.$api_pass.'&user='.$db_user.'&pass='.$db_pass;
 
 		#DEBUG TRACE#
 
Index: util/pandora_manage.pl
===================================================================
--- util/pandora_manage.pl	(revision 10314)
+++ util/pandora_manage.pl	(working copy)
@@ -29,6 +29,10 @@
 use PandoraFMS::Core;
 use PandoraFMS::Config;
 
+# To handle 'UTF-8' encoded string in command like arguments (similar to "-CA" option for perl)
+use Encode::Locale;
+Encode::Locale::decode_argv;
+
 # version: define current version
 my $version = "5.1 PS140630";
 
@@ -128,6 +132,8 @@
 	help_screen_line('--create_special_day', "<special_day> <same_day> <description> <group>", 'Create special day');
 	help_screen_line('--delete_special_day', '<special_day>', 'Delete special day');
 	help_screen_line('--update_special_day', "<special_day> <field_to_change> <new_value>", 'Update a field of a special day');
+	help_screen_line('--create_data_module_from_local_component', '<agent_name> <component_name>', "Create a new data \n\t  module from a local component");
+	help_screen_line('--create_local_component', "<component_name> <data> [<description> <id_os> <os_version> \n\t  <id_network_component_group> <type> <min> <max> <module_interval> <id_module_group> <history_data> <min_warning> \n\t <max_warning> <str_warning> <min_critical> <max_critical>\n\t  <str_critical> <min_ff_event> <post_process> <unit>\n\t  <wizard_level> <critical_instructions>\n\t  <warning_instructions> <unknown_instructions> <critical_inverse>\n\t  <warning_inverse> <id_category> <disabled_types_event>\n\t  <tags> <min_ff_event_normal> <min_ff_event_warning>\n\t  <min_ff_event_critical> <each_ff> <ff_timeout>]", 'Create local component');
 
 	print "\nUSERS:\n\n" unless $param ne '';
     help_screen_line('--create_user', '<user_name> <user_password> <is_admin> [<comments>]', 'Create user');
@@ -3885,6 +3891,14 @@
 			param_check($ltotal, 1);
 			cli_delete_special_day();
 		}
+		elsif ($param eq '--create_data_module_from_local_component') {
+			param_check($ltotal, 2);
+			cli_create_data_module_from_local_component();
+		}
+		elsif ($param eq '--create_local_component') {
+			param_check($ltotal, 35, 33);
+			cli_create_local_component();
+		}
 		else {
 			print_log "[ERROR] Invalid option '$param'.\n\n";
 			$param = '';
@@ -3980,3 +3994,110 @@
 		pandora_delete_graph_source($id_graph, $dbh, $module);
 	}
 }
+
+##############################################################################
+# Return local component id given the name
+##############################################################################
+
+sub pandora_get_local_component_id($$) {
+	my ($dbh,$name) = @_;
+	
+	my $lc_id = get_db_value($dbh, 'SELECT id FROM tlocal_component WHERE name = ?',safe_input($name));
+	
+	return defined ($lc_id) ? $lc_id : -1;
+}
+
+##############################################################################
+# Create data module from local component.
+# Related option: --create_data_module_from_local_component
+##############################################################################
+
+sub cli_create_data_module_from_local_component() {
+	my ($agent_name, $component_name) = @ARGV[2..3];
+	
+	my $agent_id = get_agent_id($dbh,$agent_name);
+	exist_check($agent_id,'agent',$agent_name);
+		
+	my $lc_id = pandora_get_local_component_id($dbh, $component_name);
+	exist_check($lc_id,'local component',$component_name);
+	
+	my $module_exists = get_agent_module_id($dbh, $component_name, $agent_id);
+	non_exist_check($module_exists, 'module name', $component_name);
+	
+	# Get local component data
+	my $component = get_db_single_row ($dbh, 'SELECT * FROM tlocal_component WHERE id = ?', $lc_id);
+	
+	#~ pandora_create_module_from_local_component ($conf, $component, $agent_id, $dbh);
+	enterprise_hook('pandora_create_module_from_local_component',[$conf, $component, $agent_id, $dbh]);
+}
+
+##############################################################################
+# Create local component.
+# Related option: --create_local_component
+##############################################################################
+
+sub cli_create_local_component() {
+
+	my ($component_name, $data, $description, $id_os, $os_version, $id_network_component_group, $type,
+		$min,$max,$module_interval, $id_module_group, $history_data, $min_warning, $max_warning, $str_warning,
+		$min_critical, $max_critical, $str_critical, $min_ff_event, $post_process, $unit, $wizard_level,
+	    $critical_instructions, $warning_instructions, $unknown_instructions, $critical_inverse, $warning_inverse,
+	    $id_category, $tags, $disabled_types_event, $min_ff_event_normal, $min_ff_event_warning, $min_ff_event_critical,
+	    $each_ff, $ff_timeout) = @ARGV[2..37];
+	
+	my %parameters;
+	
+	$parameters{'name'} = safe_input($component_name);
+	my $data_aux = safe_input($data);
+	$data_aux =~ s/&#92;n/&#x0a;/g;
+	$parameters{'data'} = $data_aux;
+	$parameters{'description'} = safe_input($description) unless !defined ($description);
+	$parameters{'id_os'} = $id_os unless !defined ($id_os);
+	$parameters{'type'} = $type unless !defined ($type);
+	if (defined $id_network_component_group) {
+		$parameters{'id_network_component_group'} = $id_network_component_group;
+	} else {
+		$parameters{'id_network_component_group'} = 1;
+	}
+	$parameters{'max'} = $max unless !defined ($max);
+	$parameters{'min'} = $min unless !defined ($min);
+	$parameters{'module_interval'} = $module_interval unless !defined ($module_interval);
+	$parameters{'id_module_group'} = $id_module_group unless !defined ($id_module_group);
+	$parameters{'history_data'} = safe_input($history_data) unless !defined ($history_data);
+	$parameters{'min_warning'} = $min_warning unless !defined ($min_warning);
+	$parameters{'max_warning'} = $max_warning unless !defined ($max_warning);
+	$parameters{'str_warning'} = $str_warning unless !defined ($str_warning);
+	$parameters{'min_critical'} = $min_critical unless !defined ($min_critical);
+	$parameters{'max_critical'} = $max_critical unless !defined ($max_critical);
+	$parameters{'str_critical'} = $str_critical unless !defined ($str_critical);
+	$parameters{'min_ff_event'} = $min_ff_event unless !defined ($min_ff_event);
+	$parameters{'post_process'} = $post_process unless !defined ($post_process);
+	$parameters{'unit'} = $unit  unless !defined ($unit);
+	$parameters{'wizard_level'} = $wizard_level unless !defined ($wizard_level);
+	$parameters{'critical_instructions'} = safe_input($critical_instructions) unless !defined ($critical_instructions);
+	$parameters{'warning_instructions'} = safe_input($warning_instructions) unless !defined ($warning_instructions);
+	$parameters{'unknown_instructions'} = safe_input($unknown_instructions) unless !defined ($unknown_instructions);
+	$parameters{'critical_inverse'} = $critical_inverse unless !defined ($critical_inverse);
+	$parameters{'warning_inverse'} = $warning_inverse unless !defined ($warning_inverse);
+	$parameters{'id_category'} = $id_category unless !defined ($id_category);
+	$parameters{'tags'} = safe_input($tags) unless !defined ($tags);
+
+	my $disabled_types_event_hash = {};
+	if ($disabled_types_event) {
+		$disabled_types_event_hash->{'going_unknown'} = 0;
+	}
+	else {
+		$disabled_types_event_hash->{'going_unknown'} = 1;
+	}
+	my $disabled_types_event_json = encode_json($disabled_types_event_hash);
+	$parameters{'disabled_types_event'} = $disabled_types_event_json unless !defined ($disabled_types_event);
+	
+	$parameters{'min_ff_event_normal'} = $min_ff_event_normal unless !defined ($min_ff_event_normal);
+	$parameters{'min_ff_event_warning'} = $min_ff_event_warning unless !defined ($min_ff_event_warning);
+	$parameters{'min_ff_event_critical'} = $min_ff_event_critical unless !defined ($min_ff_event_critical);
+	$parameters{'each_ff'} = $each_ff unless !defined ($each_ff);
+	$parameters{'ff_timeout'} = $ff_timeout unless !defined ($ff_timeout);
+	
+	my $component_id = enterprise_hook('pandora_create_local_component_from_hash',[$conf, \%parameters, $dbh]);
+
+}
Index: util/recon_scripts/wmi-recon.pl
===================================================================
--- util/recon_scripts/wmi-recon.pl	(revision 10314)
+++ util/recon_scripts/wmi-recon.pl	(working copy)
@@ -27,8 +27,9 @@
 			'daemon' => 0,
 			'PID' => '',
 			'pandora_path' => '/usr/local/etc/pandora/pandora_server.conf',
-			'ping_timeout' => 2,
-			'ping_retries' => 1,
+			'networktimeout' => 2,
+			'icmp_checks' => 1,
+			'nmap_timing_template' => 2,
 			'wmi_client' => '/usr/local/bin/wmic');
 } else {
 	%CONF = ('quiet' => 0,
@@ -36,8 +37,9 @@
 			'daemon' => 0,
 			'PID' => '',
 			'pandora_path' => '/etc/pandora/pandora_server.conf',
-			'ping_timeout' => 2,
-			'ping_retries' => 1,
+			'networktimeout' => 2,
+			'icmp_checks' => 1,
+			'nmap_timing_template' => 2,
 			'wmi_client' => '/usr/bin/wmic');
 }
 
@@ -106,10 +108,10 @@
 	my ($task, $function) = @_;
 
 	# Timeout in ms.
-	my $timeout = $CONF{'ping_timeout'} * 1000;
+	my $timeout = $CONF{'networktimeout'} * 1000;
 
 	# Added -PE to make nmap behave like ping and avoid confusion if ICMP traffic is blocked.
-	my $nmap_args = '-nsP -PE --max-retries ' . $CONF{'ping_retries'} . ' --host-timeout ' . $timeout;
+	my $nmap_args = '-nsP -PE --max-retries ' . $CONF{'icmp_checks'} . ' --host-timeout '.$timeout.' -T'.$CONF{'nmap_timing_template'};
 
 	# Scan the network.
 	my $np = new PandoraFMS::NmapParser;
Index: util/recon_scripts/snmp-recon.pl
===================================================================
--- util/recon_scripts/snmp-recon.pl	(revision 10314)
+++ util/recon_scripts/snmp-recon.pl	(working copy)
@@ -35,8 +35,9 @@
 	%CONF = (
 		'nmap' => '/usr/local/bin/nmap',
 		'pandora_path' => '/usr/local/etc/pandora/pandora_server.conf',
-		'ping_retries' => 1,
-		'ping_timeout' => 2,
+		'icmp_checks' => 1,
+		'networktimeout' => 2,
+		'nmap_timing_template' => 2,
 		'PID' => '',
 		'quiet' => 1,
 	);
@@ -44,8 +45,9 @@
 	%CONF = (
 		'nmap' => '/usr/bin/nmap',
 		'pandora_path' => '/etc/pandora/pandora_server.conf',
-		'ping_retries' => 1,
-		'ping_timeout' => 2,
+		'icmp_checks' => 1,
+		'networktimeout' => 2,
+		'nmap_timing_template' => 2,
 		'PID' => '',
 		'quiet' => 1,
 	);
@@ -861,9 +863,11 @@
 	return unless defined($agent);
 
 	# Perform a traceroute.
+	my $timeout = $CONF{'networktimeout'}*1000;
+	my $nmap_args  = '-nsP -PE --traceroute --max-retries '.$CONF{'icmp_checks'}.' --host-timeout '.$timeout.' -T'.$CONF{'nmap_timing_template'};
 	my $np = new PandoraFMS::NmapParser;
 	eval {
-		$np->parsescan($CONF{'nmap'}, '-nsP --traceroute', ($host));
+		$np->parsescan($CONF{'nmap'}, $nmap_args, ($host));
 	};
 	return if ($@);
 	
@@ -930,10 +934,11 @@
 
 # Populate ARP caches.
 message("Populating ARP caches...");
-my $timeout = $CONF{'ping_timeout'} * 1000; # Convert the timeout from s to ms.
+my $timeout = $CONF{'networktimeout'} * 1000; # Convert the timeout from s to ms.
+my $nmap_args  = '-nsP --send-ip --max-retries '.$CONF{'icmp_checks'}.' --host-timeout '.$timeout.' -T'.$CONF{'nmap_timing_template'};
 my $np = new PandoraFMS::NmapParser;
 if ($#SUBNETS >= 0) {
-	$np->parsescan($CONF{'nmap'}, '-nsP --send-ip --max-retries ' . $CONF{'ping_retries'} . ' --host-timeout ' . $timeout, @SUBNETS);
+	$np->parsescan($CONF{'nmap'}, $nmap_args, @SUBNETS);
 }
 
 # Find routers.
