/* * fs/inotify.c - inode-based file event notifications * * Authors: * John McCutchan * Robert Love * * Kernel API added by: Amy Griffis * * Copyright (C) 2005 John McCutchan * Copyright 2006 Hewlett-Packard Development Company, L.P. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2, 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. */ #include #include #include #include #include #include #include #include #include #include static atomic_t inotify_cookie; /* * Lock ordering: * * dentry->d_lock (used to keep d_move() away from dentry->d_parent) * iprune_mutex (synchronize shrink_icache_memory()) * inode_lock (protects the super_block->s_inodes list) * inode->inotify_mutex (protects inode->inotify_watches and watches->i_list) * inotify_handle->mutex (protects inotify_handle and watches->h_list) * * The inode->inotify_mutex and inotify_handle->mutex and held during execution * of a caller's event handler. Thus, the caller must not hold any locks * taken in their event handler while calling any of the published inotify * interfaces. */ /* * Lifetimes of the three main data structures--inotify_handle, inode, and * inotify_watch--are managed by reference count. * * inotify_handle: Lifetime is from inotify_init() to inotify_destroy(). * Additional references can bump the count via get_inotify_handle() and drop * the count via put_inotify_handle(). * * inotify_watch: for inotify's purposes, lifetime is from inotify_add_watch() * to remove_watch_no_event(). Additional references can bump the count via * get_inotify_watch() and drop the count via put_inotify_watch(). The caller * is reponsible for the final put after receiving IN_IGNORED, or when using * IN_ONESHOT after receiving the first event. Inotify does the final put if * inotify_destroy() is called. * * inode: Pinned so long as the inode is associated with a watch, from * inotify_add_watch() to the final put_inotify_watch(). */ /* * struct inotify_handle - represents an inotify instance * * This structure is protected by the mutex 'mutex'. */ struct inotify_handle { struct idr idr; /* idr mapping wd -> watch */ struct mutex mutex; /* protects this bad boy */ struct list_head watches; /* list of watches */ atomic_t count; /* reference count */ u32 last_wd; /* the last wd allocated */ const struct inotify_operations *in_ops; /* inotify caller operations */ }; static inline void get_inotify_handle(struct inotify_handle *ih) { atomic_inc(&ih->count); } static inline void put_inotify_handle(struct inotify_handle *ih) { if (atomic_dec_and_test(&ih->count)) { idr_destroy(&ih->idr); kfree(ih); } } /** * get_inotify_watch - grab a reference to an inotify_watch * @watch: watch to grab */ void get_inotify_watch(struct inotify_watch *watch) { atomic_inc(&watch->count); } EXPORT_SYMBOL_GPL(get_inotify_watch); /** * put_inotify_watch - decrements the ref count on a given watch. cleans up * watch references if the count reaches zero. inotify_watch is freed by * inotify callers via the destroy_watch() op. * @watch: watch to release */ void put_inotify_watch(struct inotify_watch *watch) { if (atomic_dec_and_test(&watch->count)) { struct inotify_handle *ih = watch->ih; iput(watch->inode); ih->in_ops->destroy_watch(watch); put_inotify_handle(ih); } } EXPORT_SYMBOL_GPL(put_inotify_watch); /* * inotify_handle_get_wd - returns the next WD for use by the given handle * * Callers must hold ih->mutex. This function can sleep. */ static int inotify_handle_get_wd(struct inotify_handle *ih, struct inotify_watch *watch) { int ret; do { if (unlikely(!idr_pre_get(&ih->idr, GFP_KERNEL))) return -ENOSPC; ret = idr_get_new_above(&ih->idr, watch, ih->last_wd+1, &watch->wd); } while (ret == -EAGAIN); if (likely(!ret)) ih->last_wd = watch->wd; return ret; } /* * inotify_inode_watched - returns nonzero if there are watches on this inode * and zero otherwise. We call this lockless, we do not care if we race. */ static inline int inotify_inode_watched(struct inode *inode) { return !list_empty(&inode->inotify_watches); } /* * Get child dentry flag into synch with parent inode. * Flag should always be clear for negative dentrys. */ static void set_dentry_child_flags(struct inode *inode, int watched) { struct dentry *alias; spin_lock(&dcache_lock); list_for_each_entry(alias, &inode->i_dentry, d_alias) { struct dentry *child; list_for_each_entry(child, &alias->d_subdirs, d_u.d_child) { if (!child->d_inode) { WARN_ON(child->d_flags & DCACHE_INOTIFY_PARENT_WATCHED); continue; } spin_lock(&child->d_lock); if (watched) { WARN_ON(child->d_flags & DCACHE_INOTIFY_PARENT_WATCHED); child->d_flags |= DCACHE_INOTIFY_PARENT_WATCHED; } else { WARN_ON(!(child->d_flags & DCACHE_INOTIFY_PARENT_WATCHED)); child->d_flags&=~DCACHE_INOTIFY_PARENT_WATCHED; } spin_unlock(&child->d_lock); } } spin_unlock(&dcache_lock); } /* * inotify_find_handle - find the watch associated with the given inode and * handle * * Callers must hold inode->inotify_mutex. */ static struct inotify_watch *inode_find_handle(struct inode *inode, struct inotify_handle *ih) { struct inotify_watch *watch; list_for_each_entry(watch, &inode->inotify_watches, i_list) { if (watch->ih == ih) return watch; } return NULL; } /* * remove_watch_no_event - remove watch without the IN_IGNORED event. * * Callers must hold both inode->inotify_mutex and ih->mutex. */ static void remove_watch_no_event(struct inotify_watch *watch, struct inotify_handle *ih) { list_del(&watch->i_list); list_del(&watch->h_list); if (!inotify_inode_watched(watch->inode)) set_dentry_child_flags(watch->inode, 0); idr_remove(&ih->idr, watch->wd); } /** * inotify_remove_watch_locked - Remove a watch from both the handle and the * inode. Sends the IN_IGNORED event signifying that the inode is no longer * watched. May be invoked from a caller's event handler. * @ih: inotify handle associated with watch * @watch: watch to remove * * Callers must hold both inode->inotify_mutex and ih->mutex. */ void inotify_remove_watch_locked(struct inotify_handle *ih, struct inotify_watch *watch) { remove_watch_no_event(watch, ih); ih->in_ops->handle_event(watch, watch->wd, IN_IGNORED, 0, NULL, NULL); } EXPORT_SYMBOL_GPL(inotify_remove_watch_locked); /* Kernel API for producing events */ /* * inotify_d_instantiate - instantiate dcache entry for inode */ void inotify_d_instantiate(struct dentry *entry, struct inode *inode) { struct dentry *parent; if (!inode) return; WARN_ON(entry->d_flags & DCACHE_INOTIFY_PARENT_WATCHED); spin_lock(&entry->d_lock); parent = entry->d_parent; if (parent->d_inode && inotify_inode_watched(parent->d_inode)) entry->d_flags |= DCACHE_INOTIFY_PARENT_WATCHED; spin_unlock(&entry->d_lock); } /* * inotify_d_move - dcache entry has been moved */ void inotify_d_move(struct dentry *entry) { struct dentry *parent; parent = entry->d_parent; if (inotify_inode_watched(parent->d_inode)) entry->d_flags |= DCACHE_INOTIFY_PARENT_WATCHED; else entry->d_flags &= ~DCACHE_INOTIFY_PARENT_WATCHED; } /** * inotify_inode_queue_event - queue an event to all watches on this inode * @inode: inode event is originating from * @mask: event mask describing this event * @cookie: cookie for synchronization, or zero * @name: filename, if any * @n_inode: inode associated with name */ void inotify_inode_queue_event(struct inode *inode, u32 mask, u32 cookie, const char *name, struct inode *n_inode) { struct inotify_watch *watch, *next; if (!inotify_inode_watched(inode)) return; mutex_lock(&inode->inotify_mutex); list_for_each_entry_safe(watch, next, &inode->inotify_watches, i_list) { u32 watch_mask = watch->mask; if (watch_mask & mask) { struct inotify_handle *ih= watch->ih; mutex_lock(&ih->mutex); if (watch_mask & IN_ONESHOT) remove_watch_no_event(watch, ih); ih->in_ops->handle_event(watch, watch->wd, mask, cookie, name, n_inode); mutex_unlock(&ih->mutex); } } mutex_unlock(&inode->inotify_mutex); } EXPORT_SYMBOL_GPL(inotify_inode_queue_event); /** * inotify_dentry_parent_queue_event - queue an event to a dentry's parent * @dentry: the dentry in question, we queue against this dentry's parent * @mask: event mask describing this event * @cookie: cookie for synchronization, or zero * @name: filename, if any */ void inotify_dentry_parent_queue_event(struct dentry *dentry, u32 mask, u32 cookie, const char *name) { struct dentry *parent; struct inode *inode; if (!(dentry->d_flags & DCACHE_INOTIFY_PARENT_WATCHED)) return; spin_lock(&dentry->d_lock); parent = dentry->d_parent; inode = parent->d_inode; if (inotify_inode_watched(inode)) { dget(parent); spin_unlock(&dentry->d_lock); inotify_inode_queue_event(inode, mask, cookie, name, dentry->d_inode); dput(parent); } else spin_unlock(&dentry->d_lock); } EXPORT_SYMBOL_GPL(inotify_dentry_parent_queue_event); /** * inotify_get_cookie - return a unique cookie for use in synchronizing events. */ u32 inotify_get_cookie(void) { return atomic_inc_return(&inotify_cookie); } EXPORT_SYMBOL_GPL(inotify_get_cookie); /** * inotify_unmount_inodes - an sb is unmounting. handle any watched inodes. * @list: list of inodes being unmounted (sb->s_inodes) * * Called with inode_lock held, protecting the unmounting super block's list * of inodes, and with iprune_mutex held, keeping shrink_icache_memory() at bay. * We temporarily drop inode_lock, however, and CAN block. */ void inotify_unmount_inodes(struct list_head *list) { struct inode *inode, *next_i, *need_iput = NULL; list_for_each_entry_safe(inode, next_i, list, i_sb_list) { struct inotify_watch *watch, *next_w; struct inode *need_iput_tmp; struct list_head *watches; /* * If i_count is zero, the inode cannot have any watches and * doing an __iget/iput with MS_ACTIVE clear would actually * evict all inodes with zero i_count from icache which is * unnecessarily violent and may in fact be illegal to do. */ if (!atomic_read(&inode->i_count)) continue; /* * We cannot __iget() an inode in state I_CLEAR, I_FREEING, or * I_WILL_FREE which is fine because by that point the inode * cannot have any associated watches. */ if (inode->i_state & (I_CLEAR | I_FREEING | I_WILL_FREE)) continue; need_iput_tmp = need_iput; need_iput = NULL; /* In case inotify_remove_watch_locked() drops a reference. */ if (inode != need_iput_tmp) __iget(inode); else need_iput_tmp = NULL; /* In case the dropping of a reference would nuke next_i. */ if ((&next_i->i_sb_list != list) && atomic_read(&next_i->i_count) && !(next_i->i_state & (I_CLEAR | I_FREEING | I_WILL_FREE))) { __iget(next_i); need_iput = next_i; } /* * We can safely drop inode_lock here because we hold * references on both inode and next_i. Also no new inodes * will be added since the umount has begun. Finally, * iprune_mutex keeps shrink_icache_memory() away. */ spin_unlock(&inode_lock); if (need_iput_tmp) iput(need_iput_tmp); /* for each watch, send IN_UNMOUNT and then remove it */ mutex_lock(&inode->inotify_mutex); watches = &inode->inotify_watches; list_for_each_entry_safe(watch, next_w, watches, i_list) { struct inotify_handle *ih= watch->ih; mutex_lock(&ih->mutex); ih->in_ops->handle_event(watch, watch->wd, IN_UNMOUNT, 0, NULL, NULL); inotify_remove_watch_locked(ih, watch); mutex_unlock(&ih->mutex); } mutex_unlock(&inode->inotify_mutex); iput(inode); spin_lock(&inode_lock); } } EXPORT_SYMBOL_GPL(inotify_unmount_inodes); /** * inotify_inode_is_dead - an inode has been deleted, cleanup any watches * @inode: inode that is about to be removed */ void inotify_inode_is_dead(struct inode *inode) { struct inotify_watch *watch, *next; mutex_lock(&inode->inotify_mutex); list_for_each_entry_safe(watch, next, &inode->inotify_watches, i_list) { struct inotify_handle *ih = watch->ih; mutex_lock(&ih->mutex); inotify_remove_watch_locked(ih, watch); mutex_unlock(&ih->mutex); } mutex_unlock(&inode->inotify_mutex); } EXPORT_SYMBOL_GPL(inotify_inode_is_dead); /* Kernel Consumer API */ /** * inotify_init - allocate and initialize an inotify instance * @ops: caller's inotify operations */ struct inotify_handle *inotify_init(const struct inotify_operations *ops) { struct inotify_handle *ih; ih = kmalloc(sizeof(struct inotify_handle), GFP_KERNEL); if (unlikely(!ih)) return ERR_PTR(-ENOMEM); idr_init(&ih->idr); INIT_LIST_HEAD(&ih->watches); mutex_init(&ih->mutex); ih->last_wd = 0; ih->in_ops = ops; atomic_set(&ih->count, 0); get_inotify_handle(ih); return ih; } EXPORT_SYMBOL_GPL(inotify_init); /** * inotify_init_watch - initialize an inotify watch * @watch: watch to initialize */ void inotify_init_watch(struct inotify_watch *watch) { INIT_LIST_HEAD(&watch->h_list); INIT_LIST_HEAD(&watch->i_list); atomic_set(&watch->count, 0); get_inotify_watch(watch); /* initial get */ } EXPORT_SYMBOL_GPL(inotify_init_watch); /** * inotify_destroy - clean up and destroy an inotify instance * @ih: inotify handle */ void inotify_destroy(struct inotify_handle *ih) { /* * Destroy all of the watches for this handle. Unfortunately, not very * pretty. We cannot do a simple iteration over the list, because we * do not know the inode until we iterate to the watch. But we need to * hold inode->inotify_mutex before ih->mutex. The following works. */ while (1) { struct inotify_watch *watch; struct list_head *watches; struct inode *inode; mutex_lock(&ih->mutex); watches = &ih->watches; if (list_empty(watches)) { mutex_unlock(&ih->mutex); break; } watch = list_entry(watches->next, struct inotify_watch, h_list); get_inotify_watch(watch); mutex_unlock(&ih->mutex); inode = watch->inode; mutex_lock(&inode->inotify_mutex); mutex_lock(&ih->mutex); /* make sure we didn't race with another list removal */ if (likely(idr_find(&ih->idr, watch->wd))) { remove_watch_no_event(watch, ih); put_inotify_watch(watch); } mutex_unlock(&ih->mutex); mutex_unlock(&inode->inotify_mutex); put_inotify_watch(watch); } /* free this handle: the put matching the get in inotify_init() */ put_inotify_handle(ih); } EXPORT_SYMBOL_GPL(inotify_destroy); /** * inotify_find_watch - find an existing watch for an (ih,inode) pair * @ih: inotify handle * @inode: inode to watch * @watchp: pointer to existing inotify_watch * * Caller must pin given inode (via nameidata). */ s32 inotify_find_watch(struct inotify_handle *ih, struct inode *inode, struct inotify_watch **watchp) { struct inotify_watch *old; int ret = -ENOENT; mutex_lock(&inode->inotify_mutex); mutex_lock(&ih->mutex); old = inode_find_handle(inode, ih); if (unlikely(old)) { get_inotify_watch(old); /* caller must put watch */ *watchp = old; ret = old->wd; } mutex_unlock(&ih->mutex); mutex_unlock(&inode->inotify_mutex); return ret; } EXPORT_SYMBOL_GPL(inotify_find_watch); /** * inotify_find_update_watch - find and update the mask of an existing watch * @ih: inotify handle * @inode: inode's watch to update * @mask: mask of events to watch * * Caller must pin given inode (via nameidata). */ s32 inotify_find_update_watch(struct inotify_handle *ih, struct inode *inode, u32 mask) { struct inotify_watch *old; int mask_add = 0; int ret; if (mask & IN_MASK_ADD) mask_add = 1; /* don't allow invalid bits: we don't want flags set */ mask &= IN_ALL_EVENTS | IN_ONESHOT; if (unlikely(!mask)) return -EINVAL; mutex_lock(&inode->inotify_mutex); mutex_lock(&ih->mutex); /* * Handle the case of re-adding a watch on an (inode,ih) pair that we * are already watching. We just update the mask and return its wd. */ old = inode_find_handle(inode, ih); if (unlikely(!old)) { ret = -ENOENT; goto out; } if (mask_add) old->mask |= mask; else old->mask = mask; ret = old->wd; out: mutex_unlock(&ih->mutex); mutex_unlock(&inode->inotify_mutex); return ret; } EXPORT_SYMBOL_GPL(inotify_find_update_watch); /** * inotify_add_watch - add a watch to an inotify instance * @ih: inotify handle * @watch: caller allocated watch structure * @inode: inode to watch * @mask: mask of events to watch * * Caller must pin given inode (via nameidata). * Caller must ensure it only calls inotify_add_watch() once per watch. * Calls inotify_handle_get_wd() so may sleep. */ s32 inotify_add_watch(struct inotify_handle *ih, struct inotify_watch *watch, struct inode *inode, u32 mask) { int ret = 0; /* don't allow invalid bits: we don't want flags set */ mask &= IN_ALL_EVENTS | IN_ONESHOT; if (unlikely(!mask)) return -EINVAL; watch->mask = mask; mutex_lock(&inode->inotify_mutex); mutex_lock(&ih->mutex); /* Initialize a new watch */ ret = inotify_handle_get_wd(ih, watch); if (unlikely(ret)) goto out; ret = watch->wd; /* save a reference to handle and bump the count to make it official */ get_inotify_handle(ih); watch->ih = ih; /* * Save a reference to the inode and bump the ref count to make it * official. We hold a reference to nameidata, which makes this safe. */ watch->inode = igrab(inode); if (!inotify_inode_watched(inode)) set_dentry_child_flags(inode, 1); /* Add the watch to the handle's and the inode's list */ list_add(&watch->h_list, &ih->watches); list_add(&watch->i_list, &inode->inotify_watches); out: mutex_unlock(&ih->mutex); mutex_unlock(&inode->inotify_mutex); return ret; } EXPORT_SYMBOL_GPL(inotify_add_watch); /** * inotify_rm_wd - remove a watch from an inotify instance * @ih: inotify handle * @wd: watch descriptor to remove * * Can sleep. */ int inotify_rm_wd(struct inotify_handle *ih, u32 wd) { struct inotify_watch *watch; struct inode *inode; mutex_lock(&ih->mutex); watch = idr_find(&ih->idr, wd); if (unlikely(!watch)) { mutex_unlock(&ih->mutex); return -EINVAL; } get_inotify_watch(watch); inode = watch->inode; mutex_unlock(&ih->mutex); mutex_lock(&inode->inotify_mutex); mutex_lock(&ih->mutex); /* make sure that we did not race */ if (likely(idr_find(&ih->idr, wd) == watch)) inotify_remove_watch_locked(ih, watch); mutex_unlock(&ih->mutex); mutex_unlock(&inode->inotify_mutex); put_inotify_watch(watch); return 0; } EXPORT_SYMBOL_GPL(inotify_rm_wd); /** * inotify_rm_watch - remove a watch from an inotify instance * @ih: inotify handle * @watch: watch to remove * * Can sleep. */ int inotify_rm_watch(struct inotify_handle *ih, struct inotify_watch *watch) { return inotify_rm_wd(ih, watch->wd); } EXPORT_SYMBOL_GPL(inotify_rm_watch); /* * inotify_setup - core initialization function */ static int __init inotify_setup(void) { atomic_set(&inotify_cookie, 0); return 0; } module_init(inotify_setup); 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991
# 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/>.

