summaryrefslogtreecommitdiffstats
path: root/ipalib/plugins/dns.py
blob: 33856c2762986a6f56189feb59e2e4bfd11b05ee (plain)
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
# Authors:
#   Martin Kosek <mkosek@redhat.com>
#   Pavel Zuna <pzuna@redhat.com>
#
# Copyright (C) 2010  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/>.

import netaddr
import time
import re

from ipalib.request import context
from ipalib import api, errors, output
from ipalib import Command
from ipalib.parameters import Flag, Bool, Int, Float, Str, StrEnum
from ipalib.plugins.baseldap import *
from ipalib import _, ngettext
from ipalib.util import validate_zonemgr, normalize_zonemgr, validate_hostname
from ipapython import dnsclient
from ipapython.ipautil import valid_ip
from ldap import explode_dn

__doc__ = _("""
Domain Name System (DNS)

Manage DNS zone and resource records.

EXAMPLES:

 Add new zone:
   ipa dnszone-add example.com --name-server nameserver.example.com
                               --admin-email admin@example.com

 Modify the zone to allow dynamic updates for hosts own records in realm EXAMPLE.COM:
   ipa dnszone-mod example.com --dynamic-update=TRUE \\
        --update-policy="grant EXAMPLE.COM krb5-self * A; grant EXAMPLE.COM krb5-self * AAAA;"

 Add new reverse zone specified by network IP address:
   ipa dnszone-add --name-from-ip 80.142.15.0/24
                   --name-server nameserver.example.com

 Add second nameserver for example.com:
   ipa dnsrecord-add example.com @ --ns-rec nameserver2.example.com

 Add a mail server for example.com:
   ipa dnsrecord-add example.com @ --mx-rec="10 mail2"

 Delete previously added nameserver from example.com:
   ipa dnsrecord-del example.com @ --ns-rec nameserver2.example.com

 Add LOC record for example.com:
   ipa dnsrecord-add example.com @ --loc-rec "49 11 42.4 N 16 36 29.6 E 227.64m"

 Add new A record for www.example.com: (random IP)
   ipa dnsrecord-add example.com www --a-rec 80.142.15.2

 Add new PTR record for www.example.com
   ipa dnsrecord-add 15.142.80.in-addr.arpa. 2 --ptr-rec www.example.com.

 Add new SRV records for LDAP servers. Three quarters of the requests
 should go to fast.example.com, one quarter to slow.example.com. If neither
 is available, switch to backup.example.com.
   ipa dnsrecord-add example.com _ldap._tcp --srv-rec="0 3 389 fast.example.com"
   ipa dnsrecord-add example.com _ldap._tcp --srv-rec="0 1 389 slow.example.com"
   ipa dnsrecord-add example.com _ldap._tcp --srv-rec="1 1 389 backup.example.com"

 When dnsrecord-add command is executed with no option to add a specific record
 an interactive mode is started. The mode interactively prompts for the most
 typical record types for the respective zone:
   ipa dnsrecord-add example.com www
   [A record]: 1.2.3.4,11.22.33.44      (2 interactively entered random IPs)
   [AAAA record]:                       (no AAAA address entered)
     Record name: www
     A record: 1.2.3.4, 11.22.33.44

 The interactive mode can also be used for deleting the DNS records:
   ipa dnsrecord-del example.com www
   No option to delete specific record provided.
   Delete all? Yes/No (default No):     (do not delete all records)
   Current DNS record contents:

   A record: 1.2.3.4, 11.22.33.44

   Delete A record '1.2.3.4'? Yes/No (default No):
   Delete A record '11.22.33.44'? Yes/No (default No): y
     Record name: www
     A record: 1.2.3.4                  (A record 11.22.33.44 has been deleted)

 Show zone example.com:
   ipa dnszone-show example.com

 Find zone with "example" in its domain name:
   ipa dnszone-find example

 Find records for resources with "www" in their name in zone example.com:
   ipa dnsrecord-find example.com www

 Find A records with value 10.10.0.1 in zone example.com
   ipa dnsrecord-find example.com --a-rec 10.10.0.1

 Show records for resource www in zone example.com
   ipa dnsrecord-show example.com www

 Delete zone example.com with all resource records:
   ipa dnszone-del example.com

 Resolve a host name to see if it exists (will add default IPA domain
 if one is not included):
   ipa dns-resolve www.example.com
   ipa dns-resolve www
""")

# supported resource record types
_record_types = (
    u'A', u'AAAA', u'A6', u'AFSDB', u'APL', u'CERT', u'CNAME', u'DHCID', u'DLV',
    u'DNAME', u'DNSKEY', u'DS', u'HIP', u'IPSECKEY', u'KEY', u'KX', u'LOC',
    u'MX', u'NAPTR', u'NS', u'NSEC', u'NSEC3', u'NSEC3PARAM', u'PTR',
    u'RRSIG', u'RP', u'SIG', u'SPF', u'SRV', u'SSHFP', u'TA', u'TKEY',
    u'TSIG', u'TXT',
)

# DNS zone record identificator
_dns_zone_record = u'@'

# most used record types, always ask for those in interactive prompt
_top_record_types = ('A', 'AAAA', )
_rev_top_record_types = ('PTR', )
_zone_top_record_types = ('NS', 'MX', 'LOC', )

# attributes derived from record types
_record_attributes = [str('%srecord' % t.lower()) for t in _record_types]

# supported DNS classes, IN = internet, rest is almost never used
_record_classes = (u'IN', u'CS', u'CH', u'HS')

def _rname_validator(ugettext, zonemgr):
    try:
        validate_zonemgr(zonemgr)
    except ValueError, e:
        return unicode(e)
    return None

def _create_zone_serial(**kwargs):
    """Generate serial number for zones."""
    return int('%s01' % time.strftime('%Y%d%m'))

def _reverse_zone_name(netstr):
    net = netaddr.IPNetwork(netstr)
    items = net.ip.reverse_dns.split('.')
    if net.version == 4:
        return u'.'.join(items[4 - net.prefixlen / 8:])
    elif net.version == 6:
        return u'.'.join(items[32 - net.prefixlen / 4:])
    else:
        return None

def _validate_ipaddr(ugettext, ipaddr, ip_version=None):
    try:
        ip = netaddr.IPAddress(ipaddr)

        if ip_version is not None:
            if ip.version != ip_version:
                return _('invalid IP address version (is %(value)d, must be %(required_value)d)!') \
                        % dict(value=ip.version, required_value=ip_version)
    except (netaddr.AddrFormatError, ValueError):
        return _('invalid IP address format')
    return None

