This file is indexed.

/usr/share/perl5/EBox/DHCP.pm is in zentyal-dhcp 2.3.8+quantal1.

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

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
# Copyright (C) 2008-2012 eBox Technologies S.L.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, version 2, as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

package EBox::DHCP;

use strict;
use warnings;

use base qw(EBox::Module::Service
            EBox::NetworkObserver
            EBox::LogObserver);

use EBox::Config;
use EBox::Exceptions::InvalidData;
use EBox::Exceptions::Internal;
use EBox::Exceptions::DataNotFound;
use EBox::Gettext;
use EBox::Global;
use EBox::Menu::Item;
use EBox::Menu::Folder;
use EBox::Objects;
use EBox::Validate qw(:all);


use EBox::Sudo;
use EBox::NetWrappers qw(:all);
use EBox::Service;
use EBox::DHCPLogHelper;

use EBox::Dashboard::Section;
use EBox::Dashboard::List;

use Net::IP;
use Error qw(:try);
use Perl6::Junction qw(any);
use Text::DHCPLeases;

# Module local conf stuff
# FIXME: extract this from somewhere to support multi-distro?
#use constant DHCPCONFFILE => "@DHCPDCONF@";
#use constant LEASEFILE => "@DHCPDLEASES@";
#use constant PIDFILE => "@DHCPDPID@";
#use constant DHCP_SERVICE => "@DHCPD_SERVICE@";
use constant DHCPCONFFILE => "/etc/dhcp/dhcpd.conf";
use constant LEASEFILE => "/var/lib/dhcp/dhcpd.leases";
use constant PIDFILE => "/var/run/dhcp-server/dhcpd.pid";
use constant DHCP_SERVICE => "isc-dhcp-server";

use constant TFTP_SERVICE => "tftpd-hpa";

use constant CONF_DIR => EBox::Config::conf() . 'dhcp/';
use constant PLUGIN_CONF_SUBDIR => 'plugins/';
use constant TFTPD_CONF_DIR => '/var/lib/tftpboot/';
use constant INCLUDE_DIR => EBox::Config::etc() . 'dhcp/';
use constant APPARMOR_DHCPD => '/etc/apparmor.d/local/usr.sbin.dhcpd';

# Group: Public and protected methods

# Constructor: _create
#
#    Create the zentyal-dhcp module
#
# Overrides:
#
#    <EBox::Module::Service::_create>
#
sub _create
{
    my $class = shift;
    my $self  = $class->SUPER::_create(name => 'dhcp',
                                       printableName => 'DHCP',
                                       @_);
    bless ($self, $class);

    return $self;
}

# Method: usedFiles
#
#   Override EBox::Module::Service::usedFiles
#
sub usedFiles
{
    return [
            {
             'file' => DHCPCONFFILE,
             'module' => 'dhcp',
             'reason' => __x('{server} configuration file', server => 'dhcpd'),
            },
            {
             'file'   => APPARMOR_DHCPD,
             'module' => 'dhcp',
             'reason' => __x('AppArmor profile for {server} daemon', server => 'dhcpd'),
            },
           ];
}

# Method: initialSetup
#
# Overrides:
#   EBox::Module::Base::initialSetup
#
sub initialSetup
{
    my ($self, $version) = @_;

    # Create default services, rules and conf dir
    # only if installing the first time
    unless ($version) {
        my $services = $self->global()->modInstance('services');
        my $firewall = $self->global()->modInstance('firewall');

        my $serviceName = 'tftp';
        unless ($services->serviceExists(name => $serviceName)) {
            $services->addMultipleService(
                'name' => $serviceName,
                'printableName' => 'TFTP',
                'description' => __('Trivial File Transfer Protocol'),
                'readOnly' => 1,
                'services' => [ { protocol => 'udp',
                                  sourcePort => 'any',
                                  destinationPort => 69 } ] );

            $firewall->setInternalService($serviceName, 'accept');
        }

        $serviceName = 'dhcp';
        unless ($services->serviceExists(name => $serviceName)) {
            $services->addMultipleService(
                'name' => $serviceName,
                'printableName' => 'DHCP',
                'description' => __('Dynamic Host Configuration Protocol'),
                'readOnly' => 1,
                'services' => [ { protocol => 'udp',
                                  sourcePort => '67:68',
                                  destinationPort => '67:68' } ] );

            $firewall->setInternalService($serviceName, 'accept');
        }

        $firewall->saveConfigRecursive();

        mkdir (CONF_DIR, 0755);
    }
}

# Method: appArmorProfiles
#
#   Overrides to set the own AppArmor profile to allow Dynamic DNS to
#   work and LSTP configuration using /etc/zentyal/dhcp/...
#
# Overrides:
#
#    <EBox::Module::Base::appArmorProfiles>
#
sub appArmorProfiles
{
    my ($self) = @_;

    my @params = ( 'keysFile' => $self->_keysFile(),
                   'confDir'  => $self->IncludeDir() );

    return [
        { 'binary' => 'usr.sbin.dhcpd',
          'local'  => 1,
          'file'   => 'dhcp/apparmor-dhcpd.local.mas',
          'params' => \@params }
       ];
}

# Method: actions
#
#   Override EBox::Module::Service::actions
#
sub actions
{
    return [
        {
            'action' => __x('Disable {server} init script', server => 'dhcpd'),
            'reason' => __('Zentyal will take care of start and stop ' .
                'the service'),
            'module' => 'dhcp',
        }
    ];
}

# Method: _daemons
#
# Overrides:
#
#   <EBox::Module::Service::daemons>
#
sub _daemons
{
    return [ { 'name' => DHCP_SERVICE } ];
}

# Method: _setConf
#
#      Writes the configuration files
#
# Overrides:
#
#      <EBox::Module::Base::_setConf>
#
sub _setConf
{
    my ($self) = @_;
    $self->_setDHCPConf();
    $self->_setTFTPDConf();
}

# Method: menu
#
# Overrides:
#
#     <EBox::Module::menu>
#
#
sub menu
{
    my ($self, $root) = @_;
    $root->add(new EBox::Menu::Item('url' => 'DHCP/View/Interfaces',
                                    'text' => $self->printableName(),
                                    'separator' => 'Infrastructure',
                                    'order' => 410));
}

# Method: depends
#
#     DHCP depends on DNS configuration only if the Dynamic DNS
#     feature is done.
#
# Overrides:
#
#     <EBox::Module::Base::depends>
#
sub depends
{
    my ($self) = @_;

    my $dependsList = $self->SUPER::depends();
    if ( $self->_dynamicDNSEnabled() ) {
        push(@{$dependsList}, 'dns');
    }

    return $dependsList;
}