from __future__ import absolute_import

import netaddr
import time
import re
import dns.name

from ipalib.request import context
from ipalib import api, errors, output
from ipalib import Command
from ipalib.parameters import Flag, Bool, Int, Decimal, Str, StrEnum, Any
from ipalib.plugins.baseldap import *
from ipalib import _, ngettext
from ipalib.util import (validate_zonemgr, normalize_zonemgr, normalize_zone,
        validate_hostname, validate_dns_label, validate_domain_name,
        get_dns_forward_zone_update_policy, get_dns_reverse_zone_update_policy,
        get_reverse_zone_default, zone_is_reverse, REVERSE_DNS_ZONES)
from ipapython.ipautil import valid_ip, CheckedIPAddress, is_host_resolvable

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

Manage DNS zone and resource records.


USING STRUCTURED PER-TYPE OPTIONS

There are many structured DNS RR types where DNS data stored in LDAP server
is not just a scalar value, for example an IP address or a domain name, but
a data structure which may be often complex. A good example is a LOC record
[RFC1876] which consists of many mandatory and optional parts (degrees,
minutes, seconds of latitude and longitude, altitude or precision).

It may be difficult to manipulate such DNS records without making a mistake
and entering an invalid value. DNS module provides an abstraction over these
raw records and allows to manipulate each RR type with specific options. For
each supported RR type, DNS module provides a standard option to manipulate
a raw records with format --<rrtype>-rec, e.g. --mx-rec, and special options
for every part of the RR structure with format --<rrtype>-<partname>, e.g.
--mx-preference and --mx-exchanger.