def _validate_ip4addr(ugettext, ipaddr):
    return _validate_ipaddr(ugettext, ipaddr, 4)

def _validate_ip6addr(ugettext, ipaddr):
    return _validate_ipaddr(ugettext, ipaddr, 6)

def _validate_ipnet(ugettext, ipnet):
    try:
        net = netaddr.IPNetwork(ipnet)
    except (netaddr.AddrFormatError, ValueError, UnboundLocalError):
        return _('invalid IP network format')
    return None

def _domain_name_validator(ugettext, value):
    try:
        # Allow domain name which is not fully qualified. These are supported
        # in bind and then translated as <non-fqdn-name>.<domain>.
        validate_hostname(value, check_fqdn=False)
    except ValueError, e:
        return _('invalid domain-name: %s') \
            % unicode(e)

    return None

def _hostname_validator(ugettext, value):
    try:
        validate_hostname(value)
    except ValueError, e:
        return _('invalid domain-name: %s') \
            % unicode(e)

    return None

def _normalize_hostname(domain_name):
    """Make it fully-qualified"""
    if domain_name[-1] != '.':
        return domain_name + '.'
    else:
        return domain_name

class DNSRecord(Str):
    parts = None
    supported = True
    # supported RR types: https://fedorahosted.org/bind-dyndb-ldap/browser/doc/schema

    label_format = _("%s record")
    part_label_format = "%s %s"
    doc_format = _('Comma-separated list of raw %s records')
    option_group_format = _('%s Record')
    see_rfc_msg = _("(see RFC %s for details)")
    part_name_format = "%s_part_%s"
    cli_name_format = "%s_%s"
    format_error_msg = None

    kwargs = Str.kwargs + (
        ('validatedns', bool, True),
        ('normalizedns', bool, True),
    )

    # should be replaced in subclasses
    rrtype = None
    rfc = None

    def __init__(self, name=None, *rules, **kw):
        if self.rrtype not in _record_types:
            raise ValueError("Unknown RR type: %s. Must be one of %s" % \
                    (str(self.rrtype), ", ".join(_record_types)))
        if not name:
            name = "%srecord*" % self.rrtype.lower()
        kw.setdefault('cli_name', '%s_rec' % self.rrtype.lower())
        kw.setdefault('label', self.label_format % self.rrtype)
        kw.setdefault('doc', self.doc_format % self.rrtype)
        kw['csv'] = True

        if not self.supported:
            kw['flags'] = ('no_option',)

        super(DNSRecord, self).__init__(name, *rules, **kw)

    def _get_part_values(self, value):
        values = value.split()
        if len(values) != len(self.parts):
            return None
        return tuple(values)

    def _convert_scalar(self, value, index=None):
        if isinstance(value, (tuple, list)):
            # convert parsed values to the string
            if len(value) != len(self.parts):
                raise errors.ConversionError(name=self.name, index=index,
                      error=_("Invalid number of parts!"))
            return u" ".join(super(DNSRecord, self)._convert_scalar(v, index) \
                             for v in value if v is not None)
        return super(DNSRecord, self)._convert_scalar(value, index)

    def normalize(self, value):
        if self.normalizedns: #pylint: disable=E1101
            if isinstance(value, (tuple, list)):
                value = tuple(
                            self._normalize_parts(v) for v in value \
                                    if v is not None
                        )
            elif value is not None:
                value = (self._normalize_parts(value),)

        return super(DNSRecord, self).normalize(value)

    def _normalize_parts(self, value):
        """
        Normalize a DNS record value using normalizers for its parts.
        """
        if self.parts is None:
            return value
        try:
            values = self._get_part_values(value)
            if not values:
                return value

            new_values = [ part.normalize(values[part_id]) \
                            for part_id, part in enumerate(self.parts) ]

            value = self._convert_scalar(new_values)
        except Exception:
            # cannot normalize, rather return original value than fail
            pass
        return value

    def _rule_validatedns(self, _, value):
        if not self.validatedns: #pylint: disable=E1101
            return

        if value is None:
            return

        if not self.supported:
            return _('DNS RR type "%s" is not supported by bind-dyndb-ldap plugin') \
                     % self.rrtype

        if self.parts is None:
            return

        # validate record format
        values = self._get_part_values(value)
        if not values:
            if not self.format_error_msg:
                part_names = [part.name.upper() for part in self.parts]

                if self.rfc:
                    see_rfc_msg = " " + self.see_rfc_msg % self.rfc
                else:
                    see_rfc_msg = ""
                return _('format must be specified as "%(format)s" %(rfcs)s') \
                    % dict(format=" ".join(part_names), rfcs=see_rfc_msg)
            else:
                return self.format_error_msg

        # validate every part
        for part_id, part in enumerate(self.parts):
            val = part.normalize(values[part_id])
            val = part.convert(val)
            part.validate(val)
        return None

class ARecord(DNSRecord):
    rrtype = 'A'
    rfc = 1035
    parts = (
        Str('ip_address',
            _validate_ip4addr,
            label=_('IP Address'),
        ),
    )

class A6Record(DNSRecord):
    rrtype = 'A6'
    rfc = 3226
    parts = None    # experimental rr type

class AAAARecord(DNSRecord):
    rrtype = 'AAAA'
    rfc = 3596
    parts = (
        Str('ip_address',
            _validate_ip6addr,
            label=_('IP Address'),
        ),
    )

class AFSDBRecord(DNSRecord):
    rrtype = 'AFSDB'
    rfc = 1183
    parts = (
        Int('subtype?',
            label=_('Subtype'),
            minvalue=0,
            maxvalue=65535,
        ),
        Str('hostname',
            _domain_name_validator,
            label=_('Hostname'),
        ),
    )

class APLRecord(DNSRecord):
    rrtype = 'APL'
    rfc = 3123
    supported = False

class CERTRecord(DNSRecord):
    rrtype = 'CERT'
    rfc = 4398
    parts = (
        Int('type',
            label=_('Certificate Type'),
            minvalue=0,
            maxvalue=65535,
        ),
        Int('key_tag',
            label=_('Key Tag'),
            minvalue=0,
            maxvalue=65535,
        ),
        Int('algorithm',
            label=_('Algorithm'),
            minvalue=0,
            maxvalue=255,
        ),
        Str('certificate_or_crl',
            label=_('Certificate/CRL'),
        ),
    )