# Method: initRange
#
#   Return the initial host address range for a given interface
#
# Parameters:
#
#   iface - String interface name
#
# Returns:
#
#   String - containing the initial range
#
sub initRange # (interface)
{
    my ($self, $iface) = @_;

    my $net = $self->global()->modInstance('network');
    my $address = $net->ifaceAddress($iface);
    my $netmask = $net->ifaceNetmask($iface);

    my $network = ip_network($address, $netmask);
    my ($first, $last) = $network =~ /(.*)\.(\d+)$/;
    my $init_range = $first . "." . ($last+1);
    return $init_range;
}

# Method: endRange
#
#   Return the final host address range for a given interface
#
# Parameters:
#
#   iface - String interface name
#
# Returns:
#
#   string - containing the final range
#
sub endRange # (interface)
{
    my ($self, $iface) = @_;

    my $net = $self->global()->modInstance('network');
    my $address = $net->ifaceAddress($iface);
    my $netmask = $net->ifaceNetmask($iface);

    my $broadcast = ip_broadcast($address, $netmask);
    my ($first, $last) = $broadcast =~ /(.*)\.(\d+)$/;
    my $end_range = $first . "." . ($last-1);
    return $end_range;
}

# Method: defaultGateway
#
#   Get the default gateway that will be sent to DHCP clients for a
#   given interface
#
# Parameters:
#
#       iface - interface name
#
# Returns:
#
#       string - the default gateway in a IP address form
#
# Exceptions:
#
#       <EBox::Exceptions::External> - thrown if the interface is not
#       static or the given type is none of the suggested ones
#
#       <EBox::Exceptions::DataNotFound> - thrown if the interface is
#       not found
#
sub defaultGateway # (iface)
{
    my ($self, $iface) = @_;

    my $network = $self->global()->modInstance('network');

    #if iface doesn't exists throw exception
    if (not $iface or not $network->ifaceExists($iface)) {
        throw EBox::Exceptions::DataNotFound(data => __('Interface'),
                value => $iface);
    }

    #if iface is not static, throw exception
    if($network->ifaceMethod($iface) ne 'static') {
        throw EBox::Exceptions::External(__x("{iface} is not static",
            iface => $iface));
    }

    return $self->_getModel('Options', $iface)->defaultGateway();
}

# Method: searchDomain
#
#   Get the search domain that will be sent to DHCP clients for a
#   given interface
#
# Parameters:
#
#       iface - String interface name
#
# Returns:
#
#   String - the search domain
#
#       undef  - if the none search domain has been set
#
sub searchDomain # (iface)
{
    my ($self, $iface) = @_;

    my $network = $self->global()->modInstance('network');

    #if iface doesn't exists throw exception
    if (not $iface or not $network->ifaceExists($iface)) {
        throw EBox::Exceptions::DataNotFound(data => __('Interface'),
                value => $iface);
    }

    #if iface is not static, throw exception
    if($network->ifaceMethod($iface) ne 'static') {
        throw EBox::Exceptions::External(__x("{iface} is not static",
            iface => $iface));
    }

#   $self->get_string("$iface/search");
    return $self->_getModel('Options', $iface)->searchDomain();
}

# Method: nameserver
#
#   Get the nameserver that will be sent to DHCP clients for a
#   given interface
#
# Parameters:
#
#       iface - String interface name
#       number - Int nameserver number (1 or 2)
#
#   Returns:
#
#       string - the nameserver or undef if there is no
#
# Exceptions:
#
#       <EBox::Exceptions::External> - thrown if the interface is not
#       static or the given type is none of the suggested ones
#
#       <EBox::Exceptions::DataNotFound> - thrown if the interface is
#       not found
#
#       <EBox::Exceptions::MissingArgument> - thrown if any compulsory
#       argument is missing
#
sub nameserver # (iface,number)
{
    my ($self, $iface, $number) = @_;

    if ( not defined ( $number )) {
        throw EBox::Exceptions::MissingArgument('number');
    }
    my $network = $self->global()->modInstance('network');

    #if iface doesn't exists throw exception
    if (not $iface or not $network->ifaceExists($iface)) {
        throw EBox::Exceptions::DataNotFound(data => __('Interface'),
                value => $iface);
    }

    #if iface is not static, throw exception
    if($network->ifaceMethod($iface) ne 'static') {
        throw EBox::Exceptions::External(__x("{iface} is not static",
            iface => $iface));
    }

#   $self->get_string("$iface/nameserver$number");
    return $self->_getModel('Options', $iface)->nameserver($number);
}

# Method: ntpServer
#
#       Get the NTP server that will be sent to DHCP clients for a
#       given interface
#
# Parameters:
#
#       iface - String the interface name
#
# Returns:
#
#       String - the IP address for the NTP server, undef if no
#                NTP server has been configured
#
# Exceptions:
#
#       <EBox::Exceptions::External> - thrown if the interface is not
#       static or the given type is none of the suggested ones
#
#       <EBox::Exceptions::DataNotFound> - thrown if the interface is
#       not found
#
#       <EBox::Exceptions::MissingArgument> - thrown if any compulsory
#       argument is missing
#
sub ntpServer # (iface)
{
    my ($self, $iface) = @_;

    my $network = $self->global()->modInstance('network');
    #if iface doesn't exists throw exception
    if (not $iface or not $network->ifaceExists($iface)) {
        throw EBox::Exceptions::DataNotFound(data => __('Interface'),
                                             value => $iface);
    }

    #if iface is not static, throw exception
    if($network->ifaceMethod($iface) ne 'static') {
        throw EBox::Exceptions::External(__x("{iface} is not static",
                                             iface => $iface));
    }

    return $self->_getModel('Options', $iface)->ntpServer();
}

# Method: winsServer
#
#       Get the WINS server that will be sent to DHCP clients for a
#       given interface
#
# Parameters:
#
#       iface - String the interface name
#
# Returns:
#
#       String - the IP address for the WINS server, undef if no
#                WINS server has been configured
#
# Exceptions:
#
#       <EBox::Exceptions::External> - thrown if the interface is not
#       static or the given type is none of the suggested ones
#
#       <EBox::Exceptions::DataNotFound> - thrown if the interface is
#       not found
#
#       <EBox::Exceptions::MissingArgument> - thrown if any compulsory
#       argument is missing
#
sub winsServer # (iface)
{
    my ($self, $iface) = @_;

    my $network = $self->global()->modInstance('network');
    #if iface doesn't exists throw exception
    if (not $iface or not $network->ifaceExists($iface)) {
        throw EBox::Exceptions::DataNotFound(data => __('Interface'),
                                             value => $iface);
    }

    #if iface is not static, throw exception
    if($network->ifaceMethod($iface) ne 'static') {
        throw EBox::Exceptions::External(__x("{iface} is not static",
                                             iface => $iface));
    }

    return $self->_getModel('Options', $iface)->winsServer();
}