When adding a record, either RR specific options or standard option for a raw
value can be used, they just should not be combined in one add operation. When
modifying an existing entry, new RR specific options can be used to change
one part of a DNS record, where the standard option for raw value is used
to specify the modified value. The following example demonstrates
a modification of MX record preference from 0 to 1 in a record without
modifying the exchanger:
ipa dnsrecord-mod --mx-rec="0 mx.example.com." --mx-preference=1


EXAMPLES:

 Add new zone:
   ipa dnszone-add example.com --name-server=ns \\
                               --admin-email=admin@example.com \\
                               --ip-address=10.0.0.1

 Add system permission that can be used for per-zone privilege delegation:
   ipa dnszone-add-permission 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

   This is the equivalent of:
     ipa dnszone-mod example.com --dynamic-update=TRUE \\
      --update-policy="grant EXAMPLE.COM krb5-self * A; grant EXAMPLE.COM krb5-self * AAAA; grant EXAMPLE.COM krb5-self * SSHFP;"

 Modify the zone to allow zone transfers for local network only:
   ipa dnszone-mod example.com --allow-transfer=10.0.0.0/8

 Add new reverse zone specified by network IP address:
   ipa dnszone-add --name-from-ip=80.142.15.0/24 \\
                   --name-server=ns.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 mail1"

 Add another record using MX record specific options:
  ipa dnsrecord-add example.com @ --mx-preference=20 --mx-exchanger=mail2

 Add another record using interactive mode (started when dnsrecord-add, dnsrecord-mod,
 or dnsrecord-del are executed with no options):
  ipa dnsrecord-add example.com @
  Please choose a type of DNS resource record to be added
  The most common types for this type of zone are: NS, MX, LOC

  DNS resource record type: MX
  MX Preference: 30
  MX Exchanger: mail3
    Record name: example.com
    MX record: 10 mail1, 20 mail2, 30 mail3
    NS record: nameserver.example.com., nameserver2.example.com.

 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. Create a reverse record in appropriate
 reverse zone as well. In this case a PTR record "2" pointing to www.example.com
 will be created in zone 15.142.80.in-addr.arpa.
   ipa dnsrecord-add example.com www --a-rec=80.142.15.2 --a-create-reverse

 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"

 The interactive mode can be used for easy modification:
  ipa dnsrecord-mod example.com _ldap._tcp
  No option to modify specific record provided.
  Current DNS record contents:

  SRV record: 0 3 389 fast.example.com, 0 1 389 slow.example.com, 1 1 389 backup.example.com

  Modify SRV record '0 3 389 fast.example.com'? Yes/No (default No):
  Modify SRV record '0 1 389 slow.example.com'? Yes/No (default No): y
  SRV Priority [0]:                     (keep the default value)
  SRV Weight [1]: 2                     (modified value)
  SRV Port [389]:                       (keep the default value)
  SRV Target [slow.example.com]:        (keep the default value)
  1 SRV record skipped. Only one value per DNS record type can be modified at one time.
    Record name: _ldap._tcp
    SRV record: 0 3 389 fast.example.com, 1 1 389 backup.example.com, 0 2 389 slow.example.com

 After this modification, three fifths of the requests should go to
 fast.example.com and two fifths to slow.example.com.

 An example of the interactive mode for dnsrecord-del command:
   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

 Delegate zone sub.example to another nameserver:
   ipa dnsrecord-add example.com ns.sub --a-rec=10.0.100.5
   ipa dnsrecord-add example.com sub --ns-rec=ns.sub.example.com.

 If global forwarder is configured, all requests to sub.example.com will be
 routed through the global forwarder. To change the behavior for example.com
 zone only and forward the request directly to ns.sub.example.com., global
 forwarding may be disabled per-zone:
   ipa dnszone-mod example.com --forward-policy=none

 Forward all requests for the zone external.com to another nameserver using
 a "first" policy (it will send the queries to the selected forwarder and if
 not answered it will use global resolvers):
   ipa dnszone-add external.com
   ipa dnszone-mod external.com --forwarder=10.20.0.1 \\
                                --forward-policy=first

 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