class CNAMERecord(DNSRecord):
    rrtype = 'CNAME'
    rfc = 1035
    parts = (
        Str('hostname',
            _domain_name_validator,
            label=_('Hostname'),
            doc=_('A hostname which this alias hostname points to'),
        ),
    )

class DHCIDRecord(DNSRecord):
    rrtype = 'DHCID'
    rfc = 4701
    supported = False

class DLVRecord(DNSRecord):
    rrtype = 'DLV'
    rfc = 4431
    supported = False

class DNAMERecord(DNSRecord):
    rrtype = 'DNAME'
    rfc = 2672
    parts = (
        Str('target',
            _domain_name_validator,
            label=_('Target'),
        ),
    )

class DNSKEYRecord(DNSRecord):
    rrtype = 'DNSKEY'
    rfc = 4034
    supported = False

class DSRecord(DNSRecord):
    rrtype = 'DS'
    rfc = 4034
    parts = (
        Int('key_tag',
            label=_('Key Tag'),
            minvalue=0,
            maxvalue=65535,
        ),
        Int('algorithm',
            label=_('Algorithm'),
            minvalue=0,
            maxvalue=255,
        ),
        Int('digest_type',
            label=_('Digest Type'),
            minvalue=0,
            maxvalue=255,
        ),
        Str('digest',
            label=_('Digest'),
        ),
    )

class HIPRecord(DNSRecord):
    rrtype = 'HIP'
    rfc = 5205
    supported = False

class KEYRecord(DNSRecord):
    rrtype = 'KEY'
    rfc = 2535
    parts = (
        Int('flags',
            label=_('Flags'),
            minvalue=0,
            maxvalue=65535,
        ),
        Int('protocol',
            label=_('Protocol'),
            minvalue=0,
            maxvalue=255,
        ),
        Int('algorithm',
            label=_('Algorithm'),
            minvalue=0,
            maxvalue=255,
        ),
        Str('public_key',
            label=_('Public Key'),
        ),
    )

class IPSECKEYRecord(DNSRecord):
    rrtype = 'IPSECKEY'
    rfc = 4025
    supported = False

class KXRecord(DNSRecord):
    rrtype = 'KX'
    rfc = 2230
    parts = (
        Int('preference',
            label=_('Preference'),
            doc=_('Preference given to this exchanger. Lower values are more preferred'),
            minvalue=0,
            maxvalue=65535,
        ),
        Str('exchanger',
            _domain_name_validator,
            label=_('Exchanger'),
            doc=_('A host willing to act as a key exchanger'),
        ),
    )

class LOCRecord(DNSRecord):
    rrtype = 'LOC'
    rfc = 1876
    parts = (
        Int('lat_deg',
            label=_('Degrees Latitude'),
            minvalue=0,
            maxvalue=90,
        ),
        Int('lat_min?',
            label=_('Minutes Latitude'),
            minvalue=0,
            maxvalue=59,
        ),
        Float('lat_sec?',
            label=_('Seconds Latitude'),
            minvalue=0.0,
            maxvalue=59.999,
        ),
        StrEnum('lat_dir',
            label=_('Direction Latitude'),
            values=(u'N', u'S',),
        ),
        Int('lon_deg',
            label=_('Degrees Longtitude'),
            minvalue=0,
            maxvalue=180,
        ),
        Int('lon_min?',
            label=_('Minutes Longtitude'),
            minvalue=0,
            maxvalue=59,
        ),
        Float('lon_sec?',
            label=_('Seconds Longtitude'),
            minvalue=0.0,
            maxvalue=59.999,
        ),
        StrEnum('lon_dir',
            label=_('Direction Longtitude'),
            values=(u'E', u'W',),
        ),
        Float('altitude',
            label=_('Altitude'),
            minvalue=-100000.00,
            maxvalue=42849672.95,
        ),
        Float('size?',
            label=_('Size'),
            minvalue=0.0,
            maxvalue=90000000.00,
        ),
        Float('h_precision?',
            label=_('Horizontal Precision'),
            minvalue=0.0,
            maxvalue=90000000.00,
        ),
        Float('v_precision?',
            label=_('Vertical Precision'),
            minvalue=0.0,
            maxvalue=90000000.00,
        ),
    )

    format_error_msg = _("""format must be specified as
    "d1 [m1 [s1]] {"N"|"S"}  d2 [m2 [s2]] {"E"|"W"} alt["m"] [siz["m"] [hp["m"] [vp["m"]]]]"
    where:
       d1:     [0 .. 90]            (degrees latitude)
       d2:     [0 .. 180]           (degrees longitude)
       m1, m2: [0 .. 59]            (minutes latitude/longitude)
       s1, s2: [0 .. 59.999]        (seconds latitude/longitude)
       alt:    [-100000.00 .. 42849672.95] BY .01 (altitude in meters)
       siz, hp, vp: [0 .. 90000000.00] (size/precision in meters)
    See RFC 1876 for details""")

    def _get_part_values(self, value):
        regex = re.compile(\
            r'(?P<d1>\d{1,2}\s+)(?P<m1>\d{1,2}\s+)?(?P<s1>\d{1,2}\.?\d{1,3}?\s+)?'\
            r'(?P<dir1>[N|S])\s+'\
            r'(?P<d2>\d{1,3}\s+)(?P<m2>\d{1,2}\s+)?(?P<s2>\d{1,2}\.?\d{1,3}?\s+)?'\
            r'(?P<dir2>[W|E])\s+'\
            r'(?P<alt>-?\d{1,8}\.?\d{1,2}?)m?\s*'\
            r'(?P<siz>\d{1,8}\.?\d{1,2}?)?m?\s*'\
            r'(?P<hp>\d{1,8}\.?\d{1,2}?)?m?\s*(?P<vp>\d{1,8}\.?\d{1,2}?)?m?\s*$')

        m = regex.match(value)

        if m is None:
            return None

        return tuple(x.strip() if x is not None else x for x in m.groups())

class MXRecord(DNSRecord):
    rrtype = 'MX'
    rfc = 1035
    parts = (
        Int('preference',
            label=_('Preference'),
            doc=_('Preference given to this exchanger. Lower values are more preferred'),
            minvalue=0,
            maxvalue=65535,
        ),
        Str('exchanger',
            _domain_name_validator,
            label=_('Exchanger'),
            doc=_('A host willing to act as a mail exchanger'),
        ),
    )