# Method: staticRoutes
#
#   Get the static routes. It polls the Zentyal modules which
#   implements <EBox::DHCP::StaticRouteProvider>
#
# Returns:
#
#   hash ref - contating the static toutes in hash references. The
#   key is the subnet in CIDR notation that denotes where is
#   appliable the new route.  The values are hash reference with
#   the keys 'destination', 'netmask' and 'gw'
#
sub staticRoutes
{
    my ($self) = @_;
    my %staticRoutes = ();

    my @modules = @{ $self->global()->modInstancesOfType('EBox::DHCP::StaticRouteProvider') };
    foreach  my $mod (@modules) {
        my @modStaticRoutes = @{ $mod->staticRoutes() };
        while (@modStaticRoutes) {
            my $net   = shift @modStaticRoutes;
            my $route = shift @modStaticRoutes;
            if (exists $staticRoutes{$net}) {
                push  @{$staticRoutes{$net}}, $route;
            }
            else {
                $staticRoutes{$net} = [$route];
            }
        }
    }

    return \%staticRoutes;
}

sub notifyStaticRoutesChange
{
    my ($self) = @_;
    $self->setAsChanged();
}


# Method: rangeAction
#
#   Set/add a range for a given interface
#
# Parameters:
#
#   iface - String Interface name
#       action - String to perform (add/set/del)
#
#       indexValue - String index to use to set a new value, it can be a
#       name, a from IP addr or a to IP addr.
#
#       indexField - String the field name to use as index
#
#   name - String the range name
#   from - String start of range, an ip address
#   to - String end of range, an ip address
#
#       - Named parameters
#
# Exceptions:
#
#    <EBox::Exceptions::DataNotFound> - Interface does not exist
#    <EBox::Exceptions::External> - interface is not static
#    <EBox::Exceptions::External - invalid range
#    <EBox::Exceptions::External - range overlap
#
sub rangeAction # (iface, name, from, to)
{
    my ($self, %args) = @_;

    my $iface = delete ($args{iface});
    my $action = delete ($args{action});
    unless ( $action eq any(qw(add set del))) {
        throw EBox::Exceptions::External(__('Not a valid action: add, set and del '
                    . 'are available'));
    }

    my $network = $self->global()->modInstance('network');

    #if iface doesn't exists throw exception
    if (not $iface or not $network->ifaceExists($iface)) {
        throw EBox::Exceptions::DataNotFound(data => __('Interface'),
                value => $iface);
    }

    #if iface is not static, throw exception
    if($network->ifaceMethod($iface) ne 'static') {
        throw EBox::Exceptions::External(__x("{iface} is not static",
                    iface => $iface));
    }

    my $rangeModel = $self->_getModel('RangeTable', $iface);
    if ( $action eq 'add' ) {
        $rangeModel->add( name => $args{name},
                from => $args{from},
                to   => $args{to});
    } elsif ( $action eq 'set' ) {
        my $index = delete ( $args{indexValue} );
        my $indexField = delete ( $args{indexField} );
        my @args = map { $_ => $args{$_} } keys (%args);
        $rangeModel->setIndexField($indexField);
        $rangeModel->set( $index, @args );
    } elsif ( $action eq 'del' ) {
        my $index = delete ( $args{indexValue} );
        my $indexField = delete ( $args{indexField} );
        $rangeModel->setIndexField($indexField);
        $rangeModel->del( $index );
    }
}

# Method: ranges
#
#   Return all the set ranges for a given interface
#
# Parameters:
#
#   iface - String interface name
#
# Returns:
#
#   array ref - contating the ranges in hash references. Each hash holds
#   the keys 'name', 'from' and 'to'
#
# Exceptions:
#
#       <EBox::Exceptions::DataNotFound> - Interface does not exist
#
sub ranges # (iface)
{
    my ($self, $iface) = @_;

    my $network = $self->global()->modInstance('network');

    if (not $iface or not $network->ifaceExists($iface)) {
        throw EBox::Exceptions::DataNotFound('data' => __('Interface'),
                                             'value' => $iface);
    }

    my $model = $self->_getModel('RangeTable', $iface);
    my @ranges;
    for my $id (@{$model->ids()}) {
        my $row = $model->row($id);
        push (@ranges,
              { name    => $row->valueByName('name'),
                from    => $row->valueByName('from'),
                to      => $row->valueByName('to'),
                # TODO: Restore this when more than one config per interface is possible
                options => {}, #$self->_thinClientOptions($iface, $row->valueByName('name'))
               });
    }

    return \@ranges;
}

# Method: fixedAddresses
#
#   Return the list of fixed addreses
#
# Parameters:
#
#   iface - String interface name
#
#       readonly - Boolean indicate to get the information from
#                  readonly backend or current one
#                  *(Optional)* Default value: False
#
# Returns:
#
#   array ref - contating the fixed addresses in hash refereces.
#   Each hash holds the keys 'mac', 'ip' and 'name'
#
#       hash ref - if you set readOnly parameter, then it returns
#           two keys:
#              options - hash ref containing the PXE options

#              members - array ref containing the members of this
#                        objects as it does if readOnly is set to false
#
# Exceptions:
#
#   <EBox::Exceptions::DataNotFound> - Interface does not exist
#
#       <EBox::Exceptions::External> - Interface is not static
#
sub fixedAddresses
{
    my ($self,$iface, $readOnly) = @_;

    $readOnly = 0 unless ($readOnly);

    my $global  = EBox::Global->getInstance($readOnly);
    my $network = $global->modInstance('network');

    #if iface doesn't exists throw exception
    if (not $iface or not $network->ifaceExists($iface)) {
        throw EBox::Exceptions::DataNotFound(data => __('Interface'),
                                             value => $iface);
    }

    #if iface is not static, throw exception
    if ($network->ifaceMethod($iface) ne 'static') {
        throw EBox::Exceptions::External(__x("{iface} is not static",
                                             iface => $iface));
    }

    my $ifaceModel = $self->model('Interfaces');
    my $ifaceRow = $ifaceModel->findRow(iface => $iface);
    my $ifaceConf = $ifaceRow->subModel('configuration');
    my $model = $ifaceConf->componentByName('FixedAddressTable');
    my %addrs;
    my $objMod = $global->modInstance('objects');
    for my $id (@{$model->ids()}) {
        my $row   = $model->row($id);
        my $objId = $row->valueByName('object');
        my $mbs   = $objMod->objectMembers($objId);
        # TODO: Restore this when more than one config per interface is possible
        $addrs{$objId} = { options => {},#$self->_thinClientOptions($iface, $objId),
                           members => [] };

        foreach my $member (@{$mbs}) {
            # use only IP address member type
            if ($member->{type} ne 'ipaddr') {
                next;
            }

            # Filter out the ones which does not have a MAC address
            # and a mask of 32, it does not belong to the given
            # interface and member name is unique within the fixed
            # addresses realm
            if ( $self->_allowedMemberInFixedAddress($iface, $member, $objId, $readOnly) ) {
                push (@{$addrs{$objId}->{members}}, {
                    name => $member->{name},
                    ip   => $member->{ip},
                    mac  => $member->{macaddr},
                });
            }
        }
    }

    if ( $readOnly ) {
        # The returned value is grouped by object id
        return \%addrs;
    } else {
        my @mbs = ();
        foreach my $obj (values %addrs) {
            push(@mbs, @{$obj->{members}});
        }
        return \@mbs;
    }
}

