summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--src/tests/dejagnu/config/default.exp17
1 files changed, 0 insertions, 17 deletions
diff --git a/src/tests/dejagnu/config/default.exp b/src/tests/dejagnu/config/default.exp
index aa53f333f3..018dadd28f 100644
--- a/src/tests/dejagnu/config/default.exp
+++ b/src/tests/dejagnu/config/default.exp
@@ -409,7 +409,6 @@ if ![info exists KEY] {
# We can't use them now because we don't know the right KEY.
# krb5.conf might change if running tests on another host
file delete $tmppwd/krb5.conf $tmppwd/kdc.conf $tmppwd/slave.conf \
- $tmppwd/krb.realms $tmppwd/krb.conf \
$tmppwd/krb5.client.conf $tmppwd/krb5.server.conf \
$tmppwd/krb5.kdc.conf $tmppwd/krb5.slave.conf
@@ -969,22 +968,6 @@ proc setup_kerberos_files { } {
close $aclfile
}
- # Create krb.conf file
- if ![file exists $tmppwd/krb.conf] {
- set conffile [open $tmppwd/krb.conf w]
- puts $conffile "$REALMNAME"
- puts $conffile "$REALMNAME $hostname:[expr 1 + $portbase] admin server"
- close $conffile
- }
-
- # Create krb.realms file
- if ![file exists $tmppwd/krb.realms] {
- set conffile [open $tmppwd/krb.realms w]
- puts $conffile ".[string toupper $domain] $REALMNAME"
- puts $conffile "[string toupper $domain]. $REALMNAME"
- close $conffile
- }
-
# Create dictfile file.
if ![file exists $tmppwd/dictfile] {
set dictfile [open $tmppwd/dictfile w]
58'>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
# Authors: Simo Sorce <ssorce@redhat.com>
#
# Copyright (C) 2007  Red Hat
# see file 'COPYING' for use and warranty information
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# 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, see <http://www.gnu.org/licenses/>.
#

from __future__ import absolute_import
from __future__ import print_function

import logging
import tempfile
import os
import pwd
import netaddr
import re
import sys
import time

import dns.resolver
import ldap
import six

from ipaserver.dns_data_management import (
    IPASystemRecords,
    IPADomainIsNotManagedByIPAError,
)
from ipaserver.install import installutils
from ipaserver.install import service
from ipaserver.install import sysupgrade
from ipapython import ipautil
from ipapython import dnsutil
from ipapython.dnsutil import DNSName
from ipapython.dn import DN
from ipapython.admintool import ScriptError
import ipalib
from ipalib import api, errors
from ipalib.constants import IPA_CA_RECORD
from ipaplatform import services
from ipaplatform.constants import constants
from ipaplatform.paths import paths
from ipalib.util import (validate_zonemgr_str, normalize_zonemgr,
                         get_dns_forward_zone_update_policy,
                         get_dns_reverse_zone_update_policy,
                         normalize_zone, get_reverse_zone_default,
                         zone_is_reverse, validate_dnssec_global_forwarder,
                         DNSSECSignatureMissingError, EDNS0UnsupportedError,
                         UnresolvableRecordError)

if six.PY3:
    unicode = str

logger = logging.getLogger(__name__)

NAMED_CONF = paths.NAMED_CONF
RESOLV_CONF = paths.RESOLV_CONF

named_conf_section_ipa_start_re = re.compile('\s*dyndb\s+"ipa"\s+"[^"]+"\s+{')
named_conf_section_options_start_re = re.compile('\s*options\s+{')
named_conf_section_end_re = re.compile('};')
named_conf_arg_ipa_re = re.compile(
    r'(?P<indent>\s*)(?P<name>\S+)\s"(?P<value>[^"]+)";')
named_conf_arg_options_re = re.compile(
    r'(?P<indent>\s*)(?P<name>\S+)\s+"(?P<value>[^"]+)"\s*;')
named_conf_arg_ipa_template = "%(indent)s%(name)s \"%(value)s\";\n"
named_conf_arg_options_template = "%(indent)s%(name)s \"%(value)s\";\n"
# non string args for options section
named_conf_arg_options_re_nonstr = re.compile(
    r'(?P<indent>\s*)(?P<name>\S+)\s+(?P<value>[^"]+)\s*;')
named_conf_arg_options_template_nonstr = "%(indent)s%(name)s %(value)s;\n"
# include directive
named_conf_include_re = re.compile(r'\s*include\s+"(?P<path>)"\s*;')
named_conf_include_template = "include \"%(path)s\";\n"


def create_reverse():
    return ipautil.user_input(
        "Do you want to search for missing reverse zones?",
        True
    )

def named_conf_exists():
    try:
        with open(NAMED_CONF, 'r') as named_fd:
            lines = named_fd.readlines()
    except IOError:
        return False
    for line in lines:
        if named_conf_section_ipa_start_re.match(line):
            return True
    return False

NAMED_SECTION_OPTIONS = "options"
NAMED_SECTION_IPA = "ipa"
def named_conf_get_directive(name, section=NAMED_SECTION_IPA, str_val=True):
    """Get a configuration option in bind-dyndb-ldap section of named.conf

    :str_val - set to True if directive value is string
        (only for NAMED_SECTION_OPTIONS)
    """
    if section == NAMED_SECTION_IPA:
        named_conf_section_start_re = named_conf_section_ipa_start_re
        named_conf_arg_re = named_conf_arg_ipa_re
    elif section == NAMED_SECTION_OPTIONS:
        named_conf_section_start_re = named_conf_section_options_start_re
        if str_val:
            named_conf_arg_re = named_conf_arg_options_re
        else:
            named_conf_arg_re = named_conf_arg_options_re_nonstr
    else:
        raise NotImplementedError('Section "%s" is not supported' % section)

    with open(NAMED_CONF, 'r') as f:
        target_section = False
        for line in f:
            if named_conf_section_start_re.match(line):
                target_section = True
                continue
            if named_conf_section_end_re.match(line):
                if target_section:
                    break

            if target_section:
                match = named_conf_arg_re.match(line)

                if match and name == match.group('name'):
                    return match.group('value')

def named_conf_set_directive(name, value, section=NAMED_SECTION_IPA,
                             str_val=True):
    """
    Set configuration option in bind-dyndb-ldap section of named.conf.

    When the configuration option with given name does not exist, it
    is added at the end of ipa section in named.conf.

    If the value is set to None, the configuration option is removed
    from named.conf.

    :str_val - set to True if directive value is string
        (only for NAMED_SECTION_OPTIONS)
    """
    new_lines = []

    if section == NAMED_SECTION_IPA:
        named_conf_section_start_re = named_conf_section_ipa_start_re
        named_conf_arg_re = named_conf_arg_ipa_re
        named_conf_arg_template = named_conf_arg_ipa_template
    elif section == NAMED_SECTION_OPTIONS:
        named_conf_section_start_re = named_conf_section_options_start_re
        if str_val:
            named_conf_arg_re = named_conf_arg_options_re
            named_conf_arg_template = named_conf_arg_options_template
        else:
            named_conf_arg_re = named_conf_arg_options_re_nonstr
            named_conf_arg_template = named_conf_arg_options_template_nonstr
    else:
        raise NotImplementedError('Section "%s" is not supported' % section)

    with open(NAMED_CONF, 'r') as f:
        target_section = False
        matched = False
        last_indent = "\t"
        for line in f:
            if named_conf_section_start_re.match(line):
                target_section = True
            if named_conf_section_end_re.match(line):
                if target_section and not matched and \
                        value is not None:
                    # create a new conf
                    new_conf = named_conf_arg_template \
                            % dict(indent=last_indent,
                                   name=name,
                                   value=value)
                    new_lines.append(new_conf)
                target_section = False

            if target_section and not matched:
                match = named_conf_arg_re.match(line)

                if match:
                    last_indent = match.group('indent')
                    if name == match.group('name'):
                        matched = True
                        if value is not None:
                            if not isinstance(value, six.string_types):
                                value = str(value)
                            new_conf = named_conf_arg_template \
                                    % dict(indent=last_indent,
                                           name=name,
                                           value=value)
                            new_lines.append(new_conf)
                        continue
            new_lines.append(line)

    # write new configuration
    with open(NAMED_CONF, 'w') as f:
        f.write("".join(new_lines))

def named_conf_include_exists(path):
    """
    Check if include exists in named.conf
    :param path: path in include directive
    :return: True if include exists, else False
    """
    with open(NAMED_CONF, 'r') as f:
        for line in f:
            match = named_conf_include_re.match(line)
            if match and path == match.group('path'):
                return True

    return False

def named_conf_add_include(path):
    """
    append include at the end of file
    :param path: path to be insert to include directive
    """
    with open(NAMED_CONF, 'a') as f:
        f.write(named_conf_include_template % {'path': path})


def dns_container_exists(suffix):
    """
    Test whether the dns container exists.
    """
    assert isinstance(suffix, DN)
    return api.Backend.ldap2.entry_exists(DN(('cn', 'dns'), suffix))


def dns_zone_exists(name, api=api):
    try:
        zone = api.Command.dnszone_show(unicode(name))
    except ipalib.errors.NotFound:
        return False

    if len(zone) == 0:
        return False
    else:
        return True

def get_reverse_record_name(zone, ip_address):
    ip = netaddr.IPAddress(ip_address)
    rev = '.' + normalize_zone(zone)
    fullrev = '.' + normalize_zone(ip.reverse_dns)

    if not fullrev.endswith(rev):
        raise ValueError("IP address does not match reverse zone")

    return fullrev[1:-len(rev)]

def verify_reverse_zone(zone, ip_address):
    try:
        get_reverse_record_name(zone, ip_address)
    except ValueError:
        return False

    return True

def find_reverse_zone(ip_address, api=api):
    ip = netaddr.IPAddress(ip_address)
    zone = normalize_zone(ip.reverse_dns)

    while len(zone) > 0:
        if dns_zone_exists(zone, api):
            return zone
        zone = zone.partition('.')[2]

    return None


def read_reverse_zone(default, ip_address, allow_zone_overlap=False):
    while True:
        zone = ipautil.user_input("Please specify the reverse zone name", default=default)
        if not zone:
            return None
        if not verify_reverse_zone(zone, ip_address):
            logger.error("Invalid reverse zone %s for IP address %s",
                         zone, ip_address)
            continue
        if not allow_zone_overlap:
            try:
                dnsutil.check_zone_overlap(zone, raise_on_error=False)
            except ValueError as e:
                logger.error("Reverse zone %s will not be used: %s",
                             zone, e)
                continue
        break

    return normalize_zone(zone)


def get_auto_reverse_zones(ip_addresses):
    auto_zones = []
    for ip in ip_addresses:
        if ipautil.reverse_record_exists(ip):
            # PTR exist there is no reason to create reverse zone
            logger.info("Reverse record for IP address %s already exists", ip)
            continue
        default_reverse = get_reverse_zone_default(ip)
        try:
            dnsutil.check_zone_overlap(default_reverse)
        except ValueError:
            logger.info("Reverse zone %s for IP address %s already exists",
                        default_reverse, ip)
            continue
        auto_zones.append((ip, default_reverse))
    return auto_zones

def add_zone(name, zonemgr=None, dns_backup=None, ns_hostname=None,
             update_policy=None, force=False, skip_overlap_check=False,
             api=api):

    # always normalize zones
    name = normalize_zone(name)

    if update_policy is None:
        if zone_is_reverse(name):
            update_policy = get_dns_reverse_zone_update_policy(api.env.realm, name)
        else:
            update_policy = get_dns_forward_zone_update_policy(api.env.realm)

    if zonemgr is None:
        zonemgr = 'hostmaster.%s' % name

    if ns_hostname:
        ns_hostname = normalize_zone(ns_hostname)
        ns_hostname = unicode(ns_hostname)

    try:
        api.Command.dnszone_add(unicode(name),
                                idnssoamname=ns_hostname,
                                idnssoarname=unicode(zonemgr),
                                idnsallowdynupdate=True,
                                idnsupdatepolicy=unicode(update_policy),
                                idnsallowquery=u'any',
                                idnsallowtransfer=u'none',
                                skip_overlap_check=skip_overlap_check,
                                force=force)
    except (errors.DuplicateEntry, errors.EmptyModlist):
        pass

def add_rr(zone, name, type, rdata, dns_backup=None, api=api, **kwargs):
    addkw = { '%srecord' % str(type.lower()) : unicode(rdata) }
    addkw.update(kwargs)
    try:
        api.Command.dnsrecord_add(unicode(zone), unicode(name), **addkw)
    except (errors.DuplicateEntry, errors.EmptyModlist):
        pass
    if dns_backup:
        dns_backup.add(zone, type, name, rdata)

def add_fwd_rr(zone, host, ip_address, api=api):
    addr = netaddr.IPAddress(ip_address)
    if addr.version == 4:
        add_rr(zone, host, "A", ip_address, None, api)
    elif addr.version == 6:
        add_rr(zone, host, "AAAA", ip_address, None, api)

def add_ptr_rr(zone, ip_address, fqdn, dns_backup=None, api=api):
    name = get_reverse_record_name(zone, ip_address)
    add_rr(zone, name, "PTR", normalize_zone(fqdn), dns_backup, api)


def add_ns_rr(zone, hostname, dns_backup=None, force=True, api=api):
    hostname = normalize_zone(hostname)
    add_rr(zone, "@", "NS", hostname, dns_backup=dns_backup,
           force=force, api=api)


def del_rr(zone, name, type, rdata, api=api):
    delkw = { '%srecord' % str(type.lower()) : unicode(rdata) }
    try:
        api.Command.dnsrecord_del(unicode(zone), unicode(name), **delkw)
    except (errors.NotFound, errors.AttrValueNotFound, errors.EmptyModlist):
        pass


def del_fwd_rr(zone, host, ip_address, api=api):
    addr = netaddr.IPAddress(ip_address)
    if addr.version == 4:
        del_rr(zone, host, "A", ip_address, api=api)
    elif addr.version == 6:
        del_rr(zone, host, "AAAA", ip_address, api=api)


def del_ns_rr(zone, name, rdata, api=api):
    del_rr(zone, name, 'NS', rdata, api=api)

def get_rr(zone, name, type, api=api):
    rectype = '%srecord' % unicode(type.lower())
    ret = api.Command.dnsrecord_find(unicode(zone), unicode(name))
    if ret['count'] > 0:
        for r in ret['result']:
            if rectype in r:
                return r[rectype]

    return []

def get_fwd_rr(zone, host, api=api):
    return [x for t in ("A", "AAAA") for x in get_rr(zone, host, t, api)]

def zonemgr_callback(option, opt_str, value, parser):
    """
    Properly validate and convert --zonemgr Option to IA5String
    """
    if value is not None:
        # validate the value first
        try:
            # IDNA support requires unicode
            encoding = getattr(sys.stdin, 'encoding', None)
            if encoding is None:
                encoding = 'utf-8'

            # value is of a string type in both py2 and py3
            if not isinstance(value, unicode):
                value = value.decode(encoding)

            validate_zonemgr_str(value)
        except ValueError as e:
            # FIXME we can do this in better way
            # https://fedorahosted.org/freeipa/ticket/4804
            # decode to proper stderr encoding
            stderr_encoding = getattr(sys.stderr, 'encoding', None)
            if stderr_encoding is None:
                stderr_encoding = 'utf-8'
            error = unicode(e).encode(stderr_encoding)
            parser.error(b"invalid zonemgr: " + error)

    parser.values.zonemgr = value


def check_reverse_zones(ip_addresses, reverse_zones, options, unattended,
                        search_reverse_zones=False):
    checked_reverse_zones = []

    if (not options.no_reverse and not reverse_zones
            and not options.auto_reverse):
        if unattended:
            options.no_reverse = True
        else:
            options.no_reverse = not create_reverse()

    # shortcut
    if options.no_reverse:
        return []

    # verify zones passed in options
    for rz in reverse_zones:
        # isn't the zone managed by someone else
        if not options.allow_zone_overlap:
            try:
                dnsutil.check_zone_overlap(rz)
            except ValueError as e:
                msg = "Reverse zone %s will not be used: %s" % (rz, e)
                if unattended:
                    raise ScriptError(msg)
                else:
                    logger.warning('%s', msg)
                continue
        checked_reverse_zones.append(normalize_zone(rz))

    # check that there is reverse zone for every IP
    ips_missing_reverse = []
    for ip in ip_addresses:
        if search_reverse_zones and find_reverse_zone(str(ip)):
            # reverse zone is already in LDAP
            continue
        for rz in checked_reverse_zones:
            if verify_reverse_zone(rz, ip):
                # reverse zone was entered by user
                break
        else:
            ips_missing_reverse.append(ip)

    # create reverse zone for IP addresses that does not have one
    for (ip, rz) in get_auto_reverse_zones(ips_missing_reverse):
        if options.auto_reverse:
            logger.info("Reverse zone %s will be created", rz)
            checked_reverse_zones.append(rz)
        elif unattended:
            logger.warning("Missing reverse record for IP address %s", ip)
        else:
            if ipautil.user_input("Do you want to create reverse zone for IP "
                                  "%s" % ip, True):
                rz = read_reverse_zone(rz, str(ip), options.allow_zone_overlap)
                checked_reverse_zones.append(rz)

    return checked_reverse_zones


def check_forwarders(dns_forwarders):
    print("Checking DNS forwarders, please wait ...")
    forwarders_dnssec_valid = True
    for forwarder in dns_forwarders:
        logger.debug("Checking DNS server: %s", forwarder)
        try:
            validate_dnssec_global_forwarder(forwarder)
        except DNSSECSignatureMissingError as e:
            forwarders_dnssec_valid = False
            logger.warning("DNS server %s does not support DNSSEC: %s",
                           forwarder, e)
            logger.warning("Please fix forwarder configuration to enable "
                           "DNSSEC support.\n"
                           "(For BIND 9 add directive \"dnssec-enable yes;\" "
                           "to \"options {}\")")
            print("DNS server %s: %s" % (forwarder, e))
            print("Please fix forwarder configuration to enable DNSSEC support.")
            print("(For BIND 9 add directive \"dnssec-enable yes;\" to \"options {}\")")
        except EDNS0UnsupportedError as e:
            forwarders_dnssec_valid = False
            logger.warning("DNS server %s does not support ENDS0 "
                           "(RFC 6891): %s", forwarder, e)
            logger.warning("Please fix forwarder configuration. "
                           "DNSSEC support cannot be enabled without EDNS0")
            print(("WARNING: DNS server %s does not support EDNS0 "
                   "(RFC 6891): %s" % (forwarder, e)))
        except UnresolvableRecordError as e:
            logger.error("DNS server %s: %s", forwarder, e)
            raise RuntimeError("DNS server %s: %s" % (forwarder, e))

    return forwarders_dnssec_valid


def remove_master_dns_records(hostname, realm):
    bind = BindInstance()
    bind.remove_master_dns_records(hostname, realm, realm.lower())
    bind.remove_server_ns_records(hostname)


def ensure_dnsserver_container_exists(ldap, api_instance, logger=logger):
    """
    Create cn=servers,cn=dns,$SUFFIX container. If logger is not None, emit a
    message that the container already exists when DuplicateEntry is raised
    """

    entry = ldap.make_entry(
        DN(api_instance.env.container_dnsservers, api_instance.env.basedn),
        {
            u'objectclass': [u'top', u'nsContainer'],
            u'cn': [u'servers']
        }
    )
    try:
        ldap.add_entry(entry)
    except errors.DuplicateEntry:
        logger.debug('cn=servers,cn=dns container already exists')


class DnsBackup(object):
    def __init__(self, service):
        self.service = service
        self.zones = {}

    def add(self, zone, record_type, host, rdata):
        """
        Backup a DNS record in the file store so it can later be removed.
        """
        if zone not in self.zones:
            zone_id = len(self.zones)
            self.zones[zone] = (zone_id, 0)
            self.service.backup_state("dns_zone_%s" % zone_id, zone)

        (zone_id, record_id) = self.zones[zone]
        self.service.backup_state("dns_record_%s_%s" % (zone_id, record_id),
                                  "%s %s %s" % (record_type, host, rdata))
        self.zones[zone] = (zone_id, record_id + 1)

    def clear_records(self, have_ldap):
        """
        Remove all records from the file store. If we are connected to
        ldap, we will also remove them there.
        """
        i = 0
        while True:
            zone = self.service.restore_state("dns_zone_%s" % i)
            if not zone:
                return

            j = 0
            while True:
                dns_record = self.service.restore_state("dns_record_%s_%s" % (i, j))
                if not dns_record:
                    break
                if have_ldap:
                    type, host, rdata = dns_record.split(" ", 2)
                    try:
                        delkw = { '%srecord' % str(type.lower()) : unicode(rdata) }
                        api.Command.dnsrecord_del(unicode(zone), unicode(host), **delkw)
                    except Exception:
                        pass
                j += 1

            i += 1


class BindInstance(service.Service):
    def __init__(self, fstore=None, api=api):
        super(BindInstance, self).__init__(
            "named",
            service_desc="DNS",
            fstore=fstore,
            api=api,
            service_user=constants.NAMED_USER,
            service_prefix=u'DNS',
            keytab=paths.NAMED_KEYTAB
        )
        self.dns_backup = DnsBackup(self)
        self.domain = None
        self.host = None
        self.ip_addresses = []
        self.forwarders = None
        self.sub_dict = None
        self.reverse_zones = []
        self.named_regular = services.service('named-regular', api)

    suffix = ipautil.dn_attribute_property('_suffix')

    def setup(self, fqdn, ip_addresses, realm_name, domain_name, forwarders,
              forward_policy, reverse_zones,
              named_user=constants.NAMED_USER, zonemgr=None,
              no_dnssec_validation=False):
        self.service_user = named_user
        self.fqdn = fqdn
        self.ip_addresses = ip_addresses
        self.realm = realm_name
        self.domain = domain_name
        self.forwarders = forwarders
        self.forward_policy = forward_policy
        self.host = fqdn.split(".")[0]
        self.suffix = ipautil.realm_to_suffix(self.realm)
        self.reverse_zones = reverse_zones
        self.no_dnssec_validation=no_dnssec_validation

        if not zonemgr:
            self.zonemgr = 'hostmaster.%s' % normalize_zone(self.domain)
        else:
            self.zonemgr = normalize_zonemgr(zonemgr)

        self.first_instance = not dns_container_exists(self.suffix)

        self.__setup_sub_dict()

    @property
    def host_domain(self):
        return self.fqdn.split(".", 1)[1]

    @property
    def host_in_rr(self):
        # when a host is not in a default domain, it needs to be referred
        # with FQDN and not in a domain-relative host name
        if not self.host_in_default_domain():
            return normalize_zone(self.fqdn)
        return self.host

    def host_in_default_domain(self):
        return normalize_zone(self.host_domain) == normalize_zone(self.domain)

    def create_file_with_system_records(self):
        system_records = IPASystemRecords(self.api)
        text = u'\n'.join(
            IPASystemRecords.records_list_from_zone(
                system_records.get_base_records()
            )
        )
        with tempfile.NamedTemporaryFile(
                mode="w", prefix="ipa.system.records.",
                suffix=".db", delete=False
        ) as f:
            f.write(text)
            print("Please add records in this file to your DNS system:",
                  f.name)

    def create_instance(self):

        try:
            self.stop()
        except Exception:
            pass