class NSRecord(DNSRecord):
    rrtype = 'NS'
    rfc = 1035

    parts = (
        Str('hostname',
            _domain_name_validator,
            label=_('Hostname'),
        ),
    )

class NSECRecord(DNSRecord):
    rrtype = 'NSEC'
    rfc = 4034
    format_error_msg = _('format must be specified as "NEXT TYPE1 '\
                         '[TYPE2 [TYPE3 [...]]]" (see RFC 4034 for details)')
    _allowed_types = (u'SOA',) + _record_types

    parts = (
        Str('next',
            _domain_name_validator,
            label=_('Next Domain Name'),
        ),
        StrEnum('types',
            label=_('Type Map'),
            multivalue=True,
            values=_allowed_types,
        ),
    )

    def _get_part_values(self, value):
        values = value.split()

        if len(values) < 2:
            return None

        return (values[0], tuple(values[1:]))

class NSEC3Record(DNSRecord):
    rrtype = 'NSEC3'
    rfc = 5155
    supported = False

class NSEC3PARAMRecord(DNSRecord):
    rrtype = 'NSEC3PARAM'
    rfc = 5155
    supported = False

def _validate_naptr_flags(ugettext, flags):
    allowed_flags = u'SAUP'
    flags = flags.replace('"','').replace('\'','')

    for flag in flags:
        if flag not in allowed_flags:
            return _('flags must be one of "S", "A", "U", or "P"')

class NAPTRRecord(DNSRecord):
    rrtype = 'NAPTR'
    rfc = 2915

    parts = (
        Int('order',
            label=_('Order'),
            minvalue=0,
            maxvalue=65535,
        ),
        Int('preference',
            label=_('Preference'),
            minvalue=0,
            maxvalue=65535,
        ),
        Str('flags',
            _validate_naptr_flags,
            label=_('Flags'),
            normalizer=lambda x:x.upper()
        ),
        Str('service',
            label=_('Service'),
        ),
        Str('regexp',
            label=_('Regular Expression'),
        ),
        Str('replacement',
            label=_('Replacement'),
        ),
    )

class PTRRecord(DNSRecord):
    rrtype = 'PTR'
    rfc = 1035
    parts = (
        Str('hostname',
            _hostname_validator,
            normalizer=_normalize_hostname,
            label=_('Hostname'),
            doc=_('The hostname this reverse record points to'),
        ),
    )

class RPRecord(DNSRecord):
    rrtype = 'RP'
    rfc = 1183
    supported = False

class SRVRecord(DNSRecord):
    rrtype = 'SRV'
    rfc = 2782
    parts = (
        Int('priority',
            label=_('Priority'),
            minvalue=0,
            maxvalue=65535,
        ),
        Int('weight',
            label=_('Weight'),
            minvalue=0,
            maxvalue=65535,
        ),
        Int('port',
            label=_('Port'),
            minvalue=0,
            maxvalue=65535,
        ),
        Str('target',
            label=_('Target'),
            doc=_('The domain name of the target host or \'.\' if the service is decidedly not available at this domain'),
        ),
    )

def _sig_time_validator(ugettext, value):
    time_format = "%Y%m%d%H%M%S"
    try:
        time.strptime(value, time_format)
    except ValueError:
        return _('the value does not follow "YYYYMMDDHHMMSS" time format')


class SIGRecord(DNSRecord):
    rrtype = 'SIG'
    rfc = 2535
    _allowed_types = tuple([u'SOA'] + [x for x in _record_types if x != u'SIG'])

    parts = (
        StrEnum('type_covered',
            label=_('Type Covered'),
            values=_allowed_types,
        ),
        Int('algorithm',
            label=_('Algorithm'),
            minvalue=0,
            maxvalue=255,
        ),
        Int('labels',
            label=_('Labels'),
            minvalue=0,
            maxvalue=255,
        ),
        Int('original_ttl',
            label=_('Original TTL'),
            minvalue=0,
            maxvalue=4294967295,
        ),
        Str('signature_expiration',
            _sig_time_validator,
            label=_('Signature Expiration'),
        ),
        Str('signature_inception',
            _sig_time_validator,
            label=_('Signature Inception'),
        ),
        Int('key_tag',
            label=_('Key Tag'),
            minvalue=0,
            maxvalue=65535,
        ),
        Str('signers_name',
            label=_('Signer\'s Name'),
        ),
        Str('signature',
            label=_('Signature'),
        ),
    )

class SPFRecord(DNSRecord):
    rrtype = 'SPF'
    rfc = 4408
    supported = False

class RRSIGRecord(SIGRecord):
    rrtype = 'RRSIG'
    rfc = 4034

class SSHFPRecord(DNSRecord):
    rrtype = 'SSHFP'
    rfc = 4255
    parts = (
        Int('algorithm',
            label=_('Algorithm'),
            minvalue=0,
            maxvalue=255,
        ),
        Int('fp_type',
            label=_('Fingerprint Type'),
            minvalue=0,
            maxvalue=255,
        ),
        Str('fingerprint',
            label=_('Fingerprint'),
        ),
    )

class TARecord(DNSRecord):
    rrtype = 'TA'
    supported = False

class TKEYRecord(DNSRecord):
    rrtype = 'TKEY'
    supported = False

class TSIGRecord(DNSRecord):
    rrtype = 'TSIG'
    supported = False

class TXTRecord(DNSRecord):
    rrtype = 'TXT'
    rfc = 1035
    parts = (
        Str('data',
            label=_('Text Data'),
        ),
    )

_dns_record_options = (
    ARecord(),
    AAAARecord(),
    A6Record(),
    AFSDBRecord(),
    APLRecord(),
    CERTRecord(),
    CNAMERecord(),
    DHCIDRecord(),
    DLVRecord(),
    DNAMERecord(),
    DNSKEYRecord(),
    DSRecord(),
    HIPRecord(),
    IPSECKEYRecord(),
    KEYRecord(),
    KXRecord(),
    LOCRecord(),
    MXRecord(),
    NAPTRRecord(),
    NSRecord(),
    NSECRecord(),
    NSEC3Record(),
    NSEC3PARAMRecord(),
    PTRRecord(),
    RRSIGRecord(),
    RPRecord(),
    SIGRecord(),
    SPFRecord(),
    SRVRecord(),
    SSHFPRecord(),
    TARecord(),
    TKEYRecord(),
    TSIGRecord(),
    TXTRecord(),
)

