This file is indexed.

/usr/sbin/pandora_agent is in pandorafms-agent 4.0.1-1.

This file is owned by root:root, with mode 0o755.

The actual contents of the file can be viewed below.

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
#!/usr/bin/perl
# **********************************************************************
# Pandora FMS Generic Unix/Perl Agent
# (c) 2009-2011 Artica Soluciones Tecnológicas
# with the help of many people. Please see http://pandorafms.org
# This code is licensed under GPL 2.0 license.
# **********************************************************************

=head1 NAME

pandora_agent - Pandora FMS Agent

=head1 VERSION

Version 4.0

=head1 USAGE

<< pandora_agent F<pandora home> >>

=cut


use strict;
use warnings;

use POSIX qw(strftime floor);
use Sys::Hostname;
use File::Basename;
use File::Copy;
use IO::Socket;

# Agent XML data
my $Xml;

# Semaphore used to acces $Xml
my $Sem = undef;

# Semaphore used to control the number of threads
my $ThreadSem = undef;

# Load thread support
eval {
	local $SIG{__DIE__};
	require threads;
	require threads::shared;
	require Thread::Semaphore;
};
if (!$@) {
	$Sem = Thread::Semaphore->new;
	threads::shared::share (\$Xml);
	threads::shared::share (\$Sem);
}	

use constant AGENT_VERSION => '4.0.1';
use constant AGENT_BUILD => '111220';

# Commands to retrieve total memory information in kB
use constant TOTALMEMORY_CMDS => {
	linux => 'cat /proc/meminfo | grep MemTotal: | awk \'{ print $2 }\'',
	solaris => '/usr/sbin/prtconf | awk \'/Memory/ { print $3 * 1024 }\'',
	hpux => 'swapinfo -t | grep memory | awk \'{print $2}\'',
	freebsd => '/sbin/sysctl hw.physmem | awk \'{print $2 / 1024}\'',
};

# Commands to retrieve free memory information in kB
use constant FREEMEMORY_CMDS => {
	linux => 'cat /proc/meminfo | grep MemFree: | awk \'{ print $2 }\'',
	solaris => 'vmstat 1 2 | tail -1 | awk \'{ print $5 }\'',
	hpux => 'swapinfo -t | grep memory | awk \'{print $4}\'',
	freebsd => '/sbin/sysctl -n vm.stats.vm.v_page_size vm.stats.vm.v_free_count | tr "\n" " " | awk \'{ print $1 * $2 / 1024 }\'',
};

# Commands to retrieve cpu information
use constant CPUUSAGE_CMDS => {
	linux => 'vmstat 1 2 | tail -1 | awk \'{ print $13 }\'',
	solaris => 'vmstat 1 2 | tail -1 | awk \'{ print $21 }\'',
	hpux => 'vmstat 1 2 | tail -1 | awk \'{ print $16 }\'',
	freebsd => 'vmstat -n 0 1 2 | tail -1 | awk \'{ print $15 }\''
};

# Commands to retrieve process information
use constant PROC_CMDS => {
	# cpu usage, memory usage, command name
	linux => 'ps aux | awk \'NR > 1 {ps = ""; for (i = 11; i <= NF; ++i) {ps = (ps " " $i) }; print $3, $6, ps}\'',
	solaris => 'prstat 1 1 | awk \'NR > 1 {split ($10, ps, "/"); cpu = substr ($9, 1, length ($9) - 1); mem = substr ($3, 1, length ($3) - 1); print cpu, mem, ps[1]}\'',
	hpux => 'ps -elf | awk \'NR > 1 {ps = ""; for (i = 15; i <= NF; ++i) {ps = (ps " " $i) }; print 0, $10, ps}\'',
	aix => 'ps aux | awk \'NR > 1 {print $3, $6, $11}\'',
	freebsd => 'ps axww -o %cpu= -o %mem= -o command= | sed -e "s/^ *//"',
};

# Commands to retrieve partition information in kB
use constant PART_CMDS => {
	# total, available, mount point
	linux => 'df -P | awk \'NR > 1 {print $2, $4, $6}\'',
	solaris => 'df -k | awk \'NR > 1 {print $2, $4, $6}\'',
	hpux => 'df -P | awk \'NR > 1 {print $2, $4, $6}\'',
	aix => 'df -kP | awk \'NR > 1 {print $2, $4, $6}\'',
	freebsd => 'df -k | awk \'NR > 1 {print $2, $4, $6}\''
};
	
# OS and OS version
my $OS = $^O;

my $OS_VERSION;

# Used to calculate the MD5 checksum of a string
use constant MOD232 => 2**32;

# Directory where pandora_agent.conf is located
my $ConfDir = '';

# Pandora FMS agent configuration file
my $ConfFile = 'pandora_agent.conf';

# Broker agent configuration files
my @BrokerPid;

# Configuration tokens
my %Conf = (
	'server_ip' => 'localhost',
	'server_path' => '/var/spool/pandora/data_in',
	'logfile' =>'/var/log/pandora/pandora_agent.log',
	'temporal' => '/var/spool/pandora',
	'interval' => 300,
	'debug' => 0,		
	'agent_name' => hostname (),
	'description' => '',
	'group' => '',
	'encoding' => 'ISO-8859-1',
	'server_port' => 41121,
	'transfer_mode' => 'tentacle',
	'server_pwd' => '',
	'server_ssl' => 'no',
	'server_opts' => '',
	'delayed_startup' => 0,
	'pandora_nice' => 10,
	'cron_mode' => 0,
	'remote_config' => 0,
	'secondary_mode' => 'never',
	'secondary_server_ip' => 'localhost',
	'secondary_server_path' => '/var/spool/pandora/data_in',
	'secondary_server_port' => 41121,
	'secondary_transfer_mode' => 'tentacle',
	'secondary_server_pwd' => 'mypassword',
	'secondary_server_ssl' => 'no',
	'secondary_server_opts' => '',
	'autotime' => 0,
	'timezone_offset' => 0,
	'pandora_exec' => '/usr/share/pandorafms/agent/pandora_agent_exec',
	'agent_threads' => 1,
	'udp_server_port' => 41122,
	'udp_server_auth_address' => '0.0.0.0',
	'udp_server' => 0,
	'proxy_mode' => 0,
	'proxy_max_connection' => 10,
	'proxy_timeout' => 1,
);

# Modules
my @Modules;

# Plugins
my @Plugins;

# Logfile file handle
my $LogFileFH;

# Agent name MD5;
my $AgentMD5;

# Remote configuration file name
my $RemoteConfFile;

# Remote md5 file name
my $RemoteMD5File;

# Process data
my %Procs = (
	'__utimestamp__' => 0
);

# Partition data
my %Parts = (
	'__utimestamp__' => 0
);

# Collections
my %Collections;

# $DevNull
my $DevNull = '/dev/null';

# Shell command separator
my $CmdSep = ';';

# PID of tentacle proxy, used in proxy mode
my $tentacle_pid = undef;

################################################################################
# Print usage information and exit.
################################################################################
sub print_usage () {
	print "\nUsage: $0 <Pandora home>\n\n";
	print "\tPandora home is the directory where pandora_agent.conf is located,\n";
	print "\tby default /etc/pandora.\n\n";
	exit 1;
}

################################################################################
# Print an error message and exit.
################################################################################
sub error ($) {
	my $msg = shift;
	print ("[ERROR] $msg\n\n");
	exit 1;
}

################################################################################
# Recursively delete files and directories.
################################################################################
sub rmrf {
	my $path = shift;
	local *DIR;

	if (-d $path) {
		opendir (DIR, $path) || return;
		while (defined (my $file_name = readdir(DIR))) {
			next if ($file_name eq '.' || $file_name eq '..');
			rmrf ("$path/$file_name");
		}
		closedir (DIR);
		rmdir ($path);
	} else {
		unlink ($path);
	}
}

################################################################################
# Recursively set file permissions.
################################################################################
sub chmodr {
	my ($perm, $path) = @_;
	local *DIR;

	if (-d $path) {
		opendir (DIR, $path) || return;
		while (defined (my $file_name = readdir(DIR))) {
			next if ($file_name eq '.' || $file_name eq '..');
			chmodr ($perm, "$path/$file_name");
		}
		closedir (DIR);
	}
	chmod ($perm, $path);
}