# Group: Static or class methods

# Method: ConfDir
#
#      Get the DHCP configuration directory where to store the user
#      defined configuration files
#
# Parameters:
#
#      iface - String the interface which the user configuration file
#      is within
#
# Returns:
#
#      String - the configuration path
#
sub ConfDir
{
    my ($class, $iface) = @_;

    # Create directory unless it already exists
    unless ( -d CONF_DIR . $iface ) {
        mkdir ( CONF_DIR . $iface, 0755 );
    }
    my $pluginDir = CONF_DIR . $iface . '/' . PLUGIN_CONF_SUBDIR;
    unless ( -d $pluginDir ) {
        mkdir ( $pluginDir, 0755 );
    }
    return CONF_DIR . "$iface/";
}

# Method: TftpdRootDir
#
#      Get the default Tftpd root directory to store the firmwares
#      uploaded by our users
#
# Returns:
#
#      String - the tftpd root directory path
#
sub TftpdRootDir
{
    my ($class) = @_;

    # Create directory unless it already exists
    unless ( -d TFTPD_CONF_DIR ) {
        mkdir ( TFTPD_CONF_DIR, 0755 );
    }
    return TFTPD_CONF_DIR;
}

# Method: PluginConfDir
#
#      Get the DHCP plugin configuration directory where to store the user
#      defined configuration files
#
# Parameters:
#
#      iface - String the interface which the user configuration file
#      is within
#
# Returns:
#
#      String - the configuration path
#
sub PluginConfDir
{
    my ($class, $iface) = @_;

    my $pluginDir = CONF_DIR . $iface . '/' . PLUGIN_CONF_SUBDIR;
    unless ( -d $pluginDir ) {
        mkdir ( $pluginDir, 0755 );
    }
    return $pluginDir;
}

# Method:  userConfDir
#
#  Returns:
#  path to the user configuration dir
sub userConfDir
{
  return CONF_DIR;
}

# Method: IncludeDir
#
#    Path to the directory to include custom configuration
#
# Returns:
#
#    String - the path to the directory
#
sub IncludeDir
{
    return INCLUDE_DIR;
}

# Group: Network observer implementations

# Method: ifaceMethodChanged
#
# Implements:
#
#    <EBox::NetworkObserver::ifaceMethodChanged>
#
# Returns:
#
#     true - if the old method is 'static' and there are configured
#     ranges or fixed addresses attached to this interface
#     false - otherwise
#
sub ifaceMethodChanged # (iface, old_method, new_method)
{
    my ($self, $iface, $old_method, $new_method) = @_;

    if ($old_method eq 'static'
          and $new_method ne 'static') {
        my $rangeModel = $self->_getModel('RangeTable', $iface);
        if ( defined ( $rangeModel )) {
            return 1 if ( $rangeModel->size() > 0);
        }
        my $fixedAddrModel = $self->_getModel('FixedAddressTable', $iface);
        if ( defined ( $fixedAddrModel )) {
            return 1 if ( $fixedAddrModel->size() > 0);
        }
    }

    return 0;
}

# Method: vifaceAdded
#
#
# Implements:
#
#   <EBox::NetworkObserver::vifaceAdded>
#
# Exceptions:
#
#  <EBox::Exceptions::External> - thrown *if*:
#
#   - New Virtual interface IP overlaps any configured range
#   - New Virtual interface IP is a fixed IP address
#
sub vifaceAdded # (iface, viface, address, netmask)
{
    my ( $self, $iface, $viface, $address, $netmask) = @_;

    my $net = $self->global()->modInstance('network');
    my $ip = new Net::IP($address);

    my @rangeModels = @{$self->_getAllModelInstances('RangeTable')};
    # Check that the new IP for the virtual interface isn't in any range
    foreach my $rangeModel (@rangeModels) {
        foreach my $id (@{$rangeModel->ids()}) {
            my $rangeRow = $rangeModel->row($id);
            my $from = $rangeRow->valueByName('from');
            my $to   = $rangeRow->valueByName('to');
            my $range = new Net::IP($from . ' - ' . $to);
            unless ( $ip->overlaps($range) == $IP_NO_OVERLAP ) {
                throw EBox::Exceptions::External(
                __x('The IP address of the virtual interface '
                        . 'you are trying to add is already used by the '
                        . "DHCP range '{range}' in the interface "
                        . "'{iface}'. Please, remove it before trying "
                        . 'to add a virtual interface using it.',
                        range => $rangeRow->valueByName('name'),
                        iface => $rangeModel->index()));
            }
        }

        my @fixedAddrModels = @{$self->_getAllModelInstances('FixedAddressTable')};
        # Check the new IP for the virtual interface is not a fixed address
        foreach my $model (@fixedAddrModels) {
            next unless ($model->size() > 0);
            my $iface = $model->index();
            foreach my $fixedAddr ( @{$self->fixedAddresses($iface, 0)} ) {
                my $fixedIP = new Net::IP($fixedAddr->{'ip'});
                unless ( $ip->overlaps($fixedIP) == $IP_NO_OVERLAP ) {
                    throw EBox::Exceptions::External(
                           __x('The IP address of the virtual interface '
                               . 'you are trying to add is already used by a '
                               . "DHCP fixed address from object member "
                               . "'{fixed}' in the "
                               . "interface '{iface}'. Please, remove it "
                               . 'before trying to add a virtual interface '
                               . 'using it.',
                               fixed => $fixedAddr->{'name'},
                               iface => $iface));

                }
            }
        }
    }
}