# dictionary of valid reverse zone -> number of address components
_valid_reverse_zones = {
    '.in-addr.arpa.' : 4,
    '.ip6.arpa.' : 32,
}

def zone_is_reverse(zone_name):
    for rev_zone_name in _valid_reverse_zones.keys():
        if zone_name.endswith(rev_zone_name):
            return True

    return False

def is_ns_rec_resolvable(name):
    try:
        return api.Command['dns_resolve'](name)
    except errors.NotFound:
        raise errors.NotFound(
            reason=_('Nameserver \'%(host)s\' does not have a corresponding A/AAAA record') % {'host': name}
        )

def add_forward_record(zone, name, str_address):
    addr = netaddr.IPAddress(str_address)
    try:
        if addr.version == 4:
            api.Command['dnsrecord_add'](zone, name, arecord=str_address)
        elif addr.version == 6:
            api.Command['dnsrecord_add'](zone, name, aaaarecord=str_address)
        else:
            raise ValueError('Invalid address family')
    except errors.EmptyModlist:
        pass # the entry already exists and matches

def dns_container_exists(ldap):
    try:
        ldap.get_entry(api.env.container_dns, [])
    except errors.NotFound:
        return False
    return True

class dnszone(LDAPObject):
    """
    DNS Zone, container for resource records.
    """
    container_dn = api.env.container_dns
    object_name = _('DNS zone')
    object_name_plural = _('DNS zones')
    object_class = ['top', 'idnsrecord', 'idnszone']
    default_attributes = [
        'idnsname', 'idnszoneactive', 'idnssoamname', 'idnssoarname',
        'idnssoaserial', 'idnssoarefresh', 'idnssoaretry', 'idnssoaexpire',
        'idnssoaminimum'
    ] + _record_attributes
    label = _('DNS Zones')
    label_singular = _('DNS Zone')

    takes_params = (
        Str('idnsname',
            cli_name='name',
            label=_('Zone name'),
            doc=_('Zone name (FQDN)'),
            default_from=lambda name_from_ip: _reverse_zone_name(name_from_ip),
            normalizer=lambda value: value.lower(),
            primary_key=True,
        ),
        Str('name_from_ip?', _validate_ipnet,
            label=_('Reverse zone IP network'),
            doc=_('IP network to create reverse zone name from'),
            flags=('virtual_attribute',),
        ),
        Str('idnssoamname',
            cli_name='name_server',
            label=_('Authoritative nameserver'),
            doc=_('Authoritative nameserver domain name'),
        ),
        Str('idnssoarname',
            _rname_validator,
            cli_name='admin_email',
            label=_('Administrator e-mail address'),
            doc=_('Administrator e-mail address'),
            default_from=lambda idnsname: 'hostmaster.%s' % idnsname,
            normalizer=normalize_zonemgr,
        ),
        Int('idnssoaserial',
            cli_name='serial',
            label=_('SOA serial'),
            doc=_('SOA record serial number'),
            minvalue=1,
            create_default=_create_zone_serial,
            autofill=True,
        ),
        Int('idnssoarefresh',
            cli_name='refresh',
            label=_('SOA refresh'),
            doc=_('SOA record refresh time'),
            minvalue=0,
            default=3600,
            autofill=True,
        ),
        Int('idnssoaretry',
            cli_name='retry',
            label=_('SOA retry'),
            doc=_('SOA record retry time'),
            minvalue=0,
            default=900,
            autofill=True,
        ),
        Int('idnssoaexpire',
            cli_name='expire',
            label=_('SOA expire'),
            doc=_('SOA record expire time'),
            default=1209600,
            minvalue=0,
            autofill=True,
        ),
        Int('idnssoaminimum',
            cli_name='minimum',
            label=_('SOA minimum'),
            doc=_('How long should negative responses be cached'),
            default=3600,
            minvalue=0,
            maxvalue=10800,
            autofill=True,
        ),
        Int('dnsttl?',
            cli_name='ttl',
            label=_('SOA time to live'),
            doc=_('SOA record time to live'),
        ),
        StrEnum('dnsclass?',
            cli_name='class',
            label=_('SOA class'),
            doc=_('SOA record class'),
            values=_record_classes,
        ),
        Str('idnsupdatepolicy?',
            cli_name='update_policy',
            label=_('BIND update policy'),
            doc=_('BIND update policy'),
        ),
        Bool('idnszoneactive?',
            cli_name='zone_active',
            label=_('Active zone'),
            doc=_('Is zone active?'),
            flags=['no_create', 'no_update'],
            attribute=True,
        ),
        Bool('idnsallowdynupdate?',
            cli_name='dynamic_update',
            label=_('Dynamic update'),
            doc=_('Allow dynamic updates.'),
            attribute=True,
            default=False,
            autofill=True
        ),
    )

api.register(dnszone)


class dnszone_add(LDAPCreate):
    __doc__ = _('Create new DNS zone (SOA record).')

    takes_options = LDAPCreate.takes_options + (
        Flag('force',
             label=_('Force'),
             doc=_('Force DNS zone creation even if nameserver not in DNS.'),
        ),
        Str('ip_address?', _validate_ipaddr,
            doc=_('Add the nameserver to DNS with this IP address'),
        ),
    )

    def args_options_2_params(self, *args, **options):
        # FIXME: Check if name_from_ip is valid. The framework should do that,
        #        but it does not. Before it's fixed, this should suffice.
        if 'name_from_ip' in options:
            self.obj.params['name_from_ip'](unicode(options['name_from_ip']))
        return super(dnszone_add, self).args_options_2_params(*args, **options)

    def pre_callback(self, ldap, dn, entry_attrs, *keys, **options):
        if not dns_container_exists(self.api.Backend.ldap2):
            raise errors.NotFound(reason=_('DNS is not configured'))

        entry_attrs['idnszoneactive'] = 'TRUE'

        # Check nameserver has a forward record
        nameserver = entry_attrs['idnssoamname']

        # NS record must contain domain name
        if valid_ip(nameserver):
            raise errors.ValidationError(name='name-server',
                    error=unicode(_("Nameserver address is not a fully qualified domain name")))

        if not 'ip_address' in options and not options['force']:
            is_ns_rec_resolvable(nameserver)

        if nameserver[-1] != '.':
            nameserver += '.'

        entry_attrs['nsrecord'] = nameserver
        entry_attrs['idnssoamname'] = nameserver
        return dn

    def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
        if 'ip_address' in options:
            nameserver = entry_attrs['idnssoamname'][0][:-1] # ends with a dot
            nsparts = nameserver.split('.')
            add_forward_record('.'.join(nsparts[1:]),
                               nsparts[0],
                               options['ip_address'])

        return dn