GLOBAL DNS CONFIGURATION

DNS configuration passed to command line install script is stored in a local
configuration file on each IPA server where DNS service is configured. These
local settings can be overridden with a common configuration stored in LDAP
server:

 Show global DNS configuration:
   ipa dnsconfig-show

 Modify global DNS configuration and set a list of global forwarders:
   ipa dnsconfig-mod --forwarder=10.0.0.1
""")

# 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():
    """
    Generate serial number for zones. bind-dyndb-ldap expects unix time in
    to be used for SOA serial.

    SOA serial in a date format would also work, but it may be set to far
    future when many DNS updates are done per day (more than 100). Unix
    timestamp is more resilient to this issue.
    """
    return int(time.time())

def _reverse_zone_name(netstr):
    try:
        netaddr.IPAddress(netstr)
    except (netaddr.AddrFormatError, ValueError):
        pass
    else:
        # use more sensible default prefix than netaddr default
        return unicode(get_reverse_zone_default(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, flags=netaddr.INET_PTON)

        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 _validate_bind_aci(ugettext, bind_acis):
    if not bind_acis:
        return

    bind_acis = bind_acis.split(';')
    if bind_acis[-1]:
        return _('each ACL element must be terminated with a semicolon')
    else:
        bind_acis.pop(-1)

    for bind_aci in bind_acis:
        if bind_aci in ("any", "none", "localhost", "localnets"):
            continue

        if bind_aci.startswith('!'):
            bind_aci = bind_aci[1:]

        try:
            ip = CheckedIPAddress(bind_aci, parse_netmask=True,
                                  allow_network=True, allow_loopback=True)
        except (netaddr.AddrFormatError, ValueError), e:
            return unicode(e)
        except UnboundLocalError:
            return _(u"invalid address format")

def _normalize_bind_aci(bind_acis):
    if not bind_acis:
        return
    bind_acis = bind_acis.split(';')
    normalized = []
    for bind_aci in bind_acis:
        if not bind_aci:
            continue
        if bind_aci in ("any", "none", "localhost", "localnets"):
            normalized.append(bind_aci)
            continue

        prefix = ""
        if bind_aci.startswith('!'):
            bind_aci = bind_aci[1:]
            prefix = "!"

        try:
            ip = CheckedIPAddress(bind_aci, parse_netmask=True,
                                  allow_network=True, allow_loopback=True)
            if '/' in bind_aci:    # addr with netmask
                netmask = "/%s" % ip.prefixlen
            else:
                netmask = ""
            normalized.append(u"%s%s%s" % (prefix, str(ip), netmask))
            continue
        except:
            normalized.append(bind_aci)
            continue

    acis = u';'.join(normalized)
    acis += u';'
    return acis

def _bind_hostname_validator(ugettext, value):
    if value == _dns_zone_record:
        return
    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 _dns_record_name_validator(ugettext, value):
    if value == _dns_zone_record:
        return

    try:
        map(lambda label:validate_dns_label(label, allow_underscore=True), \
            value.split(u'.'))
    except ValueError, e:
        return unicode(e)

def _validate_bind_forwarder(ugettext, forwarder):
    ip_address, sep, port = forwarder.partition(u' port ')

    ip_address_validation = _validate_ipaddr(ugettext, ip_address)

    if ip_address_validation is not None:
        return ip_address_validation

    if sep:
        try:
            port = int(port)
            if port < 0 or port > 65535:
                raise ValueError()
        except ValueError:
            return _('%(port)s is not a valid port' % dict(port=port))

    return None

def _domain_name_validator(ugettext, value):
    try:
        validate_domain_name(value)
    except ValueError, e:
        return unicode(e)

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

def is_forward_record(zone, str_address):
    addr = netaddr.IPAddress(str_address)
    if addr.version == 4:
        result = api.Command['dnsrecord_find'](zone, arecord=str_address)
    elif addr.version == 6:
        result = api.Command['dnsrecord_find'](zone, aaaarecord=str_address)
    else:
        raise ValueError('Invalid address family')

    return result['count'] > 0

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 get_reverse_zone(ipaddr, prefixlen=None):
    ip = netaddr.IPAddress(ipaddr)
    revdns = unicode(ip.reverse_dns)

    if prefixlen is None:
        revzone = u''

        result = api.Command['dnszone_find']()['result']
        for zone in result:
            zonename = zone['idnsname'][0]
            if revdns.endswith(zonename) and len(zonename) > len(revzone):
                revzone = zonename
    else:
        if ip.version == 4:
            pos = 4 - prefixlen / 8
        elif ip.version == 6:
            pos = 32 - prefixlen / 4
        items = ip.reverse_dns.split('.')
        revzone = u'.'.join(items[pos:])

        try:
            api.Command['dnszone_show'](revzone)
        except errors.NotFound:
            revzone = u''

    if len(revzone) == 0:
        raise errors.NotFound(
            reason=_('DNS reverse zone for IP address %(addr)s not found') % dict(addr=ipaddr)
        )

    revname = revdns[:-len(revzone)-1]

    return revzone, revname

def add_records_for_host_validation(option_name, host, domain, ip_addresses, check_forward=True, check_reverse=True):
    try:
        api.Command['dnszone_show'](domain)['result']
    except errors.NotFound:
        raise errors.NotFound(
            reason=_('DNS zone %(zone)s not found') % dict(zone=domain)
        )
    if not isinstance(ip_addresses, (tuple, list)):
        ip_addresses = [ip_addresses]

    for ip_address in ip_addresses:
        try:
            ip = CheckedIPAddress(ip_address, match_local=False)
        except Exception, e:
            raise errors.ValidationError(name=option_name, error=unicode(e))

        if check_forward:
            if is_forward_record(domain, unicode(ip)):
                raise errors.DuplicateEntry(
                        message=_(u'IP address %(ip)s is already assigned in domain %(domain)s.')\
                            % dict(ip=str(ip), domain=domain))

        if check_reverse:
            try:
                prefixlen = None
                if not ip.defaultnet:
                    prefixlen = ip.prefixlen
                # we prefer lookup of the IP through the reverse zone
                revzone, revname = get_reverse_zone(ip, prefixlen)
                reverse = api.Command['dnsrecord_find'](revzone, idnsname=revname)
                if reverse['count'] > 0:
                    raise errors.DuplicateEntry(
                            message=_(u'Reverse record for IP address %(ip)s already exists in reverse zone %(zone)s.')\
                            % dict(ip=str(ip), zone=revzone))
            except errors.NotFound:
                pass


def add_records_for_host(host, domain, ip_addresses, add_forward=True, add_reverse=True):
    if not isinstance(ip_addresses, (tuple, list)):
        ip_addresses = [ip_addresses]

    for ip_address in ip_addresses:
        ip = CheckedIPAddress(ip_address, match_local=False)

        if add_forward:
            add_forward_record(domain, host, unicode(ip))

        if add_reverse:
            try:
                prefixlen = None
                if not ip.defaultnet:
                    prefixlen = ip.prefixlen
                revzone, revname = get_reverse_zone(ip, prefixlen)
                addkw = { 'ptrrecord' : host + "." + domain }
                api.Command['dnsrecord_add'](revzone, revname, **addkw)
            except errors.EmptyModlist:
                # the entry already exists and matches
                pass

class DNSRecord(Str):
    # a list of parts that create the actual raw DNS record
    parts = None
    # an optional list of parameters used in record-specific operations
    extra = 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"
    extra_name_format = "%s_extra_%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.setdefault('option_group', self.option_group_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 _part_values_to_string(self, values, index):
        self._validate_parts(values)
        return u" ".join(super(DNSRecord, self)._convert_scalar(v, index) \
                             for v in values if v is not None)

    def get_parts_from_kw(self, kw, raise_on_none=True):
        part_names = tuple(self.part_name_format % (self.rrtype.lower(), part.name) \
                               for part in self.parts)
        vals = tuple(kw.get(part_name) for part_name in part_names)

        if all(val is None for val in vals):
             return

        if raise_on_none:
            for val_id,val in enumerate(vals):
                 if val is None and self.parts[val_id].required:
                    cli_name = self.cli_name_format % (self.rrtype.lower(), self.parts[val_id].name)
                    raise errors.ConversionError(name=self.name,
                                error=_("'%s' is a required part of DNS record") % cli_name)

        return vals

    def _validate_parts(self, parts):
        if len(parts) != len(self.parts):
            raise errors.ValidationError(name=self.name,
                                         error=_("Invalid number of parts!"))

    def _convert_scalar(self, value, index=None):
        if isinstance(value, (tuple, list)):
            return self._part_values_to_string(value, index)
        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

            converted_values = [ part._convert_scalar(values[part_id]) \
                                 if values[part_id] is not None else None
                                 for part_id, part in enumerate(self.parts)
                               ]

            new_values = [ part.normalize(converted_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 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

    def _convert_dnsrecord_part(self, part):
        """
        All parts of DNSRecord need to be processed and modified before they
        can be added to global DNS API. For example a prefix need to be added
        before part name so that the name is unique in the global namespace.
        """
        name = self.part_name_format % (self.rrtype.lower(), part.name)
        cli_name = self.cli_name_format % (self.rrtype.lower(), part.name)
        label = self.part_label_format % (self.rrtype, unicode(part.label))
        option_group = self.option_group_format % self.rrtype
        flags = list(part.flags) + ['dnsrecord_part', 'virtual_attribute',]

        if not part.required:
            flags.append('dnsrecord_optional')

        return part.clone_rename(name,
                     cli_name=cli_name,
                     label=label,
                     required=False,
                     option_group=option_group,
                     flags=flags,
                     hint=self.name,)   # name of parent RR param

    def _convert_dnsrecord_extra(self, extra):
        """
        Parameters for special per-type behavior need to be processed in the
        same way as record parts in _convert_dnsrecord_part().
        """
        name = self.extra_name_format % (self.rrtype.lower(), extra.name)
        cli_name = self.cli_name_format % (self.rrtype.lower(), extra.name)
        label = self.part_label_format % (self.rrtype, unicode(extra.label))
        option_group = self.option_group_format % self.rrtype
        flags = list(extra.flags) + ['dnsrecord_extra', 'virtual_attribute',]

        return extra.clone_rename(name,
                     cli_name=cli_name,
                     label=label,
                     required=False,
                     option_group=option_group,
                     flags=flags,
                     hint=self.name,)   # name of parent RR param

    def get_parts(self):
        if self.parts is None:
            return tuple()

        return tuple(self._convert_dnsrecord_part(part) for part in self.parts)

    def get_extra(self):
        if self.extra is None:
            return tuple()

        return tuple(self._convert_dnsrecord_extra(extra) for extra in self.extra)

    def __get_part_param(self, backend, part, output_kw, default=None):
        name = self.part_name_format % (self.rrtype.lower(), part.name)
        label = self.part_label_format % (self.rrtype, unicode(part.label))
        optional = not part.required

        while True:
            try:
                raw = backend.textui.prompt(label,
                                            optional=optional,
                                            default=default)
                if not raw.strip():
                    raw = default

                output_kw[name] = part(raw)
                break
            except (errors.ValidationError, errors.ConversionError), e:
                backend.textui.print_prompt_attribute_error(
                        unicode(label), unicode(e.error))

    def prompt_parts(self, backend, mod_dnsvalue=None):
        mod_parts = None
        if mod_dnsvalue is not None:
            mod_parts = self._get_part_values(mod_dnsvalue)

        user_options = {}
        if self.parts is None:
            return user_options

        for part_id, part in enumerate(self.parts):
            if mod_parts:
                default = mod_parts[part_id]
            else:
                default = None

            self.__get_part_param(backend, part, user_options, default)

        return user_options

    def prompt_missing_parts(self, backend, kw, prompt_optional=False):
        user_options = {}
        if self.parts is None:
            return user_options

        for part in self.parts:
            name = self.part_name_format % (self.rrtype.lower(), part.name)
            label = self.part_label_format % (self.rrtype, unicode(part.label))

            if name in kw:
                continue

            optional = not part.required
            if optional and not prompt_optional:
                continue

            default = part.get_default(**kw)
            self.__get_part_param(backend, part, user_options, default)

        return user_options

    # callbacks for per-type special record behavior
    def dnsrecord_add_pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
        assert isinstance(dn, DN)

    def dnsrecord_add_post_callback(self, ldap, dn, entry_attrs, *keys, **options):
        assert isinstance(dn, DN)

class ForwardRecord(DNSRecord):
    extra = (
        Flag('create_reverse?',
            label=_('Create reverse'),
            doc=_('Create reverse record for this IP Address'),
            flags=['no_update']
        ),
    )

    def dnsrecord_add_pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
        assert isinstance(dn, DN)
        reverse_option = self._convert_dnsrecord_extra(self.extra[0])
        if options.get(reverse_option.name):
            records = entry_attrs.get(self.name, [])
            if not records:
                # --<rrtype>-create-reverse is set, but there are not records
                raise errors.RequirementError(name=self.name)

            for record in records:
                add_records_for_host_validation(self.name, keys[-1], keys[-2], record,
                        check_forward=False,
                        check_reverse=True)

            setattr(context, '%s_reverse' % self.name, entry_attrs.get(self.name))

    def dnsrecord_add_post_callback(self, ldap, dn, entry_attrs, *keys, **options):
        assert isinstance(dn, DN)
        rev_records = getattr(context, '%s_reverse' % self.name, [])

        if rev_records:
            # make sure we don't run this post callback action again in nested
            # commands, line adding PTR record in add_records_for_host
            delattr(context, '%s_reverse' % self.name)
            for record in rev_records:
                try:
                    add_records_for_host(keys[-1], keys[-2], record,
                        add_forward=False, add_reverse=True)
                except Exception, e:
                    raise errors.NonFatalError(
                        reason=_('Cannot create reverse record for "%(value)s": %(exc)s') \
                                % dict(value=record, exc=unicode(e)))

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

class A6Record(DNSRecord):
    rrtype = 'A6'
    rfc = 3226
    parts = (
        Str('data',
            label=_('Record data'),
        ),
    )

    def _get_part_values(self, value):
        # A6 RR type is obsolete and only a raw interface is provided
        return (value,)

class AAAARecord(ForwardRecord):
    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',
            _bind_hostname_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',
            _bind_hostname_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',
            _bind_hostname_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',
            _bind_hostname_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,
        ),
        Decimal('lat_sec?',
            label=_('Seconds Latitude'),
            minvalue='0.0',
            maxvalue='59.999',
            precision=3,
        ),
        StrEnum('lat_dir',
            label=_('Direction Latitude'),
            values=(u'N', u'S',),
        ),
        Int('lon_deg',
            label=_('Degrees Longitude'),
            minvalue=0,
            maxvalue=180,
        ),
        Int('lon_min?',
            label=_('Minutes Longitude'),
            minvalue=0,
            maxvalue=59,
        ),
        Decimal('lon_sec?',
            label=_('Seconds Longitude'),
            minvalue='0.0',
            maxvalue='59.999',
            precision=3,
        ),
        StrEnum('lon_dir',
            label=_('Direction Longitude'),
            values=(u'E', u'W',),
        ),
        Decimal('altitude',
            label=_('Altitude'),
            minvalue='-100000.00',
            maxvalue='42849672.95',
            precision=2,
        ),
        Decimal('size?',
            label=_('Size'),
            minvalue='0.0',
            maxvalue='90000000.00',
            precision=2,
        ),
        Decimal('h_precision?',
            label=_('Horizontal Precision'),
            minvalue='0.0',
            maxvalue='90000000.00',
            precision=2,
        ),
        Decimal('v_precision?',
            label=_('Vertical Precision'),
            minvalue='0.0',
            maxvalue='90000000.00',
            precision=2,
        ),
    )

    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())

    def _validate_parts(self, parts):
        super(LOCRecord, self)._validate_parts(parts)

        # create part_name -> part_id map first
        part_name_map = dict((part.name, part_id) \
                             for part_id,part in enumerate(self.parts))

        requirements = ( ('lat_sec', 'lat_min'),
                         ('lon_sec', 'lon_min'),
                         ('h_precision', 'size'),
                         ('v_precision', 'h_precision', 'size') )

        for req in requirements:
            target_part = req[0]

            if parts[part_name_map[target_part]] is not None:
                required_parts = req[1:]
                if any(parts[part_name_map[part]] is None for part in required_parts):
                    target_cli_name = self.cli_name_format % (self.rrtype.lower(), req[0])
                    required_cli_names = [ self.cli_name_format % (self.rrtype.lower(), part)
                                           for part in req[1:] ]
                    error = _("'%(required)s' must not be empty when '%(name)s' is set") % \
                                        dict(required=', '.join(required_cli_names),
                                             name=target_cli_name)
                    raise errors.ValidationError(name=self.name, error=error)

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',
            _bind_hostname_validator,
            label=_('Exchanger'),
            doc=_('A host willing to act as a mail exchanger'),
        ),
    )

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

    parts = (
        Str('hostname',
            _bind_hostname_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',
            _bind_hostname_validator,
            label=_('Next Domain Name'),
        ),
        StrEnum('types+',
            label=_('Type Map'),
            values=_allowed_types,
            csv=True,
        ),
    )

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

        if len(values) < 2:
            return None

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

    def _part_values_to_string(self, values, index):
        self._validate_parts(values)
        values_flat = [values[0],]  # add "next" part
        types = values[1]
        if not isinstance(types, (list, tuple)):
            types = [types,]
        values_flat.extend(types)
        return u" ".join(Str._convert_scalar(self, v, index) \
                             for v in values_flat if v is not None)

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

def _srv_target_validator(ugettext, value):
    if value == u'.':
        # service not available
        return
    return _bind_hostname_validator(ugettext, value)

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',
            _srv_target_validator,
            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,
        ),
        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'),
        ),
    )

    def _get_part_values(self, value):
        # ignore any space in TXT record
        return (value,)

_dns_records = (
    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(),
)

def __dns_record_options_iter():
    for opt in (Any('dnsrecords?',
                    label=_('Records'),
                    flags=['no_create', 'no_search', 'no_update'],),
                Str('dnstype?',
                    label=_('Record type'),
                    flags=['no_create', 'no_search', 'no_update'],),
                Str('dnsdata?',
                    label=_('Record data'),
                    flags=['no_create', 'no_search', 'no_update'],)):
        # These 3 options are used in --structured format. They are defined
        # rather in takes_params than has_output_params because of their
        # order - they should be printed to CLI before any DNS part param
        yield opt
    for option in _dns_records:
        yield option

        for part in option.get_parts():
            yield part

        for extra in option.get_extra():
            yield extra

_dns_record_options = tuple(__dns_record_options_iter())
_dns_supported_record_types = tuple(record.rrtype for record in _dns_records \
                                    if record.supported)

def check_ns_rec_resolvable(zone, name):
    if name == _dns_zone_record:
        name = normalize_zone(zone)
    elif not name.endswith('.'):
        # this is a DNS name relative to the zone
        zone = dns.name.from_text(zone)
        name = unicode(dns.name.from_text(name, origin=zone))
    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 dns_container_exists(ldap):
    try:
        ldap.get_entry(api.env.container_dns, [])
    except errors.NotFound:
        return False
    return True

def default_zone_update_policy(zone):
    if zone_is_reverse(zone):
        return get_dns_reverse_zone_update_policy(api.env.realm, zone)
    else:
        return get_dns_forward_zone_update_policy(api.env.realm)

dnszone_output_params = (
    Str('managedby',
        label=_('Managedby permission'),
    ),
)

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']
    possible_objectclasses = ['ipadnszone']
    default_attributes = [
        'idnsname', 'idnszoneactive', 'idnssoamname', 'idnssoarname',
        'idnssoaserial', 'idnssoarefresh', 'idnssoaretry', 'idnssoaexpire',
        'idnssoaminimum', 'idnsallowquery', 'idnsallowtransfer',
        'idnsforwarders', 'idnsforwardpolicy'
    ] + _record_attributes
    label = _('DNS Zones')
    label_singular = _('DNS Zone')

    takes_params = (
        Str('idnsname',
            _domain_name_validator,
            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'),
            normalizer=lambda value: value.lower(),
        ),
        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,
            maxvalue=4294967295L,
            default_from=_create_zone_serial,
            autofill=True,
        ),
        Int('idnssoarefresh',
            cli_name='refresh',
            label=_('SOA refresh'),
            doc=_('SOA record refresh time'),
            minvalue=0,
            maxvalue=2147483647,
            default=3600,
            autofill=True,
        ),
        Int('idnssoaretry',
            cli_name='retry',
            label=_('SOA retry'),
            doc=_('SOA record retry time'),
            minvalue=0,
            maxvalue=2147483647,
            default=900,
            autofill=True,
        ),
        Int('idnssoaexpire',
            cli_name='expire',
            label=_('SOA expire'),
            doc=_('SOA record expire time'),
            default=1209600,
            minvalue=0,
            maxvalue=2147483647,
            autofill=True,
        ),
        Int('idnssoaminimum',
            cli_name='minimum',
            label=_('SOA minimum'),
            doc=_('How long should negative responses be cached'),
            default=3600,
            minvalue=0,
            maxvalue=2147483647,
            autofill=True,
        ),
        Int('dnsttl?',
            cli_name='ttl',
            label=_('SOA time to live'),
            doc=_('SOA record time to live'),
            minvalue=0,
            maxvalue=2147483647, # see RFC 2181
        ),
        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'),
            default_from=lambda idnsname: default_zone_update_policy(idnsname),
            autofill=True
        ),
        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
        ),
        Str('idnsallowquery?',
            _validate_bind_aci,
            normalizer=_normalize_bind_aci,
            cli_name='allow_query',
            label=_('Allow query'),
            doc=_('Semicolon separated list of IP addresses or networks which are allowed to issue queries'),
            default=u'any;',   # anyone can issue queries by default
            autofill=True,
        ),
        Str('idnsallowtransfer?',
            _validate_bind_aci,
            normalizer=_normalize_bind_aci,
            cli_name='allow_transfer',
            label=_('Allow transfer'),
            doc=_('Semicolon separated list of IP addresses or networks which are allowed to transfer the zone'),
            default=u'none;',  # no one can issue queries by default
            autofill=True,
        ),
        Str('idnsforwarders*',
            _validate_bind_forwarder,
            cli_name='forwarder',
            label=_('Zone forwarders'),
            doc=_('A list of per-zone forwarders. A custom port can be specified '
                  'for each forwarder using a standard format "IP_ADDRESS port PORT"'),
            csv=True,
        ),
        StrEnum('idnsforwardpolicy?',
            cli_name='forward_policy',
            label=_('Forward policy'),
            doc=_('Per-zone conditional forwarding policy. Set to "none" to '
                  'disable forwarding to global forwarder for this zone. In '
                  'that case, conditional zone forwarders are disregarded.'),
            values=(u'only', u'first', u'none'),
        ),
        Bool('idnsallowsyncptr?',
            cli_name='allow_sync_ptr',
            label=_('Allow PTR sync'),
            doc=_('Allow synchronization of forward (A, AAAA) and reverse (PTR) records in the zone'),
        ),
    )

    def get_dn(self, *keys, **options):
        zone = keys[-1]
        dn = super(dnszone, self).get_dn(zone, **options)
        try:
            self.backend.get_entry(dn, [''])
        except errors.NotFound:
            if zone.endswith(u'.'):
                zone = zone[:-1]
            else:
                zone = zone + u'.'
            test_dn = super(dnszone, self).get_dn(zone, **options)

            try:
                (dn, entry_attrs) = self.backend.get_entry(test_dn, [''])
            except errors.NotFound:
                pass

        return dn

    def permission_name(self, zone):
        return u"Manage DNS zone %s" % zone

    def get_name_in_zone(self, zone, hostname):
        """
        Get name of a record that is to be added to a new zone. I.e. when
        we want to add record "ipa.lab.example.com" in a zone "example.com",
        this function should return "ipa.lab". Returns None when record cannot
        be added to a zone
        """
        if hostname == _dns_zone_record:
            # special case: @ --> zone name
            return hostname

        if hostname.endswith(u'.'):
            hostname = hostname[:-1]
        if zone.endswith(u'.'):
            zone = zone[:-1]

        hostname_parts = hostname.split(u'.')
        zone_parts = zone.split(u'.')

        dns_name = list(hostname_parts)
        for host_part, zone_part in zip(reversed(hostname_parts),
                                        reversed(zone_parts)):
            if host_part != zone_part:
                return None
            dns_name.pop()

        if not dns_name:
            # hostname is directly in zone itself
            return _dns_zone_record

        return u'.'.join(dns_name)

api.register(dnszone)


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

    has_output_params = LDAPCreate.has_output_params + dnszone_output_params
    takes_options = LDAPCreate.takes_options + (
        Flag('force',
             label=_('Force'),
             doc=_('Force DNS zone creation even if nameserver is not resolvable.'),
        ),
        Str('ip_address?', _validate_ipaddr,
            doc=_('Add forward record for nameserver located in the created zone'),
        ),
    )

    def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
        assert isinstance(dn, DN)
        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=_("Nameserver address is not a domain name"))

        nameserver_ip_address = options.get('ip_address')
        normalized_zone = normalize_zone(keys[-1])

        if nameserver.endswith('.'):
            record_in_zone = self.obj.get_name_in_zone(keys[-1], nameserver)
        else:
            record_in_zone = nameserver

        if zone_is_reverse(normalized_zone):
            if not nameserver.endswith('.'):
                raise errors.ValidationError(name='name-server',
                        error=_("Nameserver for reverse zone cannot be "
                                "a relative DNS name"))
            elif nameserver_ip_address:
                raise errors.ValidationError(name='ip_address',
                        error=_("Nameserver DNS record is created for "
                                "for forward zones only"))
        elif nameserver_ip_address and nameserver.endswith('.') and not record_in_zone:
            raise errors.ValidationError(name='ip_address',
                    error=_("Nameserver DNS record is created only for "
                            "nameservers in current zone"))

        if not nameserver_ip_address and not options['force']:
             check_ns_rec_resolvable(keys[0], nameserver)

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

    def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
        assert isinstance(dn, DN)
        nameserver_ip_address = options.get('ip_address')
        if nameserver_ip_address:
            nameserver = entry_attrs['idnssoamname'][0]
            if nameserver.endswith('.'):
                dns_record = self.obj.get_name_in_zone(keys[-1], nameserver)
            else:
                dns_record = nameserver
            add_forward_record(keys[-1],
                               dns_record,
                               nameserver_ip_address)

        return dn

api.register(dnszone_add)


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

    def post_callback(self, ldap, dn, *keys, **options):
        try:
            api.Command['permission_del'](self.obj.permission_name(keys[-1]),
                    force=True)
        except errors.NotFound:
            pass
        return True

api.register(dnszone_del)


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

    takes_options = LDAPUpdate.takes_options + (
        Flag('force',
             label=_('Force'),
             doc=_('Force nameserver change even if nameserver not in DNS'),
        ),
    )

    has_output_params = LDAPUpdate.has_output_params + dnszone_output_params

    def pre_callback(self, ldap, dn, entry_attrs, attrs_list,  *keys, **options):
        nameserver = entry_attrs.get('idnssoamname')
        if nameserver and nameserver != _dns_zone_record and not options['force']:
            check_ns_rec_resolvable(keys[0], nameserver)

        return dn

api.register(dnszone_mod)


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

    has_output_params = LDAPSearch.has_output_params + dnszone_output_params

    def args_options_2_params(self, *args, **options):
        # FIXME: Check that name_from_ip is valid. This is necessary because
        #        custom validation rules, including _validate_ipnet, are not
        #        used when doing a search. Once we have a parameter type for
        #        IP network objects, this will no longer be necessary, as the
        #        parameter type will handle the validation itself (see
        #        <https://fedorahosted.org/freeipa/ticket/2266>).
        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):
        assert isinstance(base_dn, DN)
        if options.get('forward_only', False):
            search_kw = {}
            search_kw['idnsname'] = REVERSE_DNS_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).')

    has_output_params = LDAPRetrieve.has_output_params + dnszone_output_params

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 dnszone_add_permission(LDAPQuery):
    __doc__ = _('Add a permission for per-zone access delegation.')

    has_output = output.standard_value
    msg_summary = _('Added system permission "%(value)s"')

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

        try:
            (dn_, entry_attrs) = ldap.get_entry(dn, ['objectclass'])
        except errors.NotFound:
            self.obj.handle_not_found(*keys)

        permission_name = self.obj.permission_name(keys[-1])
        permission = api.Command['permission_add_noaci'](permission_name,
                         permissiontype=u'SYSTEM'
                     )['result']

        update = {}
        dnszone_ocs = entry_attrs.get('objectclass')
        if dnszone_ocs:
            dnszone_ocs.append('ipadnszone')
            update['objectclass'] = list(set(dnszone_ocs))

        update['managedby'] = [permission['dn']]
        ldap.update_entry(dn, update)

        return dict(
            result=True,
            value=permission_name,
        )

api.register(dnszone_add_permission)

class dnszone_remove_permission(LDAPQuery):
    __doc__ = _('Remove a permission for per-zone access delegation.')

    has_output = output.standard_value
    msg_summary = _('Removed system permission "%(value)s"')

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

        try:
            ldap.update_entry(dn, {'managedby': None})
        except errors.NotFound:
            self.obj.handle_not_found(*keys)
        except errors.EmptyModlist:
            # managedBy attribute is clean, lets make sure there is also no
            # dangling DNS zone permission
            pass

        permission_name = self.obj.permission_name(keys[-1])
        api.Command['permission_del'](permission_name, force=True)

        return dict(
            result=True,
            value=permission_name,
        )

api.register(dnszone_remove_permission)

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
    rdn_is_primary_key = True

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

    takes_params = (
        Str('idnsname',
            _dns_record_name_validator,
            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',