# Method:  vifaceDelete
#
# Implements:
#
#    <EBox::NetworkObserver::vifaceDelete>
#
# Returns:
#
#    true - if there are any configured range or fixed address for
#    this interface
#    false - otherwise
#
sub vifaceDelete # (iface, viface)
{
    my ($self, $iface, $viface) = @_;

    foreach my $modelName (qw(RangeTable FixedAddressTable Options)) {
        my $model = $self->_getModel($modelName, "$iface:$viface");
        my $nr = $model->size();
        if ( $nr > 0 ) {
            return 1;
        }
    }

    return 0;
}

# Method: staticIfaceAddressChanged
#
#       Return true *unless*:
#
#       - all ranges are still in the network
#       - new IP is not in any range
#       - all fixed addresses are still in the network
#       - new IP is not any fixed IP address
#
# Implements:
#
#       <EBox::NetworkObserver::staticIfaceAddressChanged>
#
sub staticIfaceAddressChanged # (iface, old_addr, old_mask, new_addr, new_mask)
{
    my ( $self, $iface, $old_addr, $old_mask, $new_addr, $new_mask) = @_;
#   my $nr = @{$self->ranges($iface)};
#   my $nf = @{$self->fixedAddresses($iface)};
#   if(($nr == 0) and ($nf == 0)){
#       return 0;
#   }

    my $ip = new Net::IP($new_addr);

    my $network = ip_network($new_addr, $new_mask);
    my $bits = bits_from_mask($new_mask);
    my $netIP = new Net::IP("$network/$bits");

    # Check ranges
    my $rangeModel = $self->_getModel('RangeTable', $iface);
    foreach my $id (@{$rangeModel->ids()}) {
        my $rangeRow = $rangeModel->row($id);
        my $range = new Net::IP($rangeRow->valueByName('from')
                                    . ' - ' .
                                $rangeRow->valueByName('to'));
        # Check the range is still in the network
        unless ($range->overlaps($netIP) == $IP_A_IN_B_OVERLAP){
            return 1;
        }
        # Check the new IP isn't in any range
        unless($ip->overlaps($range) == $IP_NO_OVERLAP ){
            return 1;
        }
    }

    my $fixedAddrs = $self->fixedAddresses($iface, 0);
    foreach my $fixedAddr (@{$fixedAddrs}) {
        my $fixedIP = new Net::IP( $fixedAddr->{'ip'} );
        # Check the fixed address is still in the network
        unless($fixedIP->overlaps($netIP) == $IP_A_IN_B_OVERLAP){
            return 1;
        }
        # Check the new IP isn't in any fixed address
        unless( $ip->overlaps($fixedIP) == $IP_NO_OVERLAP){
            return 1;
        }
    }

    return 0;
}

# Function: freeIface
#
#    Delete every single row from the models attached to this
#    interface
#
# Implements:
#
#    <EBox::NetworkObserver::freeIface>
#
#
sub freeIface #( self, iface )
{
    my ( $self, $iface ) = @_;
#   $self->delete_dir("$iface");
    $self->_removeDataModelsAttached($iface);

    my $net = $self->global()->modInstance('network');
    if ($net->ifaceMethod($iface) eq 'static') {
        $self->_checkStaticIfaces(-1);
    }
}

# Method: freeViface
#
#    Delete every single row from the models attached to this virtual
#    interface
#
# Implements:
#
#    <EBox::NetworkObserver::freeViface>
#
#
sub freeViface #( self, iface, viface )
{
    my ( $self, $iface, $viface ) = @_;
#   $self->delete_dir("$iface:$viface");
    $self->_removeDataModelsAttached("$iface:$viface");


#   my $net = $self->global()->modInstance('network');
#   if ($net->ifaceMethod($viface) eq 'static') {
    $self->_checkStaticIfaces(-1);
#   }
}

# Group: Private methods


# Impelment LogHelper interface
sub tableInfo
{
    my ($self) = @_;

    my $titles = { 'timestamp' => __('Date'),
        'interface' => __('Interface'),
        'mac' => __('MAC address'),
        'ip' => __('IP'),
        'event' => __('Event')
    };
    my @order = ('timestamp', 'ip', 'mac', 'interface', 'event');
    my $events = {'leased' => __('Leased'), 'released' => __('Released') };

    return [{
        'name' => __('DHCP'),
        'tablename' => 'leases',
        'titles' => $titles,
        'order' => \@order,
        'timecol' => 'timestamp',
        'filter' => ['interface', 'mac', 'ip'],
        'types' => { 'ip' => 'IPAddr', 'mac' => 'MACAddr' },
        'events' => $events,
        'eventcol' => 'event',
    }];
}

sub logHelper
{
    my $self = shift;

    return (new EBox::DHCPLogHelper);
}

sub _leaseIDFromIP
{
    my ($ip) = @_;
    my $id = 'a';
    #force every byte to use 3 digits to make sorting trivial
    my @bytes = split('\.', $ip);
    for my $byte (@bytes) {
        $id .= sprintf("%03d", $byte);
    }
    return $id;
}

sub _dhcpLeases
{
    my ($self) = @_;

    my @stats = stat LEASEFILE;
    @stats or
           return {};
    my $mtime = $stats[9];
    my $refresh = 0;
    if (defined $self->{leases} and (defined $self->{leasesMTime})) {
        $refresh = $mtime ne $self->{leasesMTime};
    } else {
        $refresh = 1;
    }

    if ($refresh) {
        $self->{'leases'} = {};

        my $leases;
        try {
            $leases = Text::DHCPLeases->new(file => LEASEFILE);
        } otherwise {
           my $ex = shift;
           EBox::error('Error parsing DHCP leases file (' . LEASEFILE . "): $ex");
        };

        if (not $leases) {
            return $self->{'leases'};
        }

        foreach my $lease ($leases->get_objects()) {
            my $id = _leaseIDFromIP($lease->ip_address());
            $self->{'leases'}->{$id} = $lease;
        }
        $self->{leasesMTime} = $mtime;
    }
    return $self->{'leases'};
}

sub _leaseFromIP
{
    my ($self, $ip) = @_;

    my $leases = $self->_dhcpLeases();
    my $id = _leaseIDFromIP($ip);
    return $leases->{$id};
}

sub dhcpLeasesWidget
{
    my ($self, $widget) = @_;
    my $section = new EBox::Dashboard::Section('dhcpleases');
    $widget->add($section);
    my $titles = [__('IP address'),__('MAC address'), __('Host name')];

    my $leases = $self->_dhcpLeases();

    my $ids = [];
    my $rows = {};
    foreach my $id (sort keys (%{$leases})) {
        my $lease = $leases->{$id};
        if($lease->binding_state() eq 'active') {
            my $hostname = $lease->client_hostname();
            $hostname =~ s/"//g;
            push(@{$ids}, $id);
            $rows->{$id} = [$lease->ip_address(),$lease->mac_address(),
                            $hostname];
        }
    }

    $section->add(new EBox::Dashboard::List(undef, $titles, $ids, $rows));
}