api.register(dnszone_add)


class dnszone_del(LDAPDelete):
    __doc__ = _('Delete DNS zone (SOA record).')

api.register(dnszone_del)


class dnszone_mod(LDAPUpdate):
    __doc__ = _('Modify DNS zone (SOA record).')

    def args_options_2_params(self, *args, **options):
        # FIXME: Check if name_from_ip is valid. The framework should do that,
        #        but it does not. Before it's fixed, this should suffice.
        if 'name_from_ip' in options:
            self.obj.params['name_from_ip'](unicode(options['name_from_ip']))
        return super(dnszone_mod, self).args_options_2_params(*args, **options)

api.register(dnszone_mod)


class dnszone_find(LDAPSearch):
    __doc__ = _('Search for DNS zones (SOA records).')

    def args_options_2_params(self, *args, **options):
        # FIXME: Check if name_from_ip is valid. The framework should do that,
        #        but it does not. Before it's fixed, this should suffice.
        if 'name_from_ip' in options:
            self.obj.params['name_from_ip'](unicode(options['name_from_ip']))
        return super(dnszone_find, self).args_options_2_params(*args, **options)

    def args_options_2_entry(self, *args, **options):
        if 'name_from_ip' in options:
            if 'idnsname' not in options:
                options['idnsname'] = self.obj.params['idnsname'].get_default(**options)
            del options['name_from_ip']
        return super(dnszone_find, self).args_options_2_entry(*args, **options)

    takes_options = LDAPSearch.takes_options + (
        Flag('forward_only',
            label=_('Forward zones only'),
            cli_name='forward_only',
            doc=_('Search for forward zones only'),
        ),
    )

    def pre_callback(self, ldap, filter, attrs_list, base_dn, scope, *args, **options):
        if options.get('forward_only', False):
            search_kw = {}
            search_kw['idnsname'] = _valid_reverse_zones.keys()
            rev_zone_filter = ldap.make_filter(search_kw, rules=ldap.MATCH_NONE, exact=False,
                    trailing_wildcard=False)
            filter = ldap.combine_filters((rev_zone_filter, filter), rules=ldap.MATCH_ALL)

        return (filter, base_dn, scope)


api.register(dnszone_find)


class dnszone_show(LDAPRetrieve):
    __doc__ = _('Display information about a DNS zone (SOA record).')

api.register(dnszone_show)


class dnszone_disable(LDAPQuery):
    __doc__ = _('Disable DNS Zone.')

    has_output = output.standard_value
    msg_summary = _('Disabled DNS zone "%(value)s"')

    def execute(self, *keys, **options):
        ldap = self.obj.backend

        dn = self.obj.get_dn(*keys, **options)

        try:
            ldap.update_entry(dn, {'idnszoneactive': 'FALSE'})
        except errors.EmptyModlist:
            pass

        return dict(result=True, value=keys[-1])

api.register(dnszone_disable)


class dnszone_enable(LDAPQuery):
    __doc__ = _('Enable DNS Zone.')

    has_output = output.standard_value
    msg_summary = _('Enabled DNS zone "%(value)s"')

    def execute(self, *keys, **options):
        ldap = self.obj.backend

        dn = self.obj.get_dn(*keys, **options)

        try:
            ldap.update_entry(dn, {'idnszoneactive': 'TRUE'})
        except errors.EmptyModlist:
            pass

        return dict(result=True, value=keys[-1])

api.register(dnszone_enable)


class dnsrecord(LDAPObject):
    """
    DNS record.
    """
    parent_object = 'dnszone'
    container_dn = api.env.container_dns
    object_name = _('DNS resource record')
    object_name_plural = _('DNS resource records')
    object_class = ['top', 'idnsrecord']
    default_attributes = ['idnsname'] + _record_attributes

    label = _('DNS Resource Records')
    label_singular = _('DNS Resource Record')

    takes_params = (
        Str('idnsname',
            cli_name='name',
            label=_('Record name'),
            doc=_('Record name'),
            primary_key=True,
        ),
        Int('dnsttl?',
            cli_name='ttl',
            label=_('Time to live'),
            doc=_('Time to live'),
        ),
        StrEnum('dnsclass?',
            cli_name='class',
            label=_('Class'),
            doc=_('DNS class'),
            values=_record_classes,
        ),
    ) + _dns_record_options

    def _nsrecord_pre_callback(self, ldap, dn, entry_attrs, *keys, **options):
        if options.get('force', False):
            return dn

        for ns in options['nsrecord']:
            is_ns_rec_resolvable(ns)
        return dn

    def _ptrrecord_pre_callback(self, ldap, dn, entry_attrs, *keys, **options):
        components = dn.split(',',2)
        addr = components[0].split('=')[1]
        zone = components[1].split('=')[1]
        zone_len = 0
        for valid_zone in _valid_reverse_zones:
            if zone.find(valid_zone) != -1:
                zone = zone.replace(valid_zone,'')
                zone_name = valid_zone
                zone_len = _valid_reverse_zones[valid_zone]

        if not zone_len:
            allowed_zones = ', '.join(_valid_reverse_zones)
            raise errors.ValidationError(name='cn',
                    error=unicode(_('Reverse zone for PTR record should be a sub-zone of one the following fully qualified domains: %s') % allowed_zones))

        ip_addr_comp_count = len(addr.split('.')) + len(zone.split('.'))
        if ip_addr_comp_count != zone_len:
            raise errors.ValidationError(name='cn',
                error=unicode(_('Reverse zone %(name)s requires exactly %(count)d IP address components, %(user_count)d given')
                % dict(name=zone_name, count=zone_len, user_count=ip_addr_comp_count)))

        return dn

    def is_pkey_zone_record(self, *keys):
        idnsname = keys[-1]
        if idnsname == str(_dns_zone_record) or idnsname == ('%s.' % keys[-2]):
            return True
        return False

    def get_dn(self, *keys, **options):
        if self.is_pkey_zone_record(*keys):
            return self.api.Object[self.parent_object].get_dn(*keys[:-1], **options)
        return super(dnsrecord, self).get_dn(*keys, **options)

    def attr_to_cli(self, attr):
        try:
            cliname = attr[:-len('record')].upper()
        except IndexError:
            cliname = attr
        return cliname

    def get_dns_masters(self):
        ldap = self.api.Backend.ldap2
        base_dn = 'cn=masters,cn=ipa,cn=etc,%s' % self.api.env.basedn
        ldap_filter = '(&(objectClass=ipaConfigObject)(cn=DNS))'
        dns_masters = []

        try:
            entries = ldap.find_entries(filter=ldap_filter, base_dn=base_dn)[0]

            for entry in entries:
                master_dn = entry[0]
                if master_dn.startswith('cn='):
                    master = explode_dn(master_dn)[1].replace('cn=','')
                    dns_masters.append(master)
        except errors.NotFound:
            return []

        return dns_masters

    def has_cli_options(self, options, no_option_msg, allow_empty_attrs=False):
        if any(k in options for k in ('setattr', 'addattr', 'delattr')):
            return

        has_options = False
        for attr in options.keys():
            if attr in self.params and not self.params[attr].primary_key:
                if options[attr] or allow_empty_attrs:
                    has_options = True
                    break

        if not has_options:
            raise errors.OptionError(no_option_msg)

    def get_record_option(self, rec_type):
        name = '%srecord' % rec_type.lower()
        if name in self.params:
            return self.params[name]
        else:
            return None

    def get_record_entry_attrs(self, entry_attrs):
        return dict((attr, val) for attr,val in entry_attrs.iteritems() \
                    if attr in self.params and not self.params[attr].primary_key)

    def prompt_record_options(self, rec_type_list):
        user_options = {}
        # ask for all usual record types
        for rec_type in rec_type_list:
            rec_option = self.get_record_option(rec_type)
            if rec_option is None:
                continue
            raw = self.Backend.textui.prompt(rec_option.label,optional=True)
            rec_value = rec_option(raw)
            if rec_value is not None:
                 user_options[rec_option.name] = rec_value

        return user_options