################################################################################
# Open the agent logfile and start logging.
################################################################################
sub start_log (;$) {
	my $quiet = shift;

	# Get the logfile
	my $log_file_name = read_config ('logfile');
	$log_file_name = '/var/log/pandora/pandora_agent.log' unless defined ($log_file_name);

	# Open it
	open ($LogFileFH, "> $log_file_name") or error ("Could not open log file '$log_file_name' for writing: $!.");
	if (! defined ($quiet)) {
		print "Logging to $log_file_name\n";
	}
}

################################################################################
# Close the agent logfile and stop logging.
################################################################################
sub stop_log () {
	close ($LogFileFH);
}

################################################################################
# Log a message to the agent logfile.
################################################################################
sub log_message ($$;$) {
	my ($source, $msg, $dest) = @_;
	
	if (defined ($dest)) {
		print $dest strftime ('%Y/%m/%d %H:%M:%S', localtime ()) . " - [$source] - $msg\n";
	} else {
		print $LogFileFH strftime ('%Y/%m/%d %H:%M:%S', localtime ()) . " - [$source] - $msg\n";
	}
}

################################################################################
# Parse configuration file (modules, plugins and collections)
################################################################################
sub parse_conf_modules($) {
	my ($param) = @_;
	my $module;
	
	foreach my $line (@{$param}) {
		
		next if ($line =~ m/^\s*#/) or ($line =~ m/^\s*$/);
		# Module definition
		if ($line =~ /^\s*module_begin\s*$/) {
			$module = {
				'name' => '',
				'type' => 'generic_data',
				'description' => '',
				'func' => 0,
				'params' => '',
				'description' => '',
				'interval' => 1,
				'timeout' => 0,
				'counter' => 0,
				'max' => undef,
				'min' => undef,
				'post_process' => undef,
			    'min_critical' => undef,
			    'max_critical' => undef,
			    'min_warning' => undef,
			    'max_warning' => undef,
			    'disabled' => undef,
			    'min_ff_event' => undef,
				'save' => '',
				'conditions' => [],
				'cron' => '',
				'cron_utimestamp' => 0,
				'cron_interval' => -1,
				'precondition' => [],
				'precon'=> 0
			};
		} elsif ($line =~ /^\s*module_name\s+(.+)$/) {
			$module->{'name'} = $1;
		} elsif ($line =~ /^\s*module_description\s+(.+)$/) {
			$module->{'description'} = $1;
		} elsif ($line =~ /^\s*module_type\s+(\S+)\s*$/) {
			$module->{'type'} = $1;
		}elsif ($line =~ /^\s*module_precondition\s+(.*)$/) {
			my $action = $1;
			$module->{'precon'} = 1;
			# Numeric comparison
			if ($action =~ /^\s*([<>!=]+)\s+(\d+(?:\.\d*)?)\s+(.*)$/) {
				push (@{$module->{'precondition'}}, {'operator' => $1, 'value_1' => $2, 'command' => $3});
			# Interval
			} elsif ($action =~ /^\s*[(]\s*(\d+(?:\.\d*)?)\s*,\s*(\d+(?:\.\d*)?)\s*[)]\s+(.*)$/) {
				push (@{$module->{'precondition'}}, {'operator' => '()', 'value_1' => $1, 'value_2' => $2, 'command' => $3});
			# Regular expression
			} elsif ($action =~ /^\s*=~\s+(\S*)\s+(.*)$/) {
				push (@{$module->{'precondition'}}, {'operator' => '=~', 'value_1' => $1, 'command' => $2});
			}
		} elsif ($line =~ /^\s*module_exec\s+(.+)$/) {
			$module->{'func'} = \&module_exec;
			$module->{'params'} = $1;
		} elsif ($line =~ /^\s*module_cpuusage\s+(.*)$/) {
			$module->{'func'} = \&module_cpuusage;
			$module->{'params'} = $1;
		} elsif ($line =~ /^\s*module_freememory\s+(.*)$/) {
			$module->{'func'} = \&module_freememory;
			$module->{'params'} = $1;
		} elsif ($line =~ /^\s*module_freepercentmemory\s+(.*)$/) {
			$module->{'func'} = \&module_freepercentmemory;
			$module->{'params'} = $1;
		} elsif ($line =~ /^\s*(module_proc|module_service)\s+(.+)$/) {
			$module->{'func'} = \&module_proc;
			$module->{'params'} = $2;
		} elsif ($line =~ /^\s*module_cpuproc\s+(.+)$/) {
			$module->{'func'} = \&module_cpuproc;
			$module->{'params'} = $1;
		} elsif ($line =~ /^\s*module_memproc\s+(.+)$/) {
			$module->{'func'} = \&module_memproc;
			$module->{'params'} = $1;
		} elsif ($line =~ /^\s*module_freedisk\s+(.*)$/) {
			$module->{'func'} = \&module_freedisk;
			$module->{'params'} = $1;
		} elsif ($line =~ /^\s*module_freepercentdisk\s+(.*)$/) {
			$module->{'func'} = \&module_freepercentdisk;
			$module->{'params'} = $1;
		} elsif ($line =~ /^\s*module_occupiedpercentdisk\s+(.*)$/) {
			$module->{'func'} = \&module_occupiedpercentdisk;
			$module->{'params'} = $1;
		} elsif ($line =~ /^\s*module_max\s+(.*)\s*$/) {
			$module->{'max'} = $1;
		} elsif ($line =~ /^\s*module_min\s+(.*)\s*$/) {
			$module->{'min'} = $1;
		} elsif ($line =~ /^\s*module_postprocess\s+(.*)\s*$/) {
			$module->{'post_process'} = $1;
		} elsif ($line =~ /^\s*module_interval\s+(\d+)\s*$/) {
			$module->{'interval'} = $1;

			# Make the module run the first time
			$module->{'counter'} = $1;
		} elsif ($line =~ /^\s*module_timeout\s+(\d+)\s*$/) {
			$module->{'timeout'} = $1;
		} elsif ($line =~ /^\s*module_save\s+(\w+)$/) {
			$module->{'save'} = $1;
		} elsif ($line =~ /^\s*module_condition\s+(.*)$/) {
			my $action = $1;
			# Numeric comparison
			if ($action =~ /^\s*([<>!=]+)\s+(\d+(?:\.\d*)?)\s+(.*)$/) {
				push (@{$module->{'conditions'}}, {'operator' => $1, 'value_1' => $2, 'command' => $3});
			# Interval
			} elsif ($action =~ /^\s*[(]\s*(\d+(?:\.\d*)?)\s*,\s*(\d+(?:\.\d*)?)\s*[)]\s+(.*)$/) {
				push (@{$module->{'conditions'}}, {'operator' => '()', 'value_1' => $1, 'value_2' => $2, 'command' => $3});
			# Regular expression
			} elsif ($action =~ /^\s*=~\s+(\S*)\s+(.*)$/) {
				push (@{$module->{'conditions'}}, {'operator' => '=~', 'value_1' => $1, 'command' => $2});
			}
		} elsif ($line =~ /^\s*module_crontab\s+(((\*|(\d+(-\d+){0,1}))\s*){5}).*$/) {
			$module->{'cron'} = $1;
		} elsif ($line =~ /^\s*module_cron_interval\s+(\d+).*$/) {
			$module->{'cron_interval'} = $1;
		} elsif ($line =~ /^\s*module_end\s*$/) {
			next unless ($module->{'name'} ne '') and ($module->{'func'} != 0);
			push (@Modules, $module);
		# Plugin
		} elsif ($line =~ /^\s*module_plugin\s+(.+)$/) {
			push (@Plugins, $1);
		# Module proc command redefinition		
		} elsif ($line =~ /^\s*module_proc_cmd\s+(.+)$/) {
			PROC_CMDS->{$OS} = $1;
		# Module freedisk command redefinition		
		} elsif ($line =~ /^\s*module_freedisk_cmd\s+(.+)$/) {
			PART_CMDS->{$OS} = $1;
		# Collection
		} elsif ($line =~ /^\s*file_collection\s+(.+)$/) {
			my $collection = $1;
			
			# Prevent path traversal attacks
			if ($collection !~ m/(\.\.)|\//) {
				$Collections{$collection} = 0;
			}
		# Min critical
		} elsif ($line =~ /^\s*module_min_critical\s+(.*)\s*$/) {
			$module->{'min_critical'} = $1;
		# Max critical
		} elsif ($line =~ /^\s*module_max_critical\s+(.*)\s*$/) {
			$module->{'max_critical'} = $1;
		# Min warning
		} elsif ($line =~ /^\s*module_min_warning\s+(.*)\s*$/) {
			$module->{'min_warning'} = $1;
		# Max warning
		} elsif ($line =~ /^\s*module_max_warning\s+(.*)\s*$/) {
			$module->{'max_warning'} = $1;
		# Disabled
		} elsif ($line =~ /^\s*module_disabled\s+(.*)\s*$/) {
			$module->{'disabled'} = $1;
		# Min ff event
		} elsif ($line =~ /^\s*module_min_ff_event\s+(.*)\s*$/) {
			$module->{'min_ff_event'} = $1;
		}
	}
	return;
}

################################################################################
# Create configuration file for broker agents.
################################################################################
sub write_broker_conf($){
	my ($broker_agent) = @_;
	my $content = '';

	open (CONF_FILE, "$ConfDir/$ConfFile") or error ("Could not open file '$ConfDir/$ConfFile': $!.");
	open (BROKER_FILE, ">$ConfDir/${broker_agent}.conf") or error ("Could not write configuration file: $!");

	while (my $line = <CONF_FILE>){

		# Skip broker definitions
		if ($line =~ m/^\s*broker_agent/) {
			next;
		}
		
		# Change the agent name
		if ($line =~ m/^\s*#*\s*agent_name\s+/) {
			$line = "agent_name $broker_agent\n";
		}
		# Change the logfile
		elsif ($line =~ m/^\s*logfile\s+(.*)/) {
			$line = 'logfile ' . dirname ($1) . "/$broker_agent.log\n";
		}

		print BROKER_FILE $line;
	}
	close (BROKER_FILE);
	close (CONF_FILE);
}

################################################################################
# Read configuration file. Exit on error.
################################################################################
sub read_config (;$) {
	my $token = shift;
	my @found_tokens;
	my $module;

	error ("File '$ConfDir/$ConfFile' not found.") unless (-e "$ConfDir/$ConfFile");
	open (CONF_FILE, "$ConfDir/$ConfFile") or error ("Could not open file '$ConfDir/$ConfFile': $!.");
	
	my @file = <CONF_FILE>;
	close(CONF_FILE);
	
	foreach my $line (@file){
		# Skip comments and empty lines
		next if ($line =~ m/^\s*#/) or ($line =~ m/^\s*$/);
		
		# Token search
		if (defined ($token)) {
			if ($line =~ /^\s*(\S+)\s+(.*)$/ && $1 eq $token) {
				
				# Multiple value token
				if (wantarray ()) {
					push (@found_tokens, $2);
				}
				# Single value token
				else {
					return $2;
				}
			}
			next;
		}
		next if ($line =~ /^module\s*\w*/);
		
		# Additional configuration file
		if ($line =~ /^include\s+(.*)\s*/){
			open (FILE, "$1") or next;
			my @file_conf = <FILE>;
			parse_conf_modules(\@file_conf);	
			close (FILE);
		}

		#Configuration token
		if ($line =~ /^\s*(\S+)\s+(.*)$/) {		
			log_message ('setup', "$1 is $2");
			$Conf{$1} = $2;
			
			# Remove trailing spaces
			$Conf{$1} =~ s/\s*$//;
		}
	}

	# Token search
	if (defined ($token)) {
		
		# Multiple value token
		if (wantarray ()) {
			return @found_tokens;
		}
		
		# Single value token not found.
		return undef;
	}

	# Module, plugin and collection definitions
	parse_conf_modules(\@file);

	# Update the agent MD5 since agent_name may have changed
	$AgentMD5 = md5 ($Conf{'agent_name'});
	$RemoteConfFile = "$AgentMD5.conf";
	$RemoteMD5File = "$AgentMD5.md5";
	
	# Set the maximun number of threads
	$ThreadSem = Thread::Semaphore->new ($Conf{'agent_threads'}) if defined ($Sem);

	# Set tentacle client options
	if ($Conf{'transfer_mode'} eq 'tentacle') {
		$Conf{'server_opts'} = '-x \'' . $Conf{'server_pwd'} . '\' ' . $Conf{'server_opts'} if ($Conf{'server_pwd'} ne '');
		$Conf{'server_opts'} = '-c ' . $Conf{'server_opts'} if ($Conf{'server_ssl'} eq 'yes');
	}

	# Set tentacle client options for secondary server	
	if ($Conf{'secondary_transfer_mode'} eq 'tentacle') {
		$Conf{'secondary_server_opts'} = '-x \'' . $Conf{'secondary_server_pwd'} . '\' ' . $Conf{'secondary_server_opts'} if ($Conf{'secondary_server_pwd'} ne '');
		$Conf{'secondary_server_opts'} = '-c ' . $Conf{'secondary_server_opts'} if ($Conf{'secondary_server_ssl'} eq 'yes');		
	}

}

#################################################################################
## Remove any trailing / from directory names.
#################################################################################
sub fix_directory ($) {
	my $dir = shift;
	
	my $char = chop ($dir);
	return $dir if ($char eq '/');
	return $dir . $char;
}



################################################################################
# Sends a file to the server.
################################################################################
#sub send_file ($;$) {
sub send_file {
	my ($file, $secondary) = @_;
	my $output;

	if ($Conf{'transfer_mode'} eq 'tentacle') {
 		$output = `tentacle_client -v -a $Conf{'server_ip'} -p $Conf{'server_port'} $Conf{'server_opts'} $file 2>&1 >$DevNull`;
	} elsif ($Conf{'transfer_mode'} eq 'ssh') {
 		$output = `scp -P $Conf{'server_port'} $file pandora@"$Conf{'server_ip'}:$Conf{'server_path'}" 2>&1 >$DevNull`;
	} elsif ($Conf{'transfer_mode'} eq 'ftp') {
		my $base = basename ($file);
		my $dir = dirname ($file);

		$output = `ftp -n $Conf{'server_ip'} $Conf{'server_port'} 2>&1 >$DevNull <<FEOF1
		quote USER pandora
		quote PASS $Conf{'server_pwd'}
		lcd "$dir"
		cd "$Conf{'server_path'}"
		put "$base"
		quit
		FEOF1`
	} elsif ($Conf{'transfer_mode'} eq 'local') {
		$output = `cp $file $Conf{'server_path'}/ 2>&1 >$DevNull`;
	}

	# Get the errorlevel
	my $rc = $? >> 8;
	if ($rc != 0) {
		log_message ('error', "Error sending file '$file': $output");
	}

	return $rc unless (defined ($secondary));

	# Send the file to the secondary server
	return $rc unless ($Conf{'secondary_mode'} eq 'always' || ($Conf{'secondary_mode'} eq 'on_error' && $rc != 0));
	
	swap_servers ();
	$rc = send_file ($file);
	swap_servers ();
	return $rc;
}

################################################################################
# Swap primary and secondary servers.
################################################################################
sub swap_servers () {
	($Conf{'server_ip'}, $Conf{'secondary_server_ip'}) = ($Conf{'secondary_server_ip'}, $Conf{'server_ip'});
	($Conf{'server_path'}, $Conf{'secondary_server_path'}) = ($Conf{'secondary_server_path'}, $Conf{'server_path'});
	($Conf{'server_port'}, $Conf{'secondary_server_port'}) = ($Conf{'secondary_server_port'}, $Conf{'server_port'});
	($Conf{'server_transfer_mode'}, $Conf{'secondary_server_transfer_mode'}) = ($Conf{'secondary_server_transfer_mode'}, $Conf{'server_transfer_mode'});
	($Conf{'server_pwd'}, $Conf{'secondary_server_pwd'}) = ($Conf{'secondary_server_pwd'}, $Conf{'server_pwd'});
	($Conf{'server_ssl'}, $Conf{'secondary_server_ssl'}) = ($Conf{'secondary_server_ssl'}, $Conf{'server_ssl'});
	($Conf{'server_opts'}, $Conf{'secondary_server_opts'}) = ($Conf{'secondary_server_opts'}, $Conf{'server_opts'});
}

################################################################################
# Receive a file from the server.
################################################################################
sub recv_file ($) {
	my $file = shift;
	my $output;

	if ($Conf{'transfer_mode'} eq 'tentacle') {
 		$output = `cd "$Conf{'temporal'}"$CmdSep tentacle_client -v -g -a $Conf{'server_ip'} -p $Conf{'server_port'} $Conf{'server_opts'} $file 2>&1 >$DevNull`
	} elsif ($Conf{'transfer_mode'} eq 'ssh') {
 		$output = `scp -P $Conf{'server_port'} pandora@"$Conf{'server_ip'}:$Conf{'server_path'}/$file" $Conf{'temporal'} 2>&1 >$DevNull`;
	} elsif ($Conf{'transfer_mode'} eq 'ftp') {
		my $base = basename ($file);
		my $dir = dirname ($file);

		$output = `ftp -n $Conf{'server_ip'} $Conf{'server_port'} 2>&1 >$DevNull <<FEOF1
		quote USER pandora
		quote PASS $Conf{'server_pwd'}
		lcd "$Conf{'temporal'}"
		cd "$Conf{'server_path'}"
		get "$file"
		quit
		FEOF1`
	} elsif ($Conf{'transfer_mode'} eq 'local') {
		$output = `cp $Conf{'server_path'}/$file $Conf{'temporal'} 2>&1 >$DevNull`;
	}

	# Get the errorlevel
	my $rc = $? >> 8;
	if ($rc != 0) {
		log_message ('error', "Error retrieving file: $output");
	}

	return $rc;
}

################################################################################
# Check the server for a remote configuration.
################################################################################
sub check_remote_config () {

	return unless ($Conf{'remote_config'} eq '1');

	# Calculate the configuration file MD5 digest
	open (CONF_FILE, "$ConfDir/$ConfFile") or error ("Could not open file '$ConfDir/$ConfFile': $!.");
	binmode(CONF_FILE);
	my $conf_md5 = md5 (join ('', <CONF_FILE>));
	close (CONF_FILE);

	# Get the remote MD5 file
	if (recv_file ($RemoteMD5File) != 0) {
		open (MD5_FILE, "> $Conf{'temporal'}/$RemoteMD5File") || error ("Could not open file '$ConfDir/$RemoteMD5File' for writing: $!.");
		print MD5_FILE $conf_md5;
		close (MD5_FILE);
		copy ("$ConfDir/$ConfFile", "$Conf{'temporal'}/$RemoteConfFile");
		send_file ("$Conf{'temporal'}/$RemoteConfFile");
		send_file ("$Conf{'temporal'}/$RemoteMD5File");
		log_message ('remote config', 'Uploading configuration for the first time.');
		unlink ("$Conf{'temporal'}/$RemoteConfFile");
		unlink ("$Conf{'temporal'}/$RemoteMD5File");
		return;
	}

	open (MD5_FILE, "< $Conf{'temporal'}/$RemoteMD5File") || error ("Could not open file '$ConfDir/$RemoteMD5File' for writing: $!.");
	my $remote_conf_md5 = <MD5_FILE>;
	close (MD5_FILE);
	
	# No changes
	return if ($remote_conf_md5 eq $conf_md5);
	
	# Get the new configuration file
	return if (recv_file ($RemoteConfFile) != 0);
	log_message ('remote config', 'Configuration has changed!');

	# Empty modules, plugins and collections
	@Modules = ();
	@Plugins = ();
	%Collections = ();

	# Save the new configuration and reload it
	move ("$Conf{'temporal'}/$RemoteConfFile", "$ConfDir/$ConfFile");
	read_config ();
	
	# Log file may have changed
	stop_log ();
	start_log ('quiet');
	
	#Set nice of the pandora_agent
	my $PID = $$;
	`renice "$Conf{'pandora_nice'}" "$PID"`;
}

################################################################################
# SUB launch_tentacle_proxy
# Launchs tentacle server in proxy mode.
################################################################################
sub launch_tentacle_proxy () {
	# Check if proxy server ip is right.
	if ($Conf{'server_ip'} ne "localhost") {	
		
		#Create a new process and launch tentacle.
		$tentacle_pid = fork();	

		if ($tentacle_pid == 0) {

			#Execute tentacle server as a daemon
			my $new_process = "tentacle_server -b ".$Conf{'server_ip'}." -g ".$Conf{'server_port'}." -c ".$Conf{'proxy_max_connection'}." -t ".$Conf{'proxy_timeout'};

			log_message ('setup', 'Proxy mode enabled');
			exec ($new_process);		
		} 
	} else {
		error ('You can not proxy to localhost');
	}
}

################################################################################
# Delete old collections and download new collections.
################################################################################
sub check_collections () {

	# Delete old collections
	opendir (DIR, "$ConfDir/collections") || return;
 	while (defined (my $file_name = readdir(DIR))) {
		next if ($file_name eq '.' || $file_name eq '..');

		# Do not delete md5 files associated to a collection
		$file_name =~ s/\.md5$//;

		if (! defined ($Collections{$file_name})) {
			rmrf ("$ConfDir/collections/$file_name");
			unlink ("$ConfDir/collections/$file_name.md5");
		}
	}
	closedir (DIR);

	# Download new collections
	while (my ($collection, $in_path) = each (%Collections)) {
		my $collection_file = $collection . ".zip";
		my $collection_md5_file = $collection . ".md5";

		# Add the collection directory to the PATH
		if ($in_path == 0) {
			$Collections{$collection} = 1;
			$ENV{'PATH'} .= ":$ConfDir/collections/$collection";
		}

		# Get remote md5
		next unless (recv_file ($collection_md5_file) == 0);
		open (MD5_FILE, "< $Conf{'temporal'}/$collection_md5_file") || error ("Could not open file '$Conf{'temporal'}/$collection_md5_file' for reading: $!.");
		my $remote_collection_md5 = <MD5_FILE>;
		close (MD5_FILE);
		unlink ("$Conf{'temporal'}/$collection_md5_file");

		# Read local md5
		my $local_collection_md5 = '';
		if (defined (open (MD5_FILE, "< $ConfDir/collections/$collection_md5_file"))) {
			$local_collection_md5 = <MD5_FILE>;
			close MD5_FILE;
		}

		# Check for changes
		$local_collection_md5 = $remote_collection_md5 unless defined ($local_collection_md5);
		next if ($local_collection_md5 eq $remote_collection_md5);
		
		# Download and unzip
		next unless (recv_file ($collection_file) == 0);
		rmrf ("$ConfDir/collections/$collection");
		`unzip -d "$ConfDir/collections/$collection" "$Conf{'temporal'}/$collection_file" 2>$DevNull`;
		unlink ("$Conf{'temporal'}/$collection_file");		
		
		# Save the new md5
		open (MD5_FILE, "> $ConfDir/collections/$collection_md5_file") || error ("Could not open file '$ConfDir/collections/$collection_md5_file' for writing: $!.");
		print MD5_FILE "$remote_collection_md5";
		close (MD5_FILE);
		
		# Set proper file permissions
		chmodr (0750, "$ConfDir/collections/$collection");
	}
}

###############################################################################
# MD5 leftrotate function. See http://en.wikipedia.org/wiki/MD5#Pseudocode.
###############################################################################
sub leftrotate ($$) {
	my ($x, $c) = @_;

	return (0xFFFFFFFF & ($x << $c)) | ($x >> (32 - $c));
}

###############################################################################
# Initialize some variables needed by the MD5 algorithm.
# See http://en.wikipedia.org/wiki/MD5#Pseudocode.
###############################################################################
my (@R, @K);
sub md5_init () {

	# R specifies the per-round shift amounts
	@R = (7, 12, 17, 22,  7, 12, 17, 22,  7, 12, 17, 22,  7, 12, 17, 22,
		  5,  9, 14, 20,  5,  9, 14, 20,  5,  9, 14, 20,  5,  9, 14, 20,
		  4, 11, 16, 23,  4, 11, 16, 23,  4, 11, 16, 23,  4, 11, 16, 23,
		  6, 10, 15, 21,  6, 10, 15, 21,  6, 10, 15, 21,  6, 10, 15, 21);

	# Use binary integer part of the sines of integers (radians) as constants
	for (my $i = 0; $i < 64; $i++) {
		$K[$i] = floor(abs(sin($i + 1)) * MOD232);
	}
}

###############################################################################
# Return the MD5 checksum of the given string. 
# Pseudocode from http://en.wikipedia.org/wiki/MD5#Pseudocode.
###############################################################################
sub md5 ($) {
	my $str = shift;

	# Note: All variables are unsigned 32 bits and wrap modulo 2^32 when calculating

	# Initialize variables
	my $h0 = 0x67452301;
	my $h1 = 0xEFCDAB89;
	my $h2 = 0x98BADCFE;
	my $h3 = 0x10325476;

	# Pre-processing
	my $msg = unpack ("B*", pack ("A*", $str));
	my $bit_len = length ($msg);

	# Append "1" bit to message
	$msg .= '1';

	# Append "0" bits until message length in bits ≡ 448 (mod 512)
	$msg .= '0' while ((length ($msg) % 512) != 448);

	# Append bit /* bit, not byte */ length of unpadded message as 64-bit little-endian integer to message
	$msg .= unpack ("B64", pack ("VV", $bit_len));

	# Process the message in successive 512-bit chunks
	for (my $i = 0; $i < length ($msg); $i += 512) {

		my @w;
		my $chunk = substr ($msg, $i, 512);

		# Break chunk into sixteen 32-bit little-endian words w[i], 0 <= i <= 15
		for (my $j = 0; $j < length ($chunk); $j += 32) {
			push (@w, unpack ("V", pack ("B32", substr ($chunk, $j, 32))));
		}

		# Initialize hash value for this chunk
		my $a = $h0;
		my $b = $h1;
		my $c = $h2;
		my $d = $h3;
		my $f;
		my $g;

		# Main loop
		for (my $y = 0; $y < 64; $y++) {
			if ($y <= 15) {
				$f = $d ^ ($b & ($c ^ $d));
				$g = $y;
			}
			elsif ($y <= 31) {
				$f = $c ^ ($d & ($b ^ $c));
				$g = (5 * $y + 1) % 16;
			}
			elsif ($y <= 47) {
				$f = $b ^ $c ^ $d;
				$g = (3 * $y + 5) % 16;
			}
			else {
				$f = $c ^ ($b | (0xFFFFFFFF & (~ $d)));
				$g = (7 * $y) % 16;
			}

			my $temp = $d;
			$d = $c;
			$c = $b;
			$b = ($b + leftrotate (($a + $f + $K[$y] + $w[$g]) % MOD232, $R[$y])) % MOD232;
			$a = $temp;
		}

		# Add this chunk's hash to result so far
		$h0 = ($h0 + $a) % MOD232;
		$h1 = ($h1 + $b) % MOD232;
		$h2 = ($h2 + $c) % MOD232;
		$h3 = ($h3 + $d) % MOD232;
	}

	# Digest := h0 append h1 append h2 append h3 #(expressed as little-endian)
	return unpack ("H*", pack ("V", $h0)) . unpack ("H*", pack ("V", $h1)) . unpack ("H*", pack ("V", $h2)) . unpack ("H*", pack ("V", $h3));
}

################################################################################
# Try to guess the OS version.
################################################################################
sub guess_os_version ($) {
	my $os = shift;
	my $os_version;

	# Linux
	if ($os eq 'linux') {
		$os_version = `lsb_release -sd 2>$DevNull`;
	# AIX
	} elsif ($os eq 'aix') {
		$os_version = "$2.$1" if (`uname -rv` =~ /\s*(\d)\s+(\d)\s*/);
	# Windows
	} elsif ($os =~ /win/i) {
		$os_version = `ver`;
		$DevNull = '/Nul';
		$CmdSep = '\&';
		$OS = "windows";

	# Solaris, HP-UX, BSD and others
	} else {
		$os_version = `uname -r`;
	}
	
	# Something went wrong
	return '' unless defined ($os_version);
	
	# Remove any trailing new lines
	chomp ($os_version);

	return $os_version;
}

################################################################################
# Execute the given module.
################################################################################
sub exec_module ($) {
	my $module = shift;

	# Need something to execute
	if ($module->{'func'} == 0) {
		$ThreadSem->up () if (defined ($ThreadSem) && $Conf{'agent_threads'} > 1);
		return;
	}
	
	# Check module interval
	if (++($module->{'counter'}) < $module->{'interval'}) {
		$ThreadSem->up () if (defined ($ThreadSem) && $Conf{'agent_threads'} > 1);
		return;
	}

	# Check module cron
	if (check_module_cron ($module) != 1) {
		$ThreadSem->up () if (defined ($ThreadSem) && $Conf{'agent_threads'} > 1);
		return;
	}
	
	# Reset module counter
	$module->{'counter'} = 0;

	# Temporarily disable strict refs
	no strict 'refs';

	# Run
	my @value = &{$module->{'func'}}($module);
	
	# Save the module value if needed (only works for the first returned value)
	if ($module->{'save'} ne '') {
		if (defined ($value[0])) {
			$ENV{$module->{'save'}} = $value[0] ;
		} else {
			$ENV{$module->{'save'}} = '';
		}
	}

	write_module_xml ($module, @value);
	
	$ThreadSem->up () if (defined ($ThreadSem) && $Conf{'agent_threads'} > 1);
}

################################################################################
# Load process information.
################################################################################
sub load_procs () {
	my $utimestamp = time ();

	# Do we know hoy to get process information in this OS?
	return unless defined (PROC_CMDS->{$OS});

	# Update at most once every interval
	return if ($Procs{'__utimestamp__'} > ($utimestamp - $Conf{'interval'}));

	# Get process information
	my $cmd = PROC_CMDS->{$OS};
	my @procs = `$cmd`;
	return undef unless ($? eq 0);

	# Clear past process infomation
	%Procs = ();

	# Parse process information
	foreach my $proc (@procs) {

		chomp ($proc);		
		my @proc_info = split (/\s+/, $proc);
		next unless ($#proc_info >= 2);

		# Process command
		my $proc_cmd = join (' ', @proc_info[2..$#proc_info]);

		# Process command
		$Procs{$proc_cmd} = ();
		
		# Process CPU usage
		$Procs{$proc_cmd}{'cpu'} = $proc_info[0];

		# Process virtual size
		$Procs{$proc_cmd}{'size'} = $proc_info[1];
	}

	$Procs{'__utimestamp__'} = $utimestamp;
}

################################################################################
# Load partition information.
################################################################################
sub load_parts () {
	my $utimestamp = time ();

	# Do we know hoy to get partition information in this OS?
	return unless defined (PART_CMDS->{$OS});

	# Update at most once every interval
	return if ($Parts{'__utimestamp__'} > ($utimestamp - $Conf{'interval'}));

	# Get partition information
	my $cmd = PART_CMDS->{$OS};
	my @parts = `$cmd`;
	return undef unless ($? eq 0);

	# Parse partition information
	foreach my $part (@parts) {

		chomp ($part);		
		my @part_info = split (/\s+/, $part);
		next unless ($#part_info >= 2);
		
		my $part = join (' ', @part_info[2..$#part_info]);

		# Mount point
		$Parts{$part} = ();
		
		# Total space in kB
		$Parts{$part}{'total'} = $part_info[0];

		# Available space in kB
		$Parts{$part}{'avail'} = $part_info[1];
	}

	$Parts{'__utimestamp__'} = $utimestamp;
}

################################################################################
# Execute the given command precondition.
################################################################################
sub module_precondition_exec ($) {
	my $module = shift;
	my @data;

	# Check module parameters
	return () unless ($module->{'params_precon'} ne '');

	# Execute the command
	if ($module->{'timeout'} == 0) {
		@data = `$module->{'params_precon'} 2> $DevNull`;
	} else {
		my $cmd = quotemeta ($module->{'params_precon'});
		@data = `$Conf{'pandora_exec'} $module->{'timeout'} $cmd 2> $DevNull`;
	}

	# Something went wrong or no data
	return () unless ($? eq 0 && defined ($data[0]));
	
# Evaluate module preconditions
	evaluate_module_preconditions ($module, $data[0]);
	
	return @data;
}

################################################################################
# Execute the given command.
################################################################################
sub module_exec ($) {
	my $module = shift;
	my @data;
	my $exe;

	$exe = evaluate_module_preconditions ($module);

	return @data if ($exe == 0);
	
	# Check module parameters
	return () unless ($module->{'params'} ne '');

	# Execute the command
	if ($module->{'timeout'} == 0) {
		@data = `$module->{'params'} 2> $DevNull`;
	} else {
		my $cmd = quotemeta ($module->{'params'});
		@data = `$Conf{'pandora_exec'} $module->{'timeout'} $cmd 2> $DevNull`;
	}

	# Something went wrong or no data
	return () unless ($? eq 0 && defined ($data[0]));

	# Evaluate module conditions
	evaluate_module_conditions ($module, $data[0]);

	return @data;
}

################################################################################
# Get the status of a process. 1 running, 0 not running.
################################################################################
sub module_proc ($) {
	my $module = shift;

	# Check module parameters
	return () unless ($module->{'params'} ne '');

	# Data collection layer
	load_procs ();

	return (1) if defined ($Procs{$module->{'params'}});
	return (0);
}

################################################################################
# Get the CPU usage of a process.
################################################################################
sub module_cpuproc ($) {
	my $module = shift;

	# Check module parameters
	return () unless ($module->{'params'} ne '');

	# Data collection layer
	load_procs ();

	return () unless defined ($Procs{$module->{'params'}}) and defined ($Procs{$module->{'params'}}{'cpu'});
	return ($Procs{$module->{'params'}}{'cpu'});
}

################################################################################
# Get the memory usage of a process in Mbytes.
################################################################################
sub module_memproc ($) {
	my $module = shift;

	# Check module parameters
	return () unless ($module->{'params'} ne '');

	# Data collection layer
	load_procs ();

	return () unless defined ($Procs{$module->{'params'}}) and defined ($Procs{$module->{'params'}}{'size'});
	return (sprintf ("%d", $Procs{$module->{'params'}}{'size'} / 1024));
}

################################################################################
# Get the free space in a partition in Mbytes.
################################################################################
sub module_freedisk ($) {
	my $module = shift;

	# Check module parameters
	return () unless ($module->{'params'} ne '');

	# Data collection layer
	load_parts ();

	return () unless defined ($Parts{$module->{'params'}}) and defined ($Parts{$module->{'params'}}{'avail'});
	
	my $avail = sprintf("%d", $Parts{$module->{'params'}}{'avail'} / 1024);
	return ($avail);
}

################################################################################
# Get the free space in a partition in %.
################################################################################
sub module_freepercentdisk ($) {
	my $module = shift;

	# Check module parameters
	return () unless ($module->{'params'} ne '');

	# Data collection layer
	load_parts ();

	return () unless defined ($Parts{$module->{'params'}}) and defined ($Parts{$module->{'params'}}{'avail'});
	
	my $availp = sprintf("%d", $Parts{$module->{'params'}}{'avail'} * 100 / $Parts{$module->{'params'}}{'total'});
	return ($availp);
}

################################################################################
# Get the occupied space in a partition in %.
################################################################################
sub module_occupiedpercentdisk ($) {
	my $module = shift;

	# Check module parameters
	return () unless ($module->{'params'} ne '');

	# Data collection layer
	load_parts ();

	return () unless defined ($Parts{$module->{'params'}}) and defined ($Parts{$module->{'params'}}{'avail'});
	
	my $occupiedp = sprintf("%d", ($Parts{$module->{'params'}}{'total'} - $Parts{$module->{'params'}}{'avail'}) * 100 / $Parts{$module->{'params'}}{'total'});
	return ($occupiedp);
}

################################################################################
# Get the CPU usage %.
################################################################################
sub module_cpuusage ($) {
	my $module = shift;

	# Do we know hoy to get CPU usage in this OS?
	return unless defined (CPUUSAGE_CMDS->{$OS});

	# Get CPU usage
	my $cmd = CPUUSAGE_CMDS->{$OS};
	my @data = `$cmd 2> $DevNull`;

	# Something went wrong or no data
	return () unless ($? eq 0 && defined ($data[0]));

	return ($data[0]);
}

################################################################################
# Get the free space in a partition in Mbytes.
################################################################################
sub module_freememory ($) {
	my $module = shift;

	# Do we know hoy to get memory information in this OS?
	return () unless defined (FREEMEMORY_CMDS->{$OS});

	# Get available memory
	my $cmd = FREEMEMORY_CMDS->{$OS};
	my @data = `$cmd 2> $DevNull`;

	# Something went wrong or no data
	return () unless ($? eq 0 && defined ($data[0]));

	return (sprintf ("%d", $data[0] / 1024));
}

################################################################################
# Get the free space in a partition in %.
################################################################################
sub module_freepercentmemory ($) {
	my $module = shift;

	# Do we know hoy to get memory information in this OS?
	return unless defined (TOTALMEMORY_CMDS->{$OS});

	# Get CPU usage
	my $cmd = TOTALMEMORY_CMDS->{$OS};
	my @data = `$cmd 2> $DevNull`;

	# Something went wrong or no data
	return () unless ($? eq 0 && defined ($data[0]));

	# Get total memory in MB
	my $total = sprintf ("%d", $data[0] / 1024);
	
	# Get available memory in MB
	my ($avail) = module_freememory ($module);
	return () unless defined ($avail);
	
	return sprintf (("%d", $avail * 100 / $total));
}

################################################################################
# Evaluate and execute module preconditions.
################################################################################
sub evaluate_module_preconditions ($) {
	my ($module) = @_;

	# Evaluate preconditions
	if ($module->{'precon'}){
		
		foreach my $precondition (@{$module->{'precondition'}}) {
			
			my $data = `$precondition->{'command'} 2> $DevNull`;
			
			{
				# Do not display a warning if the output of the command is not numeric
				no warnings;
				if (($precondition->{'operator'} eq '>' && $data > $precondition->{'value_1'}) ||
					($precondition->{'operator'} eq '<' && $data < $precondition->{'value_1'}) ||
					($precondition->{'operator'} eq '=' && $data == $precondition->{'value_1'}) ||
					($precondition->{'operator'} eq '!=' && $data != $precondition->{'value_1'}) ||
					($precondition->{'operator'} eq '=~' && $data =~ /$precondition->{'value_1'}/) ||
					($precondition->{'operator'} eq '()' && $data > $precondition->{'value_1'} && $data < $precondition->{'value_2'})) {
				} else {
					return 0;
				}
			};
		}
	}
	
	return 1;
}


################################################################################
# Evaluate and execute module conditions.
################################################################################
sub evaluate_module_conditions ($$) {
	my ($module, $data) = @_;

	# Evaluate conditions
	foreach my $condition (@{$module->{'conditions'}}) {
		if (($condition->{'operator'} eq '>' && $data > $condition->{'value_1'}) ||
			($condition->{'operator'} eq '<' && $data < $condition->{'value_1'}) ||
			($condition->{'operator'} eq '=' && $data == $condition->{'value_1'}) ||
			($condition->{'operator'} eq '!=' && $data != $condition->{'value_1'}) ||
			($condition->{'operator'} eq '=~' && $data =~ /$condition->{'value_1'}/) ||
			($condition->{'operator'} eq '()' && $data > $condition->{'value_1'} && $data < $condition->{'value_2'})) {
				`$condition->{'command'} 2> $DevNull`;
		}
	}
}

################################################################################
# Checks the module's cron string. Returns 1 if the module should be run, 0 if
# not.
################################################################################
sub check_module_cron ($) {
	my $module = shift;
	
	# No cron string defined
	return 1 unless ($module->{'cron'} ne '');

	# Check if the module was already executed
	return 0 unless (time() > $module->{'cron_utimestamp'});

	# Get cron configuration
	my @cron_params = split (/\s/, $module->{'cron'});

	# Get current time
	my $current_time = time();
	my @time = localtime($current_time);

	# Minutes, hours, day of the month, month and day of the week
	my @time_params = @time[1, 2, 3, 4, 6];

	# Fix month (localtime retuns 0..11 and we need 1..12)
	$time_params[3] += 1;
	
	# Check cron parameters	
	for (my $i = 0; $i < 5; $i++) {
		
		# Wildcard
		next if ($cron_params[$i] eq '*');
		
		# Get interval
		my ($bottom, $top) = split (/-/, $cron_params[$i]);
		$top = $bottom unless defined ($top);
		
		# Check interval
		if ($bottom <= $top) {
			return 0 if ($time_params[$i] < $bottom || $time_params[$i] > $top);
		} else {
			return 0 if ($time_params[$i] < $bottom && $time_params[$i] > $top);
		}
	}

	# Do not check in the next minute, hour, day or month.
	my $offset = 0; 
	if ($module->{'cron_interval'} >= 0) {
		$offset = $module->{'cron_interval'};
	} elsif($cron_params[0] ne '*') {
		# 1 minute
		$offset = 60;
	} elsif($cron_params[1] ne '*') {
		# 1 hour
		$offset = 3600;
	} elsif($cron_params[2] ne '*' || $cron_params[4] ne '*') {
		# 1 day
		$offset = 86400;
	} elsif($cron_params[3] ne '*') {
		# 31 days
		$offset = 2678400;
	}

	$module->{'cron_utimestamp'} = $current_time + $offset;
	return 1;
}

################################################################################
# Write module data in XML format.
################################################################################
sub write_module_xml ($@) {
	my ($module, @data) = @_;

	# No data
	return unless (defined $data[0]);

	# Critical section
	$Sem->down () if (defined ($Sem));

	$Xml .= "	<module>\n" .
		"	<name><![CDATA[" . $module->{'name'} . "]]></name>\n" .
		"	<description><![CDATA[" . $module->{'description'} . "]]></description>\n" . 
		"	<type>" . $module->{'type'} . "</type>\n";

	# Interval
	$Xml .= "	<module_interval>" . $module->{'interval'} . "</module_interval>\n" if ($module->{'interval'} > 1);
	
	# Min
	$Xml .= "	<min>" . $module->{'min'} . "</min>\n" if (defined ($module->{'min'}));

	# Max
	$Xml .= "	<max>" . $module->{'max'} . "</max>\n" if (defined ($module->{'max'}));

	# Post process
	$Xml .= "	<post_process>" . $module->{'post_process'} . "</post_process>\n" if (defined ($module->{'post_process'}));

	# Min critical
	$Xml .= "	<min_critical>" . $module->{'min_critical'} . "</min_critical>\n" if (defined ($module->{'min_critical'}));

	# Max critical
	$Xml .= "	<max_critical>" . $module->{'max_critical'} . "</max_critical>\n" if (defined ($module->{'max_critical'}));

	# Min warning
	$Xml .= "	<min_warning>" . $module->{'min_warning'} . "</min_warning>\n" if (defined ($module->{'min_warning'}));

	# Max warning
	$Xml .= "	<max_warning>" . $module->{'max_warning'} . "</max_warning>\n" if (defined ($module->{'max_warning'}));

	# Disabled
	$Xml .= "	<disabled>" . $module->{'disabled'} . "</disabled>\n" if (defined ($module->{'disabled'}));

	# Min ff event
	$Xml .= "	<min_ff_event>" . $module->{'min_ff_event'} . "</min_ff_event>\n" if (defined ($module->{'min_ff_event'}));

	# Data list
	if ($#data > 0) {
		$Xml .= "	<datalist>\n";
		foreach my $data_item (@data) {
			chomp ($data_item);
			$Xml .= "	<data><value><![CDATA[$data_item]]></value></data>\n";
		}
		$Xml .= "	</datalist>\n";
	# Single data
	} else {
		chomp ($data[0]);
		$Xml .= "	<data><![CDATA[$data[0]]]></data>\n";
	}
	$Xml .= "	</module>\n";

 	$Sem->up () if (defined ($Sem));
}

################################################################################
# Receive a UDP server signal to restart agent
################################################################################
sub udp_server_signal () {
	log_message ('udp server', 'Received signal to restart the agent.');
}

################################################################################
# Basic UDP server to restart agent on UDP signal received
################################################################################
sub udp_server ($$) {

	my $udp_port = shift;
	my $udp_auth_address = shift;
	my $parent_pid = getppid();

	my($sock, $oldmsg, $newmsg, $hisaddr, $hishost, $MAXLEN);
	$MAXLEN = 1024;

	log_message ('udp server', 'Starting UDP server listening on '.$udp_auth_address.":".$udp_port);
	$sock = IO::Socket::INET->new(LocalPort => $udp_port, Proto => 'udp') or die "socket: $@";

	while ($sock->recv($newmsg, $MAXLEN)) {
		my($port, $ipaddr) = sockaddr_in($sock->peername);
		$hishost = gethostbyaddr($ipaddr, AF_INET);

		log_message ('udp server', 'Received signal from '.$hishost);

		if (($udp_auth_address eq "0.0.0.0") || ($hishost eq $udp_auth_address)){
			if ($newmsg =~ /REFRESH AGENT/){
				# Send signal to restart agent
				kill 'SIGINT' , $parent_pid;
			}
		}
	}
}

################################################################################
# Execute the given plugin.
################################################################################
sub exec_plugin ($) {
	my $plugin = shift;

	my $output = `$plugin 2>$DevNull`;

	# Do not save the output if there was an error
	if ($? != 0) {
		$ThreadSem->up () if (defined ($ThreadSem) && $Conf{'agent_threads'} > 1);
		return;
	}

	# Critical section
	$Sem->down () if (defined ($Sem));
	$Xml .= $output;
 	$Sem->up () if (defined ($Sem));

	$ThreadSem->up () if (defined ($ThreadSem) && $Conf{'agent_threads'} > 1);
}

################################################################################
# TERM Handler
################################################################################
sub kill_signal_handler (){
	# Kill tentacle server if it was launched

	if (defined ($tentacle_pid)) {
			print "kill -9 $tentacle_pid\n";
			`kill -9 $tentacle_pid`;
	}
	exit (0);
}

################################################################################
# Main.
################################################################################

#Handler TERM signal.
$SIG{'TERM'} = \&kill_signal_handler;

# Check command line arguments
print_usage unless ($#ARGV == 0);
$ConfDir = fix_directory ($ARGV[0]);
error ("Directory '$ConfDir' does not exist.") unless (-d "$ConfDir");

#Pandora home path
$ENV{'PANDORA_HOME'}=$ConfDir;

# Get user to run as
my $pandora_user = read_config ('pandora_user');
if (defined ($pandora_user)) {
	# Change the EUID
	my $pandora_user_uid = getpwnam ($pandora_user);
	if (!defined ($pandora_user_uid)) {
		error ("Cannot get uid for user $pandora_user. Does the user exist and can we read /etc/passwd?");
	}
	$> = $pandora_user_uid;
	if ($> != $pandora_user_uid) {
		error ("Cannot run as $pandora_user: Insufficient permissions.");
	}
}

# Guess the OS version
$OS_VERSION = guess_os_version ($OS);

# Initialize MD5 variables
md5_init ();

# Start logging
start_log ();
log_message ('log', 'Running as user ' . getpwuid ($>));

# Read configuration file
read_config ();

$ENV{'PANDORA_AGENT'}=$Conf{'agent_name'};

# Fix directory names
$Conf{'temporal'} = fix_directory ($Conf{'temporal'});
error ("Temporal directory '" . $Conf{'temporal'} . "' does not exist.") unless (-d "$Conf{'temporal'}");
$Conf{'server_path'} = fix_directory ($Conf{'server_path'});
$Conf{'secondary_server_path'} = fix_directory ($Conf{'secondary_server_path'});

# Startup delay
log_message ('log', 'Sleeping for ' . $Conf{'delayed_startup'} . ' seconds.') if ($Conf{'delayed_startup'} > 0);
sleep ($Conf{'delayed_startup'});

#Set nice of the pandora_agent
my $PID = $$;
`renice "$Conf{'pandora_nice'}" "$PID"`;

#Launch tentacle server in proxy mode if configured
if ($Conf{'proxy_mode'}) {
	
	#Check if user is root
	if ($< != 0) {		
		launch_tentacle_proxy();
	} else {
		error ('Proxy mode can not be launched as root');
	}
}

# Add the plugins directory to the PATH
$ENV{'PATH'} .= ":$ConfDir/plugins";

# Start UDP server if configured
if ($Conf{'udp_server'} == 1){
	my $pid = fork();

	if ($pid == 0){
		udp_server ($Conf{'udp_server_port'}, $Conf{'udp_server_auth_address'});
		exit;
	}
}

# Must be set to 0 if the agent is a broker agent
my $main_agent = -1;

# Loop
while (1) {

	# Ignore signals from UDP and Tentacle server while processing execution
	if ($Conf{'udp_server'} == 1 || $Conf{'proxy_mode'}){
		$SIG{'INT'} = 'DEFAULT';
	}

	# Check for a new configuration
	check_remote_config () unless ($Conf{'debug'} eq '1');

	# Check file collections
	check_collections () unless ($Conf{'debug'} eq '1');

	# Launch broker agents
	@BrokerPid = ();
	my @broker_agents = read_config ('broker_agent');
	foreach my $broker_agent (@broker_agents) {
		
		# Create broker conf file if it does not exist
		if (! -e "$ConfDir/${broker_agent}.conf") {
			write_broker_conf($broker_agent);
		}
		
		$main_agent = fork ();
			
		# Broker agent
		if ($main_agent == 0) {
		
			# Set the configuration file
			$ConfFile = "${broker_agent}.conf";
			
			# Log to a new file
			stop_log ();
			start_log ('quiet');
				
			# Read configuration file
			@Modules = ();
			@Plugins = ();
			%Collections = ();
			read_config ();
					
			# Check for a new configuration
			check_remote_config () unless ($Conf{'debug'} eq '1');
				
			# Check file collections
			check_collections () unless ($Conf{'debug'} eq '1');
					
			# Execute
			last;
		} else {
			push (@BrokerPid, $main_agent);
		}
	}

	my $address;

	if(defined($Conf{'address'})) {
		# Check if address is auto to get the local ip
		if ($Conf{'address'} eq 'auto') {
			# Tested on Ubuntu, debian, Suse, Solaris 10 and AIX 5.1
			$address = `ifconfig -a | grep -v '127.0.0' | grep '[0-9]*\\.[0-9]*\\.[0-9]*' | awk '{ print \$2 }' | head -1 | sed -e 's/addr\\://' | sed -e 's/inet\\://'`;
			chomp($address);
		}
		else {
			$address = $Conf{'address'};
		}
	}
	
	$Xml = "<?xml version='1.0' encoding='" . $Conf{'encoding'} . "'?>\n" .
		"<agent_data description='" . $Conf{'description'} ."' group='" . $Conf{'group'} .
		"' os_name='$OS' os_version='$OS_VERSION' interval='" . $Conf{'interval'} .
		"' version='" . AGENT_VERSION . '(Build ' . AGENT_BUILD . ')' . ($Conf{'autotime'} eq '1' ? '' : "' timestamp='" . strftime ('%Y/%m/%d %H:%M:%S', localtime ())) .
		"' agent_name='" . $Conf{'agent_name'} . "' timezone_offset='". $Conf{'timezone_offset'}; 

	if (defined ($Conf{'address'})) {
		$Xml .= "' address='" .$address;
	}
	
	if (defined ($Conf{'parent_agent_name'})) {
		$Xml .= "' parent_agent_name='" .$Conf{'parent_agent_name'};
	}
	
	# Check the gis mode (exec or manual). If exec script is defined, we execute it and get the coordenates
	if (defined ($Conf{'gis_exec'}) && (-e $Conf{'gis_exec'})) {		
		my $coord_str = `$Conf{'gis_exec'}`;
		chomp($coord_str);
		my @coords = split(',',$coord_str);
		# Check if lat and long are numeric
		if (defined($coords[0]) && defined($coords[1]) && ($coords[0] =~ /^-?(\d+)\.(\d+)$|^-?(\d+)$/) && ($coords[1] =~ /^-?(\d+)\.(\d+)$|^-?(\d+)$/)) {
			my $lat = $coords[0];
			my $long = $coords[1];
			
			$Xml .= "' longitude='" .$long . "' latitude='" .$lat;

			if (defined ($coords[2])) {
				my $alt = $coords[2];
				$Xml .= "' altitude='" .$alt;
			}
			if (defined ($Conf{'position_description'})) {
				$Xml .= "' position_description='" .$Conf{'position_description'};
			}
		}
	}
	elsif (defined ($Conf{'longitude'}) && defined ($Conf{'latitude'})) {
		$Xml .= "' longitude='" .$Conf{'longitude'} . "' latitude='" .$Conf{'latitude'};
		if (defined ($Conf{'altitude'})) {
			$Xml .= "' altitude='" .$Conf{'altitude'};
		}
		if (defined ($Conf{'position_description'})) {
			$Xml .= "' position_description='" .$Conf{'position_description'};
		}
	}
	$Xml .= "'>\n";

	# Execute modules
	foreach my $module (@Modules) {

		# Execute the module in a separate thread
		if (defined ($ThreadSem) && $Conf{'agent_threads'} > 1) {
			$ThreadSem->down ();
			my $thr = threads->create (\&exec_module, $module);
			if (! defined ($thr)) {
				$ThreadSem->up ();
			} else {
				$thr->detach();
			}
		# Execute the module
		} else {
			exec_module ($module);
		}
	}

	# Execute plugins
	foreach my $plugin (@Plugins) {

		# Execute the plugin in a separate thread
		if (defined ($ThreadSem) && $Conf{'agent_threads'} > 1) {
			$ThreadSem->down ();
			my $thr = threads->create (\&exec_plugin, $plugin);
			if (! defined ($thr)) {
				$ThreadSem->up ();
			} else {
				$thr->detach();
			}
		# Execute the plugin
		} else {
			exec_plugin ($plugin);
		}
	}

	# Wait for all the threads
	$ThreadSem->down ($Conf{'agent_threads'}) if (defined ($ThreadSem) && $Conf{'agent_threads'} > 1);
	$ThreadSem->up ($Conf{'agent_threads'}) if (defined ($ThreadSem) && $Conf{'agent_threads'} > 1);
	
	$Xml .= "</agent_data>";

	# Save XML data file
	my $temp_file = $Conf{'temporal'} . '/' . $Conf{'agent_name'} . '.' . time () . '.data';
	open (TEMP_FILE, "> $temp_file") || error ("Could not write XML data file: $!");
	print TEMP_FILE $Xml;
	close (TEMP_FILE);

	# Debug mode
	if ($Conf{'debug'} eq '1') {
		log_message ('debug', "Wrote XML data file '$temp_file'");
		log_message ('debug', "Wrote XML data file '$temp_file'", *STDOUT);
		last;
	}

	# Send the XML data file
	send_file ($temp_file, 1);
	unlink ($temp_file);
	
	# Cron mode
	last if ($Conf{'cron_mode'} == 1);
	
	# Enable signal capture to break the Sleep interval on UDP signal
	if ($Conf{'udp_server'} == 1){
		$SIG{'INT'} = \&udp_server_signal;
	}

	# Sleep if main agent
	if ($main_agent != 0) {
		foreach my $broker_pid (@BrokerPid) {
			waitpid ($broker_pid, 0);
		}
		sleep ($Conf{'interval'});
	}
	# Finish if broker agent
	else {
		exit (0);
	}
}

__END__

=head1 EXIT STATUS

=over 

=item 0 on Success

=item 1 on Error

=back 

=head1 CONFIGURATION

By default pandora_agent uses F</etc/pandora> as B<home configuration directory>. There is the F<pandora_agent.conf> file with all the configuration of the agent.

=head1 DEPENDENCIES


=head1 LICENSE

This is released under the GNU Lesser General Public License.

=head1 SEE ALSO


=head1 COPYRIGHT

Copyright (c) 2005-2010 Artica Soluciones Tecnologicas S.L

=cut