### Method: widgets
#
#   Overrides <EBox::Module::Base::widgets>
#
sub widgets
{
    return {
        'dhcpleases' => {
            'title' => __("DHCP leases"),
            'widget' => \&dhcpLeasesWidget,
            'order' => 5,
            'default' => 1
        }
    };
}

# Group: Private methods

# Method: _setDHCPConf
#
#     Updates the dhcpd.conf file
#
sub _setDHCPConf
{
    my ($self) = @_;

    # Write general configuration
    my $net = $self->global()->modInstance('network');
    my $staticRoutes_r =  $self->staticRoutes();

    my $ifacesInfo = $self->_ifacesInfo($staticRoutes_r);
    my @params = ();
    push @params, ('dnsone' => $net->nameserverOne());
    push @params, ('dnstwo' => $net->nameserverTwo());
    push @params, ('thinClientOption' =>
                   $self->_areThereThinClientOptions($ifacesInfo));
    push @params, ('ifaces' => $ifacesInfo);
    push @params, ('real_ifaces' => $self->_realIfaces());
    my $dynamicDNSEnabled = $self->_dynamicDNSEnabled($ifacesInfo);
    if ( $dynamicDNSEnabled ) {
        push @params, ('dynamicDNSEnabled' => $dynamicDNSEnabled);
        push @params, ('keysFile' => $self->_keysFile());
        EBox::Sudo::root('adduser dhcpd bind');
    }
    push(@params, ('pidFile' => PIDFILE));

    $self->writeConfFile(DHCPCONFFILE, "dhcp/dhcpd.conf.mas", \@params);

}

# Method: _setTFTPDConf
#
#     Set the proper files on the TFTPD root dir
#
sub _setTFTPDConf
{
}

# Method: _ifacesInfo
#
#      Return a well structure to configure dhcp3-server using the
#      data installed in the module as well as the static routes
#      provided by <EBox::DHCP::StaticRouteProvider> modules
#
# Parameters:
#
#      staticRouters - hash ref containing those static routes to add
#      to a network which acts as key and the routes as value.
#
# Returns:
#
#      hash ref - an structure storing the required information for
#      dhcpd configuration
#
sub _ifacesInfo
{
    my ($self, $staticRoutes_r) = @_;

    my $roGlobal = EBox::Global->getInstance('readonly');
    my $net = $roGlobal->modInstance('network');
    my $ifaces = $net->allIfaces();

    my %iflist;
    foreach my $iface (@{$ifaces}) {
        if ($net->ifaceMethod($iface) eq 'static') {
            my $address = $net->ifaceAddress($iface);
            my $netmask = $net->ifaceNetmask($iface);
            my $network = ip_network($address, $netmask);

            $iflist{$iface}->{'net'} = $network;
            $iflist{$iface}->{'address'} = $address;
            $iflist{$iface}->{'netmask'} = $netmask;
            $iflist{$iface}->{'ranges'} = $self->ranges($iface);
            $iflist{$iface}->{'fixed'} = $self->fixedAddresses($iface, 'readonly');

            # look if we have static routes for this network
            my $netWithMask = EBox::NetWrappers::to_network_with_mask($network, $netmask);
            if (exists $staticRoutes_r->{$netWithMask}) {
                $iflist{$iface}->{'staticRoutes'} =
                    $staticRoutes_r->{$netWithMask};
            }

            my $gateway = $self->defaultGateway($iface);
            if (defined ($gateway)) {
                if ($gateway) {
                    $iflist{$iface}->{'gateway'} = $gateway;
                }
            } else {
                $iflist{$iface}->{'gateway'} = $address;
            }
            my $search = $self->searchDomain($iface);
            $iflist{$iface}->{'search'} = $search;
            my $nameserver1 = $self->nameserver($iface,1);
            if (defined($nameserver1) and $nameserver1 ne "") {
                $iflist{$iface}->{'nameserver1'} = $nameserver1;
            }
            my $nameserver2 = $self->nameserver($iface,2);
            if (defined($nameserver2) and $nameserver2 ne "") {
                $iflist{$iface}->{'nameserver2'} = $nameserver2;
            }
            # NTP option
            my $ntpServer = $self->ntpServer($iface);
            if ( defined($ntpServer) and $ntpServer ne "") {
                $iflist{$iface}->{'ntpServer'} = $ntpServer;
            }
            # WINS/Netbios server option
            my $winsServer = $self->winsServer($iface);
            if ( defined($winsServer) and $winsServer ne "") {
                $iflist{$iface}->{'winsServer'} = $winsServer;
            }
            # Leased times
            my $defaultLeasedTime = $self->_leasedTime('default', $iface);
            if (defined($defaultLeasedTime)) {
                $iflist{$iface}->{'defaultLeasedTime'} = $defaultLeasedTime;
            }
            my $maxLeasedTime = $self->_leasedTime('max', $iface);
            if (defined($maxLeasedTime)) {
                $iflist{$iface}->{'maxLeasedTime'} = $maxLeasedTime;
            }

            # Dynamic DNS options
            my $dynamicDomain = $self->_dynamicDNS('dynamic', $iface);
            if (defined($dynamicDomain)) {
                $iflist{$iface}->{'dynamicDomain'} = $dynamicDomain;
                $iflist{$iface}->{'staticDomain'}  = $self->_dynamicDNS('static', $iface);
                $iflist{$iface}->{'reverseZones'}  = $self->_reverseZones($iface);
            }

            # TODO: Remove this when more than one config per interface is possible
            $iflist{$iface}->{'options'}  = $self->_thinClientOptions($iface);
        }
    }

    return \%iflist;
}

# Method: _realIfaces
#
#    Get those interfaces which are real static ones containing the
#    virtual interfaces names which contain the real static interface
#
# Returns:
#
#    hash ref - containing interface name as key and an array ref
#    containing the virtual interface names as value
#
sub _realIfaces
{
    my ($self) = @_;
    my $net = $self->global()->modInstance('network');

    my $real_ifaces = $net->ifaces();
    my %realifs;
    foreach my $iface (@{$real_ifaces}) {
        if ($net->ifaceMethod($iface) eq 'static') {
            $realifs{$iface} = $net->vifaceNames($iface);
        }

    }

    return \%realifs;
}