api.register(dnsrecord)


class dnsrecord_add(LDAPCreate):
    __doc__ = _('Add new DNS resource record.')

    no_option_msg = 'No options to add a specific record provided.\n' \
            "Command help may be consulted for all supported record types."
    takes_options = LDAPCreate.takes_options + (
        Flag('force',
             label=_('Force'),
             flags=['no_option', 'no_output'],
             doc=_('force NS record creation even if its hostname is not in DNS'),
        ),
    )

    def args_options_2_entry(self, *keys, **options):
        self.obj.has_cli_options(options, self.no_option_msg)
        return super(dnsrecord_add, self).args_options_2_entry(*keys, **options)

    def interactive_prompt_callback(self, kw):
        try:
            self.obj.has_cli_options(kw, self.no_option_msg)
        except errors.OptionError:
            pass
        else:
            # some record type entered, skip this helper
            return

        # check zone type
        if kw['idnsname'] == _dns_zone_record:
            top_record_types = _zone_top_record_types
        elif zone_is_reverse(kw['dnszoneidnsname']):
            top_record_types = _rev_top_record_types
        else:
            top_record_types = _top_record_types

        # ask for all usual record types
        user_options = self.obj.prompt_record_options(top_record_types)
        kw.update(user_options)

    def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
        for rtype in options:
            rtype_cb = '_%s_pre_callback' % rtype
            if hasattr(self.obj, rtype_cb):
                dn = getattr(self.obj, rtype_cb)(ldap, dn, entry_attrs, *keys, **options)

        try:
            (dn_, old_entry) = ldap.get_entry(
                        dn, entry_attrs.keys(),
                        normalize=self.obj.normalize_dn)
            for attr in old_entry.keys():
                if attr not in _record_attributes:
                    continue
                if not isinstance(entry_attrs[attr], (tuple, list)):
                    vals = [entry_attrs[attr]]
                else:
                    vals = list(entry_attrs[attr])
                entry_attrs[attr] = list(set(old_entry[attr] + vals))
        except errors.NotFound:
            pass
        return dn

    def exc_callback(self, keys, options, exc, call_func, *call_args, **call_kwargs):
        if call_func.func_name == 'add_entry':
            if isinstance(exc, errors.DuplicateEntry):
                # A new record is being added to existing LDAP DNS object
                # Update can be safely run as old record values has been
                # already merged in pre_callback
                ldap = self.obj.backend
                dn = call_args[0]
                entry_attrs = self.obj.get_record_entry_attrs(call_args[1])
                ldap.update_entry(dn, entry_attrs, **call_kwargs)
                return
        raise exc

api.register(dnsrecord_add)


class dnsrecord_mod(LDAPUpdate):
    __doc__ = _('Modify a DNS resource record.')

    no_option_msg = 'No options to modify a specific record provided.'

    def args_options_2_entry(self, *keys, **options):
        self.obj.has_cli_options(options, self.no_option_msg, True)
        return super(dnsrecord_mod, self).args_options_2_entry(*keys, **options)

    def pre_callback(self, ldap, dn, entry_attrs, *keys, **options):
        for rtype in options:
            rtype_cb = '_%s_pre_callback' % rtype
            if options[rtype] is None and rtype in _record_attributes:
                options[rtype] = []
            if hasattr(self.obj, rtype_cb):
                dn = getattr(self.obj, rtype_cb)(ldap, dn, entry_attrs, *keys, **options)

        return dn

    def execute(self, *keys, **options):
        result = super(dnsrecord_mod, self).execute(*keys, **options)

        # remove if empty
        if not self.obj.is_pkey_zone_record(*keys):
            dn = self.obj.get_dn(*keys, **options)
            ldap = self.obj.backend
            (dn_, old_entry) = ldap.get_entry(
                    dn, _record_attributes,
                    normalize=self.obj.normalize_dn)

            del_all = True
            for attr in old_entry:
                if old_entry[attr]:
                    del_all = False
                    break

            if del_all:
                return self.obj.methods.delentry(*keys)
        return result

api.register(dnsrecord_mod)


class dnsrecord_delentry(LDAPDelete):
    """
    Delete DNS record entry.
    """
    msg_summary = _('Deleted record "%(value)s"')
    NO_CLI = True

api.register(dnsrecord_delentry)


