summaryrefslogtreecommitdiffstats
path: root/include/linux/hugetlb.h
diff options
context:
space:
mode:
authorWu Fengguang <fengguang.wu@intel.com>2009-06-16 15:32:22 -0700
committerLinus Torvalds <torvalds@linux-foundation.org>2009-06-16 19:47:36 -0700
commit20a0307c0396c2edb651401d2f2db193dda2f3c9 (patch)
tree408fde4bf84223757f5dd150e401e8d9d9df5d36 /include/linux/hugetlb.h
parenta1dd268cf6306565a31a48deff8bf4f6b4b105f7 (diff)
downloadkernel-crypto-20a0307c0396c2edb651401d2f2db193dda2f3c9.tar.gz
kernel-crypto-20a0307c0396c2edb651401d2f2db193dda2f3c9.tar.xz
kernel-crypto-20a0307c0396c2edb651401d2f2db193dda2f3c9.zip
mm: introduce PageHuge() for testing huge/gigantic pages
A series of patches to enhance the /proc/pagemap interface and to add a userspace executable which can be used to present the pagemap data. Export 10 more flags to end users (and more for kernel developers): 11. KPF_MMAP (pseudo flag) memory mapped page 12. KPF_ANON (pseudo flag) memory mapped page (anonymous) 13. KPF_SWAPCACHE page is in swap cache 14. KPF_SWAPBACKED page is swap/RAM backed 15. KPF_COMPOUND_HEAD (*) 16. KPF_COMPOUND_TAIL (*) 17. KPF_HUGE hugeTLB pages 18. KPF_UNEVICTABLE page is in the unevictable LRU list 19. KPF_HWPOISON hardware detected corruption 20. KPF_NOPAGE (pseudo flag) no page frame at the address (*) For compound pages, exporting _both_ head/tail info enables users to tell where a compound page starts/ends, and its order. a simple demo of the page-types tool # ./page-types -h page-types [options] -r|--raw Raw mode, for kernel developers -a|--addr addr-spec Walk a range of pages -b|--bits bits-spec Walk pages with specified bits -l|--list Show page details in ranges -L|--list-each Show page details one by one -N|--no-summary Don't show summay info -h|--help Show this usage message addr-spec: N one page at offset N (unit: pages) N+M pages range from N to N+M-1 N,M pages range from N to M-1 N, pages range from N to end ,M pages range from 0 to M bits-spec: bit1,bit2 (flags & (bit1|bit2)) != 0 bit1,bit2=bit1 (flags & (bit1|bit2)) == bit1 bit1,~bit2 (flags & (bit1|bit2)) == bit1 =bit1,bit2 flags == (bit1|bit2) bit-names: locked error referenced uptodate dirty lru active slab writeback reclaim buddy mmap anonymous swapcache swapbacked compound_head compound_tail huge unevictable hwpoison nopage reserved(r) mlocked(r) mappedtodisk(r) private(r) private_2(r) owner_private(r) arch(r) uncached(r) readahead(o) slob_free(o) slub_frozen(o) slub_debug(o) (r) raw mode bits (o) overloaded bits # ./page-types flags page-count MB symbolic-flags long-symbolic-flags 0x0000000000000000 487369 1903 _________________________________ 0x0000000000000014 5 0 __R_D____________________________ referenced,dirty 0x0000000000000020 1 0 _____l___________________________ lru 0x0000000000000024 34 0 __R__l___________________________ referenced,lru 0x0000000000000028 3838 14 ___U_l___________________________ uptodate,lru 0x0001000000000028 48 0 ___U_l_______________________I___ uptodate,lru,readahead 0x000000000000002c 6478 25 __RU_l___________________________ referenced,uptodate,lru 0x000100000000002c 47 0 __RU_l_______________________I___ referenced,uptodate,lru,readahead 0x0000000000000040 8344 32 ______A__________________________ active 0x0000000000000060 1 0 _____lA__________________________ lru,active 0x0000000000000068 348 1 ___U_lA__________________________ uptodate,lru,active 0x0001000000000068 12 0 ___U_lA______________________I___ uptodate,lru,active,readahead 0x000000000000006c 988 3 __RU_lA__________________________ referenced,uptodate,lru,active 0x000100000000006c 48 0 __RU_lA______________________I___ referenced,uptodate,lru,active,readahead 0x0000000000004078 1 0 ___UDlA_______b__________________ uptodate,dirty,lru,active,swapbacked 0x000000000000407c 34 0 __RUDlA_______b__________________ referenced,uptodate,dirty,lru,active,swapbacked 0x0000000000000400 503 1 __________B______________________ buddy 0x0000000000000804 1 0 __R________M_____________________ referenced,mmap 0x0000000000000828 1029 4 ___U_l_____M_____________________ uptodate,lru,mmap 0x0001000000000828 43 0 ___U_l_____M_________________I___ uptodate,lru,mmap,readahead 0x000000000000082c 382 1 __RU_l_____M_____________________ referenced,uptodate,lru,mmap 0x000100000000082c 12 0 __RU_l_____M_________________I___ referenced,uptodate,lru,mmap,readahead 0x0000000000000868 192 0 ___U_lA____M_____________________ uptodate,lru,active,mmap 0x0001000000000868 12 0 ___U_lA____M_________________I___ uptodate,lru,active,mmap,readahead 0x000000000000086c 800 3 __RU_lA____M_____________________ referenced,uptodate,lru,active,mmap 0x000100000000086c 31 0 __RU_lA____M_________________I___ referenced,uptodate,lru,active,mmap,readahead 0x0000000000004878 2 0 ___UDlA____M__b__________________ uptodate,dirty,lru,active,mmap,swapbacked 0x0000000000001000 492 1 ____________a____________________ anonymous 0x0000000000005808 4 0 ___U_______Ma_b__________________ uptodate,mmap,anonymous,swapbacked 0x0000000000005868 2839 11 ___U_lA____Ma_b__________________ uptodate,lru,active,mmap,anonymous,swapbacked 0x000000000000586c 30 0 __RU_lA____Ma_b__________________ referenced,uptodate,lru,active,mmap,anonymous,swapbacked total 513968 2007 # ./page-types -r flags page-count MB symbolic-flags long-symbolic-flags 0x0000000000000000 468002 1828 _________________________________ 0x0000000100000000 19102 74 _____________________r___________ reserved 0x0000000000008000 41 0 _______________H_________________ compound_head 0x0000000000010000 188 0 ________________T________________ compound_tail 0x0000000000008014 1 0 __R_D__________H_________________ referenced,dirty,compound_head 0x0000000000010014 4 0 __R_D___________T________________ referenced,dirty,compound_tail 0x0000000000000020 1 0 _____l___________________________ lru 0x0000000800000024 34 0 __R__l__________________P________ referenced,lru,private 0x0000000000000028 3794 14 ___U_l___________________________ uptodate,lru 0x0001000000000028 46 0 ___U_l_______________________I___ uptodate,lru,readahead 0x0000000400000028 44 0 ___U_l_________________d_________ uptodate,lru,mappedtodisk 0x0001000400000028 2 0 ___U_l_________________d_____I___ uptodate,lru,mappedtodisk,readahead 0x000000000000002c 6434 25 __RU_l___________________________ referenced,uptodate,lru 0x000100000000002c 47 0 __RU_l_______________________I___ referenced,uptodate,lru,readahead 0x000000040000002c 14 0 __RU_l_________________d_________ referenced,uptodate,lru,mappedtodisk 0x000000080000002c 30 0 __RU_l__________________P________ referenced,uptodate,lru,private 0x0000000800000040 8124 31 ______A_________________P________ active,private 0x0000000000000040 219 0 ______A__________________________ active 0x0000000800000060 1 0 _____lA_________________P________ lru,active,private 0x0000000000000068 322 1 ___U_lA__________________________ uptodate,lru,active 0x0001000000000068 12 0 ___U_lA______________________I___ uptodate,lru,active,readahead 0x0000000400000068 13 0 ___U_lA________________d_________ uptodate,lru,active,mappedtodisk 0x0000000800000068 12 0 ___U_lA_________________P________ uptodate,lru,active,private 0x000000000000006c 977 3 __RU_lA__________________________ referenced,uptodate,lru,active 0x000100000000006c 48 0 __RU_lA______________________I___ referenced,uptodate,lru,active,readahead 0x000000040000006c 5 0 __RU_lA________________d_________ referenced,uptodate,lru,active,mappedtodisk 0x000000080000006c 3 0 __RU_lA_________________P________ referenced,uptodate,lru,active,private 0x0000000c0000006c 3 0 __RU_lA________________dP________ referenced,uptodate,lru,active,mappedtodisk,private 0x0000000c00000068 1 0 ___U_lA________________dP________ uptodate,lru,active,mappedtodisk,private 0x0000000000004078 1 0 ___UDlA_______b__________________ uptodate,dirty,lru,active,swapbacked 0x000000000000407c 34 0 __RUDlA_______b__________________ referenced,uptodate,dirty,lru,active,swapbacked 0x0000000000000400 538 2 __________B______________________ buddy 0x0000000000000804 1 0 __R________M_____________________ referenced,mmap 0x0000000000000828 1029 4 ___U_l_____M_____________________ uptodate,lru,mmap 0x0001000000000828 43 0 ___U_l_____M_________________I___ uptodate,lru,mmap,readahead 0x000000000000082c 382 1 __RU_l_____M_____________________ referenced,uptodate,lru,mmap 0x000100000000082c 12 0 __RU_l_____M_________________I___ referenced,uptodate,lru,mmap,readahead 0x0000000000000868 192 0 ___U_lA____M_____________________ uptodate,lru,active,mmap 0x0001000000000868 12 0 ___U_lA____M_________________I___ uptodate,lru,active,mmap,readahead 0x000000000000086c 800 3 __RU_lA____M_____________________ referenced,uptodate,lru,active,mmap 0x000100000000086c 31 0 __RU_lA____M_________________I___ referenced,uptodate,lru,active,mmap,readahead 0x0000000000004878 2 0 ___UDlA____M__b__________________ uptodate,dirty,lru,active,mmap,swapbacked 0x0000000000001000 492 1 ____________a____________________ anonymous 0x0000000000005008 2 0 ___U________a_b__________________ uptodate,anonymous,swapbacked 0x0000000000005808 4 0 ___U_______Ma_b__________________ uptodate,mmap,anonymous,swapbacked 0x000000000000580c 1 0 __RU_______Ma_b__________________ referenced,uptodate,mmap,anonymous,swapbacked 0x0000000000005868 2839 11 ___U_lA____Ma_b__________________ uptodate,lru,active,mmap,anonymous,swapbacked 0x000000000000586c 29 0 __RU_lA____Ma_b__________________ referenced,uptodate,lru,active,mmap,anonymous,swapbacked total 513968 2007 # ./page-types --raw --list --no-summary --bits reserved offset count flags 0 15 _____________________r___________ 31 4 _____________________r___________ 159 97 _____________________r___________ 4096 2067 _____________________r___________ 6752 2390 _____________________r___________ 9355 3 _____________________r___________ 9728 14526 _____________________r___________ This patch: Introduce PageHuge(), which identifies huge/gigantic pages by their dedicated compound destructor functions. Also move prep_compound_gigantic_page() to hugetlb.c and make __free_pages_ok() non-static. Signed-off-by: Wu Fengguang <fengguang.wu@intel.com> Cc: KOSAKI Motohiro <kosaki.motohiro@jp.fujitsu.com> Cc: Andi Kleen <andi@firstfloor.org> Cc: Matt Mackall <mpm@selenic.com> Cc: Alexey Dobriyan <adobriyan@gmail.com> Cc: Ingo Molnar <mingo@elte.hu> Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
Diffstat (limited to 'include/linux/hugetlb.h')
-rw-r--r--include/linux/hugetlb.h7
1 files changed, 7 insertions, 0 deletions
diff --git a/include/linux/hugetlb.h b/include/linux/hugetlb.h
index 03be7f29ca0..a05a5ef3339 100644
--- a/include/linux/hugetlb.h
+++ b/include/linux/hugetlb.h
@@ -11,6 +11,8 @@
struct ctl_table;
+int PageHuge(struct page *page);
+
static inline int is_vm_hugetlb_page(struct vm_area_struct *vma)
{
return vma->vm_flags & VM_HUGETLB;
@@ -61,6 +63,11 @@ void hugetlb_change_protection(struct vm_area_struct *vma,
#else /* !CONFIG_HUGETLB_PAGE */
+static inline int PageHuge(struct page *page)
+{
+ return 0;
+}
+
static inline int is_vm_hugetlb_page(struct vm_area_struct *vma)
{
return 0;
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
# Authors: Rob Crittenden <rcritten@redhat.com>
#          Ade Lee <alee@redhat.com>
#          Andrew Wnuk <awnuk@redhat.com>
#
# Copyright (C) 2009  Red Hat
# see file 'COPYING' for use and warranty information
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

import array
import base64
import binascii
import ConfigParser
import dbus
import httplib
import ldap
import os
import pwd
import re
import shutil
import stat
import subprocess
import sys
import syslog
import time
import tempfile
import urllib
import xml.dom.minidom

from ipalib import api
from ipalib import pkcs10, x509
from ipalib import errors

from ipaplatform import services
from ipaplatform.paths import paths
from ipaplatform.tasks import tasks

from ipapython import dogtag
from ipapython import certmonger
from ipapython import ipautil
from ipapython import ipaldap
from ipapython.certdb import get_ca_nickname
from ipapython.dn import DN
from ipapython.ipa_log_manager import *

from ipaserver.install import certs
from ipaserver.install import dsinstance
from ipaserver.install import installutils
from ipaserver.install import service
from ipaserver.install.dogtaginstance import DogtagInstance
from ipaserver.install.dogtaginstance import PKI_USER, DEFAULT_DSPORT
from ipaserver.plugins import ldap2


# When IPA is installed with DNS support, this CNAME should hold all IPA
# replicas with CA configured
IPA_CA_RECORD = "ipa-ca"

# We need to reset the template because the CA uses the regular boot
# information
INF_TEMPLATE = """
[General]
FullMachineName=   $FQDN
SuiteSpotUserID=   $USER
SuiteSpotGroup=    $GROUP
ServerRoot=    $SERVER_ROOT
[slapd]
ServerPort=   $DSPORT
ServerIdentifier=   $SERVERID
Suffix=   $SUFFIX
RootDN=   cn=Directory Manager
RootDNPwd= $PASSWORD
ConfigFile = /usr/share/pki/ca/conf/database.ldif
"""


def get_preop_pin(instance_root, instance_name):
    # Only used for Dogtag 9
    preop_pin = None

    filename = instance_root + "/" + instance_name + "/conf/CS.cfg"

    # read the config file and get the preop pin
    try:
        f = open(filename)
    except IOError, e:
        root_logger.error("Cannot open configuration file." + str(e))
        raise e
    data = f.read()
    data = data.split('\n')
    pattern = re.compile("preop.pin=(.*)")
    for line in data:
        match = re.search(pattern, line)
        if match:
            preop_pin = match.group(1)
            break

    if preop_pin is None:
        raise RuntimeError("Unable to find preop.pin in %s. Is your CA already configured?" % filename)

    return preop_pin


def import_pkcs12(input_file, input_passwd, cert_database,
                  cert_passwd):
    ipautil.run([paths.PK12UTIL, "-d", cert_database,
                 "-i", input_file,
                 "-k", cert_passwd,
                 "-w", input_passwd])


def get_value(s):
    """
    Parse out a name/value pair from a Javascript variable.
    """
    try:
        expr = s.split('=', 1)
        value = expr[1]
        value = value.replace('\"', '')
        value = value.replace(';', '')
        value = value.replace('\\n', '\n')
        value = value.replace('\\r', '\r')
        return value
    except IndexError:
        return None


def find_substring(data, value):
    """
    Scan through a list looking for a string that starts with value.
    """
    for d in data:
        if d.startswith(value):
            return get_value(d)


def get_defList(data):
    """
    Return a dictionary of defList name/value pairs.

    A certificate signing request is specified as a series of these.
    """
    varname = None
    value = None
    skip = False
    defdict = {}
    for d in data:
        if d.startswith("defList = new Object"):
            varname = None
            value = None
            skip = False
        if d.startswith("defList.defId"):
            varname = get_value(d)
        if d.startswith("defList.defVal"):
            value = get_value(d)
            if skip:
                varname = None
                value = None
                skip = False
        if d.startswith("defList.defConstraint"):
            ctype = get_value(d)
            if ctype == "readonly":
                skip = True

        if varname and value:
            defdict[varname] = value
            varname = None
            value = None

    return defdict


def get_outputList(data):
    """
    Return a dictionary of outputList name/value pairs.

    The output from issuing a certificate is a series of these.
    """
    varname = None
    value = None
    outputdict = {}
    for d in data:
        if d.startswith("outputList = new"):
            varname = None
            value = None
        if d.startswith("outputList.outputId"):
            varname = get_value(d)
        if d.startswith("outputList.outputVal"):
            value = get_value(d)

        if varname and value:
            outputdict[varname] = value
            varname = None
            value = None

    return outputdict


def get_crl_files(path=None):
    """
    Traverse dogtag's CRL files in default CRL publish directory or in chosen
    target directory.

    @param path Custom target directory
    """
    if path is None:
        path = dogtag.configured_constants().CRL_PUBLISH_PATH

    files = os.listdir(path)
    for f in files:
        if f == "MasterCRL.bin":
            yield os.path.join(path, f)
        elif f.endswith(".der"):
            yield os.path.join(path, f)


def is_step_one_done():
    """Read CS.cfg and determine if step one of an external CA install is done
    """
    path = dogtag.install_constants.CS_CFG_PATH
    if not os.path.exists(path):
        return False
    test = installutils.get_directive(path, 'preop.ca.type', '=')
    if test == "otherca":
        return True
    return False


class CADSInstance(service.Service):
    """Certificate Authority DS instance

    The CA DS was used with Dogtag 9. Only upgraded installations still use it.
    Thus this class only does uninstallation.
    """
    def __init__(self, host_name=None, realm_name=None, domain_name=None, dm_password=None, dogtag_constants=None):
        service.Service.__init__(
            self, "pkids",
            service_desc="directory server for the CA",
            dm_password=dm_password,
            ldapi=False,
            autobind=service.DISABLED)

        self.serverid = "PKI-IPA"
        self.realm = realm_name
        self.sub_dict = None
        self.domain = domain_name
        self.fqdn = host_name
        self.dercert = None
        self.pkcs12_info = None
        self.ds_port = None
        self.master_host = None
        self.nickname = 'Server-Cert'
        self.subject_base = None

    def uninstall(self):
        if self.is_configured():
            self.print_msg("Unconfiguring CA directory server")

        enabled = self.restore_state("enabled")
        serverid = self.restore_state("serverid")

        # Just eat this state if it exists
        _running = self.restore_state("running")

        if not enabled is None and not enabled:
            services.knownservices.dirsrv.disable()

        if not serverid is None:
            # drop the trailing / off the config_dirname so the directory
            # will match what is in certmonger
            dirname = dsinstance.config_dirname(serverid)[:-1]
            dsdb = certs.CertDB(self.realm, nssdir=dirname)
            dsdb.untrack_server_cert("Server-Cert")
            dsinstance.erase_ds_instance_data(serverid)

        _user_exists = self.restore_state("user_exists")

        # At one time we removed this user on uninstall. That can potentially
        # orphan files, or worse, if another useradd runs in the interim,
        # cause files to have a new owner.


class CAInstance(DogtagInstance):
    """
    When using a dogtag CA the DS database contains just the
    server cert for DS. The mod_nss database will contain the RA agent
    cert that will be used to do authenticated requests against dogtag.

    This is done because we use python-nss and will inherit the opened
    NSS database in mod_python. In nsslib.py we do an nssinit but this will
    return success if the database is already initialized. It doesn't care
    if the database is different or not.

    external is a state machine:
       0 = not an externally signed CA
       1 = generating CSR to be signed
       2 = have signed cert, continue installation
    """

    def __init__(self, realm, ra_db, dogtag_constants=None):
        if dogtag_constants is None:
            dogtag_constants = dogtag.configured_constants()

        DogtagInstance.__init__(self, realm, "CA", "certificate server",
                                dogtag_constants)

        # for external CAs
        self.external = 0
        self.csr_file = None
        self.cert_file = None
        self.cert_chain_file = None
        self.create_ra_agent_db = True

        self.canickname = get_ca_nickname(realm)
        self.ra_agent_db = ra_db
        self.ra_agent_pwd = self.ra_agent_db + "/pwdfile.txt"
        self.ra_cert = None
        self.requestId = None
        self.tracking_nicknames = ['Server-Cert cert-pki-ca',
                                   'auditSigningCert cert-pki-ca',
                                   'ocspSigningCert cert-pki-ca',
                                   'subsystemCert cert-pki-ca']

    def configure_instance(self, host_name, domain, dm_password,
                           admin_password, ds_port=DEFAULT_DSPORT,
                           pkcs12_info=None, master_host=None, csr_file=None,
                           cert_file=None, cert_chain_file=None,
                           master_replication_port=None,
                           subject_base=None):
        """Create a CA instance.

           For Dogtag 9, this may involve creating the pki-ca instance.

           To create a clone, pass in pkcs12_info.

           Creating a CA with an external signer is a 2-step process. In
           step 1 we generate a CSR. In step 2 we are given the cert and
           chain and actually proceed to create the CA. For step 1 set
           csr_file. For step 2 set cert_file and cert_chain_file.
        """
        self.fqdn = host_name
        self.domain = domain
        self.dm_password = dm_password
        self.admin_password = admin_password
        self.ds_port = ds_port
        self.pkcs12_info = pkcs12_info
        if self.pkcs12_info is not None:
            self.clone = True
        self.master_host = master_host
        self.master_replication_port = master_replication_port
        if subject_base is None:
            self.subject_base = DN(('O', self.realm))
        else:
            self.subject_base = subject_base

        # Determine if we are installing as an externally-signed CA and
        # what stage we're in.
        if csr_file is not None:
            self.csr_file = csr_file
            self.external = 1
        elif cert_file is not None:
            self.cert_file = cert_file
            self.cert_chain_file = cert_chain_file
            self.external = 2

        self.step("creating certificate server user", self.__create_ca_user)
        if self.dogtag_constants.DOGTAG_VERSION >= 10:
            self.step("configuring certificate server instance", self.__spawn_instance)
        else:
            if not ipautil.dir_exists(paths.VAR_LIB_PKI_CA_DIR):
                self.step("creating pki-ca instance", self.create_instance)
            self.step("configuring certificate server instance", self.__configure_instance)
        self.step("stopping certificate server instance to update CS.cfg", self.stop_instance)
        self.step("disabling nonces", self.__disable_nonce)
        self.step("set up CRL publishing", self.__enable_crl_publish)
        self.step("starting certificate server instance", self.start_instance)
        # Step 1 of external is getting a CSR so we don't need to do these
        # steps until we get a cert back from the external CA.
        if self.external != 1:
            if self.dogtag_constants.DOGTAG_VERSION < 10 and not self.clone:
                self.step("creating CA agent PKCS#12 file in /root", self.__create_ca_agent_pkcs12)
            if self.create_ra_agent_db:
                self.step("creating RA agent certificate database", self.__create_ra_agent_db)
            self.step("importing CA chain to RA certificate database", self.__import_ca_chain)
            self.step("fixing RA database permissions", self.fix_ra_perms)
            self.step("setting up signing cert profile", self.__setup_sign_profile)
            self.step("set certificate subject base", self.__set_subject_in_config)
            self.step("enabling Subject Key Identifier", self.enable_subject_key_identifier)
            self.step("enabling Subject Alternative Name", self.enable_subject_alternative_name)
            self.step("enabling CRL and OCSP extensions for certificates", self.__set_crl_ocsp_extensions)
            self.step("setting audit signing renewal to 2 years", self.set_audit_renewal)
            self.step("configuring certificate server to start on boot",
                      self.enable)
            if not self.clone:
                self.step("restarting certificate server", self.restart_instance)
                self.step("requesting RA certificate from CA", self.__request_ra_certificate)
                self.step("issuing RA agent certificate", self.__issue_ra_cert)
                self.step("adding RA agent as a trusted user", self.__configure_ra)
            self.step("configure certmonger for renewals", self.configure_certmonger_renewal)
            self.step("configure certificate renewals", self.configure_cert_renewal)
            if not self.clone:
                self.step("configure RA certificate renewal", self.configure_agent_renewal)
            self.step("configure Server-Cert certificate renewal", self.track_servercert)
            self.step("Configure HTTP to proxy connections",
                      self.http_proxy)

        self.start_creation(runtime=210)

    def enable(self):
        DogtagInstance.enable(self)

    def start_instance(self):
        DogtagInstance.start_instance(self)

    def stop_instance(self):
        DogtagInstance.stop_instance(self)

    def restart_instance(self):
        DogtagInstance.restart_instance(self)

    def http_proxy(self):
        DogtagInstance.http_proxy(self)

    def __spawn_instance(self):
        """
        Create and configure a new CA instance using pkispawn.
        Creates the config file with IPA specific parameters
        and passes it to the base class to call pkispawn
        """

        # Create an empty and secured file
        (cfg_fd, cfg_file) = tempfile.mkstemp()
        os.close(cfg_fd)
        pent = pwd.getpwnam(PKI_USER)
        os.chown(cfg_file, pent.pw_uid, pent.pw_gid)

        # Create CA configuration
        config = ConfigParser.ConfigParser()
        config.optionxform = str
        config.add_section("CA")

        # Server
        config.set("CA", "pki_security_domain_name", self.security_domain_name)
        config.set("CA", "pki_enable_proxy", "True")
        config.set("CA", "pki_restart_configured_instance", "False")
        config.set("CA", "pki_backup_keys", "True")
        config.set("CA", "pki_backup_password", self.admin_password)

        # Client security database
        config.set("CA", "pki_client_database_dir", self.agent_db)
        config.set("CA", "pki_client_database_password", self.admin_password)
        config.set("CA", "pki_client_database_purge", "False")
        config.set("CA", "pki_client_pkcs12_password", self.admin_password)

        # Administrator
        config.set("CA", "pki_admin_name", "admin")
        config.set("CA", "pki_admin_uid", "admin")
        config.set("CA", "pki_admin_email", "root@localhost")
        config.set("CA", "pki_admin_password", self.admin_password)
        config.set("CA", "pki_admin_nickname", "ipa-ca-agent")
        config.set("CA", "pki_admin_subject_dn",
            str(DN(('cn', 'ipa-ca-agent'), self.subject_base)))
        config.set("CA", "pki_client_admin_cert_p12", paths.CA_AGENT_P12)

        # Directory server
        config.set("CA", "pki_ds_ldap_port", str(self.ds_port))
        config.set("CA", "pki_ds_password", self.dm_password)
        config.set("CA", "pki_ds_base_dn", self.basedn)
        config.set("CA", "pki_ds_database", "ipaca")

        # Certificate subject DN's
        config.set("CA", "pki_subsystem_subject_dn",
            str(DN(('cn', 'CA Subsystem'), self.subject_base)))
        config.set("CA", "pki_ocsp_signing_subject_dn",
            str(DN(('cn', 'OCSP Subsystem'), self.subject_base)))
        config.set("CA", "pki_ssl_server_subject_dn",
            str(DN(('cn', self.fqdn), self.subject_base)))
        config.set("CA", "pki_audit_signing_subject_dn",
            str(DN(('cn', 'CA Audit'), self.subject_base)))
        config.set("CA", "pki_ca_signing_subject_dn",
            str(DN(('cn', 'Certificate Authority'), self.subject_base)))

        # Certificate nicknames
        config.set("CA", "pki_subsystem_nickname", "subsystemCert cert-pki-ca")
        config.set("CA", "pki_ocsp_signing_nickname", "ocspSigningCert cert-pki-ca")
        config.set("CA", "pki_ssl_server_nickname", "Server-Cert cert-pki-ca")
        config.set("CA", "pki_audit_signing_nickname", "auditSigningCert cert-pki-ca")
        config.set("CA", "pki_ca_signing_nickname", "caSigningCert cert-pki-ca")

        if self.clone:
            cafile = self.pkcs12_info[0]
            shutil.copy(cafile, paths.TMP_CA_P12)
            pent = pwd.getpwnam(PKI_USER)
            os.chown(paths.TMP_CA_P12, pent.pw_uid, pent.pw_gid)

            # Security domain registration
            config.set("CA", "pki_security_domain_hostname", self.master_host)
            config.set("CA", "pki_security_domain_https_port", "443")
            config.set("CA", "pki_security_domain_user", "admin")
            config.set("CA", "pki_security_domain_password", self.admin_password)

            # Clone
            config.set("CA", "pki_clone", "True")
            config.set("CA", "pki_clone_pkcs12_path", paths.TMP_CA_P12)
            config.set("CA", "pki_clone_pkcs12_password", self.dm_password)
            config.set("CA", "pki_clone_replication_security", "TLS")
            config.set("CA", "pki_clone_replication_master_port", str(self.master_replication_port))
            config.set("CA", "pki_clone_replication_clone_port", dogtag.install_constants.DS_PORT)
            config.set("CA", "pki_clone_replicate_schema", "False")
            config.set("CA", "pki_clone_uri", "https://%s" % ipautil.format_netloc(self.master_host, 443))

        # External CA
        if self.external == 1:
            config.set("CA", "pki_external", "True")
            config.set("CA", "pki_external_csr_path", self.csr_file)

        elif self.external == 2:
            config.set("CA", "pki_external", "True")
            config.set("CA", "pki_external_ca_cert_path", self.cert_file)
            config.set("CA", "pki_external_ca_cert_chain_path", self.cert_chain_file)
            config.set("CA", "pki_external_step_two", "True")

        # Generate configuration file
        with open(cfg_file, "wb") as f:
            config.write(f)

        try:
            DogtagInstance.spawn_instance(self, cfg_file)
        finally:
            os.remove(cfg_file)

        if self.external == 1:
            print "The next step is to get %s signed by your CA and re-run ipa-server-install as:" % self.csr_file
            print "ipa-server-install --external_cert_file=/path/to/signed_certificate --external_ca_file=/path/to/external_ca_certificate"
            sys.exit(0)
        else:
            shutil.move(paths.CA_BACKUP_KEYS_P12,
                        paths.CACERT_P12)

        root_logger.debug("completed creating ca instance")

    def create_instance(self):
        """
        If for some reason the instance doesn't exist, create a new one."
        """
        # Only used for Dogtag 9

        args = [paths.PKICREATE,
                '-pki_instance_root', paths.VAR_LIB,
                '-pki_instance_name',
                        self.dogtag_constants.PKI_INSTANCE_NAME,
                '-subsystem_type', 'ca',
                '-agent_secure_port',
                        str(self.dogtag_constants.AGENT_SECURE_PORT),
                '-ee_secure_port',
                        str(self.dogtag_constants.EE_SECURE_PORT),
                '-admin_secure_port',
                        str(self.dogtag_constants.ADMIN_SECURE_PORT),
                '-ee_secure_client_auth_port',
                        str(self.dogtag_constants.EE_CLIENT_AUTH_PORT),
                '-unsecure_port', str(self.dogtag_constants.UNSECURE_PORT),
                '-tomcat_server_port',
                        str(self.dogtag_constants.TOMCAT_SERVER_PORT),
                '-redirect', 'conf=/etc/pki-ca',
                '-redirect', 'logs=/var/log/pki-ca',
                '-enable_proxy'
        ]
        ipautil.run(args, env={'PKI_HOSTNAME':self.fqdn})

    @staticmethod
    def __create_ca_user():
        try:
            pwd.getpwnam(PKI_USER)
            root_logger.debug("ca user %s exists" % PKI_USER)
        except KeyError:
            root_logger.debug("adding ca user %s" % PKI_USER)
            args = [paths.USERADD, "-c", "CA System User",
                                         "-d", paths.VAR_LIB,
                                         "-s", paths.NOLOGIN,
                                         "-M", "-r", PKI_USER]
            try:
                ipautil.run(args)
                root_logger.debug("done adding user")
            except ipautil.CalledProcessError, e:
                root_logger.critical("failed to add user %s" % e)

    def __configure_instance(self):
        # Only used for Dogtag 9
        preop_pin = get_preop_pin(
            self.server_root, self.dogtag_constants.PKI_INSTANCE_NAME)

        try:
            args = [paths.PERL, paths.PKISILENT,  "ConfigureCA",
                    "-cs_hostname", self.fqdn,
                    "-cs_port", str(self.dogtag_constants.ADMIN_SECURE_PORT),
                    "-client_certdb_dir", self.agent_db,
                    "-client_certdb_pwd", self.admin_password,
                    "-preop_pin" , preop_pin,
                    "-domain_name", self.security_domain_name,
                    "-admin_user", "admin",
                    "-admin_email",  "root@localhost",
                    "-admin_password", self.admin_password,
                    "-agent_name", "ipa-ca-agent",
                    "-agent_key_size", "2048",
                    "-agent_key_type", "rsa",
                    "-agent_cert_subject", str(DN(('CN', 'ipa-ca-agent'), self.subject_base)),
                    "-ldap_host", self.fqdn,
                    "-ldap_port", str(self.ds_port),
                    "-bind_dn", "cn=Directory Manager",
                    "-bind_password", self.dm_password,
                    "-base_dn", str(self.basedn),
                    "-db_name", "ipaca",
                    "-key_size", "2048",
                    "-key_type", "rsa",
                    "-key_algorithm", "SHA256withRSA",
                    "-save_p12", "true",
                    "-backup_pwd", self.admin_password,
                    "-subsystem_name", self.service_name,
                    "-token_name", "internal",
                    "-ca_subsystem_cert_subject_name", str(DN(('CN', 'CA Subsystem'), self.subject_base)),
                    "-ca_subsystem_cert_subject_name", str(DN(('CN', 'CA Subsystem'), self.subject_base)),
                    "-ca_ocsp_cert_subject_name", str(DN(('CN', 'OCSP Subsystem'), self.subject_base)),
                    "-ca_server_cert_subject_name", str(DN(('CN', self.fqdn), self.subject_base)),
                    "-ca_audit_signing_cert_subject_name", str(DN(('CN', 'CA Audit'), self.subject_base)),
                    "-ca_sign_cert_subject_name", str(DN(('CN', 'Certificate Authority'), self.subject_base)) ]
            if self.external == 1:
                args.append("-external")
                args.append("true")
                args.append("-ext_csr_file")
                args.append(self.csr_file)
            elif self.external == 2:
                args.append("-external")
                args.append("true")
                args.append("-ext_ca_cert_file")
                args.append(self.cert_file)
                args.append("-ext_ca_cert_chain_file")
                args.append(self.cert_chain_file)
            else:
                args.append("-external")
                args.append("false")
            if self.clone:
                """sd = security domain -->  all CS systems get registered to
                   a security domain. This is set to the hostname and port of
                   the master CA.
                """
                # The install wizard expects the file to be here.
                cafile = self.pkcs12_info[0]
                shutil.copy(cafile, paths.PKI_ALIAS_CA_P12)
                pent = pwd.getpwnam(PKI_USER)
                os.chown(paths.PKI_ALIAS_CA_P12, pent.pw_uid, pent.pw_gid )
                args.append("-clone")
                args.append("true")
                args.append("-clone_p12_file")
                args.append("ca.p12")
                args.append("-clone_p12_password")
                args.append(self.dm_password)
                args.append("-sd_hostname")
                args.append(self.master_host)
                args.append("-sd_admin_port")
                args.append("443")
                args.append("-sd_admin_name")
                args.append("admin")
                args.append("-sd_admin_password")
                args.append(self.admin_password)
                args.append("-clone_master_port")
                args.append(str(self.master_replication_port))
                args.append("-clone_start_tls")
                args.append("true")
                args.append("-clone_uri")
                args.append("https://%s" % ipautil.format_netloc(self.master_host, 443))
            else:
                args.append("-clone")
                args.append("false")

            # Define the things we don't want logged
            nolog = (self.admin_password, self.dm_password,)

            ipautil.run(args, env={'PKI_HOSTNAME':self.fqdn}, nolog=nolog)
        except ipautil.CalledProcessError, e:
            root_logger.critical("failed to configure ca instance %s" % e)
            raise RuntimeError('Configuration of CA failed')

        if self.external == 1:
            print "The next step is to get %s signed by your CA and re-run ipa-server-install as:" % self.csr_file
            print "ipa-server-install --external_cert_file=/path/to/signed_certificate --external_ca_file=/path/to/external_ca_certificate"
            sys.exit(0)

        # pkisilent makes a copy of the CA PKCS#12 file for us but gives
        # it a lousy name.
        if ipautil.file_exists(paths.ROOT_TMP_CA_P12):
            shutil.move(paths.ROOT_TMP_CA_P12, paths.CACERT_P12)

        root_logger.debug("completed creating ca instance")

    def __disable_nonce(self):
        # Turn off Nonces
        update_result = installutils.update_file(
            self.dogtag_constants.CS_CFG_PATH, 'ca.enableNonces=true',
            'ca.enableNonces=false')
        if update_result != 0:
            raise RuntimeError("Disabling nonces failed")
        pent = pwd.getpwnam(PKI_USER)
        os.chown(self.dogtag_constants.CS_CFG_PATH,
                 pent.pw_uid, pent.pw_gid)

    def __issue_ra_cert(self):
        # The CA certificate is in the agent DB but isn't trusted
        (admin_fd, admin_name) = tempfile.mkstemp()
        os.write(admin_fd, self.admin_password)
        os.close(admin_fd)

        # Look through the cert chain to get all the certs we need to add
        # trust for
        p = subprocess.Popen([paths.CERTUTIL, "-d", self.agent_db,
                              "-O", "-n", "ipa-ca-agent"], stdout=subprocess.PIPE)

        chain = p.stdout.read()
        chain = chain.split("\n")

        root_nickname=[]
        for i in xrange(len(chain)):
            m = re.match('\ *"(.*)" \[.*', chain[i])
            if m:
                nick = m.groups(0)[0]
                if nick != "ipa-ca-agent" and nick[:7] != "Builtin":
                    root_nickname.append(m.groups()[0])

        try:
            for nick in root_nickname:
                self.__run_certutil(
                    ['-M', '-t', 'CT,C,C', '-n',
                     nick],
                     database=self.agent_db, pwd_file=self.admin_password)
        finally:
            os.remove(admin_name)

        # Retrieve the certificate request so we can get the values needed
        # to issue a certificate. Use sslget here because this is a
        # temporary database and nsslib doesn't currently support gracefully
        # opening and closing an NSS database. This would leave the installer
        # process stuck using this database during the entire cycle. We need
        # to use the final RA agent database when issuing certs for DS and
        # mod_nss.
        args = [
            paths.SSLGET,
            '-v',
            '-n', 'ipa-ca-agent',
            '-p', self.admin_password,
            '-d', self.agent_db,
            '-r', '/ca/agent/ca/profileReview?requestId=%s' % self.requestId,
            '%s' % ipautil.format_netloc(
                self.fqdn, self.dogtag_constants.AGENT_SECURE_PORT),
        ]
        (stdout, _stderr, _returncode) = ipautil.run(
            args, nolog=(self.admin_password,))

        data = stdout.split(self.dogtag_constants.RACERT_LINE_SEP)
        params = get_defList(data)
        params['requestId'] = find_substring(data, "requestId")
        params['op'] = 'approve'
        params['submit'] = 'submit'
        params['requestNotes'] = ''
        params = urllib.urlencode(params)

        # Now issue the RA certificate.
        args = [
            paths.SSLGET,
            '-v',
            '-n', 'ipa-ca-agent',
            '-p', self.admin_password,
            '-d', self.agent_db,
            '-e', params,
            '-r', '/ca/agent/ca/profileProcess',
            '%s' % ipautil.format_netloc(
                self.fqdn, self.dogtag_constants.AGENT_SECURE_PORT),
        ]
        (stdout, _stderr, _returncode) = ipautil.run(
            args, nolog=(self.admin_password,))

        data = stdout.split(self.dogtag_constants.RACERT_LINE_SEP)
        outputList = get_outputList(data)

        self.ra_cert = outputList['b64_cert']

        # Strip certificate headers and convert it to proper line ending
        self.ra_cert = x509.strip_header(self.ra_cert)
        self.ra_cert = "\n".join(line.strip() for line
                                 in self.ra_cert.splitlines() if line.strip())

        # Add the new RA cert to the database in /etc/httpd/alias
        (agent_fd, agent_name) = tempfile.mkstemp()
        os.write(agent_fd, self.ra_cert)
        os.close(agent_fd)
        try:
            self.__run_certutil(
                ['-A', '-t', 'u,u,u', '-n', 'ipaCert', '-a',
                 '-i', agent_name]
            )
        finally:
            os.remove(agent_name)

    def import_ra_cert(self, rafile):
        """
        Cloned RAs will use the same RA agent cert as the master so we
        need to import from a PKCS#12 file.

        Used when setting up replication
        """
        # Add the new RA cert to the database in /etc/httpd/alias
        (agent_fd, agent_name) = tempfile.mkstemp()
        os.write(agent_fd, self.dm_password)
        os.close(agent_fd)
        try:
            import_pkcs12(rafile, agent_name, self.ra_agent_db, self.ra_agent_pwd)
        finally:
            os.remove(agent_name)

        self.configure_agent_renewal()

    def __configure_ra(self):
        # Create an RA user in the CA LDAP server and add that user to
        # the appropriate groups so it can issue certificates without
        # manual intervention.
        conn = ipaldap.IPAdmin(self.fqdn, self.ds_port)
        conn.do_simple_bind(DN(('cn', 'Directory Manager')), self.dm_password)

        decoded = base64.b64decode(self.ra_cert)

        entry_dn = DN(('uid', "ipara"), ('ou', 'People'), self.basedn)
        entry = conn.make_entry(
            entry_dn,
            objectClass=['top', 'person', 'organizationalPerson',
                         'inetOrgPerson', 'cmsuser'],
            uid=["ipara"],
            sn=["ipara"],
            cn=["ipara"],
            usertype=["agentType"],
            userstate=["1"],
            userCertificate=[decoded],
            description=['2;%s;%s;%s' % (
                str(self.requestId),
                DN(('CN', 'Certificate Authority'), self.subject_base),
                DN(('CN', 'IPA RA'), self.subject_base))])

        conn.add_entry(entry)

        dn = DN(('cn', 'Certificate Manager Agents'), ('ou', 'groups'), self.basedn)
        modlist = [(0, 'uniqueMember', '%s' % entry_dn)]
        conn.modify_s(dn, modlist)

        dn = DN(('cn', 'Registration Manager Agents'), ('ou', 'groups'), self.basedn)
        modlist = [(0, 'uniqueMember', '%s' % entry_dn)]
        conn.modify_s(dn, modlist)

        conn.unbind()

    def __run_certutil(self, args, database=None, pwd_file=None, stdin=None):
        if not database:
            database = self.ra_agent_db
        if not pwd_file:
            pwd_file = self.ra_agent_pwd
        new_args = [paths.CERTUTIL, "-d", database, "-f", pwd_file]
        new_args = new_args + args
        return ipautil.run(new_args, stdin, nolog=(pwd_file,))

    def __create_ra_agent_db(self):
        if ipautil.file_exists(self.ra_agent_db + "/cert8.db"):
            ipautil.backup_file(self.ra_agent_db + "/cert8.db")
            ipautil.backup_file(self.ra_agent_db + "/key3.db")
            ipautil.backup_file(self.ra_agent_db + "/secmod.db")
            ipautil.backup_file(self.ra_agent_db + "/pwdfile.txt")

        if not ipautil.dir_exists(self.ra_agent_db):
            os.mkdir(self.ra_agent_db)

        # Create the password file for this db
        hex_str = binascii.hexlify(os.urandom(10))
        f = os.open(self.ra_agent_pwd, os.O_CREAT | os.O_RDWR)
        os.write(f, hex_str)
        os.close(f)
        os.chmod(self.ra_agent_pwd, stat.S_IRUSR)

        (_stdout, _stderr, _returncode) = self.__run_certutil(["-N"])

    def __get_ca_chain(self):
        try:
            return dogtag.get_ca_certchain(ca_host=self.fqdn,
                dogtag_constants=self.dogtag_constants)
        except Exception, e:
            raise RuntimeError("Unable to retrieve CA chain: %s" % str(e))

    def __create_ca_agent_pkcs12(self):
        # Only used for Dogtag 9
        (pwd_fd, pwd_name) = tempfile.mkstemp()
        os.write(pwd_fd, self.admin_password)
        os.close(pwd_fd)
        try:
            ipautil.run([paths.PK12UTIL,
                         "-n", "ipa-ca-agent",
                         "-o", DogtagInstance.AGENT_P12_PATH,
                         "-d", self.agent_db,
                         "-k", pwd_name,
                         "-w", pwd_name])
        finally:
            os.remove(pwd_name)

    def __import_ca_chain(self):
        chain = self.__get_ca_chain()

        # If this chain contains multiple certs then certutil will only import
        # the first one. So we have to pull them all out and import them
        # separately. Unfortunately no NSS tool can do this so we have to
        # use openssl.

        # Convert to DER because the chain comes back as one long string which
        # makes openssl throw up.
        data = base64.b64decode(chain)

        (certlist, _stderr, _returncode) = ipautil.run(
            [paths.OPENSSL,
             "pkcs7",
             "-inform",
             "DER",
             "-print_certs",
             ], stdin=data)

        # Ok, now we have all the certificates in certs, walk through it
        # and pull out each certificate and add it to our database

        st = 1
        en = 0
        subid = 0
        ca_dn = DN(('CN','Certificate Authority'), self.subject_base)
        while st > 0:
            st = certlist.find('-----BEGIN', en)
            en = certlist.find('-----END', en+1)
            if st > 0:
                try:
                    (chain_fd, chain_name) = tempfile.mkstemp()
                    os.write(chain_fd, certlist[st:en+25])
                    os.close(chain_fd)
                    (_rdn, subject_dn) = certs.get_cert_nickname(certlist[st:en+25])
                    if subject_dn == ca_dn:
                        nick = get_ca_nickname(self.realm)
                    else:
                        nick = str(subject_dn)
                    self.__run_certutil(
                        ['-A', '-t', 'CT,C,C', '-n', nick, '-a',
                         '-i', chain_name]
                    )
                finally:
                    os.remove(chain_name)
                    subid += 1

    def __request_ra_certificate(self):
        # Create a noise file for generating our private key
        noise = array.array('B', os.urandom(128))
        (noise_fd, noise_name) = tempfile.mkstemp()
        os.write(noise_fd, noise)
        os.close(noise_fd)

        # Generate our CSR. The result gets put into stdout
        try:
            (stdout, _stderr, _returncode) = self.__run_certutil(
                ["-R", "-k", "rsa", "-g", "2048", "-s",
                 str(DN(('CN', 'IPA RA'), self.subject_base)),
                 "-z", noise_name, "-a"])
        finally:
            os.remove(noise_name)

        csr = pkcs10.strip_header(stdout)

        # Send the request to the CA
        conn = httplib.HTTPConnection(
            self.fqdn, self.dogtag_constants.UNSECURE_PORT)
        params = urllib.urlencode({'profileId': 'caServerCert',
                'cert_request_type': 'pkcs10',
                'requestor_name': 'IPA Installer',
                'cert_request': csr,
                'xmlOutput': 'true'})
        headers = {"Content-type": "application/x-www-form-urlencoded",
                   "Accept": "text/plain"}

        conn.request("POST", "/ca/ee/ca/profileSubmit", params, headers)
        res = conn.getresponse()
        if res.status == 200:
            data = res.read()
            conn.close()
            doc = xml.dom.minidom.parseString(data)
            item_node = doc.getElementsByTagName("RequestId")
            self.requestId = item_node[0].childNodes[0].data
            doc.unlink()
            self.requestId = self.requestId.strip()
            if self.requestId is None:
                raise RuntimeError("Unable to determine RA certificate requestId")
        else:
            conn.close()
            raise RuntimeError("Unable to submit RA cert request")

    def fix_ra_perms(self):
        os.chmod(self.ra_agent_db + "/cert8.db", 0640)
        os.chmod(self.ra_agent_db + "/key3.db", 0640)
        os.chmod(self.ra_agent_db + "/secmod.db", 0640)

        pent = pwd.getpwnam("apache")
        os.chown(self.ra_agent_db + "/cert8.db", 0, pent.pw_gid )
        os.chown(self.ra_agent_db + "/key3.db", 0, pent.pw_gid )
        os.chown(self.ra_agent_db + "/secmod.db", 0, pent.pw_gid )
        os.chown(self.ra_agent_pwd, pent.pw_uid, pent.pw_gid)

    def __setup_sign_profile(self):
        # Tell the profile to automatically issue certs for RAs
        installutils.set_directive(self.dogtag_constants.SIGN_PROFILE,
                'auth.instance_id', 'raCertAuth', quotes=False, separator='=')

    def prepare_crl_publish_dir(self):
        """
        Prepare target directory for CRL publishing

        Returns a path to the CRL publishing directory
        """
        publishdir = self.dogtag_constants.CRL_PUBLISH_PATH

        if not os.path.exists(publishdir):
            os.mkdir(publishdir)

        os.chmod(publishdir, 0775)
        pent = pwd.getpwnam(PKI_USER)
        os.chown(publishdir, 0, pent.pw_gid)

        tasks.restore_context(publishdir)

        return publishdir

    def __set_crl_ocsp_extensions(self):
        self.set_crl_ocsp_extensions(self.domain, self.fqdn)

    def set_crl_ocsp_extensions(self, domain, fqdn):
        """
        Configure CRL and OCSP extensions in default IPA certificate profile
        if not done already.
        """
        changed = False

        # OCSP extension
        ocsp_url = 'http://%s.%s/ca/ocsp' % (IPA_CA_RECORD, ipautil.format_netloc(domain))

        ocsp_location_0 = installutils.get_directive(
            self.dogtag_constants.IPA_SERVICE_PROFILE,
            'policyset.serverCertSet.5.default.params.authInfoAccessADLocation_0',
            separator='=')

        if ocsp_location_0 != ocsp_url:
            # Set the first OCSP URI
            installutils.set_directive(self.dogtag_constants.IPA_SERVICE_PROFILE,
                'policyset.serverCertSet.5.default.params.authInfoAccessADLocation_0',
                ocsp_url, quotes=False, separator='=')
            changed = True

        ocsp_profile_count = installutils.get_directive(
            self.dogtag_constants.IPA_SERVICE_PROFILE,
            'policyset.serverCertSet.5.default.params.authInfoAccessNumADs',
            separator='=')

        if ocsp_profile_count != '1':
            installutils.set_directive(self.dogtag_constants.IPA_SERVICE_PROFILE,
                'policyset.serverCertSet.5.default.params.authInfoAccessNumADs',
                '1', quotes=False, separator='=')
            changed = True


        # CRL extension
        crl_url = 'http://%s.%s/ipa/crl/MasterCRL.bin'% (IPA_CA_RECORD, ipautil.format_netloc(domain))

        crl_point_0 = installutils.get_directive(
            self.dogtag_constants.IPA_SERVICE_PROFILE,
            'policyset.serverCertSet.9.default.params.crlDistPointsPointName_0',
            separator='=')

        if crl_point_0 != crl_url:
            installutils.set_directive(self.dogtag_constants.IPA_SERVICE_PROFILE,
                'policyset.serverCertSet.9.default.params.crlDistPointsIssuerName_0',
                'CN=Certificate Authority,o=ipaca', quotes=False, separator='=')
            installutils.set_directive(self.dogtag_constants.IPA_SERVICE_PROFILE,
                'policyset.serverCertSet.9.default.params.crlDistPointsIssuerType_0',
                'DirectoryName', quotes=False, separator='=')
            installutils.set_directive(self.dogtag_constants.IPA_SERVICE_PROFILE,
                'policyset.serverCertSet.9.default.params.crlDistPointsPointName_0',
                crl_url, quotes=False, separator='=')
            changed = True

        crl_profile_count = installutils.get_directive(
            self.dogtag_constants.IPA_SERVICE_PROFILE,
            'policyset.serverCertSet.9.default.params.crlDistPointsNum',
            separator='=')

        if crl_profile_count != '1':
            installutils.set_directive(self.dogtag_constants.IPA_SERVICE_PROFILE,
                'policyset.serverCertSet.9.default.params.crlDistPointsNum',
                '1', quotes=False, separator='=')
            changed = True

        # CRL extension is not enabled by default
        setlist = installutils.get_directive(self.dogtag_constants.IPA_SERVICE_PROFILE,
            'policyset.serverCertSet.list', separator='=')
        new_set_list = None

        if setlist == '1,2,3,4,5,6,7,8':
            new_set_list = '1,2,3,4,5,6,7,8,9'
        elif setlist == '1,2,3,4,5,6,7,8,10':
            new_set_list = '1,2,3,4,5,6,7,8,9,10'
        elif setlist == '1,2,3,4,5,6,7,8,10,11':
            new_set_list = '1,2,3,4,5,6,7,8,9,10,11'

        if new_set_list:
            installutils.set_directive(self.dogtag_constants.IPA_SERVICE_PROFILE,
                'policyset.serverCertSet.list',
                new_set_list, quotes=False, separator='=')
            changed = True

        return changed


    def __enable_crl_publish(self):
        """
        Enable file-based CRL publishing and disable LDAP publishing.

        https://access.redhat.com/knowledge/docs/en-US/Red_Hat_Certificate_System/8.0/html/Admin_Guide/Setting_up_Publishing.html
        """
        caconfig = self.dogtag_constants.CS_CFG_PATH

        publishdir = self.prepare_crl_publish_dir()

        # Enable file publishing, disable LDAP
        installutils.set_directive(caconfig, 'ca.publish.enable', 'true', quotes=False, separator='=')
        installutils.set_directive(caconfig, 'ca.publish.ldappublish.enable', 'false', quotes=False, separator='=')

        # Create the file publisher, der only, not b64
        installutils.set_directive(caconfig, 'ca.publish.publisher.impl.FileBasedPublisher.class','com.netscape.cms.publish.publishers.FileBasedPublisher', quotes=False, separator='=')
        installutils.set_directive(caconfig, 'ca.publish.publisher.instance.FileBaseCRLPublisher.crlLinkExt', 'bin', quotes=False, separator='=')
        installutils.set_directive(caconfig, 'ca.publish.publisher.instance.FileBaseCRLPublisher.directory', publishdir, quotes=False, separator='=')
        installutils.set_directive(caconfig, 'ca.publish.publisher.instance.FileBaseCRLPublisher.latestCrlLink', 'true', quotes=False, separator='=')
        installutils.set_directive(caconfig, 'ca.publish.publisher.instance.FileBaseCRLPublisher.pluginName', 'FileBasedPublisher', quotes=False, separator='=')
        installutils.set_directive(caconfig, 'ca.publish.publisher.instance.FileBaseCRLPublisher.timeStamp', 'LocalTime', quotes=False, separator='=')
        installutils.set_directive(caconfig, 'ca.publish.publisher.instance.FileBaseCRLPublisher.zipCRLs', 'false', quotes=False, separator='=')
        installutils.set_directive(caconfig, 'ca.publish.publisher.instance.FileBaseCRLPublisher.zipLevel', '9', quotes=False, separator='=')
        installutils.set_directive(caconfig, 'ca.publish.publisher.instance.FileBaseCRLPublisher.Filename.b64', 'false', quotes=False, separator='=')
        installutils.set_directive(caconfig, 'ca.publish.publisher.instance.FileBaseCRLPublisher.Filename.der', 'true', quotes=False, separator='=')

        # The publishing rule
        installutils.set_directive(caconfig, 'ca.publish.rule.instance.FileCrlRule.enable', 'true', quotes=False, separator='=')
        installutils.set_directive(caconfig, 'ca.publish.rule.instance.FileCrlRule.mapper', 'NoMap', quotes=False, separator='=')
        installutils.set_directive(caconfig, 'ca.publish.rule.instance.FileCrlRule.pluginName', 'Rule', quotes=False, separator='=')
        installutils.set_directive(caconfig, 'ca.publish.rule.instance.FileCrlRule.predicate=', '', quotes=False, separator='')
        installutils.set_directive(caconfig, 'ca.publish.rule.instance.FileCrlRule.publisher', 'FileBaseCRLPublisher', quotes=False, separator='=')
        installutils.set_directive(caconfig, 'ca.publish.rule.instance.FileCrlRule.type', 'crl', quotes=False, separator='=')

        # Now disable LDAP publishing
        installutils.set_directive(caconfig, 'ca.publish.rule.instance.LdapCaCertRule.enable', 'false', quotes=False, separator='=')
        installutils.set_directive(caconfig, 'ca.publish.rule.instance.LdapCrlRule.enable', 'false', quotes=False, separator='=')
        installutils.set_directive(caconfig, 'ca.publish.rule.instance.LdapUserCertRule.enable', 'false', quotes=False, separator='=')
        installutils.set_directive(caconfig, 'ca.publish.rule.instance.LdapXCertRule.enable', 'false', quotes=False, separator='=')

        # If we are the initial master then we are the CRL generator, otherwise
        # we point to that master for CRLs.
        if not self.clone:
            # These next two are defaults, but I want to be explicit that the
            # initial master is the CRL generator.
            installutils.set_directive(caconfig, 'ca.crl.MasterCRL.enableCRLCache', 'true', quotes=False, separator='=')
            installutils.set_directive(caconfig, 'ca.crl.MasterCRL.enableCRLUpdates', 'true', quotes=False, separator='=')
            installutils.set_directive(caconfig, 'ca.listenToCloneModifications', 'true', quotes=False, separator='=')
        else:
            installutils.set_directive(caconfig, 'ca.crl.MasterCRL.enableCRLCache', 'false', quotes=False, separator='=')
            installutils.set_directive(caconfig, 'ca.crl.MasterCRL.enableCRLUpdates', 'false', quotes=False, separator='=')
            installutils.set_directive(caconfig, 'ca.listenToCloneModifications', 'false', quotes=False, separator='=')

    def __set_subject_in_config(self):
        # dogtag ships with an IPA-specific profile that forces a subject
        # format. We need to update that template with our base subject
        if installutils.update_file(self.dogtag_constants.IPA_SERVICE_PROFILE,
                'OU=pki-ipa, O=IPA', str(self.subject_base)):
            print "Updating subject_base in CA template failed"

    def uninstall(self):
        enabled = self.restore_state("enabled")
        if not enabled is None and not enabled:
            self.disable()

        if self.dogtag_constants.DOGTAG_VERSION >= 10:
            DogtagInstance.uninstall(self)
        else:
            if self.is_configured():
                self.print_msg("Unconfiguring CA")

            try:
                ipautil.run(["/usr/bin/pkiremove",
                             "-pki_instance_root=/var/lib",
                             "-pki_instance_name=%s" %
                                self.dogtag_constants.PKI_INSTANCE_NAME,
                             "--force"])
            except ipautil.CalledProcessError, e:
                root_logger.critical("failed to uninstall CA instance %s" % e)

        # At one time we removed this user on uninstall. That can potentially
        # orphan files, or worse, if another useradd runs in the interim,
        # cause files to have a new owner.
        _user_exists = self.restore_state("user_exists")

        services.knownservices.messagebus.start()
        cmonger = services.knownservices.certmonger
        cmonger.start()

        bus = dbus.SystemBus()
        obj = bus.get_object('org.fedorahosted.certmonger',
                             '/org/fedorahosted/certmonger')
        iface = dbus.Interface(obj, 'org.fedorahosted.certmonger')
        path = iface.find_ca_by_nickname('dogtag-ipa-ca-renew-agent')
        if path:
            iface.remove_known_ca(path)

        cmonger.stop()

        # remove CRL files
        root_logger.info("Remove old CRL files")
        for f in get_crl_files():
            root_logger.debug("Remove %s", f)
            installutils.remove_file(f)

        # remove CRL directory
        root_logger.info("Remove CRL directory")
        if os.path.exists(self.dogtag_constants.CRL_PUBLISH_PATH):
            try:
                shutil.rmtree(self.dogtag_constants.CRL_PUBLISH_PATH)
            except OSError, e:
                root_logger.warning("Error while removing CRL publish "
                                    "directory: %s" % e)

    def publish_ca_cert(self, location):
        args = ["-L", "-n", self.canickname, "-a"]
        (cert, _err, _returncode) = self.__run_certutil(args)
        fd = open(location, "w+")
        fd.write(cert)
        fd.close()
        os.chmod(location, 0444)

    @staticmethod
    def configure_certmonger_renewal():
        """
        Create a new CA type for certmonger that will retrieve updated
        certificates from the dogtag master server.
        """
        services.knownservices.messagebus.start()
        cmonger = services.knownservices.certmonger
        cmonger.enable()
        cmonger.start()

        bus = dbus.SystemBus()
        obj = bus.get_object('org.fedorahosted.certmonger',
                             '/org/fedorahosted/certmonger')
        iface = dbus.Interface(obj, 'org.fedorahosted.certmonger')
        path = iface.find_ca_by_nickname('dogtag-ipa-ca-renew-agent')
        if not path:
            iface.add_known_ca(
                'dogtag-ipa-ca-renew-agent',
                paths.DOGTAG_IPA_CA_RENEW_AGENT_SUBMIT, [])

    @staticmethod
    def configure_agent_renewal():
        try:
            certmonger.dogtag_start_tracking(
                ca='dogtag-ipa-ca-renew-agent',
                nickname='ipaCert',
                pin=None,
                pinfile=paths.ALIAS_PWDFILE_TXT,
                secdir=paths.HTTPD_ALIAS_DIR,
                pre_command=None,
                post_command='renew_ra_cert')
        except (ipautil.CalledProcessError, RuntimeError), e:
            root_logger.error(
                "certmonger failed to start tracking certificate: %s" % e)

    def __get_ca_pin(self):
        try:
            return certmonger.get_pin('internal',
                dogtag_constants=self.dogtag_constants)
        except IOError, e:
            raise RuntimeError(
                'Unable to determine PIN for CA instance: %s' % e)

    def configure_cert_renewal(self):
        """
        Configure system certificates for renewal.
        """
        nicknames = ['auditSigningCert cert-pki-ca',
                     'ocspSigningCert cert-pki-ca',
                     'subsystemCert cert-pki-ca']

        DogtagInstance.configure_renewal(self, nicknames)

    def track_servercert(self):
        """
        Specifically do not tell certmonger to restart the CA. This will be
        done by the renewal script, renew_ca_cert once all the subsystem
        certificates are renewed.
        """
        pin = self.__get_ca_pin()
        try:
            certmonger.dogtag_start_tracking(
                ca='dogtag-ipa-renew-agent',
                nickname='Server-Cert cert-pki-ca',
                pin=pin,
                pinfile=None,
                secdir=self.dogtag_constants.ALIAS_DIR,
                pre_command=None,
                post_command=None)
        except (ipautil.CalledProcessError, RuntimeError), e:
            root_logger.error(
                "certmonger failed to start tracking certificate: %s" % e)

    @staticmethod
    def stop_tracking_agent_certificate(dogtag_constants):
        """Stop tracking agent certificate. Called on uninstall.
        """
        cmonger = services.knownservices.certmonger
        services.knownservices.messagebus.start()
        cmonger.start()
        try:
            certmonger.stop_tracking('/etc/httpd/alias', nickname='ipaCert')
        except (ipautil.CalledProcessError, RuntimeError), e:
            root_logger.error(
                "certmonger failed to stop tracking certificate: %s" % str(e))
        cmonger.stop()

    def enable_subject_key_identifier(self):
        """
        See if Subject Key Identifier is set in the profile and if not, add it.
        """
        setlist = installutils.get_directive(
            self.dogtag_constants.IPA_SERVICE_PROFILE,
            'policyset.serverCertSet.list', separator='=')

        # this is the default setting from pki-ca/pki-tomcat. Don't touch it
        # if a user has manually modified it.
        if setlist == '1,2,3,4,5,6,7,8' or setlist == '1,2,3,4,5,6,7,8,9':
            setlist += ',10'
            installutils.set_directive(
                self.dogtag_constants.IPA_SERVICE_PROFILE,
                'policyset.serverCertSet.list',
                setlist,
                quotes=False, separator='=')
            installutils.set_directive(
                self.dogtag_constants.IPA_SERVICE_PROFILE,
                'policyset.serverCertSet.10.constraint.class_id',
                'noConstraintImpl',
                quotes=False, separator='=')
            installutils.set_directive(
                self.dogtag_constants.IPA_SERVICE_PROFILE,
                'policyset.serverCertSet.10.constraint.name',
                'No Constraint',
                quotes=False, separator='=')
            installutils.set_directive(
                self.dogtag_constants.IPA_SERVICE_PROFILE,
                'policyset.serverCertSet.10.default.class_id',
                'subjectKeyIdentifierExtDefaultImpl',
                quotes=False, separator='=')
            installutils.set_directive(
                self.dogtag_constants.IPA_SERVICE_PROFILE,
                'policyset.serverCertSet.10.default.name',
                'Subject Key Identifier Extension Default',
                quotes=False, separator='=')
            installutils.set_directive(
                self.dogtag_constants.IPA_SERVICE_PROFILE,
                'policyset.serverCertSet.10.default.params.critical',
                'false',
                quotes=False, separator='=')
            return True

        # No update was done
        return False

    def enable_subject_alternative_name(self):
        """
        See if Subject Alternative Name is set in the profile and if not, add
        it.
        """
        setlist = installutils.get_directive(
            self.dogtag_constants.IPA_SERVICE_PROFILE,
            'policyset.serverCertSet.list', separator='=')

        # this is the default setting from pki-ca/pki-tomcat. Don't touch it
        # if a user has manually modified it.
        if setlist == '1,2,3,4,5,6,7,8,10' or setlist == '1,2,3,4,5,6,7,8,9,10':
            setlist += ',11'
            installutils.set_directive(
                self.dogtag_constants.IPA_SERVICE_PROFILE,
                'policyset.serverCertSet.list',
                setlist,
                quotes=False, separator='=')
            installutils.set_directive(
                self.dogtag_constants.IPA_SERVICE_PROFILE,
                'policyset.serverCertSet.11.constraint.class_id',
                'noConstraintImpl',
                quotes=False, separator='=')
            installutils.set_directive(
                self.dogtag_constants.IPA_SERVICE_PROFILE,
                'policyset.serverCertSet.11.constraint.name',
                'No Constraint',
                quotes=False, separator='=')
            installutils.set_directive(
                self.dogtag_constants.IPA_SERVICE_PROFILE,
                'policyset.serverCertSet.11.default.class_id',
                'userExtensionDefaultImpl',
                quotes=False, separator='=')
            installutils.set_directive(
                self.dogtag_constants.IPA_SERVICE_PROFILE,
                'policyset.serverCertSet.11.default.name',
                'User Supplied Extension Default',
                quotes=False, separator='=')
            installutils.set_directive(
                self.dogtag_constants.IPA_SERVICE_PROFILE,
                'policyset.serverCertSet.11.default.params.userExtOID',
                '2.5.29.17',
                quotes=False, separator='=')
            return True

        # No update was done
        return False

    def set_audit_renewal(self):
        """
        The default renewal time for the audit signing certificate is
        six months rather than two years. Fix it. This is BZ 843979.
        """
        # Check the default validity period of the audit signing cert
        # and set it to 2 years if it is 6 months.
        cert_range = installutils.get_directive(
            '%s/caSignedLogCert.cfg' % self.dogtag_constants.SERVICE_PROFILE_DIR,
            'policyset.caLogSigningSet.2.default.params.range',
            separator='='
        )
        root_logger.debug(
            'caSignedLogCert.cfg profile validity range is %s' % cert_range)
        if cert_range == "180":
            installutils.set_directive(
                '%s/caSignedLogCert.cfg' % self.dogtag_constants.SERVICE_PROFILE_DIR,
                'policyset.caLogSigningSet.2.default.params.range',
                '720',
                quotes=False,
                separator='='
            )
            installutils.set_directive(
                '%s/caSignedLogCert.cfg' % self.dogtag_constants.SERVICE_PROFILE_DIR,
                'policyset.caLogSigningSet.2.constraint.params.range',
                '720',
                quotes=False,
                separator='='
            )
            root_logger.debug('updated caSignedLogCert.cfg profile validity range to 720')
            return True
        return False

    def is_renewal_master(self):
        if not self.admin_conn:
            self.ldap_connect()

        dn = DN(('cn', 'CA'), ('cn', api.env.host), ('cn', 'masters'),
                ('cn', 'ipa'), ('cn', 'etc'), api.env.basedn)
        renewal_filter = '(ipaConfigString=caRenewalMaster)'
        try:
            self.admin_conn.get_entries(base_dn=dn, filter=renewal_filter,
                                        attrs_list=[])
        except errors.NotFound:
            return False

        return True

    @staticmethod
    def update_cert_config(nickname, cert, dogtag_constants=None):
        """
        When renewing a CA subsystem certificate the configuration file
        needs to get the new certificate as well.

        nickname is one of the known nicknames.
        cert is a DER-encoded certificate.
        """

        if dogtag_constants is None:
            dogtag_constants = dogtag.configured_constants()

        # The cert directive to update per nickname
        directives = {'auditSigningCert cert-pki-ca': 'ca.audit_signing.cert',
                      'ocspSigningCert cert-pki-ca': 'ca.ocsp_signing.cert',
                      'caSigningCert cert-pki-ca': 'ca.signing.cert',
                      'subsystemCert cert-pki-ca': 'ca.subsystem.cert',
                      'Server-Cert cert-pki-ca': 'ca.sslserver.cert'}

        DogtagInstance.update_cert_cs_cfg(
            nickname, cert, directives,
            dogtag.configured_constants().CS_CFG_PATH,
            dogtag_constants)

def replica_ca_install_check(config):