# Method: _areThereThinClientOptions
#
#    Check if there are thin client options in order to allow DHCP
#    server acting as a boot server by setting these options on the
#    configuration file
#
# Parameters:
#
#    ifacesInfo - hash ref every static interface is the key and the
#    value contains every single parameter required to be written on
#    the configuration file
#
# Returns:
#
#    Boolean - true if there are thin client options in at least one
#    iface, false otherwise
#
sub _areThereThinClientOptions
{
    my ($self, $ifacesInfo) = @_;

# TODO: Restore this when more than one config per interface is possible
#     foreach my $ifaceInfo (values %{$ifacesInfo}) {
#         foreach my $range (@{$ifaceInfo->{ranges}}) {
#             if ( values %{$range->{options}} > 0 ) {
#                 return 1;
#             }
#         }
#         foreach my $objFixed (values %{$ifaceInfo->{fixed}}) {
#             if ( values %{$objFixed->{options}} > 0 ) {
#                 return 1;
#             }
#         }
#     }
    foreach my $ifaceInfo (values %{$ifacesInfo}) {
        if ( values %{$ifaceInfo->{options}} > 0 ) {
            return 1;
        }
    }
    return 0;
}

# Method: _leasedTime
#
#    Get the leased time (default or maximum) in seconds if any
#
sub _leasedTime # (which, iface)
{
    my ($self, $which, $iface) = @_;

    my $advOptionsModel = $self->_getModel('LeaseTimes', $iface);

    my $fieldName = $which . '_leased_time';
    return $advOptionsModel->row()->valueByName($fieldName);
}

# Method: _thinClientOptions
#
#    Get the thin client options
#
sub _thinClientOptions # (iface, element)
{
    my ($self, $iface, $element) = @_;

    my $thinClientModel = $self->_getModel('ThinClientOptions', $iface);

    my $ret = {};
# TODO: Restore this when more than one config per interface is possible
#    my $row = $thinClientModel->findValue(hosts => $element);
#    if ( defined($row) ) {
    if ($thinClientModel->row()->valueByName('nextServer') ne 'none') {
        $ret->{nextServerIsZentyal} = $thinClientModel->nextServerIsZentyal();#$row->id());
        $ret->{nextServer} = $thinClientModel->nextServer();#$row->id());
        $ret->{filename}   = $thinClientModel->remoteFilename();#$row->id());
        $ret->{architecture} = $thinClientModel->architecture();#$row->id());
        $ret->{fat} = $thinClientModel->fat();#$row->id());
    }
    return $ret;

}

# Method: _dynamicDNS
#
#    Get the domains to be updated by DHCP server (dynamic or statics)
#
# Returns:
#
#    undef - if the dynamic DNS feature is not enabled
#
sub _dynamicDNS # (which, iface)
{
    my ($self, $which, $iface) = @_;

    return undef unless (EBox::Global->modExists('dns'));

    my $dynamicDNSModel = $self->_getModel('DynamicDNS', $iface);

    my $dynamicOptionsRow = $dynamicDNSModel->row();
    if ($dynamicOptionsRow->valueByName('enabled')) {
        if ($which eq 'dynamic') {
            return $dynamicOptionsRow->printableValueByName('dynamic_domain');
        } elsif ($which eq 'static') {
            my $staticOption = $dynamicOptionsRow->elementByName('static_domain');
            if ($staticOption->selectedType() eq 'same') {
                return $dynamicOptionsRow->printableValueByName('dynamic_domain');
            } elsif ($staticOption->selectedType() eq 'custom') {
                return $dynamicOptionsRow->printableValueByName('static_domain');
            }
        }
    }
    return undef;
}

# Return the reverse zones for the given interface
sub _reverseZones
{
    my ($self, $iface) = @_;

    my $initRange = $self->initRange($iface);
    $initRange =~ s/1$/0/; # To make a network interface
    my $endRange  = $self->endRange($iface);

    my @revZones;
    my $ip = new Net::IP("$initRange - $endRange");
    do {
        my $rev = Net::IP->new($ip->ip())->reverse_ip();
        if ( defined($rev) ) {
            # It returns 0.netaddr.in-addr.arpa so we need to remove it
            # to make it compilant with bind zone definition
            $rev =~ s/^0\.//;
            push(@revZones, $rev);
        }
    } while ( $ip += 256 );

    return \@revZones;
}

# Return the key file to update DNS
sub _keysFile
{
    my ($self) = @_;

    my $gl = $self->global();
    if ( $gl->modExists('dns') ) {
        my $dnsMod = $gl->modInstance('dns');
        if ( $dnsMod->configured() ) {
            return $dnsMod->keysFile();
        }
    }
    return '';
}

# Return if the dynamic DNS feature is enabled for this DHCP server or
# not given the iface list info
sub _dynamicDNSEnabled # (ifacesInfo)
{
    my ($self, $ifacesInfo) = @_;

    return 0 unless ( EBox::Global->modExists('dns') );

    if ( defined($ifacesInfo) ) {
        my $nDynamicOptionsOn = grep { defined($ifacesInfo->{$_}->{'dynamicDomain'}) } keys %{$ifacesInfo};
        return ($nDynamicOptionsOn > 0);
    } else {
        my $net = $self->global()->modInstance('network');
        my $ifaces = $net->allIfaces();
        foreach my $iface (@{$ifaces}) {
            if ( $net->ifaceMethod($iface) eq 'static' ) {
                my $mod = $self->_getModel('DynamicDNS', $iface);
                if ( $mod->row()->valueByName('enabled') ) {
                    return 1;
                }
            }
        }
        return 0;
    }
}


# Returns those model instances attached to the given interface
sub _removeDataModelsAttached
{
    my ($self, $iface) = @_;
    my $ifacesModel = $self->model('Interfaces');
    my $rowId       = $ifacesModel->findId(iface => $iface);
    $ifacesModel->removeRow($rowId, 1);

#     # RangeTable/Options/FixedAddressTable
#     foreach my $modelName (qw(LeaseTimes ThinClientOptions Options RangeTable FixedAddressTable)) {
#         my $model = $self->_getModel($modelName, $iface);
#         if ( defined ( $model )) {
#             $model->removeAll(1);
#         }
#    }
}

# Model getter, check if there are any model with the given
# description, if not returns undef
sub _getModel
{
    my ($self, $modelName, $iface) = @_;
    my $row = $self->model('Interfaces')->findRow(iface => $iface);
    if (not $row) {
        throw EBox::Exceptions::Internal("Inexistent row for iface $iface")
    }

    my $configuration = $row->subModel('configuration');
    return $configuration->componentByName($modelName, 1);
}