class dnsrecord_del(LDAPUpdate):
    __doc__ = _('Delete DNS resource record.')

    no_option_msg = _('Neither --del-all nor options to delete a specific record provided.\n'\
            "Command help may be consulted for all supported record types.")
    takes_options = (
            Flag('del_all',
                default=False,
                label=_('Delete all associated records'),
            ),
    )

    def pre_callback(self, ldap, dn, entry_attrs, *keys, **options):
        try:
            (dn_, old_entry) = ldap.get_entry(
                    dn, _record_attributes,
                    normalize=self.obj.normalize_dn)
        except errors.NotFound:
            self.obj.handle_not_found(*keys)

        for attr in entry_attrs.keys():
            if attr not in _record_attributes:
                continue
            if not isinstance(entry_attrs[attr], (tuple, list)):
                vals = [entry_attrs[attr]]
            else:
                vals = entry_attrs[attr]

            for val in vals:
                try:
                    old_entry[attr].remove(val)
                except (KeyError, ValueError):
                    raise errors.AttrValueNotFound(attr=attr,
                                                   value=val)
            entry_attrs[attr] = list(set(old_entry[attr]))

        if not self.obj.is_pkey_zone_record(*keys):
            del_all = True
            for attr in old_entry:
                if old_entry[attr]:
                    del_all = False
                    break
            setattr(context, 'del_all', del_all)

        return dn

    def execute(self, *keys, **options):
        if options.get('del_all', False):
            if self.obj.is_pkey_zone_record(*keys):
                raise errors.ValidationError(
                        name='del_all',
                        error=_('Zone record \'%s\' cannot be deleted') \
                                % _dns_zone_record
                      )
            return self.obj.methods.delentry(*keys)

        result = super(dnsrecord_del, self).execute(*keys, **options)

        if getattr(context, 'del_all', False):
            return self.obj.methods.delentry(*keys)
        return result

    def args_options_2_entry(self, *keys, **options):
        self.obj.has_cli_options(options, self.no_option_msg)
        return super(dnsrecord_del, self).args_options_2_entry(*keys, **options)

    def interactive_prompt_callback(self, kw):
        if kw.get('del_all', False):
            return
        try:
            self.obj.has_cli_options(kw, self.no_option_msg)
        except errors.OptionError:
            pass
        else:
            # some record type entered, skip this helper
            return

        # get DNS record first so that the NotFound exception is raised
        # before the helper would start
        dns_record = api.Command['dnsrecord_show'](kw['dnszoneidnsname'], kw['idnsname'])['result']
        rec_types = [rec_type for rec_type in dns_record if rec_type in _record_attributes]

        self.Backend.textui.print_plain(_("No option to delete specific record provided."))
        user_del_all = self.Backend.textui.prompt_yesno(_("Delete all?"), default=False)

        if user_del_all is True:
            kw['del_all'] = True
            return

        # ask user for records to be removed
        self.Backend.textui.print_plain(_(u'Current DNS record contents:\n'))
        present_params = []
        for param in self.params:
            if param.name in _record_attributes and param.name in dns_record:
                present_params.append(param)
                rec_type_content = u', '.join(dns_record[param.name])
                self.Backend.textui.print_plain(u'%s: %s' % (param.label, rec_type_content))
        self.Backend.textui.print_plain(u'')

        # ask what records to remove
        for param in present_params:
            deleted_values = []
            for rec_value in dns_record[param.name]:
                user_del_value = self.Backend.textui.prompt_yesno(
                        _("Delete %(name)s '%(value)s'?") \
                            % dict(name=param.label, value=rec_value), default=False)
                if user_del_value is True:
                     deleted_values.append(rec_value)
            if deleted_values:
                deleted_list = u','.join(deleted_values)
                kw[param.name] = param(deleted_list)

api.register(dnsrecord_del)


class dnsrecord_show(LDAPRetrieve):
    __doc__ = _('Display DNS resource.')

    def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
        if self.obj.is_pkey_zone_record(*keys):
            entry_attrs[self.obj.primary_key.name] = [_dns_zone_record]
        return dn

api.register(dnsrecord_show)


class dnsrecord_find(LDAPSearch):
    __doc__ = _('Search for DNS resources.')

    def pre_callback(self, ldap, filter, attrs_list, base_dn, scope, *args, **options):
        # include zone record (root entry) in the search
        return (filter, base_dn, ldap.SCOPE_SUBTREE)

    def post_callback(self, ldap, entries, truncated, *args, **options):
        if entries:
            zone_obj = self.api.Object[self.obj.parent_object]
            zone_dn = zone_obj.get_dn(args[0])
            if entries[0][0] == zone_dn:
                entries[0][1][zone_obj.primary_key.name] = [_dns_zone_record]

api.register(dnsrecord_find)

class dns_resolve(Command):
    __doc__ = _('Resolve a host name in DNS.')

    has_output = output.standard_value
    msg_summary = _('Found \'%(value)s\'')

    takes_args = (
        Str('hostname',
            label=_('Hostname'),
        ),
    )

    def execute(self, *args, **options):
        query=args[0]
        if query.find(api.env.domain) == -1 and query.find('.') == -1:
            query = '%s.%s.' % (query, api.env.domain)
        if query[-1] != '.':
            query = query + '.'
        reca = dnsclient.query(query, dnsclient.DNS_C_IN, dnsclient.DNS_T_A)
        rec6 = dnsclient.query(query, dnsclient.DNS_C_IN, dnsclient.DNS_T_AAAA)
        records = reca + rec6
        found = False
        for rec in records:
            if rec.dns_type == dnsclient.DNS_T_A or \
              rec.dns_type == dnsclient.DNS_T_AAAA:
                found = True
                break

        if not found:
            raise errors.NotFound(
                reason=_('Host \'%(host)s\' not found') % {'host': query}
            )

        return dict(result=True, value=query)

api.register(dns_resolve)

class dns_is_enabled(Command):
    """
    Checks if any of the servers has the DNS service enabled.
    """
    NO_CLI = True
    has_output = output.standard_value

    base_dn = 'cn=masters,cn=ipa,cn=etc,%s' % api.env.basedn
    filter = '(&(objectClass=ipaConfigObject)(cn=DNS))'

    def execute(self, *args, **options):
        ldap = self.api.Backend.ldap2
        dns_enabled = False

        try:
            ent = ldap.find_entries(filter=self.filter, base_dn=self.base_dn)
            if len(ent):
                dns_enabled = True
        except Exception, e:
            pass

        return dict(result=dns_enabled, value=u'')

api.register(dns_is_enabled)