sub _getAllModelInstances
{
    my ($self, $modelName) = @_;
    my @models;
    my $interfaces = $self->model('Interfaces');
    foreach my $id (@{ $interfaces->ids() }) {
        my $row = $interfaces->row($id);
        my $configuration = $row->subModel('configuration');
        my $model = $configuration->componentByName($modelName, 1);
        push @models, $model if $model;
    }

    return \@models;
}

# return the Dynamic DNS configutation row for the given iface
sub dynamicDNSDomains
{
    my ($self, $iface) = @_;
    my $ddModel= $self->_getModel('DynamicDNS', $iface);
    return $ddModel->row();
}


# Check there are enough static interfaces to have DHCP service enabled
sub _checkStaticIfaces
{
    my ($self, $adjustNumber) = @_;
    defined $adjustNumber or $adjustNumber = 0;

    my $nStaticIfaces = $self->_nStaticIfaces() + $adjustNumber;
    if ($nStaticIfaces == 0) {
        if ($self->isEnabled()) {
            $self->enableService(0);
            EBox::info('DHCP service was deactivated because there was not any static interface left');
        }
    }
}

# Return the current number of static interfaces
sub _nStaticIfaces
{
    my ($self) = @_;

    my $net = $self->global()->modInstance('network');
    my $ifaces = $net->allIfaces();
    my $staticIfaces = grep  { $net->ifaceMethod($_) eq 'static' } @{$ifaces};

    return $staticIfaces;
}

# Check if the given member is allowed to be a fixed address in the
# given interface
# It should match the following criteria:
#  * The member name must be a valid hostname
#    - If not, then the member name is become to a valid one
#  * Be a valid host IP address
#  * Have a valid MAC address
#  * The IP address must be in range available for the given interface
#  * It must be not used by in the range for the given interface
#  * It must be not the interface address
#  * The member name must be unique in the object realm
#  * The MAC address must be unique for subnet
#
sub _allowedMemberInFixedAddress
{
    my ($self, $iface, $member, $objId, $readOnly) = @_;

    unless (EBox::Validate::checkDomainName($member->{'name'})) {
        $member->{'name'} = lc($member->{'name'});
        $member->{'name'} =~ s/[^a-z0-9\-]/-/g;
    }

    if ($member->{mask} != 32 or (not defined($member->{macaddr}))) {
        return 0;
    }

    my $memberIP = new Net::IP($member->{ip});
    my $gl       = EBox::Global->getInstance($readOnly);
    my $net      = $gl->modInstance('network');
    my $objs     = $gl->modInstance('objects');
    my $netIP    = new Net::IP($self->initRange($iface)
                               . '-' . $self->endRange($iface));

    # Check if the IP address is within the network
    unless ($memberIP->overlaps($netIP) == $IP_A_IN_B_OVERLAP) {
        # The IP address from the member is not in the network
        EBox::debug('IP address ' . $memberIP->print() . ' is not in the '
                    . 'network ' . $netIP->print());
        return 0;
    }

    # Check the IP address is not the interface address
    my $ifaceIP = new Net::IP($net->ifaceAddress($iface));
    unless ( $memberIP->overlaps($ifaceIP) == $IP_NO_OVERLAP ) {
        # The IP address is the interface IP address
        EBox::debug('IP address ' . $memberIP->print() . " is the $iface interface address");
        return 0;
    }

    # Check the member IP address is not within any given range by
    # RangeTable model
    my $rangeModel = $self->_getModel('RangeTable', $iface);
    foreach my $id (@{$rangeModel->ids()}) {
        my $rangeRow = $rangeModel->row($id);
        my $from     = $rangeRow->valueByName('from');
        my $to       = $rangeRow->valueByName('to');
        my $range    = new Net::IP( $from . '-' . $to);
        unless ( $memberIP->overlaps($range) == $IP_NO_OVERLAP ) {
            # The IP address is in the range
            EBox::debug('IP address ' . $memberIP->print() . ' is in range '
                        . $rangeRow->valueByName('name') . ": $from-$to");
            return 0;
        }
    }

    # Check the given member is unique within the object realm
    my $network = $self->global()->modInstance('network');
    my @otherDHCPIfaces = grep {
        my $other = $_;
        ($network->ifaceMethod($other) eq 'static') and
        ($other ne $iface)
    } @{ $network->InternalIfaces()  };
    my @fixedAddressTables = map {
        $self->_getModel('FixedAddressTable', $_)
    } @otherDHCPIfaces;

    foreach my $model (@fixedAddressTables) {
        my $ids = $model->ids();
        foreach my $id (@{$ids}) {
            my $row = $model->row($id);
            my $otherObjId = $row->valueByName('object');
            my $mbs = $objs->objectMembers($otherObjId);
            next if ( $otherObjId eq $objId); # If they are the same object

            # Check for the same member name in other object
            my @matches = grep { $_->{name} eq $member->{name} } @{$mbs};
            foreach my $match (@matches) {
                next unless ( $match->{mask} == 32 and defined($match->{macaddr}));
                EBox::warn('IP address ' . $memberIP->print() . ' not added '
                           . 'because there are two members with the same name '
                           . $member->{name} . ' in other fixed address table');
                return 0;
            }
        }
    }

    # Check for the same MAC address
    my $fixedAddrModel = $self->_getModel('FixedAddressTable', $iface);
    my $ids = $fixedAddrModel->ids();
    foreach my $id ( @{$ids} ) {
        my $row = $fixedAddrModel->row($id);
        my $otherObjId = $row->valueByName('object');
        next if ( $otherObjId eq $objId ); # Check done by unique MAC address property
        my $mbs = $objs->objectMembers($otherObjId);
        my @matches = grep {
            defined($_->{macaddr})
            and ($_->{macaddr} eq $member->{macaddr})
            and ($_->{name} ne $member->{name})
        } @{$mbs};
        if ( @matches > 0 ) {
            EBox::warn('MAC address ' . $member->{macaddr} . ' is being '
                       . 'used by ' . $member->{name} . ' and, at least, '
                       . $matches[0]->{name});
            return 0;
        }
    }

    return 1;
}

# Method: gatewayDelete
#
#  Overrides:
#    EBox::NetworkObserver::gatewayDelete
sub gatewayDelete
{
    my ($self, $gwName) = @_;

    my $global = EBox::Global->getInstance($self->{ro});
    my $network = $global->modInstance('network');
    foreach my $iface (@{$network->allIfaces()}) {
        next unless ($network->ifaceMethod($iface) eq 'static');
        my $options = $self->_getModel('Options', $iface);
        my $optionsGwName = $options->gatewayName();
        if ($gwName eq $optionsGwName) {
            return 1;
        }
    }

    return 0;
}

1;