commit_id
string
repo
string
commit_message
string
diff
string
label
int64
2ca86fe13e0efa224fbe4f374be692a8ddabdeb7
389ds/389-ds-base
Ticket 50340 - 2nd try - structs for diabled plugins will not be freed Bug: when plugins are loaded from dse.ldif enabled plugins will be added to the list of the plugin type and freed when plugins are stopped. But the memory allocated for disabled plugins will remain allocated and and be reported. Fix: The previous fix did free not enabled plugins in plugin_setup, but that caused a lot of issues. This patch frees not enabled plugins in plugin_dependency_freeall Reviewed by: ? Signed-off-by: Mark Reynolds <[email protected]>
commit 2ca86fe13e0efa224fbe4f374be692a8ddabdeb7 Author: Ludwig Krispenz <[email protected]> Date: Thu May 23 11:11:25 2019 +0000 Ticket 50340 - 2nd try - structs for diabled plugins will not be freed Bug: when plugins are loaded from dse.ldif enabled plugins will be added to the list of the plugin type and freed when plugins are stopped. But the memory allocated for disabled plugins will remain allocated and and be reported. Fix: The previous fix did free not enabled plugins in plugin_setup, but that caused a lot of issues. This patch frees not enabled plugins in plugin_dependency_freeall Reviewed by: ? Signed-off-by: Mark Reynolds <[email protected]> diff --git a/ldap/servers/slapd/plugin.c b/ldap/servers/slapd/plugin.c index 7dfab8479..0b1067849 100644 --- a/ldap/servers/slapd/plugin.c +++ b/ldap/servers/slapd/plugin.c @@ -1914,13 +1914,18 @@ void plugin_dependency_freeall() { entry_and_plugin_t *iterp, *nextp; + char *value; /* free the plugin dependency entry list */ iterp = dep_plugin_entries; while (iterp) { nextp = iterp->next; + if ((value = slapi_entry_attr_get_charptr(iterp->e, ATTR_PLUGIN_ENABLED)) && + !strcasecmp(value, "off")) { + plugin_free(iterp->plugin); + } + slapi_ch_free_string(&value); slapi_entry_free(iterp->e); - /* plugin_free(iterp->plugin); */ slapi_ch_free((void **)&iterp); iterp = nextp; } @@ -3031,7 +3036,7 @@ plugin_setup(Slapi_Entry *plugin_entry, struct slapi_componentid *group, slapi_p add_plugin_entry_dn(dn_copy); } - if (add_entry && enabled) { + if (add_entry) { /* make a copy of the plugin entry for our own use because it will be freed later by the caller */ Slapi_Entry *e_copy = slapi_entry_dup(plugin_entry); @@ -3040,7 +3045,7 @@ plugin_setup(Slapi_Entry *plugin_entry, struct slapi_componentid *group, slapi_p } PLUGIN_CLEANUP: - if (status || !enabled) { + if (status) { plugin_free(plugin); } slapi_ch_free((void **)&configdir);
0
98b57d142af6c4a42d9a69922eccc73067e07b70
389ds/389-ds-base
Ticket 48039 - nunc-stans malloc should be pluggable Description: Allow malloc, calloc, realloc, and free to be pluggable in nunc-stans. Created wrapper functions for slapi_ch_malloc, etc, to comply with C signatures. https://fedorahosted.org/389/ticket/48039 Reviewed by: ?
commit 98b57d142af6c4a42d9a69922eccc73067e07b70 Author: Mark Reynolds <[email protected]> Date: Thu Feb 26 15:07:45 2015 -0500 Ticket 48039 - nunc-stans malloc should be pluggable Description: Allow malloc, calloc, realloc, and free to be pluggable in nunc-stans. Created wrapper functions for slapi_ch_malloc, etc, to comply with C signatures. https://fedorahosted.org/389/ticket/48039 Reviewed by: ? diff --git a/ldap/servers/slapd/daemon.c b/ldap/servers/slapd/daemon.c index e4ed0dfae..dc69bc481 100644 --- a/ldap/servers/slapd/daemon.c +++ b/ldap/servers/slapd/daemon.c @@ -1251,6 +1251,30 @@ nunc_stans_logging(int priority, const char *format, va_list varg) slapi_log_error_ext(severity, "nunc-stans", (char *)format, varg, varg_copy); va_end(varg_copy); } + +static void* +nunc_stans_malloc(size_t size) +{ + return (void*)slapi_ch_malloc((unsigned long)size); +} + +static void* +nunc_stans_calloc(size_t count, size_t size) +{ + return (void*)slapi_ch_calloc((unsigned long)count, (unsigned long)size); +} + +static void* +nunc_stans_realloc(void *block, size_t size) +{ + return (void*)slapi_ch_realloc((char *)block, (unsigned long)size); +} + +static void +nunc_stans_free(void *ptr) +{ + slapi_ch_free((void **)&ptr); +} #endif void slapd_daemon( daemon_ports_t *ports ) @@ -1480,6 +1504,12 @@ void slapd_daemon( daemon_ports_t *ports ) tp_config.event_queue_size = config_get_maxdescriptors(); tp_config.work_queue_size = config_get_maxdescriptors(); tp_config.log_fct = nunc_stans_logging; + tp_config.log_start_fct = NULL; + tp_config.log_close_fct = NULL; + tp_config.malloc_fct = nunc_stans_malloc; + tp_config.calloc_fct = nunc_stans_calloc; + tp_config.realloc_fct = nunc_stans_realloc; + tp_config.free_fct = nunc_stans_free; tp = ns_thrpool_new(&tp_config); ns_add_signal_job(tp, SIGINT, NS_JOB_SIGNAL, ns_set_shutdown, NULL, NULL);
0
19d2029bbe4dc95057b0a560d95f9d98dc44b599
389ds/389-ds-base
Issue 50462 - Fix CI tests Description: Port some of the failing ticket tests to suites related: https://pagure.io/389-ds-base/issue/50462 Reviewed by: vashirov, mhonek, spichugi, and aadhikari (thanks!)
commit 19d2029bbe4dc95057b0a560d95f9d98dc44b599 Author: Mark Reynolds <[email protected]> Date: Fri Jun 21 18:14:34 2019 -0400 Issue 50462 - Fix CI tests Description: Port some of the failing ticket tests to suites related: https://pagure.io/389-ds-base/issue/50462 Reviewed by: vashirov, mhonek, spichugi, and aadhikari (thanks!) diff --git a/dirsrvtests/tests/suites/replication/acceptance_test.py b/dirsrvtests/tests/suites/replication/acceptance_test.py index bf35ef33e..943e6ab3e 100644 --- a/dirsrvtests/tests/suites/replication/acceptance_test.py +++ b/dirsrvtests/tests/suites/replication/acceptance_test.py @@ -472,6 +472,8 @@ def test_invalid_agmt(topo_m4): except ldap.LDAPError as e: m1.log.fatal('Failed to bind: ' + str(e)) assert False + + def test_warining_for_invalid_replica(topo_m4): """Testing logs to indicate the inconsistency when configuration is performed. diff --git a/dirsrvtests/tests/suites/replication/regression_nsslapd_plugin_binddn_tracking_test.py b/dirsrvtests/tests/suites/replication/regression_nsslapd_plugin_binddn_tracking_test.py deleted file mode 100644 index 23daae68b..000000000 --- a/dirsrvtests/tests/suites/replication/regression_nsslapd_plugin_binddn_tracking_test.py +++ /dev/null @@ -1,116 +0,0 @@ -# --- BEGIN COPYRIGHT BLOCK --- -# Copyright (C) 2018 Red Hat, Inc. -# All rights reserved. -# -# License: GPL (version 3 or any later version). -# See LICENSE for details. -# --- END COPYRIGHT BLOCK --- -# -import logging -import pytest -from lib389.tasks import * -from lib389.topologies import topology_m2 as topo_m2 -from lib389.utils import * -from lib389.replica import * -from lib389._constants import * -from lib389.idm.user import UserAccounts -from lib389.idm.domain import Domain - -pytestmark = pytest.mark.tier1 - -log = logging.getLogger(__name__) - - [email protected] -def test_nsslapd_plugin_binddn_tracking(topo_m2): - """ - Testing nsslapd-plugin-binddn-tracking does not cause issues around - access control and reconfiguring replication/repl agmt. - :id: f5ba7b64-fe04-11e8-a298-8c16451d917b - :setup: Replication with two masters. - :steps: - 1. Turn on bind dn tracking - 2. Add two users - 3. Add an aci - 4. Make modification as user - 5. Setup replica and create a repl agmt - 6. Modify replica - 7. Modify repl agmt - :expectedresults: - 1. Should Success. - 2. Should Success. - 3. Should Success. - 4. Should Success. - 5. Should Success. - 6. Should Success. - 7. Should Success. - """ - - log.info("Testing Ticket 47950 - Testing nsslapd-plugin-binddn-tracking") - - # - # Turn on bind dn tracking - # - topo_m2.ms["master1"].config.replace("nsslapd-plugin-binddn-tracking", "on") - # - # Add two users - # - users = UserAccounts(topo_m2.ms["master1"], DEFAULT_SUFFIX) - test_user_1 = users.create_test_user(uid=1) - test_user_2 = users.create_test_user(uid=2) - test_user_1.set('userPassword', 'password') - test_user_2.set('userPassword', 'password') - # - # Add an aci - # - USER1_DN = users.list()[0].dn - USER2_DN = users.list()[1].dn - acival = ( - '(targetattr ="cn")(version 3.0;acl "Test bind dn tracking"' - + ';allow (all) (userdn = "ldap:///%s");)' % USER1_DN - ) - Domain(topo_m2.ms["master1"], DEFAULT_SUFFIX).add("aci", acival) - - # - # Make modification as user - # - assert topo_m2.ms["master1"].simple_bind_s(USER1_DN, "password") - test_user_2.replace("cn", "new value") - # - # Setup replica and create a repl agmt - # - repl = ReplicationManager(DEFAULT_SUFFIX) - assert topo_m2.ms["master1"].simple_bind_s(DN_DM, PASSWORD) - repl.test_replication(topo_m2.ms["master1"], topo_m2.ms["master2"], 30) - repl.test_replication(topo_m2.ms["master2"], topo_m2.ms["master1"], 30) - properties = { - "cn": "test_agreement", - "nsDS5ReplicaRoot": "dc=example,dc=com", - "nsDS5ReplicaHost": "localhost.localdomain", - "nsDS5ReplicaPort": "5555", - "nsDS5ReplicaBindDN": "uid=tester", - "nsds5ReplicaCredentials": "password", - "nsDS5ReplicaTransportInfo": "LDAP", - "nsDS5ReplicaBindMethod": "SIMPLE", - } - replicas = Replicas(topo_m2.ms["master1"]) - replica = replicas.get(DEFAULT_SUFFIX) - agmts = Agreements(topo_m2.ms["master1"], basedn=replica.dn) - repl_agreement = agmts.create(properties=properties) - # - # modify replica - # - replica.replace("nsDS5ReplicaId", "7") - assert replica.present("nsDS5ReplicaId", "7") - # - # modify repl agmt - # - repl_agreement.replace('nsDS5ReplicaPort', "8888") - assert repl_agreement.present('nsDS5ReplicaPort', "8888") - - -if __name__ == "__main__": - # Run isolated - # -s for DEBUG mode - CURRENT_FILE = os.path.realpath(__file__) - pytest.main("-s %s" % CURRENT_FILE) diff --git a/dirsrvtests/tests/suites/replication/regression_test.py b/dirsrvtests/tests/suites/replication/regression_test.py index 830ef63ab..2ee0a99af 100644 --- a/dirsrvtests/tests/suites/replication/regression_test.py +++ b/dirsrvtests/tests/suites/replication/regression_test.py @@ -14,13 +14,16 @@ from lib389.utils import * from lib389.topologies import topology_m2 as topo_m2, TopologyMain, topology_m3 as topo_m3, create_topology, _remove_ssca_db from lib389._constants import * from lib389.idm.organizationalunit import OrganizationalUnits -from lib389.agreement import Agreements from lib389.idm.user import UserAccount from lib389.idm.group import Groups, Group +from lib389.idm.domain import Domain +from lib389.idm.directorymanager import DirectoryManager from lib389.replica import Replicas, ReplicationManager +from lib389.agreement import Agreements from lib389.changelog import Changelog5 from lib389 import pid_from_file + pytestmark = pytest.mark.tier1 NEW_SUFFIX_NAME = 'test_repl' @@ -489,9 +492,56 @@ def test_fetch_bindDnGroup(topo_m2): count = pattern_errorlog(errorlog_M2, regex, start_location=restart_location_M2) assert(count <= 1) - if DEBUGGING: - # Add debugging steps(if any)... - pass + +def test_plugin_bind_dn_tracking_and_replication(topo_m2): + """Testing nsslapd-plugin-binddn-tracking does not cause issues around + access control and reconfiguring replication/repl agmt. + + :id: dd689d03-69b8-4bf9-a06e-2acd19d5e2c9 + :setup: 2 master topology + :steps: + 1. Turn on plugin binddn tracking + 2. Add some users + 3. Make an update as a user + 4. Make an update to the replica config + 5. Make an update to the repliocation agreement + :expectedresults: + 1. Success + 2. Success + 3. Success + 4. Success + 5. Success + """ + + m1 = topo_m2.ms["master1"] + + # Turn on bind dn tracking + m1.config.set('nsslapd-plugin-binddn-tracking', 'on') + + # Add two users + users = UserAccounts(m1, DEFAULT_SUFFIX) + user1 = users.create_test_user(uid=1011) + user1.set('userpassword', PASSWORD) + user2 = users.create_test_user(uid=1012) + + # Add an aci + acival = '(targetattr ="cn")(version 3.0;acl "Test bind dn tracking"' + \ + ';allow (all) (userdn = "ldap:///{}");)'.format(user1.dn) + Domain(m1, DEFAULT_SUFFIX).add('aci', acival) + + # Bind as user and make an update + user1.rebind(PASSWORD) + user2.set('cn', 'new value') + dm = DirectoryManager(m1) + dm.rebind() + + # modify replica + replica = Replicas(m1).get(DEFAULT_SUFFIX) + replica.set(REPL_PROTOCOL_TIMEOUT, "30") + + # modify repl agmt + agmt = replica.get_agreements().list()[0] + agmt.set(REPL_PROTOCOL_TIMEOUT, "20") def test_cleanallruv_repl(topo_m3): diff --git a/dirsrvtests/tests/suites/replication/tombstone_fixup_test.py b/dirsrvtests/tests/suites/replication/tombstone_fixup_test.py new file mode 100644 index 000000000..b9c6aee06 --- /dev/null +++ b/dirsrvtests/tests/suites/replication/tombstone_fixup_test.py @@ -0,0 +1,129 @@ +# --- BEGIN COPYRIGHT BLOCK --- +# Copyright (C) 2017 Red Hat, Inc. +# All rights reserved. +# +# License: GPL (version 3 or any later version). +# See LICENSE for details. +# --- END COPYRIGHT BLOCK --- +# +import pytest +from lib389.tasks import * +from lib389.utils import * +from lib389.topologies import topology_m1 +from lib389.tombstone import Tombstones +from lib389.idm.user import UserAccounts, TEST_USER_PROPERTIES +from lib389.replica import ReplicationManager +from lib389._constants import (defaultProperties, DEFAULT_SUFFIX, ReplicaRole, + REPLICAID_MASTER_1, REPLICA_PRECISE_PURGING, REPLICA_PURGE_DELAY, + REPLICA_PURGE_INTERVAL) + +pytestmark = pytest.mark.tier2 + + +def test_precise_tombstone_purging(topology_m1): + """ Test precise tombstone purging + + :id: adb86f50-ae76-4ed6-82b4-3cdc30ccab79 + :setup: master1 instance + :steps: + 1. Create and Delete entry to create a tombstone + 2. export ldif, edit, and import ldif + 3. Check tombstones do not contain nsTombstoneCSN + 4. Run fixup task, and verify tombstones now have nsTombstone CSN + 5. Configure tombstone purging + 6. Verify tombstones are purged + :expectedresults: + 1. Success + 2. Success + 3. Success + 4. Success + 5. Success + 6. Success + """ + + m1 = topology_m1.ms['master1'] + m1_tasks = Tasks(m1) + + # Create tombstone entry + users = UserAccounts(m1, DEFAULT_SUFFIX) + user = users.create_test_user(uid=1001) + user.delete() + + # Verify tombstone was created + tombstones = Tombstones(m1, DEFAULT_SUFFIX) + assert len(tombstones.list()) == 1 + + # Export db, strip nsTombstoneCSN, and import it + ldif_file = "{}/export.ldif".format(m1.get_ldif_dir()) + args = {EXPORT_REPL_INFO: True, + TASK_WAIT: True} + m1_tasks.exportLDIF(DEFAULT_SUFFIX, None, ldif_file, args) + time.sleep(.5) + + # Strip LDIF of nsTombstoneCSN, getthe LDIF lines, the n create new ldif + ldif = open(ldif_file, "r") + lines = ldif.readlines() + ldif.close() + time.sleep(.5) + + ldif = open(ldif_file, "w") + for line in lines: + if not line.lower().startswith('nstombstonecsn'): + ldif.write(line) + ldif.close() + time.sleep(.5) + + # import the new ldif file + log.info('Import replication LDIF file...') + args = {TASK_WAIT: True} + m1_tasks.importLDIF(DEFAULT_SUFFIX, None, ldif_file, args) + time.sleep(.5) + + # Search for the tombstone again + tombstones = Tombstones(m1, DEFAULT_SUFFIX) + assert len(tombstones.list()) == 1 + + # + # Part 3 - test fixup task using the strip option. + # + args = {TASK_WAIT: True, + TASK_TOMB_STRIP: True} + m1_tasks.fixupTombstones(DEFAULT_BENAME, args) + time.sleep(.5) + + # Search for tombstones with nsTombstoneCSN - better not find any + for ts in tombstones.list(): + assert not ts.present("nsTombstoneCSN") + + # Now run the fixup task + args = {TASK_WAIT: True} + m1_tasks.fixupTombstones(DEFAULT_BENAME, args) + time.sleep(.5) + + # Search for tombstones with nsTombstoneCSN - better find some + tombstones = Tombstones(m1, DEFAULT_SUFFIX) + assert len(tombstones.list()) == 1 + + # + # Part 4 - Test tombstone purging + # + args = {REPLICA_PRECISE_PURGING: b'on', + REPLICA_PURGE_DELAY: b'5', + REPLICA_PURGE_INTERVAL: b'5'} + m1.replica.setProperties(DEFAULT_SUFFIX, None, None, args) + + # Wait for the interval to pass + log.info('Wait for tombstone purge interval to pass...') + time.sleep(6) + + # Add an entry to trigger replication + users.create_test_user(uid=1002) + + # Wait for the interval to pass again + log.info('Wait for tombstone purge interval to pass again...') + time.sleep(6) + + # search for tombstones, there should be none + tombstones = Tombstones(m1, DEFAULT_SUFFIX) + assert len(tombstones.list()) == 0 + diff --git a/dirsrvtests/tests/suites/replication/tombstone_test.py b/dirsrvtests/tests/suites/replication/tombstone_test.py index 1910a204c..67f800120 100644 --- a/dirsrvtests/tests/suites/replication/tombstone_test.py +++ b/dirsrvtests/tests/suites/replication/tombstone_test.py @@ -10,12 +10,12 @@ import pytest from lib389.tasks import * from lib389.utils import * from lib389.topologies import topology_m1 - from lib389.tombstone import Tombstones from lib389.idm.user import UserAccounts, TEST_USER_PROPERTIES pytestmark = pytest.mark.tier1 + def test_purge_success(topology_m1): """Verify that tombstones are created successfully @@ -54,6 +54,7 @@ def test_purge_success(topology_m1): assert len(users.list()) == 1 user_revived = users.get('testuser') + if __name__ == '__main__': # Run isolated diff --git a/dirsrvtests/tests/suites/resource_limits/fdlimits_test.py b/dirsrvtests/tests/suites/resource_limits/fdlimits_test.py index c8e45fed6..c72e8f921 100644 --- a/dirsrvtests/tests/suites/resource_limits/fdlimits_test.py +++ b/dirsrvtests/tests/suites/resource_limits/fdlimits_test.py @@ -2,9 +2,11 @@ import logging import pytest import os import ldap +import resource from lib389._constants import * from lib389.topologies import topology_st -from lib389.utils import ds_is_older +from lib389.utils import ds_is_older, ensure_str +from subprocess import check_output pytestmark = pytest.mark.tier1 @@ -12,9 +14,11 @@ logging.getLogger(__name__).setLevel(logging.INFO) log = logging.getLogger(__name__) FD_ATTR = "nsslapd-maxdescriptors" -SYSTEMD_VAL = "16384" +GLOBAL_LIMIT = resource.getrlimit(resource.RLIMIT_NOFILE)[1] +SYSTEMD_LIMIT = ensure_str(check_output("systemctl show --value -p LimitNOFILE dirsrv@standalone1".split(" ")).strip()) CUSTOM_VAL = "9000" -TOO_HIGH_VAL = "65536" +TOO_HIGH_VAL = str(GLOBAL_LIMIT * 2) +TOO_HIGH_VAL2 = str(int(SYSTEMD_LIMIT) * 2) TOO_LOW_VAL = "0" @pytest.mark.skipif(ds_is_older("1.4.1.2"), reason="Not implemented") @@ -26,7 +30,7 @@ def test_fd_limits(topology_st): :steps: 1. Check default limit 2. Change default limit - 3. Check invalid/too high limit is rejected + 3. Check invalid/too high limits are rejected 4. Check invalid/too low limit is rejected :expectedresults: 1. Success @@ -37,19 +41,25 @@ def test_fd_limits(topology_st): # Check systemd default max_fd = topology_st.standalone.config.get_attr_val_utf8(FD_ATTR) - assert max_fd == SYSTEMD_VAL + assert max_fd == SYSTEMD_LIMIT # Check custom value is applied topology_st.standalone.config.set(FD_ATTR, CUSTOM_VAL) max_fd = topology_st.standalone.config.get_attr_val_utf8(FD_ATTR) assert max_fd == CUSTOM_VAL - # Attempt to use val that is too high + # # Attempt to use value that is higher than the global system limit with pytest.raises(ldap.UNWILLING_TO_PERFORM): topology_st.standalone.config.set(FD_ATTR, TOO_HIGH_VAL) max_fd = topology_st.standalone.config.get_attr_val_utf8(FD_ATTR) assert max_fd == CUSTOM_VAL + # Attempt to use value that is higher than the value defined in the systemd service + with pytest.raises(ldap.UNWILLING_TO_PERFORM): + topology_st.standalone.config.set(FD_ATTR, TOO_HIGH_VAL2) + max_fd = topology_st.standalone.config.get_attr_val_utf8(FD_ATTR) + assert max_fd == CUSTOM_VAL + # Attempt to use val that is too low with pytest.raises(ldap.OPERATIONS_ERROR): topology_st.standalone.config.set(FD_ATTR, TOO_LOW_VAL) diff --git a/dirsrvtests/tests/tickets/ticket47819_test.py b/dirsrvtests/tests/tickets/ticket47819_test.py deleted file mode 100644 index ba8d97ed0..000000000 --- a/dirsrvtests/tests/tickets/ticket47819_test.py +++ /dev/null @@ -1,244 +0,0 @@ -# --- BEGIN COPYRIGHT BLOCK --- -# Copyright (C) 2016 Red Hat, Inc. -# All rights reserved. -# -# License: GPL (version 3 or any later version). -# See LICENSE for details. -# --- END COPYRIGHT BLOCK --- -# -import logging - -import pytest -from lib389.tasks import * -from lib389.topologies import topology_st -from lib389.replica import ReplicationManager - -from lib389._constants import (defaultProperties, DEFAULT_SUFFIX, ReplicaRole, - REPLICAID_MASTER_1, REPLICA_PRECISE_PURGING, REPLICA_PURGE_DELAY, - REPLICA_PURGE_INTERVAL) - -pytestmark = pytest.mark.tier2 - -log = logging.getLogger(__name__) - - -def test_ticket47819(topology_st): - """ -from lib389.utils import * - -# Skip on older versions -pytestmark = pytest.mark.skipif(ds_is_older('1.3.4'), reason="Not implemented") - Testing precise tombstone purging: - [1] Make sure "nsTombstoneCSN" is added to new tombstones - [2] Make sure an import of a replication ldif adds "nsTombstoneCSN" - to old tombstones - [4] Test fixup task - [3] Make sure tombstone purging works - """ - - log.info('Testing Ticket 47819 - Test precise tombstone purging') - - # - # Setup Replication - # - master = topology_st.standalone - repl = ReplicationManager(DEFAULT_SUFFIX) - repl.create_first_master(master) - repl.ensure_agreement(master, master) - - # - # Part 1 create a tombstone entry and make sure nsTombstoneCSN is added - # - log.info('Part 1: Add and then delete an entry to create a tombstone...') - - try: - topology_st.standalone.add_s(Entry(('cn=entry1,dc=example,dc=com', { - 'objectclass': 'top person'.split(), - 'sn': 'user', - 'cn': 'entry1'}))) - except ldap.LDAPError as e: - log.error('Failed to add entry: ' + e.message['desc']) - assert False - - try: - topology_st.standalone.delete_s('cn=entry1,dc=example,dc=com') - except ldap.LDAPError as e: - log.error('Failed to delete entry: ' + e.message['desc']) - assert False - - log.info('Search for tombstone entries...') - try: - entries = topology_st.standalone.search_s(DEFAULT_SUFFIX, ldap.SCOPE_SUBTREE, - '(&(nsTombstoneCSN=*)(objectclass=nsTombstone))') - if not entries: - log.fatal('Search failed to the new tombstone(nsTombstoneCSN is probably missing).') - assert False - except ldap.LDAPError as e: - log.fatal('Search failed: ' + e.message['desc']) - assert False - - log.info('Part 1 - passed') - - # - # Part 2 - import ldif with tombstones missing 'nsTombstoneCSN' - # - # First, export the replication ldif, edit the file(remove nstombstonecsn), - # and reimport it. - # - log.info('Part 2: Exporting replication ldif...') - - # Get the the full path and name for our LDIF we will be exporting - ldif_file = "/tmp/export.ldif" - - args = {EXPORT_REPL_INFO: True, - TASK_WAIT: True} - exportTask = Tasks(topology_st.standalone) - try: - exportTask.exportLDIF(DEFAULT_SUFFIX, None, ldif_file, args) - except ValueError: - assert False - time.sleep(1) - - # open the ldif file, get the lines, then rewrite the file - ldif = open(ldif_file, "r") - lines = ldif.readlines() - ldif.close() - time.sleep(1) - - ldif = open(ldif_file, "w") - for line in lines: - if not line.lower().startswith('nstombstonecsn'): - ldif.write(line) - ldif.close() - time.sleep(1) - - # import the new ldif file - log.info('Import replication LDIF file...') - importTask = Tasks(topology_st.standalone) - args = {TASK_WAIT: True} - try: - importTask.importLDIF(DEFAULT_SUFFIX, None, ldif_file, args) - os.remove(ldif_file) - except ValueError: - os.remove(ldif_file) - assert False - time.sleep(1) - - # Search for the tombstone again - log.info('Search for tombstone entries...') - try: - entries = topology_st.standalone.search_s(DEFAULT_SUFFIX, ldap.SCOPE_SUBTREE, - '(&(nsTombstoneCSN=*)(objectclass=nsTombstone))') - if not entries: - log.fatal('Search failed to fine the new tombstone(nsTombstoneCSN is probably missing).') - assert False - except ldap.LDAPError as e: - log.fatal('Search failed: ' + e.message['desc']) - assert False - - log.info('Part 2 - passed') - - # - # Part 3 - test fixup task - # - log.info('Part 3: test the fixup task') - - # Run fixup task using the strip option. This removes nsTombstoneCSN - # so we can test if the fixup task works. - args = {TASK_WAIT: True, - TASK_TOMB_STRIP: True} - fixupTombTask = Tasks(topology_st.standalone) - try: - fixupTombTask.fixupTombstones(DEFAULT_BENAME, args) - except: - assert False - time.sleep(1) - - # Search for tombstones with nsTombstoneCSN - better not find any - log.info('Search for tombstone entries...') - try: - entries = topology_st.standalone.search_s(DEFAULT_SUFFIX, ldap.SCOPE_SUBTREE, - '(&(nsTombstoneCSN=*)(objectclass=nsTombstone))') - if entries: - log.fatal('Search found tombstones with nsTombstoneCSN') - assert False - except ldap.LDAPError as e: - log.fatal('Search failed: ' + e.message['desc']) - assert False - - # Now run the fixup task - args = {TASK_WAIT: True} - fixupTombTask = Tasks(topology_st.standalone) - try: - fixupTombTask.fixupTombstones(DEFAULT_BENAME, args) - except: - assert False - time.sleep(1) - - # Search for tombstones with nsTombstoneCSN - better find some - log.info('Search for tombstone entries...') - try: - entries = topology_st.standalone.search_s(DEFAULT_SUFFIX, ldap.SCOPE_SUBTREE, - '(&(nsTombstoneCSN=*)(objectclass=nsTombstone))') - if not entries: - log.fatal('Search did not find any fixed-up tombstones') - assert False - except ldap.LDAPError as e: - log.fatal('Search failed: ' + e.message['desc']) - assert False - - log.info('Part 3 - passed') - - # - # Part 4 - Test tombstone purging - # - log.info('Part 4: test tombstone purging...') - - args = {REPLICA_PRECISE_PURGING: b'on', - REPLICA_PURGE_DELAY: b'5', - REPLICA_PURGE_INTERVAL: b'5'} - try: - topology_st.standalone.replica.setProperties(DEFAULT_SUFFIX, None, None, args) - except: - log.fatal('Failed to configure replica') - assert False - - # Wait for the interval to pass - log.info('Wait for tombstone purge interval to pass...') - time.sleep(10) - - # Add an entry to trigger replication - log.info('Perform an update to help trigger tombstone purging...') - try: - topology_st.standalone.add_s(Entry(('cn=test_entry,dc=example,dc=com', { - 'objectclass': 'top person'.split(), - 'sn': 'user', - 'cn': 'entry1'}))) - except ldap.LDAPError as e: - log.error('Failed to add entry: ' + e.message['desc']) - assert False - - # Wait for the interval to pass again - log.info('Wait for tombstone purge interval to pass again...') - time.sleep(10) - - # search for tombstones, there should be none - log.info('Search for tombstone entries...') - try: - entries = topology_st.standalone.search_s(DEFAULT_SUFFIX, ldap.SCOPE_SUBTREE, - '(&(nsTombstoneCSN=*)(objectclass=nsTombstone))') - if entries: - log.fatal('Search unexpectedly found tombstones') - assert False - except ldap.LDAPError as e: - log.fatal('Search failed: ' + e.message['desc']) - assert False - - log.info('Part 4 - passed') - - -if __name__ == '__main__': - # Run isolated - # -s for DEBUG mode - CURRENT_FILE = os.path.realpath(__file__) - pytest.main("-s %s" % CURRENT_FILE) diff --git a/dirsrvtests/tests/tickets/ticket47838_test.py b/dirsrvtests/tests/tickets/ticket47838_test.py deleted file mode 100644 index 518dd5083..000000000 --- a/dirsrvtests/tests/tickets/ticket47838_test.py +++ /dev/null @@ -1,787 +0,0 @@ -# --- BEGIN COPYRIGHT BLOCK --- -# Copyright (C) 2016 Red Hat, Inc. -# All rights reserved. -# -# License: GPL (version 3 or any later version). -# See LICENSE for details. -# --- END COPYRIGHT BLOCK --- -# -import logging -import time - -import socket -import ldap -import pytest -from lib389 import Entry -from lib389._constants import * -from lib389.topologies import topology_st -from lib389.nss_ssl import NssSsl - -log = logging.getLogger(__name__) - -CONFIG_DN = 'cn=config' -from lib389.utils import * - -# Skip on older versions -pytestmark = [pytest.mark.tier2, - pytest.mark.skipif(ds_is_older('1.3.3'), reason="Not implemented")] -ENCRYPTION_DN = 'cn=encryption,%s' % CONFIG_DN -MY_SECURE_PORT = '63601' -RSA = 'RSA' -RSA_DN = 'cn=%s,%s' % (RSA, ENCRYPTION_DN) -SERVERCERT = 'Server-Cert' -plus_all_ecount = 0 -plus_all_dcount = 0 -plus_all_ecount_noweak = 0 -plus_all_dcount_noweak = 0 - -# Cipher counts tend to change with each new verson of NSS -nss_version = '' -NSS320 = '3.20.0' -NSS321 = '3.21.0' # RHEL6 -NSS323 = '3.23.0' # F22 -NSS325 = '3.25.0' # F23/F24 -NSS327 = '3.27.0' # F25 -NSS330 = '3.30.0' # F27 - - -def _header(topology_st, label): - topology_st.standalone.log.info("\n\n###############################################") - topology_st.standalone.log.info("#######") - topology_st.standalone.log.info("####### %s" % label) - topology_st.standalone.log.info("#######") - topology_st.standalone.log.info("###############################################") - - -def test_47838_init(topology_st): - """ - Generate self signed cert and import it to the DS cert db. - Enable SSL - """ - _header(topology_st, 'Testing Ticket 47838 - harden the list of ciphers available by default') - onss_version = os.popen("rpm -q nss | awk -F'-' '{print $2}'", "r") - global nss_version - nss_version = onss_version.readline() - nss_ssl = NssSsl(dbpath=topology_st.standalone.get_cert_dir()) - nss_ssl.reinit() - nss_ssl.create_rsa_ca() - nss_ssl.create_rsa_key_and_cert() - - log.info("\n######################### enable SSL in the directory server with all ciphers ######################\n") - topology_st.standalone.simple_bind_s(DN_DM, PASSWORD) - topology_st.standalone.modify_s(ENCRYPTION_DN, [(ldap.MOD_REPLACE, 'nsSSL3', b'off'), - (ldap.MOD_REPLACE, 'nsTLS1', b'on'), - (ldap.MOD_REPLACE, 'nsSSLClientAuth', b'allowed'), - (ldap.MOD_REPLACE, 'allowWeakCipher', b'on'), - (ldap.MOD_REPLACE, 'nsSSL3Ciphers', b'+all')]) - - topology_st.standalone.modify_s(CONFIG_DN, [(ldap.MOD_REPLACE, 'nsslapd-security', b'on'), - (ldap.MOD_REPLACE, 'nsslapd-ssl-check-hostname', b'off'), - (ldap.MOD_REPLACE, 'nsslapd-secureport', ensure_bytes(MY_SECURE_PORT))]) - - topology_st.standalone.add_s(Entry((RSA_DN, {'objectclass': "top nsEncryptionModule".split(), - 'cn': RSA, - 'nsSSLPersonalitySSL': SERVERCERT, - 'nsSSLToken': 'internal (software)', - 'nsSSLActivation': 'on'}))) - - -def comp_nsSSLEnableCipherCount(topology_st, ecount): - """ - Check nsSSLEnabledCipher count with ecount - """ - log.info("Checking nsSSLEnabledCiphers...") - msgid = topology_st.standalone.search_ext(ENCRYPTION_DN, ldap.SCOPE_BASE, 'cn=*', ['nsSSLEnabledCiphers']) - enabledciphercnt = 0 - rtype, rdata, rmsgid = topology_st.standalone.result2(msgid) - topology_st.standalone.log.info("%d results" % len(rdata)) - - topology_st.standalone.log.info("Results:") - for dn, attrs in rdata: - topology_st.standalone.log.info("dn: %s" % dn) - if 'nsSSLEnabledCiphers' in attrs: - enabledciphercnt = len(attrs['nsSSLEnabledCiphers']) - topology_st.standalone.log.info("enabledCipherCount: %d" % enabledciphercnt) - assert ecount == enabledciphercnt - - -def test_47838_run_0(topology_st): - """ - Check nsSSL3Ciphers: +all - All ciphers are enabled except null. - Note: allowWeakCipher: on - """ - _header(topology_st, 'Test Case 1 - Check the ciphers availability for "+all"; allowWeakCipher: on') - topology_st.standalone.simple_bind_s(DN_DM, PASSWORD) - topology_st.standalone.modify_s(CONFIG_DN, [(ldap.MOD_REPLACE, 'nsslapd-errorlog-level', b'64')]) - time.sleep(5) - log.info("\n######################### Restarting the server ######################\n") - topology_st.standalone.restart(timeout=120) - enabled = os.popen('egrep "SSL info:" %s | egrep \": enabled\" | wc -l' % topology_st.standalone.errlog) - disabled = os.popen('egrep "SSL info:" %s | egrep \": disabled\" | wc -l' % topology_st.standalone.errlog) - ecount = int(enabled.readline().rstrip()) - dcount = int(disabled.readline().rstrip()) - - log.info("Enabled ciphers: %d" % ecount) - log.info("Disabled ciphers: %d" % dcount) - if nss_version >= NSS320: - assert ecount >= 53 - assert dcount <= 17 - else: - assert ecount >= 60 - assert dcount <= 7 - - global plus_all_ecount - global plus_all_dcount - plus_all_ecount = ecount - plus_all_dcount = dcount - weak = os.popen('egrep "SSL info:" %s | egrep "WEAK CIPHER" | wc -l' % topology_st.standalone.errlog) - wcount = int(weak.readline().rstrip()) - log.info("Weak ciphers: %d" % wcount) - assert wcount <= 29 - - comp_nsSSLEnableCipherCount(topology_st, ecount) - - -def test_47838_run_1(topology_st): - """ - Check nsSSL3Ciphers: +all - All ciphers are enabled except null. - Note: default allowWeakCipher (i.e., off) for +all - """ - _header(topology_st, 'Test Case 2 - Check the ciphers availability for "+all" with default allowWeakCiphers') - - topology_st.standalone.simple_bind_s(DN_DM, PASSWORD) - topology_st.standalone.modify_s(CONFIG_DN, [(ldap.MOD_REPLACE, 'nsslapd-errorlog-level', b'64')]) - time.sleep(1) - # Make sure allowWeakCipher is not set. - topology_st.standalone.modify_s(ENCRYPTION_DN, [(ldap.MOD_DELETE, 'allowWeakCipher', None)]) - - log.info("\n######################### Restarting the server ######################\n") - log.info("\n######################### Restarting the server ######################\n") - topology_st.standalone.stop(timeout=10) - os.system('mv %s %s.47838_0' % (topology_st.standalone.errlog, topology_st.standalone.errlog)) - os.system('touch %s' % (topology_st.standalone.errlog)) - time.sleep(1) - topology_st.standalone.start(timeout=120) - - enabled = os.popen('egrep "SSL info:" %s | egrep \": enabled\" | wc -l' % topology_st.standalone.errlog) - disabled = os.popen('egrep "SSL info:" %s | egrep \": disabled\" | wc -l' % topology_st.standalone.errlog) - ecount = int(enabled.readline().rstrip()) - dcount = int(disabled.readline().rstrip()) - - global plus_all_ecount_noweak - global plus_all_dcount_noweak - plus_all_ecount_noweak = ecount - plus_all_dcount_noweak = dcount - - log.info("Enabled ciphers: %d" % ecount) - log.info("Disabled ciphers: %d" % dcount) - assert ecount >= 31 - assert dcount <= 36 - weak = os.popen('egrep "SSL info:" %s | egrep "WEAK CIPHER" | wc -l' % topology_st.standalone.errlog) - wcount = int(weak.readline().rstrip()) - log.info("Weak ciphers: %d" % wcount) - assert wcount <= 29 - - comp_nsSSLEnableCipherCount(topology_st, ecount) - - -def test_47838_run_2(topology_st): - """ - Check nsSSL3Ciphers: +rsa_aes_128_sha,+rsa_aes_256_sha - rsa_aes_128_sha, tls_rsa_aes_128_sha, rsa_aes_256_sha, tls_rsa_aes_256_sha are enabled. - default allowWeakCipher - """ - _header(topology_st, - 'Test Case 3 - Check the ciphers availability for "+rsa_aes_128_sha,+rsa_aes_256_sha" with default allowWeakCipher') - - topology_st.standalone.simple_bind_s(DN_DM, PASSWORD) - topology_st.standalone.modify_s(ENCRYPTION_DN, - [(ldap.MOD_REPLACE, 'nsSSL3Ciphers', b'+rsa_aes_128_sha,+rsa_aes_256_sha')]) - - log.info("\n######################### Restarting the server ######################\n") - topology_st.standalone.stop(timeout=10) - os.system('mv %s %s.47838_1' % (topology_st.standalone.errlog, topology_st.standalone.errlog)) - os.system('touch %s' % (topology_st.standalone.errlog)) - time.sleep(1) - topology_st.standalone.start(timeout=120) - - enabled = os.popen('egrep "SSL info:" %s | egrep \": enabled\" | wc -l' % topology_st.standalone.errlog) - disabled = os.popen('egrep "SSL info:" %s | egrep \": disabled\" | wc -l' % topology_st.standalone.errlog) - ecount = int(enabled.readline().rstrip()) - dcount = int(disabled.readline().rstrip()) - - log.info("Enabled ciphers: %d" % ecount) - log.info("Disabled ciphers: %d" % dcount) - global plus_all_ecount - global plus_all_dcount - assert ecount == 2 - assert dcount == (plus_all_ecount + plus_all_dcount - ecount) - - comp_nsSSLEnableCipherCount(topology_st, ecount) - - -def test_47838_run_3(topology_st): - """ - Check nsSSL3Ciphers: -all - All ciphers are disabled. - default allowWeakCipher - """ - _header(topology_st, 'Test Case 4 - Check the ciphers availability for "-all"') - - topology_st.standalone.simple_bind_s(DN_DM, PASSWORD) - topology_st.standalone.modify_s(ENCRYPTION_DN, [(ldap.MOD_REPLACE, 'nsSSL3Ciphers', b'-all')]) - - log.info("\n######################### Restarting the server ######################\n") - topology_st.standalone.stop(timeout=10) - os.system('mv %s %s.47838_2' % (topology_st.standalone.errlog, topology_st.standalone.errlog)) - os.system('touch %s' % (topology_st.standalone.errlog)) - time.sleep(1) - topology_st.standalone.start(timeout=120) - - enabled = os.popen('egrep "SSL info:" %s | egrep \": enabled\" | wc -l' % topology_st.standalone.errlog) - ecount = int(enabled.readline().rstrip()) - - log.info("Enabled ciphers: %d" % ecount) - global plus_all_ecount - assert ecount == 0 - - disabledmsg = os.popen('egrep "Disabling SSL" %s' % topology_st.standalone.errlog) - log.info("Disabling SSL message?: %s" % disabledmsg.readline()) - assert disabledmsg != '' - - comp_nsSSLEnableCipherCount(topology_st, ecount) - - -def test_47838_run_4(topology_st): - """ - Check no nsSSL3Ciphers - Default ciphers are enabled. - default allowWeakCipher - """ - _header(topology_st, 'Test Case 5 - Check no nsSSL3Ciphers (default setting) with default allowWeakCipher') - - topology_st.standalone.simple_bind_s(DN_DM, PASSWORD) - topology_st.standalone.modify_s(ENCRYPTION_DN, [(ldap.MOD_DELETE, 'nsSSL3Ciphers', b'-all')]) - - log.info("\n######################### Restarting the server ######################\n") - topology_st.standalone.stop(timeout=10) - os.system('mv %s %s.47838_3' % (topology_st.standalone.errlog, topology_st.standalone.errlog)) - os.system('touch %s' % (topology_st.standalone.errlog)) - time.sleep(1) - topology_st.standalone.start(timeout=120) - enabled = os.popen('egrep "SSL info:" %s | egrep \": enabled\" | wc -l' % topology_st.standalone.errlog) - disabled = os.popen('egrep "SSL info:" %s | egrep \": disabled\" | wc -l' % topology_st.standalone.errlog) - ecount = int(enabled.readline().rstrip()) - dcount = int(disabled.readline().rstrip()) - - log.info("Enabled ciphers: %d" % ecount) - log.info("Disabled ciphers: %d" % dcount) - global plus_all_ecount - global plus_all_dcount - if nss_version >= NSS330: - assert ecount == 28 - elif nss_version >= NSS323: - assert ecount == 29 - else: - assert ecount == 20 - assert dcount == (plus_all_ecount + plus_all_dcount - ecount) - weak = os.popen( - 'egrep "SSL info:" %s | egrep \": enabled\" | egrep "WEAK CIPHER" | wc -l' % topology_st.standalone.errlog) - wcount = int(weak.readline().rstrip()) - log.info("Weak ciphers in the default setting: %d" % wcount) - assert wcount == 0 - - comp_nsSSLEnableCipherCount(topology_st, ecount) - - -def test_47838_run_5(topology_st): - """ - Check nsSSL3Ciphers: default - Default ciphers are enabled. - default allowWeakCipher - """ - _header(topology_st, 'Test Case 6 - Check default nsSSL3Ciphers (default setting) with default allowWeakCipher') - - topology_st.standalone.simple_bind_s(DN_DM, PASSWORD) - topology_st.standalone.modify_s(ENCRYPTION_DN, [(ldap.MOD_REPLACE, 'nsSSL3Ciphers', b'default')]) - - log.info("\n######################### Restarting the server ######################\n") - topology_st.standalone.stop(timeout=10) - os.system('mv %s %s.47838_4' % (topology_st.standalone.errlog, topology_st.standalone.errlog)) - os.system('touch %s' % (topology_st.standalone.errlog)) - time.sleep(1) - topology_st.standalone.start(timeout=120) - - enabled = os.popen('egrep "SSL info:" %s | egrep \": enabled\" | wc -l' % topology_st.standalone.errlog) - disabled = os.popen('egrep "SSL info:" %s | egrep \": disabled\" | wc -l' % topology_st.standalone.errlog) - ecount = int(enabled.readline().rstrip()) - dcount = int(disabled.readline().rstrip()) - - log.info("Enabled ciphers: %d" % ecount) - log.info("Disabled ciphers: %d" % dcount) - global plus_all_ecount - global plus_all_dcount - if nss_version >= NSS330: - assert ecount == 28 - elif nss_version >= NSS323: - assert ecount == 29 - else: - assert ecount == 23 - assert dcount == (plus_all_ecount + plus_all_dcount - ecount) - weak = os.popen( - 'egrep "SSL info:" %s | egrep \": enabled\" | egrep "WEAK CIPHER" | wc -l' % topology_st.standalone.errlog) - wcount = int(weak.readline().rstrip()) - log.info("Weak ciphers in the default setting: %d" % wcount) - assert wcount == 0 - - comp_nsSSLEnableCipherCount(topology_st, ecount) - - -def test_47838_run_6(topology_st): - """ - Check nsSSL3Ciphers: +all,-rsa_rc4_128_md5 - All ciphers are disabled. - default allowWeakCipher - """ - _header(topology_st, - 'Test Case 7 - Check nsSSL3Ciphers: +all,-tls_dhe_rsa_aes_128_gcm_sha with default allowWeakCipher') - - topology_st.standalone.simple_bind_s(DN_DM, PASSWORD) - topology_st.standalone.modify_s(ENCRYPTION_DN, - [(ldap.MOD_REPLACE, 'nsSSL3Ciphers', b'+all,-tls_dhe_rsa_aes_128_gcm_sha')]) - - log.info("\n######################### Restarting the server ######################\n") - topology_st.standalone.stop(timeout=10) - os.system('mv %s %s.47838_5' % (topology_st.standalone.errlog, topology_st.standalone.errlog)) - os.system('touch %s' % (topology_st.standalone.errlog)) - time.sleep(1) - topology_st.standalone.start(timeout=120) - - enabled = os.popen('egrep "SSL info:" %s | egrep \": enabled\" | wc -l' % topology_st.standalone.errlog) - disabled = os.popen('egrep "SSL info:" %s | egrep \": disabled\" | wc -l' % topology_st.standalone.errlog) - ecount = int(enabled.readline().rstrip()) - dcount = int(disabled.readline().rstrip()) - - log.info("Enabled ciphers: %d" % ecount) - log.info("Disabled ciphers: %d" % dcount) - global plus_all_ecount_noweak - global plus_all_dcount_noweak - log.info("ALL Ecount: %d" % plus_all_ecount_noweak) - log.info("ALL Dcount: %d" % plus_all_dcount_noweak) - assert ecount == (plus_all_ecount_noweak - 1) - assert dcount == (plus_all_dcount_noweak + 1) - - comp_nsSSLEnableCipherCount(topology_st, ecount) - - -def test_47838_run_7(topology_st): - """ - Check nsSSL3Ciphers: -all,+rsa_rc4_128_md5 - All ciphers are disabled. - default allowWeakCipher - """ - _header(topology_st, 'Test Case 8 - Check nsSSL3Ciphers: -all,+rsa_rc4_128_md5 with default allowWeakCipher') - - topology_st.standalone.simple_bind_s(DN_DM, PASSWORD) - topology_st.standalone.modify_s(ENCRYPTION_DN, [(ldap.MOD_REPLACE, 'nsSSL3Ciphers', b'-all,+rsa_rc4_128_md5')]) - - log.info("\n######################### Restarting the server ######################\n") - topology_st.standalone.stop(timeout=10) - os.system('mv %s %s.47838_6' % (topology_st.standalone.errlog, topology_st.standalone.errlog)) - os.system('touch %s' % (topology_st.standalone.errlog)) - time.sleep(1) - topology_st.standalone.start(timeout=120) - - enabled = os.popen('egrep "SSL info:" %s | egrep \": enabled\" | wc -l' % topology_st.standalone.errlog) - disabled = os.popen('egrep "SSL info:" %s | egrep \": disabled\" | wc -l' % topology_st.standalone.errlog) - ecount = int(enabled.readline().rstrip()) - dcount = int(disabled.readline().rstrip()) - - log.info("Enabled ciphers: %d" % ecount) - log.info("Disabled ciphers: %d" % dcount) - global plus_all_ecount - global plus_all_dcount - assert ecount == 1 - assert dcount == (plus_all_ecount + plus_all_dcount - ecount) - - comp_nsSSLEnableCipherCount(topology_st, ecount) - - -def test_47838_run_8(topology_st): - """ - Check nsSSL3Ciphers: default + allowWeakCipher: off - Strong Default ciphers are enabled. - """ - _header(topology_st, 'Test Case 9 - Check default nsSSL3Ciphers (default setting + allowWeakCipher: off)') - - topology_st.standalone.simple_bind_s(DN_DM, PASSWORD) - topology_st.standalone.modify_s(ENCRYPTION_DN, [(ldap.MOD_REPLACE, 'nsSSL3Ciphers', b'default'), - (ldap.MOD_REPLACE, 'allowWeakCipher', b'off')]) - - log.info("\n######################### Restarting the server ######################\n") - topology_st.standalone.stop(timeout=10) - os.system('mv %s %s.47838_7' % (topology_st.standalone.errlog, topology_st.standalone.errlog)) - os.system('touch %s' % (topology_st.standalone.errlog)) - time.sleep(1) - topology_st.standalone.start(timeout=120) - - enabled = os.popen('egrep "SSL info:" %s | egrep \": enabled\" | wc -l' % topology_st.standalone.errlog) - disabled = os.popen('egrep "SSL info:" %s | egrep \": disabled\" | wc -l' % topology_st.standalone.errlog) - ecount = int(enabled.readline().rstrip()) - dcount = int(disabled.readline().rstrip()) - - log.info("Enabled ciphers: %d" % ecount) - log.info("Disabled ciphers: %d" % dcount) - global plus_all_ecount - global plus_all_dcount - if nss_version >= NSS330: - assert ecount == 28 - elif nss_version >= NSS323: - assert ecount == 29 - else: - assert ecount == 23 - assert dcount == (plus_all_ecount + plus_all_dcount - ecount) - weak = os.popen( - 'egrep "SSL info:" %s | egrep \": enabled\" | egrep "WEAK CIPHER" | wc -l' % topology_st.standalone.errlog) - wcount = int(weak.readline().rstrip()) - log.info("Weak ciphers in the default setting: %d" % wcount) - assert wcount == 0 - - comp_nsSSLEnableCipherCount(topology_st, ecount) - - -def test_47838_run_9(topology_st): - """ - Check no nsSSL3Ciphers - Default ciphers are enabled. - allowWeakCipher: on - nsslapd-errorlog-level: 0 - """ - _header(topology_st, - 'Test Case 10 - Check no nsSSL3Ciphers (default setting) with no errorlog-level & allowWeakCipher on') - - topology_st.standalone.simple_bind_s(DN_DM, PASSWORD) - topology_st.standalone.modify_s(ENCRYPTION_DN, [(ldap.MOD_REPLACE, 'nsSSL3Ciphers', None), - (ldap.MOD_REPLACE, 'allowWeakCipher', b'on')]) - topology_st.standalone.modify_s(CONFIG_DN, [(ldap.MOD_REPLACE, 'nsslapd-errorlog-level', None)]) - - log.info("\n######################### Restarting the server ######################\n") - topology_st.standalone.stop(timeout=10) - os.system('mv %s %s.47838_8' % (topology_st.standalone.errlog, topology_st.standalone.errlog)) - os.system('touch %s' % (topology_st.standalone.errlog)) - time.sleep(1) - topology_st.standalone.start(timeout=120) - - enabled = os.popen('egrep "SSL info:" %s | egrep \": enabled\" | wc -l' % topology_st.standalone.errlog) - disabled = os.popen('egrep "SSL info:" %s | egrep \": disabled\" | wc -l' % topology_st.standalone.errlog) - ecount = int(enabled.readline().rstrip()) - dcount = int(disabled.readline().rstrip()) - - log.info("Enabled ciphers: %d" % ecount) - log.info("Disabled ciphers: %d" % dcount) - if nss_version >= NSS330: - assert ecount == 33 - elif nss_version >= NSS327: - assert ecount == 34 - elif nss_version >= NSS323: - assert ecount == 36 - else: - assert ecount == 30 - assert dcount == 0 - weak = os.popen( - 'egrep "SSL info:" %s | egrep \": enabled\" | egrep "WEAK CIPHER" | wc -l' % topology_st.standalone.errlog) - wcount = int(weak.readline().rstrip()) - log.info("Weak ciphers in the default setting: %d" % wcount) - if nss_version >= NSS327: - assert wcount == 5 - elif nss_version >= NSS320: - assert wcount == 7 - else: - assert wcount == 11 - - comp_nsSSLEnableCipherCount(topology_st, ecount) - - -def test_47838_run_10(topology_st): - """ - Check nsSSL3Ciphers: -TLS_RSA_WITH_NULL_MD5,+TLS_RSA_WITH_RC4_128_MD5, - +TLS_RSA_EXPORT_WITH_RC4_40_MD5,+TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5, - +TLS_DHE_RSA_WITH_DES_CBC_SHA,+SSL_RSA_FIPS_WITH_DES_CBC_SHA, - +TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA,+SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA, - +TLS_RSA_EXPORT1024_WITH_RC4_56_SHA,+TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA, - -SSL_CK_RC4_128_WITH_MD5,-SSL_CK_RC4_128_EXPORT40_WITH_MD5, - -SSL_CK_RC2_128_CBC_WITH_MD5,-SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5, - -SSL_CK_DES_64_CBC_WITH_MD5,-SSL_CK_DES_192_EDE3_CBC_WITH_MD5 - allowWeakCipher: on - nsslapd-errorlog-level: 0 - """ - _header(topology_st, - 'Test Case 11 - Check nsSSL3Ciphers: long list using the NSS Cipher Suite name with allowWeakCipher on') - - topology_st.standalone.simple_bind_s(DN_DM, PASSWORD) - topology_st.standalone.modify_s(ENCRYPTION_DN, [(ldap.MOD_REPLACE, 'nsSSL3Ciphers', - b'-TLS_RSA_WITH_NULL_MD5,+TLS_RSA_WITH_RC4_128_MD5,+TLS_RSA_EXPORT_WITH_RC4_40_MD5,+TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5,+TLS_DHE_RSA_WITH_DES_CBC_SHA,+SSL_RSA_FIPS_WITH_DES_CBC_SHA,+TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA,+SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA,+TLS_RSA_EXPORT1024_WITH_RC4_56_SHA,+TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA,-SSL_CK_RC4_128_WITH_MD5,-SSL_CK_RC4_128_EXPORT40_WITH_MD5,-SSL_CK_RC2_128_CBC_WITH_MD5,-SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5,-SSL_CK_DES_64_CBC_WITH_MD5,-SSL_CK_DES_192_EDE3_CBC_WITH_MD5')]) - - log.info("\n######################### Restarting the server ######################\n") - topology_st.standalone.stop(timeout=10) - os.system('mv %s %s.47838_9' % (topology_st.standalone.errlog, topology_st.standalone.errlog)) - os.system('touch %s' % (topology_st.standalone.errlog)) - time.sleep(1) - topology_st.standalone.start(timeout=120) - - enabled = os.popen('egrep "SSL info:" %s | egrep \": enabled\" | wc -l' % topology_st.standalone.errlog) - disabled = os.popen('egrep "SSL info:" %s | egrep \": disabled\" | wc -l' % topology_st.standalone.errlog) - ecount = int(enabled.readline().rstrip()) - dcount = int(disabled.readline().rstrip()) - - log.info("Enabled ciphers: %d" % ecount) - log.info("Disabled ciphers: %d" % dcount) - global plus_all_ecount - global plus_all_dcount - if nss_version >= NSS330: - assert ecount == 3 - else: - assert ecount == 9 - assert dcount == 0 - weak = os.popen( - 'egrep "SSL info:" %s | egrep \": enabled\" | egrep "WEAK CIPHER" | wc -l' % topology_st.standalone.errlog) - wcount = int(weak.readline().rstrip()) - log.info("Weak ciphers in the default setting: %d" % wcount) - - topology_st.standalone.log.info("ticket47838 was successfully verified.") - - comp_nsSSLEnableCipherCount(topology_st, ecount) - - -def test_47838_run_11(topology_st): - """ - Check nsSSL3Ciphers: +fortezza - SSL_GetImplementedCiphers does not return this as a secuire cipher suite - """ - _header(topology_st, 'Test Case 12 - Check nsSSL3Ciphers: +fortezza, which is not supported') - - topology_st.standalone.simple_bind_s(DN_DM, PASSWORD) - topology_st.standalone.modify_s(ENCRYPTION_DN, [(ldap.MOD_REPLACE, 'nsSSL3Ciphers', b'+fortezza')]) - - log.info("\n######################### Restarting the server ######################\n") - topology_st.standalone.stop(timeout=10) - os.system('mv %s %s.47838_10' % (topology_st.standalone.errlog, topology_st.standalone.errlog)) - os.system('touch %s' % (topology_st.standalone.errlog)) - time.sleep(1) - topology_st.standalone.start(timeout=120) - - errmsg = os.popen('egrep "SSL info:" %s | egrep "is not available in NSS"' % topology_st.standalone.errlog) - if errmsg != "": - log.info("Expected error message:") - log.info("%s" % errmsg.readline()) - else: - log.info("Expected error message was not found") - assert False - - comp_nsSSLEnableCipherCount(topology_st, 0) - - -def test_47928_run_0(topology_st): - """ - No SSL version config parameters. - Check SSL3 (TLS1.0) is off. - """ - _header(topology_st, 'Test Case 13 - No SSL version config parameters') - - topology_st.standalone.simple_bind_s(DN_DM, PASSWORD) - # add them once and remove them - topology_st.standalone.modify_s(ENCRYPTION_DN, [(ldap.MOD_REPLACE, 'nsSSL3', b'off'), - (ldap.MOD_REPLACE, 'nsTLS1', b'on'), - (ldap.MOD_REPLACE, 'sslVersionMin', b'TLS1.1'), - (ldap.MOD_REPLACE, 'sslVersionMax', b'TLS1.2')]) - topology_st.standalone.modify_s(ENCRYPTION_DN, [(ldap.MOD_DELETE, 'nsSSL3', None), - (ldap.MOD_DELETE, 'nsTLS1', None), - (ldap.MOD_DELETE, 'sslVersionMin', None), - (ldap.MOD_DELETE, 'sslVersionMax', None)]) - topology_st.standalone.modify_s(CONFIG_DN, [(ldap.MOD_REPLACE, 'nsslapd-errorlog-level', b'64')]) - time.sleep(5) - - log.info("\n######################### Restarting the server ######################\n") - topology_st.standalone.stop(timeout=10) - os.system('mv %s %s.47838_11' % (topology_st.standalone.errlog, topology_st.standalone.errlog)) - os.system('touch %s' % (topology_st.standalone.errlog)) - time.sleep(1) - topology_st.standalone.start(timeout=120) - - errmsg = os.popen( - 'egrep "SSL info:" %s | egrep "Default SSL Version settings; Configuring the version range as min: TLS1.1"' % topology_st.standalone.errlog) - if errmsg != "": - log.info("Expected message:") - log.info("%s" % errmsg.readline()) - else: - log.info("Expected message was not found") - assert False - - -def test_47928_run_1(topology_st): - """ - No nsSSL3, nsTLS1; sslVersionMin > sslVersionMax - Check sslVersionMax is ignored. - """ - _header(topology_st, 'Test Case 14 - No nsSSL3, nsTLS1; sslVersionMin > sslVersionMax') - - topology_st.standalone.simple_bind_s(DN_DM, PASSWORD) - topology_st.standalone.modify_s(ENCRYPTION_DN, [(ldap.MOD_REPLACE, 'sslVersionMin', b'TLS1.2'), - (ldap.MOD_REPLACE, 'sslVersionMax', b'TLS1.1')]) - - log.info("\n######################### Restarting the server ######################\n") - topology_st.standalone.stop(timeout=10) - os.system('mv %s %s.47838_12' % (topology_st.standalone.errlog, topology_st.standalone.errlog)) - os.system('touch %s' % (topology_st.standalone.errlog)) - topology_st.standalone.start(timeout=120) - - errmsg = os.popen( - 'egrep "SSL info:" %s | egrep "The min value of NSS version range"' % topology_st.standalone.errlog) - if errmsg != "": - log.info("Expected message:") - log.info("%s" % errmsg.readline()) - else: - log.info("Expected message was not found") - assert False - - errmsg = os.popen( - 'egrep "SSL Initialization" %s | egrep "Configured SSL version range: min: TLS1.2, max: TLS1"' % topology_st.standalone.errlog) - if errmsg != "": - log.info("Expected message:") - log.info("%s" % errmsg.readline()) - else: - log.info("Expected message was not found") - assert False - - -def test_47928_run_2(topology_st): - """ - nsSSL3: on; sslVersionMin: TLS1.1; sslVersionMax: TLS1.2 - Conflict between nsSSL3 and range; nsSSL3 is disabled - """ - _header(topology_st, 'Test Case 15 - nsSSL3: on; sslVersionMin: TLS1.1; sslVersionMax: TLS1.2') - - topology_st.standalone.simple_bind_s(DN_DM, PASSWORD) - topology_st.standalone.modify_s(ENCRYPTION_DN, [(ldap.MOD_REPLACE, 'sslVersionMin', b'TLS1.1'), - (ldap.MOD_REPLACE, 'sslVersionMax', b'TLS1.2'), - (ldap.MOD_REPLACE, 'nsSSL3', b'on')]) - - log.info("\n######################### Restarting the server ######################\n") - topology_st.standalone.stop(timeout=10) - os.system('mv %s %s.47838_13' % (topology_st.standalone.errlog, topology_st.standalone.errlog)) - os.system('touch %s' % (topology_st.standalone.errlog)) - time.sleep(1) - topology_st.standalone.start(timeout=120) - - errmsg = os.popen( - 'egrep "SSL info:" %s | egrep "Found unsecure configuration: nsSSL3: on"' % topology_st.standalone.errlog) - if errmsg != "": - log.info("Expected message:") - log.info("%s" % errmsg.readline()) - else: - log.info("Expected message was not found") - assert False - - errmsg = os.popen('egrep "SSL info:" %s | egrep "Respect the supported range."' % topology_st.standalone.errlog) - if errmsg != "": - log.info("Expected message:") - log.info("%s" % errmsg.readline()) - else: - log.info("Expected message was not found") - assert False - - errmsg = os.popen( - 'egrep "SSL Initialization" %s | egrep "Configured SSL version range: min: TLS1.1, max: TLS1"' % topology_st.standalone.errlog) - if errmsg != "": - log.info("Expected message:") - log.info("%s" % errmsg.readline()) - else: - log.info("Expected message was not found") - assert False - - -def test_47928_run_3(topology_st): - """ - nsSSL3: on; nsTLS1: off; sslVersionMin: TLS1.1; sslVersionMax: TLS1.2 - Conflict between nsSSL3/nsTLS1 and range; nsSSL3 is disabled; nsTLS1 is enabled. - """ - _header(topology_st, 'Test Case 16 - nsSSL3: on; nsTLS1: off; sslVersionMin: TLS1.1; sslVersionMax: TLS1.2') - - topology_st.standalone.simple_bind_s(DN_DM, PASSWORD) - topology_st.standalone.modify_s(ENCRYPTION_DN, [(ldap.MOD_REPLACE, 'sslVersionMin', b'TLS1.1'), - (ldap.MOD_REPLACE, 'sslVersionMax', b'TLS1.2'), - (ldap.MOD_REPLACE, 'nsSSL3', b'on'), - (ldap.MOD_REPLACE, 'nsTLS1', b'off')]) - - log.info("\n######################### Restarting the server ######################\n") - topology_st.standalone.stop(timeout=10) - os.system('mv %s %s.47838_14' % (topology_st.standalone.errlog, topology_st.standalone.errlog)) - os.system('touch %s' % (topology_st.standalone.errlog)) - time.sleep(1) - topology_st.standalone.start(timeout=120) - - errmsg = os.popen( - 'egrep "SSL info:" %s | egrep "Found unsecure configuration: nsSSL3: on"' % topology_st.standalone.errlog) - if errmsg != "": - log.info("Expected message:") - log.info("%s" % errmsg.readline()) - else: - log.info("Expected message was not found") - assert False - - errmsg = os.popen('egrep "SSL info:" %s | egrep "Respect the configured range."' % topology_st.standalone.errlog) - if errmsg != "": - log.info("Expected message:") - log.info("%s" % errmsg.readline()) - else: - log.info("Expected message was not found") - assert False - - errmsg = os.popen( - 'egrep "SSL Initialization" %s | egrep "Configured SSL version range: min: TLS1.1, max: TLS1"' % topology_st.standalone.errlog) - if errmsg != "": - log.info("Expected message:") - log.info("%s" % errmsg.readline()) - else: - log.info("Expected message was not found") - assert False - - -def test_47838_run_last(topology_st): - """ - Check nsSSL3Ciphers: all <== invalid value - All ciphers are disabled. - """ - _header(topology_st, 'Test Case 17 - Check nsSSL3Ciphers: all, which is invalid') - - topology_st.standalone.simple_bind_s(DN_DM, PASSWORD) - topology_st.standalone.modify_s(CONFIG_DN, [(ldap.MOD_REPLACE, 'nsslapd-errorlog-level', None)]) - topology_st.standalone.modify_s(ENCRYPTION_DN, [(ldap.MOD_REPLACE, 'nsSSL3Ciphers', b'all')]) - - log.info("\n######################### Restarting the server ######################\n") - topology_st.standalone.stop(timeout=10) - os.system('mv %s %s.47838_15' % (topology_st.standalone.errlog, topology_st.standalone.errlog)) - os.system('touch %s' % (topology_st.standalone.errlog)) - time.sleep(1) - topology_st.standalone.start(timeout=120) - - errmsg = os.popen('egrep "SSL info:" %s | egrep "invalid ciphers"' % topology_st.standalone.errlog) - if errmsg != "": - log.info("Expected error message:") - log.info("%s" % errmsg.readline()) - else: - log.info("Expected error message was not found") - assert False - - comp_nsSSLEnableCipherCount(topology_st, 0) - - topology_st.standalone.log.info("ticket47838, 47880, 47908, 47928 were successfully verified.") - - -if __name__ == '__main__': - # Run isolated - # -s for DEBUG mode - CURRENT_FILE = os.path.realpath(__file__) - pytest.main("-s %s" % CURRENT_FILE) diff --git a/dirsrvtests/tests/tickets/ticket47950_test.py b/dirsrvtests/tests/tickets/ticket47950_test.py deleted file mode 100644 index 744b80174..000000000 --- a/dirsrvtests/tests/tickets/ticket47950_test.py +++ /dev/null @@ -1,160 +0,0 @@ -# --- BEGIN COPYRIGHT BLOCK --- -# Copyright (C) 2016 Red Hat, Inc. -# All rights reserved. -# -# License: GPL (version 3 or any later version). -# See LICENSE for details. -# --- END COPYRIGHT BLOCK --- -# -import logging - -import pytest -from lib389.tasks import * -from lib389.topologies import topology_st - -from lib389._constants import (defaultProperties, DEFAULT_SUFFIX, ReplicaRole, - REPLICAID_MASTER_1, REPLICATION_BIND_DN, REPLICATION_BIND_PW, - REPLICATION_BIND_METHOD, REPLICATION_TRANSPORT, RA_NAME, - RA_BINDDN, RA_BINDPW, RA_METHOD, RA_TRANSPORT_PROT, - DN_DM, PASSWORD, REPLICA_ID, RA_CONSUMER_PORT) - -pytestmark = pytest.mark.tier2 - -log = logging.getLogger(__name__) - -USER1_DN = "uid=user1,%s" % DEFAULT_SUFFIX -USER2_DN = "uid=user2,%s" % DEFAULT_SUFFIX - - -def test_ticket47950(topology_st): - """ - Testing nsslapd-plugin-binddn-tracking does not cause issues around - access control and reconfiguring replication/repl agmt. - """ - - log.info('Testing Ticket 47950 - Testing nsslapd-plugin-binddn-tracking') - - # - # Turn on bind dn tracking - # - try: - topology_st.standalone.modify_s("cn=config", [(ldap.MOD_REPLACE, 'nsslapd-plugin-binddn-tracking', 'on')]) - log.info('nsslapd-plugin-binddn-tracking enabled.') - except ldap.LDAPError as e: - log.error('Failed to enable bind dn tracking: ' + e.message['desc']) - assert False - - # - # Add two users - # - try: - topology_st.standalone.add_s(Entry((USER1_DN, { - 'objectclass': "top person inetuser".split(), - 'userpassword': "password", - 'sn': "1", - 'cn': "user 1"}))) - log.info('Added test user %s' % USER1_DN) - except ldap.LDAPError as e: - log.error('Failed to add %s: %s' % (USER1_DN, e.message['desc'])) - assert False - - try: - topology_st.standalone.add_s(Entry((USER2_DN, { - 'objectclass': "top person inetuser".split(), - 'sn': "2", - 'cn': "user 2"}))) - log.info('Added test user %s' % USER2_DN) - except ldap.LDAPError as e: - log.error('Failed to add user1: ' + e.message['desc']) - assert False - - # - # Add an aci - # - try: - acival = '(targetattr ="cn")(version 3.0;acl "Test bind dn tracking"' + \ - ';allow (all) (userdn = "ldap:///%s");)' % USER1_DN - - topology_st.standalone.modify_s(DEFAULT_SUFFIX, [(ldap.MOD_ADD, 'aci', acival)]) - log.info('Added aci') - except ldap.LDAPError as e: - log.error('Failed to add aci: ' + e.message['desc']) - assert False - - # - # Make modification as user - # - try: - topology_st.standalone.simple_bind_s(USER1_DN, "password") - log.info('Bind as user %s successful' % USER1_DN) - except ldap.LDAPError as e: - log.error('Failed to bind as user1: ' + e.message['desc']) - assert False - - try: - topology_st.standalone.modify_s(USER2_DN, [(ldap.MOD_REPLACE, 'cn', 'new value')]) - log.info('%s successfully modified user %s' % (USER1_DN, USER2_DN)) - except ldap.LDAPError as e: - log.error('Failed to update user2: ' + e.message['desc']) - assert False - - # - # Setup replica and create a repl agmt - # - try: - topology_st.standalone.simple_bind_s(DN_DM, PASSWORD) - log.info('Bind as %s successful' % DN_DM) - except ldap.LDAPError as e: - log.error('Failed to bind as rootDN: ' + e.message['desc']) - assert False - - try: - topology_st.standalone.replica.enableReplication(suffix=DEFAULT_SUFFIX, role=ReplicaRole.MASTER, - replicaId=REPLICAID_MASTER_1) - log.info('Successfully enabled replication.') - except ValueError: - log.error('Failed to enable replication') - assert False - - properties = {RA_NAME: r'test plugin internal bind dn', - RA_BINDDN: defaultProperties[REPLICATION_BIND_DN], - RA_BINDPW: defaultProperties[REPLICATION_BIND_PW], - RA_METHOD: defaultProperties[REPLICATION_BIND_METHOD], - RA_TRANSPORT_PROT: defaultProperties[REPLICATION_TRANSPORT]} - - try: - repl_agreement = topology_st.standalone.agreement.create(suffix=DEFAULT_SUFFIX, host="127.0.0.1", - port="7777", properties=properties) - log.info('Successfully created replication agreement') - except InvalidArgumentError as e: - log.error('Failed to create replication agreement: ' + e.message['desc']) - assert False - - # - # modify replica - # - try: - properties = {REPLICA_ID: "7"} - topology_st.standalone.replica.setProperties(DEFAULT_SUFFIX, None, None, properties) - log.info('Successfully modified replica') - except ldap.LDAPError as e: - log.error('Failed to update replica config: ' + e.message['desc']) - assert False - - # - # modify repl agmt - # - try: - properties = {RA_CONSUMER_PORT: "8888"} - topology_st.standalone.agreement.setProperties(None, repl_agreement, None, properties) - log.info('Successfully modified replication agreement') - except ValueError: - log.error('Failed to update replica agreement: ' + repl_agreement) - assert False - - -if __name__ == '__main__': - # Run isolated - # -s for DEBUG mode - CURRENT_FILE = os.path.realpath(__file__) - pytest.main("-s %s" % CURRENT_FILE) diff --git a/ldap/servers/slapd/libglobs.c b/ldap/servers/slapd/libglobs.c index 8169863d0..81df130ce 100644 --- a/ldap/servers/slapd/libglobs.c +++ b/ldap/servers/slapd/libglobs.c @@ -4291,7 +4291,7 @@ config_set_maxdescriptors(const char *attrname, char *value, char *errorbuf, int { int32_t retVal = LDAP_SUCCESS; int64_t nValue = 0; - int64_t maxVal = 65535; + int64_t maxVal = 524288; struct rlimit rlp; char *endp = NULL; diff --git a/src/lib389/lib389/idm/directorymanager.py b/src/lib389/lib389/idm/directorymanager.py index 150a549bd..bb3b58355 100644 --- a/src/lib389/lib389/idm/directorymanager.py +++ b/src/lib389/lib389/idm/directorymanager.py @@ -43,3 +43,9 @@ class DirectoryManager(Account): """ return super(DirectoryManager, self).bind(password, *args, **kwargs) + def rebind(self, password=PW_DM): + """Rebind on the same connection + :param password: Directory Manager password + :type password: str + """ + self._instance.simple_bind_s(self.dn, password, escapehatch='i am sure')
0
4120eda907e600d7d4b7c3b54e747db8284b4037
389ds/389-ds-base
177444: duplicate password policy oids in root DSE
commit 4120eda907e600d7d4b7c3b54e747db8284b4037 Author: Pete Rowley <[email protected]> Date: Tue Jan 10 19:30:12 2006 +0000 177444: duplicate password policy oids in root DSE diff --git a/ldap/servers/slapd/control.c b/ldap/servers/slapd/control.c index d9cce7d74..40a72979d 100644 --- a/ldap/servers/slapd/control.c +++ b/ldap/servers/slapd/control.c @@ -95,10 +95,16 @@ init_controls( void ) SLAPI_OPERATION_SEARCH | SLAPI_OPERATION_COMPARE | SLAPI_OPERATION_ADD | SLAPI_OPERATION_DELETE | SLAPI_OPERATION_MODIFY | SLAPI_OPERATION_MODDN ); +/* + We do not register the password policy response because it has + the same oid as the request (and it was being reported twice in + in the root DSE supportedControls attribute) + slapi_register_supported_control( LDAP_X_CONTROL_PWPOLICY_RESPONSE, SLAPI_OPERATION_SEARCH | SLAPI_OPERATION_COMPARE | SLAPI_OPERATION_ADD | SLAPI_OPERATION_DELETE | SLAPI_OPERATION_MODIFY | SLAPI_OPERATION_MODDN ); +*/ slapi_register_supported_control( LDAP_CONTROL_GET_EFFECTIVE_RIGHTS, SLAPI_OPERATION_SEARCH ); }
0
cb73cf2b09b015696d0ef04820cfbbb564143207
389ds/389-ds-base
Ticket 47569 - ACIs do not allow attribute subtypes in targetattr keyword When validating the targetattr ACI keyword, we check if the attribute is defined in the schema. This schema check fails if the attribute has a subtype present. This patch makes the attribute syntax lookup function check if a subtype was specified before performing the looking. If a subtype is specified, it is stripped off and we just use the base attribute name to lookup the syntax from the hashtable.
commit cb73cf2b09b015696d0ef04820cfbbb564143207 Author: Nathan Kinder <[email protected]> Date: Tue Oct 22 14:28:34 2013 -0700 Ticket 47569 - ACIs do not allow attribute subtypes in targetattr keyword When validating the targetattr ACI keyword, we check if the attribute is defined in the schema. This schema check fails if the attribute has a subtype present. This patch makes the attribute syntax lookup function check if a subtype was specified before performing the looking. If a subtype is specified, it is stripped off and we just use the base attribute name to lookup the syntax from the hashtable. diff --git a/ldap/servers/slapd/attrsyntax.c b/ldap/servers/slapd/attrsyntax.c index 7abd6b781..a08ea9656 100644 --- a/ldap/servers/slapd/attrsyntax.c +++ b/ldap/servers/slapd/attrsyntax.c @@ -537,10 +537,28 @@ int attr_syntax_exists(const char *attr_name) { struct asyntaxinfo *asi; + char *check_attr_name = NULL; + char *p = NULL; + int free_attr = 0; + + /* Ignore any attribute subtypes. */ + if (p = strchr(attr_name, ';')) { + int check_attr_len = p - attr_name + 1; + + check_attr_name = (char *)slapi_ch_malloc(check_attr_len); + PR_snprintf(check_attr_name, check_attr_len, "%s", attr_name); + free_attr = 1; + } else { + check_attr_name = attr_name; + } - asi = attr_syntax_get_by_name(attr_name); + asi = attr_syntax_get_by_name(check_attr_name); attr_syntax_return( asi ); + if (free_attr) { + slapi_ch_free_string(&check_attr_name); + } + if ( asi != NULL ) { return 1;
0
f16615485adca54ecf4b51997cc54284d7353edc
389ds/389-ds-base
Ticket 50230 - improve ioerror msg when not root/dirsrv Bug Description: When not running as root or dirsrv, improve the clarity of the error messages as the previous messages were misleading. Fix Description: Improve the exception handling and messages. https://pagure.io/389-ds-base/issue/50230 Author: William Brown <[email protected]> Review by: mhonek
commit f16615485adca54ecf4b51997cc54284d7353edc Author: William Brown <[email protected]> Date: Wed Feb 27 12:11:42 2019 +1000 Ticket 50230 - improve ioerror msg when not root/dirsrv Bug Description: When not running as root or dirsrv, improve the clarity of the error messages as the previous messages were misleading. Fix Description: Improve the exception handling and messages. https://pagure.io/389-ds-base/issue/50230 Author: William Brown <[email protected]> Review by: mhonek diff --git a/src/lib389/cli/dsctl b/src/lib389/cli/dsctl index 8061b044a..ed8fc8feb 100755 --- a/src/lib389/cli/dsctl +++ b/src/lib389/cli/dsctl @@ -103,11 +103,16 @@ if __name__ == '__main__': signal.signal(signal.SIGINT, signal_handler) try: insts = inst.list(serverid=args.instance) - except PermissionError: - log.error("Unable to access instance information. Are you running as root or dirsrv?") + except (PermissionError, IOError) as e: + log.error("Unable to access instance information. Are you running as the correct user? (usually dirsrv or root)") + log.error("Error: %s" % str(e)) + sys.exit(1) + except Exception as e: + log.error("Error: %s" % str(e)) sys.exit(1) if len(insts) != 1: - log.error("No such instance '%s': this may be a permission issue." % args.instance) + log.error("No such instance '%s'" % args.instance) + log.error("Unable to access instance information. Are you running as the correct user? (usually dirsrv or root)") sys.exit(1) inst.allocate(insts[0])
0
8f5cb533588e0e83d4ffca80709d2554200514a3
389ds/389-ds-base
Resolves: #469243 Summary: ACL: support group filter Fix Description: . backoff the previous checkin . check the value of groupdn is the full ldapurl or not by ldap_url_parse. . if yes, run the search and get the search results. otherwise, evaluate the bind dn for the value as usual. . evaluate the bind dn against each group returned from the search. . additionally, added the code to trim the beginning and trailig spaces from the groupdn value, which is needed for ldap_url_parse.
commit 8f5cb533588e0e83d4ffca80709d2554200514a3 Author: Noriko Hosoi <[email protected]> Date: Sat Nov 1 22:09:16 2008 +0000 Resolves: #469243 Summary: ACL: support group filter Fix Description: . backoff the previous checkin . check the value of groupdn is the full ldapurl or not by ldap_url_parse. . if yes, run the search and get the search results. otherwise, evaluate the bind dn for the value as usual. . evaluate the bind dn against each group returned from the search. . additionally, added the code to trim the beginning and trailig spaces from the groupdn value, which is needed for ldap_url_parse. diff --git a/ldap/servers/plugins/acl/acllas.c b/ldap/servers/plugins/acl/acllas.c index 88beea158..72e7fd8c9 100644 --- a/ldap/servers/plugins/acl/acllas.c +++ b/ldap/servers/plugins/acl/acllas.c @@ -747,6 +747,7 @@ DS_LASGroupDnEval(NSErr_t *errp, char *attr_name, CmpOp_t comparator, { char *groups; + char *groupNameOrig; char *groupName; char *ptr; char *end_dn; @@ -767,7 +768,7 @@ DS_LASGroupDnEval(NSErr_t *errp, char *attr_name, CmpOp_t comparator, } groups = slapi_ch_strdup(attr_pattern); - groupName = groups; + groupNameOrig = groupName = groups; matched = ACL_FALSE; /* check if the groupdn is one of the users */ @@ -800,7 +801,17 @@ DS_LASGroupDnEval(NSErr_t *errp, char *attr_name, CmpOp_t comparator, auto char *t = end_dn; LDAP_UTF8INC(end_dn); LDAP_UTF8INC(end_dn); - *t = 0; + /* removing trailing spaces */ + LDAP_UTF8DEC(t); + while (' ' == *t || '\t' == *t) { + LDAP_UTF8DEC(t); + } + LDAP_UTF8INC(t); + *t = '\0'; + /* removing beginning spaces */ + while (' ' == *end_dn || '\t' == *end_dn) { + LDAP_UTF8INC(end_dn); + } } if (*groupName) { @@ -841,10 +852,58 @@ DS_LASGroupDnEval(NSErr_t *errp, char *attr_name, CmpOp_t comparator, slapi_log_error ( SLAPI_LOG_ACL, plugin_name, "DS_LASGroupDnEval: Param group name:%s\n", groupName); - } else {/* normal evaluation */ - - matched = acllas_eval_one_group( groupName, &lasinfo); - + } else { + LDAPURLDesc *ludp = NULL; + int rval; + Slapi_PBlock *myPb = NULL; + Slapi_Entry **grpentries = NULL; + + /* Groupdn is full ldapurl? */ + if (0 == ldap_url_parse(groupNameOrig, &ludp) && + NULL != ludp->lud_dn && + NULL != ludp->lud_scope && + NULL != ludp->lud_filter) { + /* Yes, it is full ldapurl; Let's run the search */ + myPb = slapi_pblock_new (); + slapi_search_internal_set_pb( + myPb, + ludp->lud_dn, + ludp->lud_scope, + ludp->lud_filter, + NULL, + 0, + NULL /* controls */, + NULL /* uniqueid */, + aclplugin_get_identity (ACL_PLUGIN_IDENTITY), + 0 ); + slapi_search_internal_pb(myPb); + slapi_pblock_get(myPb, SLAPI_PLUGIN_INTOP_RESULT, &rval); + if (rval == LDAP_SUCCESS) { + Slapi_Entry **ep; + slapi_pblock_get(myPb, + SLAPI_PLUGIN_INTOP_SEARCH_ENTRIES, &grpentries); + if ((grpentries != NULL) && (grpentries[0] != NULL)) { + char *edn = NULL; + for (ep = grpentries; *ep; ep++) { + /* groups having ACI */ + edn = slapi_entry_get_ndn(*ep); + matched = acllas_eval_one_group(edn, &lasinfo); + if (ACL_TRUE == matched) { + break; /* matched ! */ + } + } + } + } + slapi_free_search_results_internal(myPb); + slapi_pblock_destroy (myPb); + + } else { + /* normal evaluation */ + matched = acllas_eval_one_group( groupName, &lasinfo ); + } + if ( ludp ) { + ldap_free_urldesc( ludp ); + } } if ( matched == ACL_TRUE ) { @@ -855,7 +914,7 @@ DS_LASGroupDnEval(NSErr_t *errp, char *attr_name, CmpOp_t comparator, } } /* Nothing matched -- try the next DN */ - groupName = end_dn; + groupNameOrig = groupName = end_dn; } /* end of while */ @@ -2361,9 +2420,6 @@ acllas__eval_memberGroupDnAttr (char *attrName, Slapi_Entry *e, char ebuf [ BUFSIZ ]; Slapi_Value *sval=NULL; const struct berval *attrVal; - int qcnt = 0; - Slapi_PBlock *myPb = NULL; - Slapi_Entry **grpentries = NULL; /* Parse the URL -- getting the group attr and counting up '?'s. * If there is no group attr and there are 3 '?' marks, @@ -2374,19 +2430,12 @@ acllas__eval_memberGroupDnAttr (char *attrName, Slapi_Entry *e, str +=8; s = strchr (str, '?'); if (s) { - qcnt++; p = s; p++; *s = '\0'; base = str; s = strchr (p, '?'); - if (s) { - qcnt++; - *s = '\0'; - if (NULL != strchr (++s, '?')) { - qcnt++; - } - } + if (s) *s = '\0'; groupattr = p; } else { @@ -2394,49 +2443,6 @@ acllas__eval_memberGroupDnAttr (char *attrName, Slapi_Entry *e, return ACL_FALSE; } - /* Full LDAPURL is given? */ - if ((NULL == groupattr || 0 == strlen(groupattr)) && 3 == qcnt) { - LDAPURLDesc *ludp = NULL; - int rval; - - if ( 0 != ldap_url_parse( attrName, &ludp) ) { - slapi_ch_free ( (void **)&s_str ); - return ACL_FALSE; - } - - /* Use new search internal API */ - myPb = slapi_pblock_new (); - slapi_search_internal_set_pb( - myPb, - ludp->lud_dn, - ludp->lud_scope, - ludp->lud_filter, - NULL, - 0, - NULL /* controls */, - NULL /* uniqueid */, - aclplugin_get_identity (ACL_PLUGIN_IDENTITY), - 0 ); - slapi_search_internal_pb(myPb); - ldap_free_urldesc( ludp ); - - slapi_pblock_get(myPb, SLAPI_PLUGIN_INTOP_RESULT, &rval); - if (rval != LDAP_SUCCESS) { - slapi_ch_free ( (void **)&s_str ); - slapi_free_search_results_internal(myPb); - slapi_pblock_destroy (myPb); - return ACL_FALSE; - } - - slapi_pblock_get(myPb, SLAPI_PLUGIN_INTOP_SEARCH_ENTRIES, &grpentries); - if ((grpentries == NULL) || (grpentries[0] == NULL)) { - slapi_ch_free ( (void **)&s_str ); - slapi_free_search_results_internal(myPb); - slapi_pblock_destroy (myPb); - return ACL_FALSE; - } - } - if ( (u_group = aclg_get_usersGroup ( aclpb , n_clientdn )) == NULL) { slapi_log_error( SLAPI_LOG_ACL, plugin_name, "Failed to find/allocate a usergroup--aborting evaluation\n", 0, 0); @@ -2594,55 +2600,37 @@ acllas__eval_memberGroupDnAttr (char *attrName, Slapi_Entry *e, j, ACL_ESCAPE_STRING_WITH_PUNCTUATION (u_group->aclug_member_groups[j], ebuf),0); matched = ACL_FALSE; - if ((NULL == groupattr || 0 == strlen(groupattr)) && 3 == qcnt) { - /* Full LDAPURL case */ - for (k = 0; u_group->aclug_member_groups[k]; k++) { /* groups the bind - user belong to */ - Slapi_Entry **ep; - for (ep = grpentries; *ep; ep++) { /* groups having ACI */ - char *n_edn = slapi_entry_get_ndn(*ep); - if (slapi_utf8casecmp((ACLUCHP)u_group->aclug_member_groups[k], - (ACLUCHP)n_edn) == 0) { - matched = ACL_TRUE; - break; - } - } - } - slapi_free_search_results_internal(myPb); - slapi_pblock_destroy(myPb); - } else { - slapi_entry_attr_find( e, groupattr, &attr); - if (attr == NULL) { - slapi_ch_free ( (void **)&s_str ); - return ACL_FALSE; - } - k = slapi_attr_first_value ( attr,&sval ); - while ( k != -1 ) { - char *n_attrval; - attrVal = slapi_value_get_berval ( sval ); - n_attrval = slapi_ch_strdup( attrVal->bv_val); - n_attrval = slapi_dn_normalize (n_attrval); + slapi_entry_attr_find( e, groupattr, &attr); + if (attr == NULL) { + slapi_ch_free ( (void **)&s_str ); + return ACL_FALSE; + } + k = slapi_attr_first_value ( attr,&sval ); + while ( k != -1 ) { + char *n_attrval; + attrVal = slapi_value_get_berval ( sval ); + n_attrval = slapi_ch_strdup( attrVal->bv_val); + n_attrval = slapi_dn_normalize (n_attrval); - /* We support: The attribute value can be a USER or a GROUP. - ** Let's compare with the client, thi might be just an user. If it is not - ** then we test it against the list of groups. - */ - if (slapi_utf8casecmp ((ACLUCHP)n_attrval, (ACLUCHP)n_clientdn) == 0 ) { + /* We support: The attribute value can be a USER or a GROUP. + ** Let's compare with the client, thi might be just an user. If it is not + ** then we test it against the list of groups. + */ + if (slapi_utf8casecmp ((ACLUCHP)n_attrval, (ACLUCHP)n_clientdn) == 0 ) { + matched = ACL_TRUE; + slapi_ch_free ( (void **)&n_attrval ); + break; + } + for (j=0; j <u_group->aclug_numof_member_group; j++) { + if ( slapi_utf8casecmp((ACLUCHP)n_attrval, + (ACLUCHP)u_group->aclug_member_groups[j]) == 0) { matched = ACL_TRUE; - slapi_ch_free ( (void **)&n_attrval ); break; } - for (j=0; j <u_group->aclug_numof_member_group; j++) { - if ( slapi_utf8casecmp((ACLUCHP)n_attrval, - (ACLUCHP)u_group->aclug_member_groups[j]) == 0) { - matched = ACL_TRUE; - break; - } - } - slapi_ch_free ( (void **)&n_attrval ); - if (matched == ACL_TRUE) break; - k= slapi_attr_next_value ( attr, k, &sval ); } + slapi_ch_free ( (void **)&n_attrval ); + if (matched == ACL_TRUE) break; + k= slapi_attr_next_value ( attr, k, &sval ); } slapi_ch_free ( (void **)&s_str ); return matched;
0
71901e8edd28030cbb21b0a7f6cf68946093640e
389ds/389-ds-base
Ticket #48025 - add an option '-u' to dbgen.pl for adding group entries with uniquemembers Usage: /usr/bin/dbgen.pl [options] -o output_file -n number -u add groups containing uniquemembers; generate a group for every 100 user entries created that contains the 100 members. https://fedorahosted.org/389/ticket/48025 Reviewed by [email protected] (Thank you, Mark!!)
commit 71901e8edd28030cbb21b0a7f6cf68946093640e Author: Noriko Hosoi <[email protected]> Date: Mon Feb 9 13:58:45 2015 -0800 Ticket #48025 - add an option '-u' to dbgen.pl for adding group entries with uniquemembers Usage: /usr/bin/dbgen.pl [options] -o output_file -n number -u add groups containing uniquemembers; generate a group for every 100 user entries created that contains the 100 members. https://fedorahosted.org/389/ticket/48025 Reviewed by [email protected] (Thank you, Mark!!) diff --git a/ldap/servers/slapd/tools/rsearch/scripts/dbgen.pl.in b/ldap/servers/slapd/tools/rsearch/scripts/dbgen.pl.in index ddd21cc6f..56c56131e 100755 --- a/ldap/servers/slapd/tools/rsearch/scripts/dbgen.pl.in +++ b/ldap/servers/slapd/tools/rsearch/scripts/dbgen.pl.in @@ -75,6 +75,7 @@ sub PrintUsage { "\t -x suppress printing pre amble\n", "\t -y suppress printing organizational units\n", "\t -l location of directory containing data files, default is @templatedir@\n", + "\t -u add groups containing uniquemembers;\n\t generate a group for every 100 user entries created that contains the 100 members.\n", "\t -v verbose\n", "\t -q quiet\n", "\n"; @@ -560,6 +561,12 @@ $opt_x = 0; $opt_y = 0; $opt_z = ""; +# group + uniquemember +$opt_u = 0; +$gid = 0; +$gnum = 0; +$membercount = 100; # default member count in a group + GetOptions('number=i' => \$Number_To_Generate, 'output=s' => \$Output_File_Name, 'random=i' => \$Random_Seed, @@ -577,6 +584,7 @@ GetOptions('number=i' => \$Number_To_Generate, 'verbose' => \$Verbose, 'debug' => \$debug, 'quiet' => \$Quiet, + 'uniqueMember' => \$opt_u, ); $Random_Seed = $Random_Seed || 0xdbdbdbdb; @@ -600,6 +608,13 @@ if ("" != $opt_y) $printorgunit = 0; } +if (0 != $opt_u) { + if ($membercount > $Number_To_Generate) { + $membercount = $Number_To_Generate; + } + @members = (); +} + if ($Suffix =~ /o=/) { ($Organization) = $Suffix =~ /o=([^,]+)/; $objectvalue = "organization"; @@ -649,10 +664,10 @@ print "Done\n" if $Verbose; if ($printpreamble) { if ($piranha) { - &PrintPreAmblePiranha($Output_File_Name); + &PrintPreAmblePiranha($Output_File_Name); } else { - &PrintPreAmbleBarracuda($Output_File_Name); + &PrintPreAmbleBarracuda($Output_File_Name); } } @@ -778,17 +793,20 @@ for ($x= $BeginNum; $x < ($Number_To_Generate+$BeginNum); $x++) { $userPassword = "$uid\n"; } - if ($PrintOrgChartDat or !$printorgunit) { - $dnstr = "dn: $NamingType=$rdn,ou=People,$Suffix\n", - } else { - $dnstr = "dn: $NamingType=$rdn,ou=$OrgUnit,$Suffix\n"; - } + if ($PrintOrgChartDat or !$printorgunit) { + $dnstr = "$NamingType=$rdn,ou=People,$Suffix"; + } else { + $dnstr = "$NamingType=$rdn,ou=$OrgUnit,$Suffix"; + } - print OUTPUT_FILE - $dnstr, + if ($opt_u) { + # with group + memof + print OUTPUT_FILE + "dn: $dnstr\n", "objectClass: top\n", "objectClass: person\n", "objectClass: organizationalPerson\n", + "objectClass: inetAdmin\n", $inetOrgPerson, $ExtraObjClasses, "cn: $cn\n", "sn: $sn\n", @@ -815,7 +833,58 @@ for ($x= $BeginNum; $x < ($Number_To_Generate+$BeginNum); $x++) { "title: $title\n", $mycert, "\n"; - + push(@members, $dnstr); + $gnum += 1; + if ($gnum >= $membercount) { + my $gdnstr = "dn: cn=Group$gid,$Suffix\n"; + print OUTPUT_FILE + $gdnstr, + "objectClass: top\n", + "objectClass: groupOfUniqueNames\n", + "cn: Group$gid\n"; + foreach $member (@members) { + print OUTPUT_FILE "uniqueMember: $member\n"; + } + print OUTPUT_FILE "\n"; + @members = (); + $gid += 1; + $gnum = 0; + } + } else { + # no group + memof + print OUTPUT_FILE + "dn: $dnstr\n", + "objectClass: top\n", + "objectClass: person\n", + "objectClass: organizationalPerson\n", + $inetOrgPerson, $ExtraObjClasses, + "cn: $cn\n", + "sn: $sn\n", + "uid: $uid\n", + "givenName: $givenName\n", + "description: $description\n", + "userPassword: $userPassword", + $departmentNumber, + $employeeType, + $homePhone, + $initials, + "telephoneNumber: $telephoneNumber\n", + "facsimileTelephoneNumber: $facsimileTelephoneNumber\n", + $mobile, + $pager, + $manager, + $secretary, + $roomNumber, + $carLicense, + "l: $locality\n", + "ou: $OrgUnit\n", + "mail: $mail\n", + "postalAddress: $postalAddress\n", + "title: $title\n", + $mycert, + "\n"; + } + if (!$Quiet) { if ($x % 1000 == 0) { print "." if $Verbose; @@ -833,7 +902,7 @@ if ($Verbose) { } exit 0; - + sub ReadOrgUnits { open (ORG_UNITS, $OrgUnitsFile) || @@ -976,13 +1045,13 @@ sub PrintManagers { $userPassword = "$uid\n"; } - $dnstr = "dn: $NamingType=$rdn,ou=People,$Suffix\n"; + $dnstr = "$NamingType=$rdn,ou=People,$Suffix"; if ("" ne $orgUnit) { $oustr = "ou: $orgUnit\n"; } print OUTPUT_FILE - $dnstr, + "dn: $dnstr\n", "objectClass: top\n", "objectClass: person\n", "objectClass: organizationalPerson\n",
0
4b240e96c016af8cdd6393e3200e2550650b4fc0
389ds/389-ds-base
Issue 50506 - Fix invalid frees from pointer reference calls. Description: There were a few free calls that were not removed which caused a double free. There was also extra care needed in pw.c around shadow password attribute values. relates: https://pagure.io/389-ds-base/issue/50506 Reviewed by: lkrispen(Thanks!)
commit 4b240e96c016af8cdd6393e3200e2550650b4fc0 Author: Mark Reynolds <[email protected]> Date: Thu Aug 1 10:01:22 2019 -0400 Issue 50506 - Fix invalid frees from pointer reference calls. Description: There were a few free calls that were not removed which caused a double free. There was also extra care needed in pw.c around shadow password attribute values. relates: https://pagure.io/389-ds-base/issue/50506 Reviewed by: lkrispen(Thanks!) diff --git a/ldap/servers/plugins/replication/repl5_tot_protocol.c b/ldap/servers/plugins/replication/repl5_tot_protocol.c index 9eadb2cc4..977545c56 100644 --- a/ldap/servers/plugins/replication/repl5_tot_protocol.c +++ b/ldap/servers/plugins/replication/repl5_tot_protocol.c @@ -315,7 +315,6 @@ check_suffix_entryID(Slapi_Backend *be, Slapi_Entry *suffix) return; } entryid = (u_int32_t) atoi(entryid_str); - slapi_ch_free_string(&entryid_str); if (!bck_info.key_found || bck_info.id != entryid) { /* The suffix entryid is not present in parentid index diff --git a/ldap/servers/slapd/plugin.c b/ldap/servers/slapd/plugin.c index 771b59c71..a77bb5aa7 100644 --- a/ldap/servers/slapd/plugin.c +++ b/ldap/servers/slapd/plugin.c @@ -2812,7 +2812,6 @@ plugin_setup(Slapi_Entry *plugin_entry, struct slapi_componentid *group, slapi_p slapi_log_err(SLAPI_LOG_ERR, "plugin_setup", "Unknown plugin type \"%s\" in entry \"%s\"\n", value, slapi_entry_get_dn_const(plugin_entry)); PR_snprintf(returntext, SLAPI_DSE_RETURNTEXT_SIZE, "Unknown plugin type \"%s\" in entry", value); - slapi_ch_free_string(&value); status = -1; goto PLUGIN_CLEANUP; } diff --git a/ldap/servers/slapd/pw.c b/ldap/servers/slapd/pw.c index 1e63f9e05..2e11caab3 100644 --- a/ldap/servers/slapd/pw.c +++ b/ldap/servers/slapd/pw.c @@ -3112,8 +3112,11 @@ add_shadow_ext_password_attrs(Slapi_PBlock *pb, Slapi_Entry **e) long long sval; int mod_num = 0; char *shmin = NULL; + int shmin_free_it = 0; char *shmax = NULL; + int shmax_free_it = 0; char *shwarn = NULL; + int shwarn_free_it = 0; int rc = 0; if (!e || !*e) { @@ -3153,11 +3156,13 @@ add_shadow_ext_password_attrs(Slapi_PBlock *pb, Slapi_Entry **e) sval = strtoll(shmin, NULL, 0); if (sval != shadowval) { shmin = slapi_ch_smprintf("%lld", shadowval); + shmin_free_it = 1; mod_num++; } } else { mod_num++; shmin = slapi_ch_smprintf("%lld", shadowval); + shmin_free_it = 1; } } @@ -3175,11 +3180,13 @@ add_shadow_ext_password_attrs(Slapi_PBlock *pb, Slapi_Entry **e) sval = strtoll(shmax, NULL, 0); if (sval != shadowval) { shmax = slapi_ch_smprintf("%lld", shadowval); + shmax_free_it = 1; mod_num++; } } else { mod_num++; shmax = slapi_ch_smprintf("%lld", shadowval); + shmax_free_it = 1; } } @@ -3197,11 +3204,13 @@ add_shadow_ext_password_attrs(Slapi_PBlock *pb, Slapi_Entry **e) sval = strtoll(shwarn, NULL, 0); if (sval != shadowval) { shwarn = slapi_ch_smprintf("%lld", shadowval); + shwarn_free_it = 1; mod_num++; } } else { mod_num++; shwarn = slapi_ch_smprintf("%lld", shadowval); + shwarn_free_it = 1; } } @@ -3209,15 +3218,18 @@ add_shadow_ext_password_attrs(Slapi_PBlock *pb, Slapi_Entry **e) slapi_mods_init(smods, mod_num); if (shmin) { slapi_mods_add(smods, LDAP_MOD_REPLACE, "shadowMin", strlen(shmin), shmin); - slapi_ch_free_string(&shmin); + if (shmin_free_it) + slapi_ch_free_string(&shmin); } if (shmax) { slapi_mods_add(smods, LDAP_MOD_REPLACE, "shadowMax", strlen(shmax), shmax); - slapi_ch_free_string(&shmax); + if (shmax_free_it) + slapi_ch_free_string(&shmax); } if (shwarn) { slapi_mods_add(smods, LDAP_MOD_REPLACE, "shadowWarning", strlen(shwarn), shwarn); - slapi_ch_free_string(&shwarn); + if (shwarn_free_it) + slapi_ch_free_string(&shwarn); } /* Apply the mods to create the resulting entry. */ mods = slapi_mods_get_ldapmods_byref(smods);
0
fb54b6780e8d5113287f690dac579fe9b599e910
389ds/389-ds-base
Ticket 429 - Add nsslapd-readonly to schema Added nsslapd-readonly to DS schema https://fedorahosted.org/389/ticket/429 Reviewed by: ?
commit fb54b6780e8d5113287f690dac579fe9b599e910 Author: Mark Reynolds <[email protected]> Date: Mon Aug 20 12:35:53 2012 -0400 Ticket 429 - Add nsslapd-readonly to schema Added nsslapd-readonly to DS schema https://fedorahosted.org/389/ticket/429 Reviewed by: ? diff --git a/ldap/schema/01core389.ldif b/ldap/schema/01core389.ldif index 58b4b7604..d9d1c335b 100644 --- a/ldap/schema/01core389.ldif +++ b/ldap/schema/01core389.ldif @@ -138,6 +138,7 @@ attributeTypes: ( 2.16.840.1.113730.3.1.2135 NAME 'nsds5ReplicaCleanRUV' DESC 'N attributeTypes: ( 2.16.840.1.113730.3.1.2136 NAME 'nsds5ReplicaCleanRUVNotified' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 X-ORIGIN 'Netscape Directory Server' ) attributeTypes: ( 2.16.840.1.113730.3.1.2137 NAME 'nsds5ReplicaAbortCleanRUV' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 X-ORIGIN 'Netscape Directory Server' ) attributeTypes: ( 2.16.840.1.113730.3.1.2111 NAME 'tombstoneNumSubordinates' DESC 'count of immediate subordinates for tombstone entries' EQUALITY integerMatch ORDERING integerOrderingMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE NO-USER-MODIFICATION USAGE directoryOperation X-ORIGIN '389 directory server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2138 NAME 'nsslapd-readonly' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) # # objectclasses #
0
18b24dc3a52be5a7e17d9d8bde43c84e45a4ca0a
389ds/389-ds-base
Issue 6727 - RFE - database compaction interval should be persistent Description: Record when we start the compaction interval in the ldbm config entry so if we restart the server compaction will still take place at the intended interval Relates: https://github.com/389ds/389-ds-base/issues/6727 Reviewed by: spichugi & tbordaz(Thanks!!)
commit 18b24dc3a52be5a7e17d9d8bde43c84e45a4ca0a Author: Mark Reynolds <[email protected]> Date: Thu Apr 24 16:24:30 2025 -0400 Issue 6727 - RFE - database compaction interval should be persistent Description: Record when we start the compaction interval in the ldbm config entry so if we restart the server compaction will still take place at the intended interval Relates: https://github.com/389ds/389-ds-base/issues/6727 Reviewed by: spichugi & tbordaz(Thanks!!) diff --git a/dirsrvtests/tests/suites/config/compact_test.py b/dirsrvtests/tests/suites/config/compact_test.py index 09c71d178..a79c7639a 100644 --- a/dirsrvtests/tests/suites/config/compact_test.py +++ b/dirsrvtests/tests/suites/config/compact_test.py @@ -1,5 +1,5 @@ # --- BEGIN COPYRIGHT BLOCK --- -# Copyright (C) 2022 Red Hat, Inc. +# Copyright (C) 2025 Red Hat, Inc. # All rights reserved. # # License: GPL (version 3 or any later version). @@ -16,6 +16,9 @@ from lib389.tasks import DBCompactTask from lib389.backend import DatabaseConfig from lib389.topologies import topology_m1 as topo from lib389.utils import ldap, ds_is_older +from lib389.idm.user import UserAccounts +from lib389._constants import DEFAULT_SUFFIX + pytestmark = pytest.mark.tier2 log = logging.getLogger(__name__) @@ -82,6 +85,22 @@ def test_compaction_interval_and_time(topo): inst = topo.ms["supplier1"] + # Add and delete some entries so compaction has something to do + log.info("Adding and deleting 100 users ...") + users = UserAccounts(inst, DEFAULT_SUFFIX, rdn=None) + for num in range(100): + USER_NAME = f'test_{num}' + user = users.create(properties={ + 'uid': USER_NAME, + 'sn': USER_NAME, + 'cn': USER_NAME, + 'uidNumber': f'{num}', + 'gidNumber': f'{num}', + 'description': f'Description for {USER_NAME}', + 'homeDirectory': f'/home/{USER_NAME}' + }) + user.delete() + # Calculate the compaction time (1 minute from now) now = datetime.datetime.now() current_hour = now.hour @@ -104,16 +123,30 @@ def test_compaction_interval_and_time(topo): compact_time = hour + ":" + minute + # Get number of seconds to wait before compaction should happen + wait_seconds = 120 - now.second + # Set compaction TOD + log.debug("compact time: %s", compact_time) + log.debug("now: %s", str(now)) config = DatabaseConfig(inst) - config.set([('nsslapd-db-compactdb-interval', '2'), ('nsslapd-db-compactdb-time', compact_time)]) + config.set([('nsslapd-db-compactdb-interval', '45'), + ('nsslapd-db-compactdb-time', compact_time)]) inst.deleteErrorLogs(restart=True) # Check compaction occurred as expected - time.sleep(45) + time.sleep(25) assert not inst.searchErrorsLog("Compacting databases") - time.sleep(90) + # Make sure we can handle a restart correctly + inst.stop() + log.debug("sleeping for: %d", wait_seconds - 45) + time.sleep(wait_seconds - 45) + inst.start() + time.sleep(17) + + now = datetime.datetime.now() + log.debug("checking now: %s", str(now)) assert inst.searchErrorsLog("Compacting databases") inst.deleteErrorLogs(restart=False) diff --git a/ldap/servers/slapd/back-ldbm/db-bdb/bdb_config.c b/ldap/servers/slapd/back-ldbm/db-bdb/bdb_config.c index a1d6c6af1..c0124dea7 100644 --- a/ldap/servers/slapd/back-ldbm/db-bdb/bdb_config.c +++ b/ldap/servers/slapd/back-ldbm/db-bdb/bdb_config.c @@ -804,6 +804,32 @@ done: return retval; } +static void * +bdb_config_db_compactdb_starttime_get(void *arg) +{ + struct ldbminfo *li = (struct ldbminfo *)arg; + + return (void *)((uintptr_t)(BDB_CONFIG(li)->bdb_compactdb_starttime)); +} + +static int32_t +bdb_config_db_compactdb_starttime_set(void *arg, + void *value, + char *errorbuf __attribute__((unused)), + int phase __attribute__((unused)), + int apply) +{ + struct ldbminfo *li = (struct ldbminfo *)arg; + int32_t retval = LDAP_SUCCESS; + uint64_t val = (uint64_t)((uintptr_t)value); + + if (apply) { + BDB_CONFIG(li)->bdb_compactdb_starttime = val; + } + + return retval; +} + static void * bdb_config_db_page_size_get(void *arg) { @@ -1600,6 +1626,7 @@ static config_info bdb_config_param[] = { {CONFIG_DB_CHECKPOINT_INTERVAL, CONFIG_TYPE_INT, "60", &bdb_config_db_checkpoint_interval_get, &bdb_config_db_checkpoint_interval_set, CONFIG_FLAG_ALWAYS_SHOW | CONFIG_FLAG_ALLOW_RUNNING_CHANGE}, {CONFIG_DB_COMPACTDB_INTERVAL, CONFIG_TYPE_INT, "2592000" /*30days*/, &bdb_config_db_compactdb_interval_get, &bdb_config_db_compactdb_interval_set, CONFIG_FLAG_ALWAYS_SHOW | CONFIG_FLAG_ALLOW_RUNNING_CHANGE}, {CONFIG_DB_COMPACTDB_TIME, CONFIG_TYPE_STRING, "23:59", &bdb_config_db_compactdb_time_get, &bdb_config_db_compactdb_time_set, CONFIG_FLAG_ALWAYS_SHOW | CONFIG_FLAG_ALLOW_RUNNING_CHANGE}, + {CONFIG_DB_COMPACTDB_STARTTIME, CONFIG_TYPE_UINT64, "0" , &bdb_config_db_compactdb_starttime_get, &bdb_config_db_compactdb_starttime_set, CONFIG_FLAG_ALWAYS_SHOW | CONFIG_FLAG_ALLOW_RUNNING_CHANGE}, {CONFIG_DB_TRANSACTION_BATCH, CONFIG_TYPE_INT, "0", &bdb_get_batch_transactions, &bdb_set_batch_transactions, CONFIG_FLAG_ALWAYS_SHOW | CONFIG_FLAG_ALLOW_RUNNING_CHANGE}, {CONFIG_DB_TRANSACTION_BATCH_MIN_SLEEP, CONFIG_TYPE_INT, "50", &bdb_get_batch_txn_min_sleep, &bdb_set_batch_txn_min_sleep, CONFIG_FLAG_ALWAYS_SHOW | CONFIG_FLAG_ALLOW_RUNNING_CHANGE}, {CONFIG_DB_TRANSACTION_BATCH_MAX_SLEEP, CONFIG_TYPE_INT, "50", &bdb_get_batch_txn_max_sleep, &bdb_set_batch_txn_max_sleep, CONFIG_FLAG_ALWAYS_SHOW | CONFIG_FLAG_ALLOW_RUNNING_CHANGE}, diff --git a/ldap/servers/slapd/back-ldbm/db-bdb/bdb_layer.c b/ldap/servers/slapd/back-ldbm/db-bdb/bdb_layer.c index 29d03de78..53f1cde69 100644 --- a/ldap/servers/slapd/back-ldbm/db-bdb/bdb_layer.c +++ b/ldap/servers/slapd/back-ldbm/db-bdb/bdb_layer.c @@ -3801,27 +3801,10 @@ bdb_compact(time_t when, void *arg) slapi_log_err(SLAPI_LOG_NOTICE, "bdb_compact", "Compacting DB start: %s\n", inst->inst_name); - rc = bdb_db_compact_one_db(db, inst); - if (rc) { - slapi_log_err(SLAPI_LOG_ERR, "bdb_compact", - "Failed to compact id2entry for %s; db error - %d %s\n", - inst->inst_name, rc, db_strerror(rc)); - break; - } - /* Time to compact the DB's */ bdb_force_checkpoint(li); bdb_do_compact(li, PR_FALSE); bdb_force_checkpoint(li); - - /* Now reset the timer and compacting flag */ - rc = bdb_db_compact_one_db(db, inst); - if (rc) { - slapi_log_err(SLAPI_LOG_ERR, "bdb_compact", - "Failed to compact for %s; db error - %d %s\n", - inst->inst_name, rc, db_strerror(rc)); - break; - } } compaction_scheduled = PR_FALSE; } @@ -3847,6 +3830,41 @@ bdb_start_checkpoint_thread(struct ldbminfo *li) return return_value; } +/* + * Write the compaction interval start time value to the config. We do this as + * a delayed event because at server startup the checkpoint thread can run + * before all the plugins have been started which causes invalid memory reads. + */ +static void +bdb_write_compact_start_time(time_t when, void *arg) +{ + struct ldbminfo *li = (struct ldbminfo *)arg; + Slapi_PBlock *mod_pb = slapi_pblock_new(); + Slapi_Mods smods; + char start_time_str[20] = {0}; + int32_t rval = 0; + uint64_t start_time = slapi_current_utc_time(); + + PR_snprintf(start_time_str, sizeof(start_time_str), "%ld", start_time); + slapi_mods_init(&smods, 0); + slapi_mods_add_string(&smods, LDAP_MOD_REPLACE, + CONFIG_DB_COMPACTDB_STARTTIME, + start_time_str); + + slapi_modify_internal_set_pb(mod_pb, + "cn=bdb,cn=config,cn=ldbm database,cn=plugins,cn=config", + slapi_mods_get_ldapmods_byref(&smods), + NULL, NULL, li->li_identity, 0); + slapi_modify_internal_pb(mod_pb); + slapi_pblock_get(mod_pb, SLAPI_PLUGIN_INTOP_RESULT, &rval); + if (rval != LDAP_SUCCESS) { + slapi_log_err(SLAPI_LOG_ERR, "bdb_write_compact_start_time", + "failed to modify config_entry, err=%d\n", rval); + } + slapi_pblock_destroy(mod_pb); + slapi_mods_done(&smods); +} + /* * checkpoint thread -- borrow the timing for compacting id2entry, and eventually changelog, as well. */ @@ -3866,8 +3884,10 @@ bdb_checkpoint_threadmain(void *param) time_t compactdb_interval_update = 0; time_t checkpoint_interval_update = 0; time_t compactdb_interval = 0; + time_t compactdb_interval_orig = 0; time_t checkpoint_interval = 0; uint64_t compactdb_time = 0; + uint64_t compactdb_start_time = 0; PR_ASSERT(NULL != param); li = (struct ldbminfo *)param; @@ -3891,11 +3911,31 @@ bdb_checkpoint_threadmain(void *param) PR_Lock(li->li_config_mutex); checkpoint_interval = (time_t)BDB_CONFIG(li)->bdb_checkpoint_interval; - compactdb_interval = (time_t)BDB_CONFIG(li)->bdb_compactdb_interval; + compactdb_interval_orig = compactdb_interval = (time_t)BDB_CONFIG(li)->bdb_compactdb_interval; + compactdb_start_time = (time_t)BDB_CONFIG(li)->bdb_compactdb_starttime; penv = (bdb_db_env *)priv->dblayer_env; debug_checkpointing = BDB_CONFIG(li)->bdb_debug_checkpointing; PR_Unlock(li->li_config_mutex); + if (compactdb_start_time == 0) { + /* Ok, we don't have a start time set, get the time and write it to + * the config */ + compactdb_start_time = slapi_current_utc_time(); + slapi_eq_once_rel(bdb_write_compact_start_time, (void *)li, + slapi_current_rel_time_t() + 3); + } else { + /* We only adjust the compact interval, used for the timer, if we are + * already had a preexisting time set. This way regardless if we + * restart the server we will still compact at the expected interval */ + time_t curr_time = slapi_current_utc_time(); + if (compactdb_interval < (curr_time - compactdb_start_time)) { + /* the interval has now been passed, trigger compaction right away */ + compactdb_interval = 1; + } else { + compactdb_interval = compactdb_interval - (curr_time - compactdb_start_time); + } + } + /* assumes bdb_force_checkpoint worked */ /* * Importantly, the use of this api is not affected by backwards time steps @@ -3911,9 +3951,16 @@ bdb_checkpoint_threadmain(void *param) compactdb_interval_update = (time_t)BDB_CONFIG(li)->bdb_compactdb_interval; PR_Unlock(li->li_config_mutex); - if (compactdb_interval_update != compactdb_interval) { + if (compactdb_interval_update != compactdb_interval_orig) { /* Compact interval was changed, so reset the timer */ - slapi_timespec_expire_at(compactdb_interval_update, &compactdb_expire); + time_t curr_time = slapi_current_utc_time(); + if (compactdb_interval_update < (curr_time - compactdb_start_time)) { + /* the new interval has now been passed, trigger compaction right away */ + compactdb_interval = 1; + } else { + compactdb_interval = compactdb_interval_update - (curr_time - compactdb_start_time); + } + slapi_timespec_expire_at(compactdb_interval, &compactdb_expire); } /* Sleep for a while ... @@ -3939,16 +3986,16 @@ bdb_checkpoint_threadmain(void *param) /* now checkpoint */ bdb_checkpoint_debug_message(debug_checkpointing, - "bdb_checkpoint_threadmain - Starting checkpoint\n"); + "bdb_checkpoint_threadmain - Starting checkpoint\n"); rval = bdb_txn_checkpoint(li, (bdb_db_env *)priv->dblayer_env, - PR_TRUE, PR_FALSE); + PR_TRUE, PR_FALSE); bdb_checkpoint_debug_message(debug_checkpointing, "bdb_checkpoint_threadmain - Checkpoint Done\n"); if (rval != 0) { /* bad error */ slapi_log_err(SLAPI_LOG_CRIT, "bdb_checkpoint_threadmain", "Serious Error---Failed to checkpoint database, " - "err=%d (%s)\n", + "err=%d (%s)\n", rval, dblayer_strerror(rval)); if (LDBM_OS_ERR_IS_DISKFULL(rval)) { operation_out_of_disk_space(); @@ -3973,7 +4020,7 @@ bdb_checkpoint_threadmain(void *param) PR_snprintf(new_filename, sizeof(new_filename), "%s.old", *listp); bdb_checkpoint_debug_message(debug_checkpointing, - "Renaming %s -> %s\n", *listp, new_filename); + "Renaming %s -> %s\n", *listp, new_filename); if (rename(*listp, new_filename) != 0) { slapi_log_err(SLAPI_LOG_ERR, "bdb_checkpoint_threadmain", "Failed to rename log (%s) to (%s)\n", *listp, new_filename); @@ -3998,21 +4045,36 @@ bdb_checkpoint_threadmain(void *param) * this could have been a bug in fact, where compactdb_interval * was 0, if you change while running it would never take effect .... */ - if (compactdb_interval_update != compactdb_interval || + if (compactdb_interval_update != compactdb_interval_orig || (slapi_timespec_expire_check(&compactdb_expire) == TIMER_EXPIRED && !compaction_scheduled)) { - /* Get the time in second when the compaction should occur */ + time_t scheduled_time; + struct tm *time_info; + char buffer[80]; + + /* Get the time in seconds when the compaction should occur */ PR_Lock(li->li_config_mutex); compactdb_time = bdb_get_tod_expiration((char *)BDB_CONFIG(li)->bdb_compactdb_time); PR_Unlock(li->li_config_mutex); + scheduled_time = slapi_current_utc_time() + compactdb_time; + time_info = localtime(&scheduled_time); + strftime(buffer, 80, "%Y-%m-%d %H:%M:%S", time_info); + slapi_log_err(SLAPI_LOG_NOTICE, "bdb_checkpoint_threadmain", + "database compaction scheduled for: %s\n", + buffer); + /* Start compaction event */ compaction_scheduled = PR_TRUE; slapi_eq_once_rel(bdb_compact, (void *)li, slapi_current_rel_time_t() + compactdb_time); - /* reset interval timer */ - compactdb_interval = compactdb_interval_update; - slapi_timespec_expire_at(compactdb_interval, &compactdb_expire); + /* reset compact interval timer */ + compactdb_interval_orig = compactdb_interval_update; + slapi_timespec_expire_at(compactdb_interval_update, &compactdb_expire); + /* lastly update the config */ + compactdb_start_time = slapi_current_utc_time(); + slapi_eq_once_rel(bdb_write_compact_start_time, (void *)li, + slapi_current_rel_time_t() + 3); } } slapi_log_err(SLAPI_LOG_TRACE, "bdb_checkpoint_threadmain", "Check point before leaving\n"); @@ -7185,6 +7247,10 @@ bdb_public_dblayer_compact(Slapi_Backend *be, PRBool just_changelog) bdb_force_checkpoint(li); rc = bdb_do_compact(li, just_changelog); bdb_force_checkpoint(li); + + /* Update the compact interval after a compaction */ + bdb_write_compact_start_time(slapi_current_utc_time(), li); + return rc; } diff --git a/ldap/servers/slapd/back-ldbm/db-bdb/bdb_layer.h b/ldap/servers/slapd/back-ldbm/db-bdb/bdb_layer.h index 6e18db992..0be6cab49 100644 --- a/ldap/servers/slapd/back-ldbm/db-bdb/bdb_layer.h +++ b/ldap/servers/slapd/back-ldbm/db-bdb/bdb_layer.h @@ -91,8 +91,9 @@ typedef struct bdb_config int bdb_previous_lock_config; /* Max lock count when we last shut down-- * used to determine if we delete the mpool */ u_int32_t bdb_deadlock_policy; /* i.e. the atype to DB_ENV->lock_detect in bdb_deadlock_threadmain */ - int bdb_compactdb_interval; /* interval to execute compact id2entry dbs */ - char *bdb_compactdb_time; /* time of day to execute compact id2entry dbs */ + int bdb_compactdb_interval; /* interval to execute compact id2entry dbs */ + char *bdb_compactdb_time; /* time of day to execute compact id2entry dbs */ + uint64_t bdb_compactdb_starttime; /* the time the interval was started */ } bdb_config; int bdb_init(struct ldbminfo *li, config_info *config_array); @@ -226,7 +227,7 @@ int bdb_dse_conf_verify(struct ldbminfo *li, char *src_dir); int bdb_import_file_check_fn_t(ldbm_instance *inst); dbi_dbslist_t *bdb_list_dbs(const char *dbhome); int bdb_public_in_import(ldbm_instance *inst); -int bdb_dblayer_cursor_iterate(dbi_cursor_t *cursor, +int bdb_dblayer_cursor_iterate(dbi_cursor_t *cursor, int (*action_cb)(dbi_val_t *key, dbi_val_t *data, void *ctx), const dbi_val_t *startingkey, void *ctx); diff --git a/ldap/servers/slapd/back-ldbm/ldbm_config.h b/ldap/servers/slapd/back-ldbm/ldbm_config.h index f47a8b8a6..17418b6f2 100644 --- a/ldap/servers/slapd/back-ldbm/ldbm_config.h +++ b/ldap/servers/slapd/back-ldbm/ldbm_config.h @@ -85,6 +85,7 @@ struct config_info #define CONFIG_DB_CHECKPOINT_INTERVAL "nsslapd-db-checkpoint-interval" #define CONFIG_DB_COMPACTDB_INTERVAL "nsslapd-db-compactdb-interval" #define CONFIG_DB_COMPACTDB_TIME "nsslapd-db-compactdb-time" +#define CONFIG_DB_COMPACTDB_STARTTIME "nsslapd-db-compactdb-starttime" #define CONFIG_DB_TRANSACTION_BATCH "nsslapd-db-transaction-batch-val" #define CONFIG_DB_TRANSACTION_BATCH_MIN_SLEEP "nsslapd-db-transaction-batch-min-wait" #define CONFIG_DB_TRANSACTION_BATCH_MAX_SLEEP "nsslapd-db-transaction-batch-max-wait"
0
a9905306534b1e9974267234350b01ab9853ed38
389ds/389-ds-base
Ticket 67 - get attr by type Bug Description: In python 3 the change to utf8 has caused us some difficulty. As a result, to help ease this, we need to be able to retrieve attributes by types in DS Fix Description: In mapped object, add the ability to request types for searches when we perform them. https://pagure.io/lib389/issue/67 Author: wibrown Review by: ilias95, spichugi (Thanks!)
commit a9905306534b1e9974267234350b01ab9853ed38 Author: William Brown <[email protected]> Date: Wed Jun 21 12:48:36 2017 +1000 Ticket 67 - get attr by type Bug Description: In python 3 the change to utf8 has caused us some difficulty. As a result, to help ease this, we need to be able to retrieve attributes by types in DS Fix Description: In mapped object, add the ability to request types for searches when we perform them. https://pagure.io/lib389/issue/67 Author: wibrown Review by: ilias95, spichugi (Thanks!) diff --git a/src/lib389/lib389/_mapped_object.py b/src/lib389/lib389/_mapped_object.py index 361b479f6..c9b7eb9ea 100644 --- a/src/lib389/lib389/_mapped_object.py +++ b/src/lib389/lib389/_mapped_object.py @@ -335,6 +335,24 @@ class DSLdapObject(DSLogging): entry = self._instance.search_s(self._dn, ldap.SCOPE_BASE, attrlist=[key])[0] return entry.getValue(key) + def get_attr_val_bytes(self, key): + return ensure_bytes(self.get_attr_val(key)) + + def get_attr_vals_bytes(self, key): + return ensure_list_bytes(self.get_attrs_val(key)) + + def get_attr_val_utf8(self, key): + return ensure_str(self.get_attr_val(key)) + + def get_attr_vals_utf8(self, key): + return ensure_list_str(self.get_attrs_val(key)) + + def get_attr_val_int(self, key): + return int(self.get_attr_val(key)) + + def get_attr_vals_int(self, key): + return [int(v) for v in self.get_attrs_val(key)] + # Duplicate, but with many values. IE a dict api. # This def add_values(self, values): diff --git a/src/lib389/lib389/backend.py b/src/lib389/lib389/backend.py index 1affe1353..3e208bfef 100644 --- a/src/lib389/lib389/backend.py +++ b/src/lib389/lib389/backend.py @@ -463,7 +463,7 @@ class Backend(DSLdapObject): raise ldap.UNWILLING_TO_PERFORM("This is a protected backend!") # First check if the mapping tree has our suffix still. # suffix = self.get_attr_val('nsslapd-suffix') - bename = ensure_str(self.get_attr_val('cn')) + bename = self.get_attr_val_utf8('cn') try: mt = self._mts.get(selector=bename) # Assert the type is "backend" @@ -492,11 +492,11 @@ class Backend(DSLdapObject): * missing indcies if we are local and have log access? """ # Check for the missing mapping tree. - suffix = ensure_str(self.get_attr_val('nsslapd-suffix')) - bename = self.get_attr_val('cn') + suffix = self.get_attr_val_utf8('nsslapd-suffix') + bename = self.get_attr_val_bytes('cn') try: mt = self._mts.get(suffix) - if mt.get_attr_val('nsslapd-backend') != ensure_bytes(bename) and mt.get_attr_val('nsslapd-state') != ensure_bytes('backend') : + if mt.get_attr_val_bytes('nsslapd-backend') != bename and mt.get_attr_val('nsslapd-state') != ensure_bytes('backend') : raise ldap.NO_SUCH_OBJECT("We have a matching suffix, but not a backend or correct database name.") except ldap.NO_SUCH_OBJECT: result = DSBLE0001 diff --git a/src/lib389/lib389/config.py b/src/lib389/lib389/config.py index 07232141e..0a7539b1d 100644 --- a/src/lib389/lib389/config.py +++ b/src/lib389/lib389/config.py @@ -191,10 +191,8 @@ class Config(DSLdapObject): def _lint_passwordscheme(self): allowed_schemes = ['SSHA512', 'PBKDF2_SHA256'] - password_scheme = self.get_attr_val('passwordStorageScheme') - root_scheme = self.get_attr_val('nsslapd-rootpwstoragescheme') - u_password_scheme = ensure_str(password_scheme) - u_root_scheme = ensure_str(root_scheme) + u_password_scheme = self.get_attr_val_utf8('passwordStorageScheme') + u_root_scheme = self.get_attr_val_utf8('nsslapd-rootpwstoragescheme') if u_root_scheme not in allowed_schemes or u_password_scheme not in allowed_schemes: return DSCLE0002 return None
0
37f919a79a719c485742bb0bc2e09d8b2018a2b6
389ds/389-ds-base
Ticket 50300 - Fix memory leak in automember plugin Description: We were allocating a pblock long before it was used, and we were returning from the function on an error before we freed it. The fix just allocates the pblock right before it's used, and then it is properly freed. https://pagure.io/389-ds-base/issue/50300 Reviewed by: mreynolds (one line commit rule)
commit 37f919a79a719c485742bb0bc2e09d8b2018a2b6 Author: Mark Reynolds <[email protected]> Date: Fri Mar 22 16:27:15 2019 -0400 Ticket 50300 - Fix memory leak in automember plugin Description: We were allocating a pblock long before it was used, and we were returning from the function on an error before we freed it. The fix just allocates the pblock right before it's used, and then it is properly freed. https://pagure.io/389-ds-base/issue/50300 Reviewed by: mreynolds (one line commit rule) diff --git a/ldap/servers/plugins/automember/automember.c b/ldap/servers/plugins/automember/automember.c index fcf0cdb9a..24fd874aa 100644 --- a/ldap/servers/plugins/automember/automember.c +++ b/ldap/servers/plugins/automember/automember.c @@ -1628,7 +1628,7 @@ out: static int automember_update_member_value(Slapi_Entry *member_e, const char *group_dn, char *grouping_attr, char *grouping_value, PRFileDesc *ldif_fd, int add) { - Slapi_PBlock *mod_pb = slapi_pblock_new(); + Slapi_PBlock *mod_pb = NULL; int result = LDAP_SUCCESS; LDAPMod mod; LDAPMod *mods[2]; @@ -1708,6 +1708,7 @@ automember_update_member_value(Slapi_Entry *member_e, const char *group_dn, char member_value, grouping_attr, group_dn); } + mod_pb = slapi_pblock_new(); slapi_modify_internal_set_pb(mod_pb, group_dn, mods, 0, 0, automember_get_plugin_id(), 0); slapi_modify_internal_pb(mod_pb);
0
eacb3c96ad2ae9e448ee547a796154d27e985b7f
389ds/389-ds-base
Ticket 49097 - whitespace fixes for pblock change Bug Description: While fixing the pblock, I added a number of whitespace errors. This resolves them. Fix Description: Fix the whitespace in the changes. https://pagure.io/389-ds-base/issue/49097 Author: wibrown Review by: mreynolds (Thanks!)
commit eacb3c96ad2ae9e448ee547a796154d27e985b7f Author: William Brown <[email protected]> Date: Thu Apr 20 11:35:10 2017 +1000 Ticket 49097 - whitespace fixes for pblock change Bug Description: While fixing the pblock, I added a number of whitespace errors. This resolves them. Fix Description: Fix the whitespace in the changes. https://pagure.io/389-ds-base/issue/49097 Author: wibrown Review by: mreynolds (Thanks!) diff --git a/ldap/servers/plugins/acl/acleffectiverights.c b/ldap/servers/plugins/acl/acleffectiverights.c index fc6f7267e..c06dae1a5 100644 --- a/ldap/servers/plugins/acl/acleffectiverights.c +++ b/ldap/servers/plugins/acl/acleffectiverights.c @@ -104,8 +104,8 @@ _ger_g_permission_granted ( else { slapi_ch_free_string(&proxydn); /* this could still have been set - free it */ - Operation *pb_op; - slapi_pblock_get(pb, SLAPI_OPERATION, &pb_op); + Operation *pb_op; + slapi_pblock_get(pb, SLAPI_OPERATION, &pb_op); requestor_sdn = &(pb_op->o_sdn); } if ( slapi_sdn_get_dn (requestor_sdn) == NULL ) diff --git a/ldap/servers/slapd/abandon.c b/ldap/servers/slapd/abandon.c index 779ec4961..581b6d2c7 100644 --- a/ldap/servers/slapd/abandon.c +++ b/ldap/servers/slapd/abandon.c @@ -35,12 +35,12 @@ do_abandon( Slapi_PBlock *pb ) { int err, suppressed_by_plugin = 0; ber_int_t id; - Connection *pb_conn = NULL; - Operation *pb_op = NULL; + Connection *pb_conn = NULL; + Operation *pb_op = NULL; Operation *o; - slapi_pblock_get(pb, SLAPI_OPERATION, &pb_op); - slapi_pblock_get(pb, SLAPI_CONNECTION, &pb_conn); + slapi_pblock_get(pb, SLAPI_OPERATION, &pb_op); + slapi_pblock_get(pb, SLAPI_CONNECTION, &pb_conn); BerElement *ber = pb_op->o_ber; @@ -100,9 +100,9 @@ do_abandon( Slapi_PBlock *pb ) are applicable for the operation */ ts = operation_get_target_spec (o); if (ts) { - operation_set_target_spec (pb_op, ts); + operation_set_target_spec (pb_op, ts); } else { - slapi_log_err(SLAPI_LOG_TRACE, "do_abandon", "no target spec of abandoned operation\n"); + slapi_log_err(SLAPI_LOG_TRACE, "do_abandon", "no target spec of abandoned operation\n"); } operation_set_abandoned_op (pb_op, o->o_abandoned_op); diff --git a/ldap/servers/slapd/add.c b/ldap/servers/slapd/add.c index 1286b8950..7fa5444f3 100644 --- a/ldap/servers/slapd/add.c +++ b/ldap/servers/slapd/add.c @@ -60,11 +60,11 @@ do_add( Slapi_PBlock *pb ) int err; int rc; PRBool searchsubentry=PR_TRUE; - Connection *pb_conn = NULL; + Connection *pb_conn = NULL; slapi_log_err(SLAPI_LOG_TRACE, "do_add", "==>\n"); - slapi_pblock_get(pb, SLAPI_CONNECTION, &pb_conn); + slapi_pblock_get(pb, SLAPI_CONNECTION, &pb_conn); slapi_pblock_get( pb, SLAPI_OPERATION, &operation); ber = operation->o_ber; @@ -284,9 +284,9 @@ done: Slapi_PBlock * slapi_add_entry_internal(Slapi_Entry *e, LDAPControl **controls, int dummy __attribute__((unused))) { - Slapi_PBlock *pb = slapi_pblock_new(); - Slapi_PBlock *result_pb = NULL; - int opresult; + Slapi_PBlock *pb = slapi_pblock_new(); + Slapi_PBlock *result_pb = NULL; + int opresult; slapi_add_entry_internal_set_pb (pb, e, controls, plugin_get_default_component_id(), 0); @@ -298,9 +298,9 @@ slapi_add_entry_internal(Slapi_Entry *e, LDAPControl **controls, int dummy __att slapi_pblock_get(pb, SLAPI_PLUGIN_INTOP_RESULT, &opresult); slapi_pblock_set(result_pb, SLAPI_PLUGIN_INTOP_RESULT, &opresult); } - slapi_pblock_destroy(pb); + slapi_pblock_destroy(pb); - return result_pb; + return result_pb; } /* This is new style API to issue internal add operation. @@ -431,10 +431,10 @@ static void op_shared_add (Slapi_PBlock *pb) char *errtext = NULL; Slapi_DN *sdn = NULL; passwdPolicy *pwpolicy; - Connection *pb_conn = NULL; + Connection *pb_conn = NULL; slapi_pblock_get (pb, SLAPI_OPERATION, &operation); - slapi_pblock_get (pb, SLAPI_CONNECTION, &pb_conn); + slapi_pblock_get (pb, SLAPI_CONNECTION, &pb_conn); slapi_pblock_get (pb, SLAPI_ADD_ENTRY, &e); slapi_pblock_get (pb, SLAPI_IS_REPLICATED_OPERATION, &repl_op); slapi_pblock_get (pb, SLAPI_IS_LEGACY_REPLICATED_OPERATION, &legacy_op); @@ -446,8 +446,8 @@ static void op_shared_add (Slapi_PBlock *pb) if ((err = slapi_entry_add_rdn_values(e)) != LDAP_SUCCESS) { - send_ldap_result(pb, err, NULL, "failed to add RDN values", 0, NULL); - goto done; + send_ldap_result(pb, err, NULL, "failed to add RDN values", 0, NULL); + goto done; } /* get the proxy auth dn if the proxy auth control is present */ diff --git a/ldap/servers/slapd/back-ldbm/findentry.c b/ldap/servers/slapd/back-ldbm/findentry.c index 7565c437a..c29579ecf 100644 --- a/ldap/servers/slapd/back-ldbm/findentry.c +++ b/ldap/servers/slapd/back-ldbm/findentry.c @@ -159,8 +159,8 @@ find_entry_internal_dn( struct backentry *me; Slapi_DN ancestorsdn; slapi_sdn_init(&ancestorsdn); - Slapi_Backend *pb_backend; - slapi_pblock_get(pb, SLAPI_BACKEND, &pb_backend); + Slapi_Backend *pb_backend; + slapi_pblock_get(pb, SLAPI_BACKEND, &pb_backend); me = dn2ancestor(pb_backend, sdn, &ancestorsdn, txn, &err, 1 /* allow_suffix */); if ( !managedsait && me != NULL ) { diff --git a/ldap/servers/slapd/back-ldbm/index.c b/ldap/servers/slapd/back-ldbm/index.c index bb34c3ff3..a3dac6643 100644 --- a/ldap/servers/slapd/back-ldbm/index.c +++ b/ldap/servers/slapd/back-ldbm/index.c @@ -2022,9 +2022,8 @@ index_addordel_values_ext_sv( } ainfo_get( be, basetype, &ai ); - if ( ai == NULL || ai->ai_indexmask == 0 - || ai->ai_indexmask == INDEX_OFFLINE ) { - slapi_ch_free_string( &basetmp ); + if ( ai == NULL || ai->ai_indexmask == 0 || ai->ai_indexmask == INDEX_OFFLINE ) { + slapi_ch_free_string( &basetmp ); return( 0 ); } slapi_log_err(SLAPI_LOG_ARGS, "index_addordel_values_ext_sv", "indexmask 0x%x\n", @@ -2033,7 +2032,7 @@ index_addordel_values_ext_sv( slapi_log_err(SLAPI_LOG_ERR, "index_addordel_values_ext_sv", "index_read NULL (could not open index attr %s)\n", basetype); - slapi_ch_free_string( &basetmp ); + slapi_ch_free_string( &basetmp ); if ( err != 0 ) { ldbm_nasty("index_addordel_values_ext_sv", errmsg, 1210, err); } @@ -2101,10 +2100,10 @@ index_addordel_values_ext_sv( Slapi_Value **esubvals = NULL; Slapi_Value **substresult = NULL; Slapi_Value **origvals = NULL; - Slapi_PBlock *pipb = slapi_pblock_new(); + Slapi_PBlock *pipb = slapi_pblock_new(); - /* prepare pblock to pass ai_substr_lens */ - slapi_pblock_set( pipb, SLAPI_SYNTAX_SUBSTRLENS, ai->ai_substr_lens ); + /* prepare pblock to pass ai_substr_lens */ + slapi_pblock_set( pipb, SLAPI_SYNTAX_SUBSTRLENS, ai->ai_substr_lens ); slapi_attr_values2keys_sv_pb( &ai->ai_sattr, vals, &ivals, LDAP_FILTER_SUBSTRINGS, pipb ); origvals = ivals; @@ -2154,8 +2153,8 @@ index_addordel_values_ext_sv( matchrule_values_to_keys_sv(pb,vals,&keys); /* the matching rule indexer owns keys now */ if(keys != NULL && keys[0] != NULL) - { - /* we've computed keys */ + { + /* we've computed keys */ err = addordel_values_sv (be, db, basetype, officialOID, keys, id, flags, txn, ai, idl_disposition, NULL); if ( err != 0 ) { diff --git a/ldap/servers/slapd/back-ldbm/ldbm_delete.c b/ldap/servers/slapd/back-ldbm/ldbm_delete.c index 65b0cce1a..cfc18b0dc 100644 --- a/ldap/servers/slapd/back-ldbm/ldbm_delete.c +++ b/ldap/servers/slapd/back-ldbm/ldbm_delete.c @@ -78,7 +78,7 @@ ldbm_back_delete( Slapi_PBlock *pb ) ID ep_id = 0; ID tomb_ep_id = 0; int result_sent = 0; - Connection *pb_conn; + Connection *pb_conn; if (slapi_pblock_get(pb, SLAPI_CONN_ID, &conn_id) < 0) { conn_id = 0; /* connection is NULL */ @@ -91,7 +91,7 @@ ldbm_back_delete( Slapi_PBlock *pb ) slapi_pblock_get( pb, SLAPI_TXN, (void**)&parent_txn ); slapi_pblock_get( pb, SLAPI_OPERATION, &operation ); slapi_pblock_get( pb, SLAPI_IS_REPLICATED_OPERATION, &is_replicated_operation ); - slapi_pblock_get(pb, SLAPI_CONNECTION, &pb_conn); + slapi_pblock_get(pb, SLAPI_CONNECTION, &pb_conn); slapi_sdn_init(&nscpEntrySDN); slapi_sdn_init(&parentsdn); diff --git a/ldap/servers/slapd/back-ldbm/vlv.c b/ldap/servers/slapd/back-ldbm/vlv.c index 4840be234..37cf25dd6 100644 --- a/ldap/servers/slapd/back-ldbm/vlv.c +++ b/ldap/servers/slapd/back-ldbm/vlv.c @@ -1198,33 +1198,32 @@ vlv_search_build_candidate_list(Slapi_PBlock *pb, const Slapi_DN *base, int *vlv backend *be; int scope, rc=LDAP_SUCCESS; char *fstr; - back_txn txn = {NULL}; + back_txn txn = {NULL}; - slapi_pblock_get( pb, SLAPI_TXN, &txn.back_txn_txn ); + slapi_pblock_get( pb, SLAPI_TXN, &txn.back_txn_txn ); slapi_pblock_get( pb, SLAPI_BACKEND, &be ); - slapi_pblock_get( pb, SLAPI_SEARCH_SCOPE, &scope ); - slapi_pblock_get( pb, SLAPI_SEARCH_STRFILTER, &fstr ); + slapi_pblock_get( pb, SLAPI_SEARCH_SCOPE, &scope ); + slapi_pblock_get( pb, SLAPI_SEARCH_STRFILTER, &fstr ); slapi_rwlock_rdlock(be->vlvSearchList_lock); if((pi=vlv_find_search(be, base, scope, fstr, sort_control)) == NULL) { - unsigned int opnote = SLAPI_OP_NOTE_UNINDEXED; - int pr_idx = -1; - Connection *pb_conn = NULL; - Operation *pb_op = NULL; + unsigned int opnote = SLAPI_OP_NOTE_UNINDEXED; + int pr_idx = -1; + Connection *pb_conn = NULL; + Operation *pb_op = NULL; - slapi_pblock_get( pb, SLAPI_PAGED_RESULTS_INDEX, &pr_idx ); - slapi_rwlock_unlock(be->vlvSearchList_lock); - slapi_pblock_set( pb, SLAPI_OPERATION_NOTES, &opnote ); + slapi_pblock_get( pb, SLAPI_PAGED_RESULTS_INDEX, &pr_idx ); + slapi_rwlock_unlock(be->vlvSearchList_lock); + slapi_pblock_set( pb, SLAPI_OPERATION_NOTES, &opnote ); - slapi_pblock_get(pb, SLAPI_OPERATION, &pb_op); - slapi_pblock_get(pb, SLAPI_CONNECTION, &pb_conn); + slapi_pblock_get(pb, SLAPI_OPERATION, &pb_op); + slapi_pblock_get(pb, SLAPI_CONNECTION, &pb_conn); - pagedresults_set_unindexed( pb_conn, pb_op, pr_idx ); - rc = VLV_FIND_SEARCH_FAILED; + pagedresults_set_unindexed( pb_conn, pb_op, pr_idx ); + rc = VLV_FIND_SEARCH_FAILED; } else if((*vlv_rc=vlvIndex_accessallowed(pi, pb)) != LDAP_SUCCESS) { - slapi_rwlock_unlock(be->vlvSearchList_lock); + slapi_rwlock_unlock(be->vlvSearchList_lock); rc = VLV_ACCESS_DENIED; - } else if ((*vlv_rc=vlv_build_candidate_list(be,pi,vlv_request_control,candidates, - vlv_response_control, 1, &txn)) != LDAP_SUCCESS) { + } else if ((*vlv_rc=vlv_build_candidate_list(be,pi,vlv_request_control,candidates, vlv_response_control, 1, &txn)) != LDAP_SUCCESS) { rc = VLV_BLD_LIST_FAILED; vlv_response_control->result=*vlv_rc; } diff --git a/ldap/servers/slapd/bind.c b/ldap/servers/slapd/bind.c index 41e112e75..7f4414fd1 100644 --- a/ldap/servers/slapd/bind.c +++ b/ldap/servers/slapd/bind.c @@ -59,16 +59,16 @@ do_bind( Slapi_PBlock *pb ) slapi_pblock_get(pb, SLAPI_OPERATION, &pb_op); slapi_pblock_get(pb, SLAPI_CONNECTION, &pb_conn); - BerElement *ber = pb_op->o_ber; - int err, isroot; - ber_tag_t method = LBER_DEFAULT; - ber_int_t version = -1; - int auth_response_requested = 0; - int pw_response_requested = 0; - char *rawdn = NULL; - const char *dn = NULL; - char *saslmech = NULL; - struct berval cred = {0}; + BerElement *ber = pb_op->o_ber; + int err, isroot; + ber_tag_t method = LBER_DEFAULT; + ber_int_t version = -1; + int auth_response_requested = 0; + int pw_response_requested = 0; + char *rawdn = NULL; + const char *dn = NULL; + char *saslmech = NULL; + struct berval cred = {0}; ber_tag_t ber_rc; int rc = 0; Slapi_DN *sdn = NULL; diff --git a/ldap/servers/slapd/compare.c b/ldap/servers/slapd/compare.c index d66bf3bab..6903027b4 100644 --- a/ldap/servers/slapd/compare.c +++ b/ldap/servers/slapd/compare.c @@ -33,10 +33,10 @@ void do_compare( Slapi_PBlock *pb ) { - Operation *pb_op = NULL; - Connection *pb_conn = NULL; - slapi_pblock_get(pb, SLAPI_OPERATION, &pb_op); - slapi_pblock_get(pb, SLAPI_CONNECTION, &pb_conn); + Operation *pb_op = NULL; + Connection *pb_conn = NULL; + slapi_pblock_get(pb, SLAPI_OPERATION, &pb_op); + slapi_pblock_get(pb, SLAPI_CONNECTION, &pb_conn); BerElement *ber = pb_op->o_ber; char *rawdn = NULL; @@ -54,7 +54,7 @@ do_compare( Slapi_PBlock *pb ) slapi_counter_increment(g_get_global_snmp_vars()->ops_tbl.dsCompareOps); /* have to init this here so we can "done" it below if we short circuit */ - slapi_sdn_init(&sdn); + slapi_sdn_init(&sdn); /* * Parse the compare request. It looks like this: @@ -91,14 +91,14 @@ do_compare( Slapi_PBlock *pb ) } slapi_sdn_init_dn_passin(&sdn, rawdn); dn = slapi_sdn_get_dn(&sdn); - if (rawdn && (strlen(rawdn) > 0) && (NULL == dn)) { - /* normalization failed */ - op_shared_log_error_access(pb, "CMP", rawdn, "invalid dn"); - send_ldap_result(pb, LDAP_INVALID_DN_SYNTAX, NULL, - "invalid dn", 0, NULL); - slapi_sdn_done(&sdn); - return; - } + if (rawdn && (strlen(rawdn) > 0) && (NULL == dn)) { + /* normalization failed */ + op_shared_log_error_access(pb, "CMP", rawdn, "invalid dn"); + send_ldap_result(pb, LDAP_INVALID_DN_SYNTAX, NULL, + "invalid dn", 0, NULL); + slapi_sdn_done(&sdn); + return; + } /* * in LDAPv3 there can be optional control extensions on * the end of an LDAPMessage. we need to read them in and @@ -148,8 +148,8 @@ do_compare( Slapi_PBlock *pb ) } if ( be->be_compare != NULL ) { - int isroot; - + int isroot; + slapi_pblock_set( pb, SLAPI_BACKEND, be ); isroot = pb_op->o_isroot; @@ -181,8 +181,9 @@ do_compare( Slapi_PBlock *pb ) } free_and_return:; - if (be) + if (be) { slapi_be_Unlock(be); + } slapi_sdn_done(&sdn); ava_done( &ava ); } diff --git a/ldap/servers/slapd/connection.c b/ldap/servers/slapd/connection.c index 3b2f6d5fb..7aa271656 100644 --- a/ldap/servers/slapd/connection.c +++ b/ldap/servers/slapd/connection.c @@ -949,10 +949,10 @@ void connection_make_new_pb(Slapi_PBlock *pb, Connection *conn) */ /* *ppb = (Slapi_PBlock *) slapi_ch_calloc( 1, sizeof(Slapi_PBlock) ); */ /* *ppb = slapi_pblock_new(); */ - slapi_pblock_set(pb, SLAPI_CONNECTION, conn); + slapi_pblock_set(pb, SLAPI_CONNECTION, conn); stack_obj = connection_get_operation(); - slapi_pblock_set(pb, SLAPI_OPERATION, stack_obj->op); - slapi_pblock_set_op_stack_elem(pb, stack_obj); + slapi_pblock_set(pb, SLAPI_OPERATION, stack_obj->op); + slapi_pblock_set_op_stack_elem(pb, stack_obj); connection_add_operation( conn, stack_obj->op ); } @@ -1506,8 +1506,8 @@ connection_threadmain() int maxthreads = 0; int enable_nunc_stans = 0; long bypasspollcnt = 0; - Connection *pb_conn = NULL; - Operation *pb_op = NULL; + Connection *pb_conn = NULL; + Operation *pb_op = NULL; #ifdef ENABLE_NUNC_STANS enable_nunc_stans = config_get_enable_nunc_stans(); @@ -1535,11 +1535,11 @@ connection_threadmain() [blackflag 624234] */ ret = connection_wait_for_new_work(pb,interval); - /* - * Connection wait for new work provides the conn and op for us. - */ - slapi_pblock_get(pb, SLAPI_CONNECTION, &pb_conn); - slapi_pblock_get(pb, SLAPI_OPERATION, &pb_op); + /* + * Connection wait for new work provides the conn and op for us. + */ + slapi_pblock_get(pb, SLAPI_CONNECTION, &pb_conn); + slapi_pblock_get(pb, SLAPI_OPERATION, &pb_op); switch (ret) { case CONN_NOWORK: @@ -1606,8 +1606,8 @@ connection_threadmain() } } /* Once we're here we have a pb */ - slapi_pblock_get(pb, SLAPI_CONNECTION, &conn); - slapi_pblock_get(pb, SLAPI_OPERATION, &op); + slapi_pblock_get(pb, SLAPI_CONNECTION, &conn); + slapi_pblock_get(pb, SLAPI_OPERATION, &op); maxthreads = config_get_maxthreadsperconn(); more_data = 0; ret = connection_read_operation(conn, op, &tag, &more_data); @@ -2057,9 +2057,9 @@ void connection_remove_operation_ext( Slapi_PBlock *pb, Connection *conn, Operation *op ) { connection_remove_operation(conn, op); - void *op_stack_elem = slapi_pblock_get_op_stack_elem(pb); + void *op_stack_elem = slapi_pblock_get_op_stack_elem(pb); connection_done_operation(conn, op_stack_elem); - slapi_pblock_set(pb, SLAPI_OPERATION, NULL); + slapi_pblock_set(pb, SLAPI_OPERATION, NULL); slapi_pblock_init(pb); } @@ -2162,9 +2162,8 @@ connection_set_ssl_ssf(Connection *conn) static int is_ber_too_big(const Connection *conn, ber_len_t ber_len) { - ber_len_t maxbersize = config_get_maxbersize(); - if(ber_len > maxbersize) - { + ber_len_t maxbersize = config_get_maxbersize(); + if (ber_len > maxbersize) { log_ber_too_big_error(conn, ber_len, maxbersize); return 1; } @@ -2220,7 +2219,7 @@ static ps_wakeup_all_fn_ptr ps_wakeup_all_fn = NULL; void disconnect_server_nomutex_ext( Connection *conn, PRUint64 opconnid, int opid, PRErrorCode reason, PRInt32 error, int schedule_closure_job ) { - if ( ( conn->c_sd != SLAPD_INVALID_SOCKET && + if ( ( conn->c_sd != SLAPD_INVALID_SOCKET && conn->c_connid == opconnid ) && !(conn->c_flags & CONN_FLAG_CLOSING) ) { slapi_log_err(SLAPI_LOG_CONNS, "disconnect_server_nomutex_ext", "Setting conn %" PRIu64 " fd=%d " diff --git a/ldap/servers/slapd/control.c b/ldap/servers/slapd/control.c index 981dca1c3..c302e4b0f 100644 --- a/ldap/servers/slapd/control.c +++ b/ldap/servers/slapd/control.c @@ -176,12 +176,12 @@ get_ldapmessage_controls_ext( { LDAPControl **ctrls, *new; ber_tag_t tag; - /* ber_len_t is uint, cannot be -1 */ + /* ber_len_t is uint, cannot be -1 */ ber_len_t len = LBER_ERROR; int rc, maxcontrols, curcontrols; char *last; int managedsait, pwpolicy_ctrl; - Connection *pb_conn = NULL; + Connection *pb_conn = NULL; /* * Each LDAPMessage can have a set of controls appended diff --git a/ldap/servers/slapd/defbackend.c b/ldap/servers/slapd/defbackend.c index 57290eed6..8da702a42 100644 --- a/ldap/servers/slapd/defbackend.c +++ b/ldap/servers/slapd/defbackend.c @@ -91,27 +91,27 @@ defbackend_init( void ) */ errmsg = "slapi_pblock_set handlers failed"; rc = slapi_pblock_set( pb, SLAPI_PLUGIN_VERSION, - (void *)SLAPI_PLUGIN_CURRENT_VERSION ); + (void *)SLAPI_PLUGIN_CURRENT_VERSION ); rc |= slapi_pblock_set( pb, SLAPI_PLUGIN_DB_BIND_FN, - (void *)defbackend_bind ); + (void *)defbackend_bind ); rc |= slapi_pblock_set( pb, SLAPI_PLUGIN_DB_UNBIND_FN, - (void *)defbackend_noop ); + (void *)defbackend_noop ); rc |= slapi_pblock_set( pb, SLAPI_PLUGIN_DB_SEARCH_FN, - (void *)defbackend_default ); + (void *)defbackend_default ); rc |= slapi_pblock_set( pb, SLAPI_PLUGIN_DB_NEXT_SEARCH_ENTRY_FN, - (void *)defbackend_next_search_entry ); + (void *)defbackend_next_search_entry ); rc |= slapi_pblock_set( pb, SLAPI_PLUGIN_DB_COMPARE_FN, - (void *)defbackend_default ); + (void *)defbackend_default ); rc |= slapi_pblock_set( pb, SLAPI_PLUGIN_DB_MODIFY_FN, - (void *)defbackend_default ); + (void *)defbackend_default ); rc |= slapi_pblock_set( pb, SLAPI_PLUGIN_DB_MODRDN_FN, - (void *)defbackend_default ); + (void *)defbackend_default ); rc |= slapi_pblock_set( pb, SLAPI_PLUGIN_DB_ADD_FN, - (void *)defbackend_default ); + (void *)defbackend_default ); rc |= slapi_pblock_set( pb, SLAPI_PLUGIN_DB_DELETE_FN, - (void *)defbackend_default ); + (void *)defbackend_default ); rc |= slapi_pblock_set( pb, SLAPI_PLUGIN_DB_ABANDON_FN, - (void *)defbackend_abandon ); + (void *)defbackend_abandon ); cleanup_and_return: diff --git a/ldap/servers/slapd/delete.c b/ldap/servers/slapd/delete.c index fbcca6a38..6ce74bba3 100644 --- a/ldap/servers/slapd/delete.c +++ b/ldap/servers/slapd/delete.c @@ -260,10 +260,10 @@ static void op_shared_delete (Slapi_PBlock *pb) if (!internal_op ) { - Connection *pb_conn = NULL; - Operation *pb_op = NULL; - slapi_pblock_get(pb, SLAPI_CONNECTION, &pb_conn); - slapi_pblock_get(pb, SLAPI_OPERATION, &pb_op); + Connection *pb_conn = NULL; + Operation *pb_op = NULL; + slapi_pblock_get(pb, SLAPI_CONNECTION, &pb_conn); + slapi_pblock_get(pb, SLAPI_OPERATION, &pb_op); slapi_log_access(LDAP_DEBUG_STATS, "conn=%" PRIu64 " op=%d DEL dn=\"%s\"%s\n", pb_conn->c_connid, pb_op->o_opid, diff --git a/ldap/servers/slapd/fedse.c b/ldap/servers/slapd/fedse.c index 04fab984f..c3dfdc73b 100644 --- a/ldap/servers/slapd/fedse.c +++ b/ldap/servers/slapd/fedse.c @@ -1542,7 +1542,7 @@ internal_add_helper(Slapi_Entry *e, int dont_write_file) operation_set_flag(op, OP_FLAG_ACTION_NOLOG); slapi_add_internal_pb(newpb); - slapi_pblock_destroy(newpb); + slapi_pblock_destroy(newpb); } /* @@ -1566,22 +1566,22 @@ init_dse_file(const char *configdir, Slapi_DN *config) if(rc) { Slapi_PBlock *pb = slapi_pblock_new(); - int dont_write = 1; - dse_register_callback(pfedse,DSE_OPERATION_READ,DSE_FLAG_PREOP,config, - LDAP_SCOPE_SUBTREE,"(objectclass=nsslapdPlugin)", - load_plugin_entry, NULL, NULL); - dse_register_callback(pfedse,DSE_OPERATION_READ,DSE_FLAG_PREOP,config, - LDAP_SCOPE_BASE,"(objectclass=*)", - load_config_dse,NULL, NULL); - - slapi_pblock_set(pb, SLAPI_CONFIG_DIRECTORY, (void*)configdir); - /* don't write out the file when reading */ - slapi_pblock_set(pb, SLAPI_DSE_DONT_WRITE_WHEN_ADDING, (void*)&dont_write); + int dont_write = 1; + dse_register_callback(pfedse,DSE_OPERATION_READ,DSE_FLAG_PREOP,config, + LDAP_SCOPE_SUBTREE,"(objectclass=nsslapdPlugin)", + load_plugin_entry, NULL, NULL); + dse_register_callback(pfedse,DSE_OPERATION_READ,DSE_FLAG_PREOP,config, + LDAP_SCOPE_BASE,"(objectclass=*)", + load_config_dse,NULL, NULL); + + slapi_pblock_set(pb, SLAPI_CONFIG_DIRECTORY, (void*)configdir); + /* don't write out the file when reading */ + slapi_pblock_set(pb, SLAPI_DSE_DONT_WRITE_WHEN_ADDING, (void*)&dont_write); if(!(rc = dse_read_file(pfedse, pb))) { - slapi_log_err(SLAPI_LOG_ERR, "init_dse_file", - "Could not load config file [%s]\n", - DSE_FILENAME ); + slapi_log_err(SLAPI_LOG_ERR, "init_dse_file", + "Could not load config file [%s]\n", + DSE_FILENAME ); } slapi_pblock_destroy(pb); } diff --git a/ldap/servers/slapd/filter.c b/ldap/servers/slapd/filter.c index 58e55b7bc..949e40955 100644 --- a/ldap/servers/slapd/filter.c +++ b/ldap/servers/slapd/filter.c @@ -774,11 +774,11 @@ slapi_filter_free( struct slapi_filter *f, int recurse ) slapi_ch_free((void**)&f->f_mr_type); slapi_ber_bvdone(&f->f_mr_value); if (f->f_mr.mrf_destroy != NULL) { - Slapi_PBlock *pb = slapi_pblock_new(); - if ( ! slapi_pblock_set (pb, SLAPI_PLUGIN_OBJECT, f->f_mr.mrf_object)) { - f->f_mr.mrf_destroy (pb); - } - slapi_pblock_destroy(pb); + Slapi_PBlock *pb = slapi_pblock_new(); + if ( ! slapi_pblock_set (pb, SLAPI_PLUGIN_OBJECT, f->f_mr.mrf_object)) { + f->f_mr.mrf_destroy (pb); + } + slapi_pblock_destroy(pb); } break; diff --git a/ldap/servers/slapd/main.c b/ldap/servers/slapd/main.c index 08156fb9c..2d8c9f866 100644 --- a/ldap/servers/slapd/main.c +++ b/ldap/servers/slapd/main.c @@ -2134,95 +2134,95 @@ slapd_exemode_db2ldif(int argc, char** argv) int return_value= 0; struct slapdplugin *plugin; slapdFrontendConfig_t *slapdFrontendConfig = getFrontendConfig(); - char *my_ldiffile; - char **instp; + char *my_ldiffile; + char **instp; /* this should be the first time this are called! if the init order * is ever changed, these lines should be changed (or erased)! */ mapping_tree_init(); - /* - * if instance is given, just pass it to the backend. - * otherwise, we use included/excluded suffix list to specify a backend. - */ + /* + * if instance is given, just pass it to the backend. + * otherwise, we use included/excluded suffix list to specify a backend. + */ if (NULL == cmd_line_instance_names) { - char **instances, **ip; - int counter; + char **instances, **ip; + int counter; - if (lookup_instance_name_by_suffixes(db2ldif_include, db2ldif_exclude, - &instances) < 0) { - slapi_log_err(SLAPI_LOG_ERR, "slapd_exemode_db2ldif", - "Backend instances name [-n <name>] or " - "included suffix [-s <suffix>] need to be specified.\n"); - return 1; - } + if (lookup_instance_name_by_suffixes(db2ldif_include, db2ldif_exclude, + &instances) < 0) { + slapi_log_err(SLAPI_LOG_ERR, "slapd_exemode_db2ldif", + "Backend instances name [-n <name>] or " + "included suffix [-s <suffix>] need to be specified.\n"); + return 1; + } - if (instances) { - for (ip = instances, counter = 0; ip && *ip; ip++, counter++) - ; + if (instances) { + for (ip = instances, counter = 0; ip && *ip; ip++, counter++) + ; - if (counter == 0) { - slapi_log_err(SLAPI_LOG_ERR, "slapd_exemode_db2ldif", - "There is no backend instance to export from.\n"); - return 1; - } else { - slapi_log_err(SLAPI_LOG_INFO, "slapd_exemode_db2ldif", "db2ldif - Backend Instance(s): \n"); - for (ip = instances, counter = 0; ip && *ip; ip++, counter++) { - slapi_log_err(SLAPI_LOG_INFO, "slapd_exemode_db2ldif", "db2ldif - %s\n", *ip); - } - cmd_line_instance_names = instances; - } - } else { - slapi_log_err(SLAPI_LOG_ERR, "slapd_exemode_db2ldif", - "There is no backend instances to export from.\n"); - return 1; - } + if (counter == 0) { + slapi_log_err(SLAPI_LOG_ERR, "slapd_exemode_db2ldif", + "There is no backend instance to export from.\n"); + return 1; + } else { + slapi_log_err(SLAPI_LOG_INFO, "slapd_exemode_db2ldif", "db2ldif - Backend Instance(s): \n"); + for (ip = instances, counter = 0; ip && *ip; ip++, counter++) { + slapi_log_err(SLAPI_LOG_INFO, "slapd_exemode_db2ldif", "db2ldif - %s\n", *ip); + } + cmd_line_instance_names = instances; + } + } else { + slapi_log_err(SLAPI_LOG_ERR, "slapd_exemode_db2ldif", + "There is no backend instances to export from.\n"); + return 1; + } } - /* [622984] db2lidf -r changes database file ownership - * should call setuid before "db2ldif_dump_replica" */ - main_setuid(slapdFrontendConfig->localuser); - for (instp = cmd_line_instance_names; instp && *instp; instp++) { - int release_me = 0; + /* [622984] db2lidf -r changes database file ownership + * should call setuid before "db2ldif_dump_replica" */ + main_setuid(slapdFrontendConfig->localuser); + for (instp = cmd_line_instance_names; instp && *instp; instp++) { + int release_me = 0; - plugin = lookup_plugin_by_instance_name(*instp); - if (plugin == NULL) { - slapi_log_err(SLAPI_LOG_ERR, "slapd_exemode_db2ldif", - "Could not find backend '%s'.\n", *instp); - return 1; - } - - if (plugin->plg_db2ldif == NULL) { - slapi_log_err(SLAPI_LOG_ERR, "slapd_exemode_db2ldif", - "No db2ldif function defined for backend %s - cannot export\n", *instp); - return 1; - } + plugin = lookup_plugin_by_instance_name(*instp); + if (plugin == NULL) { + slapi_log_err(SLAPI_LOG_ERR, "slapd_exemode_db2ldif", + "Could not find backend '%s'.\n", *instp); + return 1; + } + + if (plugin->plg_db2ldif == NULL) { + slapi_log_err(SLAPI_LOG_ERR, "slapd_exemode_db2ldif", + "No db2ldif function defined for backend %s - cannot export\n", *instp); + return 1; + } - /* Make sure we aren't going to run slapd in - * a mode that is going to conflict with other - * slapd processes that are currently running - */ - if ( add_new_slapd_process(slapd_exemode, db2ldif_dump_replica, - skip_db_protect_check) == -1 ) { - slapi_log_err(SLAPI_LOG_ERR, "slapd_exemode_db2ldif", - "Shutting down due to possible conflicts " - "with other slapd processes\n"); - return 1; - } - - if (! (SLAPI_PLUGIN_IS_V2(plugin))) { - slapi_log_err(SLAPI_LOG_ERR, "slapd_exemode_db2ldif", - "%s is too old to do exports.\n", plugin->plg_name); - return 1; - } - - if (!is_quiet) { - slapd_ldap_debug |= LDAP_DEBUG_BACKLDBM; - } - if (!(slapd_ldap_debug & LDAP_DEBUG_BACKLDBM)) { - g_set_detached(1); - } + /* Make sure we aren't going to run slapd in + * a mode that is going to conflict with other + * slapd processes that are currently running + */ + if ( add_new_slapd_process(slapd_exemode, db2ldif_dump_replica, + skip_db_protect_check) == -1 ) { + slapi_log_err(SLAPI_LOG_ERR, "slapd_exemode_db2ldif", + "Shutting down due to possible conflicts " + "with other slapd processes\n"); + return 1; + } + + if (! (SLAPI_PLUGIN_IS_V2(plugin))) { + slapi_log_err(SLAPI_LOG_ERR, "slapd_exemode_db2ldif", + "%s is too old to do exports.\n", plugin->plg_name); + return 1; + } + + if (!is_quiet) { + slapd_ldap_debug |= LDAP_DEBUG_BACKLDBM; + } + if (!(slapd_ldap_debug & LDAP_DEBUG_BACKLDBM)) { + g_set_detached(1); + } Slapi_PBlock *pb = slapi_pblock_new(); slapi_pblock_set(pb, SLAPI_BACKEND, NULL); slapi_pblock_set(pb, SLAPI_PLUGIN, plugin); @@ -2235,80 +2235,80 @@ slapd_exemode_db2ldif(int argc, char** argv) int32_t task_flags = SLAPI_TASK_RUNNING_FROM_COMMANDLINE; slapi_pblock_set(pb, SLAPI_TASK_FLAGS, &task_flags); int32_t is_running = 0; - if (is_slapd_running()) { + if (is_slapd_running()) { is_running = 1; } slapi_pblock_set(pb, SLAPI_DB2LDIF_SERVER_RUNNING, &is_running); - - if (db2ldif_dump_replica) { - char **plugin_list = NULL; - char *repl_plg_name = "Multimaster Replication Plugin"; - - /* - * Only start the necessary plugins for "db2ldif -r" - * - * We need replication, but replication has its own - * dependencies - */ - plugin_get_plugin_dependencies(repl_plg_name, &plugin_list); - - eq_init(); /* must be done before plugins started */ - ps_init_psearch_system(); /* must come before plugin_startall() */ - plugin_startall(argc, argv, plugin_list); - eq_start(); /* must be done after plugins started */ - charray_free(plugin_list); - } - - if ( archive_name ) { /* redirect stdout to this file: */ + + if (db2ldif_dump_replica) { + char **plugin_list = NULL; + char *repl_plg_name = "Multimaster Replication Plugin"; + + /* + * Only start the necessary plugins for "db2ldif -r" + * + * We need replication, but replication has its own + * dependencies + */ + plugin_get_plugin_dependencies(repl_plg_name, &plugin_list); + + eq_init(); /* must be done before plugins started */ + ps_init_psearch_system(); /* must come before plugin_startall() */ + plugin_startall(argc, argv, plugin_list); + eq_start(); /* must be done after plugins started */ + charray_free(plugin_list); + } + + if ( archive_name ) { /* redirect stdout to this file: */ char *p, *q; - char sep = '/'; - - my_ldiffile = archive_name; - if (ldif_printkey & EXPORT_APPENDMODE) { - if (instp == cmd_line_instance_names) { /* first export */ - ldif_printkey |= EXPORT_APPENDMODE_1; - } else { - ldif_printkey &= ~EXPORT_APPENDMODE_1; - } - } else { /* not APPENDMODE */ - if (strcmp(archive_name, "-")) { /* not '-' */ - my_ldiffile = - (char *)slapi_ch_malloc((unsigned long)(strlen(archive_name) - + strlen(*instp) + 2)); - p = strrchr(archive_name, sep); - if (NULL == p) { - sprintf(my_ldiffile, "%s_%s", *instp, archive_name); - } else { - q = p + 1; - *p = '\0'; - sprintf(my_ldiffile, "%s%c%s_%s", - archive_name, sep, *instp, q); - *p = sep; - } - release_me = 1; - } - } + char sep = '/'; + + my_ldiffile = archive_name; + if (ldif_printkey & EXPORT_APPENDMODE) { + if (instp == cmd_line_instance_names) { /* first export */ + ldif_printkey |= EXPORT_APPENDMODE_1; + } else { + ldif_printkey &= ~EXPORT_APPENDMODE_1; + } + } else { /* not APPENDMODE */ + if (strcmp(archive_name, "-")) { /* not '-' */ + my_ldiffile = + (char *)slapi_ch_malloc((unsigned long)(strlen(archive_name) + + strlen(*instp) + 2)); + p = strrchr(archive_name, sep); + if (NULL == p) { + sprintf(my_ldiffile, "%s_%s", *instp, archive_name); + } else { + q = p + 1; + *p = '\0'; + sprintf(my_ldiffile, "%s%c%s_%s", + archive_name, sep, *instp, q); + *p = sep; + } + release_me = 1; + } + } - if (!is_quiet) { - fprintf(stderr, "ldiffile: %s\n", my_ldiffile); - } - /* just send the filename to the backend and let - * the backend open it (so they can do special - * stuff for 64-bit fs) - */ + if (!is_quiet) { + fprintf(stderr, "ldiffile: %s\n", my_ldiffile); + } + /* just send the filename to the backend and let + * the backend open it (so they can do special + * stuff for 64-bit fs) + */ slapi_pblock_set(pb, SLAPI_DB2LDIF_FILE, my_ldiffile); slapi_pblock_set(pb, SLAPI_DB2LDIF_PRINTKEY, &ldif_printkey); - } - - return_value = (plugin->plg_db2ldif)( pb ); + } + + return_value = (plugin->plg_db2ldif)( pb ); slapi_pblock_destroy(pb); - if (release_me) { - slapi_ch_free((void **)&my_ldiffile); - } - } - slapi_ch_free( (void**)&myname ); + if (release_me) { + slapi_ch_free((void **)&my_ldiffile); + } + } + slapi_ch_free( (void**)&myname ); if (db2ldif_dump_replica) { eq_stop(); /* event queue should be shutdown before closing all plugins (especailly, replication plugin) */ @@ -2440,7 +2440,7 @@ static int slapd_exemode_db2index(void) static int slapd_exemode_db2archive(void) { - int return_value= 0; + int return_value= 0; struct slapdplugin *backend_plugin; slapdFrontendConfig_t *slapdFrontendConfig = getFrontendConfig(); @@ -2460,10 +2460,10 @@ slapd_exemode_db2archive(void) * slapd processes that are currently running */ if ( add_new_slapd_process(slapd_exemode, db2ldif_dump_replica, - skip_db_protect_check) == -1 ) { + skip_db_protect_check) == -1 ) { slapi_log_err(SLAPI_LOG_ERR, "slapd_exemode_db2archive", - "Shutting down due to possible conflicts with other slapd processes\n"); - return 1; + "Shutting down due to possible conflicts with other slapd processes\n"); + return 1; } if (compute_init()) { slapi_log_err(SLAPI_LOG_ERR, "slapd_exemode_db2archive", @@ -2478,14 +2478,14 @@ slapd_exemode_db2archive(void) } Slapi_PBlock *pb = slapi_pblock_new(); - slapi_pblock_set(pb, SLAPI_BACKEND, NULL); - slapi_pblock_set(pb, SLAPI_PLUGIN, backend_plugin); - slapi_pblock_set(pb, SLAPI_SEQ_VAL, archive_name); - int32_t task_flags = SLAPI_TASK_RUNNING_FROM_COMMANDLINE; - slapi_pblock_set(pb, SLAPI_TASK_FLAGS, &task_flags); + slapi_pblock_set(pb, SLAPI_BACKEND, NULL); + slapi_pblock_set(pb, SLAPI_PLUGIN, backend_plugin); + slapi_pblock_set(pb, SLAPI_SEQ_VAL, archive_name); + int32_t task_flags = SLAPI_TASK_RUNNING_FROM_COMMANDLINE; + slapi_pblock_set(pb, SLAPI_TASK_FLAGS, &task_flags); main_setuid(slapdFrontendConfig->localuser); return_value = (backend_plugin->plg_db2archive)( pb ); - slapi_pblock_destroy(pb); + slapi_pblock_destroy(pb); return return_value; } diff --git a/ldap/servers/slapd/modify.c b/ldap/servers/slapd/modify.c index 0991e8329..447c9e330 100644 --- a/ldap/servers/slapd/modify.c +++ b/ldap/servers/slapd/modify.c @@ -98,7 +98,7 @@ void do_modify( Slapi_PBlock *pb ) { Slapi_Operation *operation = NULL; - Connection *pb_conn = NULL; + Connection *pb_conn = NULL; Slapi_Mods smods; BerElement *ber; ber_tag_t tag; @@ -120,7 +120,7 @@ do_modify( Slapi_PBlock *pb ) slapi_pblock_get( pb, SLAPI_OPERATION, &operation); ber = operation->o_ber; - slapi_pblock_get(pb, SLAPI_CONNECTION, &pb_conn); + slapi_pblock_get(pb, SLAPI_CONNECTION, &pb_conn); /* count the modify request */ slapi_counter_increment(g_get_global_snmp_vars()->ops_tbl.dsModifyEntryOps); @@ -631,7 +631,7 @@ static void op_shared_modify (Slapi_PBlock *pb, int pw_change, char *old_pw) int repl_op, internal_op, lastmod, skip_modified_attrs; char *unhashed_pw_attr = NULL; Slapi_Operation *operation; - Connection *pb_conn; + Connection *pb_conn; char errorbuf[SLAPI_DSE_RETURNTEXT_SIZE]; int err; LDAPMod *lc_mod = NULL; @@ -649,7 +649,7 @@ static void op_shared_modify (Slapi_PBlock *pb, int pw_change, char *old_pw) slapi_pblock_get (pb, SLAPI_OPERATION, &operation); internal_op= operation_is_flag_set(operation, OP_FLAG_INTERNAL); slapi_pblock_get (pb, SLAPI_SKIP_MODIFIED_ATTRS, &skip_modified_attrs); - slapi_pblock_get(pb, SLAPI_CONNECTION, &pb_conn); + slapi_pblock_get(pb, SLAPI_CONNECTION, &pb_conn); if (sdn) { passin_sdn = 1; diff --git a/ldap/servers/slapd/modrdn.c b/ldap/servers/slapd/modrdn.c index 1b6ae8cb5..bd893eede 100644 --- a/ldap/servers/slapd/modrdn.c +++ b/ldap/servers/slapd/modrdn.c @@ -401,7 +401,7 @@ op_shared_rename(Slapi_PBlock *pb, int passin_args) char *errtext = NULL; Slapi_DN *sdn = NULL; Slapi_DN *newsuperiorsdn = NULL; - Connection *pb_conn; + Connection *pb_conn; slapi_pblock_get(pb, SLAPI_ORIGINAL_TARGET, &dn); slapi_pblock_get(pb, SLAPI_MODRDN_NEWRDN, &newrdn); @@ -411,7 +411,7 @@ op_shared_rename(Slapi_PBlock *pb, int passin_args) slapi_pblock_get (pb, SLAPI_OPERATION, &operation); slapi_pblock_get(pb, SLAPI_MODRDN_TARGET_SDN, &origsdn); internal_op= operation_is_flag_set(operation, OP_FLAG_INTERNAL); - slapi_pblock_get(pb, SLAPI_CONNECTION, &pb_conn); + slapi_pblock_get(pb, SLAPI_CONNECTION, &pb_conn); /* * If ownership has not been passed to this function, we replace the diff --git a/ldap/servers/slapd/passwd_extop.c b/ldap/servers/slapd/passwd_extop.c index de1c8c298..58ee58cb2 100644 --- a/ldap/servers/slapd/passwd_extop.c +++ b/ldap/servers/slapd/passwd_extop.c @@ -132,7 +132,7 @@ passwd_apply_mods(Slapi_PBlock *pb_orig, const Slapi_DN *sdn, Slapi_Mods *mods, slapi_add_controls(&req_controls_copy, req_controls, 1); } - Slapi_PBlock *pb = slapi_pblock_new(); + Slapi_PBlock *pb = slapi_pblock_new(); slapi_modify_internal_set_pb_ext (pb, sdn, slapi_mods_get_ldapmods_byref(mods), req_controls_copy, NULL, /* UniqueID */ @@ -145,16 +145,16 @@ passwd_apply_mods(Slapi_PBlock *pb_orig, const Slapi_DN *sdn, Slapi_Mods *mods, * that the password change was initiated by the user who * sent the extended operation instead of always assuming * that it was done by the root DN. */ - Connection *pb_conn = NULL; - slapi_pblock_get(pb_orig, SLAPI_CONNECTION, &pb_conn); - slapi_pblock_set(pb, SLAPI_CONNECTION, pb_conn); + Connection *pb_conn = NULL; + slapi_pblock_get(pb_orig, SLAPI_CONNECTION, &pb_conn); + slapi_pblock_set(pb, SLAPI_CONNECTION, pb_conn); ret =slapi_modify_internal_pb (pb); /* We now clean up the connection that we copied into the * new pblock. We want to leave it untouched. */ - slapi_pblock_set(pb, SLAPI_CONNECTION, NULL); - + slapi_pblock_set(pb, SLAPI_CONNECTION, NULL); + slapi_pblock_get(pb, SLAPI_PLUGIN_INTOP_RESULT, &ret); /* Retrieve and duplicate the response controls since they will be @@ -170,12 +170,12 @@ passwd_apply_mods(Slapi_PBlock *pb_orig, const Slapi_DN *sdn, Slapi_Mods *mods, ret, slapi_sdn_get_dn(sdn)); } - slapi_pblock_destroy(pb); - } + slapi_pblock_destroy(pb); + } - slapi_log_err(SLAPI_LOG_TRACE, "passwd_apply_mods", "<= %d\n", ret); + slapi_log_err(SLAPI_LOG_TRACE, "passwd_apply_mods", "<= %d\n", ret); - return ret; + return ret; } @@ -772,8 +772,8 @@ parse_req_done: * this here since the normal modify code doesn't perform this check for * internal operations. */ - Connection *pb_conn; - slapi_pblock_get(pb, SLAPI_CONNECTION, &pb_conn); + Connection *pb_conn; + slapi_pblock_get(pb, SLAPI_CONNECTION, &pb_conn); if (!pb_op->o_isroot && !pb_conn->c_needpw && !pwpolicy->pw_change) { if (NULL == bindSDN) { bindSDN = slapi_sdn_new_normdn_byref(bindDN); diff --git a/ldap/servers/slapd/plugin.c b/ldap/servers/slapd/plugin.c index 63ac056a9..77043ff01 100644 --- a/ldap/servers/slapd/plugin.c +++ b/ldap/servers/slapd/plugin.c @@ -1569,7 +1569,7 @@ plugin_dependency_startall(int argc, char** argv, char *errmsg __attribute__((un } } - pb = slapi_pblock_new(); + pb = slapi_pblock_new(); slapi_pblock_set( pb, SLAPI_ARGC, &argc); slapi_pblock_set( pb, SLAPI_ARGV, &argv); @@ -1821,10 +1821,10 @@ plugin_dependency_startall(int argc, char** argv, char *errmsg __attribute__((un * because at this point we *have* started correctly, so we * can now free this. */ - /* This is freed in free_plugin_dep_config */ - /* + /* This is freed in free_plugin_dep_config */ + /* slapi_pblock_destroy(config[plugin_index].pb); - */ + */ /* Add this plugin to the shutdown list */ @@ -3082,7 +3082,7 @@ plugin_setup(Slapi_Entry *plugin_entry, struct slapi_componentid *group, PR_snprintf(attrname, sizeof(attrname), "%s%d", ATTR_PLUGIN_ARG, ++ii); } while (skipped < MAXSKIPPED); - pb = slapi_pblock_new(); + pb = slapi_pblock_new(); slapi_pblock_set(pb, SLAPI_PLUGIN, plugin); slapi_pblock_set(pb, SLAPI_PLUGIN_VERSION, (void *)SLAPI_PLUGIN_CURRENT_VERSION); @@ -3726,16 +3726,16 @@ static PRBool plugin_invoke_plugin_pb (struct slapdplugin *plugin, int operation, Slapi_PBlock *pb) { Slapi_DN *target_spec; - Operation *pb_op = NULL; + Operation *pb_op = NULL; PRBool rc; PR_ASSERT (plugin); PR_ASSERT (pb); /* we always allow initialization and cleanup operations */ - if (operation == SLAPI_PLUGIN_START_FN || + if (operation == SLAPI_PLUGIN_START_FN || operation == SLAPI_PLUGIN_POSTSTART_FN || - operation == SLAPI_PLUGIN_CLOSE_FN || + operation == SLAPI_PLUGIN_CLOSE_FN || operation == SLAPI_PLUGIN_CLEANUP_FN || operation == SLAPI_PLUGIN_BE_PRE_CLOSE_FN || operation == SLAPI_PLUGIN_BE_POST_OPEN_FN || @@ -3743,9 +3743,9 @@ plugin_invoke_plugin_pb (struct slapdplugin *plugin, int operation, Slapi_PBlock operation == SLAPI_PLUGIN_BE_POST_BACKUP_FN) return PR_TRUE; - slapi_pblock_get(pb, SLAPI_OPERATION, &pb_op); + slapi_pblock_get(pb, SLAPI_OPERATION, &pb_op); + - PR_ASSERT (pb_op); target_spec = operation_get_target_spec (pb_op); @@ -3774,8 +3774,8 @@ plugin_invoke_plugin_sdn (struct slapdplugin *plugin, int operation __attribute_ return PR_FALSE; } - Operation *pb_op; - slapi_pblock_get(pb, SLAPI_OPERATION, &pb_op); + Operation *pb_op; + slapi_pblock_get(pb, SLAPI_OPERATION, &pb_op); /* get configuration from the group plugin if necessary */ config = plugin_get_config (plugin); @@ -3788,7 +3788,7 @@ plugin_invoke_plugin_sdn (struct slapdplugin *plugin, int operation __attribute_ slapi_pblock_get (pb, SLAPI_IS_REPLICATED_OPERATION, &repl_op); if (repl_op) { return PR_FALSE; - } + } } if (pb_op) @@ -4484,11 +4484,11 @@ slapi_get_plugin_default_config(char *type, Slapi_ValueSet **valueset) /* retrieve attribute values from the entry */ Slapi_Attr *attr = NULL; rc = slapi_entry_attr_find(*entries, type, &attr); - if (0 == rc) { /* type value exists */ - rc = slapi_attr_get_valueset(attr, valueset); - } else { - rc = LDAP_NO_SUCH_ATTRIBUTE; - } + if (0 == rc) { /* type value exists */ + rc = slapi_attr_get_valueset(attr, valueset); + } else { + rc = LDAP_NO_SUCH_ATTRIBUTE; + } } slapi_free_search_results_internal(pb); slapi_pblock_destroy(pb); diff --git a/ldap/servers/slapd/plugin_internal_op.c b/ldap/servers/slapd/plugin_internal_op.c index c401918a4..0d18b5de2 100644 --- a/ldap/servers/slapd/plugin_internal_op.c +++ b/ldap/servers/slapd/plugin_internal_op.c @@ -201,23 +201,22 @@ slapi_seq_callback( const char *ibase, plugin_search_entry_callback srch_callback, plugin_referral_entry_callback ref_callback) { - int r; + int r; - if (ibase == NULL) - { - slapi_log_err(SLAPI_LOG_ERR, "slapi_seq_callback", - "NULL parameter\n"); - return -1; - } + if (ibase == NULL) { + slapi_log_err(SLAPI_LOG_ERR, "slapi_seq_callback", + "NULL parameter\n"); + return -1; + } Slapi_PBlock *pb = slapi_pblock_new(); - slapi_seq_internal_set_pb(pb, (char *)ibase, type, attrname, val, attrs, attrsonly, controls, - plugin_get_default_component_id(), 0); + slapi_seq_internal_set_pb(pb, (char *)ibase, type, attrname, val, attrs, attrsonly, controls, + plugin_get_default_component_id(), 0); r= seq_internal_callback_pb (pb, callback_data, res_callback, srch_callback, ref_callback); slapi_pblock_destroy(pb); - return r; + return r; } @@ -444,11 +443,11 @@ slapi_search_internal_callback(const char *ibase, Slapi_PBlock *pb = slapi_pblock_new(); int rc = 0; - slapi_search_internal_set_pb (pb, ibase, scope, ifstr, attrs, attrsonly, - controls, NULL, plugin_get_default_component_id(), 0); - - rc = search_internal_callback_pb (pb, callback_data, res_callback, - srch_callback, ref_callback); + slapi_search_internal_set_pb (pb, ibase, scope, ifstr, attrs, attrsonly, + controls, NULL, plugin_get_default_component_id(), 0); + + rc = search_internal_callback_pb (pb, callback_data, res_callback, + srch_callback, ref_callback); slapi_pblock_destroy(pb); return (rc); } @@ -461,19 +460,16 @@ slapi_search_internal(const char *base, char **attrs, int attrsonly) { - - Slapi_PBlock *pb; + Slapi_PBlock *pb; /* initialize pb */ pb = slapi_pblock_new(); - if (pb) - { - slapi_search_internal_set_pb (pb, base, scope, filter, attrs, attrsonly, controls, - NULL, plugin_get_default_component_id(), 0); - - search_internal_pb (pb); - } - + if (pb) + { + slapi_search_internal_set_pb (pb, base, scope, filter, attrs, attrsonly, controls, + NULL, plugin_get_default_component_id(), 0); + search_internal_pb (pb); + } return pb; } diff --git a/ldap/servers/slapd/plugin_syntax.c b/ldap/servers/slapd/plugin_syntax.c index f0d116750..b89e85c68 100644 --- a/ldap/servers/slapd/plugin_syntax.c +++ b/ldap/servers/slapd/plugin_syntax.c @@ -190,7 +190,7 @@ plugin_call_syntax_filter_ava_sv( slapi_log_err(SLAPI_LOG_FILTER, "plugin_call_syntax_filter_ava", "<= %d\n", rc); - slapi_pblock_destroy(pipb); + slapi_pblock_destroy(pipb); return( rc ); } @@ -263,9 +263,9 @@ plugin_call_syntax_filter_sub_sv( slapi_log_err(SLAPI_LOG_FILTER, "plugin_call_syntax_filter_sub_sv", "<= %d\n", rc); - /* Operation is owned by our caller: We need to null it now, to prevent the free */ - slapi_pblock_set( pipb, SLAPI_OPERATION, NULL ); - slapi_pblock_destroy(pipb); + /* Operation is owned by our caller: We need to null it now, to prevent the free */ + slapi_pblock_set( pipb, SLAPI_OPERATION, NULL ); + slapi_pblock_destroy(pipb); return( rc ); } @@ -798,7 +798,7 @@ slapi_attr_assertion2keys_ava_sv( if ( a2k_fn != NULL ) { rc = (*a2k_fn)( pipb, val, ivals, ftype ); } - slapi_pblock_destroy(pipb); + slapi_pblock_destroy(pipb); done: slapi_log_err(SLAPI_LOG_FILTER, "slapi_attr_assertion2keys_ava_sv", "=> %d\n", rc); @@ -866,7 +866,7 @@ slapi_call_syntax_assertion2keys_sub_sv( final, ivals ); } - slapi_pblock_destroy(pipb); + slapi_pblock_destroy(pipb); slapi_log_err(SLAPI_LOG_FILTER, "slapi_call_syntax_assertion2keys_sub_sv", "<= %d\n", rc); diff --git a/ldap/servers/slapd/psearch.c b/ldap/servers/slapd/psearch.c index 9b9393d7a..7398fd8f5 100644 --- a/ldap/servers/slapd/psearch.c +++ b/ldap/servers/slapd/psearch.c @@ -256,17 +256,17 @@ static void ps_send_results( void *arg ) { PSearch *ps = (PSearch *)arg; - PSEQNode *peq, *peqnext; - struct slapi_filter *filter = 0; - char *base = NULL; - Slapi_DN *sdn = NULL; - char *fstr = NULL; - char **pbattrs = NULL; - int conn_acq_flag = 0; - Slapi_Connection *conn = NULL; + PSEQNode *peq, *peqnext; + struct slapi_filter *filter = 0; + char *base = NULL; + Slapi_DN *sdn = NULL; + char *fstr = NULL; + char **pbattrs = NULL; + int conn_acq_flag = 0; + Slapi_Connection *conn = NULL; Connection *pb_conn = NULL; Operation *pb_op = NULL; - + g_incr_active_threadcnt(); slapi_pblock_get(ps->ps_pblock, SLAPI_CONNECTION, &pb_conn); @@ -278,87 +278,87 @@ ps_send_results( void *arg ) conn_acq_flag = connection_acquire_nolock(pb_conn); PR_ExitMonitor(pb_conn->c_mutex); - if (conn_acq_flag) { - slapi_log_err(SLAPI_LOG_CONNS, "ps_send_results", - "conn=%" PRIu64 " op=%d Could not acquire the connection - psearch aborted\n", - pb_conn->c_connid, pb_op->o_opid); - } + if (conn_acq_flag) { + slapi_log_err(SLAPI_LOG_CONNS, "ps_send_results", + "conn=%" PRIu64 " op=%d Could not acquire the connection - psearch aborted\n", + pb_conn->c_connid, pb_op->o_opid); + } PR_Lock( psearch_list->pl_cvarlock ); while ( (conn_acq_flag == 0) && !ps->ps_complete ) { - /* Check for an abandoned operation */ - if ( pb_op == NULL || slapi_op_abandoned( ps->ps_pblock ) ) { - slapi_log_err(SLAPI_LOG_CONNS, "ps_send_results", - "conn=%" PRIu64 " op=%d The operation has been abandoned\n", - pb_conn->c_connid, pb_op->o_opid); - break; - } - if ( NULL == ps->ps_eq_head ) { - /* Nothing to do */ - PR_WaitCondVar( psearch_list->pl_cvar, PR_INTERVAL_NO_TIMEOUT ); - } else { - /* dequeue the item */ - int attrsonly; - char **attrs; - LDAPControl **ectrls; - Slapi_Entry *ec; - Slapi_Filter *f = NULL; - - PR_Lock( ps->ps_lock ); - - peq = ps->ps_eq_head; - ps->ps_eq_head = peq->pe_next; - if ( NULL == ps->ps_eq_head ) { - ps->ps_eq_tail = NULL; - } - - PR_Unlock( ps->ps_lock ); - - /* Get all the information we need to send the result */ - ec = peq->pe_entry; - slapi_pblock_get( ps->ps_pblock, SLAPI_SEARCH_ATTRS, &attrs ); - slapi_pblock_get( ps->ps_pblock, SLAPI_SEARCH_ATTRSONLY, &attrsonly ); - if ( !ps->ps_send_entchg_controls || peq->pe_ctrls[0] == NULL ) { - ectrls = NULL; - } else { - ectrls = peq->pe_ctrls; - } - - /* - * Send the result. Since send_ldap_search_entry can block for - * up to 30 minutes, we relinquish all locks before calling it. - */ - PR_Unlock(psearch_list->pl_cvarlock); + /* Check for an abandoned operation */ + if ( pb_op == NULL || slapi_op_abandoned( ps->ps_pblock ) ) { + slapi_log_err(SLAPI_LOG_CONNS, "ps_send_results", + "conn=%" PRIu64 " op=%d The operation has been abandoned\n", + pb_conn->c_connid, pb_op->o_opid); + break; + } + if ( NULL == ps->ps_eq_head ) { + /* Nothing to do */ + PR_WaitCondVar( psearch_list->pl_cvar, PR_INTERVAL_NO_TIMEOUT ); + } else { + /* dequeue the item */ + int attrsonly; + char **attrs; + LDAPControl **ectrls; + Slapi_Entry *ec; + Slapi_Filter *f = NULL; + + PR_Lock( ps->ps_lock ); + + peq = ps->ps_eq_head; + ps->ps_eq_head = peq->pe_next; + if ( NULL == ps->ps_eq_head ) { + ps->ps_eq_tail = NULL; + } - /* - * The entry is in the right scope and matches the filter - * but we need to redo the filter test here to check access - * controls. See the comments at the slapi_filter_test() - * call in ps_service_persistent_searches(). - */ - slapi_pblock_get( ps->ps_pblock, SLAPI_SEARCH_FILTER, &f ); - - /* See if the entry meets the filter and ACL criteria */ - if ( slapi_vattr_filter_test( ps->ps_pblock, ec, f, - 1 /* verify_access */ ) == 0 ) { - int rc = 0; - slapi_pblock_set( ps->ps_pblock, SLAPI_SEARCH_RESULT_ENTRY, ec ); - rc = send_ldap_search_entry( ps->ps_pblock, ec, - ectrls, attrs, attrsonly ); - if (rc) { - slapi_log_err(SLAPI_LOG_CONNS, "ps_send_results", - "conn=%" PRIu64 " op=%d Error %d sending entry %s with op status %d\n", - pb_conn->c_connid, pb_op->o_opid, - rc, slapi_entry_get_dn_const(ec), pb_op->o_status); - } - } - - PR_Lock(psearch_list->pl_cvarlock); + PR_Unlock( ps->ps_lock ); - /* Deallocate our wrapper for this entry */ - pe_ch_free( &peq ); - } + /* Get all the information we need to send the result */ + ec = peq->pe_entry; + slapi_pblock_get( ps->ps_pblock, SLAPI_SEARCH_ATTRS, &attrs ); + slapi_pblock_get( ps->ps_pblock, SLAPI_SEARCH_ATTRSONLY, &attrsonly ); + if ( !ps->ps_send_entchg_controls || peq->pe_ctrls[0] == NULL ) { + ectrls = NULL; + } else { + ectrls = peq->pe_ctrls; + } + + /* + * Send the result. Since send_ldap_search_entry can block for + * up to 30 minutes, we relinquish all locks before calling it. + */ + PR_Unlock(psearch_list->pl_cvarlock); + + /* + * The entry is in the right scope and matches the filter + * but we need to redo the filter test here to check access + * controls. See the comments at the slapi_filter_test() + * call in ps_service_persistent_searches(). + */ + slapi_pblock_get( ps->ps_pblock, SLAPI_SEARCH_FILTER, &f ); + + /* See if the entry meets the filter and ACL criteria */ + if ( slapi_vattr_filter_test( ps->ps_pblock, ec, f, + 1 /* verify_access */ ) == 0 ) { + int rc = 0; + slapi_pblock_set( ps->ps_pblock, SLAPI_SEARCH_RESULT_ENTRY, ec ); + rc = send_ldap_search_entry( ps->ps_pblock, ec, + ectrls, attrs, attrsonly ); + if (rc) { + slapi_log_err(SLAPI_LOG_CONNS, "ps_send_results", + "conn=%" PRIu64 " op=%d Error %d sending entry %s with op status %d\n", + pb_conn->c_connid, pb_op->o_opid, + rc, slapi_entry_get_dn_const(ec), pb_op->o_status); + } + } + + PR_Lock(psearch_list->pl_cvarlock); + + /* Deallocate our wrapper for this entry */ + pe_ch_free( &peq ); + } } PR_Unlock( psearch_list->pl_cvarlock ); ps_remove( ps ); @@ -366,39 +366,39 @@ ps_send_results( void *arg ) /* indicate the end of search */ plugin_call_plugins( ps->ps_pblock , SLAPI_PLUGIN_POST_SEARCH_FN ); - /* free things from the pblock that were not free'd in do_search() */ - /* we strdup'd this in search.c - need to free */ - slapi_pblock_get( ps->ps_pblock, SLAPI_ORIGINAL_TARGET_DN, &base ); - slapi_pblock_set( ps->ps_pblock, SLAPI_ORIGINAL_TARGET_DN, NULL ); - slapi_ch_free_string(&base); + /* free things from the pblock that were not free'd in do_search() */ + /* we strdup'd this in search.c - need to free */ + slapi_pblock_get( ps->ps_pblock, SLAPI_ORIGINAL_TARGET_DN, &base ); + slapi_pblock_set( ps->ps_pblock, SLAPI_ORIGINAL_TARGET_DN, NULL ); + slapi_ch_free_string(&base); - /* Free SLAPI_SEARCH_* before deleting op since those are held by op */ - slapi_pblock_get( ps->ps_pblock, SLAPI_SEARCH_TARGET_SDN, &sdn ); - slapi_pblock_set( ps->ps_pblock, SLAPI_SEARCH_TARGET_SDN, NULL ); - slapi_sdn_free(&sdn); + /* Free SLAPI_SEARCH_* before deleting op since those are held by op */ + slapi_pblock_get( ps->ps_pblock, SLAPI_SEARCH_TARGET_SDN, &sdn ); + slapi_pblock_set( ps->ps_pblock, SLAPI_SEARCH_TARGET_SDN, NULL ); + slapi_sdn_free(&sdn); slapi_pblock_get( ps->ps_pblock, SLAPI_SEARCH_STRFILTER, &fstr ); slapi_pblock_set( ps->ps_pblock, SLAPI_SEARCH_STRFILTER, NULL ); - slapi_ch_free_string(&fstr); + slapi_ch_free_string(&fstr); slapi_pblock_get( ps->ps_pblock, SLAPI_SEARCH_ATTRS, &pbattrs ); slapi_pblock_set( ps->ps_pblock, SLAPI_SEARCH_ATTRS, NULL ); - if ( pbattrs != NULL ) - { - charray_free( pbattrs ); - } - - slapi_pblock_get(ps->ps_pblock, SLAPI_SEARCH_FILTER, &filter ); - slapi_pblock_set(ps->ps_pblock, SLAPI_SEARCH_FILTER, NULL ); - slapi_filter_free(filter, 1); + if ( pbattrs != NULL ) + { + charray_free( pbattrs ); + } + + slapi_pblock_get(ps->ps_pblock, SLAPI_SEARCH_FILTER, &filter ); + slapi_pblock_set(ps->ps_pblock, SLAPI_SEARCH_FILTER, NULL ); + slapi_filter_free(filter, 1); conn = pb_conn; /* save to release later - connection_remove_operation_ext will NULL the pb_conn */ /* Clean up the connection structure */ PR_EnterMonitor(conn->c_mutex); - slapi_log_err(SLAPI_LOG_CONNS, "ps_send_results", - "conn=%" PRIu64 " op=%d Releasing the connection and operation\n", - conn->c_connid, pb_op->o_opid); + slapi_log_err(SLAPI_LOG_CONNS, "ps_send_results", + "conn=%" PRIu64 " op=%d Releasing the connection and operation\n", + conn->c_connid, pb_op->o_opid); /* Delete this op from the connection's list */ connection_remove_operation_ext( ps->ps_pblock, conn, pb_op ); @@ -413,10 +413,10 @@ ps_send_results( void *arg ) ps->ps_lock = NULL; slapi_ch_free((void **) &ps->ps_pblock ); - for ( peq = ps->ps_eq_head; peq; peq = peqnext) { - peqnext = peq->pe_next; - pe_ch_free( &peq ); - } + for ( peq = ps->ps_eq_head; peq; peq = peqnext) { + peqnext = peq->pe_next; + pe_ch_free( &peq ); + } slapi_ch_free((void **) &ps ); g_decr_active_threadcnt(); } @@ -521,11 +521,11 @@ ps_service_persistent_searches( Slapi_Entry *e, Slapi_Entry *eprev, ber_int_t ch Slapi_DN *base = NULL; Slapi_Filter *f; int scope; - Connection *pb_conn = NULL; - Operation *pb_op = NULL; + Connection *pb_conn = NULL; + Operation *pb_op = NULL; - slapi_pblock_get(ps->ps_pblock, SLAPI_OPERATION, &pb_op); - slapi_pblock_get(ps->ps_pblock, SLAPI_CONNECTION, &pb_conn); + slapi_pblock_get(ps->ps_pblock, SLAPI_OPERATION, &pb_op); + slapi_pblock_get(ps->ps_pblock, SLAPI_CONNECTION, &pb_conn); /* Skip the node that doesn't meet the changetype, * or is unable to use the change in ps_send_results() diff --git a/ldap/servers/slapd/pw.c b/ldap/servers/slapd/pw.c index e6a148407..0ebc448b1 100644 --- a/ldap/servers/slapd/pw.c +++ b/ldap/servers/slapd/pw.c @@ -594,7 +594,7 @@ int update_pw_info ( Slapi_PBlock *pb , char *old_pw) { Slapi_Operation *operation = NULL; - Connection *pb_conn; + Connection *pb_conn; Slapi_Entry *e = NULL; Slapi_DN *sdn = NULL; Slapi_Mods smods; @@ -606,7 +606,7 @@ update_pw_info ( Slapi_PBlock *pb , char *old_pw) int internal_op = 0; slapi_pblock_get( pb, SLAPI_OPERATION, &operation); - slapi_pblock_get(pb, SLAPI_CONNECTION, &pb_conn); + slapi_pblock_get(pb, SLAPI_CONNECTION, &pb_conn); slapi_pblock_get( pb, SLAPI_TARGET_SDN, &sdn ); slapi_pblock_get( pb, SLAPI_REQUESTOR_NDN, &bind_dn); slapi_pblock_get( pb, SLAPI_ENTRY_PRE_OP, &e); @@ -734,11 +734,11 @@ check_pw_minage ( Slapi_PBlock *pb, const Slapi_DN *sdn, struct berval **vals __ char *dn= (char*)slapi_sdn_get_ndn(sdn); /* jcm - Had to cast away const */ passwdPolicy *pwpolicy=NULL; int pwresponse_req = 0; - Operation *pb_op; + Operation *pb_op; pwpolicy = new_passwdPolicy(pb, dn); slapi_pblock_get ( pb, SLAPI_PWPOLICY, &pwresponse_req ); - slapi_pblock_get(pb, SLAPI_OPERATION, &pb_op); + slapi_pblock_get(pb, SLAPI_OPERATION, &pb_op); if (!pb_op->o_isroot && pwpolicy->pw_minage) { @@ -759,7 +759,7 @@ check_pw_minage ( Slapi_PBlock *pb, const Slapi_DN *sdn, struct berval **vals __ char *cur_time_str = NULL; pw_allowchange_date = parse_genTime(passwordAllowChangeTime); - slapi_ch_free((void **) &passwordAllowChangeTime ); + slapi_ch_free((void **) &passwordAllowChangeTime ); /* check if allow to change the password */ cur_time_str = format_genTime ( current_time() ); @@ -777,7 +777,7 @@ check_pw_minage ( Slapi_PBlock *pb, const Slapi_DN *sdn, struct berval **vals __ } slapi_ch_free((void **) &cur_time_str ); } - slapi_entry_free( e ); + slapi_entry_free( e ); } return ( 0 ); } @@ -1237,7 +1237,7 @@ update_pw_history( Slapi_PBlock *pb, const Slapi_DN *sdn, char *old_pw ) list_of_mods[0] = &attribute; list_of_mods[1] = NULL; - mod_pb = slapi_pblock_new(); + mod_pb = slapi_pblock_new(); slapi_modify_internal_set_pb_ext(mod_pb, sdn, list_of_mods, NULL, NULL, pw_get_componentID(), 0); slapi_modify_internal_pb(mod_pb); slapi_pblock_get(mod_pb, SLAPI_PLUGIN_INTOP_RESULT, &res); @@ -1245,7 +1245,7 @@ update_pw_history( Slapi_PBlock *pb, const Slapi_DN *sdn, char *old_pw ) slapi_log_err(SLAPI_LOG_ERR, "update_pw_history", "Modify error %d on entry '%s'\n", res, dn); } - slapi_pblock_destroy(mod_pb); + slapi_pblock_destroy(mod_pb); slapi_ch_free_string(&str); bail: slapi_ch_array_free(values_replace); @@ -1678,12 +1678,12 @@ new_passwdPolicy(Slapi_PBlock *pb, const char *dn) int optype = -1; /* If we already allocated a pw policy, return it */ - if (pb != NULL) { - passwdPolicy *pwdpolicy = slapi_pblock_get_pwdpolicy(pb); - if (pwdpolicy != NULL) { - return pwdpolicy; - } - } + if (pb != NULL) { + passwdPolicy *pwdpolicy = slapi_pblock_get_pwdpolicy(pb); + if (pwdpolicy != NULL) { + return pwdpolicy; + } + } if (g_get_active_threadcnt() == 0){ /* @@ -2038,9 +2038,9 @@ done: pwdpolicy->pw_storagescheme = pwdscheme; pwdpolicy->pw_admin = slapi_sdn_dup(slapdFrontendConfig->pw_policy.pw_admin); pw_get_admin_users(pwdpolicy); - if (pb) { - slapi_pblock_set_pwdpolicy(pb, pwdpolicy); - } + if (pb) { + slapi_pblock_set_pwdpolicy(pb, pwdpolicy); + } return pwdpolicy; diff --git a/ldap/servers/slapd/pw_mgmt.c b/ldap/servers/slapd/pw_mgmt.c index 87073927c..a01afc5fa 100644 --- a/ldap/servers/slapd/pw_mgmt.c +++ b/ldap/servers/slapd/pw_mgmt.c @@ -37,7 +37,7 @@ need_new_pw( Slapi_PBlock *pb, long *t, Slapi_Entry *e, int pwresponse_req ) passwdPolicy *pwpolicy = NULL; int pwdGraceUserTime = 0; char graceUserTime[16] = {0}; - Connection *pb_conn = NULL; + Connection *pb_conn = NULL; if (NULL == e) { return (-1); @@ -87,7 +87,7 @@ need_new_pw( Slapi_PBlock *pb, long *t, Slapi_Entry *e, int pwresponse_req ) slapi_ch_free_string(&passwordExpirationTime); - slapi_pblock_get(pb, SLAPI_CONNECTION, &pb_conn); + slapi_pblock_get(pb, SLAPI_CONNECTION, &pb_conn); /* Check if password has been reset */ if ( pw_exp_date == NO_TIME ) { @@ -180,8 +180,8 @@ skip: create a pb for unbind operation. Also do_unbind calls pre and post ops. Maybe we don't want to call them */ if (pb_conn && (LDAP_VERSION2 == pb_conn->c_ldapversion)) { - Operation *pb_op = NULL; - slapi_pblock_get(pb, SLAPI_OPERATION, &pb_op); + Operation *pb_op = NULL; + slapi_pblock_get(pb, SLAPI_OPERATION, &pb_op); /* We close the connection only with LDAPv2 connections */ disconnect_server( pb_conn, pb_op->o_connid, pb_op->o_opid, SLAPD_DISCONNECT_UNBIND, 0); @@ -228,12 +228,10 @@ skip: if (pwresponse_req) { /* check for "changeafterreset" condition */ if (pb_conn->c_needpw == 1) { - slapi_pwpolicy_make_response_control( pb, *t, -1, - LDAP_PWPOLICY_CHGAFTERRESET); - } else { - slapi_pwpolicy_make_response_control( pb, *t, -1, - -1); - } + slapi_pwpolicy_make_response_control( pb, *t, -1, LDAP_PWPOLICY_CHGAFTERRESET); + } else { + slapi_pwpolicy_make_response_control( pb, *t, -1, -1); + } } if (pb_conn->c_needpw == 1) { diff --git a/ldap/servers/slapd/pw_retry.c b/ldap/servers/slapd/pw_retry.c index a54c78495..cb283bafe 100644 --- a/ldap/servers/slapd/pw_retry.c +++ b/ldap/servers/slapd/pw_retry.c @@ -230,7 +230,7 @@ pw_apply_mods(const Slapi_DN *sdn, Slapi_Mods *mods) if (mods && (slapi_mods_get_num_mods(mods) > 0)) { - Slapi_PBlock *pb = slapi_pblock_new(); + Slapi_PBlock *pb = slapi_pblock_new(); /* We don't want to overwrite the modifiersname, etc. attributes, * so we set a flag for this operation */ slapi_modify_internal_set_pb_ext (pb, sdn, @@ -248,7 +248,7 @@ pw_apply_mods(const Slapi_DN *sdn, Slapi_Mods *mods) res, slapi_sdn_get_dn(sdn)); } - slapi_pblock_destroy(pb); + slapi_pblock_destroy(pb); } return; diff --git a/ldap/servers/slapd/referral.c b/ldap/servers/slapd/referral.c index 2e0aea0f8..632dd1954 100644 --- a/ldap/servers/slapd/referral.c +++ b/ldap/servers/slapd/referral.c @@ -408,117 +408,114 @@ dn_is_below( const char *dn_norm, const char *ancestor_norm ) struct berval ** get_data_source(Slapi_PBlock *pb, const Slapi_DN *sdn, int orc, void *cfrp) { - int walker; - struct berval **bvp; - struct berval *bv; - int found_it; - Ref_Array *grefs = NULL; - Ref_Array *the_refs = NULL; - Ref_Array *cf_refs = (Ref_Array *)cfrp; - - /* If no Ref_Array is given, use global_referrals */ - if (cf_refs == NULL) { - grefs = g_get_global_referrals(); - the_refs = grefs; - GR_LOCK_READ(); - } else { - the_refs = cf_refs; - } - - /* optimization: if orc is 1 (a read), then check the readcount*/ - if (orc && the_refs->ra_readcount == 0) { + int walker; + struct berval **bvp; + struct berval *bv; + int found_it; + Ref_Array *grefs = NULL; + Ref_Array *the_refs = NULL; + Ref_Array *cf_refs = (Ref_Array *)cfrp; + + /* If no Ref_Array is given, use global_referrals */ if (cf_refs == NULL) { - GR_UNLOCK_READ(); + grefs = g_get_global_referrals(); + the_refs = grefs; + GR_LOCK_READ(); + } else { + the_refs = cf_refs; } - return (NULL); - } - - bvp = NULL; - bv = NULL; - found_it = 0; + /* optimization: if orc is 1 (a read), then check the readcount*/ + if (orc && the_refs->ra_readcount == 0) { + if (cf_refs == NULL) { + GR_UNLOCK_READ(); + } + return (NULL); + } - /* Walk down the array, testing each dn to make see if it's a parent of "dn" */ - for (walker = 0; walker < the_refs->ra_nextindex; walker++){ - if ( slapi_dn_issuffix(slapi_sdn_get_ndn(sdn), the_refs->ra_refs[walker]->ref_dn)) { - found_it = 1; - break; + bvp = NULL; + bv = NULL; + found_it = 0; + /* Walk down the array, testing each dn to make see if it's a parent of "dn" */ + for (walker = 0; walker < the_refs->ra_nextindex; walker++){ + if ( slapi_dn_issuffix(slapi_sdn_get_ndn(sdn), the_refs->ra_refs[walker]->ref_dn)) { + found_it = 1; + break; + } } - } - - /* no referral, so return NULL */ - if (!found_it) { - if (cf_refs == NULL) { - GR_UNLOCK_READ(); + /* no referral, so return NULL */ + if (!found_it) { + if (cf_refs == NULL) { + GR_UNLOCK_READ(); + } + return (NULL); } - return (NULL); - } - - /* - * Gotta make sure we're returning the right one. If orc is 1, then - * only return a read referral. if orc is 0, then only return a - * write referral. - */ - if (orc && the_refs->ra_refs[walker]->ref_reads != 1) { - if (cf_refs == NULL) { - GR_UNLOCK_READ(); + + /* + * Gotta make sure we're returning the right one. If orc is 1, then + * only return a read referral. if orc is 0, then only return a + * write referral. + */ + if (orc && the_refs->ra_refs[walker]->ref_reads != 1) { + if (cf_refs == NULL) { + GR_UNLOCK_READ(); + } + return (NULL); } - return (NULL); - } - if (!orc && the_refs->ra_refs[walker]->ref_writes != 1) { - if (cf_refs == NULL) { - GR_UNLOCK_READ(); + if (!orc && the_refs->ra_refs[walker]->ref_writes != 1) { + if (cf_refs == NULL) { + GR_UNLOCK_READ(); + } + return (NULL); } - return (NULL); - } Connection *pb_conn; slapi_pblock_get(pb, SLAPI_CONNECTION, &pb_conn); /* Fix for 310968 --- return an SSL referral to an SSL client */ - if ( 0 != ( pb_conn->c_flags & CONN_FLAG_SSL )) { - /* SSL connection */ - char * old_referral_string = NULL; - char * new_referral_string = NULL; - char *p = NULL; - /* Get the basic referral */ - bv = slapi_ch_bvdup(the_refs->ra_refs[walker]->ref_referral); - old_referral_string = bv->bv_val; - /* Re-write it to replace ldap with ldaps, and remove the port information */ - /* The original string will look like this: ldap://host:port */ - /* We need to make it look like this: ldaps://host */ - /* Potentially the ":port" part might be missing from the original */ - new_referral_string = slapi_ch_smprintf("%s%s" , LDAPS_URL_PREFIX, old_referral_string + strlen(LDAP_URL_PREFIX) ); - /* Go looking for the port */ - p = new_referral_string + (strlen(LDAPS_URL_PREFIX) + 1); - while (*p != '\0' && *p != ':') p++; - if (':' == *p) { - /* It had a port, zap it */ - *p = '\0'; - } - /* Fix the bv to point to this new string */ - bv->bv_val = new_referral_string; - /* Fix its length */ - bv->bv_len = strlen(bv->bv_val); - /* Free the copy we made of the original */ - slapi_ch_free((void**)&old_referral_string); - } else { - /* regular connection */ - bv = (struct berval *) slapi_ch_bvdup(the_refs->ra_refs[walker]->ref_referral); - } + if ( 0 != ( pb_conn->c_flags & CONN_FLAG_SSL )) { + /* SSL connection */ + char * old_referral_string = NULL; + char * new_referral_string = NULL; + char *p = NULL; + /* Get the basic referral */ + bv = slapi_ch_bvdup(the_refs->ra_refs[walker]->ref_referral); + old_referral_string = bv->bv_val; + /* Re-write it to replace ldap with ldaps, and remove the port information */ + /* The original string will look like this: ldap://host:port */ + /* We need to make it look like this: ldaps://host */ + /* Potentially the ":port" part might be missing from the original */ + new_referral_string = slapi_ch_smprintf("%s%s" , LDAPS_URL_PREFIX, old_referral_string + strlen(LDAP_URL_PREFIX) ); + /* Go looking for the port */ + p = new_referral_string + (strlen(LDAPS_URL_PREFIX) + 1); + while (*p != '\0' && *p != ':') p++; + if (':' == *p) { + /* It had a port, zap it */ + *p = '\0'; + } + /* Fix the bv to point to this new string */ + bv->bv_val = new_referral_string; + /* Fix its length */ + bv->bv_len = strlen(bv->bv_val); + /* Free the copy we made of the original */ + slapi_ch_free((void**)&old_referral_string); + } else { + /* regular connection */ + bv = (struct berval *) slapi_ch_bvdup(the_refs->ra_refs[walker]->ref_referral); + } - /* Package it up and send that puppy. */ - bvp = (struct berval **) slapi_ch_malloc( 2 * sizeof(struct berval *) ); - bvp[0] = bv; - bvp[1] = NULL; + /* Package it up and send that puppy. */ + bvp = (struct berval **) slapi_ch_malloc( 2 * sizeof(struct berval *) ); + bvp[0] = bv; + bvp[1] = NULL; - if (cf_refs == NULL) { - GR_UNLOCK_READ(); - } + if (cf_refs == NULL) { + GR_UNLOCK_READ(); + } - return(bvp); + return(bvp); } diff --git a/ldap/servers/slapd/result.c b/ldap/servers/slapd/result.c index 9c802a9bc..90b88871e 100644 --- a/ldap/servers/slapd/result.c +++ b/ldap/servers/slapd/result.c @@ -349,7 +349,7 @@ send_ldap_result_ext( slapi_pblock_get (pb, SLAPI_BIND_METHOD, &bind_method); slapi_pblock_get (pb, SLAPI_OPERATION, &operation); - slapi_pblock_get(pb, SLAPI_CONNECTION, &conn); + slapi_pblock_get(pb, SLAPI_CONNECTION, &conn); if (operation->o_status == SLAPI_OP_STATUS_RESULT_SENT) { return; /* result already sent */ @@ -817,11 +817,11 @@ send_ldapv3_referral( BerElement *ber; int i, rc, logit = 0; Slapi_Operation *operation; - Slapi_Backend *pb_backend; + Slapi_Backend *pb_backend; slapi_pblock_get (pb, SLAPI_OPERATION, &operation); - slapi_pblock_get(pb, SLAPI_CONNECTION, &conn); - slapi_pblock_get(pb, SLAPI_BACKEND, &pb_backend); + slapi_pblock_get(pb, SLAPI_CONNECTION, &conn); + slapi_pblock_get(pb, SLAPI_BACKEND, &pb_backend); slapi_log_err(SLAPI_LOG_TRACE, "send_ldapv3_referral", "=>\n"); @@ -909,7 +909,7 @@ send_ldap_referral ( char *refAttr = "ref"; char *attrs[2] = { NULL, NULL }; - Connection *pb_conn; + Connection *pb_conn; /* count the referral */ slapi_counter_increment(g_get_global_snmp_vars()->ops_tbl.dsReferrals); @@ -921,6 +921,8 @@ send_ldap_referral ( != LDAP_SUCCESS ) { return( 0 ); } + + slapi_pblock_get(pb, SLAPI_CONNECTION, &pb_conn); if ( pb_conn && pb_conn->c_ldapversion > LDAP_VERSION2 ) { /* * v3 connection - send the referral(s) in a @@ -1495,7 +1497,7 @@ send_ldap_search_entry_ext( LDAPControl **searchctrlp = NULL; - slapi_pblock_get(pb, SLAPI_CONNECTION, &conn); + slapi_pblock_get(pb, SLAPI_CONNECTION, &conn); slapi_pblock_get (pb, SLAPI_OPERATION, &operation); slapi_log_err(SLAPI_LOG_TRACE, "send_ldap_search_entry_ext", "=> (%s)\n", @@ -1522,8 +1524,8 @@ send_ldap_search_entry_ext( slapi_pblock_get(pb, SLAPI_SEARCH_CTRLS, &searchctrlp); if ( conn == NULL && e ) { - Slapi_Backend *pb_backend; - slapi_pblock_get(pb, SLAPI_BACKEND, &pb_backend); + Slapi_Backend *pb_backend; + slapi_pblock_get(pb, SLAPI_BACKEND, &pb_backend); if ( operation->o_search_entry_handler != NULL ) { if (( rc = (*operation->o_search_entry_handler)( @@ -1949,7 +1951,7 @@ log_result( Slapi_PBlock *pb, Operation *op, int err, ber_tag_t tag, int nentrie char etime[ETIME_BUFSIZ]; int pr_idx = -1; int pr_cookie = -1; - uint32_t operation_notes; + uint32_t operation_notes; slapi_pblock_get(pb, SLAPI_PAGED_RESULTS_INDEX, &pr_idx); slapi_pblock_get(pb, SLAPI_PAGED_RESULTS_COOKIE, &pr_cookie); @@ -1964,7 +1966,7 @@ log_result( Slapi_PBlock *pb, Operation *op, int err, ber_tag_t tag, int nentrie PR_snprintf(etime, ETIME_BUFSIZ, "%ld", current_time() - op->o_time); } - slapi_pblock_get(pb, SLAPI_OPERATION_NOTES, &operation_notes); + slapi_pblock_get(pb, SLAPI_OPERATION_NOTES, &operation_notes); if ( 0 == operation_notes ) { notes_str = ""; diff --git a/ldap/servers/slapd/search.c b/ldap/servers/slapd/search.c index 72b4664ab..7b2b46213 100644 --- a/ldap/servers/slapd/search.c +++ b/ldap/servers/slapd/search.c @@ -54,7 +54,7 @@ do_search( Slapi_PBlock *pb ) int strict = 0; int minssf_exclude_rootdse = 0; int filter_normalized = 0; - Connection *pb_conn = NULL; + Connection *pb_conn = NULL; slapi_log_err(SLAPI_LOG_TRACE, "do_search", "=>\n"); @@ -125,7 +125,7 @@ do_search( Slapi_PBlock *pb ) goto free_and_return; } - slapi_pblock_get(pb, SLAPI_CONNECTION, &pb_conn); + slapi_pblock_get(pb, SLAPI_CONNECTION, &pb_conn); /* * If nsslapd-minssf-exclude-rootdse is on, the minssf check has been
0
92613d99a0a80e6b53458c6f027ee1f20975bc38
389ds/389-ds-base
Bug 663191 - Don't use $USER in DSCreate.pm The $USER environment variable is used in the instance creation and removal code to determine what location to use for initconfig files. This will not work correctly if $USER is not set, or if one used su prior to running the installer. This patch uses DSUtil::getLogin instead, which gets the login name without using the $USER environment variable.
commit 92613d99a0a80e6b53458c6f027ee1f20975bc38 Author: Nathan Kinder <[email protected]> Date: Tue Dec 14 15:05:55 2010 -0800 Bug 663191 - Don't use $USER in DSCreate.pm The $USER environment variable is used in the instance creation and removal code to determine what location to use for initconfig files. This will not work correctly if $USER is not set, or if one used su prior to running the installer. This patch uses DSUtil::getLogin instead, which gets the login name without using the $USER environment variable. diff --git a/ldap/admin/src/scripts/DSCreate.pm.in b/ldap/admin/src/scripts/DSCreate.pm.in index d3c3f9d83..4e8840028 100644 --- a/ldap/admin/src/scripts/DSCreate.pm.in +++ b/ldap/admin/src/scripts/DSCreate.pm.in @@ -267,7 +267,7 @@ sub createInstanceScripts { # determine initconfig_dir my $initconfig_dir = $inf->{slapd}->{initconfig_dir}; if (!$initconfig_dir) { - if ($ENV{USER} eq 'root') { + if (getLogin eq 'root') { $initconfig_dir = "$inf->{General}->{prefix}@initconfigdir@"; } else { $initconfig_dir = "$ENV{HOME}/.@package_name@"; @@ -485,7 +485,7 @@ sub makeOtherConfigFiles { # determine initconfig_dir my $initconfig_dir = $inf->{slapd}->{initconfig_dir}; if (!$initconfig_dir) { - if ($ENV{USER} eq 'root') { + if (getLogin eq 'root') { $initconfig_dir = "$inf->{General}->{prefix}@initconfigdir@"; } else { $initconfig_dir = "$ENV{HOME}/.@package_name@"; @@ -1075,7 +1075,7 @@ sub removeDSInstance { # determine initconfig_dir if (!$initconfig_dir) { - if ($ENV{USER} eq 'root') { + if (getLogin eq 'root') { $initconfig_dir = "@initconfigdir@"; } else { $initconfig_dir = "$ENV{HOME}/.@package_name@";
0
881cade759eebaaea0cf24098adc8098f56e6bb5
389ds/389-ds-base
Issue 5156 - fix build breakage from slapi-memberof commit Description: Function prototypes were not declared correctly and this breaks the builds on new compilers. relates: #5156 Reviewed by: ?
commit 881cade759eebaaea0cf24098adc8098f56e6bb5 Author: Mark Reynolds <[email protected]> Date: Thu Apr 27 15:54:43 2023 -0400 Issue 5156 - fix build breakage from slapi-memberof commit Description: Function prototypes were not declared correctly and this breaks the builds on new compilers. relates: #5156 Reviewed by: ? diff --git a/ldap/servers/slapd/slapi-memberof.c b/ldap/servers/slapd/slapi-memberof.c index 3719f8e96..26fa977a9 100644 --- a/ldap/servers/slapd/slapi-memberof.c +++ b/ldap/servers/slapd/slapi-memberof.c @@ -83,7 +83,6 @@ static struct sm_cache_stat sm_cache_stat; static sm_memberof_cached_value *sm_ancestors_cache_lookup(Slapi_MemberOfConfig *config, const char *ndn); static PLHashEntry *sm_ancestors_cache_add(Slapi_MemberOfConfig *config, const void *key, void *value); static void sm_ancestor_hashtable_entry_free(sm_memberof_cached_value *entry); -static void sm_dump_cache_entry(sm_memberof_cached_value *double_check, const char *msg); static void sm_cache_ancestors(Slapi_MemberOfConfig *config, Slapi_Value **member_ndn_val, sm_memberof_get_groups_data *groups); static int sm_memberof_compare(Slapi_MemberOfConfig *config, const void *a, const void *b); static void sm_merge_ancestors(Slapi_Value **member_ndn_val, sm_memberof_get_groups_data *v1, sm_memberof_get_groups_data *v2); @@ -106,7 +105,7 @@ static PRIntn sm_ancestor_hashtable_remove(PLHashEntry *he, PRIntn index __attri static void sm_ancestor_hashtable_empty(Slapi_MemberOfConfig *config, char *msg); - +#if MEMBEROF_CACHE_DEBUG static void sm_dump_cache_entry(sm_memberof_cached_value *double_check, const char *msg) { @@ -117,6 +116,7 @@ sm_dump_cache_entry(sm_memberof_cached_value *double_check, const char *msg) double_check[i].nsuniqueid_val ? double_check[i].nsuniqueid_val : "NULL"); } } +#endif static sm_memberof_cached_value * sm_ancestors_cache_lookup(Slapi_MemberOfConfig *config, const char *ndn) @@ -937,8 +937,10 @@ sm_add_ancestors_cbdata(sm_memberof_cached_value *ancestors, void *callback_data } } } - slapi_log_err(SLAPI_LOG_ERR, "slapi_memberof", "sm_add_ancestors_cbdata: Ancestors of %s contained %d groups. %d added. %s\n", - slapi_value_get_string(memberdn_val), val_index, added_group, empty_ancestor ? "no ancestors" : ""); + slapi_log_err(SLAPI_LOG_ERR, "slapi_memberof", + "sm_add_ancestors_cbdata: Ancestors of %s contained %ld groups. %d added. %s\n", + slapi_value_get_string(memberdn_val), val_index, added_group, + empty_ancestor ? "no ancestors" : ""); } /* @@ -1294,4 +1296,4 @@ slapi_memberof(Slapi_MemberOfConfig *config, Slapi_DN *member_sdn, Slapi_MemberO result->nsuniqueid_vals = nsuniqueidvals; return rc; -} \ No newline at end of file +} diff --git a/ldap/servers/slapd/slapi-private.h b/ldap/servers/slapd/slapi-private.h index 8bfab623f..81618bfbc 100644 --- a/ldap/servers/slapd/slapi-private.h +++ b/ldap/servers/slapd/slapi-private.h @@ -1260,8 +1260,8 @@ void dup_ldif_line(struct berval *copy, const char *line, const char *endline); /* slapi-memberof.c */ int slapi_memberof(Slapi_MemberOfConfig *config, Slapi_DN *member_sdn, Slapi_MemberOfResult *result); -void slapi_memberof_free_memberof_plugin_config(); -int slapi_memberof_load_memberof_plugin_config(); +void slapi_memberof_free_memberof_plugin_config(void); +int slapi_memberof_load_memberof_plugin_config(void); /* lenstr stuff */
0
deeb34e1ab82bb3e6056fff1a0d90281638bc51c
389ds/389-ds-base
Ticket 47590: CI tests: add/split functions around replication Bug Description: Functions to setup replication are a bit too complex. They do a lot of things that should be split in several simpler functions. The parameters are also complex with mandatory/optional. Fix Description: The fix implements: - delSchema(attr, val) - getSchemaCSN(instance) - New class Agreement (in brooker) - status - schedule - create - init - checkProperties - _check_interval - reorganise routine from lib389 and brooker.replica to brooker.Agreement (init, status, create, schedule) - Creation of a default replica Mgr moved from lib389 to brooker.replica.create_repl_manager - Add a fix into instancebackupFS to backup changelog directory https://fedorahosted.org/389/ticket/47590 Reviewed by: Roberto Polli, Rich Megginson (Many thanks for all your Help Roberto and Rich) Flag Day: no Doc impact: no
commit deeb34e1ab82bb3e6056fff1a0d90281638bc51c Author: Thierry bordaz (tbordaz) <[email protected]> Date: Wed Nov 13 16:41:49 2013 +0100 Ticket 47590: CI tests: add/split functions around replication Bug Description: Functions to setup replication are a bit too complex. They do a lot of things that should be split in several simpler functions. The parameters are also complex with mandatory/optional. Fix Description: The fix implements: - delSchema(attr, val) - getSchemaCSN(instance) - New class Agreement (in brooker) - status - schedule - create - init - checkProperties - _check_interval - reorganise routine from lib389 and brooker.replica to brooker.Agreement (init, status, create, schedule) - Creation of a default replica Mgr moved from lib389 to brooker.replica.create_repl_manager - Add a fix into instancebackupFS to backup changelog directory https://fedorahosted.org/389/ticket/47590 Reviewed by: Roberto Polli, Rich Megginson (Many thanks for all your Help Roberto and Rich) Flag Day: no Doc impact: no diff --git a/src/lib389/bug_harness.py b/src/lib389/bug_harness.py index 1d523bc3c..621ef84c2 100644 --- a/src/lib389/bug_harness.py +++ b/src/lib389/bug_harness.py @@ -39,7 +39,7 @@ class DSAdminHarness(DSAdmin, DSAdminTools): args.setdefault('binddn', REPLBINDDN) args.setdefault('bindpw', REPLBINDPW) - return DSAdmin.setupAgreement(self, repoth, args) + return DSAdmin.createAgreement(self, repoth, args) def setupReplica(self, args): """Set default replia credentials """ diff --git a/src/lib389/lib389/__init__.py b/src/lib389/lib389/__init__.py index 2f980fff7..d034d07be 100644 --- a/src/lib389/lib389/__init__.py +++ b/src/lib389/lib389/__init__.py @@ -33,6 +33,7 @@ import operator import shutil import datetime import logging +import decimal from ldap.ldapobject import SimpleLDAPObject from ldapurl import LDAPUrl @@ -261,10 +262,12 @@ class DirSrv(SimpleLDAPObject): def __add_brookers__(self): from lib389.brooker import ( + Agreement, Replica, Backend, Config, Index) + self.agreement = Agreement(self) self.replica = Replica(self) self.backend = Backend(self) self.config = Config(self) @@ -886,16 +889,21 @@ class DirSrv(SimpleLDAPObject): def addSchema(self, attr, val): dn = "cn=schema" self.modify_s(dn, [(ldap.MOD_ADD, attr, val)]) + + def delSchema(self, attr, val): + dn = "cn=schema" + self.modify_s(dn, [(ldap.MOD_DELETE, attr, val)]) def addAttr(self, *attributes): return self.addSchema('attributeTypes', attributes) def addObjClass(self, *objectclasses): return self.addSchema('objectClasses', objectclasses) - - - - + + def getSchemaCSN(self): + ents = self.search_s("cn=schema", ldap.SCOPE_BASE, "objectclass=*", ['nsSchemaCSN']) + ent = ents[0] + return ent.getValue('nsSchemaCSN') def setupChainingIntermediate(self): confdn = ','.join(("cn=config", DN_CHAIN)) @@ -1044,7 +1052,7 @@ class DirSrv(SimpleLDAPObject): # args - DirSrv consumer (repoth), suffix, binddn, bindpw, timeout # also need an auto_init argument - def setupAgreement(self, consumer, args, cn_format=r'meTo_%s:%s', description_format=r'me to %s:%s'): + def createAgreement(self, consumer, args, cn_format=r'meTo_%s:%s', description_format=r'me to %s:%s'): """Create (and return) a replication agreement from self to consumer. - self is the supplier, - consumer is a DirSrv object (consumer can be a master) @@ -1056,9 +1064,7 @@ class DirSrv(SimpleLDAPObject): args = { 'suffix': "dc=example,dc=com", - 'bename': "userRoot", 'binddn': "cn=replrepl,cn=config", - 'bindcn': "replrepl", # so I need it? 'bindpw': "replrepl", 'bindmethod': 'simple', 'log' : True. @@ -1070,11 +1076,46 @@ class DirSrv(SimpleLDAPObject): 'o=suffix2': 'ldap://consumer.example.net:3890' } """ - assert args.get('binddn') and args.get('bindpw') suffix = args['suffix'] + if not suffix: + # This is a mandatory parameter of the command... it fails + log.warning("createAgreement: suffix is missing") + return None + + # get the RA binddn binddn = args.get('binddn') + if not binddn: + binddn = defaultProperties.get(REPLICATION_BIND_DN, None) + if not binddn: + # weird, internal error we do not retrieve the default replication bind DN + # this replica agreement will fail to update the consumer until the + # property will be set + log.warning("createAgreement: binddn not provided and default value unavailable") + pass + + + # get the RA binddn password bindpw = args.get('bindpw') - + if not bindpw: + bindpw = defaultProperties.get(REPLICATION_BIND_PW, None) + if not bindpw: + # weird, internal error we do not retrieve the default replication bind DN password + # this replica agreement will fail to update the consumer until the + # property will be set + log.warning("createAgreement: bindpw not provided and default value unavailable") + pass + + # get the RA bind method + bindmethod = args.get('bindmethod') + if not bindmethod: + bindmethod = defaultProperties.get(REPLICATION_BIND_METHOD, None) + if not bindmethod: + # weird, internal error we do not retrieve the default replication bind method + # this replica agreement will fail to update the consumer until the + # property will be set + log.warning("createAgreement: bindmethod not provided and default value unavailable") + pass + nsuffix = normalizeDN(suffix) othhost, othport, othsslport = ( consumer.host, consumer.port, consumer.sslport) @@ -1092,6 +1133,7 @@ class DirSrv(SimpleLDAPObject): 'dn': replent.dn, 'type': int(replent.nsds5replicatype) } + # define agreement entry cn = cn_format % (othhost, othport) dn_agreement = "cn=%s,%s" % (cn, self.suffixes[nsuffix]['dn']) @@ -1116,7 +1158,7 @@ class DirSrv(SimpleLDAPObject): 'nsds5replicatimeout': str(args.get('timeout', 120)), 'nsds5replicabinddn': binddn, 'nsds5replicacredentials': bindpw, - 'nsds5replicabindmethod': args.get('bindmethod', 'simple'), + 'nsds5replicabindmethod': bindmethod, 'nsds5replicaroot': nsuffix, 'nsds5replicaupdateschedule': '0000-2359 0123456', 'description': description_format % (othhost, othport) @@ -1201,6 +1243,71 @@ class DirSrv(SimpleLDAPObject): def startReplication(self, agmtdn): return self.replica.start_and_wait(agmtdn) + def enableReplication(self, suffix=None, role=None, replicaId=CONSUMER_REPLICAID, binddn=None): + if not suffix: + log.fatal("enableReplication: suffix not specified") + return 1 + + if not role: + log.fatal("enableReplication: replica role not specify (REPLICAROLE_*)") + return 1 + + # + # Check the validity of the parameters + # + + # First role and replicaID + if role == REPLICAROLE_MASTER: + # master + replica_type = REPLICA_RDWR_TYPE + else: + # hub or consumer + replica_type = REPLICA_RDONLY_TYPE + + if replica_type == REPLICA_RDWR_TYPE: + # check the replicaId [1..CONSUMER_REPLICAID[ + if not decimal.Decimal(replicaId) or (replicaId <= 0) or (replicaId >=CONSUMER_REPLICAID): + log.fatal("enableReplication: invalid replicaId (%s) for a RW replica" % replicaId) + return 1 + elif replicaId != CONSUMER_REPLICAID: + # check the replicaId is CONSUMER_REPLICAID + log.fatal("enableReplication: invalid replicaId (%s) for a Read replica (expected %d)" % (replicaId, CONSUMER_REPLICAID)) + return 1 + + # Now check we have a suffix + entries_backend = self.getBackendsForSuffix(suffix, ['nsslapd-suffix']) + if not entries_backend: + log.fatal("enableReplication: enable to retrieve the backend for %s" % suffix) + return 1 + + ent = entries_backend[0] + if normalizeDN(suffix) != normalizeDN(ent.getValue('nsslapd-suffix')): + log.warning("enableReplication: suffix (%s) and backend suffix (%s) differs" % (suffix, entries_backend[0].nsslapd-suffix)) + pass + + # Now prepare the bindDN property + if not binddn: + binddn = defaultProperties.get(REPLICATION_BIND_DN, None) + if not binddn: + # weird, internal error we do not retrieve the default replication bind DN + # this replica will not be updatable through replication until the binddn + # property will be set + log.warning("enableReplication: binddn not provided and default value unavailable") + pass + + # Now do the effectif job + # First add the changelog if master/hub + if (role == REPLICAROLE_MASTER) or (role == REPLICAROLE_HUB): + self.replica.changelog() + + # Second create the default replica manager entry if it does not exist + # it should not be called from here but for the moment I am unsure when to create it elsewhere + self.replica.create_repl_manager() + + # then enable replication + ret = self.replica.add(suffix=suffix, binddn=binddn, rtype=replica_type, rid=replicaId) + + return ret def replicaSetupAll(self, repArgs): """setup everything needed to enable replication for a given suffix. diff --git a/src/lib389/lib389/_constants.py b/src/lib389/lib389/_constants.py index 310358734..b0eb23ab4 100644 --- a/src/lib389/lib389/_constants.py +++ b/src/lib389/lib389/_constants.py @@ -5,11 +5,27 @@ (MASTER_TYPE, HUB_TYPE, LEAF_TYPE) = range(3) + +REPLICAROLE_MASTER = "master" +REPLICAROLE_HUB = "hub" +REPLICAROLE_CONSUMER = "consumer" + +CONSUMER_REPLICAID = 65535 REPLICA_RDONLY_TYPE = 2 # CONSUMER and HUB REPLICA_WRONLY_TYPE = 1 # SINGLE and MULTI MASTER REPLICA_RDWR_TYPE = REPLICA_RDONLY_TYPE | REPLICA_WRONLY_TYPE +REPLICATION_BIND_DN = 'replication_bind_dn' +REPLICATION_BIND_PW = 'replication_bind_pw' +REPLICATION_BIND_METHOD = 'replication_bind_method' + +defaultProperties = { + REPLICATION_BIND_DN: "cn=replrepl,cn=config", + REPLICATION_BIND_PW: "password", + REPLICATION_BIND_METHOD: "simple" +} + CFGSUFFIX = "o=NetscapeRoot" DEFAULT_USER = "nobody" diff --git a/src/lib389/lib389/brooker.py b/src/lib389/lib389/brooker.py index b3a1b6bca..fd8a8bde3 100644 --- a/src/lib389/lib389/brooker.py +++ b/src/lib389/lib389/brooker.py @@ -14,32 +14,412 @@ import time from lib389._constants import * -from lib389 import Entry, DirSrv +from lib389 import Entry, DirSrv, InvalidArgumentError from lib389.utils import normalizeDN, escapeDNValue, suffixfilt from lib389 import ( NoSuchEntryError ) -from lib389._constants import ( - DN_CHANGELOG, - DN_MAPPING_TREE, - DN_CHAIN, DN_LDBM, - MASTER_TYPE, - HUB_TYPE, - LEAF_TYPE, - REPLICA_RDONLY_TYPE, - REPLICA_RDWR_TYPE -) -from lib389._replication import RUV, CSN +from lib389._replication import RUV from lib389._entry import FormatDict +class Agreement(object): + ALWAYS = None + + proxied_methods = 'search_s getEntry'.split() + + def __init__(self, conn): + """@param conn - a DirSrv instance""" + self.conn = conn + self.log = conn.log + + def __getattr__(self, name): + if name in Agreement.proxied_methods: + return DirSrv.__getattr__(self.conn, name) + + + + def status(self, agreement_dn): + """Return a formatted string with the replica status. + @param agreement_dn - + """ + + attrlist = ['cn', 'nsds5BeginReplicaRefresh', 'nsds5replicaUpdateInProgress', + 'nsds5ReplicaLastInitStatus', 'nsds5ReplicaLastInitStart', + 'nsds5ReplicaLastInitEnd', 'nsds5replicaReapActive', + 'nsds5replicaLastUpdateStart', 'nsds5replicaLastUpdateEnd', + 'nsds5replicaChangesSentSinceStartup', 'nsds5replicaLastUpdateStatus', + 'nsds5replicaChangesSkippedSinceStartup', 'nsds5ReplicaHost', + 'nsds5ReplicaPort'] + try: + ent = self.conn.getEntry( + agreement_dn, ldap.SCOPE_BASE, "(objectclass=*)", attrlist) + except NoSuchEntryError: + raise NoSuchEntryError( + "Error reading status from agreement", agreement_dn) + else: + retstr = ( + "Status for %(cn)s agmt %(nsDS5ReplicaHost)s:%(nsDS5ReplicaPort)s" "\n" + "Update in progress: %(nsds5replicaUpdateInProgress)s" "\n" + "Last Update Start: %(nsds5replicaLastUpdateStart)s" "\n" + "Last Update End: %(nsds5replicaLastUpdateEnd)s" "\n" + "Num. Changes Sent: %(nsds5replicaChangesSentSinceStartup)s" "\n" + "Num. changes Skipped: %(nsds5replicaChangesSkippedSinceStartup)s" "\n" + "Last update Status: %(nsds5replicaLastUpdateStatus)s" "\n" + "Init in progress: %(nsds5BeginReplicaRefresh)s" "\n" + "Last Init Start: %(nsds5ReplicaLastInitStart)s" "\n" + "Last Init End: %(nsds5ReplicaLastInitEnd)s" "\n" + "Last Init Status: %(nsds5ReplicaLastInitStatus)s" "\n" + "Reap Active: %(nsds5ReplicaReapActive)s" "\n" + ) + # FormatDict manages missing fields in string formatting + return retstr % FormatDict(ent.data) + + def _check_interval(self, interval): + ''' + Check the interval for schedule replication is valid: + HH [0..23] + MM [0..59] + DAYS [0-6]{1,7} + + @param interval - interval in the format 'HHMM-HHMM D+' (D is day number [0-6]) + + @raise ValueError - if the inteval is illegal + ''' + c = re.compile(re.compile('^([0-9][0-9])([0-9][0-9])-([0-9][0-9])([0-9][0-9]) ([0-6]{1,7})$')) + if not c.match(interval): + raise ValueError("Bad schedule format %r" % interval) + + # check the hours + hour = int(c.group(1)) + if ((hour < 0) or (hour > 23)): + raise ValueError("Bad schedule format %r: illegal hour %d" % (interval, hour)) + hour = int(c.group(3)) + if ((hour < 0) or (hour > 23)): + raise ValueError("Bad schedule format %r: illegal hour %d" % (interval, hour)) + + # check the minutes + minute = int(c.group(2)) + if ((hour < 0) or (hour > 59)): + raise ValueError("Bad schedule format %r: illegal minute %d" % (interval, minute)) + minute = int(c.group(4)) + if ((hour < 0) or (hour > 59)): + raise ValueError("Bad schedule format %r: illegal minute %d" % (interval, minute)) + + + + + def schedule(self, agmtdn, interval='start'): + """Schedule the replication agreement + @param agmtdn - DN of the replica agreement + @param interval - in the form + - 'ALWAYS' + - 'NEVER' + - or 'HHMM-HHMM D+' With D=[0123456]+ + @raise ValueError - if interval is not valid + """ + + # check the validity of the interval + if str(interval).lower() == 'start': + interval = '0000-2359 0123456' + elif str(interval).lower == 'never': + interval = '2358-2359 0' + else: + self._check_interval(interval) + + # Check if the replica agreement exists + try: + self.conn.getEntry(agmtdn, ldap.SCOPE_BASE) + except ldap.NO_SUCH_OBJECT: + raise + + # update it + self.log.info("Schedule replication agreement %s" % agmtdn) + mod = [( + ldap.MOD_REPLACE, 'nsds5replicaupdateschedule', [interval])] + self.conn.modify_s(agmtdn, mod) + + def checkProperties(self, entry, properties): + ''' + Checks that properties defined in prop are valid and set the + replica agreement entry with the corresponding RHDS attribute name + @param entry - is the replica agreement LDAP entry + @param properties - is the dict of <prop_name>:<value> + 'schedule' -> 'nsds5replicaupdateschedule' + 'transport-info' -> 'nsds5replicatransportinfo' + 'fractional-exclude-attrs-inc' -> 'nsDS5ReplicatedAttributeList' + 'fractional-exclude-attrs-total' -> 'nsDS5ReplicatedAttributeListTotal' + 'fractional-strip-attrs' -> 'nsds5ReplicaStripAttrs' + 'transport-prot' -> 'nsds5replicatransportinfo' [ 'LDAP' ] + 'consumer-port' -> 'nsds5replicaport' [ 389 ] + 'consumer-total-init' -> 'nsds5BeginReplicaRefresh' + + @raise ValueError - if some properties are not valid + + + ''' + + # + # Schedule replication + # + if 'schedule' in properties: + self._check_interval(properties['schedule']) + entry.update({'nsds5replicaupdateschedule': properties['schedule']}) + if 'consumer-total-init' in properties: + entry.setValues('nsds5BeginReplicaRefresh', properties['consumer-total-init']) + + # + # Fractional replication properties + # + if 'fractional-exclude-attrs-inc' in properties: + entry.setValues('nsDS5ReplicatedAttributeList', properties['fractional-exclude-attrs-inc']) + if 'fractional-exclude-attrs-total' in properties: + entry.setValues('nsDS5ReplicatedAttributeListTotal', properties['fractional-exclude-attrs-total']) + if 'fractional-strip-attrs' in properties: + entry.setValues('nsds5ReplicaStripAttrs', properties['fractional-strip-attrs']) + + # + # Network parameter + if 'transport-prot' in properties: + entry.setValues('nsds5replicatransportinfo', properties['transport-prot']) + else: + entry.setValues('nsds5replicatransportinfo', 'LDAP') + + if 'consumer-port' in properties: + entry.setValues('nsds5replicaport', properties['consumer-port']) + else: + entry.setValues('nsds5replicaport', 389) + + + + def create(self, consumer, suffix=None, binddn=None, bindpw=None, cn_format=r'meTo_$host:$port', description_format=r'me to $host:$port', timeout=120, auto_init=False, bindmethod='simple', starttls=False, args=None): + """Create (and return) a replication agreement from self to consumer. + - self is the supplier, + + @param consumer: one of the following (consumer can be a master) + * a DirSrv object if chaining + * an object with attributes: host, port, sslport, __str__ + @param suffix - eg. 'dc=babel,dc=it' + @param binddn - + @param bindpw - + @param cn_format - string.Template to format the agreement name + @param timeout - replica timeout in seconds + @param auto_init - start replication immediately + @param bindmethod- 'simple' + @param starttls - True or False + @param args - further args dict. Allowed keys: + 'schedule', + 'fractional-exclude-attrs-inc', + 'fractional-exclude-attrs-total', + 'fractional-strip-attrs' + 'winsync' + + @return dn_agreement - DN of the created agreement + + @raise InvalidArgumentError - If the suffix is missing + @raise NosuchEntryError - if a replica doesn't exist for that suffix + @raise ALREADY_EXISTS - If the replica agreement already exists + @raise UNWILLING_TO_PERFORM if the database was previously + in read-only state. To create new agreements you + need to *restart* the directory server + + NOTE: this method doesn't cache connection entries + + TODO: test winsync + TODO: test chain + + """ + import string + + # Check we have a suffix [ mandatory ] + if not suffix: + self.log.warning("create: suffix is missing") + raise InvalidArgumentError('suffix is mandatory') + + # Check we have a bindDN [optional] can be set later + try: + binddn = binddn or defaultProperties[REPLICATION_BIND_DN] + if not binddn: + raise KeyError + except KeyError: + self.log.warning("create: bind DN not specified") + pass + + # Check we have a bindDN [optional] can be set later + try: + bindpw = bindpw or defaultProperties[REPLICATION_BIND_PW] + if not bindpw: + raise KeyError + except KeyError: + self.log.warning("create: %s password not specified" % (binddn)) + pass + + # Set the connection info HOST:PORT + othhost, othport, othsslport = ( + consumer.host, consumer.port, consumer.sslport) + othport = othsslport or othport + othport = othport or 389 + + # Compute the normalized suffix to be set in RA entry + nsuffix = normalizeDN(suffix) + + # adding agreement under the replica entry + replica_entries = self.conn.replica.list(suffix) + if not replica_entries: + raise NoSuchEntryError( + "Error: no replica set up for suffix " + suffix) + replica = replica_entries[0] + + # define agreement entry + cn = string.Template(cn_format).substitute({'host': othhost, 'port': othport}) + dn_agreement = ','.join(["cn=%s" % cn, replica.dn]) + + # This is probably unnecessary because + # we can just raise ALREADY_EXISTS + try: + + entry = self.conn.getEntry(dn_agreement, ldap.SCOPE_BASE) + self.log.warn("Agreement exists: %r" % dn_agreement) + raise ldap.ALREADY_EXISTS + except ldap.NO_SUCH_OBJECT: + entry = None + + # In a separate function in this scope? + entry = Entry(dn_agreement) + entry.update({ + 'objectclass': ["top", "nsds5replicationagreement"], + 'cn': cn, + 'nsds5replicahost': consumer.host, + 'nsds5replicatimeout': str(timeout), + 'nsds5replicabinddn': binddn, + 'nsds5replicacredentials': bindpw, + 'nsds5replicabindmethod': bindmethod, + 'nsds5replicaroot': nsuffix, + 'description': string.Template(description_format).substitute({'host': othhost, 'port': othport}) + }) + + # prepare the properties to set in the agreement + args = args or {} + if 'transport-info' not in args : + if starttls: + args['transport-info'] = 'TLS' + elif othsslport: + args['transport-info'] = 'SSL' + else: + args['transport-info'] = 'LDAP' + if 'consumer-port' not in args: + if starttls: + args['consumer-port'] = str(othport) + elif othsslport: + args['consumer-port'] = str(othsslport) + elif othport: + args['consumer-port'] = str(othport) + else: + args['consumer-port'] = '389' + if 'consumer-total-init' not in args: + if auto_init: + args['consumer-total-init'] = 'start' + + # now check and set the properties in the entry + self.checkProperties(entry, args) + + + # further arguments + if 'winsync' in args: # state it clearly! + self.conn.setupWinSyncAgmt(args, entry) + + try: + self.log.debug("Adding replica agreement: [%s]" % entry) + self.conn.add_s(entry) + except: + # FIXME check please! + raise + + entry = self.conn.waitForEntry(dn_agreement) + if entry: + # More verbose but shows what's going on + if 'chain' in args: + chain_args = { + 'suffix': suffix, + 'binddn': binddn, + 'bindpw': bindpw + } + # Work on `self` aka producer + if replica.nsds5replicatype == MASTER_TYPE: + self.setupChainingFarm(**chain_args) + # Work on `consumer` + # TODO - is it really required? + if replica.nsds5replicatype == LEAF_TYPE: + chain_args.update({ + 'isIntermediate': 0, + 'urls': self.conn.toLDAPURL(), + 'args': args['chainargs'] + }) + consumer.setupConsumerChainOnUpdate(**chain_args) + elif replica.nsds5replicatype == HUB_TYPE: + chain_args.update({ + 'isIntermediate': 1, + 'urls': self.conn.toLDAPURL(), + 'args': args['chainargs'] + }) + consumer.setupConsumerChainOnUpdate(**chain_args) + + return dn_agreement + def init(self, suffix=None, consumer_host=None, consumer_port=None): + """Trigger a total update of the consumer replica + - self is the supplier, + - consumer is a DirSrv object (consumer can be a master) + - cn_format - use this string to format the agreement name + @param - suffix is the suffix targeted by the total update [mandatory] + @param - consumer_host hostname of the consumer [mandatory] + @param - consumer_port port of the consumer [mandatory] + + @raise InvalidArgument: if missing mandatory argurment (suffix/host/port) + """ + # + # check the required parameters are set + # + if not suffix: + self.log.fatal("initAgreement: suffix is missing") + raise InvalidArgumentError('suffix is mandatory argument') + + nsuffix = normalizeDN(suffix) + + if not consumer_host: + self.log.fatal("initAgreement: host is missing") + raise InvalidArgumentError('host is mandatory argument') + + if not consumer_port: + self.log.fatal("initAgreement: port is missing") + raise InvalidArgumentError('port is mandatory argument') + # + # check the replica agreement already exist + # + replica_entries = self.conn.replica.list(suffix) + if not replica_entries: + raise NoSuchEntryError( + "Error: no replica set up for suffix " + suffix) + replica_entry = replica_entries[0] + self.log.debug("initAgreement: looking for replica agreements under %s" % replica_entry.dn) + try: + filt = "(&(objectclass=nsds5replicationagreement)(nsds5replicahost=%s)(nsds5replicaport=%d)(nsds5replicaroot=%s))" % (consumer_host, consumer_port, nsuffix) + entry = self.conn.getEntry(replica_entry.dn, ldap.SCOPE_ONELEVEL, filt) + except ldap.NO_SUCH_OBJECT: + self.log.fatal("initAgreement: No replica agreement to %s:%d for suffix %s" % (consumer_host, consumer_port, nsuffix)) + raise + + # + # trigger the total init + # + self.log.info("Starting total init %s" % entry.dn) + mod = [(ldap.MOD_ADD, 'nsds5BeginReplicaRefresh', 'start')] + self.conn.modify_s(entry.dn, mod) + + class Replica(object): proxied_methods = 'search_s getEntry'.split() - STOP = '2358-2359 0' - START = '0000-2359 0123456' - ALWAYS = None def __init__(self, conn): """@param conn - a DirSrv instance""" @@ -54,6 +434,49 @@ class Replica(object): """Return the replica dn of the given suffix.""" mtent = self.conn.getMTEntry(suffix) return ','.join(("cn=replica", mtent.dn)) + + def create_repl_manager(self, repl_manager_dn=None, repl_manager_pw=None): + ''' + Create an entry that will be used to bind as replica manager. + + @param repl_manager_dn - DN of the bind entry. If not provided use the default one + @param repl_manager_pw - Password of the entry. If not provide use the default one + + @raise - KeyError if can not find valid values of Bind DN and Pwd + ''' + + # check the DN and PW + try: + repl_manager_dn = repl_manager_dn or defaultProperties[REPLICATION_BIND_DN] + repl_manager_pw = repl_manager_pw or defaultProperties[REPLICATION_BIND_PW] + if not repl_manager_dn or not repl_manager_pw: + raise KeyError + except KeyError: + if not repl_manager_pw: + self.log.warning("replica_createReplMgr: bind DN password not specified") + if not repl_manager_dn: + self.log.warning("replica_createReplMgr: bind DN not specified") + raise + + # if the replication manager entry already exists, ust return + try: + entries = self.search_s(repl_manager_dn, ldap.SCOPE_BASE, "objectclass=*") + if entries: + #it already exist, fine + return + except ldap.NO_SUCH_OBJECT: + pass + + # ok it does not exist, create it + try: + attrs = { + 'nsIdleTimeout': '0', + 'passwordExpirationTime': '20381010000000Z' + } + self.conn.setupBindDN(repl_manager_dn, repl_manager_pw, attrs) + except ldap.ALREADY_EXISTS: + self.log.warn("User already exists (weird we just checked: %s " % repl_manager_dn) + def changelog(self, dbname='changelogdb'): """Add and return the replication changelog entry. @@ -155,26 +578,6 @@ class Replica(object): mod = [(ldap.MOD_ADD, 'nsds5BeginReplicaRefresh', 'start')] self.conn.modify_s(agmtdn, mod) - def stop(self, agmtdn): - """Stop replication. - @param agmtdn - agreement dn - """ - self.log.info("Stopping replication %s" % agmtdn) - mod = [( - ldap.MOD_REPLACE, 'nsds5replicaupdateschedule', [Replica.STOP])] - self.conn.modify_s(agmtdn, mod) - - def restart(self, agmtdn, schedule=START): - """Schedules a new replication. - @param agmtdn - - @param schedule - default START - `schedule` allows to customize the replication instant. - see 389 documentation for further info - """ - self.log.info("Restarting replication %s" % agmtdn) - mod = [(ldap.MOD_REPLACE, 'nsds5replicaupdateschedule', [ - schedule])] - self.modify_s(agmtdn, mod) def keep_in_sync(self, agmtdn): """ @@ -183,50 +586,16 @@ class Replica(object): self.log.info("Setting agreement for continuous replication") raise NotImplementedError("Check nsds5replicaupdateschedule before writing!") - def status(self, agreement_dn): - """Return a formatted string with the replica status. - @param agreement_dn - - """ - attrlist = ['cn', 'nsds5BeginReplicaRefresh', 'nsds5replicaUpdateInProgress', - 'nsds5ReplicaLastInitStatus', 'nsds5ReplicaLastInitStart', - 'nsds5ReplicaLastInitEnd', 'nsds5replicaReapActive', - 'nsds5replicaLastUpdateStart', 'nsds5replicaLastUpdateEnd', - 'nsds5replicaChangesSentSinceStartup', 'nsds5replicaLastUpdateStatus', - 'nsds5replicaChangesSkippedSinceStartup', 'nsds5ReplicaHost', - 'nsds5ReplicaPort'] - try: - ent = self.conn.getEntry( - agreement_dn, ldap.SCOPE_BASE, "(objectclass=*)", attrlist) - except NoSuchEntryError: - raise NoSuchEntryError( - "Error reading status from agreement", agreement_dn) - else: - retstr = ( - "Status for %(cn)s agmt %(nsDS5ReplicaHost)s:%(nsDS5ReplicaPort)s" "\n" - "Update in progress: %(nsds5replicaUpdateInProgress)s" "\n" - "Last Update Start: %(nsds5replicaLastUpdateStart)s" "\n" - "Last Update End: %(nsds5replicaLastUpdateEnd)s" "\n" - "Num. Changes Sent: %(nsds5replicaChangesSentSinceStartup)s" "\n" - "Num. changes Skipped: %(nsds5replicaChangesSkippedSinceStartup)s" "\n" - "Last update Status: %(nsds5replicaLastUpdateStatus)s" "\n" - "Init in progress: %(nsds5BeginReplicaRefresh)s" "\n" - "Last Init Start: %(nsds5ReplicaLastInitStart)s" "\n" - "Last Init End: %(nsds5ReplicaLastInitEnd)s" "\n" - "Last Init Status: %(nsds5ReplicaLastInitStatus)s" "\n" - "Reap Active: %(nsds5ReplicaReapActive)s" "\n" - ) - # FormatDict manages missing fields in string formatting - return retstr % FormatDict(ent.data) - def add(self, suffix, binddn, bindpw, rtype=MASTER_TYPE, rid=None, tombstone_purgedelay=None, purgedelay=None, referrals=None, legacy=False): + def add(self, suffix, binddn, bindpw=None, rtype=REPLICA_RDONLY_TYPE, rid=None, tombstone_purgedelay=None, purgedelay=None, referrals=None, legacy=False): """Setup a replica entry on an existing suffix. @param suffix - dn of suffix @param binddn - the replication bind dn for this replica can also be a list ["cn=r1,cn=config","cn=r2,cn=config"] @param bindpw - used to eventually provision the replication entry - @param rtype - master, hub, leaf (see above for values) - default is master + @param rtype - REPLICA_RDWR_TYPE (master) or REPLICA_RDONLY_TYPE (hub/consumer) @param rid - replica id or - if not given - an internal sequence number will be assigned # further args @@ -244,10 +613,6 @@ class Replica(object): TODO: this method does not update replica type """ # set default values - if rtype == MASTER_TYPE: - rtype = REPLICA_RDWR_TYPE - else: - rtype = REPLICA_RDONLY_TYPE if legacy: legacy = 'on' @@ -351,143 +716,10 @@ class Replica(object): return [ent.dn for ent in ents] return ents - def agreement_add(self, consumer, suffix=None, binddn=None, bindpw=None, cn_format=r'meTo_$host:$port', description_format=r'me to $host:$port', timeout=120, auto_init=False, bindmethod='simple', starttls=False, schedule=ALWAYS, args=None): - """Create (and return) a replication agreement from self to consumer. - - self is the supplier, - - @param consumer: one of the following (consumer can be a master) - * a DirSrv object if chaining - * an object with attributes: host, port, sslport, __str__ - @param suffix - eg. 'dc=babel,dc=it' - @param binddn - - @param bindpw - - @param cn_format - string.Template to format the agreement name - @param timeout - replica timeout in seconds - @param auto_init - start replication immediately - @param bindmethod- 'simple' - @param starttls - True or False - @param schedule - when to schedule the replication. default: ALWAYS - @param args - further args dict. Allowed keys: - 'fractional', - 'stripattrs', - 'winsync' - - @raise NosuchEntryError - if a replica doesn't exist for that suffix - @raise ALREADY_EXISTS - @raise UNWILLING_TO_PERFORM if the database was previously - in read-only state. To create new agreements you - need to *restart* the directory server - - NOTE: this method doesn't cache connection entries - - TODO: test winsync - TODO: test chain - - """ - import string - assert binddn and bindpw and suffix - args = args or {} - - othhost, othport, othsslport = ( - consumer.host, consumer.port, consumer.sslport) - othport = othsslport or othport - nsuffix = normalizeDN(suffix) - - # adding agreement to previously created replica - replica_entries = self.list(suffix) - if not replica_entries: - raise NoSuchEntryError( - "Error: no replica set up for suffix " + suffix) - replica = replica_entries[0] - - # define agreement entry - cn = string.Template(cn_format).substitute({'host': othhost, 'port': othport}) - dn_agreement = ','.join(["cn=%s" % cn, replica.dn]) - # This is probably unnecessary because - # we can just raise ALREADY_EXISTS - try: - entry = self.conn.getEntry(dn_agreement, ldap.SCOPE_BASE) - self.log.warn("Agreement exists: %r" % dn_agreement) - raise ldap.ALREADY_EXISTS - except ldap.NO_SUCH_OBJECT: - entry = None - - # In a separate function in this scope? - entry = Entry(dn_agreement) - entry.update({ - 'objectclass': ["top", "nsds5replicationagreement"], - 'cn': cn, - 'nsds5replicahost': consumer.host, - 'nsds5replicatimeout': str(timeout), - 'nsds5replicabinddn': binddn, - 'nsds5replicacredentials': bindpw, - 'nsds5replicabindmethod': bindmethod, - 'nsds5replicaroot': nsuffix, - 'description': string.Template(description_format).substitute({'host': othhost, 'port': othport}) - }) - if schedule: - if not re.match(r'\d{4}-\d{4} [0-6]{1,7}', schedule): # TODO put the regexp in a separate variable - raise ValueError("Bad schedule format %r" % schedule) - entry.update({'nsds5replicaupdateschedule': schedule}) - if starttls: - entry.setValues('nsds5replicatransportinfo', 'TLS') - entry.setValues('nsds5replicaport', str(othport)) - elif othsslport: - entry.setValues('nsds5replicatransportinfo', 'SSL') - entry.setValues('nsds5replicaport', str(othsslport)) - else: - entry.setValues('nsds5replicatransportinfo', 'LDAP') - entry.setValues('nsds5replicaport', str(othport)) - - if auto_init: - entry.setValues('nsds5BeginReplicaRefresh', 'start') - - # further arguments - if 'fractional' in args: - entry.setValues('nsDS5ReplicatedAttributeList', args['fractional']) - if 'stripattrs' in args: - entry.setValues('nsds5ReplicaStripAttrs', args['stripattrs']) - if 'winsync' in args: # state it clearly! - self.conn.setupWinSyncAgmt(args, entry) - - try: - self.log.debug("Adding replica agreement: [%s]" % entry) - self.conn.add_s(entry) - except: - # FIXME check please! - raise - - entry = self.conn.waitForEntry(dn_agreement) - if entry: - # More verbose but shows what's going on - if 'chain' in args: - chain_args = { - 'suffix': suffix, - 'binddn': binddn, - 'bindpw': bindpw - } - # Work on `self` aka producer - if replica.nsds5replicatype == MASTER_TYPE: - self.setupChainingFarm(**chain_args) - # Work on `consumer` - # TODO - is it really required? - if replica.nsds5replicatype == LEAF_TYPE: - chain_args.update({ - 'isIntermediate': 0, - 'urls': self.conn.toLDAPURL(), - 'args': args['chainargs'] - }) - consumer.setupConsumerChainOnUpdate(**chain_args) - elif replica.nsds5replicatype == HUB_TYPE: - chain_args.update({ - 'isIntermediate': 1, - 'urls': self.conn.toLDAPURL(), - 'args': args['chainargs'] - }) - consumer.setupConsumerChainOnUpdate(**chain_args) + + - return dn_agreement def agreement_changes(self, agmtdn): """Return a list of changes sent by this agreement.""" diff --git a/src/lib389/lib389/tools.py b/src/lib389/lib389/tools.py index b2f4cba47..3fef1e459 100644 --- a/src/lib389/lib389/tools.py +++ b/src/lib389/lib389/tools.py @@ -322,7 +322,8 @@ class DirSrvTools(object): dirsrv.sroot : root of the instance (e.g. /usr/lib64/dirsrv) dirsrv.inst : instance name (e.g. standalone for /etc/dirsrv/slapd-standalone) dirsrv.confdir : root of the instance config (e.g. /etc/dirsrv) - dirsrv.dbdir: directory where is stored the database (e.g. /var/lib/dirsrv/slapd-standalon/db + dirsrv.dbdir: directory where is stored the database (e.g. /var/lib/dirsrv/slapd-standalone/db) + dirsrv.changelogdir: directory where is stored the changelog (e.g. /var/lib/dirsrv/slapd-master/changelogdb) """ # First check it if already exists a backup file @@ -340,8 +341,18 @@ class DirSrvTools(object): os.chdir(dirsrv.prefix) prefix_pattern = "%s/" % dirsrv.prefix + # build the list of directories to scan instroot = "%s/slapd-%s" % (dirsrv.sroot, dirsrv.inst) - for dirToBackup in [ instroot, dirsrv.confdir, dirsrv.dbdir]: + ldir = [ instroot ] + if hasattr(dirsrv, 'confir'): + ldir.append(dirsrv.confdir) + if hasattr(dirsrv, 'dbdir'): + ldir.append(dirsrv.dbdir) + if hasattr(dirsrv, 'changelogdb'): + ldir.append(dirsrv.changelogdb) + + # now scan the directory list to find the files to backup + for dirToBackup in ldir: for root, dirs, files in os.walk(dirToBackup): for file in files: name = os.path.join(root, file) diff --git a/src/lib389/tests/dsadmin_test.py b/src/lib389/tests/dsadmin_test.py index 285d6612a..251617d39 100644 --- a/src/lib389/tests/dsadmin_test.py +++ b/src/lib389/tests/dsadmin_test.py @@ -207,7 +207,7 @@ def setupAgreement_test(): conn.replica.add(**args) conn.added_entries.append(args['binddn']) - dn_replica = conn.setupAgreement(consumer, args) + dn_replica = conn.createAgreement(consumer, args) def stop_start_test(): diff --git a/src/lib389/tests/replica_test.py b/src/lib389/tests/replica_test.py index c0e7febdf..c358296e8 100644 --- a/src/lib389/tests/replica_test.py +++ b/src/lib389/tests/replica_test.py @@ -174,7 +174,7 @@ def enable_logging_test(): def status_test(): - status = conn.replica.status(conn.agreement_dn) + status = conn.agreement.status(conn.agreement_dn) log.info(status) assert status
0
26f1ba532699af601cca4bee4cffcdd75c2c8fd7
389ds/389-ds-base
Ticket #48048 - Fix coverity issues - 2015/2/24 Coverity defect 13048 - Explicit null dereferenced (FORWARD_NULL) Description: Added NULL check for operation. modified: modify_schema_dse in schema.c
commit 26f1ba532699af601cca4bee4cffcdd75c2c8fd7 Author: Noriko Hosoi <[email protected]> Date: Tue Feb 24 17:31:52 2015 -0800 Ticket #48048 - Fix coverity issues - 2015/2/24 Coverity defect 13048 - Explicit null dereferenced (FORWARD_NULL) Description: Added NULL check for operation. modified: modify_schema_dse in schema.c diff --git a/ldap/servers/slapd/schema.c b/ldap/servers/slapd/schema.c index af5208191..930954799 100644 --- a/ldap/servers/slapd/schema.c +++ b/ldap/servers/slapd/schema.c @@ -2089,6 +2089,14 @@ modify_schema_dse (Slapi_PBlock *pb, Slapi_Entry *entryBefore, Slapi_Entry *entr slapi_pblock_get( pb, SLAPI_MODIFY_MODS, &mods ); slapi_pblock_get( pb, SLAPI_IS_REPLICATED_OPERATION, &is_replicated_operation); slapi_pblock_get( pb, SLAPI_OPERATION, &operation); + if (NULL == operation) { + *returncode = LDAP_OPERATIONS_ERROR; + schema_create_errormsg( returntext, SLAPI_DSE_RETURNTEXT_SIZE, + schema_errprefix_generic, "Generic", + "operation is null" ); + return (SLAPI_DSE_CALLBACK_ERROR); + } + is_internal_operation = slapi_operation_is_flag_set(operation, SLAPI_OP_FLAG_INTERNAL); /* In case we receive a schema from a supplier, check if we can accept it
0
c8370b89fc2883d0785471f5d0d837386b564170
389ds/389-ds-base
fix compiler warning for patch 49287
commit c8370b89fc2883d0785471f5d0d837386b564170 Author: Ludwig Krispenz <[email protected]> Date: Mon Jul 17 18:03:52 2017 +0200 fix compiler warning for patch 49287 diff --git a/ldap/servers/plugins/replication/repl5_plugins.c b/ldap/servers/plugins/replication/repl5_plugins.c index e53572b54..075f9efec 100644 --- a/ldap/servers/plugins/replication/repl5_plugins.c +++ b/ldap/servers/plugins/replication/repl5_plugins.c @@ -45,6 +45,7 @@ #include "repl.h" #include "cl5_api.h" #include "urp.h" +#include "csnpl.h" static char *local_purl = NULL; static char *purl_attrs[] = {"nsslapd-localhost", "nsslapd-port", "nsslapd-secureport", NULL};
0
13b80015b215a581c45fb1318fec64ddb19a49ab
389ds/389-ds-base
Ticket 49091 - remove usage of changelog semaphore it was used to replace a serial lock, but now the writing to the changelog is done inside the txn and already serialized by the backend lock. we can remove unnecessary code Reviewed by: Thierry, William - thanks
commit 13b80015b215a581c45fb1318fec64ddb19a49ab Author: Ludwig Krispenz <[email protected]> Date: Mon Jul 11 14:45:19 2016 +0200 Ticket 49091 - remove usage of changelog semaphore it was used to replace a serial lock, but now the writing to the changelog is done inside the txn and already serialized by the backend lock. we can remove unnecessary code Reviewed by: Thierry, William - thanks diff --git a/ldap/servers/plugins/replication/cl5_api.c b/ldap/servers/plugins/replication/cl5_api.c index 3c6870aef..bf68fd19f 100644 --- a/ldap/servers/plugins/replication/cl5_api.c +++ b/ldap/servers/plugins/replication/cl5_api.c @@ -136,8 +136,6 @@ typedef struct cl5dbfile * or as initialized */ RUV *purgeRUV; /* ruv to which the file has been purged */ RUV *maxRUV; /* ruv that marks the upper boundary of the data */ - char *semaName; /* semaphore name */ - PRSem *sema; /* semaphore for max concurrent cl writes */ }CL5DBFile; /* structure that allows to iterate through entries to be sent to a consumer @@ -3347,7 +3345,6 @@ static int _cl5Delete (const char *clDir, int rmDir) static void _cl5SetDefaultDBConfig(void) { - s_cl5Desc.dbConfig.maxConcurrentWrites= CL5_DEFAULT_CONFIG_MAX_CONCURRENT_WRITES; s_cl5Desc.dbConfig.fileMode = FILE_CREATE_MODE; } @@ -3355,7 +3352,6 @@ static void _cl5SetDBConfig (const CL5DBConfig *config) { /* s_cl5Desc.dbConfig.pageSize is retrieved from backend */ /* Some other configuration parameters are hardcoded... */ - s_cl5Desc.dbConfig.maxConcurrentWrites = config->maxConcurrentWrites; s_cl5Desc.dbConfig.fileMode = FILE_CREATE_MODE; } @@ -5045,15 +5041,7 @@ static int _cl5WriteOperationTxn(const char *replName, const char *replGen, goto done; } - if ( file->sema ) - { - PR_WaitSemaphore(file->sema); - } rc = file->db->put(file->db, txnid, &key, data, 0); - if ( file->sema ) - { - PR_PostSemaphore(file->sema); - } if (CL5_OS_ERR_IS_DISKFULL(rc)) { slapi_log_err(SLAPI_LOG_CRIT, repl_plugin_name_cl, @@ -6084,7 +6072,6 @@ static int _cl5NewDBFile (const char *replName, const char *replGen, CL5DBFile** int rc; DB *db = NULL; char *name; - char *semadir; #ifdef HPUX char cwd [PATH_MAX+1]; #endif @@ -6149,91 +6136,6 @@ out: (*dbFile)->replName = slapi_ch_strdup (replName); (*dbFile)->replGen = slapi_ch_strdup (replGen); - /* - * Considerations for setting up cl semaphore: - * (1) The NT version of SleepyCat uses test-and-set mutexes - * at the DB page level instead of blocking mutexes. That has - * proven to be a killer for the changelog DB, as this DB is - * accessed by multiple a reader threads (the repl thread) and - * writer threads (the server ops threads) usually at the last - * pages of the DB, due to the sequential nature of the changelog - * keys. To avoid the test-and-set mutexes, we could use semaphore - * to serialize the writers and avoid the high mutex contention - * that SleepyCat is unable to avoid. - * (2) DS 6.2 introduced the semaphore on all platforms (replaced - * the serial lock used on Windows and Linux described above). - * The number of the concurrent writes now is configurable by - * nsslapd-changelogmaxconcurrentwrites (the server needs to - * be restarted). - */ - - semadir = s_cl5Desc.dbDir; -#ifdef HPUX - /* - * HP sem_open() does not allow pathname component "./" or "../" - * in the semaphore name. For simplicity and to avoid doing - * chdir() in multi-thread environment, current working dir - * (log dir) is used to replace the original semaphore dir - * if it contains "./". - */ - if ( strstr ( semadir, "./" ) != NULL && getcwd ( cwd, PATH_MAX+1 ) != NULL ) - { - semadir = cwd; - } -#endif - - if ( semadir != NULL ) - { - (*dbFile)->semaName = slapi_ch_smprintf("%s/%s.sema", semadir, replName); - slapi_log_err(SLAPI_LOG_REPL, repl_plugin_name_cl, - "_cl5NewDBFile - semaphore %s\n", (*dbFile)->semaName); - (*dbFile)->sema = PR_OpenSemaphore((*dbFile)->semaName, - PR_SEM_CREATE | PR_SEM_EXCL, 0666, - s_cl5Desc.dbConfig.maxConcurrentWrites ); - slapi_log_err(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5NewDBFile - maxConcurrentWrites=%d\n", s_cl5Desc.dbConfig.maxConcurrentWrites ); - } - - if ((*dbFile)->sema == NULL ) - { - /* If the semaphore was left around due - * to an unclean exit last time, remove - * and re-create it. - */ - if (PR_GetError() == PR_FILE_EXISTS_ERROR) { - PRErrorCode prerr; - PR_DeleteSemaphore((*dbFile)->semaName); - prerr = PR_GetError(); - if (PR_SUCCESS != prerr) { - slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name_cl, - "_cl5NewDBFile - PR_DeleteSemaphore: %s; NSPR error - %d\n", - (*dbFile)->semaName ? (*dbFile)->semaName : "(nil)", prerr); - } - (*dbFile)->sema = PR_OpenSemaphore((*dbFile)->semaName, - PR_SEM_CREATE | PR_SEM_EXCL, 0666, - s_cl5Desc.dbConfig.maxConcurrentWrites ); - } - - /* If we still failed to create the semaphore, - * we should just error out. */ - if ((*dbFile)->sema == NULL ) - { - PRErrorCode prerr = PR_GetError(); - if (PR_FILE_EXISTS_ERROR == prerr) { - slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name_cl, - "_cl5NewDBFile - PR_OpenSemaphore: %s; sema: 0x%p, NSPR error - %d\n", - (*dbFile)->semaName ? (*dbFile)->semaName : "(nil)", (*dbFile)->sema, prerr); - slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name_cl, - "_cl5NewDBFile - Leftover semaphores may exist. " - "Run \"ipcs -s\", and remove them with \"ipcrm -s <SEMID>\" if any\n"); - } else { - slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name_cl, - "_cl5NewDBFile - Failed to create semaphore %s; NSPR error - %d\n", - (*dbFile)->semaName ? (*dbFile)->semaName : "(nil)", prerr); - } - rc = CL5_SYSTEM_ERROR; - goto done; - } - } /* compute number of entries in the file */ /* ONREPL - to improve performance, we keep entry count in memory @@ -6326,12 +6228,6 @@ static void _cl5DBCloseFile (void **data) ruv_destroy(&file->maxRUV); ruv_destroy(&file->purgeRUV); file->db = NULL; - if (file->sema) { - PR_CloseSemaphore (file->sema); - PR_DeleteSemaphore (file->semaName); - file->sema = NULL; - } - slapi_ch_free ((void**)&file->semaName); slapi_ch_free (data); } diff --git a/ldap/servers/plugins/replication/cl5_api.h b/ldap/servers/plugins/replication/cl5_api.h index ff61d7838..fce8b5c94 100644 --- a/ldap/servers/plugins/replication/cl5_api.h +++ b/ldap/servers/plugins/replication/cl5_api.h @@ -41,7 +41,6 @@ typedef struct cl5dbconfig { size_t pageSize; /* page size in bytes */ PRInt32 fileMode; /* file mode */ - PRUint32 maxConcurrentWrites; /* max number of concurrent cl writes */ char *encryptionAlgorithm; /* nsslapd-encryptionalgorithm */ char *symmetricKey; } CL5DBConfig; @@ -74,17 +73,6 @@ typedef struct cl5entry #define CL5_DEFAULT_CONFIG_CACHEMEMSIZE 1048576 /* 1 M bytes */ #define CL5_DEFAULT_CONFIG_NB_LOCK 1000 /* Number of locks in the lock table of the DB */ -/* - * Small number of concurrent writes degradate the throughput. - * Large one increases deadlock. - */ -#ifdef SOLARIS -#define CL5_DEFAULT_CONFIG_MAX_CONCURRENT_WRITES 10 -#else -#define CL5_DEFAULT_CONFIG_MAX_CONCURRENT_WRITES 2 -#endif - - #define CL5_MIN_DB_DBCACHESIZE 524288 /* min 500K bytes */ #define CL5_MIN_CACHESIZE 500 /* min number of entries */ #define CL5_MIN_CACHEMEMSIZE 262144 /* min 250K bytes */ diff --git a/ldap/servers/plugins/replication/cl5_config.c b/ldap/servers/plugins/replication/cl5_config.c index 4c299abb0..6f23768e9 100644 --- a/ldap/servers/plugins/replication/cl5_config.c +++ b/ldap/servers/plugins/replication/cl5_config.c @@ -740,7 +740,6 @@ static changelog5Config * changelog5_dup_config(changelog5Config *config) dup->dbconfig.pageSize = config->dbconfig.pageSize; dup->dbconfig.fileMode = config->dbconfig.fileMode; - dup->dbconfig.maxConcurrentWrites = config->dbconfig.maxConcurrentWrites; return dup; } @@ -813,20 +812,6 @@ static void changelog5_extract_config(Slapi_Entry* entry, changelog5Config *conf config->maxAge = slapi_ch_strdup(CL5_STR_IGNORE); } - /* - * Read the Changelog Internal Configuration Parameters for the Changelog DB - */ - arg = slapi_entry_attr_get_charptr(entry, CONFIG_CHANGELOG_MAX_CONCURRENT_WRITES); - if (arg) - { - config->dbconfig.maxConcurrentWrites = atoi (arg); - slapi_ch_free_string(&arg); - } - if ( config->dbconfig.maxConcurrentWrites <= 0 ) - { - config->dbconfig.maxConcurrentWrites = CL5_DEFAULT_CONFIG_MAX_CONCURRENT_WRITES; - } - /* * changelog encryption */ diff --git a/ldap/servers/plugins/replication/repl_shared.h b/ldap/servers/plugins/replication/repl_shared.h index b7cd98d78..c8d297888 100644 --- a/ldap/servers/plugins/replication/repl_shared.h +++ b/ldap/servers/plugins/replication/repl_shared.h @@ -33,7 +33,6 @@ #define CONFIG_CHANGELOG_COMPACTDB_ATTRIBUTE "nsslapd-changelogcompactdb-interval" #define CONFIG_CHANGELOG_TRIM_ATTRIBUTE "nsslapd-changelogtrim-interval" /* Changelog Internal Configuration Parameters -> Changelog Cache related */ -#define CONFIG_CHANGELOG_MAX_CONCURRENT_WRITES "nsslapd-changelogmaxconcurrentwrites" #define CONFIG_CHANGELOG_ENCRYPTION_ALGORITHM "nsslapd-encryptionalgorithm" #define CONFIG_CHANGELOG_SYMMETRIC_KEY "nsSymmetricKey"
0
3efb4a20fc64ed1be78bd1d812819f998ca74b01
389ds/389-ds-base
Resolves: bug 478656 Bug Description: rhds accounts are disabled in ad after full sync Reviewed by: nkinder (Thanks!) Fix Description: The incremental sync code calls send_accountcontrol_modify after adding an entry, but the total update code does not. I modified the code to do that. I also changed the send_accountcontrol_modify to force the account to be enabled if adding it. I tried just adding userAccountContro:512 to the default user add template, but AD does not like this - gives operations error. So you have to modify userAccountControl after adding the entry. I also cleaned up a couple of minor memory leaks. Platforms tested: RHEL5 Flag Day: no Doc impact: Yes - we need to document the fact that new accounts will now be created in AD enabled
commit 3efb4a20fc64ed1be78bd1d812819f998ca74b01 Author: Rich Megginson <[email protected]> Date: Wed Jan 7 21:45:55 2009 +0000 Resolves: bug 478656 Bug Description: rhds accounts are disabled in ad after full sync Reviewed by: nkinder (Thanks!) Fix Description: The incremental sync code calls send_accountcontrol_modify after adding an entry, but the total update code does not. I modified the code to do that. I also changed the send_accountcontrol_modify to force the account to be enabled if adding it. I tried just adding userAccountContro:512 to the default user add template, but AD does not like this - gives operations error. So you have to modify userAccountControl after adding the entry. I also cleaned up a couple of minor memory leaks. Platforms tested: RHEL5 Flag Day: no Doc impact: Yes - we need to document the fact that new accounts will now be created in AD enabled diff --git a/ldap/servers/plugins/replication/windows_protocol_util.c b/ldap/servers/plugins/replication/windows_protocol_util.c index 70fdfa6ac..9909adf7e 100644 --- a/ldap/servers/plugins/replication/windows_protocol_util.c +++ b/ldap/servers/plugins/replication/windows_protocol_util.c @@ -806,7 +806,7 @@ send_password_modify(Slapi_DN *sdn, char *password, Private_Repl_Protocol *prp) } static int -send_accountcontrol_modify(Slapi_DN *sdn, Private_Repl_Protocol *prp) +send_accountcontrol_modify(Slapi_DN *sdn, Private_Repl_Protocol *prp, int missing_entry) { ConnResult mod_return = 0; Slapi_Mods smods = {0}; @@ -823,9 +823,18 @@ send_accountcontrol_modify(Slapi_DN *sdn, Private_Repl_Protocol *prp) acctval = slapi_entry_attr_get_ulong(remote_entry, "userAccountControl"); } slapi_entry_free(remote_entry); + /* if we are adding a new entry, we need to set the entry to be + enabled to allow AD login */ + if (missing_entry) { + slapi_log_error(SLAPI_LOG_REPL, windows_repl_plugin_name, + "%s: New Windows entry %s will be enabled.\n", + agmt_get_long_name(prp->agmt), slapi_sdn_get_dn(sdn)); + acctval &= ~0x2; /* unset the disabled bit, if set */ + } + /* set the account to be a normal account */ acctval |= 0x0200; /* normal account == 512 */ - slapi_mods_init (&smods, 0); + slapi_mods_init (&smods, 0); PR_snprintf(acctvalstr, sizeof(acctvalstr), "%lu", acctval); slapi_mods_add_string(&smods, LDAP_MOD_REPLACE, "userAccountControl", acctvalstr); @@ -1320,7 +1329,7 @@ windows_replay_update(Private_Repl_Protocol *prp, slapi_operation_parameters *op * userAccountControl: 512 */ if (op->operation_type == SLAPI_OPERATION_ADD && missing_entry) { - return_value = send_accountcontrol_modify(remote_dn, prp); + return_value = send_accountcontrol_modify(remote_dn, prp, missing_entry); } } } @@ -1340,6 +1349,7 @@ error: { slapi_sdn_free(&remote_dn); } + slapi_ch_free_string(&password); return return_value; } @@ -3631,6 +3641,10 @@ windows_process_total_add(Private_Repl_Protocol *prp,Slapi_Entry *e, Slapi_DN* r } ldap_mods_free(entryattrs, 1); entryattrs = NULL; + + if (retval == 0) { /* set the account control bits */ + retval = send_accountcontrol_modify(remote_dn, prp, missing_entry); + } } } else { @@ -3659,6 +3673,7 @@ windows_process_total_add(Private_Repl_Protocol *prp,Slapi_Entry *e, Slapi_DN* r slapi_entry_free(remote_entry); } } + slapi_ch_free_string(&password); return retval; }
0
f21aa3dea521bcf6b48d0af1a0b480978623aa68
389ds/389-ds-base
Resolves: bug 231905 Bug Description: migration: Migrate from 1.0.x to 1.1 Reviewed by: nhosoi (Thanks!) Fix Description: The basic strategy is 1) shutdown the old servers - databases should be quiescent 2) run the migration script - this will copy all of the files (under /opt/fedora-ds/slapd-* by default) to their new FHS style locations, and fix up any entries and attributes that are obsolete or have changed (e.g. values that refer to paths) 3) service fedora-ds start The migration script does not need to do anything to the database files - the new database code added by Noriko will handle the database upgrade automagically, but I'm leaving the database upgrade code in the script, commented out, in case we need it in the future. This also fixes an annoying problem with automake - it would build ds_newinst.pl from ds_newinst.pl.in in the source ldap/admin/src directory, and use that version. This is really a problem with multi platform builds, where you want to share the ldapserver source code among multiple platforms. With the fix, built/ldap/admin/src/ds_newinst.pl is generated from srcdir/ldap/admin/src/ds_newinst.pl.in, and srcdir/ldap/admin/src/ds_newinst.pl is not written. Platforms tested: FC6 Flag Day: no Doc impact: Yes - we need to document migration
commit f21aa3dea521bcf6b48d0af1a0b480978623aa68 Author: Rich Megginson <[email protected]> Date: Fri Mar 16 21:32:44 2007 +0000 Resolves: bug 231905 Bug Description: migration: Migrate from 1.0.x to 1.1 Reviewed by: nhosoi (Thanks!) Fix Description: The basic strategy is 1) shutdown the old servers - databases should be quiescent 2) run the migration script - this will copy all of the files (under /opt/fedora-ds/slapd-* by default) to their new FHS style locations, and fix up any entries and attributes that are obsolete or have changed (e.g. values that refer to paths) 3) service fedora-ds start The migration script does not need to do anything to the database files - the new database code added by Noriko will handle the database upgrade automagically, but I'm leaving the database upgrade code in the script, commented out, in case we need it in the future. This also fixes an annoying problem with automake - it would build ds_newinst.pl from ds_newinst.pl.in in the source ldap/admin/src directory, and use that version. This is really a problem with multi platform builds, where you want to share the ldapserver source code among multiple platforms. With the fix, built/ldap/admin/src/ds_newinst.pl is generated from srcdir/ldap/admin/src/ds_newinst.pl.in, and srcdir/ldap/admin/src/ds_newinst.pl is not written. Platforms tested: FC6 Flag Day: no Doc impact: Yes - we need to document migration diff --git a/Makefile.am b/Makefile.am index 654de4f1d..a63fe88c0 100644 --- a/Makefile.am +++ b/Makefile.am @@ -21,7 +21,7 @@ DS_INCLUDES = -I$(srcdir)/ldap/include -I$(srcdir)/ldap/servers/slapd -I$(srcdir PATH_DEFINES = -DLOCALSTATEDIR="\"$(localstatedir)\"" -DSYSCONFDIR="\"$(sysconfdir)\"" \ -DLIBDIR="\"$(libdir)\"" -DBINDIR="\"$(bindir)\"" \ -DDATADIR="\"$(datadir)\"" -DDOCDIR="\"$(docdir)\"" \ - -DSBINDIR="\"$(sbindir)\"" + -DSBINDIR="\"$(sbindir)\"" -DPLUGINDIR="\"$(serverplugindir)\"" AM_CPPFLAGS = $(DEBUG_DEFINES) $(DS_DEFINES) $(DS_INCLUDES) $(PATH_DEFINES) PLUGIN_CPPFLAGS = $(AM_CPPFLAGS) @ldapsdk_inc@ @nss_inc@ @nspr_inc@ @@ -148,13 +148,14 @@ schema_DATA = $(srcdir)/ldap/schema/00core.ldif \ bin_SCRIPTS = $(srcdir)/ldap/servers/slapd/tools/rsearch/scripts/dbgen.pl \ wrappers/dbscan \ wrappers/ds_newinst \ - $(srcdir)/ldap/admin/src/ds_newinst.pl \ + ldap/admin/src/ds_newinst.pl \ wrappers/dsktune \ wrappers/infadd \ wrappers/ldap-agent \ wrappers/ldclt \ wrappers/ldif \ $(srcdir)/ldap/admin/src/logconv.pl \ + ldap/admin/src/migrateTo11 \ wrappers/migratecred \ wrappers/mmldif \ wrappers/pwdhash \ diff --git a/Makefile.in b/Makefile.in index 4d9a57b14..e00a691f1 100644 --- a/Makefile.in +++ b/Makefile.in @@ -981,7 +981,7 @@ DS_INCLUDES = -I$(srcdir)/ldap/include -I$(srcdir)/ldap/servers/slapd -I$(srcdir PATH_DEFINES = -DLOCALSTATEDIR="\"$(localstatedir)\"" -DSYSCONFDIR="\"$(sysconfdir)\"" \ -DLIBDIR="\"$(libdir)\"" -DBINDIR="\"$(bindir)\"" \ -DDATADIR="\"$(datadir)\"" -DDOCDIR="\"$(docdir)\"" \ - -DSBINDIR="\"$(sbindir)\"" + -DSBINDIR="\"$(sbindir)\"" -DPLUGINDIR="\"$(serverplugindir)\"" AM_CPPFLAGS = $(DEBUG_DEFINES) $(DS_DEFINES) $(DS_INCLUDES) $(PATH_DEFINES) PLUGIN_CPPFLAGS = $(AM_CPPFLAGS) @ldapsdk_inc@ @nss_inc@ @nspr_inc@ @@ -1064,13 +1064,14 @@ schema_DATA = $(srcdir)/ldap/schema/00core.ldif \ bin_SCRIPTS = $(srcdir)/ldap/servers/slapd/tools/rsearch/scripts/dbgen.pl \ wrappers/dbscan \ wrappers/ds_newinst \ - $(srcdir)/ldap/admin/src/ds_newinst.pl \ + ldap/admin/src/ds_newinst.pl \ wrappers/dsktune \ wrappers/infadd \ wrappers/ldap-agent \ wrappers/ldclt \ wrappers/ldif \ $(srcdir)/ldap/admin/src/logconv.pl \ + ldap/admin/src/migrateTo11 \ wrappers/migratecred \ wrappers/mmldif \ wrappers/pwdhash \ diff --git a/ldap/admin/src/migrateTo11.in b/ldap/admin/src/migrateTo11.in new file mode 100644 index 000000000..1618dece9 --- /dev/null +++ b/ldap/admin/src/migrateTo11.in @@ -0,0 +1,676 @@ +#!/usr/bin/env perl +# +# BEGIN COPYRIGHT BLOCK +# 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; version 2 of the License. +# +# This Program is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this Program; if not, write to the Free Software Foundation, Inc., 59 Temple +# Place, Suite 330, Boston, MA 02111-1307 USA. +# +# In addition, as a special exception, Red Hat, Inc. gives You the additional +# right to link the code of this Program with code not covered under the GNU +# General Public License ("Non-GPL Code") and to distribute linked combinations +# including the two, subject to the limitations in this paragraph. Non-GPL Code +# permitted under this exception must only link to the code of this Program +# through those well defined interfaces identified in the file named EXCEPTION +# found in the source code files (the "Approved Interfaces"). The files of +# Non-GPL Code may instantiate templates or use macros or inline functions from +# the Approved Interfaces without causing the resulting work to be covered by +# the GNU General Public License. Only Red Hat, Inc. may make changes or +# additions to the list of Approved Interfaces. You must obey the GNU General +# Public License in all respects for all of the Program code and other code used +# in conjunction with the Program except the Non-GPL Code covered by this +# exception. If you modify this file, you may extend this exception to your +# version of the file, but you are not obligated to do so. If you do not wish to +# provide this exception without modification, you must delete this exception +# statement from your version and license this file solely under the GPL without +# exception. +# +# Copyright (C) 2007 Red Hat, Inc. +# All rights reserved. +# END COPYRIGHT BLOCK +# + +# cmd line parsing +use Getopt::Long; +# tempfiles +use File::Temp qw(tempfile tempdir); + +# load perldap +use Mozilla::LDAP::Conn; +use Mozilla::LDAP::Utils qw(normalizeDN); +use Mozilla::LDAP::API qw(ldap_explode_dn); +use Mozilla::LDAP::LDIF; + +# these are the attributes for which we will always use +# the new value, or which do not apply anymore +my %ignoreOld = +( + 'nsslapd-errorlog' => 'nsslapd-errorlog', + 'nsslapd-accesslog' => 'nsslapd-accesslog', + 'nsslapd-auditlog' => 'nsslapd-auditlog', + 'nskeyfile' => 'nsKeyfile', + 'nscertfile' => 'nsCertfile', + 'nsslapd-pluginpath' => 'nsslapd-pluginPath', + 'nsslapd-plugintype' => 'nsslapd-pluginType', + 'nsslapd-pluginversion' => 'nsslapd-pluginVersion', + 'nsslapd-plugin-depends-on-named' => 'nsslapd-plugin-depends-on-named', +# these are new attrs that we should just pass through + 'nsslapd-schemadir' => 'nsslapd-schemadir', + 'nsslapd-lockdir' => 'nsslapd-lockdir', + 'nsslapd-tmpdir' => 'nsslapd-tmpdir', + 'nsslapd-certdir' => 'nsslapd-certdir', + 'nsslapd-ldapifilepath' => 'nsslapd-ldapifilepath', + 'nsslapd-ldapilisten' => 'nsslapd-ldapilisten', + 'nsslapd-ldapiautobind' => 'nsslapd-ldapiautobind', + 'nsslapd-ldapimaprootdn' => 'nsslapd-ldapimaprootdn', + 'nsslapd-ldapimaptoentries' => 'nsslapd-ldapimaptoentries', + 'nsslapd-ldapiuidnumbertype' => 'nsslapd-ldapiuidnumbertype', + 'nsslapd-ldapigidnumbertype' => 'nsslapd-ldapigidnumbertype', + 'nsslapd-ldapientrysearchbase' => 'nsslapd-ldapientrysearchbase', + 'nsslapd-ldapiautodnsuffix' => 'nsslapd-ldapiautodnsuffix' +); + +# these are the attributes for which we will always use +# the old value +my %alwaysUseOld = +( + 'aci' => 'aci' +); + +# global vars used throughout script + subs +my $pkgname = "@package_name@"; +# this is the new pkgname which may be something like +# fedora-ds-base - we have to strip off the -suffix +if ($pkgname =~ /-(core|base)$/) { + $pkgname =~ s/-(core|base)$//; +} +my $oldpkgname = $pkgname; +my $oldsroot = "/opt/$oldpkgname"; + +# figure out the current bdb version +my $db_version=`db_verify -V`; +my ($db_major_version, $db_minor_version); +if ($db_version =~ /Berkeley DB (\d+)\.(\d+)/) { + $db_major_version = $1; + $db_minor_version = $2; +} +my $db_verstr = "bdb/${db_major_version}.${db_minor_version}/libback-ldbm"; + +my $debuglevel = 0; +# use like this: +# debug(3, "message"); +# this will only print "message" if $debuglevel is 3 or higher (-vvv on the command line) +sub debug { + my ($level, @rest) = @_; + if ($level <= $debuglevel) { + print STDERR "+" x $level, @rest; + } +} + +sub getNewDbDir { + my ($ent, $attr, $inst) = @_; + my %objclasses = map { lc($_) => $_ } $ent->getValues('objectclass'); + my $cn = $ent->getValues('cn'); + my $newval; + if ($objclasses{nsbackendinstance}) { + $newval = "@localstatedir@/lib/$pkgname/$inst/db/$cn"; + } elsif (lc $cn eq 'config') { + $newval = "@localstatedir@/lib/$pkgname/$inst/db"; + } elsif (lc $cn eq 'changelog5') { + $newval = "@localstatedir@/lib/$pkgname/$inst/cldb"; + } + debug(2, "New value [$newval] for attr $attr in entry ", $ent->getDN(), "\n"); + return $newval; +} + +sub migrateCredentials { + my ($ent, $attr, $inst) = @_; + my $oldval = $ent->getValues($attr); + debug(3, "Executing migratecred -o $oldsroot/$inst -n @instconfigdir@/$inst -c $oldval . . .\n"); + my $newval = `migratecred -o $oldsroot/$inst -n @instconfigdir@/$inst -c $oldval`; + debug(3, "Converted old value [$oldval] to new value [$newval] for attr $attr in entry ", $ent->getDN(), "\n"); + return $newval; +} + +# these are attributes that we have to transform from +# the old value to the new value (e.g. a pathname) +# The key of this hash is the attribute name. The value +# is an anonymous sub which takes two arguments - the entry +# and the old value. The return value of the sub is +# the new value +my %transformAttr = +( + 'nsslapd-directory' => \&getNewDbDir, + 'nsslapd-db-logdirectory' => \&getNewDbDir, + 'nsslapd-changelogdir' => \&getNewDbDir, + 'nsds5replicacredentials' => \&migrateCredentials, + 'nsmultiplexorcredentials' => \&migrateCredentials +); + +#nsslapd-directory - if same as old path, convert to new, otherwise, leave it +#nsslapd-logdirectory - if same as old path, convert to new, otherwise, leave it + +#nsslapd-accesslog +#nsslapd-errorlog +#nsslapd-auditlog + +#nskeyfile +#nscertfile + +#dn: cn=Internationalization Plugin +#nsslapd-pluginArg0: $inst/config/slapd-collations.conf + +#dn: cn=referential integrity postoperation +#nsslapd-pluginarg1: $inst/logs/referint + +# don't forget changelogdb and certmap.conf +# [General] +# FullMachineName= localhost.localdomain +# SuiteSpotUserID= nobody +# ServerRoot= /usr/lib64/fedora-ds +# [slapd] +# ServerPort= 1100 +# ServerIdentifier= localhost +# Suffix= dc=example,dc=com +# RootDN= cn=Directory Manager +# RootDNPwd= Secret123 + +sub createInfFileFromDseLdif { + my $oldroot = shift; + my $inst = shift; + my $fname = "$oldroot/$inst/config/dse.ldif"; + my $id; + ($id = $inst) =~ s/^slapd-//; + open( DSELDIF, "$fname" ) || die "Can't open $fname: $!"; + my ($outfh, $inffile) = tempfile(SUFFIX => '.inf'); + my $in = new Mozilla::LDAP::LDIF(*DSELDIF) ; + while ($ent = readOneEntry $in) { + my $dn = $ent->getDN(); + if ($dn =~ /cn=config/) { + print $outfh "[General]\n"; + print $outfh "FullMachineName = ", $ent->getValues('nsslapd-localhost'), "\n"; + print $outfh "SuiteSpotUserID = ", $ent->getValues('nsslapd-localuser'), "\n"; + print $outfh "ServerRoot = @serverdir@\n"; + print $outfh "[slapd]\n"; + print $outfh "RootDN = ", $ent->getValues('nsslapd-rootdn'), "\n"; + print $outfh "RootDNPwd = ", $ent->getValues('nsslapd-rootpw'), "\n"; + print $outfh "ServerPort = ", $ent->getValues('nsslapd-port'), "\n"; + print $outfh "ServerIdentifier = $id\n"; + print $outfh "Suffix = o=deleteAfterMigration\n"; + print $outfh "start_server= 0\n"; + last; + } + } + close $outfh; + close DSELDIF; + + return $inffile; +} + +sub makeNewInst { + my ($ds_newinst, $inffile) = @_; + system ($ds_newinst, $inffile) == 0 or + die "Could not create new instance using $ds_newinst with inffile $inffile: $?"; +} + +sub copyDatabaseDirs { + my $srcdir = shift; + my $destdir = shift; + if (-d $srcdir && ! -d $destdir) { + debug(0, "Copying database directory $srcdir to $destdir\n"); + system ("cp -p -r $srcdir $destdir") == 0 or + die "Could not copy database directory $srcdir to $destdir: $?"; + } elsif (! -d $srcdir) { + die "Error: database directory $srcdir does not exist"; + } else { + debug(0, "The destination directory $destdir already exists, copying files/dirs individually\n"); + foreach my $file (glob("$srcdir/*")) { + debug(3, "Copying $file to $destdir\n"); + if (-f $file) { + system ("cp -p $file $destdir") == 0 or + die "Error: could not copy $file to $destdir: $!"; + } elsif (-d $file) { + system ("cp -p -r $file $destdir") == 0 or + die "Error: could not copy $file to $destdir: $!"; + } + } + } +} + +sub copyDatabases { + my $oldroot = shift; + my $inst = shift; + my $newdbdir = shift; + + # global config and instance specific config are children of this entry + my $basedbdn = normalizeDN("cn=ldbm database,cn=plugins,cn=config"); + # get the list of databases, their index and transaction log locations + my $fname = "$oldroot/$inst/config/dse.ldif"; + open( DSELDIF, "$fname" ) || die "Can't open $fname: $!"; + my $in = new Mozilla::LDAP::LDIF(*DSELDIF); + my $targetdn = normalizeDN("cn=config,cn=ldbm database,cn=plugins,cn=config"); + while ($ent = readOneEntry $in) { + next if (!$ent->getDN()); # just skip root dse + # look for the one level children of $basedbdn + my @rdns = ldap_explode_dn($ent->getDN(), 0); + my $parentdn = normalizeDN(join(',', @rdns[1..$#rdns])); + if ($parentdn eq $basedbdn) { + my $cn = $ent->getValues('cn'); + my %objclasses = map { lc($_) => $_ } $ent->getValues('objectclass'); + if ($cn eq 'config') { # global config + debug(1, "Found ldbm database plugin config entry ", $ent->getDN(), "\n"); + my $dir = $ent->getValues('nsslapd-directory'); + my $homedir = $ent->getValues('nsslapd-db-home-directory'); + my $logdir = $ent->getValues('nsslapd-db-logdirectory'); + debug(1, "old db dir = $dir homedir = $homedir logdir = $logdir\n"); + my $srcdir = $homedir || $dir || "$oldroot/$inst/db"; + copyDatabaseDirs($srcdir, $newdbdir); + copyDatabaseDirs($logdir, $newdbdir) if ($logdir && $logdir ne $srcdir); + } elsif ($objclasses{nsbackendinstance}) { + debug(1, "Found ldbm database instance entry ", $ent->getDN(), "\n"); + my $dir = $ent->getValues('nsslapd-directory'); + # the default db instance directory is + # $oldroot/$inst/$cn + debug(1, "old instance $cn dbdir $dir\n"); + my $srcdir = $dir || "$oldroot/$inst/db/$cn"; + copyDatabaseDirs($srcdir, "$newdbdir/$cn"); + } # else just ignore for now + } + } + close DSELDIF; + + # server automagically upgrades database if needed +# upgradeDatabase($newdbdir); + # fix the DBVERSION files +# updateDBVERSION($newdbdir); + # fix guardian files +# updateDBguardian($newdbdir); +} + +sub copySecurityFiles { + my $oldroot = shift; + my $inst = shift; + my $destdir = shift; + + if (! -d "$oldroot/alias") { + debug(0, "Error: security file directory $oldroot/alias not found\n"); + } elsif (! -d $destdir) { + debug(0, "Error: new security file directory $destdir not found\n"); + } else { + debug(1, "Copying $oldroot/alias/$inst-cert8.db to $destdir/cert8.db\n"); + system ("cp -p $oldroot/alias/$inst-cert8.db $destdir/cert8.db") == 0 or + die "Error: could not copy $oldroot/alias/$inst-cert8.db to $destdir/cert8.db: $!"; + debug(1, "Copying $oldroot/alias/$inst-key3.db to $destdir/key3.db\n"); + system ("cp -p $oldroot/alias/$inst-key3.db $destdir/key3.db") == 0 or + die "Error: could not copy $oldroot/alias/$inst-key3.db to $destdir/key3.db: $!"; + debug(1, "Copying $oldroot/alias/secmod.db to $destdir/secmod.db\n"); + system ("cp -p $oldroot/alias/secmod.db $destdir/secmod.db") == 0 or + die "Error: could not copy $oldroot/alias/secmod.db to $destdir/secmod.db: $!"; + if (-f "$oldroot/alias/$inst-pin.txt") { + debug(1, "Copying $oldroot/alias/$inst-pin.txt to $destdir/pin.txt\n"); + system ("cp -p $oldroot/alias/$inst-pin.txt $destdir/pin.txt") == 0 or + die "Error: could not copy $oldroot/alias/$inst-pin.txt to $destdir/pin.txt: $!"; + } + if (-f "$oldroot/shared/config/certmap.conf") { + debug(1, "Copying $oldroot/shared/config/certmap.conf to $destdir/certmap.conf\n"); + system ("cp -p $oldroot/shared/config/certmap.conf $destdir/certmap.conf") == 0 or + die "Error: could not copy $oldroot/shared/config/certmap.conf to $destdir/certmap.conf: $!"; + } + } +} + +sub copyChangelogDB { + my $oldroot = shift; + my $inst = shift; + my $newdbdir = shift; + # changelog config entry + my $cldn = normalizeDN("cn=changelog5, cn=config"); + my $fname = "$oldroot/$inst/config/dse.ldif"; + open( DSELDIF, "$fname" ) || die "Can't open $fname: $!"; + my $in = new Mozilla::LDAP::LDIF(*DSELDIF); + while ($ent = readOneEntry $in) { + my $targetdn = normalizeDN($ent->getDN()); + if ($targetdn eq $cldn) { + my $oldcldir = $ent->getValues('nsslapd-changelogdir'); + debug(1, "old cldb dir = $oldcldir\n"); + my $srcdir = $oldcldir || "$oldroot/$inst/cldb"; + copyDatabaseDirs($srcdir, $newdbdir); + + # server automagically upgrades database if needed +# upgradeDatabase($newdbdir); + + last; + } + } + close DSELDIF; +} + +sub fixAttrsInEntry { + my ($ent, $inst) = @_; + for my $attr (keys %{$ent}) { + my $lcattr = lc $attr; + if ($transformAttr{$lcattr}) { + $ent->setValues($attr, &{$transformAttr{$lcattr}}($ent, $attr, $inst)); + } + } +} + +sub mergeEntries { + my ($old, $new, $inst) = @_; + my %inoldonly; # attrs in old entry but not new one + my %innewonly; # attrs in new entry but not old one + my @attrs; # attrs common to old and new + # if the attribute exists in the old entry but not the new one + # we should probably add it (checking for special cases first) + # if the attribute exists in the new entry but not the old one + # we might have to delete it from the new entry + # first, get a list of all attributes + foreach my $attr (keys %{$old}) { + if (! $new->exists($attr)) { + $inoldonly{$attr} = $attr; + } else { + push @attrs, $attr; + } + } + foreach my $attr (keys %{$new}) { + if (! $old->exists($attr)) { + $innewonly{$attr} = $attr; + } + } + + # iterate through the attr lists + my $cn = lc $new->getValues("cn"); + foreach my $attr (keys %inoldonly, keys %innewonly, @attrs) { + my $lcattr = lc $attr; + if ($ignoreOld{$lcattr}) { + next; # use new value or just omit if attr is obsolete + } elsif ($transformAttr{$lcattr}) { + # only transform if the value is in the old entry + if (!$innewonly{$attr}) { + $new->setValues($attr, &{$transformAttr{$lcattr}}($old, $attr, $inst)); + } + } elsif ($cn eq "internationalization plugin" and $lcattr eq "nsslapd-pluginarg0") { + next; # use the new value of this path name + } elsif ($cn eq "referential integrity postoperation" and $lcattr eq "nsslapd-pluginarg1") { + next; # use the new value of this path name + } elsif ($innewonly{$attr}) { + $new->remove($attr); # in new but not old - just remove it + } else { + $new->setValues($attr, $old->getValues($attr)); # use old value + } + } +} + +sub mergeDseLdif { + my $oldroot = shift; + my $inst = shift; + my $ent; + + # first, read in old file + my %olddse; # map of normalized DN to Entry + my @olddns; # the DNs in their original order + my $fname = "$oldroot/$inst/config/dse.ldif"; + open( OLDDSELDIF, $fname ) || die "Can't open $fname: $!"; + my $in = new Mozilla::LDAP::LDIF(*OLDDSELDIF); + while ($ent = readOneEntry $in) { + my $dn = normalizeDN($ent->getDN()); + push @olddns, $dn; + $olddse{$dn} = $ent; + } + close OLDDSELDIF; + + # next, read in new file + my %newdse; # map of normalized DN to Entry + my @newdns; # the DNs in their original order that are not in olddns + $fname = "@instconfigdir@/$inst/dse.ldif"; + open( NEWDSELDIF, $fname ) || die "Can't open $fname: $!"; + $in = new Mozilla::LDAP::LDIF(*NEWDSELDIF); + while ($ent = readOneEntry $in) { + my $dn = normalizeDN($ent->getDN()); + $newdse{$dn} = $ent; + if (! exists $olddse{$dn}) { + push @newdns, $dn; + } + } + close NEWDSELDIF; + + # temp file for new, merged dse.ldif + my ($dsefh, $tmpdse) = tempfile(SUFFIX => '.ldif'); + # now, compare entries + # if the entry exists in the old tree but not the new, add it + # if the entry exists in the new tree but not the old, delete it + # otherwise, merge the entries + # @olddns contains the dns in the old dse.ldif, including ones that + # may also be in the new dse.ldif + # @newdns contains dns that are only in the new dse.ldif + for my $dn (@olddns, @newdns) { + my $oldent = $olddse{$dn}; + my $newent = $newdse{$dn}; + my $outputent; + if ($oldent && !$newent) { + # may have to fix up some values in the old entry + fixAttrsInEntry($oldent, $inst); + # output $oldent + $outputent = $oldent; + } elsif (!$oldent && $newent) { + next if ($dn =~ /o=deleteAfterMigration/i); + # output $newent + $outputent = $newent; + } else { #merge + # $newent will contain the merged entry + mergeEntries($oldent, $newent, $inst); + $outputent = $newent; + } + # special fix for rootDSE - perldap doesn't like "" for a dn + if (! $outputent->getDN()) { + my $ary = $outputent->getLDIFrecords(); + shift @$ary; # remove "dn" + shift @$ary; # remove the empty dn value + print $dsefh "dn:\n"; + print $dsefh (Mozilla::LDAP::LDIF::pack_LDIF (78, $ary), "\n"); + } else { + Mozilla::LDAP::LDIF::put_LDIF($dsefh, 78, $outputent); + } + } + close $dsefh; + + return $tmpdse; +} + +sub usage { + print STDERR <<EOF; +Usage: $0 [-h] [-v....v] [-o /path/to/oldserverroot] [-i slapd-instance ... -i slapd-instanceN] + +INTRODUCTION + +This script will copy instances (data and configuration) from the old +server root directory to their new FHS locations. This script does a +copy only - the data in the old instances will be left untouched. The +old instances must be shutdown first to ensure that the databases are +copied safely. The new instances will not be started by migration, +but can be started after running migration by doing + + service $pkgname start + +WARNINGS + +You will not be able to use the console or Admin Express to manage +instances that have been migrated. You will be able to use the web +applications such as the Directory Server Gateway, Directory Express, +and Org Chart. + +If you have configured your main database or replication changelog +database to use separate partitions for log files and index files, +this configuration will not be migrated. All of your data +will be copied to the standard FHS location +@localstatedir@/lib/$pkgname/slapd-INSTANCE/db (or cldb). + +OPTIONS + +-v Increase the verbosity - you can specify this more than once + (e.g. -vvvv) for more output +-o The old server root directory (default $oldsroot) +-i Instance to migrate - by default, all instances in $oldsroot + will be migrated, but you can specify one or more if you do + not want all of them (e.g. -i slapd-inst1 -i slapd-inst2) +-h This message + +EOF + + exit 1; +} + +################################################################# +# Main script begins here +################################################################# + +my @instances; # the instances to migrate + +# process command line options +Getopt::Long::Configure(qw(bundling)); # bundling allows -vvvvvv +GetOptions('verbose|v+' => \$debuglevel, + 'instance|i=s' => \@instances, + 'oldsroot|o=s' => \$oldsroot, + 'help|h' => sub { &usage }); + + +# get list of instances to migrate +if (! @instances) { + # an instance must be a directory called $oldsroot/slapd-something and the file + # $oldsroot/slapd-something/config/dse.ldif must exist + @instances = grep { -d && -f "$_/config/dse.ldif" && ($_ =~ s,$oldsroot/,,) } glob("$oldsroot/slapd-*"); +} + +die "No instances found to migrate" unless (@instances); + +# find ds_newinst.pl - in same directory as this script or in PATH +my $ds_newinst; +($ds_newinst = $0) =~ s|/[^/]+$|/ds_newinst.pl|; +if (! -x $ds_newinst) { + $ds_newinst = "ds_newinst.pl"; # just get from path +} + +# for each instance +foreach my $inst (@instances) { +# set instance specific defaults + my $newdbdir = "@localstatedir@/lib/$pkgname/$inst/db"; + my $newcertdir = "@instconfigdir@/$inst"; + my $newcldbdir = "@localstatedir@/lib/$pkgname/$inst/cldb"; + +# extract the information needed for ds_newinst.pl + my $inffile = createInfFileFromDseLdif($oldsroot, $inst); + debug(2, "Using inffile $inffile created from $oldsroot/$inst\n"); + +# create the new instance + makeNewInst($ds_newinst, $inffile); + unlink($inffile); + +# copy over the files/directories +# copy the databases + copyDatabases($oldsroot, $inst, $newdbdir); + +# copy the security related files + copySecurityFiles($oldsroot, $inst, $newcertdir); + +# copy the repl changelog database + copyChangelogDB($oldsroot, $inst, $newcldbdir); + +# merge the old info into the new dse.ldif + my $tmpdse = mergeDseLdif($oldsroot, $inst); + +# get user/group of new dse + my ($dev, $ino, $mode, $uid, $gid, @rest) = stat "@instconfigdir@/$inst/dse.ldif"; +# save the original new dse.ldif + system("cp -p @instconfigdir@/$inst/dse.ldif @instconfigdir@/$inst/dse.ldif.premigrate"); +# copy the new one + system("cp $tmpdse @instconfigdir@/$inst/dse.ldif"); +# change owner/group + chmod $mode, "@instconfigdir@/$inst/dse.ldif"; + chown $uid, $gid, "@instconfigdir@/$inst/dse.ldif"; + +# remove the temp one + unlink($tmpdse); +} + +debug(0, "\n\nDone! Migration is complete.\n"); +debug(0, "You can start your new servers with: service fedora-ds start\n"); + +# the server automagically upgrades the databases, so these are not needed for now +# sub upgradeDatabase { +# my $newdbdir = shift; +# # now, recover the database to flush the data from the log file(s) +# # into the .db4 (index) files +# debug(0, "Recovering and flushing log files in $newdbdir . . .\n"); +# my $vflag = ""; +# if ($debuglevel > 2) { +# $vflag = "-v"; +# } +# system("db42_recover $vflag -h $newdbdir") == 0 or +# die "Error: could not recover the db files in $newdbdir: $!"; +# # then, remove the log file(s) (log.xxxxx) and the old memory region files (__db.XXX files) +# debug(0, "Removing old log and memory region files in $newdbdir . . .\n"); +# system("rm -f $newdbdir/log.* $newdbdir/__db.*") == 0 or +# die "Error: could not remove log and mem region files in $newdbdir: $!"; +# # finally, upgrade the index files +# debug(0, "Upgrading all database files in $newdbdir . . .\n"); +# for my $dbfile (<$newdbdir/*/*.db4>) { +# debug(2, "Upgrading database file $dbfile . . .\n"); +# system("db_upgrade -h $newdbdir $dbfile") == 0 or +# die "Error: could not upgrade database file $dbfile: $!"; +# } +# for my $dbfile (<$newdbdir/*.db4>) { +# debug(2, "Upgrading database file $dbfile . . .\n"); +# system("db_upgrade -h $newdbdir $dbfile") == 0 or +# die "Error: could not upgrade database file $dbfile: $!"; +# } +# } + +# sub updateDBVERSION { +# my $newdbdir = shift; +# my $fname = "$newdbdir/DBVERSION"; +# my @flist = ($fname); +# push @flist, glob("$newdbdir/*/DBVERSION"); +# for $fname (@flist) { +# if (-f $fname) { +# debug(2, "Updating $fname to $db_verstr\n"); +# open(FNAME, ">$fname") or die "Can't write $fname: $!"; +# print FNAME $db_verstr, "\n"; +# close FNAME; +# } else { +# debug(0, "No $fname - skipping\n"); +# } +# } +# } + +# sub updateDBguardian { +# my $newdbdir = shift; +# my $fname = "$newdbdir/guardian"; +# my @flist = ($fname); +# push @flist, glob("$newdbdir/*/guardian"); +# for $fname (@flist) { +# if (-f $fname) { +# debug(2, "Updating $fname to $db_verstr\n"); +# open(FNAME, "$fname") or die "Can't read $fname: $!"; +# my @lines = <FNAME>; +# close FNAME; +# open(FNAME, ">$fname") or die "Can't write $fname: $!"; +# for (@lines) { +# if (/^version:/) { +# print FNAME "version:$db_verstr\n"; +# } else { +# print FNAME; +# } +# } +# close FNAME; +# } else { +# debug(0, "No $fname - skipping\n"); +# } +# } +# } diff --git a/ldap/servers/slapd/tools/migratecred.c b/ldap/servers/slapd/tools/migratecred.c index 4c764a717..83f26674d 100644 --- a/ldap/servers/slapd/tools/migratecred.c +++ b/ldap/servers/slapd/tools/migratecred.c @@ -46,6 +46,9 @@ #include <limits.h> #include <stdarg.h> #include <stdlib.h> +#ifdef HAVE_UNISTD_H +#include <unistd.h> +#endif #ifndef _WIN32 #include <sys/param.h> /* MAXPATHLEN */ @@ -56,7 +59,8 @@ static void usage(char *name) { - fprintf(stderr, "usage: %s -o 5.0InstancePath -n 5.1InstancePath -c 5.0Credential\n", name); + fprintf(stderr, "usage: %s -o OldInstancePath -n NewInstancePath -c OldCredential [-p NewPluginPath]\n", name); + fprintf(stderr, "New plugin path defaults to [%s] if not given\n", PLUGINDIR); exit(1); } @@ -76,18 +80,18 @@ static void dostounixpath(char *szText) } #endif -/* Script used during 5.0 to 5.1 migration: replication and +/* Script used during migration: replication and chaining backend credentials must be converted. Assumption: the built-in des-plugin.so lib has been used - in 5.0 and is used in 5.1 + in the old version and is used in the new version Usage: migrateCred - -o <5.0 instance path> - -n <5.1 instance path> - -c <5.0 credential, with prefix> + -o <old instance path> + -n <new instance path> + -c <old credential, with prefix> - Return 5.1 credential with prefix + Return new credential with prefix */ int @@ -96,6 +100,7 @@ main( int argc, char **argv) char *cmd = argv[0]; char *oldpath = NULL; char *newpath = NULL; + char *pluginpath = NULL; char *prefixCred = NULL; char *cred = NULL; @@ -104,7 +109,7 @@ main( int argc, char **argv) char libpath[MAXPATHLEN]; char *shared_lib; - char *opts = "o:n:c:"; + char *opts = "o:n:c:p:"; int i; while (( i = getopt( argc, argv, opts )) != EOF ) @@ -143,6 +148,13 @@ main( int argc, char **argv) fprintf(stderr, "Invalid -c argument: %s (wrong prefix?).\n", prefixCred); } } + break; + case 'p': + pluginpath = strdup(optarg); +#ifdef _WIN32 + dostounixpath(pluginpath); +#endif /* _WIN32 */ + break; default: usage(cmd); @@ -177,13 +189,26 @@ main( int argc, char **argv) #endif #endif - snprintf(libpath, sizeof(libpath), "%s/../lib/des-plugin%s", newpath, shared_lib); - libpath[sizeof(libpath)-1] = 0; + if (!pluginpath) { + pluginpath = strdup(PLUGINDIR); +#ifdef _WIN32 + dostounixpath(pluginpath); +#endif /* _WIN32 */ + } + + if (access(pluginpath, R_OK)) { + snprintf(libpath, sizeof(libpath), "%s/../lib/des-plugin%s", newpath, shared_lib); + libpath[sizeof(libpath)-1] = 0; + } else { + snprintf(libpath, sizeof(libpath), "%s/libdes-plugin%s", pluginpath, shared_lib); + libpath[sizeof(libpath)-1] = 0; + } fct = (migrate_fn_type)sym_load(libpath, "migrateCredentials", "DES Plugin", 1 /* report errors */ ); if ( fct == NULL ) { + usage(cmd); return(1); }
0
d98428a7ce012615e190c48d82e25909d9ae271a
389ds/389-ds-base
Ticket 4326 - entryuuid fixup did not work correctly (#4328) Bug Description: due to an oversight in how fixup tasks worked, the entryuuid fixup task did not work correctly and would not persist over restarts. Fix Description: Correctly implement entryuuid fixup. fixes: #4326 Author: William Brown <[email protected]> Review by: mreynolds (thanks!)
commit d98428a7ce012615e190c48d82e25909d9ae271a Author: Firstyear <[email protected]> Date: Wed Sep 23 09:19:34 2020 +1000 Ticket 4326 - entryuuid fixup did not work correctly (#4328) Bug Description: due to an oversight in how fixup tasks worked, the entryuuid fixup task did not work correctly and would not persist over restarts. Fix Description: Correctly implement entryuuid fixup. fixes: #4326 Author: William Brown <[email protected]> Review by: mreynolds (thanks!) diff --git a/dirsrvtests/tests/suites/entryuuid/basic_test.py b/dirsrvtests/tests/suites/entryuuid/basic_test.py index beb73701d..4d8a40909 100644 --- a/dirsrvtests/tests/suites/entryuuid/basic_test.py +++ b/dirsrvtests/tests/suites/entryuuid/basic_test.py @@ -12,6 +12,7 @@ import time import shutil from lib389.idm.user import nsUserAccounts, UserAccounts from lib389.idm.account import Accounts +from lib389.idm.domain import Domain from lib389.topologies import topology_st as topology from lib389.backend import Backends from lib389.paths import Paths @@ -190,6 +191,7 @@ def test_entryuuid_fixup_task(topology): 3. Enable the entryuuid plugin 4. Run the fixup 5. Assert the entryuuid now exists + 6. Restart and check they persist :expectedresults: 1. Success @@ -197,6 +199,7 @@ def test_entryuuid_fixup_task(topology): 3. Success 4. Success 5. Suddenly EntryUUID! + 6. Still has EntryUUID! """ # 1. Disable the plugin plug = EntryUUIDPlugin(topology.standalone) @@ -220,7 +223,22 @@ def test_entryuuid_fixup_task(topology): assert(task.is_complete() and task.get_exit_code() == 0) topology.standalone.config.loglevel(vals=(ErrorLog.DEFAULT,)) - # 5. Assert the uuid. - euuid = account.get_attr_val_utf8('entryUUID') - assert(euuid is not None) + # 5.1 Assert the uuid on the user. + euuid_user = account.get_attr_val_utf8('entryUUID') + assert(euuid_user is not None) + + # 5.2 Assert it on the domain entry. + domain = Domain(topology.standalone, dn=DEFAULT_SUFFIX) + euuid_domain = domain.get_attr_val_utf8('entryUUID') + assert(euuid_domain is not None) + + # Assert it persists after a restart. + topology.standalone.restart() + # 6.1 Assert the uuid on the use. + euuid_user_2 = account.get_attr_val_utf8('entryUUID') + assert(euuid_user_2 == euuid_user) + + # 6.2 Assert it on the domain entry. + euuid_domain_2 = domain.get_attr_val_utf8('entryUUID') + assert(euuid_domain_2 == euuid_domain) diff --git a/src/plugins/entryuuid/src/lib.rs b/src/plugins/entryuuid/src/lib.rs index 6b5e8d1bb..92977db05 100644 --- a/src/plugins/entryuuid/src/lib.rs +++ b/src/plugins/entryuuid/src/lib.rs @@ -187,9 +187,46 @@ impl SlapiPlugin3 for EntryUuid { } } -pub fn entryuuid_fixup_mapfn(mut e: EntryRef, _data: &()) -> Result<(), PluginError> { - assign_uuid(&mut e); - Ok(()) +pub fn entryuuid_fixup_mapfn(e: &EntryRef, _data: &()) -> Result<(), PluginError> { + /* Supply a modification to the entry. */ + let sdn = e.get_sdnref(); + + /* Sanity check that entryuuid doesn't already exist */ + if e.contains_attr("entryUUID") { + log_error!( + ErrorLevel::Trace, + "skipping fixup for -> {}", + sdn.to_dn_string() + ); + return Ok(()); + } + + // Setup the modifications + let mut mods = SlapiMods::new(); + + let u: Uuid = Uuid::new_v4(); + let uuid_value = Value::from(&u); + let values: ValueArray = std::iter::once(uuid_value).collect(); + mods.append(ModType::Replace, "entryUUID", values); + + /* */ + let lmod = Modify::new(&sdn, mods, plugin_id())?; + + match lmod.execute() { + Ok(_) => { + log_error!(ErrorLevel::Trace, "fixed-up -> {}", sdn.to_dn_string()); + Ok(()) + } + Err(e) => { + log_error!( + ErrorLevel::Error, + "entryuuid_fixup_mapfn -> fixup failed -> {} {:?}", + sdn.to_dn_string(), + e + ); + Err(PluginError::GenericFailure) + } + } } #[cfg(test)] diff --git a/src/slapi_r_plugin/src/constants.rs b/src/slapi_r_plugin/src/constants.rs index cf76ccbdb..34845c2f4 100644 --- a/src/slapi_r_plugin/src/constants.rs +++ b/src/slapi_r_plugin/src/constants.rs @@ -5,6 +5,11 @@ use std::os::raw::c_char; pub const LDAP_SUCCESS: i32 = 0; pub const PLUGIN_DEFAULT_PRECEDENCE: i32 = 50; +#[repr(i32)] +pub enum OpFlags { + ByassReferrals = 0x0040_0000, +} + #[repr(i32)] /// The set of possible function handles we can register via the pblock. These /// values correspond to slapi-plugin.h. diff --git a/src/slapi_r_plugin/src/entry.rs b/src/slapi_r_plugin/src/entry.rs index 034efe692..22ae45189 100644 --- a/src/slapi_r_plugin/src/entry.rs +++ b/src/slapi_r_plugin/src/entry.rs @@ -70,6 +70,14 @@ impl EntryRef { } } + pub fn contains_attr(&self, name: &str) -> bool { + let cname = CString::new(name).expect("invalid attr name"); + let va = unsafe { slapi_entry_attr_get_valuearray(self.raw_e, cname.as_ptr()) }; + + // If it's null, it's not present, so flip the logic. + !va.is_null() + } + pub fn add_value(&mut self, a: &str, v: &ValueRef) { // turn the attr to a c string. // TODO FIX diff --git a/src/slapi_r_plugin/src/lib.rs b/src/slapi_r_plugin/src/lib.rs index e589057b6..be28cac95 100644 --- a/src/slapi_r_plugin/src/lib.rs +++ b/src/slapi_r_plugin/src/lib.rs @@ -11,6 +11,7 @@ pub mod dn; pub mod entry; pub mod error; pub mod log; +pub mod modify; pub mod pblock; pub mod plugin; pub mod search; @@ -27,6 +28,7 @@ pub mod prelude { pub use crate::entry::EntryRef; pub use crate::error::{DseCallbackStatus, LDAPError, PluginError, RPluginError}; pub use crate::log::{log_error, ErrorLevel}; + pub use crate::modify::{ModType, Modify, SlapiMods}; pub use crate::pblock::{Pblock, PblockRef}; pub use crate::plugin::{register_plugin_ext, PluginIdRef, SlapiPlugin3}; pub use crate::search::{Search, SearchScope}; diff --git a/src/slapi_r_plugin/src/macros.rs b/src/slapi_r_plugin/src/macros.rs index a185470db..97fc5d7ef 100644 --- a/src/slapi_r_plugin/src/macros.rs +++ b/src/slapi_r_plugin/src/macros.rs @@ -828,7 +828,7 @@ macro_rules! slapi_r_search_callback_mapfn { let e = EntryRef::new(raw_e); let data_ptr = raw_data as *const _; let data = unsafe { &(*data_ptr) }; - match $cb_mod_ident(e, data) { + match $cb_mod_ident(&e, data) { Ok(_) => LDAPError::Success as i32, Err(e) => e as i32, } diff --git a/src/slapi_r_plugin/src/modify.rs b/src/slapi_r_plugin/src/modify.rs new file mode 100644 index 000000000..30864377a --- /dev/null +++ b/src/slapi_r_plugin/src/modify.rs @@ -0,0 +1,118 @@ +use crate::constants::OpFlags; +use crate::dn::SdnRef; +use crate::error::{LDAPError, PluginError}; +use crate::pblock::Pblock; +use crate::plugin::PluginIdRef; +use crate::value::{slapi_value, ValueArray}; + +use std::ffi::CString; +use std::ops::{Deref, DerefMut}; +use std::os::raw::c_char; + +extern "C" { + fn slapi_modify_internal_set_pb_ext( + pb: *const libc::c_void, + dn: *const libc::c_void, + mods: *const *const libc::c_void, + controls: *const *const libc::c_void, + uniqueid: *const c_char, + plugin_ident: *const libc::c_void, + op_flags: i32, + ); + fn slapi_modify_internal_pb(pb: *const libc::c_void); + fn slapi_mods_free(smods: *const *const libc::c_void); + fn slapi_mods_get_ldapmods_byref(smods: *const libc::c_void) -> *const *const libc::c_void; + fn slapi_mods_new() -> *const libc::c_void; + fn slapi_mods_add_mod_values( + smods: *const libc::c_void, + mtype: i32, + attrtype: *const c_char, + value: *const *const slapi_value, + ); +} + +#[derive(Debug)] +#[repr(i32)] +pub enum ModType { + Add = 0, + Delete = 1, + Replace = 2, +} + +pub struct SlapiMods { + inner: *const libc::c_void, + vas: Vec<ValueArray>, +} + +impl Drop for SlapiMods { + fn drop(&mut self) { + unsafe { slapi_mods_free(&self.inner as *const *const libc::c_void) } + } +} + +impl SlapiMods { + pub fn new() -> Self { + SlapiMods { + inner: unsafe { slapi_mods_new() }, + vas: Vec::new(), + } + } + + pub fn append(&mut self, modtype: ModType, attrtype: &str, values: ValueArray) { + // We can get the value array pointer here to push to the inner + // because the internal pointers won't change even when we push them + // to the list to preserve their lifetime. + let vas = values.as_ptr(); + // We take ownership of this to ensure it lives as least as long as our + // slapimods structure. + self.vas.push(values); + // now we can insert these to the modes. + let c_attrtype = CString::new(attrtype).expect("failed to allocate attrtype"); + unsafe { slapi_mods_add_mod_values(self.inner, modtype as i32, c_attrtype.as_ptr(), vas) }; + } +} + +pub struct Modify { + pb: Pblock, + mods: SlapiMods, +} + +pub struct ModifyResult { + pb: Pblock, +} + +impl Modify { + pub fn new(dn: &SdnRef, mods: SlapiMods, plugin_id: PluginIdRef) -> Result<Self, PluginError> { + let pb = Pblock::new(); + let lmods = unsafe { slapi_mods_get_ldapmods_byref(mods.inner) }; + // OP_FLAG_ACTION_LOG_ACCESS + + unsafe { + slapi_modify_internal_set_pb_ext( + pb.deref().as_ptr(), + dn.as_ptr(), + lmods, + std::ptr::null(), + std::ptr::null(), + plugin_id.raw_pid, + OpFlags::ByassReferrals as i32, + ) + }; + + Ok(Modify { pb, mods }) + } + + pub fn execute(self) -> Result<ModifyResult, LDAPError> { + let Modify { + mut pb, + mods: _mods, + } = self; + unsafe { slapi_modify_internal_pb(pb.deref().as_ptr()) }; + let result = pb.get_op_result(); + + match result { + 0 => Ok(ModifyResult { pb }), + _e => Err(LDAPError::from(result)), + } + } +} diff --git a/src/slapi_r_plugin/src/pblock.rs b/src/slapi_r_plugin/src/pblock.rs index b69ce1680..0f83914f3 100644 --- a/src/slapi_r_plugin/src/pblock.rs +++ b/src/slapi_r_plugin/src/pblock.rs @@ -11,6 +11,7 @@ pub use crate::log::{log_error, ErrorLevel}; extern "C" { fn slapi_pblock_set(pb: *const libc::c_void, arg: i32, value: *const libc::c_void) -> i32; fn slapi_pblock_get(pb: *const libc::c_void, arg: i32, value: *const libc::c_void) -> i32; + fn slapi_pblock_destroy(pb: *const libc::c_void); fn slapi_pblock_new() -> *const libc::c_void; } @@ -41,6 +42,12 @@ impl DerefMut for Pblock { } } +impl Drop for Pblock { + fn drop(&mut self) { + unsafe { slapi_pblock_destroy(self.value.raw_pb) } + } +} + pub struct PblockRef { raw_pb: *const libc::c_void, } diff --git a/src/slapi_r_plugin/src/value.rs b/src/slapi_r_plugin/src/value.rs index 5a40dd279..46246837a 100644 --- a/src/slapi_r_plugin/src/value.rs +++ b/src/slapi_r_plugin/src/value.rs @@ -96,6 +96,10 @@ impl ValueArray { let bs = vs.into_boxed_slice(); Box::leak(bs) as *const _ as *const *const slapi_value } + + pub fn as_ptr(&self) -> *const *const slapi_value { + self.data.as_ptr() as *const *const slapi_value + } } impl FromIterator<Value> for ValueArray {
0
dd7d487abd35314636b9a66a78ff9330b06f6ca5
389ds/389-ds-base
Issue 5734 - RFE - Exclude pwdFailureTime and ContextCSN (#5735) Bug Description: A customer reported an issue with openldap to 389ds migration. This was due to their openldap instance using a number of openldap attributes that I had not encountered in other migrations. These attributes are operational to openldap only and can be safely excluded. Fix Description: Exclude pwdFailureTime and ContextCSN fixes: https://github.com/389ds/389-ds-base/issues/5734 Author: William Brown <[email protected]> Review by: ???
commit dd7d487abd35314636b9a66a78ff9330b06f6ca5 Author: Firstyear <[email protected]> Date: Fri Apr 21 10:29:09 2023 +1000 Issue 5734 - RFE - Exclude pwdFailureTime and ContextCSN (#5735) Bug Description: A customer reported an issue with openldap to 389ds migration. This was due to their openldap instance using a number of openldap attributes that I had not encountered in other migrations. These attributes are operational to openldap only and can be safely excluded. Fix Description: Exclude pwdFailureTime and ContextCSN fixes: https://github.com/389ds/389-ds-base/issues/5734 Author: William Brown <[email protected]> Review by: ??? diff --git a/src/lib389/lib389/migrate/plan.py b/src/lib389/lib389/migrate/plan.py index 89677c716..c60fb1527 100644 --- a/src/lib389/lib389/migrate/plan.py +++ b/src/lib389/lib389/migrate/plan.py @@ -662,6 +662,7 @@ class Migration(object): [ # Core openldap attrs that we can't use, and don't matter. 'entrycsn', + 'contextcsn', 'structuralobjectclass', # pwd attributes from ppolicy which are not supported. 'pwdattribute', @@ -669,6 +670,8 @@ class Migration(object): 'pwdsafemodify', 'pwdcheckmodule', 'pwdmaxrecordedfailure', + # ppolicy attr that isn't in schema that isn't supported. + 'pwdfailuretime', # dds attributes we don't support 'dgidentity', 'dgauthz'
0
e1ce0261ad2787a1e048af704d42a073ee05f8f8
389ds/389-ds-base
Issue 43 - Add support for Referential Integrity plugin Description: Add dsconf support for configuring the Referential Integrity plugin from the command line, along with functional tests for testing its functionality. https://pagure.io/lib389/issue/43 Author: Ilias95 Review by: wibrown (Thanks!)
commit e1ce0261ad2787a1e048af704d42a073ee05f8f8 Author: Ilias Stamatis <[email protected]> Date: Tue Aug 15 20:48:57 2017 +0300 Issue 43 - Add support for Referential Integrity plugin Description: Add dsconf support for configuring the Referential Integrity plugin from the command line, along with functional tests for testing its functionality. https://pagure.io/lib389/issue/43 Author: Ilias95 Review by: wibrown (Thanks!) diff --git a/src/lib389/cli/dsconf b/src/lib389/cli/dsconf index 73d12a24e..ea1d056a8 100755 --- a/src/lib389/cli/dsconf +++ b/src/lib389/cli/dsconf @@ -26,6 +26,7 @@ from lib389.cli_conf.plugins import memberof as cli_memberof from lib389.cli_conf.plugins import usn as cli_usn from lib389.cli_conf.plugins import rootdn_ac as cli_rootdn_ac from lib389.cli_conf.plugins import whoami as cli_whoami +from lib389.cli_conf.plugins import referint as cli_referint from lib389.cli_base import disconnect_instance, connect_instance from lib389.cli_base.dsrc import dsrc_to_ldap, dsrc_arg_concat @@ -71,6 +72,7 @@ if __name__ == '__main__': cli_usn.create_parser(subparsers) cli_rootdn_ac.create_parser(subparsers) cli_whoami.create_parser(subparsers) + cli_referint.create_parser(subparsers) args = parser.parse_args() diff --git a/src/lib389/lib389/cli_conf/plugins/referint.py b/src/lib389/lib389/cli_conf/plugins/referint.py new file mode 100644 index 000000000..9d52b89cc --- /dev/null +++ b/src/lib389/lib389/cli_conf/plugins/referint.py @@ -0,0 +1,197 @@ +# --- BEGIN COPYRIGHT BLOCK --- +# Copyright (C) 2016-2017 Red Hat, Inc. +# All rights reserved. +# +# License: GPL (version 3 or any later version). +# See LICENSE for details. +# --- END COPYRIGHT BLOCK --- + +import ldap + +from lib389.plugins import ReferentialIntegrityPlugin +from lib389.cli_conf.plugin import add_generic_plugin_parsers + + +def manage_update_delay(inst, basedn, log, args): + plugin = ReferentialIntegrityPlugin(inst) + if args.value is None: + val = plugin.get_update_delay_formatted() + log.info(val) + else: + plugin.set_update_delay(args.value) + log.info('referint-update-delay set to "{}"'.format(args.value)) + +def display_membership_attr(inst, basedn, log, args): + plugin = ReferentialIntegrityPlugin(inst) + log.info(plugin.get_membership_attr_formatted()) + +def add_membership_attr(inst, basedn, log, args): + plugin = ReferentialIntegrityPlugin(inst) + try: + plugin.add_membership_attr(args.value) + except ldap.TYPE_OR_VALUE_EXISTS: + log.info('Value "{}" already exists.'.format(args.value)) + else: + log.info('successfully added membership attribute "{}"'.format(args.value)) + +def remove_membership_attr(inst, basedn, log, args): + plugin = ReferentialIntegrityPlugin(inst) + try: + plugin.remove_membership_attr(args.value) + except ldap.OPERATIONS_ERROR: + log.error("Error: Failed to delete. At least one value for membership attribute should exist.") + except ldap.NO_SUCH_ATTRIBUTE: + log.error('Error: Failed to delete. No value "{0}" found.'.format(args.value)) + else: + log.info('successfully removed membership attribute "{}"'.format(args.value)) + +def display_scope(inst, basedn, log, args): + plugin = ReferentialIntegrityPlugin(inst) + val = plugin.get_entryscope_formatted() + if not val: + log.info("nsslapd-pluginEntryScope is not set") + else: + log.info(val) + +def add_scope(inst, basedn, log, args): + plugin = ReferentialIntegrityPlugin(inst) + try: + plugin.add_entryscope(args.value) + except ldap.TYPE_OR_VALUE_EXISTS: + log.info('Value "{}" already exists.'.format(args.value)) + else: + log.info('successfully added nsslapd-pluginEntryScope value "{}"'.format(args.value)) + +def remove_scope(inst, basedn, log, args): + plugin = ReferentialIntegrityPlugin(inst) + try: + plugin.remove_entryscope(args.value) + except ldap.NO_SUCH_ATTRIBUTE: + log.error('Error: Failed to delete. No value "{0}" found.'.format(args.value)) + else: + log.info('successfully removed nsslapd-pluginEntryScope value "{}"'.format(args.value)) + +def remove_all_scope(inst, basedn, log, args): + plugin = ReferentialIntegrityPlugin(inst) + plugin.remove_all_entryscope() + log.info('successfully removed all nsslapd-pluginEntryScope values') + +def display_excludescope(inst, basedn, log, args): + plugin = ReferentialIntegrityPlugin(inst) + val = plugin.get_excludescope_formatted() + if not val: + log.info("nsslapd-pluginExcludeEntryScope is not set") + else: + log.info(val) + +def add_excludescope(inst, basedn, log, args): + plugin = ReferentialIntegrityPlugin(inst) + try: + plugin.add_excludescope(args.value) + except ldap.TYPE_OR_VALUE_EXISTS: + log.info('Value "{}" already exists.'.format(args.value)) + else: + log.info('successfully added nsslapd-pluginExcludeEntryScope value "{}"'.format(args.value)) + +def remove_excludescope(inst, basedn, log, args): + plugin = ReferentialIntegrityPlugin(inst) + try: + plugin.remove_excludescope(args.value) + except ldap.NO_SUCH_ATTRIBUTE: + log.error('Error: Failed to delete. No value "{0}" found.'.format(args.value)) + else: + log.info('successfully removed nsslapd-pluginExcludeEntryScope value "{}"'.format(args.value)) + +def remove_all_excludescope(inst, basedn, log, args): + plugin = ReferentialIntegrityPlugin(inst) + plugin.remove_all_excludescope() + log.info('successfully removed all nsslapd-pluginExcludeEntryScope values') + +def display_container_scope(inst, basedn, log, args): + plugin = ReferentialIntegrityPlugin(inst) + val = plugin.get_container_scope_formatted() + if not val: + log.info("nsslapd-pluginContainerScope is not set") + else: + log.info(val) + +def add_container_scope(inst, basedn, log, args): + plugin = ReferentialIntegrityPlugin(inst) + try: + plugin.add_container_scope(args.value) + except ldap.TYPE_OR_VALUE_EXISTS: + log.info('Value "{}" already exists.'.format(args.value)) + else: + log.info('successfully added nsslapd-pluginContainerScope value "{}"'.format(args.value)) + +def remove_container_scope(inst, basedn, log, args): + plugin = ReferentialIntegrityPlugin(inst) + try: + plugin.remove_container_scope(args.value) + except ldap.NO_SUCH_ATTRIBUTE: + log.error('Error: Failed to delete. No value "{0}" found.'.format(args.value)) + else: + log.info('successfully removed nsslapd-pluginContainerScope value "{}"'.format(args.value)) + +def remove_all_container_scope(inst, basedn, log, args): + plugin = ReferentialIntegrityPlugin(inst) + plugin.remove_all_container_scope() + log.info('successfully removed all nsslapd-pluginContainerScope values') + + +def create_parser(subparsers): + referint_parser = subparsers.add_parser('referint', help='Manage and configure Referential Integrity plugin') + + subcommands = referint_parser.add_subparsers(help='action') + + add_generic_plugin_parsers(subcommands, ReferentialIntegrityPlugin) + + delay_parser = subcommands.add_parser('delay', help='get or set update delay') + delay_parser.set_defaults(func=manage_update_delay) + delay_parser.add_argument('value', nargs='?', help='The value to set as update delay') + + attr_parser = subcommands.add_parser('attrs', help='get or manage membership attributes') + attr_parser.set_defaults(func=display_membership_attr) + attr_subcommands = attr_parser.add_subparsers(help='action') + add_attr_parser = attr_subcommands.add_parser('add', help='add membership attribute') + add_attr_parser.set_defaults(func=add_membership_attr) + add_attr_parser.add_argument('value', help='membership attribute to add') + del_attr_parser = attr_subcommands.add_parser('del', help='remove membership attribute') + del_attr_parser.set_defaults(func=remove_membership_attr) + del_attr_parser.add_argument('value', help='membership attribute to remove') + + scope_parser = subcommands.add_parser('scope', help='get or manage referint scope') + scope_parser.set_defaults(func=display_scope) + scope_subcommands = scope_parser.add_subparsers(help='action') + add_scope_parser = scope_subcommands.add_parser('add', help='add entry scope value') + add_scope_parser.set_defaults(func=add_scope) + add_scope_parser.add_argument('value', help='The value to add in referint entry scope') + del_scope_parser = scope_subcommands.add_parser('del', help='remove entry scope value') + del_scope_parser.set_defaults(func=remove_scope) + del_scope_parser.add_argument('value', help='The value to remove from entry scope') + delall_scope_parser = scope_subcommands.add_parser('delall', help='remove all entry scope values') + delall_scope_parser.set_defaults(func=remove_all_scope) + + exclude_parser = subcommands.add_parser('exclude', help='get or manage referint exclude scope') + exclude_parser.set_defaults(func=display_excludescope) + exclude_subcommands = exclude_parser.add_subparsers(help='action') + add_exclude_parser = exclude_subcommands.add_parser('add', help='add exclude scope value') + add_exclude_parser.set_defaults(func=add_excludescope) + add_exclude_parser.add_argument('value', help='The value to add in exclude scope') + del_exclude_parser = exclude_subcommands.add_parser('del', help='remove exclude scope value') + del_exclude_parser.set_defaults(func=remove_excludescope) + del_exclude_parser.add_argument('value', help='The value to remove from exclude scope') + delall_exclude_parser = exclude_subcommands.add_parser('delall', help='remove all exclude scope values') + delall_exclude_parser.set_defaults(func=remove_all_excludescope) + + container_parser = subcommands.add_parser('container', help='get or manage referint container scope') + container_parser.set_defaults(func=display_container_scope) + container_subcommands = container_parser.add_subparsers(help='action') + add_container_parser = container_subcommands.add_parser('add', help='add container scope value') + add_container_parser.set_defaults(func=add_container_scope) + add_container_parser.add_argument('value', help='The value to add in container scope') + del_container_parser = container_subcommands.add_parser('del', help='remove container scope value') + del_container_parser.set_defaults(func=remove_container_scope) + del_container_parser.add_argument('value', help='The value to remove from container scope') + delall_container_parser = container_subcommands.add_parser('delall', help='remove all container scope values') + delall_container_parser.set_defaults(func=remove_all_container_scope) diff --git a/src/lib389/lib389/plugins.py b/src/lib389/lib389/plugins.py index 61567fe1f..d683f21a9 100644 --- a/src/lib389/lib389/plugins.py +++ b/src/lib389/lib389/plugins.py @@ -8,6 +8,7 @@ import ldap import copy +import os.path from lib389 import tasks from lib389._mapped_object import DSLdapObjects, DSLdapObject @@ -118,23 +119,111 @@ class ManagedEntriesPlugin(Plugin): # Because there are potentially many MEP configs. class ReferentialIntegrityPlugin(Plugin): + _plugin_properties = { + 'cn' : 'referential integrity postoperation', + 'nsslapd-pluginEnabled': 'off', + 'nsslapd-pluginPath': 'libreferint-plugin', + 'nsslapd-pluginInitfunc': 'referint_postop_init', + 'nsslapd-pluginType': 'betxnpostoperation', + 'nsslapd-pluginprecedence': '40', + 'nsslapd-plugin-depends-on-type': 'database', + 'referint-update-delay': '0', + 'referint-membership-attr': ['member', 'uniquemember', 'owner', 'seeAlso',], + 'nsslapd-pluginId' : 'referint', + 'nsslapd-pluginVendor' : '389 Project', + 'nsslapd-pluginVersion' : '1.3.7.0', + 'nsslapd-pluginDescription' : 'referential integrity plugin', + } + def __init__(self, instance, dn="cn=referential integrity postoperation,cn=plugins,cn=config", batch=False): super(ReferentialIntegrityPlugin, self).__init__(instance, dn, batch) + self._create_objectclasses.extend(['extensibleObject']) + self._must_attributes.extend([ + 'referint-update-delay', + 'referint-logfile', + 'referint-membership-attr', + ]) self._lint_functions = [self._lint_update_delay] + def create(self, rdn=None, properties=None, basedn=None): + referint_log = os.path.join(self._instance.ds_paths.log_dir, "referint") + if properties is None: + properties = {'referint-logfile': referint_log} + else: + properties['referint-logfile'] = referint_log + return super(ReferentialIntegrityPlugin, self).create(rdn, properties, basedn) + def _lint_update_delay(self): if self.status(): delay = self.get_attr_val_int("referint-update-delay") if delay is not None and delay != 0: return DSRILE0001 - # referint-update-delay: 0 - # referint-logfile: /opt/dirsrv/var/log/dirsrv/slapd-standalone_2/referint - # referint-logchanges: 0 - # referint-membership-attr: member - # referint-membership-attr: uniquemember - # referint-membership-attr: owner - # referint-membership-attr: seeAlso + def get_update_delay(self): + return self.get_attr_val_int('referint-update-delay') + + def get_update_delay_formatted(self): + return self.display_attr('referint-update-delay') + + def set_update_delay(self, value): + self.set('referint-update-delay', str(value)) + + def get_membership_attr(self, formatted=False): + return self.get_attr_vals_utf8('referint-membership-attr') + + def get_membership_attr_formatted(self): + return self.display_attr('referint-membership-attr') + + def add_membership_attr(self, attr): + self.add('referint-membership-attr', attr) + + def remove_membership_attr(self, attr): + self.remove('referint-membership-attr', attr) + + def get_entryscope(self, formatted=False): + return self.get_attr_vals_utf8('nsslapd-pluginentryscope') + + def get_entryscope_formatted(self): + return self.display_attr('nsslapd-pluginentryscope') + + def add_entryscope(self, attr): + self.add('nsslapd-pluginentryscope', attr) + + def remove_entryscope(self, attr): + self.remove('nsslapd-pluginentryscope', attr) + + def remove_all_entryscope(self): + self.remove_all('nsslapd-pluginentryscope') + + def get_excludescope(self): + return self.get_attr_vals_ut8('nsslapd-pluginexcludeentryscope') + + def get_excludescope_formatted(self): + return self.display_attr('nsslapd-pluginexcludeentryscope') + + def add_excludescope(self, attr): + self.add('nsslapd-pluginexcludeentryscope', attr) + + def remove_excludescope(self, attr): + self.remove('nsslapd-pluginexcludeentryscope', attr) + + def remove_all_excludescope(self): + self.remove_all('nsslapd-pluginexcludeentryscope') + + def get_container_scope(self): + return self.get_attr_vals_ut8('nsslapd-plugincontainerscope') + + def get_container_scope_formatted(self): + return self.display_attr('nsslapd-plugincontainerscope') + + def add_container_scope(self, attr): + self.add('nsslapd-plugincontainerscope', attr) + + def remove_container_scope(self, attr): + self.remove('nsslapd-plugincontainerscope', attr) + + def remove_all_container_scope(self): + self.remove_all('nsslapd-plugincontainerscope') class SyntaxValidationPlugin(Plugin): def __init__(self, instance, dn="cn=Syntax Validation Task,cn=plugins,cn=config", batch=False): diff --git a/src/lib389/lib389/tests/cli/conf_plugins/referint_test.py b/src/lib389/lib389/tests/cli/conf_plugins/referint_test.py new file mode 100644 index 000000000..8a31ffcf3 --- /dev/null +++ b/src/lib389/lib389/tests/cli/conf_plugins/referint_test.py @@ -0,0 +1,119 @@ +# --- BEGIN COPYRIGHT BLOCK --- +# Copyright (C) 2016-2017 Red Hat, Inc. +# All rights reserved. +# +# License: GPL (version 3 or any later version). +# See LICENSE for details. +# --- END COPYRIGHT BLOCK --- + +import pytest + +from lib389.tests.cli import topology as default_topology +from lib389.cli_base import LogCapture, FakeArgs +from lib389.plugins import ReferentialIntegrityPlugin +from lib389.cli_conf.plugins import referint as referint_cli + + [email protected](scope="module") +def topology(request): + topology = default_topology(request) + + plugin = ReferentialIntegrityPlugin(topology.standalone) + if not plugin.exists(): + plugin.create() + + # we need to restart the server after enabling the plugin + plugin.enable() + topology.standalone.restart() + topology.logcap.flush() + + return topology + + +def test_set_update_delay(topology): + args = FakeArgs() + + args.value = 60 + referint_cli.manage_update_delay(topology.standalone, None, topology.logcap.log, args) + assert topology.logcap.contains('referint-update-delay set to "60"') + topology.logcap.flush() + + args.value = None + referint_cli.manage_update_delay(topology.standalone, None, topology.logcap.log, args) + assert topology.logcap.contains("referint-update-delay: 60") + topology.logcap.flush() + + args.value = 0 + referint_cli.manage_update_delay(topology.standalone, None, topology.logcap.log, args) + assert topology.logcap.contains('referint-update-delay set to "0"') + topology.logcap.flush() + + args.value = None + referint_cli.manage_update_delay(topology.standalone, None, topology.logcap.log, args) + assert topology.logcap.contains("referint-update-delay: 0") + topology.logcap.flush() + +def test_add_membership_attr(topology): + args = FakeArgs() + + args.value = "member2" + referint_cli.add_membership_attr(topology.standalone, None, topology.logcap.log, args) + assert topology.logcap.contains("successfully added membership attribute") + topology.logcap.flush() + + referint_cli.display_membership_attr(topology.standalone, None, topology.logcap.log, args) + assert topology.logcap.contains(": member2") + topology.logcap.flush() + +def test_add_membership_attr_with_value_that_already_exists(topology): + plugin = ReferentialIntegrityPlugin(topology.standalone) + # setup test + if not "uniqueMember" in plugin.get_membership_attr(): + plugin.add_membership_attr("uniqueMember") + + args = FakeArgs() + + args.value = "uniqueMember" + referint_cli.add_membership_attr(topology.standalone, None, topology.logcap.log, args) + assert topology.logcap.contains("already exists") + topology.logcap.flush() + +def test_remove_membership_attr_with_value_that_exists(topology): + plugin = ReferentialIntegrityPlugin(topology.standalone) + # setup test + if not "uniqueMember" in plugin.get_membership_attr(): + plugin.add_membership_attr("uniqueMember") + + args = FakeArgs() + + args.value = "uniqueMember" + referint_cli.remove_membership_attr(topology.standalone, None, topology.logcap.log, args) + assert topology.logcap.contains("successfully removed membership attribute") + topology.logcap.flush() + + referint_cli.display_membership_attr(topology.standalone, None, topology.logcap.log, args) + assert not topology.logcap.contains(": uniqueMember") + topology.logcap.flush() + +def test_remove_membership_attr_with_value_that_doesnt_exist(topology): + args = FakeArgs() + + args.value = "whatever" + referint_cli.remove_membership_attr(topology.standalone, None, topology.logcap.log, args) + assert topology.logcap.contains('No value "{0}" found'.format(args.value)) + topology.logcap.flush() + +def test_try_remove_all_membership_attr_values(topology): + plugin = ReferentialIntegrityPlugin(topology.standalone) + #setup test + membership_values = plugin.get_membership_attr() + assert len(membership_values) > 0 + for val in membership_values[:-1]: + plugin.remove_membership_attr(val) + + args = FakeArgs() + + args.value = membership_values[-1] + referint_cli.remove_membership_attr(topology.standalone, None, topology.logcap.log, args) + assert topology.logcap.contains("Error: Failed to delete. At least one value for membership attribute should exist.") + topology.logcap.flush() diff --git a/src/lib389/lib389/tests/plugins/referint_test.py b/src/lib389/lib389/tests/plugins/referint_test.py new file mode 100644 index 000000000..53500d9d9 --- /dev/null +++ b/src/lib389/lib389/tests/plugins/referint_test.py @@ -0,0 +1,83 @@ +# --- BEGIN COPYRIGHT BLOCK --- +# Copyright (C) 2016-2017 Red Hat, Inc. +# All rights reserved. +# +# License: GPL (version 3 or any later version). +# See LICENSE for details. +# --- END COPYRIGHT BLOCK --- +# + +import pytest + +from lib389.topologies import topology_st +from lib389.plugins import ReferentialIntegrityPlugin +from lib389.tests.plugins.utils import ( + create_test_user, create_test_group, delete_objects) + + [email protected](scope="module") +def plugin(request): + return ReferentialIntegrityPlugin(topology_st(request).standalone) + + +def test_referint_enable_disable(plugin): + """ + Test that the plugin doesn't do anything while disabled, and functions + properly when enabled. + + NOTICE: This test case leaves the plugin enabled for the following tests. + """ + # assert plugin is disabled (by default) + assert plugin.status() == False + + user1 = create_test_user(plugin._instance) + group = create_test_group(plugin._instance) + group.add_member(user1.dn) + + user1.delete() + # assert that user was not removed from group because the plugin is disabled + assert group.present(attr='member', value=user1.dn) + + # enable the plugin and restart the server for the action to take effect + plugin.enable() + plugin._instance.restart() + assert plugin.status() == True + + user2 = create_test_user(plugin._instance) + group.add_member(user2.dn) + + user2.delete() + # assert that user was removed from the group as well + assert not group.present(attr='member', value=user2.dn) + + # clean up for subsequent test cases + delete_objects([group]) + +def test_membership_attr(plugin): + """ + Test that the plugin performs integrity updates based on the attributes + defined by referint-membership-attr. + """ + # remove a membership attribute + plugin.remove_membership_attr('uniquemember') + + user1 = create_test_user(plugin._instance) + group = create_test_group(plugin._instance, unique_group=True) + group.add_member(user1.dn) + + user1.delete() + # assert that the user was not removed from the group + assert group.present(attr='uniquemember', value=user1.dn) + + # now put this membership attribute back and try again + plugin.add_membership_attr('uniquemember') + + user2 = create_test_user(plugin._instance) + group.add_member(user2.dn) + + user2.delete() + # assert that user was removed from the group as well + assert not group.present(attr='uniquemember', value=user2.dn) + + # clean up for subsequent test cases + delete_objects([group])
0
632ecb90d96ac0535656f5aaf67fd2be4b81d310
389ds/389-ds-base
Ticket 50251 - clear text passwords visable in CLI verbose mode logging Bug Description: If you run any of the CLI tools using "-v", and set a password, that password will be displayed in clear text in the console. Fix Description: Create an internal list of sensitive attributes to filter, and mask them in the operation debug logging. But still allow the password to be seen if you set the env variable DEBUGGING=true We also still print the root DN password if it is a container installation. https://pagure.io/389-ds-base/issue/50251 Reviewed by: spichugi, firstyear, and mhonek (Thanks!!!)
commit 632ecb90d96ac0535656f5aaf67fd2be4b81d310 Author: Mark Reynolds <[email protected]> Date: Mon May 13 11:58:57 2019 -0400 Ticket 50251 - clear text passwords visable in CLI verbose mode logging Bug Description: If you run any of the CLI tools using "-v", and set a password, that password will be displayed in clear text in the console. Fix Description: Create an internal list of sensitive attributes to filter, and mask them in the operation debug logging. But still allow the password to be seen if you set the env variable DEBUGGING=true We also still print the root DN password if it is a container installation. https://pagure.io/389-ds-base/issue/50251 Reviewed by: spichugi, firstyear, and mhonek (Thanks!!!) diff --git a/src/lib389/lib389/_constants.py b/src/lib389/lib389/_constants.py index 9b720a6b7..ee5ed9e3e 100644 --- a/src/lib389/lib389/_constants.py +++ b/src/lib389/lib389/_constants.py @@ -41,6 +41,12 @@ REPLICATION_BIND_METHOD = RA_METHOD REPLICATION_TRANSPORT = RA_TRANSPORT_PROT REPLICATION_TIMEOUT = RA_TIMEOUT +# Attributes that should be masked from logging output +SENSITIVE_ATTRS = ['userpassword', + 'nsslapd-rootpw', + 'nsds5replicacredentials', + 'nsmultiplexorcredentials'] + TRANS_STARTTLS = "starttls" TRANS_SECURE = "secure" TRANS_NORMAL = "normal" diff --git a/src/lib389/lib389/_entry.py b/src/lib389/lib389/_entry.py index be8d7c55d..041d0c276 100644 --- a/src/lib389/lib389/_entry.py +++ b/src/lib389/lib389/_entry.py @@ -6,7 +6,6 @@ # See LICENSE for details. # --- END COPYRIGHT BLOCK --- -import re import six import logging import ldif @@ -17,12 +16,13 @@ import sys from lib389._constants import * from lib389.properties import * -from lib389.utils import ensure_str, ensure_bytes, ensure_list_bytes +from lib389.utils import (ensure_str, ensure_bytes, ensure_list_bytes, display_log_data) MAJOR, MINOR, _, _, _ = sys.version_info log = logging.getLogger(__name__) + class FormatDict(cidict): def __getitem__(self, name): if name in self: @@ -258,12 +258,13 @@ class Entry(object): def update(self, dct): """Update passthru to the data attribute.""" - log.debug("update dn: %r with %r" % (self.dn, dct)) + log.debug("updating dn: {}".format(self.dn)) for k, v in list(dct.items()): if isinstance(v, list) or isinstance(v, tuple): self.data[k] = v else: self.data[k] = [v] + log.debug("updated dn: {} with {}".format(self.dn, display_log_data(dct))) def __repr__(self): """Convert the Entry to its LDIF representation""" diff --git a/src/lib389/lib389/_mapped_object.py b/src/lib389/lib389/_mapped_object.py index f1a54c3fa..3953a67d6 100644 --- a/src/lib389/lib389/_mapped_object.py +++ b/src/lib389/lib389/_mapped_object.py @@ -7,18 +7,18 @@ # See LICENSE for details. # --- END COPYRIGHT BLOCK --- +import os import ldap import ldap.dn from ldap import filter as ldap_filter import logging import json from functools import partial - from lib389._entry import Entry from lib389._constants import DIRSRV_STATE_ONLINE, SER_ROOT_DN, SER_ROOT_PW from lib389.utils import ( ensure_bytes, ensure_str, ensure_int, ensure_list_bytes, ensure_list_str, - ensure_list_int + ensure_list_int, display_log_value, display_log_data ) # This function filter and term generation provided thanks to @@ -370,7 +370,7 @@ class DSLdapObject(DSLogging): action_txt = "UNKNOWN" if value is None or len(value) < 512: - self._log.debug("%s set %s: (%r, %r)" % (self._dn, action_txt, key, value)) + self._log.debug("%s set %s: (%r, %r)" % (self._dn, action_txt, key, display_log_value(key, value))) else: self._log.debug("%s set %s: (%r, value too large)" % (self._dn, action_txt, key)) if self._instance.state != DIRSRV_STATE_ONLINE: @@ -827,11 +827,11 @@ class DSLdapObject(DSLogging): """ assert(len(self._create_objectclasses) > 0) basedn = ensure_str(basedn) - self._log.debug('Checking "%s" under %s : %s' % (rdn, basedn, properties)) + self._log.debug('Checking "%s" under %s : %s' % (rdn, basedn, display_log_data(properties))) # Add the objectClasses to the properties (dn, valid_props) = self._validate(rdn, properties, basedn) # Check if the entry exists or not? .add_s is going to error anyway ... - self._log.debug('Validated dn %s : valid_props %s' % (dn, valid_props)) + self._log.debug('Validated dn {}'.format(dn)) exists = False @@ -863,8 +863,8 @@ class DSLdapObject(DSLogging): e.update({'objectclass': ensure_list_bytes(self._create_objectclasses)}) e.update(valid_props) # We rely on exceptions here to indicate failure to the parent. - self._log.debug('Creating entry %s : %s' % (dn, e)) self._instance.add_ext_s(e, serverctrls=self._server_controls, clientctrls=self._client_controls, escapehatch='i am sure') + self._log.debug('Created entry %s : %s' % (dn, display_log_data(e.data))) # If it worked, we need to fix our instance dn for the object's self reference. Because # we may not have a self reference yet (just created), it may have changed (someone # set dn, but validate altered it). diff --git a/src/lib389/lib389/instance/setup.py b/src/lib389/lib389/instance/setup.py index c6ca83c72..347eba924 100644 --- a/src/lib389/lib389/instance/setup.py +++ b/src/lib389/lib389/instance/setup.py @@ -438,7 +438,7 @@ class SetupDs(object): backend['suffix'] = val break else: - print("The suffix \"{}\" is not a valid DN") + print("The suffix \"{}\" is not a valid DN".format(val)) continue else: backend['suffix'] = suffix @@ -932,6 +932,10 @@ class SetupDs(object): # Change the root password finally ds_instance.config.set('nsslapd-rootpw', slapd['root_password']) + # We need to log the password when containerised + if self.containerised: + self.log.debug("Root DN password: {}".format(slapd['root_password'])) + # Complete. if general['start']: # Restart for changes to take effect - this could be removed later diff --git a/src/lib389/lib389/tests/utils_test.py b/src/lib389/lib389/tests/utils_test.py index 8104b6293..5378066b6 100644 --- a/src/lib389/lib389/tests/utils_test.py +++ b/src/lib389/lib389/tests/utils_test.py @@ -134,6 +134,17 @@ def test_formatInfData_withconfigserver(): log.info("content: %r" % ret) [email protected]('data', [ + ({'userpaSSwoRd': '1234', 'nsslaPd-rootpw': '5678', 'regularAttr': 'originalvalue'}, + {'userpaSSwoRd': '********', 'nsslaPd-rootpw': '********', 'regularAttr': 'originalvalue'}), + ({'userpassword': ['1', '2', '3'], 'nsslapd-rootpw': ['x']}, + {'userpassword': ['********', '********', '********'], 'nsslapd-rootpw': ['********']}) +]) +def test_get_log_data(data): + before, after = data + assert display_log_data(before) == after + + if __name__ == "__main__": CURRENT_FILE = os.path.realpath(__file__) pytest.main("-s -v %s" % CURRENT_FILE) diff --git a/src/lib389/lib389/utils.py b/src/lib389/lib389/utils.py index a7c1d75a9..49bcad8b7 100644 --- a/src/lib389/lib389/utils.py +++ b/src/lib389/lib389/utils.py @@ -46,7 +46,7 @@ from lib389.paths import Paths from lib389.dseldif import DSEldif from lib389._constants import ( DEFAULT_USER, VALGRIND_WRAPPER, DN_CONFIG, CFGSUFFIX, LOCALHOST, - ReplicaRole, CONSUMER_REPLICAID + ReplicaRole, CONSUMER_REPLICAID, SENSITIVE_ATTRS ) from lib389.properties import ( SER_HOST, SER_USER_ID, SER_GROUP_ID, SER_STRICT_HOSTNAME_CHECKING, SER_PORT, @@ -56,6 +56,8 @@ from lib389.properties import ( MAJOR, MINOR, _, _, _ = sys.version_info +DEBUGGING = os.getenv('DEBUGGING', default=False) + log = logging.getLogger(__name__) # @@ -1200,6 +1202,7 @@ def get_instance_list(prefix=None): insts.sort() return insts + def get_user_is_ds_owner(): # Check if we have permission to administer the DS instance. This is required # for some tasks such as installing, killing, or editing configs for the @@ -1215,6 +1218,7 @@ def get_user_is_ds_owner(): return True return False + def get_user_is_root(): cur_uid = os.getuid() if cur_uid == 0: @@ -1222,9 +1226,26 @@ def get_user_is_root(): return True return False + def basedn_to_ldap_dns_uri(basedn): - # ldap:///dc%3Dexample%2Cdc%3Dcom + # ldap:///dc%3Dexample%2Cdc%3Dcom return "ldaps:///" + basedn.replace("=", "%3D").replace(",", "%2C") +def display_log_value(attr, value, hide_sensitive=True): + # Mask all the sensitive attribute values + if DEBUGGING or not hide_sensitive: + return value + else: + if attr.lower() in SENSITIVE_ATTRS: + if type(value) in (list, tuple): + return list(map(lambda _: '********', value)) + else: + return '********' + else: + return value + +def display_log_data(data, hide_sensitive=True): + # Take a dict and mask all the sensitive data + return {a: display_log_value(a, v, hide_sensitive) for a, v in data.items()}
0
1aa243533d6a6734a732cee97132c5ab6428d64d
389ds/389-ds-base
Resolves: 207457 Summary: Changed the way we specify the memory offset in the slapi_counter_set_value() assembly code to make it work properly with gcc3.
commit 1aa243533d6a6734a732cee97132c5ab6428d64d Author: Nathan Kinder <[email protected]> Date: Fri Nov 21 17:06:05 2008 +0000 Resolves: 207457 Summary: Changed the way we specify the memory offset in the slapi_counter_set_value() assembly code to make it work properly with gcc3. diff --git a/ldap/servers/slapd/slapi_counter.c b/ldap/servers/slapd/slapi_counter.c index 0a43bbbca..c9930d590 100644 --- a/ldap/servers/slapd/slapi_counter.c +++ b/ldap/servers/slapd/slapi_counter.c @@ -306,7 +306,7 @@ PRUint64 slapi_counter_set_value(Slapi_Counter *counter, PRUint64 newvalue) " movl 4%0, %%edx;" /* Put newval in ECX:EBX */ " movl %1, %%ebx;" - " movl 4%1, %%ecx;" + " movl 4+%1, %%ecx;" /* If EDX:EAX and counter-> are the same, * replace *ptr with ECX:EBX */ " lock; cmpxchg8b %0;"
0
274823860ac98b153e7f0bc84d979861c4ca895f
389ds/389-ds-base
Ticket 49330 - Improve ndn cache performance. Bug Description: Normalised DN's are a costly process to update and maintain. As a result, a normalised DN cache was created. Yet it was never able to perform well. In some datasets with large sets of dn attr types, the NDN cache actively hurt performance. The issue stemmed from 3 major issues in the design of the NDN cache. First, it is a global cache which means it exists behind a rwlock. This causes delay as threads wait behind the lock to access or update the cache (especially on a miss). Second, the cache was limited to 4073 buckets. Despite the fact that a prime number on a hash causes a skew in distribution, this was in an NSPR hash - which does not grow dynamically, rather devolving a bucket to a linked list. AS a result, once you passed ~3000 your lookup performance would degrade rapidly to O(1) Finally, the cache's lru policy did not evict least used - it evicted the 10,000 least used. So if you tuned your cache to match the NSPR map, every inclusion that would trigger a delete of old values would effectively empty your cache. ON bigger set sizes, this has to walk the map (at O(1)) to clean 10,000 elements. Premature optimisation strikes again .... Fix Description: Throw it out. Rewrite. We now use a hash algo that has proper distribution across a set. The hash sizes slots to a power of two. Finally, each thread has a private cache rather than shared which completely eliminates a lock contention and even NUMA performance issues. Interestingly this fix should have improvements for DB imports, memberof and refint performance and more. Some testing has shown in simple search workloads a 10% improvement in throughput, and on complex searches a 47x improvement. https://pagure.io/389-ds-base/issue/49330 Author: wibrown Review by: lkrispen, tbordaz (Thanks!)
commit 274823860ac98b153e7f0bc84d979861c4ca895f Author: William Brown <[email protected]> Date: Tue Jul 25 16:09:59 2017 +1000 Ticket 49330 - Improve ndn cache performance. Bug Description: Normalised DN's are a costly process to update and maintain. As a result, a normalised DN cache was created. Yet it was never able to perform well. In some datasets with large sets of dn attr types, the NDN cache actively hurt performance. The issue stemmed from 3 major issues in the design of the NDN cache. First, it is a global cache which means it exists behind a rwlock. This causes delay as threads wait behind the lock to access or update the cache (especially on a miss). Second, the cache was limited to 4073 buckets. Despite the fact that a prime number on a hash causes a skew in distribution, this was in an NSPR hash - which does not grow dynamically, rather devolving a bucket to a linked list. AS a result, once you passed ~3000 your lookup performance would degrade rapidly to O(1) Finally, the cache's lru policy did not evict least used - it evicted the 10,000 least used. So if you tuned your cache to match the NSPR map, every inclusion that would trigger a delete of old values would effectively empty your cache. ON bigger set sizes, this has to walk the map (at O(1)) to clean 10,000 elements. Premature optimisation strikes again .... Fix Description: Throw it out. Rewrite. We now use a hash algo that has proper distribution across a set. The hash sizes slots to a power of two. Finally, each thread has a private cache rather than shared which completely eliminates a lock contention and even NUMA performance issues. Interestingly this fix should have improvements for DB imports, memberof and refint performance and more. Some testing has shown in simple search workloads a 10% improvement in throughput, and on complex searches a 47x improvement. https://pagure.io/389-ds-base/issue/49330 Author: wibrown Review by: lkrispen, tbordaz (Thanks!) diff --git a/Makefile.am b/Makefile.am index 134206d91..26f1a271e 100644 --- a/Makefile.am +++ b/Makefile.am @@ -1228,8 +1228,8 @@ libslapd_la_SOURCES = ldap/servers/slapd/add.c \ ldap/servers/slapd/slapi_pal.c \ $(libavl_a_SOURCES) -libslapd_la_CPPFLAGS = $(AM_CPPFLAGS) $(DSPLUGIN_CPPFLAGS) $(SASL_INCLUDES) @db_inc@ $(SVRCORE_INCLUDES) @kerberos_inc@ @pcre_inc@ -libslapd_la_LIBADD = $(LDAPSDK_LINK) $(SASL_LINK) $(SVRCORE_LINK) $(NSS_LINK) $(NSPR_LINK) $(KERBEROS_LINK) $(PCRE_LINK) $(THREADLIB) $(SYSTEMD_LINK) +libslapd_la_CPPFLAGS = $(AM_CPPFLAGS) $(DSPLUGIN_CPPFLAGS) $(SASL_INCLUDES) @db_inc@ $(SVRCORE_INCLUDES) @kerberos_inc@ @pcre_inc@ $(SDS_CPPFLAGS) +libslapd_la_LIBADD = $(LDAPSDK_LINK) $(SASL_LINK) $(SVRCORE_LINK) $(NSS_LINK) $(NSPR_LINK) $(KERBEROS_LINK) $(PCRE_LINK) $(THREADLIB) $(SYSTEMD_LINK) libsds.la libslapd_la_LDFLAGS = $(AM_LDFLAGS) $(SLAPD_LDFLAGS) diff --git a/dirsrvtests/tests/suites/basic/basic_test.py b/dirsrvtests/tests/suites/basic/basic_test.py index 7b7768668..1a35efed2 100644 --- a/dirsrvtests/tests/suites/basic/basic_test.py +++ b/dirsrvtests/tests/suites/basic/basic_test.py @@ -325,6 +325,7 @@ def test_basic_acl(topology_st, import_example_ldif): """Run some basic access control(ACL) tests""" log.info('Running test_basic_acl...') + topology_st.standalone.start() DENY_ACI = ('(targetattr = "*") (version 3.0;acl "deny user";deny (all)' + '(userdn = "ldap:///' + USER1_DN + '");)') diff --git a/ldap/servers/slapd/back-ldbm/monitor.c b/ldap/servers/slapd/back-ldbm/monitor.c index 403d6a2e1..5f57b9f51 100644 --- a/ldap/servers/slapd/back-ldbm/monitor.c +++ b/ldap/servers/slapd/back-ldbm/monitor.c @@ -50,6 +50,9 @@ ldbm_back_monitor_instance_search(Slapi_PBlock *pb __attribute__((unused)), PRUint64 hits, tries; long nentries, maxentries, count; size_t size, maxsize; + size_t thread_size; + size_t evicts; + size_t slots; /* NPCTE fix for bugid 544365, esc 0. <P.R> <04-Jul-2001> */ struct stat astat; /* end of NPCTE fix for bugid 544365 */ @@ -124,7 +127,7 @@ ldbm_back_monitor_instance_search(Slapi_PBlock *pb __attribute__((unused)), } /* normalized dn cache stats */ if (ndn_cache_started()) { - ndn_cache_get_stats(&hits, &tries, &size, &maxsize, &count); + ndn_cache_get_stats(&hits, &tries, &size, &maxsize, &thread_size, &evicts, &slots, &count); sprintf(buf, "%" PRIu64, tries); MSET("normalizedDnCacheTries"); sprintf(buf, "%" PRIu64, hits); @@ -133,6 +136,8 @@ ldbm_back_monitor_instance_search(Slapi_PBlock *pb __attribute__((unused)), MSET("normalizedDnCacheMisses"); sprintf(buf, "%lu", (unsigned long)(100.0 * (double)hits / (double)(tries > 0 ? tries : 1))); MSET("normalizedDnCacheHitRatio"); + sprintf(buf, "%"PRIu64, evicts); + MSET("NormalizedDnCacheEvictions"); sprintf(buf, "%lu", (long unsigned int)size); MSET("currentNormalizedDnCacheSize"); if (maxsize == 0) { @@ -141,6 +146,10 @@ ldbm_back_monitor_instance_search(Slapi_PBlock *pb __attribute__((unused)), sprintf(buf, "%lu", (long unsigned int)maxsize); } MSET("maxNormalizedDnCacheSize"); + sprintf(buf, "%"PRIu64, thread_size); + MSET("NormalizedDnCacheThreadSize"); + sprintf(buf, "%"PRIu64, slots); + MSET("NormalizedDnCacheThreadSlots"); sprintf(buf, "%ld", count); MSET("currentNormalizedDnCacheCount"); } diff --git a/ldap/servers/slapd/dn.c b/ldap/servers/slapd/dn.c index 252d4e1a0..05ca16117 100644 --- a/ldap/servers/slapd/dn.c +++ b/ldap/servers/slapd/dn.c @@ -22,6 +22,9 @@ #include "slap.h" #include <plhash.h> +/* For the ndn cache - this gives up siphash13 */ +#include <sds.h> + #undef SDN_DEBUG static void add_rdn_av(char *avstart, char *avend, int *rdn_av_countp, struct berval **rdn_avsp, struct berval *avstack); @@ -32,52 +35,89 @@ static void rdn_av_swap(struct berval *av1, struct berval *av2, int escape); static int does_cn_uses_dn_syntax_in_dns(char *type, char *dn); /* normalized dn cache related definitions*/ -struct - ndn_cache_lru -{ - struct ndn_cache_lru *prev; - struct ndn_cache_lru *next; - char *key; -}; - -struct - ndn_cache_ctx -{ - struct ndn_cache_lru *head; - struct ndn_cache_lru *tail; +struct ndn_cache_stats { Slapi_Counter *cache_hits; Slapi_Counter *cache_tries; - Slapi_Counter *cache_misses; - size_t cache_size; - size_t cache_max_size; - long cache_count; + Slapi_Counter *cache_count; + Slapi_Counter *cache_size; + Slapi_Counter *cache_evicts; + size_t max_size; + size_t thread_max_size; + size_t slots; }; -struct - ndn_hash_val -{ +struct ndn_cache_value { + size_t size; + size_t slot; + char *dn; char *ndn; - size_t len; - int size; - struct ndn_cache_lru *lru_node; /* used to speed up lru shuffling */ + struct ndn_cache_value *next; + struct ndn_cache_value *prev; + struct ndn_cache_value *child; +}; + +/* + * This uses a similar alloc trick to IDList to keep + * The amount of derefs small. + */ +struct ndn_cache { + /* + * We keep per thread stats and flush them occasionally + */ + size_t max_size; + /* Need to track this because we need to provide diffs to counter */ + size_t last_count; + size_t count; + /* Number of ops */ + size_t tries; + /* hit vs miss. in theroy miss == tries - hits.*/ + size_t hits; + /* How many values we kicked out */ + size_t evicts; + /* Need to track this because we need to provide diffs to counter */ + size_t last_size; + size_t size; + + size_t slots; + /* + * This is used by siphash to prevent hash bugket attacks + */ + char key[16]; + + struct ndn_cache_value *head; + struct ndn_cache_value *tail; + struct ndn_cache_value *table[1]; }; -#define NDN_FLUSH_COUNT 10000 /* number of DN's to remove when cache fills up */ -#define NDN_MIN_COUNT 1000 /* the minimum number of DN's to keep in the cache */ -#define NDN_CACHE_BUCKETS 2053 /* prime number */ +/* + * This means we need 1 MB minimum per thread + * + */ +#define NDN_CACHE_MINIMUM_CAPACITY 1048576 +/* + * This helps us define the number of hashtable slots + * to create. We assume an average DN is 64 chars long + * This way we end up we a ht entry of: + * 8 bytes: from the table pointing to us. + * 8 bytes: next ptr + * 8 bytes: prev ptr + * 8 bytes + 64: dn + * 8 bytes + 64: ndn itself. + * This gives us 168 bytes. In theory this means + * 6241 entries, but we have to clamp this to a power of + * two, so we have 8192 slots. In reality, dns may be + * shorter *and* the dn may be the same as the ndn + * so we *may* store more ndns that this. Again, a good reason + * to round the ht size up! + */ +#define NDN_ENTRY_AVG_SIZE 168 +/* + * After how many operations do we sync our per-thread stats. + */ +#define NDN_STAT_COMMIT_FREQUENCY 256 -static PLHashNumber ndn_hash_string(const void *key); static int ndn_cache_lookup(char *dn, size_t dn_len, char **result, char **udn, int *rc); -static void ndn_cache_update_lru(struct ndn_cache_lru **node); static void ndn_cache_add(char *dn, size_t dn_len, char *ndn, size_t ndn_len); -static void ndn_cache_delete(char *dn); -static void ndn_cache_flush(void); -static void ndn_cache_free(void); -static int ndn_started = 0; -static PRLock *lru_lock = NULL; -static Slapi_RWLock *ndn_cache_lock = NULL; -static struct ndn_cache_ctx *ndn_cache = NULL; -static PLHashTable *ndn_cache_hashtable = NULL; #define ISBLANK(c) ((c) == ' ') #define ISBLANKSTR(s) (((*(s)) == '2') && (*((s) + 1) == '0')) @@ -2699,165 +2739,420 @@ slapi_sdn_get_size(const Slapi_DN *sdn) */ /* - * Hashing function using Bernstein's method + * siphash13 provides a uint64_t hash of the incoming data. This means that in theory, + * the hash is anything between 0 -> 0xFFFFFFFFFFFFFFFF. The result is distributed + * evenly over the set of numbers, so we can assume that given some infinite set of + * inputs, we'll have even distribution of all values across 0 -> 0xFFFFFFFFFFFFFFF. + * In mathematics, given a set of integers, when you modulo them by a factor of the + * input, the result retains the same distribution properties. IE, if you modulo the + * numbers say 0 - 32 and they are evenly distributed, when do 0 -> 32 % 16, you will + * still see even distribution (but duplicates now). + * + * So we use this property - we scale the number of slots by powers of 2 so that we + * can do hash % slots and retain even distribution. IE: + * + * (0 -> 0xFFFFFFFFFFFFFFFF) % slots = .... + * + * This means we get even distribution: *but* it creates a scenario where we are more + * likely to cause a collision as a result. + * + * Anyway, so lets imagine our small hashtable: + * + * *t_cache + * ------------------------- + * | 0 | 1 | 2 | 3 | + * ------------------------- + * + * So any incoming DN will be put through: + * + * (0 -> 0xFFFFFFFFFFFFFFFF) % 4 = slot + * + * So lets say we add the values a, b, c (in that order) + * + * *t_cache + * head: A + * tail: C + * ------------------------- + * | 0 | 1 | 2 | 3 | + * ------------------------- + * ------------------------- + * | A | B | C | | + * |n: |n: A |n: B | | + * |p: B |p: C |p: | | + * ------------------------- + * + * Because C was accessed (rather inserted) last, it's at the "tail". This is the + * *most recently used* element. Because A was inserted first, it's the *least* + * used. So lets do a look up on A: + * + * *t_cache + * head: B + * tail: A + * ------------------------- + * | 0 | 1 | 2 | 3 | + * ------------------------- + * ------------------------- + * | A | B | C | | + * |n: C |n: |n: B | | + * |p: |p: C |p: A | | + * ------------------------- + * + * Because we did a lookup on A, we cut it out from the list and moved it to the tail. + * This has pushed B to the head. + * + * Now lets say we need to do a removal to fit "D". We would remove elements from the + * head until we have space. Here we just need to trim B. + * + * *t_cache + * head: C + * tail: D + * ------------------------- + * | 0 | 1 | 2 | 3 | + * ------------------------- + * ------------------------- + * | A | | C | D | + * |n: C | |n: |n: A | + * |p: D | |p: A |p: | + * ------------------------- + * + * So we have removed B, and inserted D to the tail. Again, because A was more recently + * read than C, C is now at the head. This process continues until the heat death of + * the universe, or the server stops, what ever comes first (we write very stable code here ;) + * + * Now, lets discuss the "child" pointers in the nodes. + * + * Because of: + * + * (0 -> 0xFFFFFFFFFFFFFFFF) % 4 = slot + * + * The *smaller* the table, the more *likely* a hash collision is to occur (and in theory + * even at a full table size they could still occur ...). + * + * So when you have a small table like this one I originally did *not* have the ability + * to have multiple values per bucket, and just let the evictions take place. I did some + * tests and found in this case, the LL behaviours were faster than repeated evictions. + * + * So lets say in our table we add another value, and it conflicts with the hash of C: + * + * *t_cache + * head: C + * tail: E + * ------------------------- + * | 0 | 1 | 2 | 3 | + * ------------------------- + * ------------------------- + * | A | | C | D | + * |n: C | |n: |n: A | + * |p: D | |p: A |p: E | + * ------------------------- + * | E | + * |n: D | + * |p: | + * ------- + * + * Now when we do a look up of "E" we'll collide on bucket 2, and then descend down til + * we exhaust, or find our element. If we were to remove C, we would just promote E to + * be the head of that slot. + * + * Again, I did test both with and without this - with was much faster, and relies on + * how even our hash distribution is *and* that generally with small table sizes we + * have small capacity, so we evict some values and keep these chains short. + * */ -static PLHashNumber -ndn_hash_string(const void *key) -{ - PLHashNumber hash = 5381; - unsigned char *x = (unsigned char *)key; - int c; - while ((c = *x++)) { - hash = ((hash << 5) + hash) ^ c; +static pthread_key_t ndn_cache_key; +static pthread_once_t ndn_cache_key_once = PTHREAD_ONCE_INIT; +static struct ndn_cache_stats t_cache_stats = {0}; +/* + * WARNING: For some reason we try to use the NDN cache *before* + * we have a chance to configure it. As a result, we need to rely + * on a trick in the way we start, that we start in one thread + * so we can manipulate ints as though they were atomics, then + * we start in *one* thread, so it's set, then when threads + * fork the get barriers, so we can go from there. However we *CANNOT* + * change this at runtime without expensive atomics per op, so lets + * not bother until we improve libglobs to be COW. + */ +static int32_t ndn_enabled = 0; + +static struct ndn_cache * +ndn_thread_cache_create(size_t thread_max_size, size_t slots) { + size_t t_cache_size = sizeof(struct ndn_cache) + (slots * sizeof(struct ndn_cache_value *)); + struct ndn_cache *t_cache = (struct ndn_cache *)slapi_ch_calloc(1, t_cache_size); + + t_cache->max_size = thread_max_size; + t_cache->slots = slots; + + return t_cache; +} + +static void +ndn_thread_cache_commit_status(struct ndn_cache *t_cache) { + /* + * Every so often we commit these atomically. We do this infrequently + * to avoid the costly atomics. + */ + if (t_cache->tries % NDN_STAT_COMMIT_FREQUENCY == 0) { + /* We can just add tries and hits. */ + slapi_counter_add(t_cache_stats.cache_evicts, t_cache->evicts); + slapi_counter_add(t_cache_stats.cache_tries, t_cache->tries); + slapi_counter_add(t_cache_stats.cache_hits, t_cache->hits); + t_cache->hits = 0; + t_cache->tries = 0; + t_cache->evicts = 0; + /* Count and size need diff */ + int64_t diff = (t_cache->size - t_cache->last_size); + if (diff > 0) { + // We have more .... + slapi_counter_add(t_cache_stats.cache_size, (uint64_t)diff); + } else if (diff < 0) { + slapi_counter_subtract(t_cache_stats.cache_size, (uint64_t)llabs(diff)); + } + t_cache->last_size = t_cache->size; + + diff = (t_cache->count - t_cache->last_count); + if (diff > 0) { + // We have more .... + slapi_counter_add(t_cache_stats.cache_count, (uint64_t)diff); + } else if (diff < 0) { + slapi_counter_subtract(t_cache_stats.cache_count, (uint64_t)llabs(diff)); + } + t_cache->last_count = t_cache->count; + } - return hash; } -void +static void +ndn_thread_cache_value_destroy(struct ndn_cache *t_cache, struct ndn_cache_value *v) { + /* Update stats */ + t_cache->size = t_cache->size - v->size; + t_cache->count--; + t_cache->evicts++; + + if (v == t_cache->head) { + t_cache->head = v->prev; + } + if (v == t_cache->tail) { + t_cache->tail = v->next; + } + + /* Cut the node out. */ + if (v->next != NULL) { + v->next->prev = v->prev; + } + if (v->prev != NULL) { + v->prev->next = v->next; + } + /* Set the pointer in the table to NULL */ + /* Now see if we were in a list */ + struct ndn_cache_value *slot_node = t_cache->table[v->slot]; + if (slot_node == v) { + t_cache->table[v->slot] = v->child; + } else { + struct ndn_cache_value *former_slot_node = NULL; + do { + former_slot_node = slot_node; + slot_node = slot_node->child; + } while(slot_node != v); + /* Okay, now slot_node is us, and former is our parent */ + former_slot_node->child = v->child; + } + + slapi_ch_free((void **)&(v->dn)); + slapi_ch_free((void **)&(v->ndn)); + slapi_ch_free((void **)&v); +} + +static void +ndn_thread_cache_destroy(void *v_cache) { + struct ndn_cache *t_cache = (struct ndn_cache *)v_cache; + /* + * FREE ALL THE NODES!!! + */ + struct ndn_cache_value *node = t_cache->tail; + struct ndn_cache_value *next_node = NULL; + while (node) { + next_node = node->next; + ndn_thread_cache_value_destroy(t_cache, node); + node = next_node; + } + slapi_ch_free((void **)&t_cache); +} + +static void +ndn_cache_key_init() { + if (pthread_key_create(&ndn_cache_key, ndn_thread_cache_destroy) != 0) { + /* Log a scary warning? */ + slapi_log_err(SLAPI_LOG_ERR, "ndn_cache_init", "Failed to create pthread key, aborting.\n"); + } +} + +int32_t ndn_cache_init() { - if (!config_get_ndn_cache_enabled() || ndn_started) { - return; + ndn_enabled = config_get_ndn_cache_enabled(); + if (ndn_enabled == 0) { + /* + * Don't configure the keys or anything, need a restart + * to enable. We'll just never use ndn cache in this + * run. + */ + return 0; } - ndn_cache_hashtable = PL_NewHashTable(NDN_CACHE_BUCKETS, ndn_hash_string, PL_CompareStrings, PL_CompareValues, 0, 0); - ndn_cache = (struct ndn_cache_ctx *)slapi_ch_malloc(sizeof(struct ndn_cache_ctx)); - ndn_cache->cache_max_size = config_get_ndn_cache_size(); - ndn_cache->cache_hits = slapi_counter_new(); - ndn_cache->cache_tries = slapi_counter_new(); - ndn_cache->cache_misses = slapi_counter_new(); - ndn_cache->cache_count = 0; - ndn_cache->cache_size = sizeof(struct ndn_cache_ctx) + sizeof(PLHashTable) + sizeof(PLHashTable); - ndn_cache->head = NULL; - ndn_cache->tail = NULL; - ndn_started = 1; - if (NULL == (lru_lock = PR_NewLock()) || NULL == (ndn_cache_lock = slapi_new_rwlock())) { - ndn_cache_destroy(); - slapi_log_err(SLAPI_LOG_ERR, "ndn_cache_init", "Failed to create locks. Disabling cache.\n"); + + /* Create the pthread key */ + (void)pthread_once(&ndn_cache_key_once, ndn_cache_key_init); + + /* Create the global stats. */ + t_cache_stats.max_size = config_get_ndn_cache_size(); + t_cache_stats.cache_evicts = slapi_counter_new(); + t_cache_stats.cache_tries = slapi_counter_new(); + t_cache_stats.cache_hits = slapi_counter_new(); + t_cache_stats.cache_count = slapi_counter_new(); + t_cache_stats.cache_size = slapi_counter_new(); + /* Get thread numbers and calc the per thread size */ + int32_t maxthreads = (int32_t)config_get_threadnumber(); + size_t tentative_size = t_cache_stats.max_size / maxthreads; + if (tentative_size < NDN_CACHE_MINIMUM_CAPACITY) { + tentative_size = NDN_CACHE_MINIMUM_CAPACITY; + t_cache_stats.max_size = NDN_CACHE_MINIMUM_CAPACITY * maxthreads; } + t_cache_stats.thread_max_size = tentative_size; + + /* + * Slots *must* be a power of two, even if the number of entries + * we store will be *less* than this. + */ + size_t possible_elements = tentative_size / NDN_ENTRY_AVG_SIZE; + /* + * So this is like 1048576 / 168, so we get 6241. Now we need to + * shift this to get the number of bits. + */ + size_t shifts = 0; + while (possible_elements > 0) { + shifts++; + possible_elements = possible_elements >> 1; + } + /* + * So now we can use this to make the slot count. + */ + t_cache_stats.slots = 1 << shifts; + /* Done? */ + return 0; } void ndn_cache_destroy() { - if (!ndn_started) { + if (ndn_enabled == 0) { return; } - if (lru_lock) { - PR_DestroyLock(lru_lock); - lru_lock = NULL; - } - if (ndn_cache_lock) { - slapi_destroy_rwlock(ndn_cache_lock); - ndn_cache_lock = NULL; - } - if (ndn_cache_hashtable) { - ndn_cache_free(); - PL_HashTableDestroy(ndn_cache_hashtable); - ndn_cache_hashtable = NULL; - } - config_set_ndn_cache_enabled(CONFIG_NDN_CACHE, "off", NULL, 1); - slapi_counter_destroy(&ndn_cache->cache_hits); - slapi_counter_destroy(&ndn_cache->cache_tries); - slapi_counter_destroy(&ndn_cache->cache_misses); - slapi_ch_free((void **)&ndn_cache); - - ndn_started = 0; + slapi_counter_destroy(&(t_cache_stats.cache_tries)); + slapi_counter_destroy(&(t_cache_stats.cache_hits)); + slapi_counter_destroy(&(t_cache_stats.cache_count)); + slapi_counter_destroy(&(t_cache_stats.cache_size)); + slapi_counter_destroy(&(t_cache_stats.cache_evicts)); } int ndn_cache_started() { - return ndn_started; + return ndn_enabled; } /* * Look up this dn in the ndn cache */ static int -ndn_cache_lookup(char *dn, size_t dn_len, char **result, char **udn, int *rc) +ndn_cache_lookup(char *dn, size_t dn_len, char **ndn, char **udn, int *rc) { - struct ndn_hash_val *ndn_ht_val = NULL; - char *ndn, *key; - int rv = 0; - - if (NULL == udn) { - return rv; + if (ndn_enabled == 0 || NULL == udn) { + return 0; } *udn = NULL; - if (ndn_started == 0) { - return rv; - } + if (dn_len == 0) { - *result = dn; + *ndn = dn; *rc = 0; return 1; } - slapi_counter_increment(ndn_cache->cache_tries); - slapi_rwlock_rdlock(ndn_cache_lock); - ndn_ht_val = (struct ndn_hash_val *)PL_HashTableLookupConst(ndn_cache_hashtable, dn); - if (ndn_ht_val) { - ndn_cache_update_lru(&ndn_ht_val->lru_node); - slapi_counter_increment(ndn_cache->cache_hits); - if ((ndn_ht_val->len != dn_len) || - /* even if the lengths match, dn may not be normalized yet. - * (e.g., 'cn="o=ABC",o=XYZ' vs. 'cn=o\3DABC,o=XYZ') */ - (memcmp(dn, ndn_ht_val->ndn, dn_len))) { - *rc = 1; /* free result */ - ndn = slapi_ch_malloc(ndn_ht_val->len + 1); - memcpy(ndn, ndn_ht_val->ndn, ndn_ht_val->len); - ndn[ndn_ht_val->len] = '\0'; - *result = ndn; - } else { - /* the dn was already normalized, just return the dn as the result */ - *result = dn; - *rc = 0; - } - rv = 1; - } else { - /* copy/preserve the udn, so we can use it as the key when we add dn's to the hashtable */ - key = slapi_ch_malloc(dn_len + 1); - memcpy(key, dn, dn_len); - key[dn_len] = '\0'; - *udn = key; + + struct ndn_cache *t_cache = pthread_getspecific(ndn_cache_key); + if (t_cache == NULL) { + t_cache = ndn_thread_cache_create(t_cache_stats.thread_max_size, t_cache_stats.slots); + pthread_setspecific(ndn_cache_key, t_cache); + /* If we have no cache, we can't look up ... */ + return 0; } - slapi_rwlock_unlock(ndn_cache_lock); - return rv; -} + t_cache->tries++; -/* - * Move this lru node to the top of the list - */ -static void -ndn_cache_update_lru(struct ndn_cache_lru **node) -{ - struct ndn_cache_lru *prev, *next, *curr_node = *node; + /* + * Hash our DN ... + */ + uint64_t dn_hash = sds_siphash13(dn, dn_len, t_cache->key); + /* Where should it be? */ + size_t expect_slot = dn_hash % t_cache->slots; - if (curr_node == NULL) { - return; - } - PR_Lock(lru_lock); - if (curr_node->prev == NULL) { - /* already the top node */ - PR_Unlock(lru_lock); - return; - } - prev = curr_node->prev; - next = curr_node->next; - if (next) { - next->prev = prev; - prev->next = next; - } else { - /* this was the tail, so reset the tail */ - ndn_cache->tail = prev; - prev->next = NULL; + /* + * Is it there? + */ + if (t_cache->table[expect_slot] != NULL) { + /* + * Check it really matches, could be collision. + */ + struct ndn_cache_value *node = t_cache->table[expect_slot]; + while (node != NULL) { + if (strcmp(dn, node->dn) == 0) { + /* + * Update LRU + * Are we already the tail? If so, we can just skip. + * remember, this means in a set of 1, we will always be tail + */ + if (t_cache->tail != node) { + /* + * Okay, we are *not* the tail. We could be anywhere between + * tail -> ... -> x -> head + * or even, we are the head ourself. + */ + if (t_cache->head == node) { + /* We are the head, update head to our predecessor */ + t_cache->head = node->prev; + /* Remember, the head has no next. */ + t_cache->head->next = NULL; + } else { + /* Right, we aren't the head, so we have a next node. */ + node->next->prev = node->prev; + } + /* Because we must be in the middle somewhere, we can assume next and prev exist. */ + node->prev->next = node->next; + /* + * Tail can't be NULL if we have a value in the cache, so we can + * just deref this. + */ + node->next = t_cache->tail; + t_cache->tail->prev = node; + t_cache->tail = node; + node->prev = NULL; + } + + /* Update that we have a hit.*/ + t_cache->hits++; + /* Cope the NDN to the caller. */ + *ndn = slapi_ch_strdup(node->ndn); + /* Indicate to the caller to free this. */ + *rc = 1; + ndn_thread_cache_commit_status(t_cache); + return 1; + } + node = node->child; + } } - curr_node->prev = NULL; - curr_node->next = ndn_cache->head; - ndn_cache->head->prev = curr_node; - ndn_cache->head = curr_node; - PR_Unlock(lru_lock); + /* If we miss, we need to duplicate dn to udn here. */ + *udn = slapi_ch_strdup(dn); + *rc = 0; + ndn_thread_cache_commit_status(t_cache); + return 0; } /* @@ -2866,12 +3161,10 @@ ndn_cache_update_lru(struct ndn_cache_lru **node) static void ndn_cache_add(char *dn, size_t dn_len, char *ndn, size_t ndn_len) { - struct ndn_hash_val *ht_entry; - struct ndn_cache_lru *new_node = NULL; - PLHashEntry *he; - int size; - - if (ndn_started == 0 || dn_len == 0) { + if (ndn_enabled == 0) { + return; + } + if (dn_len == 0) { return; } if (strlen(ndn) > ndn_len) { @@ -2881,161 +3174,89 @@ ndn_cache_add(char *dn, size_t dn_len, char *ndn, size_t ndn_len) /* * Calculate the approximate memory footprint of the hash entry, key, and lru entry. */ - size = (dn_len * 2) + ndn_len + sizeof(PLHashEntry) + sizeof(struct ndn_hash_val) + sizeof(struct ndn_cache_lru); + struct ndn_cache_value *new_value = (struct ndn_cache_value *)slapi_ch_calloc(1, sizeof(struct ndn_cache_value)); + new_value->size = sizeof(struct ndn_cache_value) + dn_len + ndn_len; + /* DN is alloc for us */ + new_value->dn = dn; + /* But we need to copy ndn */ + new_value->ndn = slapi_ch_strdup(ndn); + /* - * Create our LRU node + * Get our local cache out. */ - new_node = (struct ndn_cache_lru *)slapi_ch_malloc(sizeof(struct ndn_cache_lru)); - if (new_node == NULL) { - slapi_log_err(SLAPI_LOG_ERR, "ndn_cache_add", "Failed to allocate new lru node.\n"); - return; + struct ndn_cache *t_cache = pthread_getspecific(ndn_cache_key); + if (t_cache == NULL) { + t_cache = ndn_thread_cache_create(t_cache_stats.thread_max_size, t_cache_stats.slots); + pthread_setspecific(ndn_cache_key, t_cache); } - new_node->prev = NULL; - new_node->key = dn; /* dn has already been allocated */ /* - * Its possible this dn was added to the hash by another thread. + * Hash the DN */ - slapi_rwlock_wrlock(ndn_cache_lock); - ht_entry = (struct ndn_hash_val *)PL_HashTableLookupConst(ndn_cache_hashtable, dn); - if (ht_entry) { - /* already exists, free the node and return */ - slapi_rwlock_unlock(ndn_cache_lock); - slapi_ch_free_string(&new_node->key); - slapi_ch_free((void **)&new_node); - return; - } + uint64_t dn_hash = sds_siphash13(new_value->dn, dn_len, t_cache->key); /* - * Create the hash entry + * Get the insert slot: This works because the number spaces of dn_hash is + * a 64bit int, and slots is a power of two. As a result, we end up with + * even distribution of the values. */ - ht_entry = (struct ndn_hash_val *)slapi_ch_malloc(sizeof(struct ndn_hash_val)); - if (ht_entry == NULL) { - slapi_rwlock_unlock(ndn_cache_lock); - slapi_log_err(SLAPI_LOG_ERR, "ndn_cache_add", "Failed to allocate new hash entry.\n"); - slapi_ch_free_string(&new_node->key); - slapi_ch_free((void **)&new_node); - return; - } - ht_entry->ndn = slapi_ch_malloc(ndn_len + 1); - memcpy(ht_entry->ndn, ndn, ndn_len); - ht_entry->ndn[ndn_len] = '\0'; - ht_entry->len = ndn_len; - ht_entry->size = size; - ht_entry->lru_node = new_node; + size_t insert_slot = dn_hash % t_cache->slots; + /* Track this for free */ + new_value->slot = insert_slot; + /* - * Check if our cache is full + * Okay, check if we have space, else we need to trim nodes from + * the LRU */ - PR_Lock(lru_lock); /* grab the lru lock now, as ndn_cache_flush needs it */ - if (ndn_cache->cache_max_size != 0 && ((ndn_cache->cache_size + size) > ndn_cache->cache_max_size)) { - ndn_cache_flush(); + while (t_cache->head && (t_cache->size + new_value->size) > t_cache->max_size) { + struct ndn_cache_value *trim_node = t_cache->head; + ndn_thread_cache_value_destroy(t_cache, trim_node); } + /* - * Set the ndn cache lru nodes + * Add it! */ - if (ndn_cache->head == NULL && ndn_cache->tail == NULL) { - /* this is the first node */ - ndn_cache->head = new_node; - ndn_cache->tail = new_node; - new_node->next = NULL; + if (t_cache->table[insert_slot] == NULL) { + t_cache->table[insert_slot] = new_value; } else { - new_node->next = ndn_cache->head; - if (ndn_cache->head) - ndn_cache->head->prev = new_node; + /* + * Hash collision! We need to replace the bucket then .... + * insert at the head of the slot to make this simpler. + */ + new_value->child = t_cache->table[insert_slot]; + t_cache->table[insert_slot] = new_value; } - ndn_cache->head = new_node; - PR_Unlock(lru_lock); + /* - * Add the new object to the hashtable, and update our stats + * Finally, stick this onto the tail because it's the newest. */ - he = PL_HashTableAdd(ndn_cache_hashtable, new_node->key, (void *)ht_entry); - if (he == NULL) { - slapi_log_err(SLAPI_LOG_ERR, "ndn_cache_add", "Failed to add new entry to hash(%s)\n", dn); - } else { - ndn_cache->cache_count++; - ndn_cache->cache_size += size; + if (t_cache->head == NULL) { + t_cache->head = new_value; } - slapi_rwlock_unlock(ndn_cache_lock); -} - -/* - * cache is full, remove the least used dn's. lru_lock/ndn_cache write lock are already taken - */ -static void -ndn_cache_flush(void) -{ - struct ndn_cache_lru *node, *next, *flush_node; - int i; - - node = ndn_cache->tail; - for (i = 0; node && i < NDN_FLUSH_COUNT && ndn_cache->cache_count > NDN_MIN_COUNT; i++) { - flush_node = node; - /* update the lru */ - next = node->prev; - next->next = NULL; - ndn_cache->tail = next; - node = next; - /* now update the hash */ - ndn_cache->cache_count--; - ndn_cache_delete(flush_node->key); - slapi_ch_free_string(&flush_node->key); - slapi_ch_free((void **)&flush_node); + if (t_cache->tail != NULL) { + new_value->next = t_cache->tail; + t_cache->tail->prev = new_value; } + t_cache->tail = new_value; - slapi_log_err(SLAPI_LOG_CACHE, "ndn_cache_flush", "Flushed cache.\n"); -} - -static void -ndn_cache_free(void) -{ - struct ndn_cache_lru *node, *next, *flush_node; - - if (!ndn_cache) { - return; - } - - node = ndn_cache->tail; - while (node && ndn_cache->cache_count) { - flush_node = node; - /* update the lru */ - next = node->prev; - if (next) { - next->next = NULL; - } - ndn_cache->tail = next; - node = next; - /* now update the hash */ - ndn_cache->cache_count--; - ndn_cache_delete(flush_node->key); - slapi_ch_free_string(&flush_node->key); - slapi_ch_free((void **)&flush_node); - } -} - -/* this is already "write" locked from ndn_cache_add */ -static void -ndn_cache_delete(char *dn) -{ - struct ndn_hash_val *ht_entry; + /* + * And update the stats. + */ + t_cache->size = t_cache->size + new_value->size; + t_cache->count++; - ht_entry = (struct ndn_hash_val *)PL_HashTableLookupConst(ndn_cache_hashtable, dn); - if (ht_entry) { - ndn_cache->cache_size -= ht_entry->size; - slapi_ch_free_string(&ht_entry->ndn); - slapi_ch_free((void **)&ht_entry); - PL_HashTableRemove(ndn_cache_hashtable, dn); - } } /* stats for monitor */ void -ndn_cache_get_stats(PRUint64 *hits, PRUint64 *tries, size_t *size, size_t *max_size, long *count) -{ - slapi_rwlock_rdlock(ndn_cache_lock); - *hits = slapi_counter_get_value(ndn_cache->cache_hits); - *tries = slapi_counter_get_value(ndn_cache->cache_tries); - *size = ndn_cache->cache_size; - *max_size = ndn_cache->cache_max_size; - *count = ndn_cache->cache_count; - slapi_rwlock_unlock(ndn_cache_lock); +ndn_cache_get_stats(PRUint64 *hits, PRUint64 *tries, size_t *size, size_t *max_size, size_t *thread_size, size_t *evicts, size_t *slots, long *count) +{ + *max_size = t_cache_stats.max_size; + *thread_size = t_cache_stats.thread_max_size; + *slots = t_cache_stats.slots; + *evicts = slapi_counter_get_value(t_cache_stats.cache_evicts); + *hits = slapi_counter_get_value(t_cache_stats.cache_hits); + *tries = slapi_counter_get_value(t_cache_stats.cache_tries); + *size = slapi_counter_get_value(t_cache_stats.cache_size); + *count = slapi_counter_get_value(t_cache_stats.cache_count); } /* Common ancestor sdn is allocated. diff --git a/ldap/servers/slapd/libglobs.c b/ldap/servers/slapd/libglobs.c index 06aa0dcd4..6a8ab156b 100644 --- a/ldap/servers/slapd/libglobs.c +++ b/ldap/servers/slapd/libglobs.c @@ -1936,9 +1936,7 @@ config_set_ndn_cache_max_size(const char *attrname, char *value, char *errorbuf, size = NDN_DEFAULT_SIZE; } if (apply) { - CFG_LOCK_WRITE(slapdFrontendConfig); - slapdFrontendConfig->ndn_cache_max_size = size; - CFG_UNLOCK_WRITE(slapdFrontendConfig); + __atomic_store_8(&(slapdFrontendConfig->ndn_cache_max_size), size, __ATOMIC_RELEASE); } return retVal; @@ -3894,7 +3892,7 @@ int config_set_threadnumber(const char *attrname, char *value, char *errorbuf, int apply) { int retVal = LDAP_SUCCESS; - long threadnum = 0; + int32_t threadnum = 0; char *endp = NULL; slapdFrontendConfig_t *slapdFrontendConfig = getFrontendConfig(); @@ -3917,10 +3915,7 @@ config_set_threadnumber(const char *attrname, char *value, char *errorbuf, int a retVal = LDAP_OPERATIONS_ERROR; } if (apply) { - CFG_LOCK_WRITE(slapdFrontendConfig); - /* max_threads = threadnum; */ - slapdFrontendConfig->threadnumber = threadnum; - CFG_UNLOCK_WRITE(slapdFrontendConfig); + __atomic_store_4(&(slapdFrontendConfig->threadnumber), threadnum, __ATOMIC_RELAXED); } return retVal; } @@ -5401,22 +5396,20 @@ config_get_encryptionalias(void) return retVal; } -long +int32_t config_get_threadnumber(void) { slapdFrontendConfig_t *slapdFrontendConfig = getFrontendConfig(); - long retVal; + int32_t retVal; - CFG_LOCK_READ(slapdFrontendConfig); - retVal = slapdFrontendConfig->threadnumber; - CFG_UNLOCK_READ(slapdFrontendConfig); + retVal = __atomic_load_4(&(slapdFrontendConfig->threadnumber), __ATOMIC_RELAXED); - if (retVal == -1) { + if (retVal <= 0) { retVal = util_get_hardware_threads(); } /* We *still* can't detect hardware threads. Okay, return 30 :( */ - if (retVal == -1) { + if (retVal <= 0) { retVal = 30; } @@ -6072,16 +6065,12 @@ config_get_max_filter_nest_level() return __atomic_load_4(&(slapdFrontendConfig->max_filter_nest_level), __ATOMIC_ACQUIRE); } -size_t +uint64_t config_get_ndn_cache_size() { slapdFrontendConfig_t *slapdFrontendConfig = getFrontendConfig(); - size_t retVal; - CFG_LOCK_READ(slapdFrontendConfig); - retVal = slapdFrontendConfig->ndn_cache_max_size; - CFG_UNLOCK_READ(slapdFrontendConfig); - return retVal; + return __atomic_load_8(&(slapdFrontendConfig->ndn_cache_max_size), __ATOMIC_ACQUIRE); } int32_t diff --git a/ldap/servers/slapd/main.c b/ldap/servers/slapd/main.c index 68f7751b7..520e1ab3e 100644 --- a/ldap/servers/slapd/main.c +++ b/ldap/servers/slapd/main.c @@ -1011,7 +1011,11 @@ main(int argc, char **argv) } /* initialize the normalized DN cache */ - ndn_cache_init(); + if (ndn_cache_init() != 0) { + slapi_log_err(SLAPI_LOG_EMERG, "main", "Unable to create ndn cache\n"); + return_value = 1; + goto cleanup; + } global_backend_lock_init(); @@ -2159,6 +2163,8 @@ slapd_exemode_ldif2db(struct main_config *mcfg) } slapi_pblock_destroy(pb); slapi_ch_free((void **)&(mcfg->myname)); + charray_free(mcfg->cmd_line_instance_names); + charray_free(mcfg->db2ldif_include); charray_free(mcfg->db2index_attrs); charray_free(mcfg->ldif_file); return (return_value); @@ -2340,6 +2346,8 @@ slapd_exemode_db2ldif(int argc, char **argv, struct main_config *mcfg) } } slapi_ch_free((void **)&(mcfg->myname)); + charray_free(mcfg->cmd_line_instance_names); + charray_free(mcfg->db2ldif_include); if (mcfg->db2ldif_dump_replica) { eq_stop(); /* event queue should be shutdown before closing all plugins (especailly, replication plugin) */ @@ -2511,6 +2519,7 @@ slapd_exemode_db2archive(struct main_config *mcfg) int32_t task_flags = SLAPI_TASK_RUNNING_FROM_COMMANDLINE; slapi_pblock_set(pb, SLAPI_TASK_FLAGS, &task_flags); return_value = (backend_plugin->plg_db2archive)(pb); + slapi_ch_free((void **)&(mcfg->myname)); slapi_pblock_destroy(pb); return return_value; } @@ -2558,6 +2567,7 @@ slapd_exemode_archive2db(struct main_config *mcfg) slapi_pblock_set(pb, SLAPI_TASK_FLAGS, &task_flags); slapi_pblock_set(pb, SLAPI_BACKEND_INSTANCE_NAME, mcfg->cmd_line_instance_name); return_value = (backend_plugin->plg_archive2db)(pb); + slapi_ch_free((void **)&(mcfg->myname)); slapi_pblock_destroy(pb); return return_value; } diff --git a/ldap/servers/slapd/proto-slap.h b/ldap/servers/slapd/proto-slap.h index daadfe5f1..83e4dce97 100644 --- a/ldap/servers/slapd/proto-slap.h +++ b/ldap/servers/slapd/proto-slap.h @@ -462,7 +462,7 @@ char *config_get_rootpwstoragescheme(void); char *config_get_localuser(void); char *config_get_workingdir(void); char *config_get_encryptionalias(void); -long config_get_threadnumber(void); +int32_t config_get_threadnumber(void); int config_get_maxthreadsperconn(void); int config_get_maxdescriptors(void); int config_get_reservedescriptors(void); @@ -533,7 +533,7 @@ PRInt64 config_get_disk_threshold(void); int config_get_disk_grace_period(void); int config_get_disk_logging_critical(void); int config_get_ndn_cache_count(void); -size_t config_get_ndn_cache_size(void); +uint64_t config_get_ndn_cache_size(void); int config_get_ndn_cache_enabled(void); int config_get_return_orig_type_switch(void); char *config_get_allowed_sasl_mechs(void); diff --git a/ldap/servers/slapd/slap.h b/ldap/servers/slapd/slap.h index 841dc92a2..4e3cbd30f 100644 --- a/ldap/servers/slapd/slap.h +++ b/ldap/servers/slapd/slap.h @@ -2261,7 +2261,7 @@ typedef struct _slapdFrontendConfig char *SNMPorganization; char *SNMPlocation; char *SNMPcontact; - long threadnumber; + int32_t threadnumber; int timelimit; char *accesslog; struct berval **defaultreferral; @@ -2433,7 +2433,7 @@ typedef struct _slapdFrontendConfig /* normalized dn cache */ slapi_onoff_t ndn_cache_enabled; - size_t ndn_cache_max_size; + uint64_t ndn_cache_max_size; slapi_onoff_t return_orig_type; /* if on, search returns original type set in attr list */ slapi_onoff_t sasl_mapping_fallback; diff --git a/ldap/servers/slapd/slapi-private.h b/ldap/servers/slapd/slapi-private.h index 87d9367fb..5a0825979 100644 --- a/ldap/servers/slapd/slapi-private.h +++ b/ldap/servers/slapd/slapi-private.h @@ -373,10 +373,10 @@ Slapi_DN *slapi_sdn_init_normdn_ndn_passin(Slapi_DN *sdn, const char *dn); Slapi_DN *slapi_sdn_init_normdn_passin(Slapi_DN *sdn, const char *dn); char *slapi_dn_normalize_original(char *dn); char *slapi_dn_normalize_case_original(char *dn); -void ndn_cache_init(void); +int32_t ndn_cache_init(void); void ndn_cache_destroy(void); int ndn_cache_started(void); -void ndn_cache_get_stats(PRUint64 *hits, PRUint64 *tries, size_t *size, size_t *max_size, long *count); +void ndn_cache_get_stats(PRUint64 *hits, PRUint64 *tries, size_t *size, size_t *max_size, size_t *thread_size, size_t *evicts, size_t *slots, long *count); #define NDN_DEFAULT_SIZE 20971520 /* 20mb - size of normalized dn cache */ /* filter.c */ diff --git a/test/libslapd/operation/v3_compat.c b/test/libslapd/operation/v3_compat.c index be70c25b7..0b470622e 100644 --- a/test/libslapd/operation/v3_compat.c +++ b/test/libslapd/operation/v3_compat.c @@ -24,6 +24,8 @@ void test_libslapd_operation_v3c_target_spec(void **state __attribute__((unused))) { + /* Need to start the ndn cache ... */ + ndn_cache_init(); /* Will we need to test PB / op interactions? */ /* Test the operation of the target spec is maintained. */ Slapi_Operation *op = slapi_operation_new(SLAPI_OP_FLAG_INTERNAL); @@ -53,4 +55,6 @@ test_libslapd_operation_v3c_target_spec(void **state __attribute__((unused))) /* target_spec in now the b_sdn, so operation free will free it */ // slapi_sdn_free(&b_sdn); operation_free(&op, NULL); + /* Close ndn cache */ + ndn_cache_destroy(); } diff --git a/test/libslapd/pblock/v3_compat.c b/test/libslapd/pblock/v3_compat.c index 22a99f30b..25bf7283d 100644 --- a/test/libslapd/pblock/v3_compat.c +++ b/test/libslapd/pblock/v3_compat.c @@ -9,6 +9,9 @@ #include "../../test_slapd.h" #include <string.h> +/* We need this for ndn init */ +#include <slap.h> + /* * Assert that the compatability requirements of the plugin V3 pblock API * are upheld. @@ -21,6 +24,7 @@ void test_libslapd_pblock_v3c_target_dn(void **state __attribute__((unused))) { + ndn_cache_init(); /* Create a pblock */ Slapi_PBlock *pb = slapi_pblock_new(); Slapi_Operation *op = slapi_operation_new(SLAPI_OP_FLAG_INTERNAL); @@ -68,12 +72,14 @@ test_libslapd_pblock_v3c_target_dn(void **state __attribute__((unused))) /* It works! */ slapi_pblock_destroy(pb); + ndn_cache_destroy(); } void test_libslapd_pblock_v3c_target_sdn(void **state __attribute__((unused))) { + ndn_cache_init(); /* SLAPI_TARGET_SDN */ Slapi_PBlock *pb = slapi_pblock_new(); Slapi_Operation *op = slapi_operation_new(SLAPI_OP_FLAG_INTERNAL); @@ -137,6 +143,7 @@ test_libslapd_pblock_v3c_target_sdn(void **state __attribute__((unused))) /* It works! */ slapi_pblock_destroy(pb); + ndn_cache_destroy(); } /* nf here means "no implicit free". For now implies no dup */ @@ -177,6 +184,7 @@ _test_libslapi_pblock_v3c_generic_nf_char(Slapi_PBlock *pb, int type, int *confl void test_libslapd_pblock_v3c_original_target_dn(void **state __attribute__((unused))) { + ndn_cache_init(); /* SLAPI_ORIGINAL_TARGET_DN */ Slapi_PBlock *pb = slapi_pblock_new(); Slapi_Operation *op = slapi_operation_new(SLAPI_OP_FLAG_INTERNAL); @@ -190,6 +198,7 @@ test_libslapd_pblock_v3c_original_target_dn(void **state __attribute__((unused)) /* It works! */ slapi_pblock_destroy(pb); + ndn_cache_destroy(); } void
0
d23ef6d303185c322aeb9d755daa767ecc111e19
389ds/389-ds-base
Ticket 50125 - perl fix ups for tmpfiles Bug Description: I missed updating the perl tools during the tmpfiles fix. Fix Description: Change the name in dscreate.pm https://pagure.io/389-ds-base/issue/50125 Author: William Brown <[email protected]> Review by: vashirov (Thanks!)
commit d23ef6d303185c322aeb9d755daa767ecc111e19 Author: William Brown <[email protected]> Date: Thu Jan 17 09:58:42 2019 +1000 Ticket 50125 - perl fix ups for tmpfiles Bug Description: I missed updating the perl tools during the tmpfiles fix. Fix Description: Change the name in dscreate.pm https://pagure.io/389-ds-base/issue/50125 Author: William Brown <[email protected]> Review by: vashirov (Thanks!) diff --git a/ldap/admin/src/scripts/DSCreate.pm.in b/ldap/admin/src/scripts/DSCreate.pm.in index 248b65d09..b586cef53 100644 --- a/ldap/admin/src/scripts/DSCreate.pm.in +++ b/ldap/admin/src/scripts/DSCreate.pm.in @@ -1066,7 +1066,7 @@ sub updateSelinuxPolicy { sub updateTmpfilesDotD { my $inf = shift; - my $dir = "@with_tmpfiles_d@"; + my $dir = "@tmpfiles_d@"; my $rundir; my $lockdir; my $parentdir; @@ -1430,7 +1430,7 @@ sub removeDSInstance { } } - my $tmpfilesdir = "@with_tmpfiles_d@"; + my $tmpfilesdir = "@tmpfiles_d@"; my $tmpfilesname = "$tmpfilesdir/@package_name@-$inst.conf"; if ((getLogin() eq 'root') && $tmpfilesdir && -d $tmpfilesdir && -f $tmpfilesname) { my $rc = unlink($tmpfilesname);
0
73cb6b9e4875fd2ff9a7745c47ffc7826600297d
389ds/389-ds-base
Issue: 48851 - investigate and port TET matching rules filter tests(index) Investigate and port TET matching rules filter tests(index) Relates: https://pagure.io/389-ds-base/issue/48851 Author: aborah Reviewed by: Simon Pichugin
commit 73cb6b9e4875fd2ff9a7745c47ffc7826600297d Author: Anuj Borah <[email protected]> Date: Tue Jun 18 15:22:56 2019 +0530 Issue: 48851 - investigate and port TET matching rules filter tests(index) Investigate and port TET matching rules filter tests(index) Relates: https://pagure.io/389-ds-base/issue/48851 Author: aborah Reviewed by: Simon Pichugin diff --git a/dirsrvtests/tests/suites/filter/filter_indexing_test.py b/dirsrvtests/tests/suites/filter/filter_indexing_test.py new file mode 100644 index 000000000..c7aec90ab --- /dev/null +++ b/dirsrvtests/tests/suites/filter/filter_indexing_test.py @@ -0,0 +1,163 @@ +# --- BEGIN COPYRIGHT BLOCK --- +# Copyright (C) 2019 Red Hat, Inc. +# All rights reserved. +# +# License: GPL (version 3 or any later version). +# See LICENSE for details. +# --- END COPYRIGHT BLOCK ---- + + +""" +verify and testing indexing Filter from a search +""" + +import os +import pytest + +from lib389._constants import DEFAULT_SUFFIX, PW_DM +from lib389.topologies import topology_st as topo +from lib389.idm.user import UserAccounts +from lib389.idm.account import Accounts +from lib389.cos import CosTemplates +from lib389.schema import Schema + +pytestmark = pytest.mark.tier1 + + +FILTERS = ["(|(|(ou=nothing1)(ou=people))(|(ou=nothing2)(ou=nothing3)))", + "(|(|(ou=people)(ou=nothing1))(|(ou=nothing2)(ou=nothing3)))", + "(|(|(ou=nothing1)(ou=nothing2))(|(ou=people)(ou=nothing3)))", + "(|(|(ou=nothing1)(ou=nothing2))(|(ou=nothing3)(ou=people)))", + "(&(sn<=0000000000000000)(givenname>=FFFFFFFFFFFFFFFF))", + "(&(sn>=0000000000000000)(sn<=1111111111111111))", + "(&(sn>=0000000000000000)(givenname<=FFFFFFFFFFFFFFFF))"] + +INDEXES = ["(uidNumber=18446744073709551617)", + "(gidNumber=18446744073709551617)", + "(MYINTATTR=18446744073709551617)", + "(&(uidNumber=*)(!(uidNumber=18446744073709551617)))", + "(&(gidNumber=*)(!(gidNumber=18446744073709551617)))", + "(&(uidNumber=*)(!(gidNumber=18446744073709551617)))", + "(&(myintattr=*)(!(myintattr=18446744073709551617)))", + "(uidNumber>=-18446744073709551617)", + "(gidNumber>=-18446744073709551617)", + "(uidNumber<=18446744073709551617)", + "(gidNumber<=18446744073709551617)", + "(myintattr<=18446744073709551617)"] + + +INDEXES_FALSE = ["(gidNumber=54321)", + "(uidNumber=54321)", + "(myintattr=54321)", + "(gidNumber<=-999999999999999999999999999999)", + "(uidNumber<=-999999999999999999999999999999)", + "(myintattr<=-999999999999999999999999999999)", + "(gidNumber>=999999999999999999999999999999)", + "(uidNumber>=999999999999999999999999999999)", + "(myintattr>=999999999999999999999999999999)"] + + [email protected](scope="module") +def _create_entries(topo): + """ + Will create necessary users for this script. + """ + # Creating Users + users_people = UserAccounts(topo.standalone, DEFAULT_SUFFIX) + + for count in range(3): + users_people.create(properties={ + 'ou': ['Accounting', 'People'], + 'cn': f'User {count}F', + 'sn': f'{count}' * 16, + 'givenname': 'FFFFFFFFFFFFFFFF', + 'uid': f'user{count}F', + 'mail': f'user{count}[email protected]', + 'manager': f'uid=user{count}F,ou=People,{DEFAULT_SUFFIX}', + 'userpassword': PW_DM, + 'homeDirectory': '/home/' + f'user{count}F', + 'uidNumber': '1000', + 'gidNumber': '2000', + }) + + cos = CosTemplates(topo.standalone, DEFAULT_SUFFIX, rdn='ou=People') + for user, number, des in [('a', '18446744073709551617', '2^64+1'), + ('b', '18446744073709551618', '2^64+1'), + ('c', '-18446744073709551617', '-2^64+1'), + ('d', '-18446744073709551618', '-2^64+1'), + ('e', '0', '0'), + ('f', '2', '2'), + ('g', '-2', '-2')]: + cos.create(properties={ + 'cn': user, + 'uidnumber': number, + 'gidnumber': number, + 'myintattr': number, + 'description': f'uidnumber value {des} - gidnumber is same but not indexed' + }) + + [email protected]("real_value", FILTERS) +def test_positive(topo, _create_entries, real_value): + """Test positive filters + :id: 57243326-91ae-11e9-aca3-8c16451d917b + :setup: Standalone + :steps: + 1. Try to pass filter rules as per the condition . + :expected results: + 1. Pass + """ + assert Accounts(topo.standalone, DEFAULT_SUFFIX).filter(real_value) + + +def test_indexing_schema(topo, _create_entries): + """Test with schema + :id: 67a2179a-91ae-11e9-9a33-8c16451d917b + :setup: Standalone + :steps: + 1. Add attribute types to Schema. + 2. Try to pass filter rules as per the condition . + :expected results: + 1. Pass + 2. Pass + """ + cos = CosTemplates(topo.standalone, DEFAULT_SUFFIX, rdn='ou=People') + Schema(topo.standalone).add('attributetypes', + "( 8.9.10.11.12.13.14.15 NAME 'myintattr' DESC 'for integer " + "syntax index ordering testing' EQUALITY integerMatch ORDERING " + "integerOrderingMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 )") + topo.standalone.restart() + assert cos.filter("(myintattr>=-18446744073709551617)") + + [email protected]("real_value", INDEXES) +def test_indexing(topo, _create_entries, real_value): + """Test positive index filters + :id: 7337589a-91ae-11e9-ad44-8c16451d917b + :setup: Standalone + :steps: + 1. Try to pass filter rules as per the condition . + :expected results: + 1. Pass + """ + cos = CosTemplates(topo.standalone, DEFAULT_SUFFIX, rdn='ou=People') + assert cos.filter(real_value) + + [email protected]("real_value", INDEXES_FALSE) +def test_indexing_negative(topo, _create_entries, real_value): + """Test negative index filters + :id: 7e19deae-91ae-11e9-900c-8c16451d917b + :setup: Standalone + :steps: + 1. Try to pass negative filter rules as per the condition . + :expected results: + 1. Fail + """ + cos = CosTemplates(topo.standalone, DEFAULT_SUFFIX, rdn='ou=People') + assert not cos.filter(real_value) + + +if __name__ == '__main__': + CURRENT_FILE = os.path.realpath(__file__) + pytest.main("-s -v %s" % CURRENT_FILE)
0
836e08dc192bd3a9c8a10c3869c5efc48bf13024
389ds/389-ds-base
Bug(s) fixed: 181827 Bug Description: If you delete an attribute from an entry on AD, the attribute doesn't get deleted on the DS side. The replication code doesn't even notice that the entry changed. Reviewed by: Rich, Noriko, Pete (thanks!) Files: see diffs Branch: HEAD, Directory71Branch Fix Description: The dirsync search control passes back deleted attributes with no values. If you try to add a Slapi_Attr with no values to a Slapi_Entry, it doesn't get added. This fix stuffs the deleted attributes into the deleted attributes list in the Slapi_Entry and checks for them when creating the modification operations to be performed on the local entry. Flag Day: no Doc impact: no QA impact: A regression test needs to be added New Tests integrated into TET: none
commit 836e08dc192bd3a9c8a10c3869c5efc48bf13024 Author: Nathan Kinder <[email protected]> Date: Mon Feb 20 19:36:24 2006 +0000 Bug(s) fixed: 181827 Bug Description: If you delete an attribute from an entry on AD, the attribute doesn't get deleted on the DS side. The replication code doesn't even notice that the entry changed. Reviewed by: Rich, Noriko, Pete (thanks!) Files: see diffs Branch: HEAD, Directory71Branch Fix Description: The dirsync search control passes back deleted attributes with no values. If you try to add a Slapi_Attr with no values to a Slapi_Entry, it doesn't get added. This fix stuffs the deleted attributes into the deleted attributes list in the Slapi_Entry and checks for them when creating the modification operations to be performed on the local entry. Flag Day: no Doc impact: no QA impact: A regression test needs to be added New Tests integrated into TET: none diff --git a/ldap/servers/plugins/replication/windows_connection.c b/ldap/servers/plugins/replication/windows_connection.c index 58408a49d..4583c1026 100644 --- a/ldap/servers/plugins/replication/windows_connection.c +++ b/ldap/servers/plugins/replication/windows_connection.c @@ -557,7 +557,19 @@ windows_LDAPMessage2Entry(LDAP * ld, LDAPMessage * msg, int attrsonly) { { type_to_use = a; } - slapi_entry_add_values( e, type_to_use, aVal); + + /* If the list of attribute values is null, we need to delete this attribute + * from the local entry. + */ + if (aVal == NULL) { + /* Windows will send us an attribute with no values if it was deleted + * on the AD side. Add this attribute to the deleted attributes list */ + Slapi_Attr *attr = slapi_attr_new(); + slapi_attr_init(attr, type_to_use); + entry_add_deleted_attribute_wsi(e, attr); + } else { + slapi_entry_add_values( e, type_to_use, aVal); + } ldap_memfree(a); ldap_value_free_len(aVal); diff --git a/ldap/servers/plugins/replication/windows_protocol_util.c b/ldap/servers/plugins/replication/windows_protocol_util.c index 827f7ab85..e3227f891 100644 --- a/ldap/servers/plugins/replication/windows_protocol_util.c +++ b/ldap/servers/plugins/replication/windows_protocol_util.c @@ -2496,6 +2496,7 @@ windows_generate_update_mods(Private_Repl_Protocol *prp,Slapi_Entry *remote_entr { int retval = 0; Slapi_Attr *attr = NULL; + Slapi_Attr *del_attr = NULL; int is_user = 0; int is_group = 0; int rc = 0; @@ -2638,17 +2639,48 @@ windows_generate_update_mods(Private_Repl_Protocol *prp,Slapi_Entry *remote_entr *do_modify = 1; } } + if (vs) { slapi_valueset_free(vs); vs = NULL; } - if (local_type) - { - slapi_ch_free((void**)&local_type); - local_type = NULL; - } - } + + slapi_ch_free_string(&local_type); + } + + /* Check if any attributes were deleted from the remote entry */ + entry_first_deleted_attribute(remote_entry, &del_attr); + while (del_attr != NULL) { + Slapi_Attr *local_attr = NULL; + char *type = NULL; + char *local_type = NULL; + int mapdn = 0; + + /* Map remote type to local type */ + slapi_attr_get_type(del_attr, &type); + if ( is_straight_mapped_attr(type,is_user,is_nt4) ) { + local_type = slapi_ch_strdup(type); + } else { + windows_map_attr_name(type , to_windows, is_user, 0 /* not create */, &local_type, &mapdn); + } + + /* Check if this attr exists in the local entry */ + if (local_type) { + slapi_entry_attr_find(local_entry, local_type, &local_attr); + if (local_attr) { + slapi_log_error(SLAPI_LOG_REPL, windows_repl_plugin_name, + "windows_generate_update_mods: deleting %s attribute from local entry\n", local_type); + /* Delete this attr from the local entry */ + slapi_mods_add_mod_values(smods, LDAP_MOD_DELETE, local_type, NULL); + *do_modify = 1; + } + } + + entry_next_deleted_attribute(remote_entry, &del_attr); + slapi_ch_free_string(&local_type); + } + if (slapi_is_loglevel_set(SLAPI_LOG_REPL) && *do_modify) { slapi_mods_dump(smods,"windows sync"); @@ -2669,14 +2701,18 @@ windows_update_remote_entry(Private_Repl_Protocol *prp,Slapi_Entry *remote_entry /* Now perform the modify if we need to */ if (0 == retval && do_modify) { + char dnbuf[BUFSIZ]; + char *dn = slapi_sdn_get_dn(slapi_entry_get_sdn_const(remote_entry)); slapi_log_error(SLAPI_LOG_REPL, windows_repl_plugin_name, - "windows_update_remote_entry: modifying entry %s\n", slapi_sdn_get_dn(slapi_entry_get_sdn_const(remote_entry))); + "windows_update_remote_entry: modifying entry %s\n", escape_string(dn, dnbuf)); retval = windows_conn_send_modify(prp->conn, slapi_sdn_get_dn(slapi_entry_get_sdn_const(remote_entry)),slapi_mods_get_ldapmods_byref(&smods), NULL,NULL); } else { + char dnbuf[BUFSIZ]; + char *dn = slapi_sdn_get_dn(slapi_entry_get_sdn_const(remote_entry)); slapi_log_error(SLAPI_LOG_REPL, windows_repl_plugin_name, - "no mods generated for entry: %s\n", slapi_sdn_get_dn(slapi_entry_get_sdn_const(remote_entry))); + "no mods generated for remote entry: %s\n", escape_string(dn, dnbuf)); } slapi_mods_done(&smods); return retval; @@ -2701,8 +2737,10 @@ windows_update_local_entry(Private_Repl_Protocol *prp,Slapi_Entry *remote_entry, pb = slapi_pblock_new(); if (pb) { + char dnbuf[BUFSIZ]; + char *dn = slapi_sdn_get_dn(slapi_entry_get_sdn_const(local_entry)); slapi_log_error(SLAPI_LOG_REPL, windows_repl_plugin_name, - "modifying entry: %s\n", slapi_sdn_get_dn(slapi_entry_get_sdn_const(local_entry))); + "modifying entry: %s\n", escape_string(dn, dnbuf)); slapi_modify_internal_set_pb (pb, slapi_entry_get_ndn(local_entry), slapi_mods_get_ldapmods_byref(&smods), NULL, NULL, repl_get_plugin_identity (PLUGIN_MULTIMASTER_REPLICATION), 0); slapi_modify_internal_pb (pb); @@ -2710,7 +2748,7 @@ windows_update_local_entry(Private_Repl_Protocol *prp,Slapi_Entry *remote_entry, if (rc) { slapi_log_error(SLAPI_LOG_FATAL, windows_repl_plugin_name, - "windows_update_local_entry: failed to modify entry %s\n", slapi_sdn_get_dn(slapi_entry_get_sdn_const(local_entry))); + "windows_update_local_entry: failed to modify entry %s\n", escape_string(dn, dnbuf)); } slapi_pblock_destroy(pb); } else @@ -2721,8 +2759,10 @@ windows_update_local_entry(Private_Repl_Protocol *prp,Slapi_Entry *remote_entry, } else { + char dnbuf[BUFSIZ]; + char *dn = slapi_sdn_get_dn(slapi_entry_get_sdn_const(local_entry)); slapi_log_error(SLAPI_LOG_REPL, windows_repl_plugin_name, - "no mods generated for entry: %s\n", slapi_sdn_get_dn(slapi_entry_get_sdn_const(remote_entry))); + "no mods generated for local entry: %s\n", escape_string(dn, dnbuf)); } slapi_mods_done(&smods); return retval; @@ -2959,6 +2999,22 @@ windows_process_dirsync_entry(Private_Repl_Protocol *prp,Slapi_Entry *e, int is_ windows_get_remote_entry(prp,slapi_entry_get_sdn_const(e),&remote_entry); if (remote_entry) { + /* We need to check for any deleted attrs from the dirsync entry + * and pass them into the newly fetched remote entry. */ + Slapi_Attr *attr = NULL; + Slapi_Attr *rem_attr = NULL; + entry_first_deleted_attribute(e, &attr); + while (attr != NULL) { + /* We need to dup the attr and add it to the remote entry. + * rem_attr is now owned by remote_entry, so don't free it */ + rem_attr = slapi_attr_dup(attr); + if (rem_attr) { + entry_add_deleted_attribute_wsi(remote_entry, rem_attr); + rem_attr = NULL; + } + entry_next_deleted_attribute(e, &attr); + } + rc = windows_update_local_entry(prp, remote_entry, local_entry); slapi_entry_free(remote_entry); remote_entry = NULL;
0
751446440f5269a246e6e652a64e63aa5933734a
389ds/389-ds-base
Ticket 49424 - Resolve csiphash alignment issues Bug Description: On some platforms, uint64_t is not the same size as a void * - as well, if the input is not aligned correctly, then a number of nasty crashes can result Fix Description: Instead of relying on alignment to be correct, we should memcpy the data to inputs instead. https://pagure.io/389-ds-base/issue/49424 Author: wibrown Review by: lslebodn, cgrzemba, vashirov, mreynolds (Thanks!)
commit 751446440f5269a246e6e652a64e63aa5933734a Author: William Brown <[email protected]> Date: Mon Oct 30 12:01:34 2017 +1000 Ticket 49424 - Resolve csiphash alignment issues Bug Description: On some platforms, uint64_t is not the same size as a void * - as well, if the input is not aligned correctly, then a number of nasty crashes can result Fix Description: Instead of relying on alignment to be correct, we should memcpy the data to inputs instead. https://pagure.io/389-ds-base/issue/49424 Author: wibrown Review by: lslebodn, cgrzemba, vashirov, mreynolds (Thanks!) diff --git a/src/libsds/external/csiphash/csiphash.c b/src/libsds/external/csiphash/csiphash.c index 0089c82f7..2351db6cf 100644 --- a/src/libsds/external/csiphash/csiphash.c +++ b/src/libsds/external/csiphash/csiphash.c @@ -32,6 +32,9 @@ #include <inttypes.h> #include <stddef.h> /* for size_t */ +#include <stdlib.h> /* calloc,free */ +#include <string.h> /* memcpy */ + #include <config.h> #if defined(HAVE_SYS_ENDIAN_H) @@ -75,11 +78,24 @@ uint64_t sds_siphash13(const void *src, size_t src_sz, const char key[16]) { - const uint64_t *_key = (uint64_t *)key; + uint64_t _key[2] = {0}; + memcpy(_key, key, 16); uint64_t k0 = _le64toh(_key[0]); uint64_t k1 = _le64toh(_key[1]); uint64_t b = (uint64_t)src_sz << 56; - const uint64_t *in = (uint64_t *)src; + + size_t input_sz = (src_sz / sizeof(uint64_t)) + 1; + + /* Account for non-uint64_t alligned input */ + /* Could make this stack allocation */ + uint64_t *in = calloc(1, input_sz * sizeof(uint64_t)); + /* + * Because all crypto code sucks, they modify *in + * during operation, so we stash a copy of the ptr here. + * alternately, we could use stack allocated array, but gcc + * will complain about the vla being unbounded. + */ + uint64_t *in_ptr = memcpy(in, src, src_sz); uint64_t v0 = k0 ^ 0x736f6d6570736575ULL; uint64_t v1 = k1 ^ 0x646f72616e646f6dULL; @@ -96,27 +112,15 @@ sds_siphash13(const void *src, size_t src_sz, const char key[16]) v0 ^= mi; } + /* + * Because we allocate in as size + 1, we can over-read 0 + * for this buffer to be padded correctly. in here is a pointer to the + * excess data because the while loop above increments the in pointer + * to point to the excess once src_sz drops < 8. + */ uint64_t t = 0; - uint8_t *pt = (uint8_t *)&t; - uint8_t *m = (uint8_t *)in; - - switch (src_sz) { - case 7: - pt[6] = m[6]; /* FALLTHRU */ - case 6: - pt[5] = m[5]; /* FALLTHRU */ - case 5: - pt[4] = m[4]; /* FALLTHRU */ - case 4: - *((uint32_t *)&pt[0]) = *((uint32_t *)&m[0]); - break; - case 3: - pt[2] = m[2]; /* FALLTHRU */ - case 2: - pt[1] = m[1]; /* FALLTHRU */ - case 1: - pt[0] = m[0]; /* FALLTHRU */ - } + memcpy(&t, in, sizeof(uint64_t)); + b |= _le64toh(t); v3 ^= b; @@ -126,5 +130,9 @@ sds_siphash13(const void *src, size_t src_sz, const char key[16]) v2 ^= 0xff; // dround dROUND(v0, v1, v2, v3); + + free(in_ptr); + return (v0 ^ v1) ^ (v2 ^ v3); } + diff --git a/src/libsds/test/test_sds_csiphash.c b/src/libsds/test/test_sds_csiphash.c index cdb6b7f46..cc9a6b2b5 100644 --- a/src/libsds/test/test_sds_csiphash.c +++ b/src/libsds/test/test_sds_csiphash.c @@ -25,23 +25,48 @@ static void test_siphash(void **state __attribute__((unused))) { - - // uint64_t value = 0; uint64_t hashout = 0; char key[16] = {0}; - uint64_t test_a = 15794382300316794652U; - uint64_t test_b = 13042610424265326907U; + uint64_t test_simple = 15794382300316794652U; - // Initial simple test + /* Initial simple test */ value = htole64(5); hashout = sds_siphash13(&value, sizeof(uint64_t), key); - assert_true(hashout == test_a); + assert_int_equal(hashout, test_simple); + + /* Test a range of input sizes to check endianness behaviour */ + + hashout = sds_siphash13("a", 1, key); + assert_int_equal(hashout, 0x407448d2b89b1813U); + + hashout = sds_siphash13("aa", 2, key); + assert_int_equal(hashout, 0x7910e0436ed8d1deU); + + hashout = sds_siphash13("aaa", 3, key); + assert_int_equal(hashout, 0xf752893a6c769652U); + + hashout = sds_siphash13("aaaa", 4, key); + assert_int_equal(hashout, 0x8b02350718d87164U); + + hashout = sds_siphash13("aaaaa", 5, key); + assert_int_equal(hashout, 0x92a991474c7eef2U); + + hashout = sds_siphash13("aaaaaa", 6, key); + assert_int_equal(hashout, 0xf0ab815a640277ccU); + + hashout = sds_siphash13("aaaaaaa", 7, key); + assert_int_equal(hashout, 0x33f3c6d7dbc82c0dU); + + hashout = sds_siphash13("aaaaaaaa", 8, key); + assert_int_equal(hashout, 0xc501b12e18428c92U); + + hashout = sds_siphash13("aaaaaaaabbbb", 12, key); + assert_int_equal(hashout, 0xcddca673069ade64U); - char *test = "abc"; - hashout = sds_siphash13(test, 4, key); - assert_true(hashout == test_b); + hashout = sds_siphash13("aaaaaaaabbbbbbbb", 16, key); + assert_int_equal(hashout, 0xdc54f0bfc0e1deb0U); } int
0
74045251c748d3a6d15cb37e920d6ba6ddbfc922
389ds/389-ds-base
Ticket 49184 - Overflow in memberof Bug Description: The function memberof_call_foreach_dn can be used to retrieve ancestors of a given entry. (ancestors are groups owning directly or indirectly a given entry). With the use of group cache in memberof, at the entrance of memberof_call_foreach_dn there is an attempt to get the entry ancestors from the cache. Before doing so it needs to test if the cache is safe. In fact in case of circular groups the use of the cache is disabled and lookup in the cache should not happend. To know if the cache is safe it needs to access a flag (use_cache) in callback_data. The callback_data structure is opaque at this level. So accessing it while its structure is unknown is dangerous. The bug is that we may read an 'int' at an offset that overflow the actual structure. This is just a test and should not trigger a crash. Fix Description: Add a flag to call memberof_call_foreach_dn so that, that indicates if it is valid to use the group cache. https://pagure.io/389-ds-base/issue/49184 Reviewed by: William Brown and Mark Reynolds (thanks to you !!) Platforms tested: F23 Flag Day: no Doc impact: no
commit 74045251c748d3a6d15cb37e920d6ba6ddbfc922 Author: Thierry Bordaz <[email protected]> Date: Thu Apr 13 15:21:49 2017 +0200 Ticket 49184 - Overflow in memberof Bug Description: The function memberof_call_foreach_dn can be used to retrieve ancestors of a given entry. (ancestors are groups owning directly or indirectly a given entry). With the use of group cache in memberof, at the entrance of memberof_call_foreach_dn there is an attempt to get the entry ancestors from the cache. Before doing so it needs to test if the cache is safe. In fact in case of circular groups the use of the cache is disabled and lookup in the cache should not happend. To know if the cache is safe it needs to access a flag (use_cache) in callback_data. The callback_data structure is opaque at this level. So accessing it while its structure is unknown is dangerous. The bug is that we may read an 'int' at an offset that overflow the actual structure. This is just a test and should not trigger a crash. Fix Description: Add a flag to call memberof_call_foreach_dn so that, that indicates if it is valid to use the group cache. https://pagure.io/389-ds-base/issue/49184 Reviewed by: William Brown and Mark Reynolds (thanks to you !!) Platforms tested: F23 Flag Day: no Doc impact: no diff --git a/dirsrvtests/tests/tickets/ticket49184_test.py b/dirsrvtests/tests/tickets/ticket49184_test.py new file mode 100644 index 000000000..20edfde58 --- /dev/null +++ b/dirsrvtests/tests/tickets/ticket49184_test.py @@ -0,0 +1,146 @@ +import time +import ldap +import logging +import pytest +from lib389 import DirSrv, Entry, tools, tasks +from lib389.tools import DirSrvTools +from lib389._constants import * +from lib389.properties import * +from lib389.tasks import * +from lib389.utils import * +from lib389.topologies import topology_st as topo + +DEBUGGING = os.getenv("DEBUGGING", default=False) +GROUP_DN_1 = ("cn=group1," + DEFAULT_SUFFIX) +GROUP_DN_2 = ("cn=group2," + DEFAULT_SUFFIX) +SUPER_GRP1 = ("cn=super_grp1," + DEFAULT_SUFFIX) +SUPER_GRP2 = ("cn=super_grp2," + DEFAULT_SUFFIX) +SUPER_GRP3 = ("cn=super_grp3," + DEFAULT_SUFFIX) + +if DEBUGGING: + logging.getLogger(__name__).setLevel(logging.DEBUG) +else: + logging.getLogger(__name__).setLevel(logging.INFO) +log = logging.getLogger(__name__) + +def _add_group_with_members(topo, group_dn): + # Create group + try: + topo.standalone.add_s(Entry((group_dn, + {'objectclass': 'top groupofnames extensibleObject'.split(), + 'cn': 'group'}))) + except ldap.LDAPError as e: + log.fatal('Failed to add group: error ' + e.message['desc']) + assert False + + # Add members to the group - set timeout + log.info('Adding members to the group...') + for idx in range(1, 5): + try: + MEMBER_VAL = ("uid=member%d,%s" % (idx, DEFAULT_SUFFIX)) + topo.standalone.modify_s(group_dn, + [(ldap.MOD_ADD, + 'member', + MEMBER_VAL)]) + except ldap.LDAPError as e: + log.fatal('Failed to update group: member (%s) - error: %s' % + (MEMBER_VAL, e.message['desc'])) + assert False + +def _check_memberof(topo, member=None, memberof=True, group_dn=None): + # Check that members have memberof attribute on M1 + for idx in range(1, 5): + try: + USER_DN = ("uid=member%d,%s" % (idx, DEFAULT_SUFFIX)) + ent = topo.standalone.getEntry(USER_DN, ldap.SCOPE_BASE, "(objectclass=*)") + if presence_flag: + assert ent.hasAttr('memberof') and ent.getValue('memberof') == group_dn + else: + assert not ent.hasAttr('memberof') + except ldap.LDAPError as e: + log.fatal('Failed to retrieve user (%s): error %s' % (USER_DN, e.message['desc'])) + assert False + +def _check_memberof(topo, member=None, memberof=True, group_dn=None): + ent = topo.standalone.getEntry(member, ldap.SCOPE_BASE, "(objectclass=*)") + if memberof: + assert group_dn + assert ent.hasAttr('memberof') and group_dn in ent.getValues('memberof') + else: + if ent.hasAttr('memberof'): + assert group_dn not in ent.getValues('memberof') + + +def test_ticket49184(topo): + """Write your testcase here... + + Also, if you need any testcase initialization, + please, write additional fixture for that(include finalizer). + """ + + topo.standalone.plugins.enable(name=PLUGIN_MEMBER_OF) + topo.standalone.restart(timeout=10) + + # + # create some users and a group + # + log.info('create users and group...') + for idx in range(1, 5): + try: + USER_DN = ("uid=member%d,%s" % (idx, DEFAULT_SUFFIX)) + topo.standalone.add_s(Entry((USER_DN, + {'objectclass': 'top extensibleObject'.split(), + 'uid': 'member%d' % (idx)}))) + except ldap.LDAPError as e: + log.fatal('Failed to add user (%s): error %s' % (USER_DN, e.message['desc'])) + assert False + + # add all users in GROUP_DN_1 and checks each users is memberof GROUP_DN_1 + _add_group_with_members(topo, GROUP_DN_1) + for idx in range(1, 5): + USER_DN = ("uid=member%d,%s" % (idx, DEFAULT_SUFFIX)) + _check_memberof(topo, member=USER_DN, memberof=True, group_dn=GROUP_DN_1 ) + + # add all users in GROUP_DN_2 and checks each users is memberof GROUP_DN_2 + _add_group_with_members(topo, GROUP_DN_2) + for idx in range(1, 5): + USER_DN = ("uid=member%d,%s" % (idx, DEFAULT_SUFFIX)) + _check_memberof(topo, member=USER_DN, memberof=True, group_dn=GROUP_DN_2 ) + + # add the level 2, 3 and 4 group + for super_grp in (SUPER_GRP1, SUPER_GRP2, SUPER_GRP3): + topo.standalone.add_s(Entry((super_grp, + {'objectclass': 'top groupofnames extensibleObject'.split(), + 'cn': 'super_grp'}))) + topo.standalone.modify_s(SUPER_GRP1, + [(ldap.MOD_ADD, + 'member', + GROUP_DN_1), + (ldap.MOD_ADD, + 'member', + GROUP_DN_2)]) + topo.standalone.modify_s(SUPER_GRP2, + [(ldap.MOD_ADD, + 'member', + GROUP_DN_1), + (ldap.MOD_ADD, + 'member', + GROUP_DN_2)]) + return + topo.standalone.delete_s(GROUP_DN_2) + for idx in range(1, 5): + USER_DN = ("uid=member%d,%s" % (idx, DEFAULT_SUFFIX)) + _check_memberof(topo, member=USER_DN, memberof=True, group_dn=GROUP_DN_1 ) + _check_memberof(topo, member=USER_DN, memberof=False, group_dn=GROUP_DN_2 ) + + if DEBUGGING: + # Add debugging steps(if any)... + pass + + +if __name__ == '__main__': + # Run isolated + # -s for DEBUG mode + CURRENT_FILE = os.path.realpath(__file__) + pytest.main("-s %s" % CURRENT_FILE) + diff --git a/ldap/servers/plugins/memberof/memberof.c b/ldap/servers/plugins/memberof/memberof.c index 899358d44..8d36b80fb 100644 --- a/ldap/servers/plugins/memberof/memberof.c +++ b/ldap/servers/plugins/memberof/memberof.c @@ -159,7 +159,7 @@ static int memberof_qsort_compare(const void *a, const void *b); static void memberof_load_array(Slapi_Value **array, Slapi_Attr *attr); static int memberof_del_dn_from_groups(Slapi_PBlock *pb, MemberOfConfig *config, Slapi_DN *sdn); static int memberof_call_foreach_dn(Slapi_PBlock *pb, Slapi_DN *sdn, MemberOfConfig *config, - char **types, plugin_search_entry_callback callback, void *callback_data, int *cached); + char **types, plugin_search_entry_callback callback, void *callback_data, int *cached, PRBool use_grp_cache); static int memberof_is_direct_member(MemberOfConfig *config, Slapi_Value *groupdn, Slapi_Value *memberdn); static int memberof_is_grouping_attr(char *type, MemberOfConfig *config); @@ -659,7 +659,7 @@ memberof_del_dn_from_groups(Slapi_PBlock *pb, MemberOfConfig *config, Slapi_DN * slapi_log_err(SLAPI_LOG_PLUGIN, MEMBEROF_PLUGIN_SUBSYSTEM, "memberof_del_dn_from_groups: Ancestors of %s\n", slapi_sdn_get_dn(sdn)); rc = memberof_call_foreach_dn(pb, sdn, config, groupattrs, - memberof_del_dn_type_callback, &data, &cached); + memberof_del_dn_type_callback, &data, &cached, PR_FALSE); } return rc; @@ -777,7 +777,7 @@ add_ancestors_cbdata(memberof_cached_value *ancestors, void *callback_data) */ int memberof_call_foreach_dn(Slapi_PBlock *pb __attribute__((unused)), Slapi_DN *sdn, - MemberOfConfig *config, char **types, plugin_search_entry_callback callback, void *callback_data, int *cached) + MemberOfConfig *config, char **types, plugin_search_entry_callback callback, void *callback_data, int *cached, PRBool use_grp_cache) { Slapi_PBlock *search_pb = NULL; Slapi_DN *base_sdn = NULL; @@ -792,9 +792,6 @@ memberof_call_foreach_dn(Slapi_PBlock *pb __attribute__((unused)), Slapi_DN *sdn int free_it = 0; int rc = 0; int i = 0; - memberof_cached_value *ht_grp = NULL; - memberof_get_groups_data *data = (memberof_get_groups_data*) callback_data; - const char *ndn = slapi_sdn_get_ndn(sdn); *cached = 0; @@ -802,17 +799,24 @@ memberof_call_foreach_dn(Slapi_PBlock *pb __attribute__((unused)), Slapi_DN *sdn return (rc); } - /* Here we will retrieve the ancestor of sdn. - * The key access is the normalized sdn - * This is done through recursive internal searches of parents - * If the ancestors of sdn are already cached, just use - * this value + /* This flags indicates memberof_call_foreach_dn is called to retrieve ancestors (groups). + * To improve performance, it can use a cache. (it will not in case of circular groups) + * When this flag is true it means no circular group are detected (so far) so we can use the cache */ - if (data && data->use_cache) { + if (use_grp_cache) { + /* Here we will retrieve the ancestor of sdn. + * The key access is the normalized sdn + * This is done through recursive internal searches of parents + * If the ancestors of sdn are already cached, just use + * this value + */ + memberof_cached_value *ht_grp = NULL; + const char *ndn = slapi_sdn_get_ndn(sdn); + ht_grp = ancestors_cache_lookup((const void *) ndn); if (ht_grp) { #if MEMBEROF_CACHE_DEBUG - slapi_log_err(SLAPI_LOG_PLUGIN, MEMBEROF_PLUGIN_SUBSYSTEM, "memberof_call_foreach_dn: Ancestors of %s already cached (%x)\n", ndn, ht_grp); + slapi_log_err(SLAPI_LOG_PLUGIN, MEMBEROF_PLUGIN_SUBSYSTEM, "memberof_call_foreach_dn: Ancestors of %s already cached (%x)\n", ndn, ht_grp); #endif add_ancestors_cbdata(ht_grp, callback_data); *cached = 1; @@ -1106,7 +1110,7 @@ memberof_replace_dn_from_groups(Slapi_PBlock *pb, MemberOfConfig *config, slapi_log_err(SLAPI_LOG_PLUGIN, MEMBEROF_PLUGIN_SUBSYSTEM, "memberof_replace_dn_from_groups: Ancestors of %s\n", slapi_sdn_get_dn(post_sdn)); if((ret = memberof_call_foreach_dn(pb, pre_sdn, config, groupattrs, memberof_replace_dn_type_callback, - &data, &cached))) + &data, &cached, PR_FALSE))) { break; } @@ -2383,7 +2387,7 @@ memberof_get_groups_r(MemberOfConfig *config, Slapi_DN *member_sdn, slapi_log_err(SLAPI_LOG_PLUGIN, MEMBEROF_PLUGIN_SUBSYSTEM, "memberof_get_groups_r: Ancestors of %s\n", slapi_sdn_get_dn(member_sdn)); #endif rc = memberof_call_foreach_dn(NULL, member_sdn, config, config->groupattrs, - memberof_get_groups_callback, &member_data, &cached); + memberof_get_groups_callback, &member_data, &cached, member_data.use_cache); merge_ancestors(&member_ndn_val, &member_data, data); if (!cached && member_data.use_cache) @@ -2578,7 +2582,7 @@ memberof_test_membership(Slapi_PBlock *pb, MemberOfConfig *config, int cached = 0; return memberof_call_foreach_dn(pb, group_sdn, config, attrs, - memberof_test_membership_callback, config, &cached); + memberof_test_membership_callback, config, &cached, PR_FALSE); } /*
0
aa3b4e66bcb893e1db2733f77a986873e0a8f888
389ds/389-ds-base
Issue 6086 - Ambiguous warning about SELinux in dscreate for non-root user Bug Description: When an instance is created using dscreate under non-root user, there is a scary looking ambiguous warning: > Selinux support will be disabled, continue? [yes]: It's not clear to the user what exactly are the implications (system-wide disabling of SELinux?). We should provide a better wording. Fix Description: Change the wording and fix spelling of SELinux in the log messages. Fixes: https://github.com/389ds/389-ds-base/issues/6086 Reviewed by: @progier389 (Thanks!)
commit aa3b4e66bcb893e1db2733f77a986873e0a8f888 Author: Viktor Ashirov <[email protected]> Date: Thu Feb 8 12:37:14 2024 +0100 Issue 6086 - Ambiguous warning about SELinux in dscreate for non-root user Bug Description: When an instance is created using dscreate under non-root user, there is a scary looking ambiguous warning: > Selinux support will be disabled, continue? [yes]: It's not clear to the user what exactly are the implications (system-wide disabling of SELinux?). We should provide a better wording. Fix Description: Change the wording and fix spelling of SELinux in the log messages. Fixes: https://github.com/389ds/389-ds-base/issues/6086 Reviewed by: @progier389 (Thanks!) diff --git a/src/lib389/lib389/config.py b/src/lib389/lib389/config.py index 23a60d979..09056cee1 100644 --- a/src/lib389/lib389/config.py +++ b/src/lib389/lib389/config.py @@ -70,9 +70,9 @@ class Config(DSLdapObject): if selinux_present() and (key.lower() == 'nsslapd-secureport' or key.lower() == 'nsslapd-port'): # Get old port and remove label old_port = self.get_attr_val_utf8(key) - self.log.debug("Removing old port's selinux label...") + self.log.debug("Removing old port's SELinux label...") selinux_label_port(old_port, remove_label=True) - self.log.debug("Setting new port's selinux label...") + self.log.debug("Setting new port's SELinux label...") selinux_label_port(value) super(Config, self).replace(key, value) diff --git a/src/lib389/lib389/instance/remove.py b/src/lib389/lib389/instance/remove.py index 6f31f2364..9e41fb5be 100644 --- a/src/lib389/lib389/instance/remove.py +++ b/src/lib389/lib389/instance/remove.py @@ -122,7 +122,7 @@ def remove_ds_instance(dirsrv, force=False): except OSError as e: _log.debug("Failed to remove tmpfile: " + str(e)) - # Nor can we assume we have selinux. Try docker sometime ;) + # Nor can we assume we have SELinux. if dirsrv.ds_paths.with_selinux: # Remove selinux port label _log.debug("Removing the port labels") @@ -133,7 +133,7 @@ def remove_ds_instance(dirsrv, force=False): selinux_label_port(dirsrv.sslport, remove_label=True) # If this was the last instance, remove the ssca instance - # and all ds related selinux customizations + # and all ds related SELinux customizations insts = dirsrv.list(all=True) if len(insts) == 0: ssca = NssSsl(dbpath=dirsrv.get_ssca_dir()) diff --git a/src/lib389/lib389/instance/setup.py b/src/lib389/lib389/instance/setup.py index 1cdb47348..01027bc7e 100644 --- a/src/lib389/lib389/instance/setup.py +++ b/src/lib389/lib389/instance/setup.py @@ -318,7 +318,7 @@ class SetupDs(object): # Let them know about the selinux status if not selinux_present(): - val = input('\nSelinux support will be disabled, continue? [yes]: ') + val = input('\nSELinux labels will not be applied, continue? [yes]: ') if val.strip().lower().startswith('n'): return diff --git a/src/lib389/lib389/tools.py b/src/lib389/lib389/tools.py index 7e47d373d..df6ba7923 100644 --- a/src/lib389/lib389/tools.py +++ b/src/lib389/lib389/tools.py @@ -410,7 +410,7 @@ class DirSrvTools(object): certdir = e_config.getValue('nsslapd-certdir') # have to stop the server before replacing any security files DirSrvTools.stop(dirsrv) - # allow secport for selinux + # allow secport for SELinux if secport != 636: try: log.debug("Configuring SELinux on port: %s", str(secport)) diff --git a/src/lib389/lib389/utils.py b/src/lib389/lib389/utils.py index 963ed2324..4f3967889 100644 --- a/src/lib389/lib389/utils.py +++ b/src/lib389/lib389/utils.py @@ -194,7 +194,7 @@ SIZE_PATTERN = r'\s*(\d*\.?\d*)\s*([tgmk]?)b?\s*' def selinux_present(): """ - Determine if selinux libraries are on a system, and if so, if we are in + Determine if SELinux libraries are on a system, and if so, if we are in a state to consume them (enabled, disabled). :returns: bool @@ -204,20 +204,20 @@ def selinux_present(): try: import selinux if selinux.is_selinux_enabled(): - # We have selinux, lets see if we are allowed to configure it. + # We have SELinux, lets see if we are allowed to configure it. # (just checking the uid for now - we may rather check if semanage command success) if os.geteuid() != 0: - log.info('Non privileged user cannot use semanage, will not relabel ports or files.' ) + log.info('Non-privileged user cannot use semanage, will not relabel ports or files.' ) elif not os.path.exists('/usr/sbin/semanage'): log.info('semanage command is not installed, will not relabel ports or files. Please install policycoreutils-python-utils.' ) else: status = True else: # We have the module, but it's disabled. - log.info('selinux is disabled, will not relabel ports or files.' ) + log.info('SELinux is disabled, will not relabel ports or files.' ) except ImportError: # No python module, so who knows what state we are in. - log.error('selinux python module not found, will not relabel files.' ) + log.error('SELinux python module not found, will not relabel files.' ) return status @@ -233,11 +233,11 @@ def selinux_restorecon(path): try: import selinux except ImportError: - log.debug('selinux python module not found, skipping relabel path %s' % path) + log.debug('SELinux python module not found, skipping relabel path %s' % path) return if not selinux.is_selinux_enabled(): - log.debug('selinux is disabled, skipping relabel path %s' % path) + log.debug('SELinux is disabled, skipping relabel path %s' % path) return try: @@ -320,7 +320,7 @@ def selinux_label_file(path, label): rc = 0 for i in range(5): try: - log.debug(f"Setting label {label} in SELinux file context {path}. Attempt {i}") + log.debug(f"Setting label {label} in SELinux file context {path}. Attempt {i}") result = subprocess.run(["semanage", "fcontext", "-a", "-t", label, path], stdout=subprocess.PIPE, stderr=subprocess.PIPE) @@ -375,7 +375,7 @@ def selinux_clean_ports_label(): def _get_selinux_port_policies(port): - """Get a list of selinux port policies for the specified port, 'tcp' protocol and + """Get a list of SELinux port policies for the specified port, 'tcp' protocol and excluding 'unreserved_port_t', 'reserved_port_t', 'ephemeral_port_t' labels""" # [2:] - cut first lines containing the headers. [:-1] - empty line @@ -413,11 +413,11 @@ def selinux_label_port(port, remove_label=False): try: import selinux except ImportError: - log.debug('selinux python module not found, skipping port labeling.') + log.debug('SELinux python module not found, skipping port labeling.') return if not selinux_present(): - log.debug('selinux is disabled, skipping port relabel') + log.debug('SELinux is disabled, skipping port relabel') return # We only label ports that ARE NOT in the default policy that comes with @@ -618,7 +618,7 @@ def valgrind_enable(sbin_dir, wrapper=None): (making a backup of the original ns-slapd binary). The script calling valgrind_enable() must be run as the 'root' user - as selinux needs to be disabled for valgrind to work + as SELinux needs to be disabled for valgrind to work The server instance(s) should be stopped prior to calling this function. Then after calling valgrind_enable(): @@ -685,7 +685,7 @@ def valgrind_enable(sbin_dir, wrapper=None): raise IOError('failed to copy valgrind wrapper to ns-slapd, error: %s' % e.strerror) - # Disable selinux + # Disable SELinux if os.geteuid() == 0: os.system('setenforce 0') @@ -709,7 +709,7 @@ def valgrind_disable(sbin_dir): Restore the ns-slapd binary to its original state - the server instances are expected to be stopped. - Note - selinux is enabled at the end of this process. + Note - SELinux is enabled at the end of this process. :param sbin_dir - the location of the ns-slapd binary (e.g. /usr/sbin) :raise ValueError @@ -742,7 +742,7 @@ def valgrind_disable(sbin_dir): raise ValueError('Failed to delete backup ns-slapd, error: %s' % e.strerror) - # Enable selinux + # Enable SELinux if os.geteuid() == 0: os.system('setenforce 1')
0
06ff5b77dc03056bfb92bd24c6fabf13fe607e25
389ds/389-ds-base
Issue 4262 - Remove legacy tools subpackage (restart instances after rpm install) Description: Update specfile to restart instances after installing new rpm Relates: https://github.com/389ds/389-ds-base/issues/4262 Reviewed by: viktor(Thanks!)
commit 06ff5b77dc03056bfb92bd24c6fabf13fe607e25 Author: Mark Reynolds <[email protected]> Date: Mon Oct 26 11:02:59 2020 -0400 Issue 4262 - Remove legacy tools subpackage (restart instances after rpm install) Description: Update specfile to restart instances after installing new rpm Relates: https://github.com/389ds/389-ds-base/issues/4262 Reviewed by: viktor(Thanks!) diff --git a/rpm/389-ds-base.spec.in b/rpm/389-ds-base.spec.in index fb73d6323..a810690cb 100644 --- a/rpm/389-ds-base.spec.in +++ b/rpm/389-ds-base.spec.in @@ -61,7 +61,8 @@ Group: System Environment/Daemons # Is this still needed? BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-root-%(%{__id_u} -n) Obsoletes: %{name} <= 1.4.0.9 -Obsoletes: %{name}-legacy-tools +Obsoletes: %{name}-legacy-tools < 1.4.4.6 +Obsoletes: %{name}-legacy-tools-debuginfo < 1.4.4.6 Provides: ldif2ldbm # Attach the buildrequires to the top level package: @@ -495,6 +496,41 @@ fi # Reload our sysctl before we restart (if we can) sysctl --system &> $output; true +# Gather the running instances so we can restart them +instbase="%{_sysconfdir}/%{pkgname}" +ninst=0 +for dir in $instbase/slapd-* ; do + echo dir = $dir >> $output 2>&1 || : + if [ ! -d "$dir" ] ; then continue ; fi + case "$dir" in *.removed) continue ;; esac + basename=`basename $dir` + inst="%{pkgname}@`echo $basename | sed -e 's/slapd-//g'`" + echo found instance $inst - getting status >> $output 2>&1 || : + if /bin/systemctl -q is-active $inst ; then + echo instance $inst is running >> $output 2>&1 || : + instances="$instances $inst" + else + echo instance $inst is not running >> $output 2>&1 || : + fi + ninst=`expr $ninst + 1` +done +if [ $ninst -eq 0 ] ; then + echo no instances to upgrade >> $output 2>&1 || : + exit 0 # have no instances to upgrade - just skip the rest +else + # restart running instances + echo shutting down all instances . . . >> $output 2>&1 || : + for inst in $instances ; do + echo stopping instance $inst >> $output 2>&1 || : + /bin/systemctl stop $inst >> $output 2>&1 || : + done + for inst in $instances ; do + echo starting instance $inst >> $output 2>&1 || : + /bin/systemctl start $inst >> $output 2>&1 || : + done +fi + + %preun if [ $1 -eq 0 ]; then # Final removal # remove instance specific service files/links
0
4d9f7ad14480b5eeac1d2fe4cf98320a567f5e9f
389ds/389-ds-base
bump version to 1.2.7.1
commit 4d9f7ad14480b5eeac1d2fe4cf98320a567f5e9f Author: Rich Megginson <[email protected]> Date: Tue Nov 23 19:11:33 2010 -0700 bump version to 1.2.7.1 diff --git a/VERSION.sh b/VERSION.sh index 6dfceb3c8..496617dcd 100644 --- a/VERSION.sh +++ b/VERSION.sh @@ -10,7 +10,7 @@ vendor="389 Project" # PACKAGE_VERSION is constructed from these VERSION_MAJOR=1 VERSION_MINOR=2 -VERSION_MAINT=7 +VERSION_MAINT=7.1 # if this is a PRERELEASE, set VERSION_PREREL # otherwise, comment it out # be sure to include the dot prefix in the prerel
0
cd1ab967a91a8d91fa15c722c79db0bc06958ded
389ds/389-ds-base
bump version to 1.2.6.a1
commit cd1ab967a91a8d91fa15c722c79db0bc06958ded Author: Rich Megginson <[email protected]> Date: Tue Jan 12 14:57:51 2010 -0700 bump version to 1.2.6.a1 diff --git a/VERSION.sh b/VERSION.sh index 4a90065c7..051b14bfc 100644 --- a/VERSION.sh +++ b/VERSION.sh @@ -10,11 +10,11 @@ vendor="389 Project" # PACKAGE_VERSION is constructed from these VERSION_MAJOR=1 VERSION_MINOR=2 -VERSION_MAINT=5 +VERSION_MAINT=6 # if this is a PRERELEASE, set VERSION_PREREL # otherwise, comment it out # be sure to include the dot prefix in the prerel -VERSION_PREREL=.rc4 +VERSION_PREREL=.a1 # NOTES on VERSION_PREREL # use aN for an alpha release e.g. a1, a2, etc. # use rcN for a release candidate e.g. rc1, rc2, etc.
0
10d403542c5f58f9aefdaab3765eca9085ba4078
389ds/389-ds-base
Bug 613056 - fix coverify Defect Type: Null pointer dereferences issues 11892 - 11939 https://bugzilla.redhat.com/show_bug.cgi?id=613056 Resolves: bug 613056 Bug description: Fix coverify Defect Type: Null pointer dereferences issues 11892 - 11939 description: Catch possible NULL pointer in load_config().
commit 10d403542c5f58f9aefdaab3765eca9085ba4078 Author: Endi S. Dewata <[email protected]> Date: Fri Jul 9 20:55:37 2010 -0500 Bug 613056 - fix coverify Defect Type: Null pointer dereferences issues 11892 - 11939 https://bugzilla.redhat.com/show_bug.cgi?id=613056 Resolves: bug 613056 Bug description: Fix coverify Defect Type: Null pointer dereferences issues 11892 - 11939 description: Catch possible NULL pointer in load_config(). diff --git a/ldap/servers/snmp/main.c b/ldap/servers/snmp/main.c index a216d34d3..f4ca8af99 100644 --- a/ldap/servers/snmp/main.c +++ b/ldap/servers/snmp/main.c @@ -373,6 +373,10 @@ load_config(char *conf_path) instancename = NULL; goto close_and_exit; } + } else { + printf("ldap-agent: missing instance name\n"); + error = 1; + goto close_and_exit; } /* Open dse.ldif */
0
fb3e95164cefa38dc979c2e05f5cb309606bef5a
389ds/389-ds-base
Issue 4299 - UI - Add Role funtionality (#5163) Description: Add Role management features to UI. Improve CLI role functionality. Relates: https://github.com/389ds/389-ds-base/issues/4299 Reviewed by: @mreynolds389 (Thanks!)
commit fb3e95164cefa38dc979c2e05f5cb309606bef5a Author: Simon Pichugin <[email protected]> Date: Tue Feb 15 10:40:56 2022 -0800 Issue 4299 - UI - Add Role funtionality (#5163) Description: Add Role management features to UI. Improve CLI role functionality. Relates: https://github.com/389ds/389-ds-base/issues/4299 Reviewed by: @mreynolds389 (Thanks!) diff --git a/src/cockpit/389-console/src/lib/ldap_editor/lib/utils.jsx b/src/cockpit/389-console/src/lib/ldap_editor/lib/utils.jsx index 50c95bc9f..b9c08b9c0 100644 --- a/src/cockpit/389-console/src/lib/ldap_editor/lib/utils.jsx +++ b/src/cockpit/389-console/src/lib/ldap_editor/lib/utils.jsx @@ -341,7 +341,7 @@ export function getBaseLevelEntryAttributes (serverId, baseDn, entryAttributesCa `ldapsearch -LLL -o ldif-wrap=no -Y EXTERNAL -b "${baseDn}"` + ` -H ldapi://%2fvar%2frun%2fslapd-${serverId}.socket` + ` ${optionTimeLimit}` + - ' -s base "(|(objectClass=*)(objectClass=ldapSubEntry))" \\*' // + + ' -s base "(|(objectClass=*)(objectClass=ldapSubEntry))" nsRoleDN \\*' // + // ' | /usr/bin/head -c 150001' // Taking 1 additional character to check if the // the entry was indeed bigger than 150K. ]; diff --git a/src/cockpit/389-console/src/lib/ldap_editor/wizards/newEntry.jsx b/src/cockpit/389-console/src/lib/ldap_editor/wizards/newEntry.jsx index 8be38ae25..cacd019b1 100644 --- a/src/cockpit/389-console/src/lib/ldap_editor/wizards/newEntry.jsx +++ b/src/cockpit/389-console/src/lib/ldap_editor/wizards/newEntry.jsx @@ -17,6 +17,7 @@ import { } from '../lib/constants.jsx'; import AddUser from './operations/addUser.jsx'; import AddGroup from './operations/addGroup.jsx'; +import AddRole from './operations/addRole.jsx'; import AddLdapEntry from './operations/addLdapEntry.jsx'; import GenericUpdate from './operations/genericUpdate.jsx'; @@ -106,10 +107,9 @@ class NewEntryWizard extends React.Component { name="radio-new-step-start" id="radio-new-step-start-3" /> - {/* <Radio + <Radio className="ds-margin-top-lg" value="Role" - isDisabled isChecked={this.state.getStartedStepRadio === 'Role'} onChange={this.handleOnChange} label="Create a new Role" @@ -117,7 +117,7 @@ class NewEntryWizard extends React.Component { name="radio-new-step-start" id="radio-new-step-start-4" /> - <Radio + {/* <Radio className="ds-margin-top-lg" value="CoS" isDisabled @@ -173,6 +173,11 @@ class NewEntryWizard extends React.Component { {...wizardProps} treeViewRootSuffixes={this.props.treeViewRootSuffixes} /> + } else if (getStartedStepRadio === 'Role') { + return <AddRole + {...wizardProps} + treeViewRootSuffixes={this.props.treeViewRootSuffixes} + /> } else if (getStartedStepRadio === 'OrganizationalUnit') { return <GenericUpdate editorLdapServer={this.props.editorLdapServer} @@ -193,15 +198,6 @@ class NewEntryWizard extends React.Component { { id: 4, name: 'CoS 4', component: <p>Step 4</p>, canJumpTo: this.state.stepIdReached >= 4 }, { id: 5, name: 'CoS End', component: <p>Review Step</p>, nextButtonText: 'Finish', canJumpTo: this.state.stepIdReached >= 5 } ]; - } else if (getStartedStepRadio === 'Role') { - myTitle = 'Add a new Role Entry'; - mySteps = [ - // ...this.state.initialStep, - { id: 2, name: 'Role 2', component: <p>Step 2</p>, canJumpTo: this.state.stepIdReached >= 2 }, - { id: 3, name: 'Role 3', component: <p>Step 3</p>, canJumpTo: this.state.stepIdReached >= 3 }, - { id: 4, name: 'Role 4', component: <p>Step 4</p>, canJumpTo: this.state.stepIdReached >= 4 }, - { id: 5, name: 'Role End', component: <p>Review Step</p>, nextButtonText: 'Finish', canJumpTo: this.state.stepIdReached >= 5 } - ]; } else { return <AddLdapEntry allObjectclasses={this.props.allObjectclasses} diff --git a/src/cockpit/389-console/src/lib/ldap_editor/wizards/operations/addRole.jsx b/src/cockpit/389-console/src/lib/ldap_editor/wizards/operations/addRole.jsx new file mode 100644 index 000000000..610e7d2d9 --- /dev/null +++ b/src/cockpit/389-console/src/lib/ldap_editor/wizards/operations/addRole.jsx @@ -0,0 +1,1000 @@ +import React from 'react'; +import { + Alert, + Button, + Card, + CardBody, + CardTitle, + DualListSelector, + Form, + Grid, + GridItem, + Label, + Modal, + ModalVariant, + Radio, + SearchInput, + SimpleList, + SimpleListItem, + Text, + TextContent, + TextInput, + TextVariants, + ValidatedOptions, + Wizard, + BadgeToggle, + Dropdown, + DropdownItem, + DropdownPosition, + Pagination, +} from '@patternfly/react-core'; +import { + Table, + TableHeader, + TableBody, + TableVariant, + headerCol, +} from '@patternfly/react-table'; +import EditableTable from '../../lib/editableTable.jsx'; +import LdapNavigator from '../../lib/ldapNavigator.jsx'; +import { + createLdapEntry, + runGenericSearch, + generateUniqueId +} from '../../lib/utils.jsx'; +import { + InfoCircleIcon +} from '@patternfly/react-icons'; + + +class AddRole extends React.Component { + constructor (props) { + super(props); + + this.roleDefinitionArray = ['description', 'nsRoleScopeDN']; + this.filteredRoleDefinitionArray = ['nsRoleFilter']; + this.nestedRoleDefinitionArray = ['nsRoleDN']; + this.singleValuedAttributes = ['nsRoleFilter', 'nsRoleDN', 'nsRoleScopeDN']; + + this.requiredAttributes = ['cn', 'nsRoleFilter', 'nsRoleDN']; + + this.attributeValidationRules = [ + { + name: 'required', + validator: value => value.trim() !== '', + errorText: 'This field is required' + } + ]; + + this.state = { + alertVariant: 'info', + namingRowID: -1, + namingAttrVal: '', + namingAttr: '', + namingVal: '', + ldifArray: [], + cleanLdifArray: [], + savedRows: [], + commandOutput: '', + resultVariant: 'default', + allAttributesSelected: false, + stepIdReached: 0, + // currentStepId: 1, + itemCountAddUser: 0, + pageAddRole: 1, + perpageAddRole: 10, + columnsRole: [ + { title: 'Attribute Name', cellTransforms: [headerCol()] }, + { title: 'From ObjectClass' } + ], + rowsRole: [], + pagedRowsRole: [], + selectedAttributes: ['cn'], + isAttrDropDownOpen: false, + // Values + noEmptyValue: false, + columnsValues: [ + 'Attribute', + 'Value' + ], + // Review step + reviewValue: '', + reviewInvalidText: 'Invalid LDIF', + reviewIsValid: true, + reviewValidated: 'default', + // reviewHelperText: 'LDIF data' + editableTableData: [], + rdn: "", + rdnValue: "", + parentDN: "", + isTreeLoading: false, + roleType: "managed", + roleDNs: [], + searching: false, + searchPattern: "", + showLDAPNavModal: false, + rolesSearchBaseDn: "", + rolesAvailableOptions: [], + rolesChosenOptions: [], + }; + + this.handleBaseDnSelection = (treeViewItem) => { + this.setState({ + rolesSearchBaseDn: treeViewItem.dn + }); + } + + this.showTreeLoadingState = (isTreeLoading) => { + this.setState({ + isTreeLoading, + searching: isTreeLoading ? true : false + }); + } + + this.openLDAPNavModal = () => { + this.setState({ + showLDAPNavModal: true + }); + }; + + this.closeLDAPNavModal = () => { + this.setState({ + showLDAPNavModal: false + }); + }; + + this.onNext = ({ id }) => { + this.setState({ + stepIdReached: this.state.stepIdReached < id ? id : this.state.stepIdReached + }); + if (id === 3) { + // Update the attributes table. + this.updateAttributesTableRows(); + this.updateValuesTableRows(); + } else if (id === 4) { + // Update the values table. + this.updateValuesTableRows(); + } else if (id === 5) { + // Generate the LDIF data. + this.generateLdifData(); + } else if (id === 6) { + // Create the LDAP entry. + const myLdifArray = this.state.ldifArray; + createLdapEntry(this.props.editorLdapServer, + myLdifArray, + (result) => { + this.setState({ + commandOutput: result.errorCode === 0 ? 'Role successfully created!' : 'Failed to create role: ' + result.errorCode, + resultVariant: result.errorCode === 0 ? 'success' : 'danger' + }, () => { + this.props.onReload(); + }); + // Update the wizard operation information. + const myDn = myLdifArray[0].substring(4); + const relativeDn = myLdifArray[6].replace(": ", "="); // cn val + const opInfo = { + operationType: 'ADD', + resultCode: result.errorCode, + time: Date.now(), + entryDn: myDn, + relativeDn: relativeDn + } + this.props.setWizardOperationInfo(opInfo); + } + ); + } + }; + + this.onBack = ({ id }) => { + if (id === 4) { + // true ==> Do not check the attribute selection when navigating back. + this.updateValuesTableRows(true); + } + }; + + this.handleSearchClick = () => { + this.setState({ + isSearchRunning: true, + rolesAvailableOptions: [] + }, () => { this.getEntries () }); + }; + + this.handleSearchPattern = searchPattern => { + this.setState({ searchPattern }); + }; + + this.getEntries = () => { + const baseDn = this.state.rolesSearchBaseDn; + const pattern = this.state.searchPattern; + const filter = pattern === '' + ? '(|(objectClass=LDAPsubentry)(objectClass=nsRoleDefinition))' + : `(&(|(objectClass=LDAPsubentry)(objectClass=nsRoleDefinition)(objectClass=nsSimpleRoleDefinition)(objectClass=nsComplexRoleDefinition)(objectClass=nsManagedRoleDefinition)(objectClass=nsFilteredRoleDefinition)(objectClass=nsNestedRoleDefinition))(|(cn=*${pattern}*)(uid=${pattern})))`; + const attrs = 'cn'; + + const params = { + serverId: this.props.editorLdapServer, + baseDn: baseDn, + scope: 'sub', + filter: filter, + attributes: attrs + }; + runGenericSearch(params, (resultArray) => { + const newOptionsArray = resultArray.map(result => { + const lines = result.split('\n'); + // TODO: Currently picking the first value found. + // Might be worth to take the value that is used as RDN in case of multiple values. + + // Handle base64-encoded data: + const pos0 = lines[0].indexOf(':: '); + const pos1 = lines[1].indexOf(':: '); + + let dnLine = lines[0]; + if (pos0 > 0) { + const decoded = decodeLine(dnLine); + dnLine = `${decoded[0]}: ${decoded[1]}`; + } + const value = pos1 === -1 + ? (lines[1]).split(': ')[1] + : decodeLine(lines[1])[1]; + + return ( + <span title={dnLine}> + {value} + </span> + ); + }); + + this.setState({ + rolesAvailableOptions: newOptionsArray, + isSearchRunning: false + }); + }); + } + + this.removeDuplicates = (options) => { + const titles = options.map(item => item.props.title); + const noDuplicates = options + .filter((item, index) => { + return titles.indexOf(item.props.title) === index; + }); + return noDuplicates; + }; + + this.usersOnListChange = (newAvailableOptions, newChosenOptions) => { + const newAvailNoDups = this.removeDuplicates(newAvailableOptions); + const newChosenNoDups = this.removeDuplicates(newChosenOptions); + + this.setState({ + rolesAvailableOptions: newAvailNoDups.sort(), + rolesChosenOptions: newChosenNoDups.sort() + }); + + }; + + this.handleRadioChange = (_, event) => { + this.setState({ + roleType: event.currentTarget.id, + }); + }; + + this.handleChange = this.handleChange.bind(this); + } + + updateAttributesTableRows () { + const attributesArray = []; + attributesArray.push({ + cells: ['cn', 'LdapSubEntry'], + selected: true, + isAttributeSelected: true, + disableCheckbox: true + }); + + this.roleDefinitionArray.map(attr => { + attributesArray.push({ cells: [attr, 'nsRoleDefinition'] }); + }); + + if (this.state.roleType === 'filtered') { + this.filteredRoleDefinitionArray.map(attr => { + attributesArray.push({ cells: [attr, 'nsFilteredRoleDefinition'], + selected: true, + isAttributeSelected: true, + disableCheckbox: true + }); + }); + } else if (this.state.roleType === 'nested') { + this.nestedRoleDefinitionArray.map(attr => { + attributesArray.push({ cells: [attr, 'nsNestedRoleDefinition'], + selected: true, + isAttributeSelected: true, + disableCheckbox: true + }); + }); + } + + // Sort the attributes + attributesArray.sort((a, b) => (a.cells[0] > b.cells[0]) ? 1 : -1); + + this.setState({ + selectedAttributes: ['cn', + ...(this.state.roleType === 'filtered' ? ['nsRoleFilter'] : []), + ...(this.state.roleType === 'nested' ? ['nsRoleDN'] : [])], + itemCountAddUser: attributesArray.length, + rowsRole: attributesArray, + pagedRowsRole: attributesArray.slice(0, this.state.perpageAddRole), + parentDN: this.props.wizardEntryDn, + rolesSearchBaseDn: this.props.wizardEntryDn + }); + } + + componentDidMount () { + this.setState({ + parentDN: this.props.wizardEntryDn, + rolesSearchBaseDn: this.props.wizardEntryDn + }); + } + + onSetpageAddRole = (_event, pageNumber) => { + this.setState({ + pageAddRole: pageNumber, + pagedRowsRole: this.getAttributesToShow(pageNumber, this.state.perpageAddRole) + }); + }; + + onPerPageSelectAddUser = (_event, perPage) => { + this.setState({ + pageAddRole: 1, + perpageAddRole: perPage, + pagedRowsRole: this.getAttributesToShow(1, perPage) + }); + }; + + getAttributesToShow (page, perPage) { + const start = (page - 1) * perPage; + const end = page * perPage; + const newRows = this.state.rowsRole.slice(start, end); + return newRows; + } + + isAttributeSingleValued = attr => { + return this.singleValuedAttributes.includes(attr); + }; + + isAttributeRequired = attr => { + return this.requiredAttributes.includes(attr); + } + + onSelect = (event, isSelected, rowId) => { + let rows; + let selectedAttributes; + if (rowId === -1) { + // Process the full table entries ( rowsRole ) + rows = this.state.rowsRole.map(oneRow => { + oneRow.selected = isSelected; + oneRow.isAttributeSelected = isSelected; + return oneRow; + }); + // Quick hack until the code is upgraded to a version that supports "disableCheckbox" + // Both 'cn' and 'sn' ( first 2 elements in the table ) are mandatory. + // TODO: https://www.patternfly.org/v4/components/table#selectable + // ==> disableSelection: true + rows[0].selected = true; + rows[0].isAttributeSelected = true; + selectedAttributes = ['cn']; + if (this.state.roleType === 'filtered') { + selectedAttributes.push('nsRoleFilter'); + rows[1].selected = true; + rows[1].isAttributeSelected = true; + } else if (this.state.roleType === 'nested') { + selectedAttributes.push('nsRoleDN'); + rows[1].selected = true; + rows[1].isAttributeSelected = true; + } + this.setState({ + rowsRole: rows, + allAttributesSelected: isSelected, + selectedAttributes + }, + () => { + this.setState({ + pagedRowsRole: this.getAttributesToShow(this.state.pageAddRole, this.state.perpageAddRole) + }); + this.updateValuesTableRows(); + }); + } else { + // Quick hack until the code is upgraded to a version that supports "disableCheckbox" + if (this.state.pagedRowsRole[rowId].disableCheckbox === true) { + return; + } // End hack. + + // Process only the entries in the current page ( pagedRowsRole ) + rows = [...this.state.pagedRowsRole]; + rows[rowId].selected = isSelected; + // Find the entry in the full array and set 'isAttributeSelected' accordingly + // The property 'isAttributeSelected' is used to build the LDAP entry to add. + // The row ID cannot be used since it changes with the pagination. + const attrName = this.state.pagedRowsRole[rowId].cells[0]; + const allItems = [...this.state.rowsRole]; + const index = allItems.findIndex(item => item.cells[0] === attrName); + allItems[index].isAttributeSelected = isSelected; + const selectedAttributes = allItems + .filter(item => item.isAttributeSelected) + .map(selectedAttr => selectedAttr.cells[0]); + + this.setState({ + rowsRole: allItems, + pagedRowsRole: rows, + selectedAttributes + }, + () => this.updateValuesTableRows()); + } + }; + + updateValuesTableRows = (skipAttributeSelection) => { + const newSelectedAttrs = this.state.allAttributesSelected + ? ['cn', + ...this.roleDefinitionArray, + ...this.filteredRoleDefinitionArray, + ...this.nestedRoleDefinitionArray] + : [...this.state.selectedAttributes]; + let namingRowID = this.state.namingRowID; + let namingAttrVal = this.state.namingAttrVal + let editableTableData = []; + let namingAttr = this.state.namingAttr; + let namingVal = this.state.namingVal; + + if (this.state.savedRows.length === 0) { + editableTableData = newSelectedAttrs.map(attrName => { + const obj = { + id: generateUniqueId(), + attr: attrName, + val: namingVal ? namingVal : '', + required: false, + namingAttr: false, + } + return obj; + }); + editableTableData.sort((a, b) => (a.attr > b.attr) ? 1 : -1); + namingRowID = editableTableData[0].id, + namingAttrVal = editableTableData[0].attr + "=" + editableTableData[0].val; + namingAttr = editableTableData[0].attr; + namingVal = editableTableData[0].val; + if (this.state.roleType === 'nested') { + for (const userObj of this.state.rolesChosenOptions) { + const dn_val = userObj.props.title.replace(/^dn: /, ""); + editableTableData = editableTableData.filter((item) => (item.val !== dn_val)); + editableTableData.push({id: generateUniqueId(), + attr: 'nsRoleDN', + val: dn_val, + required: true, + namingAttr: false, + }); + } + } + this.setState({ + savedRows: editableTableData + }); + } else { + if (skipAttributeSelection) { // Do not check the attribute selection ( because it has not changed ). + editableTableData = [...this.state.savedRows]; + } else { + const arrayOfAttrObjects = [...this.state.savedRows]; + for (const myAttr of newSelectedAttrs) { + const found = arrayOfAttrObjects.find(el => el.attr === myAttr); + if (found === undefined) { + // The new attribute was not in the list of saved attributes, add it. + arrayOfAttrObjects.push({ + id: generateUniqueId(), + attr: myAttr, + val: '', + required: false, + namingAttr: false, + }); + } + } + // Remove the newly unselected attribute(s). + editableTableData = arrayOfAttrObjects + .filter(datum => { + const attrName = datum.attr; + const found = newSelectedAttrs.find(attr => attr === attrName); + return (found !== undefined); + }); + + // Sort the rows + editableTableData.sort((a, b) => (a.attr > b.attr) ? 1 : -1); + if (this.state.namingRowID === -1) { + namingRowID = editableTableData[0].id + } + } + if (this.state.roleType === 'nested') { + for (const userObj of this.state.rolesChosenOptions) { + const dn_val = userObj.props.title.replace(/^dn: /, ""); + editableTableData = editableTableData.filter((item) => (item.val !== dn_val)); + editableTableData.push({id: generateUniqueId(), + attr: 'nsRoleDN', + val: dn_val, + required: true, + namingAttr: false, + }); + } + } + this.setState({ + savedRows: editableTableData + }); + } + + // Update the attributes to process. + this.setState({ + editableTableData, + rdn: editableTableData[0].attr, + namingRowID, + namingAttrVal, + namingAttr, + namingVal, + }); + }; + + enableNextStep = (noEmptyValue) => { + this.setState({ noEmptyValue }); + }; + + setNamingRowID = (namingRowID) => { + let namingAttrVal = ""; + let namingAttr = ""; + let namingVal = ""; + let rows = this.state.savedRows; + + if (rows.length === 0) { + rows = this.state.editableTableData + } + for (const row of rows) { + if (row.id === namingRowID) { + namingAttrVal = row.attr + "=" + row.val; + namingAttr = row.attr; + namingVal = row.val; + break; + } + } + + this.setState({ + namingRowID, + namingAttrVal, + namingAttr, + namingVal, + }); + }; + + onAttrDropDownToggle = isOpen => { + this.setState({ + isAttrDropDownOpen: isOpen + }); + }; + + onAttrDropDownSelect = event => { + this.setState((prevState, props) => { + return { isAttrDropDownOpen: !prevState.isAttrDropDownOpen }; + }); + }; + + buildAttrDropdown = () => { + const { isAttrDropDownOpen, selectedAttributes } = this.state; + const numSelected = selectedAttributes.length; + const items = selectedAttributes.map((attr) => + <DropdownItem key={attr}>{attr}</DropdownItem> + ); + + return ( + <Dropdown + className="ds-dropdown-padding" + onSelect={this.onAttrDropDownSelect} + position={DropdownPosition.left} + toggle={ + <BadgeToggle id="toggle-attr-select" onToggle={this.onAttrDropDownToggle}> + {numSelected !== 0 ? <>{numSelected} selected </> : <>0 selected </>} + </BadgeToggle> + } + isOpen={isAttrDropDownOpen} + dropdownItems={items} + /> + ); + } + + saveCurrentRows = (savedRows, namingID) => { + this.setState({ savedRows }, + () => { + // Update the naming information after the new rows have been saved. + if (namingID != -1) { // The namingIndex is set to -1 if the row is not the naming one. + this.setNamingRowID(namingID); + } + }); + } + + generateLdifData = () => { + const objectClassData = ['ObjectClass: top', + 'ObjectClass: LdapSubEntry', + 'ObjectClass: nsRoleDefinition']; + if (this.state.roleType === 'managed') { + objectClassData.push('ObjectClass: nsSimpleRoleDefinition', + 'ObjectClass: nsManagedRoleDefinition'); + } else if (this.state.roleType === 'filtered') { + objectClassData.push('ObjectClass: nsComplexRoleDefinition', + 'ObjectClass: nsFilteredRoleDefinition'); + } else if (this.state.roleType === 'nested') { + objectClassData.push('ObjectClass: nsComplexRoleDefinition', + 'ObjectClass: nsNestedRoleDefinition'); + } + + const valueData = []; + for (const item of this.state.savedRows) { + const attrName = item.attr; + valueData.push(`${attrName}: ${item.val}`); + if (objectClassData.length === 5) { // There will a maximum of 4 ObjectClasses. + continue; + } + // TODO: Find a better logic! + //if ((!objectClassData.includes('ObjectClass: InetOrgPerson')) && + //this.inetorgPersonArray.includes(attrName)) { + // objectClassData.push('ObjectClass: InetOrgPerson'); + //} + //if (!objectClassData.includes('ObjectClass: OrganizationalPerson') && + //this.organizationalPersonArray.includes(attrName)) { + // objectClassData.push('ObjectClass: OrganizationalPerson'); + //} + } + + const ldifArray = [ + `dn: ${this.state.namingAttrVal},${this.props.wizardEntryDn}`, + ...objectClassData, + ...valueData + ]; + + this.setState({ ldifArray }); + } + + handleChange (e) { + const attr = e.target.id; + const value = e.target.type === 'checkbox' ? e.target.checked : e.target.value; + this.setState({ + [attr]: value, + }) + } + + render () { + const { + itemCountAddUser, pageAddRole, perpageAddRole, columnsRole, pagedRowsRole, + ldifArray, cleanLdifArray, columnsValues, noEmptyValue, alertVariant, + namingAttrVal, namingAttr, resultVariant, editableTableData, + stepIdReached, namingVal, rolesSearchBaseDn, rolesAvailableOptions, + rolesChosenOptions, showLDAPNavModal, commandOutput, roleType + } = this.state; + + const rdnValue = namingVal; + const myTitle = (namingAttrVal === '' || rdnValue === '') + ? 'Invalid Naming Attribute - Empty Value!' + : 'DN ( Distinguished Name )'; + + const namingValAndTypeStep = ( + <div> + <TextContent> + <Text component={TextVariants.h3}> + Select Name And Role Type + </Text> + </TextContent> + <Form autoComplete="off"> + <Grid className="ds-margin-top-xlg"> + <GridItem span={2} className="ds-label"> + Role Name + </GridItem> + <GridItem span={10}> + <TextInput + value={namingVal} + type="text" + id="namingVal" + aria-describedby="namingVal" + name="namingVal" + onChange={(str, e) => { + this.handleChange(e); + }} + validated={this.state.namingVal === '' ? ValidatedOptions.error : ValidatedOptions.default} + /> + </GridItem> + </Grid> + + <TextContent className="ds-margin-top-lg"> + <Text component={TextVariants.h5}> + Choose Role Type + </Text> + </TextContent> + <div className="ds-left-margin"> + <Radio + name="roleType" + id="managed" + value="managed" + label="Managed" + isChecked={this.state.roleType === 'managed'} + onChange={this.handleRadioChange} + description="This attribute uses objectclass 'RoleOfNames'" + /> + <Radio + name="roleType" + id="filtered" + value="filtered" + label="Filtered" + isChecked={this.state.roleType === 'filtered'} + onChange={this.handleRadioChange} + description="This attribute uses objectclass 'RoleOfUniqueNames'" + className="ds-margin-top" + /> + <Radio + name="roleType" + id="nested" + value="nested" + label="Nested" + isChecked={this.state.roleType === 'nested'} + onChange={this.handleRadioChange} + description="This attribute uses objectclass 'RoleOfUniqueNames'" + className="ds-margin-top" + /> + </div> + </Form> + </div> + ); + + const addRolesStep = ( + <React.Fragment> + <Form autoComplete="off"> + <Grid> + <GridItem span={12}> + <TextContent> + <Text component={TextVariants.h3}> + Add Roles to the Nested Role + </Text> + </TextContent> + </GridItem> + <GridItem span={12} className="ds-margin-top-xlg"> + <Label onClick={this.openLDAPNavModal} href="#" variant="outline" color="blue" icon={<InfoCircleIcon />}> + Search Base DN + </Label> + <strong>&nbsp;&nbsp;{rolesSearchBaseDn}</strong> + </GridItem> + <GridItem span={12} className="ds-margin-top"> + <SearchInput + placeholder="Find roles..." + value={this.state.searchPattern} + onChange={this.handleSearchPattern} + onSearch={this.handleSearchClick} + onClear={() => { this.handleSearchPattern('') }} + /> + </GridItem> + <GridItem span={12} className="ds-margin-top-xlg"> + <DualListSelector + availableOptions={rolesAvailableOptions} + chosenOptions={rolesChosenOptions} + availableOptionsTitle="Available Roles" + chosenOptionsTitle="Chosen Roles" + onListChange={this.usersOnListChange} + id="usersSelector" + /> + </GridItem> + + <Modal + variant={ModalVariant.medium} + title="Choose A Branch To Search" + isOpen={showLDAPNavModal} + onClose={this.closeLDAPNavModal} + actions={[ + <Button + key="confirm" + variant="primary" + onClick={this.closeLDAPNavModal} + > + Done + </Button> + ]} + > + <Card isHoverable className="ds-indent ds-margin-bottom-md"> + <CardBody> + <LdapNavigator + treeItems={[...this.props.treeViewRootSuffixes]} + editorLdapServer={this.props.editorLdapServer} + skipLeafEntries={true} + handleNodeOnClick={this.handleBaseDnSelection} + showTreeLoadingState={this.showTreeLoadingState} + /> + </CardBody> + </Card> + </Modal> + </Grid> + </Form> + </React.Fragment> + ); + + const roleAttributesStep = ( + <> + <div className="ds-container"> + <TextContent> + <Text component={TextVariants.h3}> + Select Entry Attributes + </Text> + </TextContent> + {this.buildAttrDropdown()} + </div> + <Pagination + itemCount={itemCountAddUser} + page={pageAddRole} + perPage={perpageAddRole} + onSetPage={this.onSetpageAddRole} + widgetId="pagination-options-menu-add-user" + onPerPageSelect={this.onPerPageSelectAddUser} + isCompact + /> + <Table + cells={columnsRole} + rows={pagedRowsRole} + onSelect={this.onSelect} + variant={TableVariant.compact} + aria-label="Pagination User Attributes" + > + <TableHeader /> + <TableBody /> + </Table> + </> + ); + + const roleValuesStep = ( + <React.Fragment> + <Form autoComplete="off"> + <Grid> + <GridItem className="ds-margin-top" span={12}> + <Alert + variant={namingAttr === '' || namingVal === '' + ? 'warning' + : 'success'} + isInline + title={myTitle} + > + <b>Entry DN:&nbsp;&nbsp;&nbsp;</b>{(namingAttr ? namingAttr : "??????")}={namingVal ? namingVal : "??????"},{this.props.wizardEntryDn} + </Alert> + </GridItem> + <GridItem span={12} className="ds-margin-top-xlg"> + <TextContent> + <Text component={TextVariants.h3}> + Set Attribute Values + </Text> + </TextContent> + </GridItem> + </Grid> + </Form> + <GridItem className="ds-left-margin" span={11}> + <EditableTable + editableTableData={editableTableData} + isAttributeSingleValued={this.isAttributeSingleValued} + isAttributeRequired={this.isAttributeRequired} + enableNextStep={this.enableNextStep} + setNamingRowID={this.setNamingRowID} + saveCurrentRows={this.saveCurrentRows} + namingRowID={this.state.namingRowID} + namingAttr={this.state.namingAttr} + /> + </GridItem> + </React.Fragment> + ); + + const ldifListItems = ldifArray.map((line, index) => + <SimpleListItem key={index} isCurrent={line.startsWith('dn: ')}> + {line} + </SimpleListItem> + ); + + const roleCreationStep = ( + <div> + <Alert + variant="info" + isInline + title="LDIF Content for Role Creation" + /> + <Card isHoverable> + <CardBody> + { (ldifListItems.length > 0) && + <SimpleList aria-label="LDIF data User"> + {ldifListItems} + </SimpleList> + } + </CardBody> + </Card> + </div> + ); + + let nb = -1; + const ldifLines = ldifArray.map(line => { + nb++; + return { data: line, id: nb }; + }) + const roleReviewStep = ( + <div> + <Alert + variant={resultVariant} + isInline + title="Result for Role Creation" + > + {commandOutput} + </Alert> + {resultVariant === 'danger' && + <Card isHoverable> + <CardTitle> + LDIF Data + </CardTitle> + <CardBody> + {ldifLines.map((line) => ( + <h6 key={line.id}>{line.data}</h6> + ))} + </CardBody> + </Card> + } + </div> + ); + + const addRoleSteps = [ + { + id: 1, + name: 'Select Name & Type', + component: namingValAndTypeStep, + enableNext: namingVal === '' ? false : true, + hideBackButton: true + }, + ...(roleType === 'nested' ? [ + { + id: 2, + name: 'Add Nested Roles', + component: addRolesStep, + canJumpTo: stepIdReached >= 2 && stepIdReached < 6 + }, + ] : []), + { + id: 3, + name: 'Select Attributes', + component: roleAttributesStep, + canJumpTo: stepIdReached >= 3 && stepIdReached < 6 + }, + { + id: 4, + name: 'Set Values', + component: roleValuesStep, + canJumpTo: stepIdReached >= 4 && stepIdReached < 6, + enableNext: noEmptyValue + }, + { + id: 5, + name: 'Create Role', + component: roleCreationStep, + nextButtonText: 'Create', + canJumpTo: stepIdReached >= 5 && stepIdReached < 6 + }, + { + id: 6, + name: 'Review Result', + component: roleReviewStep, + nextButtonText: 'Finish', + canJumpTo: stepIdReached >= 5, + hideBackButton: true + } + ]; + + const title = <> + Parent DN: &nbsp;&nbsp;<strong>{this.props.wizardEntryDn}</strong> + </>; + + return ( + <Wizard + isOpen={this.props.isWizardOpen} + onClose={this.props.toggleOpenWizard} + onNext={this.onNext} + onBack={this.onBack} + title="Add A Role" + description={title} + steps={addRoleSteps} + /> + ); + } +} + +export default AddRole; diff --git a/src/cockpit/389-console/src/lib/ldap_editor/wizards/operations/addUser.jsx b/src/cockpit/389-console/src/lib/ldap_editor/wizards/operations/addUser.jsx index 5367e4da3..1d5714be1 100644 --- a/src/cockpit/389-console/src/lib/ldap_editor/wizards/operations/addUser.jsx +++ b/src/cockpit/389-console/src/lib/ldap_editor/wizards/operations/addUser.jsx @@ -52,6 +52,7 @@ class AddUser extends React.Component { this.personOptionalArray = [ 'userPassword', 'telephoneNumber', 'seeAlso', 'description' ]; + this.operationalOptionalArray = ['nsRoleDN']; this.singleValuedAttributes = [ 'preferredDeliveryMethod', 'displayName', 'employeeNumber', 'preferredLanguage' ]; @@ -89,7 +90,7 @@ class AddUser extends React.Component { ], rowsUser: [], pagedRowsUser: [], - selectedAttributes: ['cn', 'sn'], + selectedAttributes: ['cn', 'sn', 'nsRoleDN'], isAttrDropDownOpen: false, // Values noEmptyValue: false, @@ -179,13 +180,15 @@ class AddUser extends React.Component { this.personOptionalArray.map(attr => { attributesArray.push({ cells: [attr, 'Person'] }); }); - this.organizationalPersonArray.map(attr => { attributesArray.push({ cells: [attr, 'OrganizationalPerson'] }); }); this.inetorgPersonArray.map(attr => { attributesArray.push({ cells: [attr, 'InetOrgPerson'] }); }); + this.operationalOptionalArray.map(attr => { + attributesArray.push({ cells: [attr, ''] }); + }); // Sort the attributes attributesArray.sort((a, b) => (a.cells[0] > b.cells[0]) ? 1 : -1); @@ -290,7 +293,8 @@ class AddUser extends React.Component { ? ['cn', 'sn', ...this.personOptionalArray, ...this.organizationalPersonArray, - ...this.inetorgPersonArray] + ...this.inetorgPersonArray, + ...this.operationalOptionalArray] : [...this.state.selectedAttributes]; let namingRowID = this.state.namingRowID; let namingAttrVal = this.state.namingAttrVal diff --git a/src/cockpit/389-console/src/lib/ldap_editor/wizards/operations/editLdapEntry.jsx b/src/cockpit/389-console/src/lib/ldap_editor/wizards/operations/editLdapEntry.jsx index cca243ae4..ac9006075 100644 --- a/src/cockpit/389-console/src/lib/ldap_editor/wizards/operations/editLdapEntry.jsx +++ b/src/cockpit/389-console/src/lib/ldap_editor/wizards/operations/editLdapEntry.jsx @@ -583,6 +583,34 @@ class EditLdapEntry extends React.Component { }); } } + + // If we're editing a user then add nsRoleDN attribute to the possible list + let personOC = false; + for (const existingOC of this.state.selectedObjectClasses) { + if (existingOC.cells[0].toLowerCase() === 'person' || + existingOC.cells[0].toLowerCase() === 'nsperson') { + personOC = true; + break; + } + } + let roleDNAttr = 'nsRoleDN' + if ((personOC && !attrList.includes(roleDNAttr))) { + let selected = false; + for (const existingRow of this.state.editableTableData) { + if (existingRow.attr.toLowerCase() === roleDNAttr.toLowerCase()) { + selected = true; + break; + } + } + + attrList.push(roleDNAttr); + rowsAttr.push({ + attributeName: roleDNAttr, + isAttributeSelected: selected, + selected: selected, + cells: [roleDNAttr, ''] + }); + } }); // Update the rows where user can select the attributes. diff --git a/src/lib389/lib389/cli_idm/role.py b/src/lib389/lib389/cli_idm/role.py index 3bc6ad502..dc316cac9 100644 --- a/src/lib389/lib389/cli_idm/role.py +++ b/src/lib389/lib389/cli_idm/role.py @@ -8,12 +8,25 @@ # --- END COPYRIGHT BLOCK --- import ldap -from lib389.idm.role import Role, Roles +from lib389.idm.role import ( + Role, + Roles, + ManagedRoles, + FilteredRoles, + NestedRoles, + MUST_ATTRIBUTES, + MUST_ATTRIBUTES_NESTED + ) from lib389.cli_base import ( + populate_attr_arguments, + _get_arg, + _get_attributes, + _generic_get, _generic_get_dn, _generic_list, _generic_delete, _generic_modify_dn, + _generic_create, _get_dn_arg, _warn, ) @@ -27,11 +40,31 @@ def list(inst, basedn, log, args): _generic_list(inst, basedn, log.getChild('_generic_list'), MANY, args) +def get(inst, basedn, log, args): + rdn = _get_arg( args.selector, msg="Enter %s to retrieve" % RDN) + _generic_get(inst, basedn, log.getChild('_generic_get'), MANY, rdn, args) + + def get_dn(inst, basedn, log, args): dn = _get_dn_arg(args.dn, msg="Enter dn to retrieve") _generic_get_dn(inst, basedn, log.getChild('_generic_get_dn'), MANY, dn, args) +def create_managed(inst, basedn, log, args): + kwargs = _get_attributes(args, MUST_ATTRIBUTES) + _generic_create(inst, basedn, log.getChild('_generic_create'), ManagedRoles, kwargs, args) + + +def create_filtered(inst, basedn, log, args): + kwargs = _get_attributes(args, MUST_ATTRIBUTES) + _generic_create(inst, basedn, log.getChild('_generic_create'), FilteredRoles, kwargs, args) + + +def create_nested(inst, basedn, log, args): + kwargs = _get_attributes(args, MUST_ATTRIBUTES_NESTED) + _generic_create(inst, basedn, log.getChild('_generic_create'), NestedRoles, kwargs, args) + + def delete(inst, basedn, log, args, warn=True): dn = _get_dn_arg(args.dn, msg="Enter dn to delete") if warn: @@ -88,18 +121,33 @@ def unlock(inst, basedn, log, args): def create_parser(subparsers): - role_parser = subparsers.add_parser('role', help='''Manage generic roles, with tasks -like modify, locking and unlocking.''') + role_parser = subparsers.add_parser('role', help='''Manage roles.''') subcommands = role_parser.add_subparsers(help='action') list_parser = subcommands.add_parser('list', help='list roles that could login to the directory') list_parser.set_defaults(func=list) + get_parser = subcommands.add_parser('get', help='get') + get_parser.set_defaults(func=get) + get_parser.add_argument('selector', nargs='?', help='The term to search for') + get_dn_parser = subcommands.add_parser('get-by-dn', help='get-by-dn <dn>') get_dn_parser.set_defaults(func=get_dn) get_dn_parser.add_argument('dn', nargs='?', help='The dn to get and display') + create_managed_parser = subcommands.add_parser('create-managed', help='create') + create_managed_parser.set_defaults(func=create_managed) + populate_attr_arguments(create_managed_parser, MUST_ATTRIBUTES) + + create_filtered_parser = subcommands.add_parser('create-filtered', help='create') + create_filtered_parser.set_defaults(func=create_filtered) + populate_attr_arguments(create_filtered_parser, MUST_ATTRIBUTES) + + create_nested_parser = subcommands.add_parser('create-nested', help='create') + create_nested_parser.set_defaults(func=create_nested) + populate_attr_arguments(create_nested_parser, MUST_ATTRIBUTES_NESTED) + modify_dn_parser = subcommands.add_parser('modify-by-dn', help='modify-by-dn <dn> <add|delete|replace>:<attribute>:<value> ...') modify_dn_parser.set_defaults(func=modify) modify_dn_parser.add_argument('dn', nargs=1, help='The dn to modify') diff --git a/src/lib389/lib389/idm/role.py b/src/lib389/lib389/idm/role.py index 9a2bff3d6..07214239d 100644 --- a/src/lib389/lib389/idm/role.py +++ b/src/lib389/lib389/idm/role.py @@ -14,6 +14,13 @@ from lib389.cos import CosTemplates, CosClassicDefinitions from lib389.mappingTree import MappingTrees from lib389.idm.nscontainer import nsContainers +MUST_ATTRIBUTES = [ + 'cn', +] +MUST_ATTRIBUTES_NESTED = [ + 'cn', + 'nsRoleDN' +] class RoleState(Enum): ACTIVATED = "activated" @@ -319,7 +326,7 @@ class NestedRole(Role): def __init__(self, instance, dn=None): super(NestedRole, self).__init__(instance, dn) - self._must_attributes = ['cn', 'nsRoleDN'] + self._must_attributes = MUST_ATTRIBUTES_NESTED self._rdn_attribute = 'cn' self._create_objectclasses = ['nsComplexRoleDefinition', 'nsNestedRoleDefinition']
0
08a6aadc924103b045c4dd4b4ef6b56952252257
389ds/389-ds-base
Ticket 49730 - Remove unused Mozilla ldapsdk variables Bug Description: The recent removal of support for Mozilla's ldapsdk in b770ac7 left behind some unused variables. Fix Description: Remove the unused variables from the code base. Author: Hugh McMaster <[email protected]> Review by: firstyear, mreynolds, mhonek
commit 08a6aadc924103b045c4dd4b4ef6b56952252257 Author: Hugh McMaster <[email protected]> Date: Thu May 16 22:00:36 2019 +1000 Ticket 49730 - Remove unused Mozilla ldapsdk variables Bug Description: The recent removal of support for Mozilla's ldapsdk in b770ac7 left behind some unused variables. Fix Description: Remove the unused variables from the code base. Author: Hugh McMaster <[email protected]> Review by: firstyear, mreynolds, mhonek diff --git a/Makefile.am b/Makefile.am index 01ac3a04d..2c1dc3865 100644 --- a/Makefile.am +++ b/Makefile.am @@ -137,7 +137,7 @@ AM_CFLAGS = $(DEBUG_CFLAGS) $(GCCSEC_CFLAGS) $(ASAN_CFLAGS) $(MSAN_CFLAGS) $(TSA AM_CXXFLAGS = $(DEBUG_CXXFLAGS) $(GCCSEC_CFLAGS) $(ASAN_CFLAGS) $(MSAN_CFLAGS) $(TSAN_CFLAGS) $(UBSAN_CFLAGS) # Flags for Directory Server # WARNING: This needs a clean up, because slap.h is a horrible mess and is publically exposed! -DSPLUGIN_CPPFLAGS = $(DS_DEFINES) $(DS_INCLUDES) $(PATH_DEFINES) $(SYSTEMD_DEFINES) $(NUNCSTANS_INCLUDES) @openldap_inc@ @ldapsdk_inc@ $(NSS_CFLAGS) $(NSPR_INCLUDES) $(SYSTEMD_CFLAGS) +DSPLUGIN_CPPFLAGS = $(DS_DEFINES) $(DS_INCLUDES) $(PATH_DEFINES) $(SYSTEMD_DEFINES) $(NUNCSTANS_INCLUDES) @openldap_inc@ $(NSS_CFLAGS) $(NSPR_INCLUDES) $(SYSTEMD_CFLAGS) # This should give access to internal headers only for tests!!! DSINTERNAL_CPPFLAGS = -I$(srcdir)/include/ldaputil # Flags for Datastructure Library @@ -2211,8 +2211,6 @@ fixupcmd = sed \ -e 's,@libdir\@,$(libdir),g' \ -e 's,@libexecdir\@,$(libexecdir),g' \ -e 's,@nss_libdir\@,$(nss_libdir),g' \ - -e 's,@ldapsdk_libdir\@,$(ldapsdk_libdir),g' \ - -e 's,@ldapsdk_bindir\@,$(ldapsdk_bindir),g' \ -e 's,@ldaptool_bindir\@,$(ldaptool_bindir),g' \ -e 's,@ldaptool_opts\@,$(ldaptool_opts),g' \ -e 's,@plainldif_opts\@,$(plainldif_opts),g' \ diff --git a/configure.ac b/configure.ac index 3660e6816..aa50ce177 100644 --- a/configure.ac +++ b/configure.ac @@ -885,10 +885,6 @@ AC_SUBST(PACKAGE_BASE_VERSION) AM_CONDITIONAL(OPENLDAP,test "$with_openldap" = "yes") # write out paths for binary components -AC_SUBST(ldapsdk_inc) -AC_SUBST(ldapsdk_lib) -AC_SUBST(ldapsdk_libdir) -AC_SUBST(ldapsdk_bindir) AC_SUBST(ldaplib) AC_SUBST(ldaplib_defs) AC_SUBST(ldaptool_bindir) diff --git a/ldap/admin/src/scripts/ldif2ldap.in b/ldap/admin/src/scripts/ldif2ldap.in index 99497d572..a2b0f1c39 100755 --- a/ldap/admin/src/scripts/ldif2ldap.in +++ b/ldap/admin/src/scripts/ldif2ldap.in @@ -2,7 +2,6 @@ . @datadir@/@package_name@/data/DSSharedLib -libpath_add "@ldapsdk_libdir@" libpath_add "@libdir@" libpath_add "@nss_libdir@" libpath_add "@libdir@/@package_name@/" diff --git a/ldap/admin/src/scripts/monitor.in b/ldap/admin/src/scripts/monitor.in index d833d8791..291a51e17 100755 --- a/ldap/admin/src/scripts/monitor.in +++ b/ldap/admin/src/scripts/monitor.in @@ -3,7 +3,6 @@ . @datadir@/@package_name@/data/DSSharedLib libpath_add "@libdir@/@package_name@/" -libpath_add "@ldapsdk_libdir@" libpath_add "@libdir@" libpath_add "@nss_libdir@"
0
91c03a8ad10486ee55ac5830206ce846483a1b69
389ds/389-ds-base
Resolves: #193724 Summary: "nested" filtered roles result in deadlock Description: Function slapi_vattr_values_get_sp used to use the context allocated on the stack. Changed it to call vattr_context_new to set the locally created pblock (local_pb). The pblock is used to pass the context loop info as the stack gets deeper to prevent the stack overflow. At the end of this function slapi_vattr_values_get_sp, slapi_pblock_destroy is called if the context is local (use_local_ctx). The function cleans up pb_vattr_context internally.
commit 91c03a8ad10486ee55ac5830206ce846483a1b69 Author: Noriko Hosoi <[email protected]> Date: Thu Nov 1 20:24:07 2007 +0000 Resolves: #193724 Summary: "nested" filtered roles result in deadlock Description: Function slapi_vattr_values_get_sp used to use the context allocated on the stack. Changed it to call vattr_context_new to set the locally created pblock (local_pb). The pblock is used to pass the context loop info as the stack gets deeper to prevent the stack overflow. At the end of this function slapi_vattr_values_get_sp, slapi_pblock_destroy is called if the context is local (use_local_ctx). The function cleans up pb_vattr_context internally. diff --git a/ldap/servers/slapd/vattr.c b/ldap/servers/slapd/vattr.c index 8e34f305f..5c22cb057 100644 --- a/ldap/servers/slapd/vattr.c +++ b/ldap/servers/slapd/vattr.c @@ -630,163 +630,162 @@ int vattr_test_filter( Slapi_PBlock *pb, */ SLAPI_DEPRECATED int slapi_vattr_values_get_sp(vattr_context *c, - /* Entry we're interested in */ Slapi_Entry *e, - /* attr type name */ char *type, - /* pointer to result set */ Slapi_ValueSet** results, - int *type_name_disposition, - char** actual_type_name, int flags, - int *buffer_flags) -{ - - PRBool use_local_ctx=PR_FALSE; - vattr_context ctx; - int rc = 0; - int sp_bit = 0; /* Set if an SP supplied an answer */ - vattr_sp_handle_list *list = NULL; - - vattr_get_thang my_get = {0}; - - if (c != NULL) { - rc = vattr_context_grok(&c); - if (0 != rc) { - if(!vattr_context_is_loop_msg_displayed(&c)) - { - /* Print a handy error log message */ - LDAPDebug(LDAP_DEBUG_ANY,"Detected virtual attribute loop in get on entry %s, attribute %s\n", slapi_entry_get_dn_const(e), type, 0); - vattr_context_set_loop_msg_displayed(&c); - } - return rc; - } - } else { - use_local_ctx=PR_TRUE; - ctx.vattr_context_loop_count=1; - ctx.error_displayed = 0; - } - - /* For attributes which are in the entry, we just need to get to the Slapi_Attr structure and yank out the slapi_value_set - structure. We either return a pointer directly to it, or we copy it, depending upon whether the caller asked us to try to - avoid copying. - */ - - /* First grok the entry, and remember what we saw. This call does no more than walk down the entry attribute list, do some string compares and copy pointers. */ - vattr_helper_get_entry_conts(e,type, &my_get); - /* Having done that, we now consult the attribute map to find service providers who are interested */ - /* Look for attribute in the map */ - if(!(flags & SLAPI_REALATTRS_ONLY)) - { - list = vattr_map_sp_getlist(type); - if (list) { - vattr_sp_handle *current_handle = NULL; - void *hint = NULL; - /* first lets consult the cache to save work */ - int cache_status; - - cache_status = - slapi_entry_vattrcache_find_values_and_type(e, type, - results, - actual_type_name); - switch(cache_status) - { - case SLAPI_ENTRY_VATTR_RESOLVED_EXISTS: /* cached vattr */ - { - sp_bit = 1; - - /* Complete analysis of type matching */ - if ( 0 == slapi_attr_type_cmp( type , *actual_type_name, SLAPI_TYPE_CMP_EXACT) ) - { - *type_name_disposition = SLAPI_VIRTUALATTRS_TYPE_NAME_MATCHED_EXACTLY_OR_ALIAS; - } else { - *type_name_disposition = SLAPI_VIRTUALATTRS_TYPE_NAME_MATCHED_SUBTYPE; - } - - break; - } - - case SLAPI_ENTRY_VATTR_RESOLVED_ABSENT: /* does not exist */ - break; /* look in entry */ - - case SLAPI_ENTRY_VATTR_NOT_RESOLVED: /* not resolved */ - default: /* any other result, resolve */ - { - for (current_handle = vattr_map_sp_first(list,&hint); current_handle; current_handle = vattr_map_sp_next(current_handle,&hint)) - { - if (use_local_ctx) - { - rc = vattr_call_sp_get_value(current_handle,&ctx,e,&my_get,type,results,type_name_disposition,actual_type_name,flags,buffer_flags, hint); - } - else - { - /* call this SP */ - rc = vattr_call_sp_get_value(current_handle,c,e,&my_get,type,results,type_name_disposition,actual_type_name,flags,buffer_flags, hint); - } - - if (0 == rc) - { - sp_bit = 1; - break; - } - } - - if(!sp_bit) - { - /* clean up, we have failed and must now examine the - * entry itself - * But first lets cache the no result - * Creates the type (if necessary). - */ - slapi_entry_vattrcache_merge_sv(e, type, NULL ); - - } - else - { - /* - * we need to cache the virtual attribute - * creates the type (if necessary) and dups - * results. - */ - slapi_entry_vattrcache_merge_sv(e, *actual_type_name, - *results ); - } - - break; - } - } - } - } - /* If no SP supplied the answer, take it from the entry */ - if (!sp_bit && !(flags & SLAPI_VIRTUALATTRS_ONLY)) - { - rc = 0; /* reset return code (cause an sp must have failed) */ - *type_name_disposition = my_get.get_name_disposition; + /* Entry we're interested in */ Slapi_Entry *e, + /* attr type name */ char *type, + /* pointer to result set */ Slapi_ValueSet** results, + int *type_name_disposition, + char** actual_type_name, int flags, + int *buffer_flags) +{ + PRBool use_local_ctx = PR_FALSE; + Slapi_PBlock *local_pb = NULL; + vattr_context *ctx = NULL; + int rc = 0; + int sp_bit = 0; /* Set if an SP supplied an answer */ + vattr_sp_handle_list *list = NULL; + + vattr_get_thang my_get = {0}; + + if (c != NULL) { + rc = vattr_context_grok(&c); + if (0 != rc) { + if(!vattr_context_is_loop_msg_displayed(&c)) + { + /* Print a handy error log message */ + LDAPDebug(LDAP_DEBUG_ANY, + "Detected virtual attribute loop in get on entry %s, attribute %s\n", + slapi_entry_get_dn_const(e), type, 0); + vattr_context_set_loop_msg_displayed(&c); + } + return rc; + } + ctx = c; + } else { + use_local_ctx = PR_TRUE; + local_pb = slapi_pblock_new(); + ctx = vattr_context_new( local_pb ); + ctx->vattr_context_loop_count = 1; + ctx->error_displayed = 0; + } + + /* For attributes which are in the entry, we just need to get to the Slapi_Attr structure and yank out the slapi_value_set + structure. We either return a pointer directly to it, or we copy it, depending upon whether the caller asked us to try to + avoid copying. + */ + + /* First grok the entry, and remember what we saw. This call does no more than walk down the entry attribute list, do some string compares and copy pointers. */ + vattr_helper_get_entry_conts(e,type, &my_get); + /* Having done that, we now consult the attribute map to find service providers who are interested */ + /* Look for attribute in the map */ + if(!(flags & SLAPI_REALATTRS_ONLY)) + { + list = vattr_map_sp_getlist(type); + if (list) { + vattr_sp_handle *current_handle = NULL; + void *hint = NULL; + /* first lets consult the cache to save work */ + int cache_status; + + cache_status = + slapi_entry_vattrcache_find_values_and_type(e, type, + results, + actual_type_name); + switch(cache_status) + { + case SLAPI_ENTRY_VATTR_RESOLVED_EXISTS: /* cached vattr */ + { + sp_bit = 1; + + /* Complete analysis of type matching */ + if ( 0 == slapi_attr_type_cmp( type , *actual_type_name, SLAPI_TYPE_CMP_EXACT) ) + { + *type_name_disposition = SLAPI_VIRTUALATTRS_TYPE_NAME_MATCHED_EXACTLY_OR_ALIAS; + } else { + *type_name_disposition = SLAPI_VIRTUALATTRS_TYPE_NAME_MATCHED_SUBTYPE; + } + + break; + } - if (my_get.get_present) { - if (flags & SLAPI_VIRTUALATTRS_REQUEST_POINTERS) { - *results = my_get.get_present_values; - *actual_type_name = my_get.get_type_name; - } else { - *results = valueset_dup(my_get.get_present_values); - if (NULL == *results) { - rc = ENOMEM; - } else { - *actual_type_name = slapi_ch_strdup(my_get.get_type_name); - if (NULL == *actual_type_name) { - rc = ENOMEM; - } - } - } - if (flags & SLAPI_VIRTUALATTRS_REQUEST_POINTERS) { - *buffer_flags = SLAPI_VIRTUALATTRS_RETURNED_POINTERS; - } else { - *buffer_flags = SLAPI_VIRTUALATTRS_RETURNED_COPIES; - } - } else { - rc = SLAPI_VIRTUALATTRS_NOT_FOUND; - } - } - if (!use_local_ctx) { - vattr_context_ungrok(&c); - } - return rc; + case SLAPI_ENTRY_VATTR_RESOLVED_ABSENT: /* does not exist */ + break; /* look in entry */ + + case SLAPI_ENTRY_VATTR_NOT_RESOLVED: /* not resolved */ + default: /* any other result, resolve */ + { + for (current_handle = vattr_map_sp_first(list,&hint); current_handle; current_handle = vattr_map_sp_next(current_handle,&hint)) + { + rc = vattr_call_sp_get_value(current_handle,ctx,e,&my_get,type,results,type_name_disposition,actual_type_name,flags,buffer_flags, hint); + if (0 == rc) + { + sp_bit = 1; + break; + } + } + + if(!sp_bit) + { + /* clean up, we have failed and must now examine the + * entry itself + * But first lets cache the no result + * Creates the type (if necessary). + */ + slapi_entry_vattrcache_merge_sv(e, type, NULL ); + + } + else + { + /* + * we need to cache the virtual attribute + * creates the type (if necessary) and dups + * results. + */ + slapi_entry_vattrcache_merge_sv(e, *actual_type_name, + *results ); + } + + break; + } + } + } + } + /* If no SP supplied the answer, take it from the entry */ + if (!sp_bit && !(flags & SLAPI_VIRTUALATTRS_ONLY)) + { + rc = 0; /* reset return code (cause an sp must have failed) */ + *type_name_disposition = my_get.get_name_disposition; + + if (my_get.get_present) { + if (flags & SLAPI_VIRTUALATTRS_REQUEST_POINTERS) { + *results = my_get.get_present_values; + *actual_type_name = my_get.get_type_name; + } else { + *results = valueset_dup(my_get.get_present_values); + if (NULL == *results) { + rc = ENOMEM; + } else { + *actual_type_name = slapi_ch_strdup(my_get.get_type_name); + if (NULL == *actual_type_name) { + rc = ENOMEM; + } + } + } + if (flags & SLAPI_VIRTUALATTRS_REQUEST_POINTERS) { + *buffer_flags = SLAPI_VIRTUALATTRS_RETURNED_POINTERS; + } else { + *buffer_flags = SLAPI_VIRTUALATTRS_RETURNED_COPIES; + } + } else { + rc = SLAPI_VIRTUALATTRS_NOT_FOUND; + } + } + if (use_local_ctx) { + /* slapi_pblock_destroy cleans up pb_vattr_context, as well */ + slapi_pblock_destroy(local_pb); + } else { + vattr_context_ungrok(&c); + } + return rc; } /*
0
63b8ecee2d6d24c5de5d7b826a5bb47bc83ee45d
389ds/389-ds-base
Ticket #48295 - CI test: added test cases for ticket 48295 Description: Entry cache is not rolled back -- Linked Attributes plug-in - wrong behaviour when adding valid and broken links
commit 63b8ecee2d6d24c5de5d7b826a5bb47bc83ee45d Author: Noriko Hosoi <[email protected]> Date: Mon Dec 21 17:27:06 2015 -0800 Ticket #48295 - CI test: added test cases for ticket 48295 Description: Entry cache is not rolled back -- Linked Attributes plug-in - wrong behaviour when adding valid and broken links diff --git a/dirsrvtests/tickets/ticket48295_test.py b/dirsrvtests/tickets/ticket48295_test.py new file mode 100644 index 000000000..13a7f88a2 --- /dev/null +++ b/dirsrvtests/tickets/ticket48295_test.py @@ -0,0 +1,212 @@ +# --- BEGIN COPYRIGHT BLOCK --- +# Copyright (C) 2015 Red Hat, Inc. +# All rights reserved. +# +# License: GPL (version 3 or any later version). +# See LICENSE for details. +# --- END COPYRIGHT BLOCK --- +# +import os +import sys +import time +import ldap +import logging +import pytest +import shutil +from lib389 import DirSrv, Entry, tools +from lib389 import DirSrvTools +from lib389.tools import DirSrvTools +from lib389._constants import * +from lib389.properties import * + +log = logging.getLogger(__name__) + +installation_prefix = None + +LINKEDATTR_PLUGIN = 'cn=Linked Attributes,cn=plugins,cn=config' +MANAGER_LINK = 'cn=Manager Link,' + LINKEDATTR_PLUGIN +OU_PEOPLE = 'ou=People,' + DEFAULT_SUFFIX +LINKTYPE = 'directReport' +MANAGEDTYPE = 'manager' + +class TopologyStandalone(object): + def __init__(self, standalone): + standalone.open() + self.standalone = standalone + + [email protected](scope="module") +def topology(request): + ''' + This fixture is used to standalone topology for the 'module'. + ''' + global installation_prefix + + if installation_prefix: + args_instance[SER_DEPLOYED_DIR] = installation_prefix + + standalone = DirSrv(verbose=False) + + # Args for the standalone instance + args_instance[SER_HOST] = HOST_STANDALONE + args_instance[SER_PORT] = PORT_STANDALONE + args_instance[SER_SERVERID_PROP] = SERVERID_STANDALONE + args_standalone = args_instance.copy() + standalone.allocate(args_standalone) + + # Get the status of the instance and restart it if it exists + instance_standalone = standalone.exists() + + # Remove the instance + if instance_standalone: + standalone.delete() + + # Create the instance + standalone.create() + + # Used to retrieve configuration information (dbdir, confdir...) + standalone.open() + + # clear the tmp directory + standalone.clearTmpDir(__file__) + + # Here we have standalone instance up and running + return TopologyStandalone(standalone) + + +def _header(topology, label): + topology.standalone.log.info("###############################################") + topology.standalone.log.info("####### %s" % label) + topology.standalone.log.info("###############################################") + +def check_attr_val(topology, dn, attr, expected, revert): + try: + centry = topology.standalone.search_s(dn, ldap.SCOPE_BASE, 'uid=*') + if centry: + val = centry[0].getValue(attr) + if val: + if val.lower() == expected.lower(): + if revert: + log.info('Value of %s %s exists, which should not.' % (attr, expected)) + assert False + else: + log.info('Value of %s is %s' % (attr, expected)) + else: + if revert: + log.info('NEEDINFO: Value of %s is not %s, but %s' % (attr, expected, val)) + else: + log.info('Value of %s is not %s, but %s' % (attr, expected, val)) + assert False + else: + if revert: + log.info('Value of %s does not expectedly exist' % attr) + else: + log.info('Value of %s does not exist' % attr) + assert False + else: + log.fatal('Failed to get %s' % dn) + assert False + except ldap.LDAPError as e: + log.fatal('Failed to search ' + dn + ': ' + e.message['desc']) + assert False + + +def _48295_init(topology): + """ + Set up Linked Attribute + """ + _header(topology, 'Testing Ticket 48295 - Entry cache is not rolled back -- Linked Attributes plug-in - wrong behaviour when adding valid and broken links') + + log.info('Enable Dynamic plugins, and the linked Attrs plugin') + try: + topology.standalone.modify_s(DN_CONFIG, [(ldap.MOD_REPLACE, 'nsslapd-dynamic-plugins', 'on')]) + except ldap.LDAPError as e: + ldap.fatal('Failed to enable dynamic plugin!' + e.message['desc']) + assert False + + try: + topology.standalone.plugins.enable(name=PLUGIN_LINKED_ATTRS) + except ValueError as e: + ldap.fatal('Failed to enable linked attributes plugin!' + e.message['desc']) + assert False + + log.info('Add the plugin config entry') + try: + topology.standalone.add_s(Entry((MANAGER_LINK, { + 'objectclass': 'top extensibleObject'.split(), + 'cn': 'Manager Link', + 'linkType': LINKTYPE, + 'managedType': MANAGEDTYPE + }))) + except ldap.LDAPError as e: + log.fatal('Failed to add linked attr config entry: error ' + e.message['desc']) + assert False + + log.info('Add 2 entries: manager1 and employee1') + try: + topology.standalone.add_s(Entry(('uid=manager1,%s' % OU_PEOPLE, { + 'objectclass': 'top extensibleObject'.split(), + 'uid': 'manager1'}))) + except ldap.LDAPError as e: + log.fatal('Add manager1 failed: error ' + e.message['desc']) + assert False + + try: + topology.standalone.add_s(Entry(('uid=employee1,%s' % OU_PEOPLE, { + 'objectclass': 'top extensibleObject'.split(), + 'uid': 'employee1'}))) + except ldap.LDAPError as e: + log.fatal('Add employee1 failed: error ' + e.message['desc']) + assert False + + log.info('PASSED') + + +def _48295_run(topology): + """ + Add 2 linktypes - one exists, another does not + """ + + _header(topology, 'Add 2 linktypes to manager1 - one exists, another does not to make sure the managed entry does not have managed type.') + try: + topology.standalone.modify_s('uid=manager1,%s' % OU_PEOPLE, + [(ldap.MOD_ADD, LINKTYPE, 'uid=employee1,%s' % OU_PEOPLE), + (ldap.MOD_ADD, LINKTYPE, 'uid=doNotExist,%s' % OU_PEOPLE)]) + except ldap.UNWILLING_TO_PERFORM: + log.info('Add uid=employee1 and uid=doNotExist expectedly failed.') + pass + + log.info('Check managed attribute does not exist.') + check_attr_val(topology, 'uid=employee1,%s' % OU_PEOPLE, MANAGEDTYPE, 'uid=manager1,%s' % OU_PEOPLE, True) + + log.info('PASSED') + + +def _48295_final(topology): + topology.standalone.delete() + log.info('All PASSED') + + +def test_ticket48295(topology): + ''' + run_isolated is used to run these test cases independently of a test scheduler (xunit, py.test..) + To run isolated without py.test, you need to + - edit this file and comment '@pytest.fixture' line before 'topology' function. + - set the installation prefix + - run this program + ''' + global installation_prefix + installation_prefix = None + + _48295_init(topology) + + _48295_run(topology) + + _48295_final(topology) + +if __name__ == '__main__': + # Run isolated + # -s for DEBUG mode + + CURRENT_FILE = os.path.realpath(__file__) + pytest.main("-s %s" % CURRENT_FILE)
0
34c929353280b93eebe214f1c21f5b788aff1c39
389ds/389-ds-base
Ticket 47538 - Fix repl-monitor color and lag times Bug Description: Colors do not match the legend, and when the supplier or consumer max csns are not available, the lag time is displayed incorrectly. Fix Description: The color hash table needed to be sorted before processing, and we were not properly detecting the "Unavailable" state of a replica which lead to the odd lag times. Also added the string "Unavailable" for uninitialized values which allowed for a cleaner report when replicas are offline. Updated the man page as well. https://fedorahosted.org/389/ticket/47538 Reviewed by: nhosoi(Thanks!)
commit 34c929353280b93eebe214f1c21f5b788aff1c39 Author: Mark Reynolds <[email protected]> Date: Tue Jun 28 15:41:42 2016 -0400 Ticket 47538 - Fix repl-monitor color and lag times Bug Description: Colors do not match the legend, and when the supplier or consumer max csns are not available, the lag time is displayed incorrectly. Fix Description: The color hash table needed to be sorted before processing, and we were not properly detecting the "Unavailable" state of a replica which lead to the odd lag times. Also added the string "Unavailable" for uninitialized values which allowed for a cleaner report when replicas are offline. Updated the man page as well. https://fedorahosted.org/389/ticket/47538 Reviewed by: nhosoi(Thanks!) diff --git a/ldap/admin/src/scripts/repl-monitor.pl.in b/ldap/admin/src/scripts/repl-monitor.pl.in index 0247f24e7..248cf8bfc 100755 --- a/ldap/admin/src/scripts/repl-monitor.pl.in +++ b/ldap/admin/src/scripts/repl-monitor.pl.in @@ -596,7 +596,7 @@ sub process_suppliers # Skip replicas without agreements defined yet next if (! grep {$_->{ridx} == $ridx} @allagreements); $maxcsn = &print_master_header ($ridx, $mid); - if ( "$maxcsn" ne "none" ) { + if ( "$maxcsn" ne "Unavailable" ) { &print_consumer_header (); &print_consumers ($ridx, $mid); } @@ -754,12 +754,12 @@ sub print_consumers my ($c_maxcsn, $c_maxcsn_str, $c_lastmodified, $c_sidx, $lag, $markcolor); my ($c_replicaroot, $c_replicatype); my ($first_entry, $s_ldapurl, $c_ldapurl); - my $supplier_maxcsn = "_"; + my $supplier_maxcsn = "Unavailable"; my ($nrows); my ($found); undef @ouragreements; - $c_lastmodified = ""; + $c_lastmodified = "Unavailable"; # Collect all the consumer replicas for the current master replica push (@consumers, $m_ridx); @@ -790,18 +790,20 @@ sub print_consumers if ($c_ridx >= 0) { $myruv = $allruvs {"$c_ridx:$mid"}; - ($c_maxcsn, $c_lastmodified) = split ( /;/, $myruv ); - ($c_sidx, $c_replicaroot, $c_replicatype) = split (/:/, $allreplicas[$c_ridx]); - $c_replicaroot = "same as master" if $m_replicaroot eq $c_replicaroot; + if ($myruv) { + ($c_maxcsn, $c_lastmodified) = split ( /;/, $myruv ); + ($c_sidx, $c_replicaroot, $c_replicatype) = split (/:/, $allreplicas[$c_ridx]); + $c_replicaroot = "same as master" if $m_replicaroot eq $c_replicaroot; + } } else { # $c_ridx is actually -$c_sidx when c is not available $c_sidx = -$c_ridx; - $c_maxcsn_str = "_"; + $c_maxcsn_str = "Unavailable"; $lag = "n/a"; $markcolor = "red"; - $c_replicaroot = "_"; - $c_replicatype = "_"; + $c_replicaroot = "Unavailable"; + $c_replicatype = "Unavailable"; } $nrows = 0; @@ -932,7 +934,7 @@ sub get_supplier_maxcsn { my ($ridx, $s, $cn, $h, $p) = @_; my $decimalcsn; - my $csn = ""; + my $csn = "Unavailable"; # normalize suffix $s =~ s/ //; $s =~ lc $s; @@ -944,7 +946,7 @@ sub get_supplier_maxcsn last; } } - if($csn ne ""){ + if($csn && $csn ne "Unavailable"){ $decimalcsn = &to_decimal_csn ($csn); return "$csn:$decimalcsn"; } @@ -966,11 +968,16 @@ sub cacl_time_lag $supplier_csn_str = &to_string_csn ($s_maxcsn); $csn_str = &to_string_csn ($c_maxcsn); - if ($s_maxcsn && !$c_maxcsn) { + if ((!$s_maxcsn || $s_maxcsn eq "Unavailable") && + (!$c_maxcsn || $c_maxcsn eq "Unavailable")) { + $lag_str = "?:??:??"; + $markcolor = "white"; # Both unknown + } + elsif ($s_maxcsn && (!$c_maxcsn || $c_maxcsn eq "Unavailable")) { $lag_str = "- ?:??:??"; $markcolor = &get_color (36000); # assume consumer has big latency } - elsif (!$s_maxcsn && $c_maxcsn) { + elsif ((!$s_maxcsn || $s_maxcsn eq "Unavailable") && $c_maxcsn) { $lag_str = "+ ?:??:??"; $markcolor = &get_color (1); # consumer is ahead of supplier } @@ -1180,7 +1187,7 @@ sub to_decimal_csn { my ($maxcsn) = @_; if (!$maxcsn || $maxcsn eq "" || $maxcsn eq "Unavailable") { - return "none"; + return "Unavailable"; } my ($tm, $seq, $masterid, $subseq) = unpack("a8 a4 a4 a4", $maxcsn); @@ -1195,9 +1202,13 @@ sub to_decimal_csn sub to_string_csn { - my ($rawcsn, $decimalcsn) = split(/:/, "@_"); + my $str = shift; + if (!defined($str)){ + return "Unavailable"; + } + my ($rawcsn, $decimalcsn) = split(/:/, "$str"); if (!$rawcsn || $rawcsn eq "") { - return "none"; + return "Unavailable"; } if ($rawcsn eq "Unavailable"){ return $rawcsn; @@ -1221,7 +1232,7 @@ sub get_color $lag_minute /= 60; my ($color) = $allcolors { $colorkeys[0] }; - foreach ( keys %allcolors) { + foreach ( sort keys %allcolors) { if ($lag_minute >= $_){ $color = $allcolors {$_}; } @@ -1300,14 +1311,15 @@ sub print_legend if($opt_s){ return; } print "\n<center><p><font class=page-subtitle color=#0099cc>Time Lag Legend:</font><p>\n"; print "<table cellpadding=6 cols=$nlegends width=40%>\n<tr>\n"; + print "\n<td bgcolor=white><center>Unknown</center></td>\n"; my ($i, $j); for ($i = 0; $i < $nlegends - 1; $i++) { $j = $colorkeys[$i]; - print "\n<td bgcolor=$allcolors{$j}><center>within $colorkeys[$i+1] min</center></td>\n"; + print "\n<td bgcolor=$allcolors{$j}><center>Within $colorkeys[$i+1] minutes</center></td>\n"; } $j = $colorkeys[$i]; - print "\n<td bgcolor=$allcolors{$j}><center>over $colorkeys[$i] min</center></td>\n"; - print "\n<td bgcolor=red><center>server n/a</center></td>\n"; + print "\n<td bgcolor=$allcolors{$j}><center>Over $colorkeys[$i] minutes</center></td>\n"; + print "\n<td bgcolor=red><center>Server n/a</center></td>\n"; print "</table></center>\n"; } diff --git a/man/man1/repl-monitor.1 b/man/man1/repl-monitor.1 index 37a5fa48a..17b9c4b95 100644 --- a/man/man1/repl-monitor.1 +++ b/man/man1/repl-monitor.1 @@ -2,7 +2,7 @@ .\" First parameter, NAME, should be all caps .\" Second parameter, SECTION, should be 1-8, maybe w/ subsection .\" other parameters are allowed: see man(7), man(1) -.TH REPL-MONITOR 1 "May 18, 2008" +.TH REPL-MONITOR 1 "Jun 28, 2016" .\" Please adjust this date whenever revising the manpage. .\" .\" Some roff macros, for reference: @@ -68,6 +68,56 @@ Prompt for passwords Print plain text report .br +.SH CONFIGURATION FILE +This section describes the various directives that can be used in the configuration file. +.TP +.B [connection] +The connection details about a replica +.br + +host:port:binddn:bindpwd:cert_file +.br + +or, +.br + +host:port=shadowport:binddn:bindpwd:cert_file +.TP +.B [alias] +Define an alias for a server, this alias is used in the report in place of the +hostname/port + +.br +alias = host:port +.TP +.B [color] +Set a color based on the replicaton lag time lowmark (in minutes) +.br + +.R lowmark = color +.SH EXAMPLE +Example of a configuration file: + +[connection] +.br +localhost.localdomain:3891:cn=directory manager:password:* +.br +localhost2.localdomain:3892:cn=directory manager:password:* + +[alias] +.br +MY_SYSTEM1 = localhost.localdomain:3891 +.br +MY_SYSTEM2 = localhost2.localdomain:3892 + +[color] +.br +0 = #CCFFCC +.br +5 = #FFFFCC +.br +60 = #FFCCCC + .SH AUTHOR repl-monitor was written by the 389 Project. .SH "REPORTING BUGS" @@ -75,14 +125,14 @@ Report bugs to https://fedorahosted.org/389/newticket. .SH COPYRIGHT Copyright \(co 2001 Sun Microsystems, Inc. Used by permission. .br -Copyright \(co 2008 Red Hat, Inc. +Copyright \(co 2016 Red Hat, Inc. .br This manual page was written by Michele Baldessari <[email protected]>, for the Debian project (but may be used by others). .br -Manual page updated by Mark Reynolds <[email protected]> 10/11/13 +Manual page updated by Mark Reynolds <[email protected]> 6/28/2016 .br This is free software. You may redistribute copies of it under the terms of the Directory Server license found in the LICENSE file of this software distribution. This license is essentially the GNU General Public -License version 2 with an exception for plug\(hyin distribution. +License version 3 with an exception for plug\(hyin distribution.
0
44a223f73a537445976a77af1652515ea46f970b
389ds/389-ds-base
Ticket #48231 - logconv autobind handling regression caused by 47446 Description: When there are autobinds with ldapi, the tool fails with an syntax error: Use of uninitialized value in transliteration (tr///) at /Local/dirsrv/bin/logconv.pl line 2018, <$LOGFH> line 207. Use of uninitialized value $tmpp in hash element at /Local/dirsrv/bin/logconv.pl line 2019, <$LOGFH> line 207. Thanks for providing the fix and testing it, pj101 and [email protected]. Reviewed by [email protected]. https://fedorahosted.org/389/ticket/48231
commit 44a223f73a537445976a77af1652515ea46f970b Author: Noriko Hosoi <[email protected]> Date: Thu Jul 30 11:07:40 2015 -0700 Ticket #48231 - logconv autobind handling regression caused by 47446 Description: When there are autobinds with ldapi, the tool fails with an syntax error: Use of uninitialized value in transliteration (tr///) at /Local/dirsrv/bin/logconv.pl line 2018, <$LOGFH> line 207. Use of uninitialized value $tmpp in hash element at /Local/dirsrv/bin/logconv.pl line 2019, <$LOGFH> line 207. Thanks for providing the fix and testing it, pj101 and [email protected]. Reviewed by [email protected]. https://fedorahosted.org/389/ticket/48231 diff --git a/ldap/admin/src/logconv.pl b/ldap/admin/src/logconv.pl index 3113f8ae8..9cd9aaa50 100755 --- a/ldap/admin/src/logconv.pl +++ b/ldap/admin/src/logconv.pl @@ -2025,8 +2025,8 @@ sub parseLineNormal if($1 eq $rootDN){ $rootDNBindCount++; } + $tmpp = $1; if($usage =~ /f/ || $usage =~ /u/ || $usage =~ /U/ || $usage =~ /b/ || $verb eq "yes"){ - $tmpp = $1; $tmpp =~ tr/A-Z/a-z/; $hashes->{bindlist}->{$tmpp}++; }
0
5b4e7f84bfe5658210be38a7560323fb9c1870ed
389ds/389-ds-base
Use WinSync components from sbc.
commit 5b4e7f84bfe5658210be38a7560323fb9c1870ed Author: Thomas Lackey <[email protected]> Date: Mon May 16 21:58:00 2005 +0000 Use WinSync components from sbc. diff --git a/components.mk b/components.mk index 43c9a420f..d218fa4ee 100644 --- a/components.mk +++ b/components.mk @@ -526,7 +526,7 @@ WRAPPER = wrapper_win32_$(WRAPPER_VERSION).zip WRAPPER_DEST = $(NSCP_DISTDIR_FULL_RTL)/wrapper WRAPPER_FILE = $(WRAPPER_DEST)/$(WRAPPER) WRAPPER_FILES = $(WRAPPER) -WRAPPER_RELEASE = $(COMPONENTS_DIR_DEV)/wrapper +WRAPPER_RELEASE = $(COMPONENTS_DIR)/wrapper WRAPPER_DIR = $(WRAPPER_RELEASE)/$(WRAPPER_VERSION) WRAPPER_DEP = $(WRAPPER_FILE) WRAPPER_REL_DIR=$(subst -bin,,$(subst .zip,,$(WRAPPER))) @@ -556,7 +556,7 @@ SWIG = swigwin-$(SWIG_VERSION).zip SWIG_DEST = $(NSCP_DISTDIR_FULL_RTL)/swig SWIG_FILE = $(SWIG_DEST)/$(SWIG) SWIG_FILES = $(SWIG) -SWIG_RELEASE = $(COMPONENTS_DIR_DEV)/swig +SWIG_RELEASE = $(COMPONENTS_DIR)/swig SWIG_DIR = $(SWIG_RELEASE)/$(SWIG_VERSION) SWIG_DEP = $(SWIG_FILE) SWIG_REL_DIR=$(subst -bin,,$(subst .zip,,$(SWIG))) @@ -589,7 +589,7 @@ APACHEDS_DEST = $(NSCP_DISTDIR_FULL_RTL)/apacheds APACHEDS_FILE = $(APACHEDS_DEST)/$(APACHEDS) APACHEDS_FILES = $(APACHEDS) APACHEDSSRC_FILES = $(APACHEDSSRC) -APACHEDS_RELEASE = $(COMPONENTS_DIR_DEV)/apacheds +APACHEDS_RELEASE = $(COMPONENTS_DIR)/apacheds APACHEDS_DIR = $(APACHEDS_RELEASE)/$(APACHEDS_VERSION) APACHEDS_DEP = $(APACHEDS_FILE) APACHEDS_REL_DIR=$(subst -bin,,$(subst .jar,,$(APACHEDS))) @@ -626,7 +626,7 @@ MAVEN = maven-$(MAVEN_VERSION).zip MAVEN_DEST = $(NSCP_DISTDIR_FULL_RTL)/maven MAVEN_FILE = $(MAVEN_DEST)/$(MAVEN) MAVEN_FILES = $(MAVEN) -MAVEN_RELEASE = $(COMPONENTS_DIR_DEV)/maven +MAVEN_RELEASE = $(COMPONENTS_DIR)/maven MAVEN_DIR = $(MAVEN_RELEASE)/$(MAVEN_VERSION) MAVEN_DEP = $(MAVEN_FILE) MAVEN_REL_DIR=$(subst -bin,,$(subst .zip,,$(MAVEN)))
0
f41a430b5a802254a8fbb7bdf7e359413053b34d
389ds/389-ds-base
Issue 31 - Add functional tests for MemberOf plugin Description: Add tests for testing the functionality of MemberOf plugin. These tests make sure the plugin behaves properly based on its configuration. https://pagure.io/lib389/issue/31 Author: Ilias95 Review by: wibrown (Thanks, great work!)
commit f41a430b5a802254a8fbb7bdf7e359413053b34d Author: Ilias Stamatis <[email protected]> Date: Mon Jun 19 04:08:10 2017 +0300 Issue 31 - Add functional tests for MemberOf plugin Description: Add tests for testing the functionality of MemberOf plugin. These tests make sure the plugin behaves properly based on its configuration. https://pagure.io/lib389/issue/31 Author: Ilias95 Review by: wibrown (Thanks, great work!) diff --git a/src/lib389/lib389/tests/plugins/__init__.py b/src/lib389/lib389/tests/plugins/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/src/lib389/lib389/tests/plugins/memberof_test.py b/src/lib389/lib389/tests/plugins/memberof_test.py new file mode 100644 index 000000000..5079bd113 --- /dev/null +++ b/src/lib389/lib389/tests/plugins/memberof_test.py @@ -0,0 +1,310 @@ +# --- BEGIN COPYRIGHT BLOCK --- +# Copyright (C) 2016-2017 Red Hat, Inc. +# All rights reserved. +# +# License: GPL (version 3 or any later version). +# See LICENSE for details. +# --- END COPYRIGHT BLOCK --- +# + +import pytest + +from lib389.topologies import topology_st +from lib389.plugins import MemberOfPlugin +from lib389.properties import BACKEND_NAME, BACKEND_SUFFIX +from lib389._constants import DEFAULT_SUFFIX +from lib389.tests.plugins.utils import ( + create_test_user, create_test_group, create_test_ou, delete_objects) + + [email protected](scope="module") +def plugin(request): + topology = topology_st(request) + plugin = MemberOfPlugin(topology.standalone) + return plugin + + +def test_memberof_enable_disable(plugin): + """ + Test that the plugin doesn't do anything while disabled, and functions + properly when enabled. + + NOTICE: This test case leaves the plugin enabled for the following tests. + """ + # assert plugin is disabled (by default) + assert plugin.status() == False + + user = create_test_user(plugin._instance) + group = create_test_group(plugin._instance) + + # add user to the group (which normally triggers the plugin) + group.add_member(user.dn) + + memberofattr = plugin.get_attr() + # assert no memberof attribute was created by the plugin + assert not memberofattr in user.get_all_attrs() + + # enable the plugin and restart the server for the action to take effect + plugin.enable() + plugin._instance.restart() + assert plugin.status() == True + + # trigger the plugin again + group.remove_member(user.dn) + group.add_member(user.dn) + + # assert that the memberof attribute was now properly set + assert memberofattr in user.get_all_attrs() + + # clean up for subsequent test cases + delete_objects([user, group]) + +def test_memberofattr(plugin): + """ + Test that the plugin automatically creates an attribute on user entries + declaring membership after adding them to a group. The attribute depends + on the value of memberOfAttr. + """ + memberofattr = "memberOf" + plugin.set_attr(memberofattr) + + user = create_test_user(plugin._instance) + group = create_test_group(plugin._instance) + + # memberof attribute should not yet appear + assert not memberofattr in user.get_all_attrs() + + # trigger the plugin + group.add_member(user.dn) + + # assert that the memberof attribute was automatically set by the plugin + assert group.dn in user.get_attr_vals(memberofattr) + + # clean up for subsequent test cases + delete_objects([user, group]) + +def test_memberofgroupattr(plugin): + """ + memberOfGroupAttr gives the attribute in the group entry to poll to identify + member DNs. Test that the memberOf is set on a user only for groups whose + membership attribute is included in memberOfGroupAttr. + """ + memberofattr = plugin.get_attr() + + # initially "member" should be the default and only value of memberOfGroupAttr + assert plugin.get_attr_vals('memberofgroupattr') == ['member'] + + user = create_test_user(plugin._instance) + group_normal = create_test_group(plugin._instance) + group_unique = create_test_group(plugin._instance, unique_group=True) + + # add user to both groups + group_normal.add_member(user.dn) + group_unique.add_member(user.dn) + + # assert that the memberof attribute was set for normal group only + assert group_normal.dn in user.get_attr_vals(memberofattr) + assert not group_unique.dn in user.get_attr_vals(memberofattr) + + # add another value to memberOfGroupAttr + plugin.add_groupattr('uniqueMember') + + # remove user from groups and add them again in order to trigger the plugin + group_normal.remove_member(user.dn) + group_normal.add_member(user.dn) + group_unique.remove_member(user.dn) + group_unique.add_member(user.dn) + + # assert that the memberof attribute was set for both groups this time + assert group_normal.dn in user.get_attr_vals(memberofattr) + assert group_unique.dn in user.get_attr_vals(memberofattr) + + # clean up for subsequent test cases + delete_objects([user, group_normal, group_unique]) + +def test_memberofallbackends(plugin): + """ + By default the MemberOf plugin only looks for potential members for users + who are in the same database as the group. Test that when memberOfAllBackends + is enabled, memberOf will search across all databases instead. + """ + ou_value = "ou=People2" + ou_suffix = DEFAULT_SUFFIX + + # create a new backend + plugin._instance.backends.create( + None, properties={ + BACKEND_NAME: "People2Data", + BACKEND_SUFFIX: ou_value + "," + ou_suffix, + }) + + # create a new sub-suffix stored in the new backend + ou2 = create_test_ou(plugin._instance, ou=ou_value, suffix=ou_suffix) + + # add a user in the default backend + user_b1 = create_test_user(plugin._instance) + # add a user in the new backend + user_b2 = create_test_user(plugin._instance, suffix=ou2.dn) + # create a group in the default backend + group = create_test_group(plugin._instance) + + # configure memberof to search only for users who are in the same backend as the group + plugin.disable_allbackends() + + group.add_member(user_b1.dn) + group.add_member(user_b2.dn) + + memberofattr = plugin.get_attr() + + # assert that memberOfAttr was set for the user stored in the same backend as the group + assert group.dn in user_b1.get_attr_vals(memberofattr) + # assert that memberOfAttr was NOT set for the user stored in a different backend + assert not memberofattr in user_b2.get_all_attrs() + + # configure memberof to search across all backends + plugin.enable_allbackends() + + # remove users from group and add them again in order to re-trigger the plugin + group.remove_member(user_b1.dn) + group.remove_member(user_b2.dn) + group.add_member(user_b1.dn) + group.add_member(user_b2.dn) + + # assert that memberOfAttr was set for users stored in both backends + assert group.dn in user_b1.get_attr_vals(memberofattr) + assert group.dn in user_b2.get_attr_vals(memberofattr) + + # clean up for subsequent test cases + delete_objects([user_b1, user_b2, group, ou2]) + +def test_memberofskipnested(plugin): + """ + Test that when memberOfSkipNested is off (default) they plugin can properly + handle nested groups (groups that are member of other groups). Respectively + make sure that when memberOfSkipNested is on, the plugin lists only groups + to which a user was added directly. + """ + user = create_test_user(plugin._instance) + group1 = create_test_group(plugin._instance) + group2 = create_test_group(plugin._instance) + + # don't skip nested groups (this is the default) + plugin.disable_skipnested() + + # create a nested group by listing group1 as a member of group2 + group2.add_member(group1.dn) + # add user to group1 only + group1.add_member(user.dn) + + memberofattr = plugin.get_attr() + + assert group2.dn in group1.get_attr_vals(memberofattr) + # assert that memberOfAttr of user includes both groups + # even though they were not directly added to group2 + assert group1.dn in user.get_attr_vals(memberofattr) + assert group2.dn in user.get_attr_vals(memberofattr) + + # skip nested groups + plugin.enable_skipnested() + + # remove from groups and add again in order to re-trigger the plugin + group2.remove_member(group1.dn) + group1.remove_member(user.dn) + group2.add_member(group1.dn) + group1.add_member(user.dn) + + assert group2.dn in group1.get_attr_vals(memberofattr) + # assert that user's memberOfAttr includes only the group to which they were added + assert group1.dn in user.get_attr_vals(memberofattr) + assert not group2.dn in user.get_attr_vals(memberofattr) + + # clean up for subsequent test cases + delete_objects([user, group1, group2]) + +def test_memberofautoaddocc(plugin): + """ + Test that the MemberOf plugin automatically adds the object class defined + by memberOfAutoAddOC to a user object, if it does not contain an object + class that allows the memberOf attribute. + """ + user = create_test_user(plugin._instance) + group = create_test_group(plugin._instance) + + # delete any object classes that allow the memberOf attribute + if "nsMemberOf" in user.get_attr_vals("objectClass"): + user.remove("objectClass", "nsMemberOf") + if "inetUser" in user.get_attr_vals("objectClass"): + user.remove("objectClass", "inetUser") + if "inetAdmin" in user.get_attr_vals("objectClass"): + user.remove("objectClass", "inetAdmin") + + # set a valid object class to memberOfAutoAddOC + plugin.set_autoaddoc("nsMemberOf") + # assert that user has not got this object class at the moment + assert not "nsMemberOf" in user.get_attr_vals("objectClass") + + # trigger the plugin + group.add_member(user.dn) + + # assert that the object class defined by memberOfAutoAddOC now exists + assert "nsMemberOf" in user.get_attr_vals("objectClass") + + # reset user entry + group.remove_member(user.dn) + user.remove("objectClass", "nsMemberOf") + + # repeat for different object class + plugin.set_autoaddoc("inetUser") + assert not "inetUser" in user.get_attr_vals("objectClass") + + # re-trigger the plugin + group.add_member(user.dn) + + assert "inetUser" in user.get_attr_vals("objectClass") + + group.remove_member(user.dn) + user.remove("objectClass", "inetUser") + + # repeat for different object class + plugin.set_autoaddoc("inetAdmin") + assert not "inetAdmin" in user.get_attr_vals("objectClass") + + # re-trigger the plugin + group.add_member(user.dn) + + assert "inetAdmin" in user.get_attr_vals("objectClass") + + # clean up for subsequent test cases + delete_objects([user, group]) + +def test_scoping(plugin): + """ + Tests that the MemberOf plugin works on suffixes listed in memberOfEntryScope, + but skips suffixes listed in memberOfEntryScopeExcludeSubtree. + """ + # create a new ou and 2 users under different ous + ou2 = create_test_ou(plugin._instance) + user_p1 = create_test_user(plugin._instance) + user_p2 = create_test_user(plugin._instance, suffix=ou2.dn) + group = create_test_group(plugin._instance) + + # define include and exclude suffixes for MemberOf + plugin.add_entryscope(DEFAULT_SUFFIX) + plugin.add_excludescope(ou2.dn) + + group.add_member(user_p1.dn) + group.add_member(user_p2.dn) + + memberofattr = plugin.get_attr() + + # assert that memberOfAttr was set for entry of an included suffix + assert group.dn in user_p1.get_attr_vals(memberofattr) + # assert that memberOfAttr was NOT set for entry of an excluded suffix + assert not memberofattr in user_p2.get_all_attrs() + + # clean up for subsequent test cases + delete_objects([user_p1, user_p2, group, ou2]) + + # This does not work at the moment, because there is a bug in DS (#49284). + # plugin.remove_all_excludescope() + # plugin.remove_all_entryscope() diff --git a/src/lib389/lib389/tests/plugins/utils.py b/src/lib389/lib389/tests/plugins/utils.py new file mode 100644 index 000000000..4a7e248f5 --- /dev/null +++ b/src/lib389/lib389/tests/plugins/utils.py @@ -0,0 +1,123 @@ +# --- BEGIN COPYRIGHT BLOCK --- +# Copyright (C) 2016-2017 Red Hat, Inc. +# All rights reserved. +# +# License: GPL (version 3 or any later version). +# See LICENSE for details. +# --- END COPYRIGHT BLOCK --- +# + +from lib389.idm.user import UserAccount +from lib389.idm.group import Group, UniqueGroup +from lib389.idm.organisationalunit import OrganisationalUnit +from lib389._constants import DEFAULT_SUFFIX + + +# These globals are only used by the functions of this module. +# Each time we create a new test user/group/ou we increment the corresponding +# variable by 1, in order to ensure DN uniqueness. +test_user_id = 0 +test_group_id = 0 +test_ou_id = 0 + + +def create_test_user(instance, cn=None, suffix=None): + """ + Creates a new user for testing. + + It tries to create a user that doesn't already exist by using a different + ID each time. However, if it is provided with an existing cn/suffix it + will fail to create a new user and it will raise an LDAP error. + + Returns a UserAccount object. + """ + global test_user_id + + if cn is None: + cn = "cn=testuser_" + str(test_user_id) + test_user_id += 1 + + if suffix is None: + suffix = "ou=People," + DEFAULT_SUFFIX + dn = cn + "," + suffix + + properties = { + 'uid': cn, + 'cn': cn, + 'sn': 'user', + 'uidNumber': str(1000+test_user_id), + 'gidNumber': '2000', + 'homeDirectory': '/home/' + cn + } + + user = UserAccount(instance, dn) + user.create(properties=properties) + + return user + +def create_test_group(instance, cn=None, suffix=None, unique_group=False): + """ + Creates a new group for testing. + + It tries to create a group that doesn't already exist by using a different + ID each time. However, if it is provided with an existing cn/suffix it + will fail to create a new group and it will raise an LDAP error. + + Returns a Group object. + """ + global test_group_id + + if cn is None: + cn = "cn=testgroup_" + str(test_group_id) + test_group_id += 1 + + if suffix is None: + suffix = "ou=Groups," + DEFAULT_SUFFIX + dn = cn + "," + suffix + + properties = { + 'cn': cn, + 'ou': 'groups', + } + + if unique_group: + group = UniqueGroup(instance, dn) + else: + group = Group(instance, dn) + + group.create(properties=properties) + + return group + +def create_test_ou(instance, ou=None, suffix=None): + """ + Creates a new Organizational Unit for testing. + + It tries to create a ou that doesn't already exist by using a different + ID each time. However, if it is provided with an existing ou/suffix it + will fail to create a new ou and it will raise an LDAP error. + + Returns an OrganisationalUnit object. + """ + global test_ou_id + + if ou is None: + ou = "ou=TestOU_" + str(test_ou_id) + test_ou_id += 1 + + if suffix is None: + suffix = DEFAULT_SUFFIX + dn = ou + "," + suffix + + properties = { + 'ou': ou, + } + + ou = OrganisationalUnit(instance, dn) + ou.create(properties=properties) + + return ou + +def delete_objects(objects): + for obj in objects: + obj.delete()
0
cbb8ad61d1760b7bf97607a1659cf36ab15bfd5c
389ds/389-ds-base
Resolves: 253818 Summary: Support FHS opt layout for perldir and propertydir.
commit cbb8ad61d1760b7bf97607a1659cf36ab15bfd5c Author: Nathan Kinder <[email protected]> Date: Wed Aug 22 05:11:34 2007 +0000 Resolves: 253818 Summary: Support FHS opt layout for perldir and propertydir. diff --git a/configure b/configure index aec91f148..afaae43a5 100755 --- a/configure +++ b/configure @@ -23160,6 +23160,10 @@ if test "$with_fhs_opt" = "yes"; then serverplugindir=/plugins # relative to datadir infdir=/inf + # location of property/resource files, relative to datadir + propertydir=/properties + # relative to libdir + perldir=/perl else if test "$with_fhs" = "yes"; then ac_default_prefix=/usr @@ -23178,17 +23182,17 @@ else serverplugindir=/$PACKAGE_NAME/plugins # relative to datadir infdir=/$PACKAGE_NAME/inf + # location of property/resource files, relative to datadir + propertydir=/$PACKAGE_NAME/properties + # relative to libdir + perldir=/$PACKAGE_NAME/perl fi # Shared paths for all layouts # relative to sysconfdir configdir=/$PACKAGE_NAME/config -# location of property/resource files, relative to datadir -propertydir=/$PACKAGE_NAME/properties # relative to sysconfdir schemadir=/$PACKAGE_NAME/schema -# relative to libdir -perldir=/$PACKAGE_NAME/perl # default user, group defaultuser=nobody diff --git a/configure.ac b/configure.ac index 2bd249b3a..e4f2574ec 100644 --- a/configure.ac +++ b/configure.ac @@ -165,6 +165,10 @@ if test "$with_fhs_opt" = "yes"; then serverplugindir=/plugins # relative to datadir infdir=/inf + # location of property/resource files, relative to datadir + propertydir=/properties + # relative to libdir + perldir=/perl else if test "$with_fhs" = "yes"; then ac_default_prefix=/usr @@ -185,17 +189,17 @@ else serverplugindir=/$PACKAGE_NAME/plugins # relative to datadir infdir=/$PACKAGE_NAME/inf + # location of property/resource files, relative to datadir + propertydir=/$PACKAGE_NAME/properties + # relative to libdir + perldir=/$PACKAGE_NAME/perl fi # Shared paths for all layouts # relative to sysconfdir configdir=/$PACKAGE_NAME/config -# location of property/resource files, relative to datadir -propertydir=/$PACKAGE_NAME/properties # relative to sysconfdir schemadir=/$PACKAGE_NAME/schema -# relative to libdir -perldir=/$PACKAGE_NAME/perl # default user, group defaultuser=nobody
0
0762be835d519d82fd8627105874fd3cdd861278
389ds/389-ds-base
Bug 573889 - Migration does not remove deprecated schema The DSMigration.pm has been modified such that it executes the update scripts including removing deprecated schema.
commit 0762be835d519d82fd8627105874fd3cdd861278 Author: Endi S. Dewata <[email protected]> Date: Tue Oct 5 16:31:20 2010 -0400 Bug 573889 - Migration does not remove deprecated schema The DSMigration.pm has been modified such that it executes the update scripts including removing deprecated schema. diff --git a/ldap/admin/src/scripts/DSMigration.pm.in b/ldap/admin/src/scripts/DSMigration.pm.in index 38407ba24..1bd594c66 100644 --- a/ldap/admin/src/scripts/DSMigration.pm.in +++ b/ldap/admin/src/scripts/DSMigration.pm.in @@ -51,6 +51,7 @@ use Migration; use DSUtil; use Inf; use DSCreate; +use DSUpdate; # tempfiles use File::Temp qw(tempfile tempdir); @@ -1042,6 +1043,10 @@ sub migrateDSInstance { return @errs; } + if (@errs = updateDS($mig)) { + return @errs; + } + # next, the databases if (@errs = migrateDatabases($mig, $inst, $src, $dest)) { return @errs;
0
09b769566b5ac421130687cd77c82635d915c809
389ds/389-ds-base
Issue 5965 - UI, CLI - Fix Account Policy Plugin functionality issues (#6323) Description: Make state attributes creatable. Fix existing accpol_check_all_state_attrs_test test. Add new notification modal - WarningModal. Fix configArea to nsslapd-pluginarg0 in UI and CLI. Fix various minor UI issues. Note: CoS entry and Account Policy configuration entry can be created using LDAP Browser. Fixes: https://github.com/389ds/389-ds-base/issues/5965 Reviewed by: @progier389 (Thanks!)
commit 09b769566b5ac421130687cd77c82635d915c809 Author: Simon Pichugin <[email protected]> Date: Tue Sep 17 17:05:43 2024 -0700 Issue 5965 - UI, CLI - Fix Account Policy Plugin functionality issues (#6323) Description: Make state attributes creatable. Fix existing accpol_check_all_state_attrs_test test. Add new notification modal - WarningModal. Fix configArea to nsslapd-pluginarg0 in UI and CLI. Fix various minor UI issues. Note: CoS entry and Account Policy configuration entry can be created using LDAP Browser. Fixes: https://github.com/389ds/389-ds-base/issues/5965 Reviewed by: @progier389 (Thanks!) diff --git a/dirsrvtests/tests/suites/plugins/accpol_check_all_state_attrs_test.py b/dirsrvtests/tests/suites/plugins/accpol_check_all_state_attrs_test.py index ec518ca7f..b7ffd3d78 100644 --- a/dirsrvtests/tests/suites/plugins/accpol_check_all_state_attrs_test.py +++ b/dirsrvtests/tests/suites/plugins/accpol_check_all_state_attrs_test.py @@ -1,5 +1,5 @@ # --- BEGIN COPYRIGHT BLOCK --- -# Copyright (C) 2023 Red Hat, Inc. +# Copyright (C) 2024 Red Hat, Inc. # All rights reserved. # # License: GPL (version 3 or any later version). @@ -36,7 +36,6 @@ NEW_PASSWORD = 'password123' USER_SELF_MOD_ACI = '(targetattr="userpassword")(version 3.0; acl "pwp test"; allow (all) userdn="ldap:///self";)' ANON_ACI = "(targetattr=\"*\")(version 3.0; acl \"Anonymous Read access\"; allow (read,search,compare) userdn = \"ldap:///anyone\";)" [email protected](reason='https://github.com/389ds/389-ds-base/issues/5998') def test_inactivty_and_expiration(topo): """Test account expiration works when we are checking all state attributes @@ -61,12 +60,14 @@ def test_inactivty_and_expiration(topo): 7. Success """ - INACTIVITY_LIMIT = 60 + # passwordMaxAge should be less than accountInactivityLimit divided by 2 + INACTIVITY_LIMIT = 12 + MAX_AGE = 2 # Configure instance inst = topo.standalone inst.config.set('passwordexp', 'on') - inst.config.set('passwordmaxage', '2') + inst.config.set('passwordmaxage', str(MAX_AGE)) inst.config.set('passwordGraceLimit', '5') inst.config.set('nsslapd-errorlog-level', str(LOG_PLUGIN + LOG_DEFAULT)) @@ -87,15 +88,6 @@ def test_inactivty_and_expiration(topo): 'homeDirectory': '/home/test', }) - # Reset test user password to reset passwordExpirationtime - conn = test_user.bind(PASSWORD) - test_user = UserAccount(conn, TEST_ENTRY_DN) - date_pw_is_set = datetime.now() - test_user.replace('userpassword', NEW_PASSWORD) - - # Sleep a little bit, we'll sleep the remaining 10 seconds later - time.sleep(3) - # Configure account policy plugin plugin = AccountPolicyPlugin(inst) plugin.enable() @@ -110,20 +102,19 @@ def test_inactivty_and_expiration(topo): accp.set('checkAllStateAttrs', 'on') inst.restart() - # Bind as test user to reset lastLoginTime - conn = test_user.bind(NEW_PASSWORD) + # Reset test user password to reset passwordExpirationtime + conn = test_user.bind(PASSWORD) test_user = UserAccount(conn, TEST_ENTRY_DN) + test_user.reset_password(NEW_PASSWORD) + + # Sleep a little bit, we'll sleep the remaining time later + time.sleep(INACTIVITY_LIMIT / 2) + + # Bind as test user to reset lastLoginTime + test_user.bind(NEW_PASSWORD) - # Sleep to exceed passwordexprattiontime over INACTIVITY_LIMIT seconds, but less than - # INACTIVITY_LIMIT seconds for lastLoginTime - # Based on real time because inst.restart() time is unknown - limit = timedelta(seconds=INACTIVITY_LIMIT+1) - now = datetime.now() - if now - date_pw_is_set >= limit: - pytest.mark.skip(reason="instance restart time was greater than inactivity limit") - return - deltat = limit + date_pw_is_set - now - time.sleep(deltat.total_seconds()) + # Sleep the remaining time plus extra double passwordMaxAge seconds + time.sleep(INACTIVITY_LIMIT / 2 + MAX_AGE * 2) # Try to bind, but password expiration should reject this as lastLogintTime # has not exceeded the inactivity limit diff --git a/src/cockpit/389-console/src/lib/notifications.jsx b/src/cockpit/389-console/src/lib/notifications.jsx index 06c31c34b..089feb223 100644 --- a/src/cockpit/389-console/src/lib/notifications.jsx +++ b/src/cockpit/389-console/src/lib/notifications.jsx @@ -97,6 +97,54 @@ export class DoubleConfirmModal extends React.Component { } } +export class WarningModal extends React.Component { + render() { + const { + showModal, + closeHandler, + mTitle, + mMsg, + } = this.props; + + return ( + <Modal + variant={ModalVariant.small} + title={mTitle} + titleIconVariant="warning" + isOpen={showModal} + aria-labelledby="warning-modal" + onClose={closeHandler} + actions={[ + <Button key="ok" variant="primary" onClick={closeHandler}> + {_("Okay")} + </Button> + ]} + > + <Form isHorizontal autoComplete="off"> + <TextContent> + <Text className="ds-margin-top ds-margin-bottom" component={TextVariants.h3}> + {mMsg} + </Text> + </TextContent> + </Form> + </Modal> + ); + } +} + +WarningModal.propTypes = { + showModal: PropTypes.bool, + closeHandler: PropTypes.func, + mTitle: PropTypes.string, + mMsg: PropTypes.string, +}; + +WarningModal.defaultProps = { + showModal: false, + mTitle: "", + mMsg: "", +}; + DoubleConfirmModal.propTypes = { showModal: PropTypes.bool, closeHandler: PropTypes.func, diff --git a/src/cockpit/389-console/src/lib/plugins/accountPolicy.jsx b/src/cockpit/389-console/src/lib/plugins/accountPolicy.jsx index f909cf909..79e6626fc 100644 --- a/src/cockpit/389-console/src/lib/plugins/accountPolicy.jsx +++ b/src/cockpit/389-console/src/lib/plugins/accountPolicy.jsx @@ -18,14 +18,17 @@ import { import PropTypes from "prop-types"; import PluginBasicConfig from "./pluginBasicConfig.jsx"; import { log_cmd, valid_dn } from "../tools.jsx"; -import { DoubleConfirmModal } from "../notifications.jsx"; +import { + DoubleConfirmModal, + WarningModal +} from "../notifications.jsx"; const _ = cockpit.gettext; // Use default account policy name class AccountPolicy extends React.Component { - componentDidMount() { + componentDidMount(prevProps) { this.updateFields(); } @@ -48,6 +51,8 @@ class AccountPolicy extends React.Component { this.handleAddConfig = this.handleAddConfig.bind(this); this.handleEditConfig = this.handleEditConfig.bind(this); this.deleteConfig = this.deleteConfig.bind(this); + this.handleDeleteConfig = this.handleDeleteConfig.bind(this); + this.closeWarningModal = this.closeWarningModal.bind(this); this.handleSaveConfig = this.handleSaveConfig.bind(this); this.cmdOperation = this.cmdOperation.bind(this); this.handleShowConfirmDelete = this.handleShowConfirmDelete.bind(this); @@ -74,6 +79,7 @@ class AccountPolicy extends React.Component { limitAttrName: "", specAttrName: "", stateAttrName: "", + checkAllStateAttrs: false, _configDN: "", _altStateAttrName: [], _alwaysRecordLogin: false, @@ -81,6 +87,7 @@ class AccountPolicy extends React.Component { _limitAttrName: "", _specAttrName: "", _stateAttrName: "", + _checkAllStateAttrs: false, errorModal: {}, saveBtnDisabledModal: true, modalChecked: false, @@ -94,6 +101,8 @@ class AccountPolicy extends React.Component { isAltStateAttrOpen: false, isLimitAttrOpen: false, showConfirmDelete: false, + showWarningModal: false, + warningMessage: "", }; // Always Record Login Attribute @@ -275,6 +284,7 @@ class AccountPolicy extends React.Component { limitAttrName: "accountInactivityLimit", specAttrName: "acctPolicySubentry", stateAttrName: "lastLoginTime", + checkAllStateAttrs: false, _configDN: "", _altStateAttrName: "createTimestamp", _alwaysRecordLogin: false, @@ -282,6 +292,7 @@ class AccountPolicy extends React.Component { _limitAttrName: "accountInactivityLimit", _specAttrName: "acctPolicySubentry", _stateAttrName: "lastLoginTime", + _checkAllStateAttrs: false, savingModal: false, saveBtnDisabledModal: true, }); @@ -311,7 +322,6 @@ class AccountPolicy extends React.Component { savingModal: false, saveBtnDisabledModal: true, configDN: this.state.configArea, - _configDN: this.state.configArea, altStateAttrName: configEntry.altstateattrname === undefined ? "createTimestamp" @@ -376,18 +386,21 @@ class AccountPolicy extends React.Component { configEntryModalShow: true, newEntry: true, configDN: this.state.configArea, + _configDN: this.state.configArea, altStateAttrName: "createTimestamp", alwaysRecordLogin: false, alwaysRecordLoginAttr: "lastLoginTime", limitAttrName: "accountInactivityLimit", specAttrName: "acctPolicySubentry", stateAttrName: "lastLoginTime", + checkAllStateAttrs: false, _altStateAttrName: "createTimestamp", _alwaysRecordLogin: false, _alwaysRecordLoginAttr: "lastLoginTime", _limitAttrName: "accountInactivityLimit", _specAttrName: "acctPolicySubentry", _stateAttrName: "lastLoginTime", + _checkAllStateAttrs: false, saveBtnDisabledModal: false, // We preset the form so it's ready to save }); }); @@ -406,7 +419,8 @@ class AccountPolicy extends React.Component { alwaysRecordLoginAttr, limitAttrName, specAttrName, - stateAttrName + stateAttrName, + checkAllStateAttrs } = this.state; let cmd = [ @@ -419,7 +433,9 @@ class AccountPolicy extends React.Component { action, configDN, "--always-record-login", - alwaysRecordLogin ? "yes" : "no" + alwaysRecordLogin ? "yes" : "no", + "--check-all-state-attrs", + checkAllStateAttrs ? "yes" : "no", ]; cmd = [...cmd, "--alt-state-attr"]; @@ -524,6 +540,22 @@ class AccountPolicy extends React.Component { }); } + handleDeleteConfig() { + const parentDN = "cn=Account Policy Plugin,cn=plugins,cn=config"; + if (this.state.configDN.toLowerCase().endsWith(parentDN.toLowerCase())) { + this.setState({ + showWarningModal: true, + warningMessage: _("Cannot delete this entry as it is a child of the Account Policy Plugin configuration."), + }); + } else { + this.handleShowConfirmDelete(); + } + } + + closeWarningModal() { + this.setState({ showWarningModal: false }); + } + deleteConfig() { const cmd = [ "dsconf", @@ -569,10 +601,16 @@ class AccountPolicy extends React.Component { handleAddConfig() { this.cmdOperation("add"); + if (!this.state.saveBtnDisabled && !this.state.saving) { + this.handleSaveConfig(); + } } handleEditConfig() { this.cmdOperation("set"); + if (!this.state.saveBtnDisabled && !this.state.saving) { + this.handleSaveConfig(); + } } handleCheckboxChange(checked, e) { @@ -600,7 +638,8 @@ class AccountPolicy extends React.Component { all_good = false; const attrs = [ 'configDN', 'altStateAttrName', 'alwaysRecordLogin', - 'alwaysRecordLoginAttr', 'limitAttrName', 'stateAttrName' + 'alwaysRecordLoginAttr', 'limitAttrName', 'stateAttrName', + 'checkAllStateAttrs', ]; for (const check_attr of attrs) { if (this.state[check_attr] !== this.state['_' + check_attr]) { @@ -659,10 +698,18 @@ class AccountPolicy extends React.Component { if (this.props.rows.length > 0) { const pluginRow = this.props.rows.find(row => row.cn[0] === "Account Policy Plugin"); this.setState({ + configDN: + pluginRow["nsslapd-pluginarg0"] === undefined + ? "" + : pluginRow["nsslapd-pluginarg0"][0], configArea: - pluginRow.nsslapd_pluginconfigarea === undefined + pluginRow["nsslapd-pluginarg0"] === undefined + ? "" + : pluginRow["nsslapd-pluginarg0"][0], + _configArea: + pluginRow["nsslapd-pluginarg0"] === undefined ? "" - : pluginRow.nsslapd_pluginconfigarea[0] + : pluginRow["nsslapd-pluginarg0"][0], }, () => { this.sharedConfigExists() }); } } @@ -699,7 +746,9 @@ class AccountPolicy extends React.Component { _("Successfully updated Account Policy Plugin") ); this.setState({ - saving: false + saving: false, + saveBtnDisabled: true, + _configArea: this.state.configArea }); this.props.pluginListHandler(); }) @@ -730,6 +779,7 @@ class AccountPolicy extends React.Component { limitAttrName, specAttrName, stateAttrName, + checkAllStateAttrs, newEntry, configEntryModalShow, error, @@ -750,7 +800,7 @@ class AccountPolicy extends React.Component { let modalButtons = []; if (!newEntry) { modalButtons = [ - <Button key="del" variant="primary" onClick={this.handleShowConfirmDelete}> + <Button key="del" variant="primary" onClick={this.handleDeleteConfig}> {_("Delete Config")} </Button>, <Button @@ -811,7 +861,7 @@ class AccountPolicy extends React.Component { name="configDN" onChange={(str, e) => { this.handleModalChange(e) }} validated={errorModal.configDN ? ValidatedOptions.error : ValidatedOptions.default} - isDisabled={newEntry} + isDisabled /> <FormHelperText isError isHidden={!errorModal.configDN}> {_("Value must be a valid DN")} @@ -825,7 +875,7 @@ class AccountPolicy extends React.Component { <GridItem span={4}> <Select variant={SelectVariant.typeahead} - typeAheadAriaLabel="Type an attribute name" + typeAheadAriaLabel={_("Type an attribute name")} onToggle={this.handleRecordLoginToggle} onSelect={this.handleRecordLoginSelect} onClear={this.handleRecordLoginClear} @@ -861,7 +911,7 @@ class AccountPolicy extends React.Component { <GridItem span={8}> <Select variant={SelectVariant.typeahead} - typeAheadAriaLabel="Type an attribute name" + typeAheadAriaLabel={_("Type an attribute name")} onToggle={this.handleSpecificAttrToggle} onSelect={this.handleSpecificAttrSelect} onClear={this.handleSpecificAttrClear} @@ -880,14 +930,14 @@ class AccountPolicy extends React.Component { </Select> </GridItem> </Grid> - <Grid title={_("Specifies the primary time attribute used to evaluate an account policy (stateAttrName)")}> + <Grid title={_("Specifies the attribute within the policy to use for the account inactivation limit (limitAttrName)")}> <GridItem span={4} className="ds-label"> {_("Limit Attribute")} </GridItem> <GridItem span={8}> <Select variant={SelectVariant.typeahead} - typeAheadAriaLabel="Type an attribute name" + typeAheadAriaLabel={_("Type an attribute name")} onToggle={this.handleLimitAttrToggle} onSelect={this.handleLimitAttrSelect} onClear={this.handleLimitAttrClear} @@ -913,7 +963,7 @@ class AccountPolicy extends React.Component { <GridItem span={8}> <Select variant={SelectVariant.typeahead} - typeAheadAriaLabel="Type an attribute name" + typeAheadAriaLabel={_("Type an attribute name")} onToggle={this.handleStateAttrToggle} onSelect={this.handleStateAttrSelect} onClear={this.handleStateAttrClear} @@ -922,6 +972,7 @@ class AccountPolicy extends React.Component { aria-labelledby="typeAhead-state-attr" placeholderText={_("Type an attribute name ...")} noResultsFoundText={_("There are no matching entries")} + isCreatable > {this.props.attributes.map((attr, index) => ( <SelectOption @@ -932,14 +983,14 @@ class AccountPolicy extends React.Component { </Select> </GridItem> </Grid> - <Grid title={_("Provides a backup attribute for the server to reference to evaluate the expiration time (altStateAttrName)")}> + <Grid title={_("Provides a backup attribute to evaluate the expiration time if the main state attribute is not present (altStateAttrName)")}> <GridItem span={4} className="ds-label"> {_("Alternative State Attribute")} </GridItem> <GridItem span={8}> <Select variant={SelectVariant.typeahead} - typeAheadAriaLabel="Type an attribute name" + typeAheadAriaLabel={_("Type an attribute name")} onToggle={this.handleAlternativeStateToggle} onSelect={this.handleAlternativeStateSelect} onClear={this.handleAlternativeStateClear} @@ -948,6 +999,7 @@ class AccountPolicy extends React.Component { aria-labelledby="typeAhead-alt-state-attr" placeholderText={_("Type an attribute name ...")} noResultsFoundText={_("There are no matching entries")} + isCreatable > {this.props.attributes.map((attr, index) => ( <SelectOption @@ -958,30 +1010,18 @@ class AccountPolicy extends React.Component { </Select> </GridItem> </Grid> - <Grid title={_("Specifies the attribute within the policy to use for the account inactivation limit (limitAttrName)")}> + <Grid title={_("Check both the 'state attribute', and the 'alternate state attribute' regaredless if the main state attribute is present")}> <GridItem span={4} className="ds-label"> - {_("Limit Attribute")} + {_("Check All State Attributes")} </GridItem> <GridItem span={8}> - <Select - variant={SelectVariant.typeahead} - typeAheadAriaLabel={_("Type an attribute name")} - onToggle={this.handleLimitAttrToggle} - onSelect={this.handleLimitAttrSelect} - onClear={this.handleLimitAttrClear} - selections={limitAttrName} - isOpen={this.state.isLimitAttrOpen} - aria-labelledby="typeAhead-limit-attr" - placeholderText={_("Type an attribute name ...")} - noResultsFoundText={_("There are no matching entries")} - > - {this.props.attributes.map((attr, index) => ( - <SelectOption - key={index} - value={attr} - /> - ))} - </Select> + <Checkbox + id="checkAllStateAttrs" + className="ds-left-margin" + isChecked={checkAllStateAttrs} + onChange={this.handleCheckboxChange} + label={_("Check Both - State and Alternative State Attributes")} + /> </GridItem> </Grid> </Form> @@ -999,7 +1039,7 @@ class AccountPolicy extends React.Component { toggleLoadingHandler={this.props.toggleLoadingHandler} > <Form isHorizontal autoComplete="off"> - <Grid title={_("DN of the shared config entry (nsslapd-pluginConfigArea)")}> + <Grid title={_("DN of the shared config entry (nsslapd-pluginarg0)")}> <GridItem span={3} className="ds-label"> {_("Shared Config Entry")} </GridItem> @@ -1023,7 +1063,7 @@ class AccountPolicy extends React.Component { key="manage" variant="primary" onClick={this.handleOpenModal} - isDisabled={!this.state.sharedConfigExists && saveBtnDisabled} + isDisabled={error.configArea || !configArea} > {this.state.sharedConfigExists ? _("Manage Config") : _("Create Config")} </Button> @@ -1056,6 +1096,12 @@ class AccountPolicy extends React.Component { mSpinningMsg={_("Deleting ...")} mBtnName={_("Delete")} /> + <WarningModal + showModal={this.state.showWarningModal} + closeHandler={this.closeWarningModal} + mTitle={_("Cannot Delete Entry")} + mMsg={this.state.warningMessage} + /> </div> ); } diff --git a/src/lib389/lib389/cli_conf/plugins/accountpolicy.py b/src/lib389/lib389/cli_conf/plugins/accountpolicy.py index 3cf95d337..139c23fdd 100644 --- a/src/lib389/lib389/cli_conf/plugins/accountpolicy.py +++ b/src/lib389/lib389/cli_conf/plugins/accountpolicy.py @@ -12,7 +12,7 @@ from lib389.cli_conf import add_generic_plugin_parsers, generic_object_edit, gen from lib389.cli_base import CustomHelpFormatter arg_to_attr = { - 'config_entry': 'nsslapd_pluginconfigarea' + 'config_entry': 'nsslapd-pluginarg0' } arg_to_attr_config = { @@ -41,8 +41,8 @@ def accountpolicy_add_config(inst, basedn, log, args): raise ValueError("Specified DN is not a valid DN") config = generic_object_add(AccountPolicyConfig, inst, log, args, arg_to_attr_config, dn=targetdn) plugin = AccountPolicyPlugin(inst) - plugin.replace('nsslapd_pluginConfigArea', config.dn) - log.info('Account Policy attribute nsslapd-pluginConfigArea (config_entry) ' + plugin.set('nsslapd-pluginarg0', config.dn) + log.info('Account Policy attribute nsslapd-pluginarg0 (config_entry) ' 'was set in the main plugin config') @@ -112,7 +112,7 @@ def create_parser(subparsers): edit = subcommands.add_parser('set', help='Edit the plugin settings', formatter_class=CustomHelpFormatter) edit.set_defaults(func=accountpolicy_edit) - edit.add_argument('--config-entry', help='Sets the nsslapd-pluginConfigArea attribute') + edit.add_argument('--config-entry', help='Sets the nsslapd-pluginarg0 attribute') config = subcommands.add_parser('config-entry', help='Manage the config entry', formatter_class=CustomHelpFormatter) config_subcommands = config.add_subparsers(help='action')
0
53da4c81903a44d75e8b111ea652f8d97baa623b
389ds/389-ds-base
Bug 691574 - (cov#10573) check return value in GER code We should check the return value of proxyauth_get_dn() in the get effective rights code.
commit 53da4c81903a44d75e8b111ea652f8d97baa623b Author: Nathan Kinder <[email protected]> Date: Mon Mar 28 14:27:48 2011 -0700 Bug 691574 - (cov#10573) check return value in GER code We should check the return value of proxyauth_get_dn() in the get effective rights code. diff --git a/ldap/servers/plugins/acl/acleffectiverights.c b/ldap/servers/plugins/acl/acleffectiverights.c index a8666648b..e30370d34 100644 --- a/ldap/servers/plugins/acl/acleffectiverights.c +++ b/ldap/servers/plugins/acl/acleffectiverights.c @@ -124,8 +124,7 @@ _ger_g_permission_granted ( /* * The requestor may be either the bind dn or a proxy dn */ - proxyauth_get_dn ( pb, &proxydn, &errtext ); - if ( proxydn != NULL ) + if ((proxyauth_get_dn( pb, &proxydn, &errtext ) == LDAP_SUCCESS) && ( proxydn != NULL )) { { requestor_sdn = slapi_sdn_new_dn_passin ( proxydn ); }
0
c6ad848118500991cfbc790a7c16e74179c3ce95
389ds/389-ds-base
Issue 50028 - Add a new CI test case Bug Description: There was a request for having -y option for ds-replcheck. Fix Description: Added a test to Check ds-replcheck works if password file is provided with -y option. Relates: https://pagure.io/389-ds-base/issue/50028 Review by: mhonek
commit c6ad848118500991cfbc790a7c16e74179c3ce95 Author: Akshay Adhikari <[email protected]> Date: Fri Jul 12 12:46:24 2019 +0530 Issue 50028 - Add a new CI test case Bug Description: There was a request for having -y option for ds-replcheck. Fix Description: Added a test to Check ds-replcheck works if password file is provided with -y option. Relates: https://pagure.io/389-ds-base/issue/50028 Review by: mhonek diff --git a/dirsrvtests/tests/suites/ds_tools/replcheck_test.py b/dirsrvtests/tests/suites/ds_tools/replcheck_test.py index 7264a4c7e..010340af0 100644 --- a/dirsrvtests/tests/suites/ds_tools/replcheck_test.py +++ b/dirsrvtests/tests/suites/ds_tools/replcheck_test.py @@ -464,6 +464,38 @@ def test_check_missing_tombstones(topo_tls_ldapi): topo_tls_ldapi.resume_all_replicas() +def test_dsreplcheck_with_password_file(topo_tls_ldapi, tmpdir): + """Check ds-replcheck works if password file is provided + with -y option. + + :id: 0d847ec7-6eaf-4cb5-a9c6-e4a5a1778f93 + :setup: Two master replication + :steps: + 1. Create a password file with the default password of the server. + 2. Run ds-replcheck with -y option (used to pass password file) + :expectedresults: + 1. It should be successful + 2. It should be successful + """ + m1 = topo_tls_ldapi.ms["master1"] + m2 = topo_tls_ldapi.ms["master2"] + + ds_replcheck_path = os.path.join(m1.ds_paths.bin_dir, 'ds-replcheck') + f = tmpdir.mkdir("my_dir").join("password_file.txt") + f.write(PW_DM) + + if ds_is_newer("1.4.1.2"): + tool_cmd = [ds_replcheck_path, 'online', '-b', DEFAULT_SUFFIX, '-D', DN_DM, '-y', f.strpath, + '-m', 'ldaps://{}:{}'.format(m1.host, m1.sslport), + '-r', 'ldaps://{}:{}'.format(m2.host, m2.sslport)] + else: + tool_cmd = [ds_replcheck_path, '-b', DEFAULT_SUFFIX, '-D', DN_DM, '-y', f.strpath, + '-m', 'ldaps://{}:{}'.format(m1.host, m1.sslport), + '-r', 'ldaps://{}:{}'.format(m2.host, m2.sslport)] + + subprocess.Popen(tool_cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding='utf-8') + + if __name__ == '__main__': # Run isolated # -s for DEBUG mode
0
088aa353564048e5a5b8b21ffba2f8f2982f86e0
389ds/389-ds-base
use slapi_entry_attr_get_bool instead of slapi_entry_attr_get_int for the fallback and secure config attrs
commit 088aa353564048e5a5b8b21ffba2f8f2982f86e0 Author: Rich Megginson <[email protected]> Date: Thu May 25 14:37:14 2006 +0000 use slapi_entry_attr_get_bool instead of slapi_entry_attr_get_int for the fallback and secure config attrs diff --git a/ldap/servers/plugins/pam_passthru/pam_ptconfig.c b/ldap/servers/plugins/pam_passthru/pam_ptconfig.c index ed2d0e1cd..4bdcf342a 100644 --- a/ldap/servers/plugins/pam_passthru/pam_ptconfig.c +++ b/ldap/servers/plugins/pam_passthru/pam_ptconfig.c @@ -448,8 +448,8 @@ pam_passthru_apply_config (Slapi_PBlock *pb, Slapi_Entry* entryBefore, Slapi_Ent char *new_service = NULL; char *pam_ident_attr = NULL; char *map_method = NULL; - int fallback; - int secure; + PRBool fallback; + PRBool secure; *returncode = LDAP_SUCCESS; @@ -458,8 +458,8 @@ pam_passthru_apply_config (Slapi_PBlock *pb, Slapi_Entry* entryBefore, Slapi_Ent new_service = slapi_entry_attr_get_charptr(e, PAMPT_SERVICE_ATTR); excludes = slapi_entry_attr_get_charray(e, PAMPT_EXCLUDES_ATTR); includes = slapi_entry_attr_get_charray(e, PAMPT_INCLUDES_ATTR); - fallback = slapi_entry_attr_get_int(e, PAMPT_FALLBACK_ATTR); - secure = slapi_entry_attr_get_int(e, PAMPT_SECURE_ATTR); + fallback = slapi_entry_attr_get_bool(e, PAMPT_FALLBACK_ATTR); + secure = slapi_entry_attr_get_bool(e, PAMPT_SECURE_ATTR); /* lock config here */ slapi_lock_mutex(theConfig.lock);
0
d1946d8f5c1e2f318587c06ecd4016f9b9027783
389ds/389-ds-base
610281 - fix coverity Defect Type: Control flow issues https://bugzilla.redhat.com/show_bug.cgi?id=610281 11817 DEADCODE Triaged Unassigned Bug Moderate Fix Required NSUniqueAttr_Init() ds/ldap/servers/plugins/uiduniq/uid.c Comment: NSUniqueAttr_Init declared err twice. One at the top and another in BEGIN - END (do - while loop). The second err in the do - while loop is trashed when it gets out of the loop. Regardless of the result in the do - while loop, err = 0 (success) was returned to the caller. We are removing the second err in the BEGIN (== do - while) scope. 945 int err;
commit d1946d8f5c1e2f318587c06ecd4016f9b9027783 Author: Noriko Hosoi <[email protected]> Date: Fri Jul 2 17:46:13 2010 -0700 610281 - fix coverity Defect Type: Control flow issues https://bugzilla.redhat.com/show_bug.cgi?id=610281 11817 DEADCODE Triaged Unassigned Bug Moderate Fix Required NSUniqueAttr_Init() ds/ldap/servers/plugins/uiduniq/uid.c Comment: NSUniqueAttr_Init declared err twice. One at the top and another in BEGIN - END (do - while loop). The second err in the do - while loop is trashed when it gets out of the loop. Regardless of the result in the do - while loop, err = 0 (success) was returned to the caller. We are removing the second err in the BEGIN (== do - while) scope. 945 int err; diff --git a/ldap/servers/plugins/uiduniq/uid.c b/ldap/servers/plugins/uiduniq/uid.c index 64b5b1448..de7310fe2 100644 --- a/ldap/servers/plugins/uiduniq/uid.c +++ b/ldap/servers/plugins/uiduniq/uid.c @@ -942,7 +942,6 @@ NSUniqueAttr_Init(Slapi_PBlock *pb) int err = 0; BEGIN - int err; int argc; char **argv;
0
75f917e168ecfb204a92662579dac32ce959898b
389ds/389-ds-base
Resolves: bug 288451 Description: Show-Stopper - Migration from HP-PARISC DS 6.21 to DS80 on HP-Itaninum Fix Description: Cannot start servers until after the data and config has been migrated.
commit 75f917e168ecfb204a92662579dac32ce959898b Author: Rich Megginson <[email protected]> Date: Fri Sep 14 16:26:17 2007 +0000 Resolves: bug 288451 Description: Show-Stopper - Migration from HP-PARISC DS 6.21 to DS80 on HP-Itaninum Fix Description: Cannot start servers until after the data and config has been migrated. diff --git a/ldap/admin/src/scripts/DSMigration.pm.in b/ldap/admin/src/scripts/DSMigration.pm.in index fd8ac04dd..089f41212 100644 --- a/ldap/admin/src/scripts/DSMigration.pm.in +++ b/ldap/admin/src/scripts/DSMigration.pm.in @@ -743,9 +743,9 @@ sub migrateDS { return 0; } - if (!$mig->{start_servers}) { - $inf->{slapd}->{start_server} = 0; - } + # create servers but do not start them until after databases + # have been migrated + $inf->{slapd}->{start_server} = 0; # create the new instance @errs = createDSInstance($inf); @@ -768,6 +768,15 @@ sub migrateDS { $mig->msg(@errs); return 0; } + + # finally, start the server + if ($mig->{start_servers}) { + $inf->{slapd}->{start_server} = 1; + if (@errs = DSCreate::startServer($inf)) { + $mig->msg(@errs); + return 0; + } + } } return 1;
0
3bf0ca3253f3cefff70cc9f3e1ecb70978fb506b
389ds/389-ds-base
Resolves: #316281 Summary: db2bak fails if the archive path exists and ends with '/' (Comment #8) Description: Changed the condition to normalize the path: if '.' or '/' is included in the path, normalize it.
commit 3bf0ca3253f3cefff70cc9f3e1ecb70978fb506b Author: Noriko Hosoi <[email protected]> Date: Fri Nov 30 17:23:13 2007 +0000 Resolves: #316281 Summary: db2bak fails if the archive path exists and ends with '/' (Comment #8) Description: Changed the condition to normalize the path: if '.' or '/' is included in the path, normalize it. diff --git a/ldap/servers/slapd/util.c b/ldap/servers/slapd/util.c index aaf5e0614..e51c66855 100644 --- a/ldap/servers/slapd/util.c +++ b/ldap/servers/slapd/util.c @@ -529,8 +529,8 @@ rel2abspath_ext( char *relpath, char *cwd ) } } retpath = slapi_ch_strdup(abspath); - /* if there's no '.', no need to call normalize_path */ - if (NULL != strchr(abspath, '.') || NULL != strstr(abspath, _PSEP2)) + /* if there's no '.' or separators, no need to call normalize_path */ + if (NULL != strchr(abspath, '.') || NULL != strstr(abspath, _PSEP)) { char **norm_path = normalize_path(abspath); char **np, *rp;
0
33279b75e84e01f89aa8bfc2d3707d3a53d3218d
389ds/389-ds-base
Issue 4410 RFE - ndn cache with arc in rust Bug Description: As we move to LMDB and require a concurrently readable model, we need access to concurrently readable datastructures. Fix Description: This is a poc of NDN cache in rust with a concurrently readable adaptive replacement cache. fixes: #4410 Author: William Brown <[email protected]> Review by: ???
commit 33279b75e84e01f89aa8bfc2d3707d3a53d3218d Author: William Brown <[email protected]> Date: Fri May 15 11:59:33 2020 +1000 Issue 4410 RFE - ndn cache with arc in rust Bug Description: As we move to LMDB and require a concurrently readable model, we need access to concurrently readable datastructures. Fix Description: This is a poc of NDN cache in rust with a concurrently readable adaptive replacement cache. fixes: #4410 Author: William Brown <[email protected]> Review by: ??? diff --git a/Makefile.am b/Makefile.am index a8f3de442..91b5ea661 100644 --- a/Makefile.am +++ b/Makefile.am @@ -913,6 +913,7 @@ RSLAPD_LIB = @abs_top_builddir@/rs/@rust_target_dir@/librslapd.a librslapd_la_SOURCES = \ src/librslapd/Cargo.toml \ src/librslapd/build.rs \ + src/librslapd/src/cache.rs \ src/librslapd/src/lib.rs librslapd_la_EXTRA = src/librslapd/Cargo.lock diff --git a/ldap/servers/slapd/dn.c b/ldap/servers/slapd/dn.c index 8a2b5d28c..c84588a19 100644 --- a/ldap/servers/slapd/dn.c +++ b/ldap/servers/slapd/dn.c @@ -22,8 +22,12 @@ #include "slap.h" #include <plhash.h> +#ifdef RUST_ENABLE +#include <rust-slapi-private.h> +#else /* For the ndn cache - this gives up siphash13 */ #include <sds.h> +#endif #undef SDN_DEBUG @@ -46,6 +50,7 @@ struct ndn_cache_stats { uint64_t slots; }; +#ifndef RUST_ENABLE struct ndn_cache_value { uint64_t size; uint64_t slot; @@ -55,6 +60,7 @@ struct ndn_cache_value { struct ndn_cache_value *prev; struct ndn_cache_value *child; }; +#endif /* * This uses a similar alloc trick to IDList to keep @@ -64,7 +70,9 @@ struct ndn_cache { /* * We keep per thread stats and flush them occasionally */ - uint64_t max_size; +#ifdef RUST_ENABLE + ARCacheChar *cache; +#else /* Need to track this because we need to provide diffs to counter */ uint64_t last_count; uint64_t count; @@ -78,6 +86,8 @@ struct ndn_cache { uint64_t last_size; uint64_t size; uint64_t slots; + /* The per-thread max size */ + uint64_t max_size; /* * This is used by siphash to prevent hash bucket attacks */ @@ -86,6 +96,7 @@ struct ndn_cache { struct ndn_cache_value *head; struct ndn_cache_value *tail; struct ndn_cache_value *table[1]; +#endif }; /* @@ -2880,9 +2891,12 @@ slapi_sdn_get_size(const Slapi_DN *sdn) * */ + +#ifndef RUST_ENABLE static pthread_key_t ndn_cache_key; static pthread_once_t ndn_cache_key_once = PTHREAD_ONCE_INIT; static struct ndn_cache_stats t_cache_stats = {0}; +#endif /* * WARNING: For some reason we try to use the NDN cache *before* * we have a chance to configure it. As a result, we need to rely @@ -2894,18 +2908,27 @@ static struct ndn_cache_stats t_cache_stats = {0}; * not bother until we improve libglobs to be COW. */ static int32_t ndn_enabled = 0; +#ifdef RUST_ENABLE +static ARCacheChar *cache = NULL; +#endif static struct ndn_cache * ndn_thread_cache_create(size_t thread_max_size, size_t slots) { size_t t_cache_size = sizeof(struct ndn_cache) + (slots * sizeof(struct ndn_cache_value *)); struct ndn_cache *t_cache = (struct ndn_cache *)slapi_ch_calloc(1, t_cache_size); +#ifdef RUST_ENABLE + t_cache->cache = cache; +#else t_cache->max_size = thread_max_size; t_cache->slots = slots; +#endif return t_cache; } +#ifdef RUST_ENABLE +#else static void ndn_thread_cache_commit_status(struct ndn_cache *t_cache) { /* @@ -2921,6 +2944,7 @@ ndn_thread_cache_commit_status(struct ndn_cache *t_cache) { t_cache->tries = 0; t_cache->evicts = 0; /* Count and size need diff */ + // Get the size from the main cache. int64_t diff = (t_cache->size - t_cache->last_size); if (diff > 0) { // We have more .... @@ -2941,7 +2965,9 @@ ndn_thread_cache_commit_status(struct ndn_cache *t_cache) { } } +#endif +#ifndef RUST_ENABLE static void ndn_thread_cache_value_destroy(struct ndn_cache *t_cache, struct ndn_cache_value *v) { /* Update stats */ @@ -2982,10 +3008,12 @@ ndn_thread_cache_value_destroy(struct ndn_cache *t_cache, struct ndn_cache_value slapi_ch_free((void **)&(v->ndn)); slapi_ch_free((void **)&v); } +#endif static void ndn_thread_cache_destroy(void *v_cache) { struct ndn_cache *t_cache = (struct ndn_cache *)v_cache; +#ifndef RUST_ENABLE /* * FREE ALL THE NODES!!! */ @@ -2996,9 +3024,11 @@ ndn_thread_cache_destroy(void *v_cache) { ndn_thread_cache_value_destroy(t_cache, node); node = next_node; } +#endif slapi_ch_free((void **)&t_cache); } +#ifndef RUST_ENABLE static void ndn_cache_key_init() { if (pthread_key_create(&ndn_cache_key, ndn_thread_cache_destroy) != 0) { @@ -3006,6 +3036,7 @@ ndn_cache_key_init() { slapi_log_err(SLAPI_LOG_ERR, "ndn_cache_init", "Failed to create pthread key, aborting.\n"); } } +#endif int32_t ndn_cache_init() @@ -3020,16 +3051,22 @@ ndn_cache_init() return 0; } +#ifdef RUST_ENABLE + uint64_t max_size = config_get_ndn_cache_size(); + if (max_size < NDN_CACHE_MINIMUM_CAPACITY) { + max_size = NDN_CACHE_MINIMUM_CAPACITY; + } + uintptr_t max_estimate = max_size / NDN_ENTRY_AVG_SIZE; + /* + * Since we currently only do one op per read, we set 0 because there + * is no value in having the read thread cache. + */ + uintptr_t max_thread_read = 0; + /* Setup the main cache which all other caches will inherit. */ + cache = cache_char_create(max_estimate, max_thread_read); +#else /* Create the pthread key */ (void)pthread_once(&ndn_cache_key_once, ndn_cache_key_init); - - /* Create the global stats. */ - t_cache_stats.max_size = config_get_ndn_cache_size(); - t_cache_stats.cache_evicts = slapi_counter_new(); - t_cache_stats.cache_tries = slapi_counter_new(); - t_cache_stats.cache_hits = slapi_counter_new(); - t_cache_stats.cache_count = slapi_counter_new(); - t_cache_stats.cache_size = slapi_counter_new(); /* Get thread numbers and calc the per thread size */ int32_t maxthreads = (int32_t)config_get_threadnumber(); size_t tentative_size = t_cache_stats.max_size / maxthreads; @@ -3057,6 +3094,14 @@ ndn_cache_init() * So now we can use this to make the slot count. */ t_cache_stats.slots = 1 << shifts; + /* Create the global stats. */ + t_cache_stats.max_size = config_get_ndn_cache_size(); + t_cache_stats.cache_evicts = slapi_counter_new(); + t_cache_stats.cache_tries = slapi_counter_new(); + t_cache_stats.cache_hits = slapi_counter_new(); + t_cache_stats.cache_count = slapi_counter_new(); + t_cache_stats.cache_size = slapi_counter_new(); +#endif /* Done? */ return 0; } @@ -3067,11 +3112,15 @@ ndn_cache_destroy() if (ndn_enabled == 0) { return; } +#ifdef RUST_ENABLE + cache_char_free(cache); +#else slapi_counter_destroy(&(t_cache_stats.cache_tries)); slapi_counter_destroy(&(t_cache_stats.cache_hits)); slapi_counter_destroy(&(t_cache_stats.cache_count)); slapi_counter_destroy(&(t_cache_stats.cache_size)); slapi_counter_destroy(&(t_cache_stats.cache_evicts)); +#endif } int @@ -3083,6 +3132,67 @@ ndn_cache_started() /* * Look up this dn in the ndn cache */ +#ifdef RUST_ENABLE +/* This is the rust version of the ndn cache */ + +static int32_t +ndn_cache_lookup(char *dn, size_t dn_len, char **ndn, char **udn, int32_t *rc) +{ + if (ndn_enabled == 0 || NULL == udn) { + return 0; + } + *udn = NULL; + + if (dn_len == 0) { + *ndn = dn; + *rc = 0; + return 1; + } + + /* Look for it */ + ARCacheCharRead *read_txn = cache_char_read_begin(cache); + PR_ASSERT(read_txn); + + const char *cache_ndn = cache_char_read_get(read_txn, dn); + if (cache_ndn != NULL) { + *ndn = slapi_ch_strdup(cache_ndn); + /* + * We have to complete the read after the strdup else it's + * not safe to access the pointer. + */ + cache_char_read_complete(read_txn); + *rc = 1; + return 1; + } else { + cache_char_read_complete(read_txn); + /* If we miss, we need to duplicate dn to udn here. */ + *udn = slapi_ch_strdup(dn); + *rc = 0; + return 0; + } +} + +static void +ndn_cache_add(char *dn, size_t dn_len, char *ndn, size_t ndn_len) +{ + if (ndn_enabled == 0) { + return; + } + if (dn_len == 0) { + return; + } + if (strlen(ndn) > ndn_len) { + /* we need to null terminate the ndn */ + *(ndn + ndn_len) = '\0'; + } + + ARCacheCharRead *read_txn = cache_char_read_begin(cache); + PR_ASSERT(read_txn); + cache_char_read_include(read_txn, dn, ndn); + cache_char_read_complete(read_txn); +} + +#else static int ndn_cache_lookup(char *dn, size_t dn_len, char **ndn, char **udn, int *rc) { @@ -3264,11 +3374,52 @@ ndn_cache_add(char *dn, size_t dn_len, char *ndn, size_t ndn_len) t_cache->count++; } +#endif +/* end rust_enable */ /* stats for monitor */ void ndn_cache_get_stats(uint64_t *hits, uint64_t *tries, uint64_t *size, uint64_t *max_size, uint64_t *thread_size, uint64_t *evicts, uint64_t *slots, uint64_t *count) { +#ifdef RUST_ENABLE + /* + * A pretty big note here - the ARCache stores things by slot, not size, because + * getting the real byte size is expensive in some cases (that are beyond this + * project). Additionally, due to the concurrent nature of this, the size is + * not really accurate to begin with anyway, but you know, this is a best + * effort for stats for the user to see. + */ + uint64_t reader_hits; + uint64_t reader_includes; + uint64_t write_hits; + uint64_t write_inc_or_mod; + uint64_t freq; + uint64_t recent; + uint64_t freq_evicts; + uint64_t recent_evicts; + uint64_t p_weight; + cache_char_stats(cache, + &reader_hits, + &reader_includes, + &write_hits, + &write_inc_or_mod, + max_size, + &freq, + &recent, + &freq_evicts, + &recent_evicts, + &p_weight, + slots + ); + /* ARCache stores by key count not size, so we recombine with the avg entry size */ + *max_size = *max_size * NDN_ENTRY_AVG_SIZE; + *thread_size = 0; + *evicts = freq_evicts + recent_evicts; + *hits = write_hits + reader_hits; + *tries = *hits + reader_includes + write_inc_or_mod; + *size = (freq + recent) * NDN_ENTRY_AVG_SIZE; + *count = (freq + recent); +#else *max_size = t_cache_stats.max_size; *thread_size = t_cache_stats.thread_max_size; *slots = t_cache_stats.slots; @@ -3277,6 +3428,7 @@ ndn_cache_get_stats(uint64_t *hits, uint64_t *tries, uint64_t *size, uint64_t *m *tries = slapi_counter_get_value(t_cache_stats.cache_tries); *size = slapi_counter_get_value(t_cache_stats.cache_size); *count = slapi_counter_get_value(t_cache_stats.cache_count); +#endif } /* Common ancestor sdn is allocated. diff --git a/src/Cargo.lock b/src/Cargo.lock index f571954e7..0fcd783a0 100644 --- a/src/Cargo.lock +++ b/src/Cargo.lock @@ -1,11 +1,19 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. +[[package]] +name = "ahash" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "const-random 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "ansi_term" version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -13,14 +21,14 @@ name = "atty" version = "0.2.14" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "hermit-abi 0.1.13 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.71 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", + "hermit-abi 0.1.17 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.80 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "autocfg" -version = "1.0.0" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] @@ -46,20 +54,20 @@ name = "cbindgen" version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "clap 2.33.1 (registry+https://github.com/rust-lang/crates.io-index)", - "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", - "proc-macro2 1.0.18 (registry+https://github.com/rust-lang/crates.io-index)", - "quote 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.111 (registry+https://github.com/rust-lang/crates.io-index)", - "serde_json 1.0.53 (registry+https://github.com/rust-lang/crates.io-index)", - "syn 1.0.30 (registry+https://github.com/rust-lang/crates.io-index)", + "clap 2.33.3 (registry+https://github.com/rust-lang/crates.io-index)", + "log 0.4.11 (registry+https://github.com/rust-lang/crates.io-index)", + "proc-macro2 1.0.24 (registry+https://github.com/rust-lang/crates.io-index)", + "quote 1.0.7 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.117 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_json 1.0.59 (registry+https://github.com/rust-lang/crates.io-index)", + "syn 1.0.48 (registry+https://github.com/rust-lang/crates.io-index)", "tempfile 3.1.0 (registry+https://github.com/rust-lang/crates.io-index)", - "toml 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)", + "toml 0.5.7 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "cc" -version = "1.0.54" +version = "1.0.62" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "jobserver 0.1.21 (registry+https://github.com/rust-lang/crates.io-index)", @@ -70,9 +78,14 @@ name = "cfg-if" version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + [[package]] name = "clap" -version = "2.33.1" +version = "2.33.3" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "ansi_term 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -80,17 +93,124 @@ dependencies = [ "bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", "strsim 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", "textwrap 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", - "unicode-width 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", + "unicode-width 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", "vec_map 0.8.2 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "cloudabi" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "concread" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "ahash 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", + "crossbeam 0.7.3 (registry+https://github.com/rust-lang/crates.io-index)", + "crossbeam-epoch 0.8.2 (registry+https://github.com/rust-lang/crates.io-index)", + "crossbeam-utils 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)", + "num 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", + "parking_lot 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", + "rand 0.7.3 (registry+https://github.com/rust-lang/crates.io-index)", + "smallvec 1.4.2 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "const-random" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "const-random-macro 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)", + "proc-macro-hack 0.5.19 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "const-random-macro" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "getrandom 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", + "proc-macro-hack 0.5.19 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "crossbeam" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", + "crossbeam-channel 0.4.4 (registry+https://github.com/rust-lang/crates.io-index)", + "crossbeam-deque 0.7.3 (registry+https://github.com/rust-lang/crates.io-index)", + "crossbeam-epoch 0.8.2 (registry+https://github.com/rust-lang/crates.io-index)", + "crossbeam-queue 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", + "crossbeam-utils 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "crossbeam-channel" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "crossbeam-utils 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)", + "maybe-uninit 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "crossbeam-deque" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "crossbeam-epoch 0.8.2 (registry+https://github.com/rust-lang/crates.io-index)", + "crossbeam-utils 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)", + "maybe-uninit 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "autocfg 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", + "crossbeam-utils 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)", + "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "maybe-uninit 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "memoffset 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)", + "scopeguard 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "crossbeam-queue" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", + "crossbeam-utils 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)", + "maybe-uninit 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "crossbeam-utils" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "autocfg 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", + "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "entryuuid" version = "0.1.0" dependencies = [ - "cc 1.0.54 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.71 (registry+https://github.com/rust-lang/crates.io-index)", - "paste 0.1.15 (registry+https://github.com/rust-lang/crates.io-index)", + "cc 1.0.62 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.80 (registry+https://github.com/rust-lang/crates.io-index)", + "paste 0.1.18 (registry+https://github.com/rust-lang/crates.io-index)", "slapi_r_plugin 0.1.0", "uuid 0.8.1 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -99,9 +219,9 @@ dependencies = [ name = "entryuuid_syntax" version = "0.1.0" dependencies = [ - "cc 1.0.54 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.71 (registry+https://github.com/rust-lang/crates.io-index)", - "paste 0.1.15 (registry+https://github.com/rust-lang/crates.io-index)", + "cc 1.0.62 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.80 (registry+https://github.com/rust-lang/crates.io-index)", + "paste 0.1.18 (registry+https://github.com/rust-lang/crates.io-index)", "slapi_r_plugin 0.1.0", "uuid 0.8.1 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -113,8 +233,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "base64 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)", "byteorder 1.3.4 (registry+https://github.com/rust-lang/crates.io-index)", - "getrandom 0.1.14 (registry+https://github.com/rust-lang/crates.io-index)", - "openssl 0.10.29 (registry+https://github.com/rust-lang/crates.io-index)", + "getrandom 0.1.15 (registry+https://github.com/rust-lang/crates.io-index)", + "openssl 0.10.30 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -132,25 +252,43 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "getrandom" -version = "0.1.14" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.80 (registry+https://github.com/rust-lang/crates.io-index)", + "wasi 0.9.0+wasi-snapshot-preview1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "getrandom" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.71 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.80 (registry+https://github.com/rust-lang/crates.io-index)", "wasi 0.9.0+wasi-snapshot-preview1 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "hermit-abi" -version = "0.1.13" +version = "0.1.17" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "libc 0.2.71 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.80 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "instant" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cfg-if 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "itoa" -version = "0.4.5" +version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] @@ -158,7 +296,7 @@ name = "jobserver" version = "0.1.21" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "libc 0.2.71 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.80 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -168,7 +306,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "libc" -version = "0.2.71" +version = "0.2.80" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] @@ -176,7 +314,7 @@ name = "librnsslapd" version = "0.1.0" dependencies = [ "cbindgen 0.9.1 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.71 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.80 (registry+https://github.com/rust-lang/crates.io-index)", "slapd 0.1.0", ] @@ -185,92 +323,204 @@ name = "librslapd" version = "0.1.0" dependencies = [ "cbindgen 0.9.1 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.71 (registry+https://github.com/rust-lang/crates.io-index)", + "concread 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.80 (registry+https://github.com/rust-lang/crates.io-index)", "slapd 0.1.0", ] +[[package]] +name = "lock_api" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "scopeguard 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "log" -version = "0.4.8" +version = "0.4.11" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "maybe-uninit" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "memoffset" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "autocfg 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "num" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "num-bigint 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", + "num-complex 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", + "num-integer 0.1.44 (registry+https://github.com/rust-lang/crates.io-index)", + "num-iter 0.1.42 (registry+https://github.com/rust-lang/crates.io-index)", + "num-rational 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)", + "num-traits 0.2.14 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "num-bigint" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "autocfg 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "num-integer 0.1.44 (registry+https://github.com/rust-lang/crates.io-index)", + "num-traits 0.2.14 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "num-complex" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "num-traits 0.2.14 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "num-integer" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "autocfg 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "num-traits 0.2.14 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "num-iter" +version = "0.1.42" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "autocfg 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "num-integer 0.1.44 (registry+https://github.com/rust-lang/crates.io-index)", + "num-traits 0.2.14 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "num-rational" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "autocfg 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "num-bigint 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", + "num-integer 0.1.44 (registry+https://github.com/rust-lang/crates.io-index)", + "num-traits 0.2.14 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "num-traits" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "autocfg 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "openssl" -version = "0.10.29" +version = "0.10.30" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", "foreign-types 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)", "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.71 (registry+https://github.com/rust-lang/crates.io-index)", - "openssl-sys 0.9.57 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.80 (registry+https://github.com/rust-lang/crates.io-index)", + "openssl-sys 0.9.58 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "openssl-sys" -version = "0.9.57" +version = "0.9.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "autocfg 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "cc 1.0.62 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.80 (registry+https://github.com/rust-lang/crates.io-index)", + "pkg-config 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)", + "vcpkg 0.2.10 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "parking_lot" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "instant 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", + "lock_api 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)", + "parking_lot_core 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "parking_lot_core" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "autocfg 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", - "cc 1.0.54 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.71 (registry+https://github.com/rust-lang/crates.io-index)", - "pkg-config 0.3.17 (registry+https://github.com/rust-lang/crates.io-index)", - "vcpkg 0.2.9 (registry+https://github.com/rust-lang/crates.io-index)", + "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", + "cloudabi 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "instant 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.80 (registry+https://github.com/rust-lang/crates.io-index)", + "redox_syscall 0.1.57 (registry+https://github.com/rust-lang/crates.io-index)", + "smallvec 1.4.2 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "paste" -version = "0.1.15" +version = "0.1.18" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "paste-impl 0.1.15 (registry+https://github.com/rust-lang/crates.io-index)", - "proc-macro-hack 0.5.16 (registry+https://github.com/rust-lang/crates.io-index)", + "paste-impl 0.1.18 (registry+https://github.com/rust-lang/crates.io-index)", + "proc-macro-hack 0.5.19 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "paste-impl" -version = "0.1.15" +version = "0.1.18" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "proc-macro-hack 0.5.16 (registry+https://github.com/rust-lang/crates.io-index)", - "proc-macro2 1.0.18 (registry+https://github.com/rust-lang/crates.io-index)", - "quote 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)", - "syn 1.0.30 (registry+https://github.com/rust-lang/crates.io-index)", + "proc-macro-hack 0.5.19 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "pkg-config" -version = "0.3.17" +version = "0.3.19" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "ppv-lite86" -version = "0.2.8" +version = "0.2.10" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "proc-macro-hack" -version = "0.5.16" +version = "0.5.19" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "proc-macro2" -version = "1.0.18" +version = "1.0.24" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", + "unicode-xid 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "quote" -version = "1.0.6" +version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "proc-macro2 1.0.18 (registry+https://github.com/rust-lang/crates.io-index)", + "proc-macro2 1.0.24 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -278,8 +528,8 @@ name = "rand" version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "getrandom 0.1.14 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.71 (registry+https://github.com/rust-lang/crates.io-index)", + "getrandom 0.1.15 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.80 (registry+https://github.com/rust-lang/crates.io-index)", "rand_chacha 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", "rand_core 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", "rand_hc 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -290,7 +540,7 @@ name = "rand_chacha" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "ppv-lite86 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", + "ppv-lite86 0.2.10 (registry+https://github.com/rust-lang/crates.io-index)", "rand_core 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -299,7 +549,7 @@ name = "rand_core" version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "getrandom 0.1.14 (registry+https://github.com/rust-lang/crates.io-index)", + "getrandom 0.1.15 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -312,15 +562,15 @@ dependencies = [ [[package]] name = "redox_syscall" -version = "0.1.56" +version = "0.1.57" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "remove_dir_all" -version = "0.5.2" +version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -332,32 +582,37 @@ name = "ryu" version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" +[[package]] +name = "scopeguard" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + [[package]] name = "serde" -version = "1.0.111" +version = "1.0.117" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "serde_derive 1.0.111 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_derive 1.0.117 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "serde_derive" -version = "1.0.111" +version = "1.0.117" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "proc-macro2 1.0.18 (registry+https://github.com/rust-lang/crates.io-index)", - "quote 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)", - "syn 1.0.30 (registry+https://github.com/rust-lang/crates.io-index)", + "proc-macro2 1.0.24 (registry+https://github.com/rust-lang/crates.io-index)", + "quote 1.0.7 (registry+https://github.com/rust-lang/crates.io-index)", + "syn 1.0.48 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "serde_json" -version = "1.0.53" +version = "1.0.59" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "itoa 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", + "itoa 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", "ryu 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.111 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.117 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -372,11 +627,16 @@ name = "slapi_r_plugin" version = "0.1.0" dependencies = [ "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.71 (registry+https://github.com/rust-lang/crates.io-index)", - "paste 0.1.15 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.80 (registry+https://github.com/rust-lang/crates.io-index)", + "paste 0.1.18 (registry+https://github.com/rust-lang/crates.io-index)", "uuid 0.8.1 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "smallvec" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" + [[package]] name = "strsim" version = "0.8.0" @@ -384,12 +644,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "syn" -version = "1.0.30" +version = "1.0.48" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "proc-macro2 1.0.18 (registry+https://github.com/rust-lang/crates.io-index)", - "quote 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)", - "unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", + "proc-macro2 1.0.24 (registry+https://github.com/rust-lang/crates.io-index)", + "quote 1.0.7 (registry+https://github.com/rust-lang/crates.io-index)", + "unicode-xid 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -398,11 +658,11 @@ version = "3.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.71 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.80 (registry+https://github.com/rust-lang/crates.io-index)", "rand 0.7.3 (registry+https://github.com/rust-lang/crates.io-index)", - "redox_syscall 0.1.56 (registry+https://github.com/rust-lang/crates.io-index)", - "remove_dir_all 0.5.2 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", + "redox_syscall 0.1.57 (registry+https://github.com/rust-lang/crates.io-index)", + "remove_dir_all 0.5.3 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -410,25 +670,25 @@ name = "textwrap" version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "unicode-width 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", + "unicode-width 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "toml" -version = "0.5.6" +version = "0.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "serde 1.0.111 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.117 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "unicode-width" -version = "0.1.7" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "unicode-xid" -version = "0.2.0" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] @@ -441,7 +701,7 @@ dependencies = [ [[package]] name = "vcpkg" -version = "0.2.9" +version = "0.2.10" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] @@ -456,7 +716,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "winapi" -version = "0.3.8" +version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -474,56 +734,84 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" [metadata] +"checksum ahash 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)" = "f6789e291be47ace86a60303502173d84af8327e3627ecf334356ee0f87a164c" "checksum ansi_term 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ee49baf6cb617b853aa8d93bf420db2383fab46d314482ca2803b40d5fde979b" "checksum atty 0.2.14 (registry+https://github.com/rust-lang/crates.io-index)" = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" -"checksum autocfg 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "f8aac770f1885fd7e387acedd76065302551364496e46b3dd00860b2f8359b9d" +"checksum autocfg 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a" "checksum base64 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)" = "0b25d992356d2eb0ed82172f5248873db5560c4721f564b13cb5193bda5e668e" "checksum bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693" "checksum byteorder 1.3.4 (registry+https://github.com/rust-lang/crates.io-index)" = "08c48aae112d48ed9f069b33538ea9e3e90aa263cfa3d1c24309612b1f7472de" "checksum cbindgen 0.9.1 (registry+https://github.com/rust-lang/crates.io-index)" = "9daec6140ab4dcd38c3dd57e580b59a621172a526ac79f1527af760a55afeafd" -"checksum cc 1.0.54 (registry+https://github.com/rust-lang/crates.io-index)" = "7bbb73db36c1246e9034e307d0fba23f9a2e251faa47ade70c1bd252220c8311" +"checksum cc 1.0.62 (registry+https://github.com/rust-lang/crates.io-index)" = "f1770ced377336a88a67c473594ccc14eca6f4559217c34f64aac8f83d641b40" "checksum cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)" = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" -"checksum clap 2.33.1 (registry+https://github.com/rust-lang/crates.io-index)" = "bdfa80d47f954d53a35a64987ca1422f495b8d6483c0fe9f7117b36c2a792129" +"checksum cfg-if 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" +"checksum clap 2.33.3 (registry+https://github.com/rust-lang/crates.io-index)" = "37e58ac78573c40708d45522f0d80fa2f01cc4f9b4e2bf749807255454312002" +"checksum cloudabi 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "4344512281c643ae7638bbabc3af17a11307803ec8f0fcad9fae512a8bf36467" +"checksum concread 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)" = "d2242b1bac936b6a156d2056e3d98d2424d044dbf7bbdaa856c4e6d629cc5aa5" +"checksum const-random 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)" = "02dc82c12dc2ee6e1ded861cf7d582b46f66f796d1b6c93fa28b911ead95da02" +"checksum const-random-macro 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)" = "fc757bbb9544aa296c2ae00c679e81f886b37e28e59097defe0cf524306f6685" +"checksum crossbeam 0.7.3 (registry+https://github.com/rust-lang/crates.io-index)" = "69323bff1fb41c635347b8ead484a5ca6c3f11914d784170b158d8449ab07f8e" +"checksum crossbeam-channel 0.4.4 (registry+https://github.com/rust-lang/crates.io-index)" = "b153fe7cbef478c567df0f972e02e6d736db11affe43dfc9c56a9374d1adfb87" +"checksum crossbeam-deque 0.7.3 (registry+https://github.com/rust-lang/crates.io-index)" = "9f02af974daeee82218205558e51ec8768b48cf524bd01d550abe5573a608285" +"checksum crossbeam-epoch 0.8.2 (registry+https://github.com/rust-lang/crates.io-index)" = "058ed274caafc1f60c4997b5fc07bf7dc7cca454af7c6e81edffe5f33f70dace" +"checksum crossbeam-queue 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "774ba60a54c213d409d5353bda12d49cd68d14e45036a285234c8d6f91f92570" +"checksum crossbeam-utils 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)" = "c3c7c73a2d1e9fc0886a08b93e98eb643461230d5f1925e4036204d5f2e261a8" "checksum fernet 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "e7ac567fd75ce6bc28b68e63b5beaa3ce34f56bafd1122f64f8647c822e38a8b" "checksum foreign-types 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)" = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" "checksum foreign-types-shared 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" -"checksum getrandom 0.1.14 (registry+https://github.com/rust-lang/crates.io-index)" = "7abc8dd8451921606d809ba32e95b6111925cd2906060d2dcc29c070220503eb" -"checksum hermit-abi 0.1.13 (registry+https://github.com/rust-lang/crates.io-index)" = "91780f809e750b0a89f5544be56617ff6b1227ee485bcb06ebe10cdf89bd3b71" -"checksum itoa 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)" = "b8b7a7c0c47db5545ed3fef7468ee7bb5b74691498139e4b3f6a20685dc6dd8e" +"checksum getrandom 0.1.15 (registry+https://github.com/rust-lang/crates.io-index)" = "fc587bc0ec293155d5bfa6b9891ec18a1e330c234f896ea47fbada4cadbe47e6" +"checksum getrandom 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ee8025cf36f917e6a52cce185b7c7177689b838b7ec138364e50cc2277a56cf4" +"checksum hermit-abi 0.1.17 (registry+https://github.com/rust-lang/crates.io-index)" = "5aca5565f760fb5b220e499d72710ed156fdb74e631659e99377d9ebfbd13ae8" +"checksum instant 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)" = "cb1fc4429a33e1f80d41dc9fea4d108a88bec1de8053878898ae448a0b52f613" +"checksum itoa 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)" = "dc6f3ad7b9d11a0c00842ff8de1b60ee58661048eb8049ed33c73594f359d7e6" "checksum jobserver 0.1.21 (registry+https://github.com/rust-lang/crates.io-index)" = "5c71313ebb9439f74b00d9d2dcec36440beaf57a6aa0623068441dd7cd81a7f2" "checksum lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" -"checksum libc 0.2.71 (registry+https://github.com/rust-lang/crates.io-index)" = "9457b06509d27052635f90d6466700c65095fdf75409b3fbdd903e988b886f49" -"checksum log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)" = "14b6052be84e6b71ab17edffc2eeabf5c2c3ae1fdb464aae35ac50c67a44e1f7" -"checksum openssl 0.10.29 (registry+https://github.com/rust-lang/crates.io-index)" = "cee6d85f4cb4c4f59a6a85d5b68a233d280c82e29e822913b9c8b129fbf20bdd" -"checksum openssl-sys 0.9.57 (registry+https://github.com/rust-lang/crates.io-index)" = "7410fef80af8ac071d4f63755c0ab89ac3df0fd1ea91f1d1f37cf5cec4395990" -"checksum paste 0.1.15 (registry+https://github.com/rust-lang/crates.io-index)" = "d53181dcd37421c08d3b69f887784956674d09c3f9a47a04fece2b130a5b346b" -"checksum paste-impl 0.1.15 (registry+https://github.com/rust-lang/crates.io-index)" = "05ca490fa1c034a71412b4d1edcb904ec5a0981a4426c9eb2128c0fda7a68d17" -"checksum pkg-config 0.3.17 (registry+https://github.com/rust-lang/crates.io-index)" = "05da548ad6865900e60eaba7f589cc0783590a92e940c26953ff81ddbab2d677" -"checksum ppv-lite86 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)" = "237a5ed80e274dbc66f86bd59c1e25edc039660be53194b5fe0a482e0f2612ea" -"checksum proc-macro-hack 0.5.16 (registry+https://github.com/rust-lang/crates.io-index)" = "7e0456befd48169b9f13ef0f0ad46d492cf9d2dbb918bcf38e01eed4ce3ec5e4" -"checksum proc-macro2 1.0.18 (registry+https://github.com/rust-lang/crates.io-index)" = "beae6331a816b1f65d04c45b078fd8e6c93e8071771f41b8163255bbd8d7c8fa" -"checksum quote 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)" = "54a21852a652ad6f610c9510194f398ff6f8692e334fd1145fed931f7fbe44ea" +"checksum libc 0.2.80 (registry+https://github.com/rust-lang/crates.io-index)" = "4d58d1b70b004888f764dfbf6a26a3b0342a1632d33968e4a179d8011c760614" +"checksum lock_api 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)" = "28247cc5a5be2f05fbcd76dd0cf2c7d3b5400cb978a28042abcd4fa0b3f8261c" +"checksum log 0.4.11 (registry+https://github.com/rust-lang/crates.io-index)" = "4fabed175da42fed1fa0746b0ea71f412aa9d35e76e95e59b192c64b9dc2bf8b" +"checksum maybe-uninit 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "60302e4db3a61da70c0cb7991976248362f30319e88850c487b9b95bbf059e00" +"checksum memoffset 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)" = "043175f069eda7b85febe4a74abbaeff828d9f8b448515d3151a14a3542811aa" +"checksum num 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "8b7a8e9be5e039e2ff869df49155f1c06bd01ade2117ec783e56ab0932b67a8f" +"checksum num-bigint 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "5e9a41747ae4633fce5adffb4d2e81ffc5e89593cb19917f8fb2cc5ff76507bf" +"checksum num-complex 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "747d632c0c558b87dbabbe6a82f3b4ae03720d0646ac5b7b4dae89394be5f2c5" +"checksum num-integer 0.1.44 (registry+https://github.com/rust-lang/crates.io-index)" = "d2cc698a63b549a70bc047073d2949cce27cd1c7b0a4a862d08a8031bc2801db" +"checksum num-iter 0.1.42 (registry+https://github.com/rust-lang/crates.io-index)" = "b2021c8337a54d21aca0d59a92577a029af9431cb59b909b03252b9c164fad59" +"checksum num-rational 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)" = "12ac428b1cb17fce6f731001d307d351ec70a6d202fc2e60f7d4c5e42d8f4f07" +"checksum num-traits 0.2.14 (registry+https://github.com/rust-lang/crates.io-index)" = "9a64b1ec5cda2586e284722486d802acf1f7dbdc623e2bfc57e65ca1cd099290" +"checksum openssl 0.10.30 (registry+https://github.com/rust-lang/crates.io-index)" = "8d575eff3665419f9b83678ff2815858ad9d11567e082f5ac1814baba4e2bcb4" +"checksum openssl-sys 0.9.58 (registry+https://github.com/rust-lang/crates.io-index)" = "a842db4709b604f0fe5d1170ae3565899be2ad3d9cbc72dedc789ac0511f78de" +"checksum parking_lot 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)" = "a4893845fa2ca272e647da5d0e46660a314ead9c2fdd9a883aabc32e481a8733" +"checksum parking_lot_core 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)" = "c361aa727dd08437f2f1447be8b59a33b0edd15e0fcee698f935613d9efbca9b" +"checksum paste 0.1.18 (registry+https://github.com/rust-lang/crates.io-index)" = "45ca20c77d80be666aef2b45486da86238fabe33e38306bd3118fe4af33fa880" +"checksum paste-impl 0.1.18 (registry+https://github.com/rust-lang/crates.io-index)" = "d95a7db200b97ef370c8e6de0088252f7e0dfff7d047a28528e47456c0fc98b6" +"checksum pkg-config 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)" = "3831453b3449ceb48b6d9c7ad7c96d5ea673e9b470a1dc578c2ce6521230884c" +"checksum ppv-lite86 0.2.10 (registry+https://github.com/rust-lang/crates.io-index)" = "ac74c624d6b2d21f425f752262f42188365d7b8ff1aff74c82e45136510a4857" +"checksum proc-macro-hack 0.5.19 (registry+https://github.com/rust-lang/crates.io-index)" = "dbf0c48bc1d91375ae5c3cd81e3722dff1abcf81a30960240640d223f59fe0e5" +"checksum proc-macro2 1.0.24 (registry+https://github.com/rust-lang/crates.io-index)" = "1e0704ee1a7e00d7bb417d0770ea303c1bccbabf0ef1667dae92b5967f5f8a71" +"checksum quote 1.0.7 (registry+https://github.com/rust-lang/crates.io-index)" = "aa563d17ecb180e500da1cfd2b028310ac758de548efdd203e18f283af693f37" "checksum rand 0.7.3 (registry+https://github.com/rust-lang/crates.io-index)" = "6a6b1679d49b24bbfe0c803429aa1874472f50d9b363131f0e89fc356b544d03" "checksum rand_chacha 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "f4c8ed856279c9737206bf725bf36935d8666ead7aa69b52be55af369d193402" "checksum rand_core 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)" = "90bde5296fc891b0cef12a6d03ddccc162ce7b2aff54160af9338f8d40df6d19" "checksum rand_hc 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ca3129af7b92a17112d59ad498c6f81eaf463253766b90396d39ea7a39d6613c" -"checksum redox_syscall 0.1.56 (registry+https://github.com/rust-lang/crates.io-index)" = "2439c63f3f6139d1b57529d16bc3b8bb855230c8efcc5d3a896c8bea7c3b1e84" -"checksum remove_dir_all 0.5.2 (registry+https://github.com/rust-lang/crates.io-index)" = "4a83fa3702a688b9359eccba92d153ac33fd2e8462f9e0e3fdf155239ea7792e" +"checksum redox_syscall 0.1.57 (registry+https://github.com/rust-lang/crates.io-index)" = "41cc0f7e4d5d4544e8861606a285bb08d3e70712ccc7d2b84d7c0ccfaf4b05ce" +"checksum remove_dir_all 0.5.3 (registry+https://github.com/rust-lang/crates.io-index)" = "3acd125665422973a33ac9d3dd2df85edad0f4ae9b00dafb1a05e43a9f5ef8e7" "checksum ryu 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)" = "71d301d4193d031abdd79ff7e3dd721168a9572ef3fe51a1517aba235bd8f86e" -"checksum serde 1.0.111 (registry+https://github.com/rust-lang/crates.io-index)" = "c9124df5b40cbd380080b2cc6ab894c040a3070d995f5c9dc77e18c34a8ae37d" -"checksum serde_derive 1.0.111 (registry+https://github.com/rust-lang/crates.io-index)" = "3f2c3ac8e6ca1e9c80b8be1023940162bf81ae3cffbb1809474152f2ce1eb250" -"checksum serde_json 1.0.53 (registry+https://github.com/rust-lang/crates.io-index)" = "993948e75b189211a9b31a7528f950c6adc21f9720b6438ff80a7fa2f864cea2" +"checksum scopeguard 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" +"checksum serde 1.0.117 (registry+https://github.com/rust-lang/crates.io-index)" = "b88fa983de7720629c9387e9f517353ed404164b1e482c970a90c1a4aaf7dc1a" +"checksum serde_derive 1.0.117 (registry+https://github.com/rust-lang/crates.io-index)" = "cbd1ae72adb44aab48f325a02444a5fc079349a8d804c1fc922aed3f7454c74e" +"checksum serde_json 1.0.59 (registry+https://github.com/rust-lang/crates.io-index)" = "dcac07dbffa1c65e7f816ab9eba78eb142c6d44410f4eeba1e26e4f5dfa56b95" +"checksum smallvec 1.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "fbee7696b84bbf3d89a1c2eccff0850e3047ed46bfcd2e92c29a2d074d57e252" "checksum strsim 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)" = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a" -"checksum syn 1.0.30 (registry+https://github.com/rust-lang/crates.io-index)" = "93a56fabc59dce20fe48b6c832cc249c713e7ed88fa28b0ee0a3bfcaae5fe4e2" +"checksum syn 1.0.48 (registry+https://github.com/rust-lang/crates.io-index)" = "cc371affeffc477f42a221a1e4297aedcea33d47d19b61455588bd9d8f6b19ac" "checksum tempfile 3.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "7a6e24d9338a0a5be79593e2fa15a648add6138caa803e2d5bc782c371732ca9" "checksum textwrap 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060" -"checksum toml 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)" = "ffc92d160b1eef40665be3a05630d003936a3bc7da7421277846c2613e92c71a" -"checksum unicode-width 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)" = "caaa9d531767d1ff2150b9332433f32a24622147e5ebb1f26409d5da67afd479" -"checksum unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "826e7639553986605ec5979c7dd957c7895e93eabed50ab2ffa7f6128a75097c" +"checksum toml 0.5.7 (registry+https://github.com/rust-lang/crates.io-index)" = "75cf45bb0bef80604d001caaec0d09da99611b3c0fd39d3080468875cdb65645" +"checksum unicode-width 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)" = "9337591893a19b88d8d87f2cec1e73fad5cdfd10e5a6f349f498ad6ea2ffb1e3" +"checksum unicode-xid 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "f7fe0bb3479651439c9112f72b6c505038574c9fbb575ed1bf3b797fa39dd564" "checksum uuid 0.8.1 (registry+https://github.com/rust-lang/crates.io-index)" = "9fde2f6a4bea1d6e007c4ad38c6839fa71cbb63b6dbf5b595aa38dc9b1093c11" -"checksum vcpkg 0.2.9 (registry+https://github.com/rust-lang/crates.io-index)" = "55d1e41d56121e07f1e223db0a4def204e45c85425f6a16d462fd07c8d10d74c" +"checksum vcpkg 0.2.10 (registry+https://github.com/rust-lang/crates.io-index)" = "6454029bf181f092ad1b853286f23e2c507d8e8194d01d92da4a55c274a5508c" "checksum vec_map 0.8.2 (registry+https://github.com/rust-lang/crates.io-index)" = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191" "checksum wasi 0.9.0+wasi-snapshot-preview1 (registry+https://github.com/rust-lang/crates.io-index)" = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519" -"checksum winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)" = "8093091eeb260906a183e6ae1abdba2ef5ef2257a21801128899c3fc699229c6" +"checksum winapi 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)" = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" "checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" "checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" diff --git a/src/librslapd/Cargo.toml b/src/librslapd/Cargo.toml index 08309c224..7d37cd840 100644 --- a/src/librslapd/Cargo.toml +++ b/src/librslapd/Cargo.toml @@ -15,6 +15,7 @@ crate-type = ["staticlib", "lib"] [dependencies] slapd = { path = "../slapd" } libc = "0.2" +concread = "^0.2.5" [build-dependencies] cbindgen = "0.9" diff --git a/src/librslapd/src/cache.rs b/src/librslapd/src/cache.rs new file mode 100644 index 000000000..6c1e2d679 --- /dev/null +++ b/src/librslapd/src/cache.rs @@ -0,0 +1,183 @@ +// This exposes C-FFI capable bindings for the concread concurrently readable cache. +use concread::arcache::{ARCache, ARCacheReadTxn, ARCacheWriteTxn}; +use std::ffi::{CString, CStr}; +use std::os::raw::c_char; +use std::borrow::Borrow; +use std::convert::TryInto; + +pub struct ARCacheChar { + inner: ARCache<CString, CString>, +} + +pub struct ARCacheCharRead<'a> { + inner: ARCacheReadTxn<'a, CString, CString>, +} + +pub struct ARCacheCharWrite<'a> { + inner: ARCacheWriteTxn<'a, CString, CString>, +} + +#[no_mangle] +pub extern "C" fn cache_char_create(max: usize, read_max: usize) -> *mut ARCacheChar { + let cache: Box<ARCacheChar> = Box::new(ARCacheChar { inner: ARCache::new_size(max, read_max) }); + Box::into_raw(cache) +} + +#[no_mangle] +pub extern "C" fn cache_char_free(cache: *mut ARCacheChar) { + // Should we be responsible to drain and free everything? + debug_assert!(!cache.is_null()); + unsafe { + Box::from_raw(cache); + } +} + +#[no_mangle] +pub extern "C" fn cache_char_stats( + cache: *mut ARCacheChar, + reader_hits: &mut u64, + reader_includes: &mut u64, + write_hits: &mut u64, + write_inc_or_mod: &mut u64, + shared_max: &mut u64, + freq: &mut u64, + recent: &mut u64, + freq_evicts: &mut u64, + recent_evicts: &mut u64, + p_weight: &mut u64, + all_seen_keys: &mut u64, +) { + let cache_ref = unsafe { + debug_assert!(!cache.is_null()); + &(*cache) as &ARCacheChar + }; + let stat_rguard = cache_ref.inner.view_stats(); + let stats = stat_rguard.borrow(); + *reader_hits = stats.reader_hits.try_into().unwrap(); + *reader_includes = stats.reader_includes.try_into().unwrap(); + *write_hits = stats.write_hits.try_into().unwrap(); + *write_inc_or_mod = stats.write_inc_or_mod.try_into().unwrap(); + *shared_max = stats.shared_max.try_into().unwrap(); + *freq = stats.freq.try_into().unwrap(); + *recent = stats.recent.try_into().unwrap(); + *freq_evicts = stats.freq_evicts.try_into().unwrap(); + *recent_evicts = stats.recent_evicts.try_into().unwrap(); + *p_weight = stats.p_weight.try_into().unwrap(); + *all_seen_keys = stats.all_seen_keys.try_into().unwrap(); +} + + +// start read +#[no_mangle] +pub extern "C" fn cache_char_read_begin(cache: *mut ARCacheChar) -> *mut ARCacheCharRead<'static> { + let cache_ref = unsafe { + debug_assert!(!cache.is_null()); + &(*cache) as &ARCacheChar + }; + let read_txn = Box::new(ARCacheCharRead { inner: cache_ref.inner.read() }); + Box::into_raw(read_txn) +} + +#[no_mangle] +pub extern "C" fn cache_char_read_complete(read_txn: *mut ARCacheCharRead) { + debug_assert!(!read_txn.is_null()); + unsafe { + Box::from_raw(read_txn); + } +} + +#[no_mangle] +pub extern "C" fn cache_char_read_get(read_txn: *mut ARCacheCharRead, key: *const c_char) -> *const c_char { + let read_txn_ref = unsafe { + debug_assert!(!read_txn.is_null()); + &mut (*read_txn) as &mut ARCacheCharRead + }; + + let key_ref = unsafe { CStr::from_ptr(key) }; + let key_dup = CString::from(key_ref); + + // Return a null pointer on miss. + read_txn_ref.inner.get(&key_dup) + .map(|v| v.as_ptr()) + .unwrap_or(std::ptr::null()) +} + +#[no_mangle] +pub extern "C" fn cache_char_read_include(read_txn: *mut ARCacheCharRead, key: *const c_char, val: *const c_char) { + let read_txn_ref = unsafe { + debug_assert!(!read_txn.is_null()); + &mut (*read_txn) as &mut ARCacheCharRead + }; + + let key_ref = unsafe { CStr::from_ptr(key) }; + let key_dup = CString::from(key_ref); + + let val_ref = unsafe { CStr::from_ptr(val) }; + let val_dup = CString::from(val_ref); + read_txn_ref.inner.insert(key_dup, val_dup); +} + +#[no_mangle] +pub extern "C" fn cache_char_write_begin(cache: *mut ARCacheChar) -> *mut ARCacheCharWrite<'static> { + let cache_ref = unsafe { + debug_assert!(!cache.is_null()); + &(*cache) as &ARCacheChar + }; + let write_txn = Box::new(ARCacheCharWrite { inner: cache_ref.inner.write() }); + Box::into_raw(write_txn) +} + +#[no_mangle] +pub extern "C" fn cache_char_write_commit(write_txn: *mut ARCacheCharWrite) { + debug_assert!(!write_txn.is_null()); + let wr = unsafe { + Box::from_raw(write_txn) + }; + (*wr).inner.commit(); +} + +#[no_mangle] +pub extern "C" fn cache_char_write_rollback(write_txn: *mut ARCacheCharWrite) { + debug_assert!(!write_txn.is_null()); + unsafe { + Box::from_raw(write_txn); + } +} + +#[no_mangle] +pub extern "C" fn cache_char_write_include(write_txn: *mut ARCacheCharWrite, key: *const c_char, val: *const c_char) { + let write_txn_ref = unsafe { + debug_assert!(!write_txn.is_null()); + &mut (*write_txn) as &mut ARCacheCharWrite + }; + + let key_ref = unsafe { CStr::from_ptr(key) }; + let key_dup = CString::from(key_ref); + + let val_ref = unsafe { CStr::from_ptr(val) }; + let val_dup = CString::from(val_ref); + write_txn_ref.inner.insert(key_dup, val_dup); +} + +#[cfg(test)] +mod tests { + use crate::cache::*; + + #[test] + fn test_cache_basic() { + let cache_ptr = cache_char_create(1024, 8); + let read_txn = cache_char_read_begin(cache_ptr); + + let k1 = CString::new("Hello").unwrap(); + let v1 = CString::new("Hello").unwrap(); + + assert!(cache_char_read_get(read_txn, k1.as_ptr()).is_null()); + cache_char_read_include(read_txn, k1.as_ptr(), v1.as_ptr()); + assert!(!cache_char_read_get(read_txn, k1.as_ptr()).is_null()); + + cache_char_read_complete(read_txn); + cache_char_free(cache_ptr); + } +} + + diff --git a/src/librslapd/src/lib.rs b/src/librslapd/src/lib.rs index cf283a7ce..9a5415ab2 100644 --- a/src/librslapd/src/lib.rs +++ b/src/librslapd/src/lib.rs @@ -4,12 +4,15 @@ // Remember this is just a c-bindgen stub, all logic should come from slapd! extern crate libc; +extern crate concread; use slapd; use libc::c_char; use std::ffi::{CStr, CString}; +mod cache; + #[no_mangle] pub extern "C" fn do_nothing_rust() -> usize { 0
0
0fd4415e2a4995b2d64aa77120d7158472026f86
389ds/389-ds-base
Merge fixes over
commit 0fd4415e2a4995b2d64aa77120d7158472026f86 Author: David Boreham <[email protected]> Date: Wed May 4 23:54:31 2005 +0000 Merge fixes over diff --git a/ldap/servers/ntds/apacheds/org/apache/ldap/server/NetAPIPartition.java b/ldap/servers/ntds/apacheds/org/apache/ldap/server/NetAPIPartition.java index a5ac5a6b3..e932ee35f 100644 --- a/ldap/servers/ntds/apacheds/org/apache/ldap/server/NetAPIPartition.java +++ b/ldap/servers/ntds/apacheds/org/apache/ldap/server/NetAPIPartition.java @@ -79,9 +79,25 @@ public class NetAPIPartition implements ContextPartition { static { System.loadLibrary("jnetman"); - System.out.println("dll loaded"); + //System.out.println("dll loaded"); } + + public static byte[] HexStringToByteArray(String hexString) { + byte[] byteArray = new byte[hexString.length() / 2]; + for(int i = 0; i < hexString.length() / 2; i++) { + byteArray[i] = (byte)Integer.parseInt(hexString.substring(i * 2, (i * 2) + 2), 16); + } + return byteArray; + } + public static String ByteArrayToHexString(byte[] byteArray) { + String hexString = ""; + for(int i = 0; i < byteArray.length; i++) { + hexString = hexString.concat(Integer.toHexString(byteArray[i] & 0xff)); + } + return hexString; + } + //private LdapName suffix; private String suffix; private static final String container = new String("cn=users").toLowerCase(); @@ -99,12 +115,12 @@ public class NetAPIPartition implements ContextPartition { } try { - outLog.write(new Date() + ": reached NetAPIPartition"); + outLog.write(new Date() + ": reached NetAPIPartition" + "\n"); outLog.flush(); } catch(Exception e) { } - System.out.println("reached NetAPIPartition"); + //System.out.println("reached NetAPIPartition"); suffix = normSuffix.toString(); } @@ -118,12 +134,12 @@ public class NetAPIPartition implements ContextPartition { */ public void delete( Name name ) throws NamingException { try { - outLog.write(new Date() + ": reached NetAPIPartition.delete: " + name); + outLog.write(new Date() + ": reached NetAPIPartition.delete: " + name + "\n"); outLog.flush(); } catch(Exception e) { } - System.out.println("reached NetAPIPartition.delete: " + name); + //System.out.println("reached NetAPIPartition.delete: " + name); String rdn = getRDN(name.toString()); boolean deletedSomthing = false; @@ -186,12 +202,12 @@ public class NetAPIPartition implements ContextPartition { */ public void add( String upName, Name normName, Attributes entry ) throws NamingException { try { - outLog.write(new Date() + ": reached NetAPIPartition.add: " + normName); + outLog.write(new Date() + ": reached NetAPIPartition.add: " + normName + "\n"); outLog.flush(); } catch(Exception e) { } - System.out.println("reached NetAPIPartition.add: " + normName); + //System.out.println("reached NetAPIPartition.add: " + normName); String rdn = getRDN(normName.toString()); Attribute attribute = entry.get("objectClass"); @@ -272,12 +288,12 @@ public class NetAPIPartition implements ContextPartition { */ public void modify( Name name, int modOp, Attributes mods ) throws NamingException { try { - outLog.write(new Date() + ": reached NetAPIPartition.modify1: " + name); + outLog.write(new Date() + ": reached NetAPIPartition.modify1: " + name + "\n"); outLog.flush(); } catch(Exception e) { } - System.out.println("reached NetAPIPartition.modify1: " + name); + //System.out.println("reached NetAPIPartition.modify1: " + name); ModificationItem[] modItems = new ModificationItem[mods.size()]; NamingEnumeration modAttributes = mods.getAll(); @@ -300,12 +316,12 @@ public class NetAPIPartition implements ContextPartition { */ public void modify( Name name, ModificationItem [] mods ) throws NamingException { try { - outLog.write(new Date() + ": reached NetAPIPartition.modify2: " + name); + outLog.write(new Date() + ": reached NetAPIPartition.modify2: " + name + "\n"); outLog.flush(); } catch(Exception e) { } - System.out.println("reached NetAPIPartition.modify2: " + name); + //System.out.println("reached NetAPIPartition.modify2: " + name); String rdn = getRDN(name.toString()); boolean modifiedSomething = false; @@ -389,12 +405,12 @@ public class NetAPIPartition implements ContextPartition { */ public NamingEnumeration list( Name base ) throws NamingException { try { - outLog.write(new Date() + ": reached NetAPIPartition.list"); + outLog.write(new Date() + ": reached NetAPIPartition.list" + "\n"); outLog.flush(); } catch(Exception e) { } - System.out.println("reached NetAPIPartition.list"); + //System.out.println("reached NetAPIPartition.list"); return new BasicAttribute(base.toString()).getAll(); } @@ -419,12 +435,12 @@ public class NetAPIPartition implements ContextPartition { public NamingEnumeration search( Name base, Map env, ExprNode filter, SearchControls searchCtls ) throws NamingException { try { - outLog.write(new Date() + ": reached NetAPIPartition.search: " + base); + outLog.write(new Date() + ": reached NetAPIPartition.search: " + base + "\n"); outLog.flush(); } catch(Exception e) { } - System.out.println("reached NetAPIPartition.search: " + base + " " + filter); + //System.out.println("reached NetAPIPartition.search: " + base + " " + filter); BasicAttribute results = new BasicAttribute(null); SearchResult result; @@ -536,12 +552,12 @@ public class NetAPIPartition implements ContextPartition { */ public Attributes lookup( Name name ) throws NamingException { try { - outLog.write(new Date() + ": reached NetAPIPartition.lookup1: " + name); + outLog.write(new Date() + ": reached NetAPIPartition.lookup1: " + name + "\n"); outLog.flush(); } catch(Exception e) { } - System.out.println("reached NetAPIPartition.lookup1: " + name); + //System.out.println("reached NetAPIPartition.lookup1: " + name); BasicAttributes attributes = null; BasicAttribute attribute; @@ -597,12 +613,12 @@ public class NetAPIPartition implements ContextPartition { */ public Attributes lookup( Name dn, String [] attrIds ) throws NamingException { try { - outLog.write(new Date() + ": reached NetAPIPartition.lookup2: " + dn); + outLog.write(new Date() + ": reached NetAPIPartition.lookup2: " + dn + "\n"); outLog.flush(); } catch(Exception e) { } - System.out.println("reached NetAPIPartition.lookup2: " + dn); + //System.out.println("reached NetAPIPartition.lookup2: " + dn); return lookup(dn); } @@ -617,12 +633,12 @@ public class NetAPIPartition implements ContextPartition { */ public boolean hasEntry( Name name ) throws NamingException { try { - outLog.write(new Date() + ": reached NetAPIPartition.hasEntry: " + name); + outLog.write(new Date() + ": reached NetAPIPartition.hasEntry: " + name + "\n"); outLog.flush(); } catch(Exception e) { } - System.out.println("reached NetAPIPartition.hasEntry: " + name); + //System.out.println("reached NetAPIPartition.hasEntry: " + name); boolean result = false; String rdn = getRDN(name.toString()); @@ -658,12 +674,12 @@ public class NetAPIPartition implements ContextPartition { */ public boolean isSuffix( Name name ) throws NamingException { try { - outLog.write(new Date() + ": reached NetAPIPartition.isSuffix"); + outLog.write(new Date() + ": reached NetAPIPartition.isSuffix" + "\n"); outLog.flush(); } catch(Exception e) { } - System.out.println("reached NetAPIPartition.isSuffix"); + //System.out.println("reached NetAPIPartition.isSuffix"); return false; } @@ -684,12 +700,12 @@ public class NetAPIPartition implements ContextPartition { public void modifyRn( Name name, String newRn, boolean deleteOldRn ) throws NamingException { try { - outLog.write(new Date() + ": reached NetAPIPartition.modifyRn"); + outLog.write(new Date() + ": reached NetAPIPartition.modifyRn" + "\n"); outLog.flush(); } catch(Exception e) { } - System.out.println("reached NetAPIPartition.modifyRn"); + //System.out.println("reached NetAPIPartition.modifyRn"); } @@ -705,12 +721,12 @@ public class NetAPIPartition implements ContextPartition { */ public void move( Name oriChildName, Name newParentName ) throws NamingException { try { - outLog.write(new Date() + ": reached NetAPIPartition.move1"); + outLog.write(new Date() + ": reached NetAPIPartition.move1" + "\n"); outLog.flush(); } catch(Exception e) { } - System.out.println("reached NetAPIPartition.move1"); + //System.out.println("reached NetAPIPartition.move1"); } @@ -734,12 +750,12 @@ public class NetAPIPartition implements ContextPartition { public void move( Name oriChildName, Name newParentName, String newRn, boolean deleteOldRn ) throws NamingException { try { - outLog.write(new Date() + ": reached NetAPIPartition.move2"); + outLog.write(new Date() + ": reached NetAPIPartition.move2" + "\n"); outLog.flush(); } catch(Exception e) { } - System.out.println("reached NetAPIPartition.move2"); + //System.out.println("reached NetAPIPartition.move2"); } @@ -759,12 +775,12 @@ public class NetAPIPartition implements ContextPartition { */ public void close() throws NamingException { try { - outLog.write(new Date() + ": reached NetAPIPartition.close"); + outLog.write(new Date() + ": reached NetAPIPartition.close" + "\n"); outLog.flush(); } catch(Exception e) { } - System.out.println("reached NetAPIPartition.close"); + //System.out.println("reached NetAPIPartition.close"); } @@ -776,12 +792,12 @@ public class NetAPIPartition implements ContextPartition { */ public boolean isClosed() { try { - outLog.write(new Date() + ": reached NetAPIPartition.isClosed"); + outLog.write(new Date() + ": reached NetAPIPartition.isClosed" + "\n"); outLog.flush(); } catch(Exception e) { } - System.out.println("reached NetAPIPartition.isClosed"); + //System.out.println("reached NetAPIPartition.isClosed"); return true; } @@ -1051,9 +1067,11 @@ public class NetAPIPartition implements ContextPartition { attribute.add(new Long(user.GetCodePage()).toString()); attributes.put(attribute); - attribute = new BasicAttribute("description"); - attribute.add(user.GetComment()); - attributes.put(attribute); + if(!user.GetComment().equals("")) { + attribute = new BasicAttribute("description"); + attribute.add(user.GetComment()); + attributes.put(attribute); + } attribute = new BasicAttribute("countryCode"); attribute.add(new Long(user.GetCountryCode()).toString()); @@ -1063,13 +1081,17 @@ public class NetAPIPartition implements ContextPartition { attribute.add(new Long(user.GetFlags()).toString()); attributes.put(attribute); - attribute = new BasicAttribute("homeDirectory"); - attribute.add(user.GetHomeDir()); - attributes.put(attribute); + if(!user.GetHomeDir().equals("")) { + attribute = new BasicAttribute("homeDirectory"); + attribute.add(user.GetHomeDir()); + attributes.put(attribute); + } - attribute = new BasicAttribute("homeDrive"); - attribute.add(user.GetHomeDirDrive()); - attributes.put(attribute); + if(!user.GetHomeDirDrive().equals("")) { + attribute = new BasicAttribute("homeDrive"); + attribute.add(user.GetHomeDirDrive()); + attributes.put(attribute); + } attribute = new BasicAttribute("lastLogoff"); attribute.add(new Long(user.GetLastLogoff()).toString()); @@ -1080,7 +1102,7 @@ public class NetAPIPartition implements ContextPartition { attributes.put(attribute); attribute = new BasicAttribute("logonHours"); - attribute.add(user.GetLogonHours()); + attribute.add(HexStringToByteArray(user.GetLogonHours())); attributes.put(attribute); attribute = new BasicAttribute("maxStorage"); @@ -1091,29 +1113,39 @@ public class NetAPIPartition implements ContextPartition { attribute.add(new Long(user.GetNumLogons()).toString()); attributes.put(attribute); - attribute = new BasicAttribute("profilePath"); - attribute.add(user.GetProfile()); - attributes.put(attribute); + if(!user.GetProfile().equals("")) { + attribute = new BasicAttribute("profilePath"); + attribute.add(user.GetProfile()); + attributes.put(attribute); + } - attribute = new BasicAttribute("scriptPath"); - attribute.add(user.GetScriptPath()); - attributes.put(attribute); + if(!user.GetScriptPath().equals("")) { + attribute = new BasicAttribute("scriptPath"); + attribute.add(user.GetScriptPath()); + attributes.put(attribute); + } attribute = new BasicAttribute("sAMAccountName"); attribute.add(username); attributes.put(attribute); - attribute = new BasicAttribute("userWorkstations"); - attribute.add(user.GetWorkstations()); - attributes.put(attribute); + if(!user.GetWorkstations().equals("")) { + attribute = new BasicAttribute("userWorkstations"); + attribute.add(user.GetWorkstations()); + attributes.put(attribute); + } - attribute = new BasicAttribute("cn"); - attribute.add(username); - attributes.put(attribute); + if(!user.GetFullname().equals("")) { + attribute = new BasicAttribute("cn"); + attribute.add(user.GetFullname()); + attributes.put(attribute); + } - attribute = new BasicAttribute("name"); - attribute.add(user.GetFullname()); - attributes.put(attribute); + if(!user.GetFullname().equals("")) { + attribute = new BasicAttribute("name"); + attribute.add(user.GetFullname()); + attributes.put(attribute); + } attribute = new BasicAttribute("memberOf"); result = user.LoadGroups(); @@ -1175,10 +1207,12 @@ public class NetAPIPartition implements ContextPartition { attribute = new BasicAttribute("groupType"); attribute.add(new Long(GLOBAL_FLAG).toString()); attributes.put(attribute); - - attribute = new BasicAttribute("description"); - attribute.add(group.GetComment()); - attributes.put(attribute); + + if(!group.GetComment().equals("")) { + attribute = new BasicAttribute("description"); + attribute.add(group.GetComment()); + attributes.put(attribute); + } attribute = new BasicAttribute("member"); result = group.LoadUsers(); @@ -1232,9 +1266,11 @@ public class NetAPIPartition implements ContextPartition { attribute.add(new Long(DOMAINLOCAL_FLAG).toString()); attributes.put(attribute); - attribute = new BasicAttribute("description"); - attribute.add(localGroup.GetComment()); - attributes.put(attribute); + if(!localGroup.GetComment().equals("")) { + attribute = new BasicAttribute("description"); + attribute.add(localGroup.GetComment()); + attributes.put(attribute); + } attribute = new BasicAttribute("member"); result = localGroup.LoadUsers(); @@ -1333,15 +1369,15 @@ public class NetAPIPartition implements ContextPartition { user.SetHomeDirDrive((String)mods[i].getAttribute().get()); } } - else if(mods[i].getAttribute().getID().compareToIgnoreCase("logonHours") == 0) { + else if(mods[i].getAttribute().getID().compareToIgnoreCase("logonHours") == 0) { if(mods[i].getModificationOp() == DirContext.ADD_ATTRIBUTE) { - user.SetLogonHours((String)mods[i].getAttribute().get()); + user.SetLogonHours(ByteArrayToHexString((byte[])mods[i].getAttribute().get())); } else if(mods[i].getModificationOp() == DirContext.REMOVE_ATTRIBUTE) { - user.SetLogonHours(""); + user.SetLogonHours("ffffffffffffffffffffffffffffffffffffffffff"); } else if(mods[i].getModificationOp() == DirContext.REPLACE_ATTRIBUTE) { - user.SetLogonHours((String)mods[i].getAttribute().get()); + user.SetLogonHours(ByteArrayToHexString((byte[])mods[i].getAttribute().get())); } } else if(mods[i].getAttribute().getID().compareToIgnoreCase("maxStorage") == 0) { @@ -1502,8 +1538,20 @@ public class NetAPIPartition implements ContextPartition { } } else if(mods[i].getModificationOp() == DirContext.REMOVE_ATTRIBUTE) { - tempName = getRDN((String)mods[i].getAttribute().get()); - group.RemoveUser(tempName); + tempName = (String)mods[i].getAttribute().get(); + if(tempName != null) { + tempName = getRDN((String)mods[i].getAttribute().get()); + group.RemoveUser(tempName); + } + else { + group.LoadUsers(); + while(group.HasMoreUsers()) { + tempName = group.NextUserName(); + if(!tempName.endsWith("$")) { + group.RemoveUser(tempName); + } + } + } } else if(mods[i].getModificationOp() == DirContext.REPLACE_ATTRIBUTE) { HashSet users = new HashSet(); @@ -1559,8 +1607,20 @@ public class NetAPIPartition implements ContextPartition { } } else if(mods[i].getModificationOp() == DirContext.REMOVE_ATTRIBUTE) { - tempName = getRDN((String)mods[i].getAttribute().get()); - localGroup.RemoveUser(tempName); + tempName = (String)mods[i].getAttribute().get(); + if(tempName != null) { + tempName = getRDN((String)mods[i].getAttribute().get()); + localGroup.RemoveUser(tempName); + } + else { + localGroup.LoadUsers(); + while(localGroup.HasMoreUsers()) { + tempName = localGroup.NextUserName(); + if(!tempName.endsWith("$")) { + localGroup.RemoveUser(tempName); + } + } + } } else if(mods[i].getModificationOp() == DirContext.REPLACE_ATTRIBUTE) { HashSet users = new HashSet(); diff --git a/ldap/servers/ntds/apacheds/usersync.schema b/ldap/servers/ntds/apacheds/usersync.schema index d2d836d6d..5f87ff61c 100644 --- a/ldap/servers/ntds/apacheds/usersync.schema +++ b/ldap/servers/ntds/apacheds/usersync.schema @@ -240,6 +240,12 @@ attributetype ( 1.2.840.113556.1.4.2 SYNTAX 1.3.6.1.4.1.1466.115.121.1.40 SINGLE-VALUE ) +# added for usersync +attributetype ( 1.2.840.113556.1.4.3 + NAME 'GUID' + SYNTAX 1.3.6.1.4.1.1466.115.121.1.40 + SINGLE-VALUE ) + attributetype ( 1.2.840.113556.1.4.52 NAME 'lastLogon' SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 @@ -460,6 +466,7 @@ objectclass ( 1.3.6.1.4.1.7114.2.2.10 ntPwdHistory $ objectCategory $ objectGUID $ + GUID $ # added for usersync operatorCount $ otherLoginWorkstations $ preferredOU $ @@ -520,6 +527,7 @@ objectclass ( 1.3.6.1.4.1.7114.2.2.12 systemFlags $ objectCategory $ objectGUID $ + GUID $ # added for usersync objectSid $ sAMAccountName $ sAMAccountType $
0
137db8058e7486fff21534dd3bea85273d3a5d65
389ds/389-ds-base
issue 4612 - Fix pytest fourwaymmr_test for non root user (#4613)
commit 137db8058e7486fff21534dd3bea85273d3a5d65 Author: progier389 <[email protected]> Date: Wed Feb 10 19:18:00 2021 +0100 issue 4612 - Fix pytest fourwaymmr_test for non root user (#4613) diff --git a/dirsrvtests/tests/suites/fourwaymmr/fourwaymmr_test.py b/dirsrvtests/tests/suites/fourwaymmr/fourwaymmr_test.py index ee0a83d1a..f092a8b76 100644 --- a/dirsrvtests/tests/suites/fourwaymmr/fourwaymmr_test.py +++ b/dirsrvtests/tests/suites/fourwaymmr/fourwaymmr_test.py @@ -14,6 +14,7 @@ from lib389.topologies import topology_m4 as topo_m4 from lib389.replica import * from lib389.idm.user import UserAccounts from lib389.agreement import * +from contextlib import suppress pytestmark = pytest.mark.tier2 @@ -215,7 +216,8 @@ def test_bad_replication_agreement(topo_m4): topo_m4.ms["master{}".format(i)].confdir + "/dse_test_bug157377.ldif", ) - os.chown('{}/dse_test_bug157377.ldif'.format(topo_m4.all_insts.get('master{}'.format(i)).confdir), + with suppress(PermissionError): + os.chown('{}/dse_test_bug157377.ldif'.format(topo_m4.all_insts.get('master{}'.format(i)).confdir), pwd.getpwnam('dirsrv').pw_uid, grp.getgrnam('dirsrv').gr_gid) for i in ["master1", "master2", "master3", "master4"]: topo_m4.all_insts.get(i).start() @@ -244,7 +246,8 @@ def test_bad_replication_agreement(topo_m4): + "/dse_test_bug157377.ldif", topo_m4.ms["master{}".format(i)].confdir + "/dse.ldif", ) - os.chown('{}/dse_test_bug157377.ldif'.format(topo_m4.all_insts.get('master{}'.format(i)).confdir), + with suppress(PermissionError): + os.chown('{}/dse_test_bug157377.ldif'.format(topo_m4.all_insts.get('master{}'.format(i)).confdir), pwd.getpwnam('dirsrv').pw_uid, grp.getgrnam('dirsrv').gr_gid) for inst in topo_m4: inst.start()
0
138daaa4b171b770e0372c19fb5f656309eea4b1
389ds/389-ds-base
Bug 609590 - fix coverity Defect Type: Memory - corruptions issues https://bugzilla.redhat.com/show_bug.cgi?id=609590 Resolves: bug 609590 Bug Description: fix coverity Defect Type: Memory - corruptions issues Reviewed by: nhosoi (Thanks!) Branch: HEAD Fix Description: The code wants to allocate space for a struct berval, not struct berval *. Platforms tested: RHEL5 x86_64 Flag Day: no Doc impact: no
commit 138daaa4b171b770e0372c19fb5f656309eea4b1 Author: Rich Megginson <[email protected]> Date: Wed Jun 30 14:18:36 2010 -0600 Bug 609590 - fix coverity Defect Type: Memory - corruptions issues https://bugzilla.redhat.com/show_bug.cgi?id=609590 Resolves: bug 609590 Bug Description: fix coverity Defect Type: Memory - corruptions issues Reviewed by: nhosoi (Thanks!) Branch: HEAD Fix Description: The code wants to allocate space for a struct berval, not struct berval *. Platforms tested: RHEL5 x86_64 Flag Day: no Doc impact: no diff --git a/ldap/servers/slapd/tools/ldclt/ldapfct.c b/ldap/servers/slapd/tools/ldclt/ldapfct.c index b19c6895c..4d1ac6a3d 100644 --- a/ldap/servers/slapd/tools/ldclt/ldapfct.c +++ b/ldap/servers/slapd/tools/ldclt/ldapfct.c @@ -1523,7 +1523,7 @@ buildNewModAttribFile ( { int nbAttribs; /* Nb of attributes */ LDAPMod attribute; /* To build the attributes */ - struct berval *bv = malloc(sizeof(struct berval *)); + struct berval *bv = malloc(sizeof(struct berval)); attribute.mod_bvalues = (struct berval **)malloc(2 * sizeof(struct berval *)); if ((bv == NULL) || (attribute.mod_bvalues == NULL)) {
0
744df65e75035466cf501a2a2809d223f7466a8f
389ds/389-ds-base
Issue 6615 - test_custom_path CI test fails (#6616) test_custom_path CI test fails because the instance used to perform the backup is not up to date with the config Issue: #6615 Reviewed by: @tbordaz
commit 744df65e75035466cf501a2a2809d223f7466a8f Author: progier389 <[email protected]> Date: Tue Feb 18 15:10:49 2025 +0100 Issue 6615 - test_custom_path CI test fails (#6616) test_custom_path CI test fails because the instance used to perform the backup is not up to date with the config Issue: #6615 Reviewed by: @tbordaz diff --git a/dirsrvtests/tests/suites/clu/dsctl_acceptance_test.py b/dirsrvtests/tests/suites/clu/dsctl_acceptance_test.py index 796833042..46b658c8e 100644 --- a/dirsrvtests/tests/suites/clu/dsctl_acceptance_test.py +++ b/dirsrvtests/tests/suites/clu/dsctl_acceptance_test.py @@ -11,11 +11,10 @@ import pytest import os import time from lib389.topologies import topology_st as topo +from lib389.paths import Paths log = logging.getLogger(__name__) -#unstable or unstatus tests, skipped for now [email protected](max_runs=2, min_passes=1) def test_custom_path(topo): """Test that a custom path, backup directory, is correctly used by lib389 when the server is stopped. @@ -45,9 +44,13 @@ def test_custom_path(topo): time.sleep(.5) # Stop the server and take a backup - topo.standalone.stop() + inst = topo.standalone + inst.stop() + # Refresh ds_paths + inst.ds_paths = Paths(inst.serverid, instance=inst, local=inst.isLocal) + time.sleep(.5) - topo.standalone.db2bak(None) # Bug, bak dir is being pulled from defaults.inf, and not from config + inst.db2bak(None) # Bug, bak dir is being pulled from defaults.inf, and not from config # Verify backup was written to LDIF directory log.info("AFTER: ldif dir (new bak dir): " + ldif_dir + " items: " + str(len(os.listdir(ldif_dir))))
0
10bffac3b3bc922feaf7d781388b54bc78de4146
389ds/389-ds-base
Issue 49875 - Move SystemD service config to a drop-in file Bug Description: Runtime configuration options are mixed into the service specification which should seldom be changed by users. Fix Description: Move the runtime configuration options into a drop-in file. These options are then automatically pulled in by SystemD. Additional Info: Erasing the default values of the mentioned options to implicitly pull in system defaults which are more sane nowadays. The .service file is now common for xsan and non-xsan builds, the former differring only by an additional drop-in file. Related https://pagure.io/389-ds-base/issue/49875 Author: Matus Honek <[email protected]> Review by: firstyear, mreynolds, vashirov (thanks!)
commit 10bffac3b3bc922feaf7d781388b54bc78de4146 Author: Matus Honek <[email protected]> Date: Mon May 27 10:59:03 2019 +0000 Issue 49875 - Move SystemD service config to a drop-in file Bug Description: Runtime configuration options are mixed into the service specification which should seldom be changed by users. Fix Description: Move the runtime configuration options into a drop-in file. These options are then automatically pulled in by SystemD. Additional Info: Erasing the default values of the mentioned options to implicitly pull in system defaults which are more sane nowadays. The .service file is now common for xsan and non-xsan builds, the former differring only by an additional drop-in file. Related https://pagure.io/389-ds-base/issue/49875 Author: Matus Honek <[email protected]> Review by: firstyear, mreynolds, vashirov (thanks!) diff --git a/Makefile.am b/Makefile.am index 2c1dc3865..c64eabb6c 100644 --- a/Makefile.am +++ b/Makefile.am @@ -300,6 +300,7 @@ serverdir = $(libdir)/@serverdir@ serverplugindir = $(libdir)@serverplugindir@ taskdir = $(datadir)@scripttemplatedir@ systemdsystemunitdir = @with_systemdsystemunitdir@ +systemdsystemunitdropindir = @with_systemdsystemunitdir@/$(PACKAGE_NAME)@.service.d systemdsystemconfdir = @with_systemdsystemconfdir@ systemdgroupname = @with_systemdgroupname@ initdir = @initdir@ @@ -880,6 +881,11 @@ if SYSTEMD systemdsystemunit_DATA = wrappers/$(PACKAGE_NAME)@.service \ wrappers/$(systemdgroupname) \ wrappers/$(PACKAGE_NAME)-snmp.service + +systemdsystemunitdropin_DATA = wrappers/$(PACKAGE_NAME)@.service.d/custom.conf +if with_sanitizer +systemdsystemunitdropin_DATA += wrappers/$(PACKAGE_NAME)@.service.d/xsan.conf +endif else if INITDDIR init_SCRIPTS = wrappers/$(PACKAGE_NAME) \ @@ -2312,12 +2318,17 @@ endif # yes, that is an @ in the filename . . . %/$(PACKAGE_NAME)@.service: %/systemd.template.service.in if [ ! -d $(dir $@) ] ; then mkdir -p $(dir $@) ; fi - if [ ! -z ${SANITIZER} ] ; then \ - service_template=$(shell echo $^ | sed 's/template/template.xsan/g'); \ - else \ - service_template=$^; \ - fi; \ - $(fixupcmd) $$service_template > $@ + $(fixupcmd) $^ > $@ + +%/$(PACKAGE_NAME)@.service.d/custom.conf: %/systemd.template.service.custom.conf.in + if [ ! -d $(dir $@) ] ; then mkdir -p $(dir $@) ; fi + $(fixupcmd) $^ > $@ + +if with_sanitizer +%/$(PACKAGE_NAME)@.service.d/xsan.conf: %/systemd.template.service.xsan.conf.in + if [ ! -d $(dir $@) ] ; then mkdir -p $(dir $@) ; fi + $(fixupcmd) $^ > $@ +endif %/$(systemdgroupname): %/systemd.group.in if [ ! -d $(dir $@) ] ; then mkdir -p $(dir $@) ; fi diff --git a/configure.ac b/configure.ac index aa50ce177..0abcfbd14 100644 --- a/configure.ac +++ b/configure.ac @@ -196,6 +196,8 @@ AC_SUBST([ubsan_cflags]) AC_SUBST([ubsan_rust_defs]) AM_CONDITIONAL(enable_ubsan,test "$enable_ubsan" = "yes") +AM_CONDITIONAL(with_sanitizer,test "$enable_asan" = "yes" -o "$enable_msan" = "yes" -o "$enable_tsan" = "yes" -o "$enable_ubsan" = "yes") + # Enable CLANG AC_MSG_CHECKING(for --enable-clang) AC_ARG_ENABLE(clang, AS_HELP_STRING([--enable-clang], [Enable clang (default: no)]), diff --git a/wrappers/systemd.template.service.custom.conf.in b/wrappers/systemd.template.service.custom.conf.in new file mode 100644 index 000000000..0dce62826 --- /dev/null +++ b/wrappers/systemd.template.service.custom.conf.in @@ -0,0 +1,52 @@ +# To change any of the below values, please use a drop-in file in which +# you can declare overrides according to systemd.unit(5), either of: +# - applying to all instances: +# /etc/systemd/system/[email protected]/custom.conf +# - applying to a single instance (overriding the above): +# /etc/systemd/system/dirsrv@<instance>.service.d/custom.conf +# +# Some of the most interesting coniguration options are mentioned below. +# See systemd.service(5) and systemd.exec(5) for the respective documentation. +# +# After updating the service configuration, do not forget to apply the changes: +# - reload systemd configuration: systemctl daemon-reload +# - restart the service: systemctl restart @package_name@@<instance>.service + +[Service] +TimeoutStartSec=0 +TimeoutStopSec=600 + +# These are from man systemd.exec and man systemd.resource-control + +# This controls the resources to the direct child of systemd, in +# this case ns-slapd. Because we are type notify we recieve these +# limits correctly. + +# This controls the number of file handles avaliable. File handles +# correlate to sockets for the process, and our access to logs and +# databases. Note, the configuration setting in Directory Server, +# "nsslapd-maxdescriptors", can override this limit. +#LimitNOFILE= + +# You can limit the memory in the cgroup with these, and ns-slapd +# will account for them in it's autotuning. +# Memory account may be controlled by DefaultMemoryAccounting= in systemd-system.conf +#MemoryAccounting=yes +#MemoryLimit=<bytes> + +# Limits on the size of coredump that may be produced by the process. It's not +# specified how this interacts with coredumpd. +# 0 means not to produce cores. +#LimitCORE=<bytes> + +# Limit number of processes (threads) we may spawn. We don't advise you change +# this as DS will autodetect your threads / cpus and adjust as needed. +#LimitNPROC= + +# Possible hardening options: +#PrivateDevices=yes +#ProtectSystem=yes +#ProtectHome=yes +#PrivateTmp=yes + + diff --git a/wrappers/systemd.template.service.in b/wrappers/systemd.template.service.in index 7142c3492..2ac6f978f 100644 --- a/wrappers/systemd.template.service.in +++ b/wrappers/systemd.template.service.in @@ -1,17 +1,6 @@ -# you usually do not want to edit this file - instead, edit the -# @initconfigdir@/@[email protected] file instead - otherwise, -# do not edit this file in /lib/systemd/system - instead, do the following: -# cp /lib/systemd/system/dirsrv\@.service /etc/systemd/system/dirsrv\@.service -# mkdir -p /etc/systemd/system/@[email protected] -# edit /etc/systemd/system/dirsrv\@.service - uncomment the LimitNOFILE=8192 line -# where %i is the name of the instance -# you may already have a symlink in -# /etc/systemd/system/@[email protected]/dirsrv@%i.service pointing to -# /lib/systemd/system/dirsrv\@.service - you will have to change it to link -# to /etc/systemd/system/dirsrv\@.service instead -# ln -s /etc/systemd/system/dirsrv\@.service /etc/systemd/system/@[email protected]/dirsrv@%i.service -# systemctl daemon-reload -# systemctl (re)start @systemdgroupname@ +# You should not need to edit this file. Instead, use a drop-in file as described in: +# /usr/lib/systemd/system/@package_name@@.service.d/custom.conf + [Unit] Description=@capbrand@ Directory Server %i. PartOf=@systemdgroupname@ @@ -21,51 +10,11 @@ Before=radiusd.service [Service] Type=notify NotifyAccess=all -TimeoutStartSec=0 -TimeoutStopSec=600 EnvironmentFile=-@initconfigdir@/@package_name@ EnvironmentFile=-@initconfigdir@/@package_name@-%i PIDFile=@localstatedir@/run/@package_name@/slapd-%i.pid ExecStartPre=@libexecdir@/ds_systemd_ask_password_acl @instconfigdir@/slapd-%i/dse.ldif ExecStart=@sbindir@/ns-slapd -D @instconfigdir@/slapd-%i -i @localstatedir@/run/@package_name@/slapd-%i.pid -#### To change any of these values or directives, you should use a drop in file -# such as: /etc/systemd/system/dirsrv@<instance>.d/custom.conf - -# These are from man systemd.exec and man systemd.resource-control - -# This controls the resources to the direct child of systemd, in -# this case ns-slapd. Because we are type notify we recieve these -# limits correctly. - -# This controls the number of file handles avaliable. File handles -# correlate to sockets for the process, and our access to logs and -# databases. Note, the configuration setting in Directory Server, -# "nsslapd-maxdescriptors", can override this limit. -LimitNOFILE=16384 - -# You can limit the memory in the cgroup with these, and ns-slapd -# will account for them in it's autotuning. -# Memory account may be controlled by DefaultMemoryAccounting= in systemd-system.conf -# MemoryAccounting=true -# MemoryLimit=bytes - -# Limits on the size of coredump that may be produced by the process. It's not -# specified how this interacts with coredumpd. -# 0 means not to produce cores. -# This value is 64G -LimitCORE=68719476736 - -# Limit number of processes (threads) we may spawn. We don't advise you change -# this as DS will autodetect your threads / cpus and adjust as needed. -# LimitNPROC= - -# Hardening options: -# PrivateDevices=true -# ProtectSystem=true -# ProtectHome=true -# PrivateTmp=true - [Install] WantedBy=multi-user.target - diff --git a/wrappers/systemd.template.service.xsan.conf.in b/wrappers/systemd.template.service.xsan.conf.in new file mode 100644 index 000000000..f4bf809b9 --- /dev/null +++ b/wrappers/systemd.template.service.xsan.conf.in @@ -0,0 +1,11 @@ +# This file is present because the server has been built with a sanitizer. +# It is not meant for a production usage. +[Unit] +Description=@capbrand@ Directory Server with @SANITIZER@ %i. + +[Service] +# We can't symbolize here, as llvm symbolize crashes when it goes near systemd. +Environment=ASAN_OPTIONS=log_path=@localstatedir@/run/@package_name@/ns-slapd-%i.asan:print_stacktrace=1 +Environment=TSAN_OPTIONS=log_path=@localstatedir@/run/@package_name@/ns-slapd-%i.tsan:print_stacktrace=1:second_deadlock_stack=1:history_size=7 +Environment=MSAN_OPTIONS=log_path=@localstatedir@/run/@package_name@/ns-slapd-%i.msan:print_stacktrace=1 +Environment=UBSAN_OPTIONS=log_path=@localstatedir@/run/@package_name@/ns-slapd-%i.ubsan:print_stacktrace=1 diff --git a/wrappers/systemd.template.xsan.service.in b/wrappers/systemd.template.xsan.service.in deleted file mode 100644 index 541392ff8..000000000 --- a/wrappers/systemd.template.xsan.service.in +++ /dev/null @@ -1,77 +0,0 @@ -# you usually do not want to edit this file - instead, edit the -# @initconfigdir@/@[email protected] file instead - otherwise, -# do not edit this file in /lib/systemd/system - instead, do the following: -# cp /lib/systemd/system/dirsrv\@.service /etc/systemd/system/dirsrv\@.service -# mkdir -p /etc/systemd/system/@[email protected] -# edit /etc/systemd/system/dirsrv\@.service - uncomment the LimitNOFILE=8192 line -# where %i is the name of the instance -# you may already have a symlink in -# /etc/systemd/system/@[email protected]/dirsrv@%i.service pointing to -# /lib/systemd/system/dirsrv\@.service - you will have to change it to link -# to /etc/systemd/system/dirsrv\@.service instead -# ln -s /etc/systemd/system/dirsrv\@.service /etc/systemd/system/@[email protected]/dirsrv@%i.service -# systemctl daemon-reload -# systemctl (re)start @systemdgroupname@ -[Unit] -Description=@capbrand@ Directory Server with @SANITIZER@ %i. -PartOf=@systemdgroupname@ -After=chronyd.service ntpd.service network-online.target syslog.target -Before=radiusd.service - -[Service] -Type=notify -NotifyAccess=all -TimeoutStartSec=0 -TimeoutStopSec=600 -EnvironmentFile=@initconfigdir@/@package_name@ -EnvironmentFile=@initconfigdir@/@package_name@-%i -PIDFile=@localstatedir@/run/@package_name@/slapd-%i.pid -# We can't symbolize here, as llvm symbolize crashes when it goes near systemd. -Environment=ASAN_OPTIONS=log_path=@localstatedir@/run/@package_name@/ns-slapd-%i.asan:print_stacktrace=1 -Environment=TSAN_OPTIONS=log_path=@localstatedir@/run/@package_name@/ns-slapd-%i.tsan:print_stacktrace=1:second_deadlock_stack=1:history_size=7 -Environment=MSAN_OPTIONS=log_path=@localstatedir@/run/@package_name@/ns-slapd-%i.msan:print_stacktrace=1 -Environment=UBSAN_OPTIONS=log_path=@localstatedir@/run/@package_name@/ns-slapd-%i.ubsan:print_stacktrace=1 -LimitCORE=infinity -ExecStartPre=@libexecdir@/ds_systemd_ask_password_acl @instconfigdir@/slapd-%i/dse.ldif -ExecStart=@sbindir@/ns-slapd -D @instconfigdir@/slapd-%i -i @localstatedir@/run/@package_name@/slapd-%i.pid - -#### To change any of these values or directives, you should use a drop in file -# such as: /etc/systemd/system/dirsrv@<instance>.d/custom.conf - -# These are from man systemd.exec and man systemd.resource-control - -# This controls the resources to the direct child of systemd, in -# this case ns-slapd. Because we are type notify we recieve these -# limits correctly. - -# This controls the number of file handles avaliable. File handles -# correlate to sockets for the process, and our access to logs and -# databases. -LimitNOFILE=16384 - -# You can limit the memory in the cgroup with these, and ns-slapd -# will account for them in it's autotuning. -# Memory account may be controlled by DefaultMemoryAccounting= in systemd-system.conf -# MemoryAccounting=true -# MemoryLimit=bytes - -# Limits on the size of coredump that may be produced by the process. It's not -# specified how this interacts with coredumpd. -# 0 means not to produce cores. -# This value is 64G -LimitCORE=68719476736 - -# Limit number of processes (threads) we may spawn. We don't advise you change -# this as DS will autodetect your threads / cpus and adjust as needed. -# LimitNPROC= - -# Hardening options: -# PrivateDevices=true -# ProtectSystem=true -# ProtectHome=true -# PrivateTmp=true - - -[Install] -WantedBy=multi-user.target -
0
18ccdb43205cfcb91104557a4c5e3eeb058554ac
389ds/389-ds-base
Ticket 49281 - improve db2* tests Bug Description: In lib389 50 we change how db2bak and db2ldif work, so we need to update our tests accordingly Fix Description: Add start/stop as needed, and prevent the raw call to perl tools. https://pagure.io/389-ds-base/issue/49281 Author: wibrown Review by: mreynolds (Thanks!)
commit 18ccdb43205cfcb91104557a4c5e3eeb058554ac Author: William Brown <[email protected]> Date: Tue Jun 6 15:51:39 2017 +1000 Ticket 49281 - improve db2* tests Bug Description: In lib389 50 we change how db2bak and db2ldif work, so we need to update our tests accordingly Fix Description: Add start/stop as needed, and prevent the raw call to perl tools. https://pagure.io/389-ds-base/issue/49281 Author: wibrown Review by: mreynolds (Thanks!) diff --git a/dirsrvtests/tests/suites/basic/basic_test.py b/dirsrvtests/tests/suites/basic/basic_test.py index c548103a7..f9a954a74 100644 --- a/dirsrvtests/tests/suites/basic/basic_test.py +++ b/dirsrvtests/tests/suites/basic/basic_test.py @@ -235,9 +235,11 @@ def test_basic_import_export(topology_st, import_example_ldif): assert False # Offline + topology_st.standalone.stop() if not topology_st.standalone.ldif2db(DEFAULT_BENAME, None, None, None, import_ldif): log.fatal('test_basic_import_export: Offline import failed') assert False + topology_st.standalone.start() # # Test online and offline LDIF export @@ -254,6 +256,7 @@ def test_basic_import_export(topology_st, import_example_ldif): assert False # Offline export + topology_st.standalone.stop() if not topology_st.standalone.db2ldif(DEFAULT_BENAME, (DEFAULT_SUFFIX,), None, None, None, export_ldif): log.fatal('test_basic_import_export: Failed to run offline db2ldif') @@ -302,6 +305,7 @@ def test_basic_backup(topology_st, import_example_ldif): assert False # Test offline backup + topology_st.standalone.stop() if not topology_st.standalone.db2bak(backup_dir): log.fatal('test_basic_backup: Offline backup failed') assert False @@ -310,6 +314,7 @@ def test_basic_backup(topology_st, import_example_ldif): if not topology_st.standalone.bak2db(backup_dir): log.fatal('test_basic_backup: Offline backup failed') assert False + topology_st.standalone.start() log.info('test_basic_backup: PASSED') diff --git a/dirsrvtests/tests/tickets/ticket47536_test.py b/dirsrvtests/tests/tickets/ticket47536_test.py index ef9817f92..8847601aa 100644 --- a/dirsrvtests/tests/tickets/ticket47536_test.py +++ b/dirsrvtests/tests/tickets/ticket47536_test.py @@ -405,10 +405,8 @@ def test_ticket47536(topology_m2): entries = topology_m2.ms["master2"].search_s(DEFAULT_SUFFIX, ldap.SCOPE_SUBTREE, '(uid=*)') assert 20 == len(entries) - db2ldifpl = '%s/db2ldif.pl' % topology_m2.ms["master1"].get_sbin_dir() - cmdline = [db2ldifpl, '-n', 'userRoot', '-Z', SERVERID_MASTER_1, '-D', DN_DM, '-w', PASSWORD] - log.info("##### db2ldif.pl -- %s" % (cmdline)) - doAndPrintIt(cmdline) + output_file = os.path.join(topology_m2.ms["master1"].get_ldif_dir(), "master1.ldif") + topology_m2.ms["master1"].tasks.exportLDIF(benamebase='userRoot', output_file=output_file, args={'wait': True}) log.info("Ticket 47536 - PASSED") diff --git a/dirsrvtests/tests/tickets/ticket48383_test.py b/dirsrvtests/tests/tickets/ticket48383_test.py index b1fa93d11..a147448b3 100644 --- a/dirsrvtests/tests/tickets/ticket48383_test.py +++ b/dirsrvtests/tests/tickets/ticket48383_test.py @@ -69,7 +69,7 @@ def test_ticket48383(topology_st): ldifpath = os.path.join(topology_st.standalone.get_ldif_dir(), "%s.ldif" % SERVERID_STANDALONE) # stop the server - topology_st.standalone.stop(timeout=30) + topology_st.standalone.stop() # Now export and import the DB. It's easier than db2index ... topology_st.standalone.db2ldif(bename=DEFAULT_BENAME, suffixes=[DEFAULT_SUFFIX], excludeSuffixes=[], encrypt=False, repl_data=True, outputfile=ldifpath) @@ -77,6 +77,7 @@ def test_ticket48383(topology_st): result = topology_st.standalone.ldif2db(DEFAULT_BENAME, None, None, False, ldifpath) assert (result) + topology_st.standalone.start() # see if user1 exists at all ....
0
da5bbc5c702b4b853be8a6c94d5f6042b8bce17d
389ds/389-ds-base
Ticket 7 - Incorrect result check Bug Description: Coverity detected an issue where tmp_fd was not checked for null with fopen. Fix Description: Add the correct checks for fopen Add checks for malloc return codes. https://pagure.io/svrcore/issue/7 Author: wibrown Review by: nhosoi (Thanks!)
commit da5bbc5c702b4b853be8a6c94d5f6042b8bce17d Author: William Brown <[email protected]> Date: Tue Apr 12 14:34:09 2016 +1000 Ticket 7 - Incorrect result check Bug Description: Coverity detected an issue where tmp_fd was not checked for null with fopen. Fix Description: Add the correct checks for fopen Add checks for malloc return codes. https://pagure.io/svrcore/issue/7 Author: wibrown Review by: nhosoi (Thanks!) diff --git a/src/file.c b/src/file.c index bb2e437ef..59ebf4d8b 100644 --- a/src/file.c +++ b/src/file.c @@ -153,11 +153,15 @@ getPin(SVRCOREPinObj *ctx, const char *tokenName, PRBool retry) } while(0); /* If adding fails, disable the whole object */ - if (!ent) obj->disabled = PR_TRUE; + if (!ent) { + obj->disabled = PR_TRUE; + } - /* Add to list */ - ent->next = obj->badPinList; - obj->badPinList = ent; + if (ent) { + /* Add to list */ + ent->next = obj->badPinList; + obj->badPinList = ent; + } return 0; } diff --git a/src/pk11.c b/src/pk11.c index 0634732ed..30f8deb64 100644 --- a/src/pk11.c +++ b/src/pk11.c @@ -249,7 +249,7 @@ SVRCORE_Pk11StoreGetPin(char **out, SVRCOREPk11PinStore *store) { SVRCOREError err = SVRCORE_Success; unsigned char *plain; - SECStatus rv; + SECStatus rv = 0; PK11Context *ctx = 0; int outLen; diff --git a/src/systemd-ask-pass.c b/src/systemd-ask-pass.c index c11e0dfbc..171f63e50 100644 --- a/src/systemd-ask-pass.c +++ b/src/systemd-ask-pass.c @@ -179,6 +179,11 @@ getPin(SVRCOREPinObj *obj, const char *tokenName, PRBool retry) char *socket_path = malloc(sizeof(char) * 50); char *ask_path = malloc(sizeof(char) * 50); char *tmp_path = malloc(sizeof(char) * 50); + if (token == NULL || tbuf == NULL || socket_path == NULL + || ask_path == NULL || tmp_path == NULL ) { + err = SVRCORE_NoMemory_Error; + goto out; + } snprintf(socket_path, 50, "%s/sck.%d", path, pid ); snprintf(ask_path, 50, "%s/ask.%d", path, pid ); @@ -240,6 +245,12 @@ getPin(SVRCOREPinObj *obj, const char *tokenName, PRBool retry) umask( S_IWGRP | S_IWOTH ); tmp_fd = fopen(tmp_path, "w"); + if (tmp_fd == NULL) { + fprintf(stderr, "SVRCORE systemd:getPin() -> opening ask file FAILED\n",); + err = SVRCORE_IOOperationError; + goto out; + } + // Create the inf file asking for the password // Write data to the file // [Ask] @@ -259,9 +270,7 @@ getPin(SVRCOREPinObj *obj, const char *tokenName, PRBool retry) // Id=Who wants it // fprintf(tmp_fd, "Id=svrcore\n"); // Icon? - if (tmp_fd != NULL) { - fclose(tmp_fd); - } + fclose(tmp_fd); // rename the file to .ask ?? // -rw-r--r--. 1 root root 127 Mar 22 13:08 ask.9m8ftM
0
596d83cfe6711aca60a303e48bed08a0ad15148a
389ds/389-ds-base
203043 - Support password generation when using the password modify extended operation
commit 596d83cfe6711aca60a303e48bed08a0ad15148a Author: Nathan Kinder <[email protected]> Date: Fri Aug 18 23:03:10 2006 +0000 203043 - Support password generation when using the password modify extended operation diff --git a/ldap/servers/slapd/passwd_extop.c b/ldap/servers/slapd/passwd_extop.c index 40eb16268..d996d06e0 100644 --- a/ldap/servers/slapd/passwd_extop.c +++ b/ldap/servers/slapd/passwd_extop.c @@ -68,6 +68,12 @@ #define LDAP_EXTOP_PASSMOD_TAG_OLDPWD 0x81U #define LDAP_EXTOP_PASSMOD_TAG_NEWPWD 0x82U +/* ber tags for the PasswdModifyResponseValue sequence */ +#define LDAP_EXTOP_PASSMOD_TAG_GENPWD 0x80U + +/* number of bytes used for random password generation */ +#define LDAP_EXTOP_PASSMOD_GEN_PASSWD_LEN 8 + /* OID of the extended operation handled by this plug-in */ #define EXOP_PASSWD_OID "1.3.6.1.4.1.4203.1.11.1" @@ -191,6 +197,34 @@ static int passwd_modify_userpassword(Slapi_Entry *targetEntry, const char *newP return ret; } +/* Generate a new random password */ +static int passwd_modify_generate_passwd(char **genpasswd) +{ + unsigned char data[ LDAP_EXTOP_PASSMOD_GEN_PASSWD_LEN ]; + char enc[ 1 + LDIF_BASE64_LEN( LDAP_EXTOP_PASSMOD_GEN_PASSWD_LEN) ]; + + if (genpasswd == NULL) { + return LDAP_OPERATIONS_ERROR; + } + + /* get 8 random bytes from NSS */ + PK11_GenerateRandom( data, LDAP_EXTOP_PASSMOD_GEN_PASSWD_LEN ); + + /* b64 encode the 8 bytes to get a password made up of + * printable characters. ldif_base64_encode() will + * zero-terminate the string */ + (void)ldif_base64_encode( data, enc, LDAP_EXTOP_PASSMOD_GEN_PASSWD_LEN, -1 ); + + /* This will get freed by the caller */ + *genpasswd = slapi_ch_malloc( 1 + LDAP_EXTOP_PASSMOD_GEN_PASSWD_LEN); + + /* trim the password to the proper length. */ + PL_strncpyz( *genpasswd, enc, 1 + LDAP_EXTOP_PASSMOD_GEN_PASSWD_LEN ); + + return LDAP_SUCCESS; +} + + /* Password Modify Extended operation plugin function */ int passwd_modify_extop( Slapi_PBlock *pb ) @@ -205,22 +239,14 @@ passwd_modify_extop( Slapi_PBlock *pb ) int ret=0, rc=0, sasl_ssf=0; unsigned long tag=0, len=-1; struct berval *extop_value = NULL; + struct berval *gen_passwd = NULL; BerElement *ber = NULL; + BerElement *response_ber = NULL; Slapi_Entry *targetEntry=NULL; Connection *conn = NULL; /* Slapi_DN sdn; */ LDAPDebug( LDAP_DEBUG_TRACE, "=> passwd_modify_extop\n", 0, 0, 0 ); - /* Get the pb ready for sending Password Modify Extended Responses back to the client. - * The only requirement is to set the LDAP OID of the extended response to the EXOP_PASSWD_OID. */ - - if ( slapi_pblock_set( pb, SLAPI_EXT_OP_RET_OID, EXOP_PASSWD_OID ) != 0 ) { - errMesg = "Could not set extended response oid.\n"; - rc = LDAP_OPERATIONS_ERROR; - slapi_log_error( SLAPI_LOG_PLUGIN, "passwd_modify_extop", - errMesg ); - goto free_and_return; - } /* Before going any further, we'll make sure that the right extended operation plugin * has been called: i.e., the OID shipped whithin the extended operation request must @@ -278,22 +304,25 @@ passwd_modify_extop( Slapi_PBlock *pb ) } /* Format of request to parse - * - * PasswdModifyRequestValue ::= SEQUENCE { - * userIdentity [0] OCTET STRING OPTIONAL - * oldPasswd [1] OCTET STRING OPTIONAL - * newPasswd [2] OCTET STRING OPTIONAL } - */ - slapi_pblock_get(pb, SLAPI_EXT_OP_REQ_VALUE, &extop_value); + * + * PasswdModifyRequestValue ::= SEQUENCE { + * userIdentity [0] OCTET STRING OPTIONAL + * oldPasswd [1] OCTET STRING OPTIONAL + * newPasswd [2] OCTET STRING OPTIONAL } + * + * The request value field is optional. If it is + * provided, at least one field must be filled in. + */ /* ber parse code */ if ( ber_scanf( ber, "{") == LBER_ERROR ) { - LDAPDebug( LDAP_DEBUG_ANY, - "ber_scanf failed :{\n", 0, 0, 0 ); - errMesg = "ber_scanf failed\n"; - rc = LDAP_PROTOCOL_ERROR; - goto free_and_return; + /* The request field wasn't provided. We'll + * now try to determine the userid and verify + * knowledge of the old password via other + * means. + */ + goto parse_req_done; } else { tag = ber_peek_tag( ber, &len); } @@ -343,12 +372,9 @@ passwd_modify_extop( Slapi_PBlock *pb ) rc = LDAP_PROTOCOL_ERROR; goto free_and_return; } - } else { - errMesg = "New passwd must be supplied by the user.\n"; - rc = LDAP_PARAM_ERROR; - goto free_and_return; } - + +parse_req_done: /* Uncomment for debugging, otherwise we don't want to leak the password values into the log... */ /* LDAPDebug( LDAP_DEBUG_ARGS, "passwd: dn (%s), oldPasswd (%s) ,newPasswd (%s)\n", dn, oldPasswd, newPasswd); */ @@ -376,13 +402,60 @@ passwd_modify_extop( Slapi_PBlock *pb ) } } - /* We don't implement password generation, so if the request implies - * that they asked us to do that, we must refuse to process it */ - if (newPasswd == NULL || *newPasswd == '\0') { - /* Refuse to handle this operation because we don't allow password generation */ - errMesg = "New passwd must be supplied by the user.\n"; - rc = LDAP_PARAM_ERROR; - goto free_and_return; + /* A new password was not supplied in the request, so we need to generate + * a random one and return it to the user in a response. + */ + if (newPasswd == NULL || *newPasswd == '\0') { + /* Do a free of newPasswd here to be safe, otherwise we may leak 1 byte */ + slapi_ch_free_string( &newPasswd ); + + /* Generate a new password */ + if (passwd_modify_generate_passwd( &newPasswd ) != LDAP_SUCCESS) { + errMesg = "Error generating new password.\n"; + rc = LDAP_OPERATIONS_ERROR; + goto free_and_return; + } + + /* Make sure a passwd was actually generated */ + if (newPasswd == NULL || *newPasswd == '\0') { + errMesg = "Error generating new password.\n"; + rc = LDAP_OPERATIONS_ERROR; + goto free_and_return; + } + + /* + * Create the response message since we generated a new password. + * + * PasswdModifyResponseValue ::= SEQUENCE { + * genPasswd [0] OCTET STRING OPTIONAL } + */ + if ( (response_ber = ber_alloc()) == NULL ) { + rc = LDAP_NO_MEMORY; + goto free_and_return; + } + + if ( LBER_ERROR == ( ber_printf( response_ber, "{" ) ) ) { + ber_free( response_ber, 1 ); + rc = LDAP_ENCODING_ERROR; + goto free_and_return; + } + + if ( LBER_ERROR == ( ber_printf( response_ber, "ts", LDAP_EXTOP_PASSMOD_TAG_GENPWD, + newPasswd ) ) ) { + ber_free( response_ber, 1 ); + rc = LDAP_ENCODING_ERROR; + goto free_and_return; + } + + if ( LBER_ERROR == ( ber_printf( response_ber, "}" ) ) ) { + ber_free( response_ber, 1 ); + rc = LDAP_ENCODING_ERROR; + } + + ber_flatten(response_ber, &gen_passwd); + + /* We're done with response_ber now, so free it */ + ber_free( response_ber, 1 ); } @@ -463,21 +536,25 @@ passwd_modify_extop( Slapi_PBlock *pb ) rc = ret; goto free_and_return; } + + if (gen_passwd && (gen_passwd->bv_val != '\0')) { + /* Set the reponse to let the user know the generated password */ + slapi_pblock_set(pb, SLAPI_EXT_OP_RET_VALUE, gen_passwd); + } LDAPDebug( LDAP_DEBUG_TRACE, "<= passwd_modify_extop: %d\n", rc, 0, 0 ); /* Free anything that we allocated above */ free_and_return: - - slapi_ch_free_string(&oldPasswd); - slapi_ch_free_string(&newPasswd); - /* Either this is the same pointer that we allocated and set above, - or whoever used it should have freed it and allocated a new - value that we need to free here */ + slapi_ch_free_string(&oldPasswd); + slapi_ch_free_string(&newPasswd); + /* Either this is the same pointer that we allocated and set above, + * or whoever used it should have freed it and allocated a new + * value that we need to free here */ slapi_pblock_get( pb, SLAPI_ORIGINAL_TARGET, &dn ); - slapi_ch_free_string(&dn); + slapi_ch_free_string(&dn); slapi_pblock_set( pb, SLAPI_ORIGINAL_TARGET, NULL ); - slapi_ch_free_string(&authmethod); + slapi_ch_free_string(&authmethod); if ( targetEntry != NULL ){ slapi_entry_free (targetEntry); @@ -493,6 +570,9 @@ passwd_modify_extop( Slapi_PBlock *pb ) send_ldap_result( pb, rc, NULL, errMesg, 0, NULL ); + /* We can free the generated password bval now */ + ber_bvfree(gen_passwd); + return( SLAPI_PLUGIN_EXTENDED_SENT_RESULT ); }/* passwd_modify_extop */
0
34635fbff3f82edca50fbb0582d62b170722addf
389ds/389-ds-base
Ticket 48103 - update DS for new nunc-stans header file Description: Remove references to ns_thrpool.h, and replace it with nunc-stans.h Also the function params for ns_add_job needed to be updated. https://fedorahosted.org/389/ticket/48103 Reviewed by: rmeggins(Thanks!)
commit 34635fbff3f82edca50fbb0582d62b170722addf Author: Mark Reynolds <[email protected]> Date: Fri Mar 6 11:32:00 2015 -0500 Ticket 48103 - update DS for new nunc-stans header file Description: Remove references to ns_thrpool.h, and replace it with nunc-stans.h Also the function params for ns_add_job needed to be updated. https://fedorahosted.org/389/ticket/48103 Reviewed by: rmeggins(Thanks!) diff --git a/configure b/configure index e1e0525b6..8d8ca080f 100755 --- a/configure +++ b/configure @@ -21325,7 +21325,7 @@ $as_echo "using $withval" >&6; } nunc_stans_lib="-L$withval/lib" nunc_stans_libdir="$withval/lib" nunc_stans_incdir="$withval/include" - if ! test -e "$nunc_stans_incdir/nunc-stans/ns_thrpool.h" ; then + if ! test -e "$nunc_stans_incdir/nunc-stans/nunc-stans.h" ; then as_fn_error $? "$withval include dir not found" "$LINENO" 5 fi nunc_stans_inc="-I$nunc_stans_incdir" @@ -21347,7 +21347,7 @@ $as_echo_n "checking for --with-nunc-stans-inc... " >&6; } # Check whether --with-nunc-stans-inc was given. if test "${with_nunc_stans_inc+set}" = set; then : withval=$with_nunc_stans_inc; - if test -e "$withval"/nunc-stans/ns_thrpool.h + if test -e "$withval"/nunc-stans/nunc-stans.h then { $as_echo "$as_me:${as_lineno-$LINENO}: result: using $withval" >&5 $as_echo "using $withval" >&6; } diff --git a/ldap/servers/slapd/daemon.c b/ldap/servers/slapd/daemon.c index 07d57b84c..b37ca6d3a 100644 --- a/ldap/servers/slapd/daemon.c +++ b/ldap/servers/slapd/daemon.c @@ -3278,7 +3278,7 @@ ns_handle_new_connection(struct ns_job_t *job) */ c->c_tp = ns_job_get_tp(job); connection_acquire_nolock(c); /* event framework now has ref */ - ns_add_job(ns_job_get_tp(job), NULL, NS_JOB_NONE, ns_handle_pr_read_ready, c); + ns_add_job(ns_job_get_tp(job), NS_JOB_NONE, ns_handle_pr_read_ready, c, NULL); return; } #endif diff --git a/ldap/servers/slapd/slap.h b/ldap/servers/slapd/slap.h index 8a0d11a84..6447ee591 100644 --- a/ldap/servers/slapd/slap.h +++ b/ldap/servers/slapd/slap.h @@ -173,7 +173,7 @@ typedef struct symbol_t { #include "uuid.h" #ifdef ENABLE_NUNC_STANS -#include <nunc-stans/ns_thrpool.h> +#include <nunc-stans/nunc-stans.h> #endif #if defined(OS_solaris) diff --git a/m4/nunc-stans.m4 b/m4/nunc-stans.m4 index 91ba72e0a..a2137d3e8 100644 --- a/m4/nunc-stans.m4 +++ b/m4/nunc-stans.m4 @@ -34,7 +34,7 @@ AC_ARG_WITH(nunc-stans, AS_HELP_STRING([--with-nunc-stans@<:@=PATH@:>@],[nunc-st nunc_stans_lib="-L$withval/lib" nunc_stans_libdir="$withval/lib" nunc_stans_incdir="$withval/include" - if ! test -e "$nunc_stans_incdir/nunc-stans/ns_thrpool.h" ; then + if ! test -e "$nunc_stans_incdir/nunc-stans/nunc-stans.h" ; then AC_MSG_ERROR([$withval include dir not found]) fi nunc_stans_inc="-I$nunc_stans_incdir" @@ -49,7 +49,7 @@ AC_MSG_RESULT(no)) AC_MSG_CHECKING(for --with-nunc-stans-inc) AC_ARG_WITH(nunc-stans-inc, AS_HELP_STRING([--with-nunc-stans-inc=PATH],[nunc-stans include file directory]), [ - if test -e "$withval"/nunc-stans/ns_thrpool.h + if test -e "$withval"/nunc-stans/nunc-stans.h then AC_MSG_RESULT([using $withval]) nunc_stans_incdir="$withval"
0
e6a8fd3f45a96fbb7da3e472c36382d59fadad4e
389ds/389-ds-base
Resolves: 445305 Summary: Ensure directories created by installer get the requested mode applied.
commit e6a8fd3f45a96fbb7da3e472c36382d59fadad4e Author: Nathan Kinder <[email protected]> Date: Wed Dec 17 17:22:22 2008 +0000 Resolves: 445305 Summary: Ensure directories created by installer get the requested mode applied. diff --git a/ldap/admin/src/scripts/DSCreate.pm.in b/ldap/admin/src/scripts/DSCreate.pm.in index 9430cf2dd..efb1fa651 100644 --- a/ldap/admin/src/scripts/DSCreate.pm.in +++ b/ldap/admin/src/scripts/DSCreate.pm.in @@ -160,6 +160,7 @@ sub changeOwnerMode { my $uid = getpwnam $inf->{General}->{SuiteSpotUserID}; my $gid = -1; # default to leave it alone + my $mode_string = ""; if (defined($inf->{General}->{SuiteSpotGroup})) { $gid = getgrnam $inf->{General}->{SuiteSpotGroup}; @@ -171,6 +172,10 @@ sub changeOwnerMode { if ($!) { return ('error_chmoding_file', $it, $!); } + + $mode_string = sprintf "%lo", $mode; + debug(1, "changeOwnerMode: changed mode of $it to $mode_string\n"); + $! = 0; # clear errno if ( $gidonly ) { chown -1, $gid, $it; @@ -181,6 +186,12 @@ sub changeOwnerMode { return ('error_chowning_file', $it, $inf->{General}->{SuiteSpotUserID}, $!); } + if ( $gidonly ) { + debug(1, "changeOwnerMode: changed group ownership of $it to group $gid\n"); + } else { + debug(1, "changeOwnerMode: changed ownership of $it to user $uid group $gid\n"); + } + return (); } diff --git a/ldap/admin/src/scripts/Util.pm.in b/ldap/admin/src/scripts/Util.pm.in index 9600fc9b2..20aea64b7 100644 --- a/ldap/admin/src/scripts/Util.pm.in +++ b/ldap/admin/src/scripts/Util.pm.in @@ -860,6 +860,7 @@ sub makePaths { my ($path, $mode, $user, $group) = @_; my $uid = getpwnam $user; my $gid = -1; # default to leave it alone + my $mode_string = ""; if ($group) { $gid = getgrnam $group; @@ -882,7 +883,10 @@ sub makePaths { if ($!) { return ('error_chowning_directory', $_, $!); } - debug(1, "makePaths: created directory $_ mode $mode user $user group $group\n"); + chmod $mode, $_; + $mode_string = sprintf "%lo", $mode; + debug(1, "makePaths: created directory $_ mode $mode_string user $user group $group\n"); + debug(2, "\t" . `ls -ld $_`); } return (); diff --git a/ldap/servers/slapd/snmp_collator.c b/ldap/servers/slapd/snmp_collator.c index 9aefadce9..9fb629d28 100644 --- a/ldap/servers/slapd/snmp_collator.c +++ b/ldap/servers/slapd/snmp_collator.c @@ -528,17 +528,22 @@ snmp_collator_create_semaphore() if (errno == EEXIST) { /* It appears that we didn't exit cleanly last time and left the semaphore * around. Recreate it since we don't know what state it is in. */ - sem_unlink(stats_sem_name); + if (sem_unlink(stats_sem_name) != 0) { + LDAPDebug( LDAP_DEBUG_ANY, "Failed to delete old semaphore for stats file (%s). " + "Error %d (%s).\n", szStatsFile, errno, slapd_system_strerror(errno) ); + exit(1); + } + if ((stats_sem = sem_open(stats_sem_name, O_CREAT | O_EXCL, SLAPD_DEFAULT_FILE_MODE, 1)) == SEM_FAILED) { /* No dice */ - LDAPDebug( LDAP_DEBUG_ANY, "Failed to create semaphore for stats file (%s). Error %d.\n", - szStatsFile, errno, 0 ); + LDAPDebug( LDAP_DEBUG_ANY, "Failed to create semaphore for stats file (%s). Error %d (%s).\n", + szStatsFile, errno, slapd_system_strerror(errno) ); exit(1); } } else { /* Some other problem occurred creating the semaphore. */ - LDAPDebug( LDAP_DEBUG_ANY, "Failed to create semaphore for stats file (%s). Error %d.\n", - szStatsFile, errno, 0 ); + LDAPDebug( LDAP_DEBUG_ANY, "Failed to create semaphore for stats file (%s). Error %d.(%s)\n", + szStatsFile, errno, slapd_system_strerror(errno) ); exit(1); } }
0
aa86616ef8fa462a064573d1708cbd7202496592
389ds/389-ds-base
Bug 619122 - fix coverify Defect Type: Resource leaks issues CID 11975 - 12053 https://bugzilla.redhat.com/show_bug.cgi?id=619122 Resolves: bug 619122 Bug description: fix coverify Defect Type: Resource leaks issues CID 11976. description: The ACLEvalBuildContext() has been modified to release curauthplist when an error occurs.
commit aa86616ef8fa462a064573d1708cbd7202496592 Author: Endi S. Dewata <[email protected]> Date: Wed Jul 28 12:26:33 2010 -0500 Bug 619122 - fix coverify Defect Type: Resource leaks issues CID 11975 - 12053 https://bugzilla.redhat.com/show_bug.cgi?id=619122 Resolves: bug 619122 Bug description: fix coverify Defect Type: Resource leaks issues CID 11976. description: The ACLEvalBuildContext() has been modified to release curauthplist when an error occurs. diff --git a/lib/libaccess/oneeval.cpp b/lib/libaccess/oneeval.cpp index 83b98deea..8056e0ec3 100644 --- a/lib/libaccess/oneeval.cpp +++ b/lib/libaccess/oneeval.cpp @@ -542,6 +542,8 @@ ACLEvalBuildContext( return 0; error: + if (curauthplist) + PListDestroy(curauthplist); if (absauthplist) PListDestroy(absauthplist); if (cache) {
0
55106fe77d2c834b0ba866d440bb8ce08c1d01ff
389ds/389-ds-base
Bug 751645 - crash when simple paged fails to send entry to client https://bugzilla.redhat.com/show_bug.cgi?id=751645 Resolves: bug 751645 Bug Description: crash when simple paged fails to send entry to client Reviewed by: nkinder,nhosoi (Thanks!) Branch: master Fix Description: The crash happens when the server is sending back the paged result entry responses to the client and there is a problem with the connection e.g. the client closes the socket while the server is doing the PR_Send/PR_Write on the client socket. If the reader thread in connection_read_operation() sees the close first, it will call disconnect_server() to disconnect the socket and cleanup the pagedresult structure back_search_result_set in the Connection*. The problem with this is that it leaves a dangling reference to the pagedresult structures in the writer thread in ldbm_back_next_search_entry_ext. When that code sees the error from the write, it will also attempt to free the search result, and will get an invalid or double free error. The solution is to not do the pagedresults_cleanup in disconnect_server(), but instead allow the writer thread to do the cleanup safely. The connection_cleanup() function will call pagedresults_cleanup() to avoid any memory leaks. The only thing the disconnect_server() function needs to do is to reset the c_timelimit to avoid the "slapd stops responding" and "simple paged results timeout" problems. Platforms tested: RHEL6 x86_64 Flag Day: no Doc impact: no
commit 55106fe77d2c834b0ba866d440bb8ce08c1d01ff Author: Rich Megginson <[email protected]> Date: Wed Nov 9 13:05:39 2011 -0700 Bug 751645 - crash when simple paged fails to send entry to client https://bugzilla.redhat.com/show_bug.cgi?id=751645 Resolves: bug 751645 Bug Description: crash when simple paged fails to send entry to client Reviewed by: nkinder,nhosoi (Thanks!) Branch: master Fix Description: The crash happens when the server is sending back the paged result entry responses to the client and there is a problem with the connection e.g. the client closes the socket while the server is doing the PR_Send/PR_Write on the client socket. If the reader thread in connection_read_operation() sees the close first, it will call disconnect_server() to disconnect the socket and cleanup the pagedresult structure back_search_result_set in the Connection*. The problem with this is that it leaves a dangling reference to the pagedresult structures in the writer thread in ldbm_back_next_search_entry_ext. When that code sees the error from the write, it will also attempt to free the search result, and will get an invalid or double free error. The solution is to not do the pagedresults_cleanup in disconnect_server(), but instead allow the writer thread to do the cleanup safely. The connection_cleanup() function will call pagedresults_cleanup() to avoid any memory leaks. The only thing the disconnect_server() function needs to do is to reset the c_timelimit to avoid the "slapd stops responding" and "simple paged results timeout" problems. Platforms tested: RHEL6 x86_64 Flag Day: no Doc impact: no diff --git a/ldap/servers/slapd/connection.c b/ldap/servers/slapd/connection.c index b95759a1f..27e4fe10e 100644 --- a/ldap/servers/slapd/connection.c +++ b/ldap/servers/slapd/connection.c @@ -2766,9 +2766,7 @@ disconnect_server_nomutex( Connection *conn, PRUint64 opconnid, int opid, PRErro conn->c_gettingber = 0; connection_abandon_operations( conn ); - - pagedresults_cleanup(conn, 0 /* already locked */); /* In case the connection is on pagedresult. - Better to call it after the op is abandened. */ + conn->c_timelimit = 0; /* needed here to ensure simple paged results timeout properly and don't impact subsequent ops */ if (! config_check_referral_mode()) { /*
0
4569c95e91282a57b4b4a0a27f783cbea7bb0f59
389ds/389-ds-base
Ticket 551 - Multivalued rootdn-days-allowed in RootDN Access Control plugin always results in access control violation Bug Description: The server allows you to add multiple rootdn-days-allowed attributes. Fix Description: The attribute needs to be single valued. Added rootdn plugin attributes to schema, and improved dse schema checking at server startupi & setup. https://fedorahosted.org/389/ticket/551 Reviewed by: Noriko(Thanks!)
commit 4569c95e91282a57b4b4a0a27f783cbea7bb0f59 Author: Mark Reynolds <[email protected]> Date: Thu Jan 10 11:52:31 2013 -0500 Ticket 551 - Multivalued rootdn-days-allowed in RootDN Access Control plugin always results in access control violation Bug Description: The server allows you to add multiple rootdn-days-allowed attributes. Fix Description: The attribute needs to be single valued. Added rootdn plugin attributes to schema, and improved dse schema checking at server startupi & setup. https://fedorahosted.org/389/ticket/551 Reviewed by: Noriko(Thanks!) diff --git a/ldap/ldif/template-dse.ldif.in b/ldap/ldif/template-dse.ldif.in index b854c4746..95ed60cfd 100644 --- a/ldap/ldif/template-dse.ldif.in +++ b/ldap/ldif/template-dse.ldif.in @@ -741,7 +741,7 @@ nsslapd-plugin-depends-on-type: database dn: cn=RootDN Access Control,cn=plugins,cn=config objectclass: top objectclass: nsSlapdPlugin -objectclass: extensibleObject +objectclass: rootDNPluginConfig cn: RootDN Access Control nsslapd-pluginpath: librootdn-access-plugin.so nsslapd-plugininitfunc: rootdn_init diff --git a/ldap/schema/01core389.ldif b/ldap/schema/01core389.ldif index 1c9112fc1..7fe8b13fc 100644 --- a/ldap/schema/01core389.ldif +++ b/ldap/schema/01core389.ldif @@ -141,11 +141,19 @@ attributeTypes: ( 2.16.840.1.113730.3.1.2137 NAME 'nsds5ReplicaAbortCleanRUV' DE attributeTypes: ( 2.16.840.1.113730.3.1.2111 NAME 'tombstoneNumSubordinates' DESC 'count of immediate subordinates for tombstone entries' EQUALITY integerMatch ORDERING integerOrderingMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE NO-USER-MODIFICATION USAGE directoryOperation X-ORIGIN '389 directory server' ) attributeTypes: ( 2.16.840.1.113730.3.1.2138 NAME 'nsslapd-readonly' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) attributeTypes: ( 2.16.840.1.113730.3.1.2143 NAME 'nsslapd-sasl-mapping-fallback' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2144 NAME 'rootdn-open-time' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2145 NAME 'rootdn-close-time' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2146 NAME 'rootdn-days-allowed' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2147 NAME 'rootdn-allow-host' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2148 NAME 'rootdn-deny-host' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2149 NAME 'rootdn-allow-ip' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2150 NAME 'rootdn-deny-ip' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2151 NAME 'nsslapd-plugin-depends-on-type' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 X-ORIGIN 'Netscape Directory Server' ) # # objectclasses # objectClasses: ( 2.16.840.1.113730.3.2.40 NAME 'directoryServerFeature' DESC 'Netscape defined objectclass' SUP top MAY ( oid $ cn $ multiLineDescription ) X-ORIGIN 'Netscape Directory Server' ) -objectClasses: ( 2.16.840.1.113730.3.2.41 NAME 'nsslapdPlugin' DESC 'Netscape defined objectclass' SUP top MUST ( cn $ nsslapd-pluginPath $ nsslapd-pluginInitFunc $ nsslapd-pluginType $ nsslapd-pluginId $ nsslapd-pluginVersion $ nsslapd-pluginVendor $ nsslapd-pluginDescription $ nsslapd-pluginEnabled ) MAY ( nsslapd-pluginConfigArea ) X-ORIGIN 'Netscape Directory Server' ) +objectClasses: ( 2.16.840.1.113730.3.2.41 NAME 'nsslapdPlugin' DESC 'Netscape defined objectclass' SUP top MUST ( cn $ nsslapd-pluginPath $ nsslapd-pluginInitFunc $ nsslapd-pluginType $ nsslapd-pluginId $ nsslapd-pluginVersion $ nsslapd-pluginVendor $ nsslapd-pluginDescription $ nsslapd-pluginEnabled ) MAY ( nsslapd-pluginConfigArea $ nsslapd-plugin-depends-on-type ) X-ORIGIN 'Netscape Directory Server' ) objectClasses: ( 2.16.840.1.113730.3.2.44 NAME 'nsIndex' DESC 'Netscape defined objectclass' SUP top MUST ( cn $ nsSystemIndex ) MAY ( description $ nsIndexType $ nsMatchingRule ) X-ORIGIN 'Netscape Directory Server' ) objectClasses: ( 2.16.840.1.113730.3.2.109 NAME 'nsBackendInstance' DESC 'Netscape defined objectclass' SUP top MUST ( CN ) X-ORIGIN 'Netscape Directory Server' ) objectClasses: ( 2.16.840.1.113730.3.2.110 NAME 'nsMappingTree' DESC 'Netscape defined objectclass' SUP top MUST ( CN ) X-ORIGIN 'Netscape Directory Server' ) @@ -158,3 +166,5 @@ objectClasses: ( 2.16.840.1.113730.3.2.317 NAME 'nsSaslMapping' DESC 'Netscape d objectClasses: ( 2.16.840.1.113730.3.2.43 NAME 'nsSNMP' DESC 'Netscape defined objectclass' SUP top MUST ( cn $ nsSNMPEnabled ) MAY ( nsSNMPOrganization $ nsSNMPLocation $ nsSNMPContact $ nsSNMPDescription $ nsSNMPName $ nsSNMPMasterHost $ nsSNMPMasterPort ) X-ORIGIN 'Netscape Directory Server' ) objectClasses: ( nsEncryptionConfig-oid NAME 'nsEncryptionConfig' DESC 'Netscape defined objectclass' SUP top MUST ( cn ) MAY ( nsCertfile $ nsKeyfile $ nsSSL2 $ nsSSL3 $ nsTLS1 $ nsSSLSessionTimeout $ nsSSL3SessionTimeout $ nsSSLClientAuth $ nsSSL2Ciphers $ nsSSL3Ciphers $ nsSSLSupportedCiphers) X-ORIGIN 'Netscape' ) objectClasses: ( nsEncryptionModule-oid NAME 'nsEncryptionModule' DESC 'Netscape defined objectclass' SUP top MUST ( cn ) MAY ( nsSSLToken $ nsSSLPersonalityssl $ nsSSLActivation ) X-ORIGIN 'Netscape' ) +objectClasses: ( 2.16.840.1.113730.3.2.327 NAME 'rootDNPluginConfig' DESC 'Netscape defined objectclass' SUP top MUST ( cn ) MAY ( rootdn-open-time $ rootdn-close-time $ rootdn-days-allowed $ rootdn-allow-host $ rootdn-deny-host $ rootdn-allow-ip $ rootdn-deny-ip ) X-ORIGIN 'Netscape' ) + diff --git a/ldap/servers/slapd/dse.c b/ldap/servers/slapd/dse.c index fd404321f..75b9502ee 100644 --- a/ldap/servers/slapd/dse.c +++ b/ldap/servers/slapd/dse.c @@ -81,6 +81,7 @@ #define SLAPI_DSE_TRACELEVEL LDAP_DEBUG_TRACE #endif /* SLAPI_DSE_DEBUG */ +#define SCHEMA_VIOLATION -2 #define STOP_TRAVERSAL -2 /* This is returned by dupentry_replace if the duplicate entry was found and @@ -704,9 +705,9 @@ dse_read_one_file(struct dse *pdse, const char *filename, Slapi_PBlock *pb, if ( (NULL != pdse) && (NULL != filename) ) { /* check if the "real" file exists and cam be used, if not try tmp as backup */ - rc = dse_check_file((char *)filename, pdse->dse_tmpfile); - if (!rc) - rc = dse_check_file((char *)filename, pdse->dse_fileback); + rc = dse_check_file((char *)filename, pdse->dse_tmpfile); + if (!rc) + rc = dse_check_file((char *)filename, pdse->dse_fileback); if ( (rc = PR_GetFileInfo( filename, &prfinfo )) != PR_SUCCESS ) { @@ -799,9 +800,14 @@ dse_read_one_file(struct dse *pdse, const char *filename, Slapi_PBlock *pb, DSE_FLAG_PREOP, e, NULL, &returncode, returntext) == SLAPI_DSE_CALLBACK_OK) { - /* this will free the entry if not added, so it is - definitely consumed by this call */ - dse_add_entry_pb(pdse, e, pb); + /* + * This will free the entry if not added, so it is + * definitely consumed by this call + */ + if(dse_add_entry_pb(pdse, e, pb) == SCHEMA_VIOLATION){ + /* schema violation, return failure */ + rc = 0; + } } else /* free entry if not used */ { @@ -1119,7 +1125,11 @@ dse_write_entry( caddr_t data, caddr_t arg ) /* * Adds an entry to the dse backend. The passed in entry will be - * free'd always. */ + * free'd always. + * + * return -1 for duplicate entry + * return -2 for schema violation (SCHEMA_VIOLATION) + */ static int dse_add_entry_pb(struct dse* pdse, Slapi_Entry *e, Slapi_PBlock *pb) { @@ -1190,7 +1200,9 @@ dse_add_entry_pb(struct dse* pdse, Slapi_Entry *e, Slapi_PBlock *pb) * Verify that the new or merged entry conforms to the schema. * Errors are logged by slapi_entry_schema_check(). */ - (void)slapi_entry_schema_check( pb, schemacheckentry ); + if(slapi_entry_schema_check( pb, schemacheckentry )){ + rc = SCHEMA_VIOLATION; + } slapi_entry_free(schemacheckentry); }
0
af1287767d2b1cfb52204949699c8e9ed62aae0b
389ds/389-ds-base
Issue 5236 - UI add specialized group edit modal Description: Added a modal for handling groups: viewing, adding and removing members Revised overall project: - "Search Base" handling using a label button was not intuitive. Changed it a more recognizable href. - Made table "trash Can" icons visibly clickable - Edit/add entry wizard, the big red "Empty Value!" label is no longer displayed while you edit the value relates: https://github.com/389ds/389-ds-base/issues/5236 Reviewed by: spichugi(Thanks!)
commit af1287767d2b1cfb52204949699c8e9ed62aae0b Author: Mark Reynolds <[email protected]> Date: Wed Nov 30 12:33:04 2022 -0500 Issue 5236 - UI add specialized group edit modal Description: Added a modal for handling groups: viewing, adding and removing members Revised overall project: - "Search Base" handling using a label button was not intuitive. Changed it a more recognizable href. - Made table "trash Can" icons visibly clickable - Edit/add entry wizard, the big red "Empty Value!" label is no longer displayed while you edit the value relates: https://github.com/389ds/389-ds-base/issues/5236 Reviewed by: spichugi(Thanks!) diff --git a/src/cockpit/389-console/README.md b/src/cockpit/389-console/README.md index 95648daa0..cc25d5c3f 100644 --- a/src/cockpit/389-console/README.md +++ b/src/cockpit/389-console/README.md @@ -162,7 +162,7 @@ To test changes to the 389-console plugin, you can set up links from your worksp - Create cockpit directory under user's home directory - mkdir ~/.local/share/cockpit/389-console + mkdir ~/.local/share/cockpit - Link your workspace directory diff --git a/src/cockpit/389-console/src/css/ds.css b/src/cockpit/389-console/src/css/ds.css index 47c9bdd14..967575702 100644 --- a/src/cockpit/389-console/src/css/ds.css +++ b/src/cockpit/389-console/src/css/ds.css @@ -88,6 +88,10 @@ td { color: #f0ab00 !important; } +.ds-pf-green-color { + color: green !important; +} + .ds-editor-tree { max-height: 70vh; overflow: auto; @@ -112,6 +116,10 @@ td { text-align: right; } +.ds-left-align { + text-align: left !important; +} + .ds-label { /* mimics PF4 FormGroup Label */ font-size: 14px; @@ -244,11 +252,11 @@ textarea { } .ds-float-right { - float: right; + float: right !important; } .ds-float-left { - float: left; + float: left !important; } .ds-config-header { diff --git a/src/cockpit/389-console/src/lib/database/databaseTables.jsx b/src/cockpit/389-console/src/lib/database/databaseTables.jsx index 39c23d5d3..976e467e3 100644 --- a/src/cockpit/389-console/src/lib/database/databaseTables.jsx +++ b/src/cockpit/389-console/src/lib/database/databaseTables.jsx @@ -54,13 +54,15 @@ class ReferralTable extends React.Component { getDeleteButton(name) { return ( - <TrashAltIcon - className="ds-center" - onClick={() => { - this.props.deleteRef(name); - }} - title="Delete this referral" - /> + <a> + <TrashAltIcon + className="ds-center" + onClick={() => { + this.props.deleteRef(name); + }} + title="Delete this referral" + /> + </a> ); } @@ -317,13 +319,15 @@ class EncryptedAttrTable extends React.Component { getDeleteButton(name) { return ( - <TrashAltIcon - className="ds-center" - onClick={() => { - this.props.deleteAttr(name); - }} - title="Delete this attribute" - /> + <a> + <TrashAltIcon + className="ds-center" + onClick={() => { + this.props.deleteAttr(name); + }} + title="Delete this attribute" + /> + </a> ); } diff --git a/src/cockpit/389-console/src/lib/ldap_editor/lib/editableTable.jsx b/src/cockpit/389-console/src/lib/ldap_editor/lib/editableTable.jsx index bf40f48cb..9463de61a 100644 --- a/src/cockpit/389-console/src/lib/ldap_editor/lib/editableTable.jsx +++ b/src/cockpit/389-console/src/lib/ldap_editor/lib/editableTable.jsx @@ -451,19 +451,17 @@ class EditableTable extends React.Component { } }, { - title: (value, rowIndex, cellIndex, props) => ( <React.Fragment> <EditableTextCell // isDisabled={myData.isDisabled} - value={value !== "" ? "********" : ""} + value={value !== "" ? "********" : <Label color="red" icon={<InfoCircleIcon />}> Empty value! </Label>} rowIndex={rowIndex} cellIndex={cellIndex} props={props} handleTextInputChange={this.handleTextInputChange} inputAriaLabel={'_' + value} // To avoid empty property when value is empty. /> - { value === '' && <Label color="red" icon={<InfoCircleIcon />}> Empty value! </Label> } </React.Fragment> ), props: { @@ -521,14 +519,13 @@ class EditableTable extends React.Component { <React.Fragment> <EditableTextCell // isDisabled={myData.isDisabled} - value={value} + value={value === "" ? <Label color="red" icon={<InfoCircleIcon />}> Empty value! </Label> : value} rowIndex={rowIndex} cellIndex={cellIndex} props={props} handleTextInputChange={this.handleTextInputChange} inputAriaLabel={'_' + value} // To avoid empty property when value is empty. /> - { value === '' && <Label color="red" icon={<InfoCircleIcon />}> Empty value! </Label> } </React.Fragment> ), props: { diff --git a/src/cockpit/389-console/src/lib/ldap_editor/lib/utils.jsx b/src/cockpit/389-console/src/lib/ldap_editor/lib/utils.jsx index 9b54387fd..324b0fbcc 100644 --- a/src/cockpit/389-console/src/lib/ldap_editor/lib/utils.jsx +++ b/src/cockpit/389-console/src/lib/ldap_editor/lib/utils.jsx @@ -1250,3 +1250,12 @@ export function isValidLDAPUrl (url) { } return false; } + +export function getBaseDNFromTree (entrydn, treeViewRootSuffixes) { + for (const suffixObj of treeViewRootSuffixes) { + if (entrydn.toLowerCase().indexOf(suffixObj.name.toLowerCase()) !== -1) { + return suffixObj.name; + } + } + return ""; +} diff --git a/src/cockpit/389-console/src/lib/ldap_editor/wizards/genericWizard.jsx b/src/cockpit/389-console/src/lib/ldap_editor/wizards/genericWizard.jsx index af74ff716..56433317b 100644 --- a/src/cockpit/389-console/src/lib/ldap_editor/wizards/genericWizard.jsx +++ b/src/cockpit/389-console/src/lib/ldap_editor/wizards/genericWizard.jsx @@ -19,40 +19,37 @@ class GenericWizard extends React.Component { setWizardOperationInfo: this.props.setWizardOperationInfo, onReload: this.props.onReload, onModrdnReload: this.props.onModrdnReload, - addNotification: this.props.addNotification + addNotification: this.props.addNotification, + // LDAP Data + treeViewRootSuffixes: this.props.treeViewRootSuffixes, + allObjectclasses: this.props.allObjectclasses, }; switch (this.props.wizardName) { case ENTRY_MENU.acis: return <AciWizard {...wizardProps } - treeViewRootSuffixes={this.props.treeViewRootSuffixes} />; case ENTRY_MENU.new: return <NewEntryWizard {...wizardProps } - allObjectclasses={this.props.allObjectclasses} - treeViewRootSuffixes={this.props.treeViewRootSuffixes} />; case ENTRY_MENU.edit: return <EditLdapEntry {...wizardProps} - allObjectclasses={this.props.allObjectclasses} />; case ENTRY_MENU.rename: return <RenameEntry {...wizardProps} - allObjectclasses={this.props.allObjectclasses} - treeViewRootSuffixes={this.props.treeViewRootSuffixes} />; case ENTRY_MENU.cos: return <CoSEntryWizard {...wizardProps} - allObjectclasses={this.props.allObjectclasses} - treeViewRootSuffixes={this.props.treeViewRootSuffixes} />; case ENTRY_MENU.delete: - return <DeleteOperationWizard {...wizardProps } />; + return <DeleteOperationWizard + {...wizardProps } + />; default: console.log(`Unknown Wizard in GenericWizard class: ${this.props.wizardName}`); return null; diff --git a/src/cockpit/389-console/src/lib/ldap_editor/wizards/operations/aciNew.jsx b/src/cockpit/389-console/src/lib/ldap_editor/wizards/operations/aciNew.jsx index ba5482ce8..3f086d966 100644 --- a/src/cockpit/389-console/src/lib/ldap_editor/wizards/operations/aciNew.jsx +++ b/src/cockpit/389-console/src/lib/ldap_editor/wizards/operations/aciNew.jsx @@ -13,8 +13,6 @@ import { Form, FormHelperText, FormSelect, FormSelectOption, Grid, GridItem, HelperText, HelperTextItem, - InputGroup, - Label, Modal, ModalVariant, SearchInput, Select, SelectOption, SelectVariant, @@ -892,10 +890,19 @@ class AddNewAci extends React.Component { /> } <div className="ds-margin-bottom-md" /> - <Label onClick={this.onUsersDrawerClick} href="#" variant="outline" color="blue" icon={<InfoCircleIcon />}> - Search Base DN - </Label> - <strong>&nbsp;&nbsp;{usersSearchBaseDn}</strong> + <TextContent> + <Text> + Search Base: + <Text + className="ds-left-margin" + component={TextVariants.a} + onClick={this.onUsersDrawerClick} + href="#" + > + {usersSearchBaseDn} + </Text> + </Text> + </TextContent> <Drawer className="ds-margin-top" isExpanded={isUsersDrawerExpanded} onExpand={this.onDrawerExpand}> <DrawerContent panelContent={usersPanelContent}> diff --git a/src/cockpit/389-console/src/lib/ldap_editor/wizards/operations/addCosDefinition.jsx b/src/cockpit/389-console/src/lib/ldap_editor/wizards/operations/addCosDefinition.jsx index 4233adf07..9c8b60568 100644 --- a/src/cockpit/389-console/src/lib/ldap_editor/wizards/operations/addCosDefinition.jsx +++ b/src/cockpit/389-console/src/lib/ldap_editor/wizards/operations/addCosDefinition.jsx @@ -345,7 +345,7 @@ class AddCoS extends React.Component { this.setState({ cosAttrRows, attributeList, - tableModificationTime + tableModificationTime }); }); this.setState({ @@ -910,10 +910,19 @@ class AddCoS extends React.Component { </TextContent> </GridItem> <GridItem span={9} className="ds-margin-top-xlg"> - <Label onClick={this.openLDAPNavModal} href="#" variant="outline" color="blue" icon={<InfoCircleIcon />}> - Search Base DN - </Label> - <strong>&nbsp;&nbsp;{cosSearchBaseDn}</strong> + <TextContent> + <Text> + Search Base: + <Text + className="ds-left-margin" + component={TextVariants.a} + onClick={this.openLDAPNavModal} + href="#" + > + {cosSearchBaseDn} + </Text> + </Text> + </TextContent> </GridItem> <GridItem span={3} className="ds-margin-top-xlg ds-right-align"> <Button @@ -937,7 +946,7 @@ class AddCoS extends React.Component { CoS Template Selected: <strong>&nbsp;&nbsp;{cosTemplateDNSelected}</strong> </GridItem> <GridItem span={12} className="ds-margin-top-xlg"> - {(cosAvailableOptions.length !== 0) ? + {(cosAvailableOptions.length !== 0) ? <SimpleList onSelect={this.onSelectTemplate}> {cosAvailableOptions} </SimpleList> diff --git a/src/cockpit/389-console/src/lib/ldap_editor/wizards/operations/addGroup.jsx b/src/cockpit/389-console/src/lib/ldap_editor/wizards/operations/addGroup.jsx index 9873e625b..767bfce07 100644 --- a/src/cockpit/389-console/src/lib/ldap_editor/wizards/operations/addGroup.jsx +++ b/src/cockpit/389-console/src/lib/ldap_editor/wizards/operations/addGroup.jsx @@ -30,7 +30,8 @@ import { import LdapNavigator from '../../lib/ldapNavigator.jsx'; import { createLdapEntry, - runGenericSearch + runGenericSearch, + decodeLine } from '../../lib/utils.jsx'; import { InfoCircleIcon @@ -478,10 +479,19 @@ class AddGroup extends React.Component { </TextContent> </GridItem> <GridItem span={12} className="ds-margin-top-xlg"> - <Label onClick={this.openLDAPNavModal} href="#" variant="outline" color="blue" icon={<InfoCircleIcon />}> - Search Base DN - </Label> - <strong>&nbsp;&nbsp;{usersSearchBaseDn}</strong> + <TextContent> + <Text> + Search Base: + <Text + className="ds-left-margin" + component={TextVariants.a} + onClick={this.openLDAPNavModal} + href="#" + > + {usersSearchBaseDn} + </Text> + </Text> + </TextContent> </GridItem> <GridItem span={12} className="ds-margin-top"> <SearchInput diff --git a/src/cockpit/389-console/src/lib/ldap_editor/wizards/operations/addRole.jsx b/src/cockpit/389-console/src/lib/ldap_editor/wizards/operations/addRole.jsx index 3618a9fd4..fed14b40f 100644 --- a/src/cockpit/389-console/src/lib/ldap_editor/wizards/operations/addRole.jsx +++ b/src/cockpit/389-console/src/lib/ldap_editor/wizards/operations/addRole.jsx @@ -754,10 +754,19 @@ class AddRole extends React.Component { </TextContent> </GridItem> <GridItem span={12} className="ds-margin-top-xlg"> - <Label onClick={this.openLDAPNavModal} href="#" variant="outline" color="blue" icon={<InfoCircleIcon />}> - Search Base DN - </Label> - <strong>&nbsp;&nbsp;{rolesSearchBaseDn}</strong> + <TextContent> + <Text> + Search Base: + <Text + className="ds-left-margin" + component={TextVariants.a} + onClick={this.openLDAPNavModal} + href="#" + > + {rolesSearchBaseDn} + </Text> + </Text> + </TextContent> </GridItem> <GridItem span={12} className="ds-margin-top"> <SearchInput diff --git a/src/cockpit/389-console/src/lib/ldap_editor/wizards/operations/editGroup.jsx b/src/cockpit/389-console/src/lib/ldap_editor/wizards/operations/editGroup.jsx new file mode 100644 index 000000000..fe50c0262 --- /dev/null +++ b/src/cockpit/389-console/src/lib/ldap_editor/wizards/operations/editGroup.jsx @@ -0,0 +1,606 @@ +import React from 'react'; +import { + Button, + Card, + CardBody, + Divider, + DualListSelector, + Form, + Grid, + GridItem, + Modal, + ModalVariant, + SearchInput, + Tab, + Tabs, + TabTitleText, + Text, + TextContent, + TextInput, + TextVariants, +} from '@patternfly/react-core'; +import { + UsersIcon +} from '@patternfly/react-icons'; +import LdapNavigator from '../../lib/ldapNavigator.jsx'; +import { + runGenericSearch, + decodeLine, + getBaseDNFromTree, + modifyLdapEntry, + getBaseLevelEntryAttributes, +} from '../../lib/utils.jsx'; +import { DoubleConfirmModal } from "../../../notifications.jsx"; +import GroupTable from './groupTable.jsx'; + +class EditGroup extends React.Component { + constructor (props) { + super(props); + + this.state = { + activeTabKey: 0, + saving: false, + isTreeLoading: false, + members: [], + searching: false, + searchPattern: "", + showLDAPNavModal: false, + usersSearchBaseDn: "", + usersAvailableOptions: [], + usersChosenOptions: [], + ldifArray: [], + showConfirmMemberDelete: false, + showConfirmBulkDelete: false, + modalOpen: true, + modalSpinning: false, + modalChecked: false, + delMember: "", + bulkDeleting: false, + delMemberList: [], + showViewEntry: false, + }; + + // Toggle currently active tab + this.handleNavSelect = (event, tabIndex) => { + event.preventDefault(); + this.setState({ + activeTabKey: tabIndex + }); + }; + + this.handleBaseDnSelection = (treeViewItem) => { + this.setState({ + usersSearchBaseDn: treeViewItem.dn + }); + } + + this.showTreeLoadingState = (isTreeLoading) => { + this.setState({ + isTreeLoading, + searching: isTreeLoading ? true : false + }); + } + + this.openLDAPNavModal = () => { + this.setState({ + showLDAPNavModal: true + }); + }; + + this.closeLDAPNavModal = () => { + this.setState({ + showLDAPNavModal: false + }); + }; + + this.closeModal = () => { + this.setState({ + modalOpen: false + }); + }; + + this.handleSearchClick = () => { + this.setState({ + isSearchRunning: true, + usersAvailableOptions: [] + }, () => { this.getEntries () }); + }; + + this.handleSearchPattern = searchPattern => { + this.setState({ searchPattern }); + }; + + this.getEntries = () => { + const baseDn = this.state.usersSearchBaseDn; + const pattern = this.state.searchPattern; + const filter = pattern === '' || pattern === '*' + ? '(|(objectClass=person)(objectClass=nsPerson)(objectClass=nsAccount)(objectClass=nsOrgPerson)(objectClass=posixAccount))' + : `(&(|(objectClass=person)(objectClass=nsPerson)(objectClass=nsAccount)(objectClass=nsOrgPerson)(objectClass=posixAccount))(|(cn=*${pattern}*)(uid=*${pattern}*)))`; + const attrs = 'dn'; + + const params = { + serverId: this.props.editorLdapServer, + baseDn: baseDn, + scope: 'sub', + filter: filter, + attributes: attrs + }; + runGenericSearch(params, (resultArray) => { + const newOptionsArray = resultArray.map(result => { + const lines = result.split('\n'); + const dnEncoded = lines[0].indexOf(':: '); + let dnLine = lines[0]; + if (dnEncoded > 0) { + const decoded = decodeLine(dnLine); + dnLine = decoded[1]; + } else { + dnLine = dnLine.substring(4); + } + + // Is this dn already chosen? + for (const cOption of this.state.usersChosenOptions) { + if (cOption.props.title === dnLine) { + return "skip"; + } + } + + // Check here is member is already in the group + if (this.props.members.includes(dnLine)) { + return ( + <span className="ds-pf-green-color" title={dnLine + " (ALREADY A MEMBER)"}> + {dnLine} + </span> + ); + } else { + return ( + <span title={dnLine}> + {dnLine} + </span> + ); + } + }).filter(member_option => member_option !== "skip"); + + newOptionsArray.sort((a, b) => (a.props.children > b.props.children ? 1 : -1)); + this.setState({ + usersAvailableOptions: newOptionsArray, + isSearchRunning: false + }); + }); + } + + this.usersOnListChange = (newAvailableOptions, newChosenOptions) => { + let newNewAvailOptions = [...newAvailableOptions]; + let newNewChosenOptions = [] + + for (const option of newChosenOptions) { + if ('className' in option.props && option.props.className.indexOf("ds-pf-green-color") !== -1) { + // This member is in the group already(green), put it back + newNewAvailOptions.push(option); + } else { + // This member is not in the group, allow it + newNewChosenOptions.push(option); + } + } + + this.setState({ + usersAvailableOptions: newNewAvailOptions.sort((a, b) => (a.props.children > b.props.children ? 1 : -1)), + usersChosenOptions: newNewChosenOptions.sort((a, b) => (a.props.children > b.props.children ? 1 : -1)) + }); + }; + + this.showConfirmMemberDelete = this.showConfirmMemberDelete.bind(this); + this.closeConfirmMemberDelete = this.closeConfirmMemberDelete.bind(this); + this.showConfirmBulkDelete = this.showConfirmBulkDelete.bind(this); + this.closeConfirmBulkDelete = this.closeConfirmBulkDelete.bind(this); + this.addMembers = this.addMembers.bind(this); + this.delMember = this.delMember.bind(this); + this.onSelectMember = this.onSelectMember.bind(this); + this.delBulkMembers = this.delBulkMembers.bind(this); + this.handleModalChange = this.handleModalChange.bind(this); + this.switchEditor = this.switchEditor.bind(this); + this.editEntry = this.editEntry.bind(this); + this.viewEntry = this.viewEntry.bind(this); + this.closeViewEntry = this.closeViewEntry.bind(this); + }; + + componentDidMount() { + this.setState({ + members: [...this.props.members], + _members: [...this.props.members], + usersSearchBaseDn: getBaseDNFromTree(this.props.groupdn, this.props.treeViewRootSuffixes) + }); + } + + switchEditor () { + this.setState({ + modalOpen: false, + }, () => { + this.props.onReload(1); + this.props.useGenericEditor(); + }); + } + + editEntry (memberdn) { + this.setState({ + modalOpen: false, + }); + this.props.openEditEntry(memberdn); + } + + viewEntry (memberdn) { + getBaseLevelEntryAttributes(this.props.editorLdapServer, + memberdn, + (entryDetails) => { + let ldifArray = []; + entryDetails + .filter(data => (data.attribute + data.value !== '' && // Filter out empty lines + data.attribute !== '???: ')) // and data for empty suffix(es) and in case of failure. + .map((line, index) => { + if (index === 1000) { + ldifArray.push({ + 'attribute': '... Truncated', + 'value': " - Entry too large to display ..." + }); + return; + } else if (index > 1000) { + return; + } + ldifArray.push(line); + }); + this.setState({ + showViewEntry: true, + ldifArray: ldifArray, + }); + }); + } + + closeViewEntry () { + this.setState({ + showViewEntry: false, + ldifArray: [], + }); + } + + handleModalChange(e) { + const value = e.target.type === 'checkbox' ? e.target.checked : e.target.value; + this.setState({ + [e.target.id]: value + }); + } + + showConfirmMemberDelete (name) { + let ldifArray = []; + let memberAttr = "uniquemember"; + + if (this.props.isGroupOfNames) { + memberAttr = "member"; + } + ldifArray.push(`dn: ${this.props.groupdn}`); + ldifArray.push('changetype: modify'); + ldifArray.push(`delete: ${memberAttr}`); + ldifArray.push(`${memberAttr}: ${name}`); + + this.setState({ + showConfirmMemberDelete: true, + delMember: name, + modalChecked: false, + modalSpinning: false, + ldifArray: ldifArray, + }); + } + + closeConfirmMemberDelete() { + this.setState({ + showConfirmMemberDelete: false, + modalSpinning: false, + modalChecked: false, + delMember: "", + }); + } + + addMembers () { + const params = { serverId: this.props.editorLdapServer }; + let ldifArray = []; + let memberAttr = "uniquemember"; + let memCount = 0; + + this.setState({ + saving: true, + }); + + if (this.props.isGroupOfNames) { + memberAttr = "member"; + } + ldifArray.push(`dn: ${this.props.groupdn}`); + ldifArray.push('changetype: modify'); + + // Loop of dual select list + for (const user of this.state.usersChosenOptions) { + ldifArray.push(`add: ${memberAttr}`); + ldifArray.push(`${memberAttr}: ${user.props.title}`); + ldifArray.push('-'); + memCount += 1; + } + + modifyLdapEntry(params, ldifArray, (result) => { + if (result.errorCode === 0) { + this.props.addNotification( + "success", + "Successfully added " + memCount + " member" + (memCount > 1 ? "s" : "") + ); + } else { + this.props.addNotification( + "error", + "Failed to update group, error code: " + result.errorCode + ); + } + this.setState({ + saving: false, + usersChosenOptions: [], + }, () => { this.props.onReload(1) }); + }); + } + + delMember () { + const params = { serverId: this.props.editorLdapServer }; + modifyLdapEntry(params, this.state.ldifArray, (result) => { + if (result.errorCode === 0) { + this.props.addNotification( + "success", + "Successfully updated group" + ); + } else { + this.props.addNotification( + "error", + "Failed to update group, error code: " + result.errorCode + ); + } + this.setState({ + showConfirmMemberDelete: false, + showConfirmBulkDelete: false, + bulkDeleting: false, + }, () => { this.props.onReload(1) }); + }); + } + + onSelectMember(memberdn, isSelected) { + let delMemList = [...this.state.delMemberList]; + if (isSelected) { + if (!delMemList.includes(memberdn)) { + // Add member to delete + delMemList.push(memberdn); + } + } else { + let idx = delMemList.indexOf(memberdn); + if (idx !== -1) { + // Remove member from delete list + delMemList.splice(idx, 1); + } + } + + this.setState({ + delMemberList: delMemList + }); + }; + + showConfirmBulkDelete () { + this.setState({ + showConfirmBulkDelete: true, + modalChecked: false, + modalSpinning: false, + }); + } + + closeConfirmBulkDelete () { + this.setState({ + showConfirmBulkDelete: false, + }); + } + + delBulkMembers () { + if (this.state.delMemberList.length === 0) { + return; + } + this.setState({ + bulkDeleting: true, + }); + let ldifArray = []; + let memberAttr = "uniquemember"; + + if (this.props.isGroupOfNames) { + memberAttr = "member"; + } + ldifArray.push(`dn: ${this.props.groupdn}`); + ldifArray.push('changetype: modify'); + for (const member of this.state.delMemberList) { + ldifArray.push(`delete: ${memberAttr}`); + ldifArray.push(`${memberAttr}: ${member}`); + ldifArray.push(`-`); + } + this.setState({ + ldifArray: ldifArray, + }, () => this.delMember() ); + } + + render () { + const { + usersSearchBaseDn, usersAvailableOptions, + usersChosenOptions, showLDAPNavModal, members, modalOpen, + saving, delMemberList, showViewEntry, ldifArray, + } = this.state; + const title = <><UsersIcon />&nbsp;&nbsp;{this.props.groupdn}</>; + const extraPrimaryProps = {}; + let saveBtnName = "Add Members"; + if (saving) { + saveBtnName = "Saving ..."; + extraPrimaryProps.spinnerAriaValueText = "Saving"; + } + + const delMemList = this.state.delMemberList.map((member) => + <div key={member} className="ds-left-margin ds-left-align">{member}</div>); + + return ( + <div> + <Modal + className="ds-modal-select-tall" + variant={ModalVariant.large} + title={title} + isOpen={modalOpen} + onClose={this.closeModal} + actions={[ + <Button + key="switch" + variant="secondary" + onClick={this.switchEditor} + className="ds-float-right" + > + Switch To Generic Editor + </Button>, + ]} + > + <Tabs activeKey={this.state.activeTabKey} onSelect={this.handleNavSelect}> + <Tab + eventKey={0} + title={<TabTitleText>Current Members <font size="2">({this.props.members.length})</font></TabTitleText>} + > + <GroupTable + key={members + delMemberList} + rows={members} + removeMember={this.showConfirmMemberDelete} + onSelectMember={this.onSelectMember} + showConfirmBulkDelete={this.showConfirmBulkDelete} + delMemberList={delMemberList} + viewEntry={this.viewEntry} + editEntry={this.props.openEditEntry} + saving={this.state.bulkDeleting} + /> + </Tab> + <Tab eventKey={1} title={<TabTitleText>Find New Members</TabTitleText>}> + <Form autoComplete="off"> + <Grid className="ds-indent"> + <GridItem span={12} className="ds-margin-top-xlg"> + <TextContent> + <Text> + Search Base: + <Text + className="ds-left-margin" + component={TextVariants.a} + onClick={this.openLDAPNavModal} + href="#" + > + {usersSearchBaseDn} + </Text> + </Text> + </TextContent> + </GridItem> + <GridItem span={12} className="ds-margin-top-lg"> + <SearchInput + placeholder="Find members..." + value={this.state.searchPattern} + onChange={this.handleSearchPattern} + onSearch={this.handleSearchClick} + onClear={() => { this.handleSearchPattern('') }} + /> + </GridItem> + <GridItem span={12} className="ds-margin-top-xlg"> + <DualListSelector + availableOptions={usersAvailableOptions} + chosenOptions={usersChosenOptions} + availableOptionsTitle="Available Members" + chosenOptionsTitle="Chosen Members" + onListChange={this.usersOnListChange} + id="usersSelector" + /> + <Button + className="ds-margin-top" + isDisabled={usersChosenOptions.length === 0 || this.state.saving} + variant="primary" + onClick={this.addMembers} + isLoading={this.state.saving} + spinnerAriaValueText={this.state.saving ? "Saving" : undefined} + {...extraPrimaryProps} + > + {saveBtnName} + </Button> + </GridItem> + <Modal + variant={ModalVariant.medium} + title="Choose A Branch To Search" + isOpen={showLDAPNavModal} + onClose={this.closeLDAPNavModal} + actions={[ + <Button + key="confirm" + variant="primary" + onClick={this.closeLDAPNavModal} + > + Done + </Button> + ]} + > + <Card isSelectable className="ds-indent ds-margin-bottom-md"> + <CardBody> + <LdapNavigator + treeItems={[...this.props.treeViewRootSuffixes]} + editorLdapServer={this.props.editorLdapServer} + skipLeafEntries={true} + handleNodeOnClick={this.handleBaseDnSelection} + showTreeLoadingState={this.showTreeLoadingState} + /> + </CardBody> + </Card> + </Modal> + <Divider + className="ds-margin-top-lg" + /> + </Grid> + </Form> + </Tab> + </Tabs> + <Modal + variant={ModalVariant.medium} + title="View Entry" + isOpen={showViewEntry} + onClose={this.closeViewEntry} + > + <Card isSelectable className="ds-indent ds-margin-bottom-md"> + <CardBody className="ds-textarea"> + {ldifArray.map((line) => ( + <h6 key={line.attribute+line.value}>{line.attribute}{line.value}</h6> + ))} + </CardBody> + </Card> + </Modal> + <DoubleConfirmModal + showModal={this.state.showConfirmMemberDelete} + closeHandler={this.closeConfirmMemberDelete} + handleChange={this.handleModalChange} + actionHandler={this.delMember} + spinning={this.state.modalSpinning} + item={this.state.delMember} + checked={this.state.modalChecked} + mTitle="Remove Member From Group" + mMsg="Are you sure you want to remove this member?" + mSpinningMsg="Deleting ..." + mBtnName="Delete" + /> + <DoubleConfirmModal + showModal={this.state.showConfirmBulkDelete} + closeHandler={this.closeConfirmBulkDelete} + handleChange={this.handleModalChange} + actionHandler={this.delBulkMembers} + spinning={this.state.modalSpinning} + item={delMemList} + checked={this.state.modalChecked} + mTitle="Remove Members From Group" + mMsg="Are you sure you want to remove these members?" + mSpinningMsg="Deleting ..." + mBtnName="Delete Members" + /> + </Modal> + </div> + ); + } +} + +export default EditGroup; diff --git a/src/cockpit/389-console/src/lib/ldap_editor/wizards/operations/editLdapEntry.jsx b/src/cockpit/389-console/src/lib/ldap_editor/wizards/operations/editLdapEntry.jsx index f623e9438..279f06b74 100644 --- a/src/cockpit/389-console/src/lib/ldap_editor/wizards/operations/editLdapEntry.jsx +++ b/src/cockpit/389-console/src/lib/ldap_editor/wizards/operations/editLdapEntry.jsx @@ -5,11 +5,8 @@ import { Bullseye, Card, CardHeader, CardBody, CardTitle, Dropdown, DropdownItem, DropdownPosition, - FormSelect, FormSelectOption, Grid, GridItem, Label, LabelGroup, - Modal, - ModalVariant, Pagination, SearchInput, SimpleList, SimpleListItem, @@ -36,6 +33,7 @@ import { modifyLdapEntry, } from '../../lib/utils.jsx'; import EditableTable from '../../lib/editableTable.jsx'; +import EditGroup from './editGroup.jsx'; import { LDAP_OPERATIONS, BINARY_ATTRIBUTES, @@ -95,6 +93,11 @@ class EditLdapEntry extends React.Component { selectedAttributes: [], attrsToRemove: [], modifying: true, + isGroupOfNames: false, + isGroupOfUniqueNames: false, + groupMembers: [], + groupGenericEditor: false, + localProps: {...this.props}, }; this.onNext = ({ id }) => { @@ -114,7 +117,7 @@ class EditLdapEntry extends React.Component { // Generate the LDIF data at step 4. this.generateLdifData(); } else if (id === 6) { - const params = { serverId: this.props.editorLdapServer }; + const params = { serverId: this.state.localProps.editorLdapServer }; modifyLdapEntry(params, this.state.ldifArray, (result) => { if (result.errorCode === 0) { result.output = "Successfully modified entry" @@ -124,13 +127,13 @@ class EditLdapEntry extends React.Component { commandOutput: result.errorCode === 0 ? 'Successfully modified entry!' : 'Failed to modify entry, error: ' + result.errorCode , resultVariant: result.errorCode === 0 ? 'success' : 'danger', modifying: false, - }, () => { this.props.onReload() }); // refreshes tableView + }, () => { this.state.localProps.onReload() }); // refreshes tableView const opInfo = { // This is what refreshes treeView operationType: 'MODIFY', resultCode: result.errorCode, time: Date.now() } - this.props.setWizardOperationInfo(opInfo); + this.state.localProps.setWizardOperationInfo(opInfo); }); } }; @@ -160,7 +163,7 @@ class EditLdapEntry extends React.Component { const val = value.toLowerCase(); // Get fresh list of Objectclasses and what is selected - this.props.allObjectclasses.map(oc => { + this.state.localProps.allObjectclasses.map(oc => { let selected = false; let selectionDisabled = false; for (const selectedOC of this.state.selectedObjectClasses) { @@ -233,9 +236,29 @@ class EditLdapEntry extends React.Component { }) } + this.useGroupGenericEditor = this.useGroupGenericEditor.bind(this); + this.loadEntry = this.loadEntry.bind(this); // End constructor(). } + useGroupGenericEditor = () => { + this.originalEntryRows = []; + this.setState({ + groupGenericEditor: true + }); + } + + openEditEntry = (dn) => { + // used by group modal + let editProps = { ...this.state.localProps}; + editProps.wizardEntryDn = dn; + this.setState({ + localProps: editProps, + isGroupOfNames: false, + isGroupOfUniqueNames: false, + }) + } + isAttributeSingleValued = (attr) => { return this.singleValuedAttributes.includes(attr.toLowerCase()); }; @@ -265,22 +288,24 @@ class EditLdapEntry extends React.Component { }); } - componentDidMount () { + loadEntry(reload) { const ocArray = []; - getSingleValuedAttributes(this.props.editorLdapServer, - (myAttrs) => { - this.singleValuedAttributes = [...myAttrs]; - }); + if (reload) { + this.originalEntryRows = []; + } - getBaseLevelEntryAttributes(this.props.editorLdapServer, - this.props.wizardEntryDn, + getBaseLevelEntryAttributes(this.state.localProps.editorLdapServer, + this.state.localProps.wizardEntryDn, (entryDetails) => { let objectclasses = []; - const rdnInfo = getRdnInfo(this.props.wizardEntryDn); + const rdnInfo = getRdnInfo(this.state.localProps.wizardEntryDn); let namingAttr = ""; let namingValue = ""; let namingIndex = -1; let attrPropsName = ""; + let isGroupOfUniqueNames = false; + let isGroupOfNames = false; + let members = []; entryDetails .filter(data => (data.attribute + data.value !== '' && // Filter out empty lines @@ -295,6 +320,11 @@ class EditLdapEntry extends React.Component { if (attrLowerCase === "objectclass") { objectclasses.push(val); + if (val.toLowerCase() === "groupofnames") { + isGroupOfNames = true; + } else if (val.toLowerCase() === "groupofuniquenames") { + isGroupOfUniqueNames = true; + } } else { // Base64 encoded values if (line.attribute === "dn") { @@ -341,10 +371,15 @@ class EditLdapEntry extends React.Component { obj.required = namingAttribute; this.originalEntryRows.push(obj); } + + // Handle groupo members separately + if (attrLowerCase === "member" || attrLowerCase === "uniquemember") { + members.push(val); + } }); // Mark the existing objectclass classes as selected - this.props.allObjectclasses.map(oc => { + this.state.localProps.allObjectclasses.map(oc => { let selected = false; let selectionDisabled = false; for (const entryOC of objectclasses) { @@ -388,6 +423,9 @@ class EditLdapEntry extends React.Component { namingValue: namingValue, origAttrs: JSON.parse(JSON.stringify(this.originalEntryRows)), origOC: JSON.parse(JSON.stringify(selectedObjectClasses)), + isGroupOfNames: isGroupOfNames, + isGroupOfUniqueNames: isGroupOfUniqueNames, + groupMembers: members.sort(), loading: false, }, () => { this.updateAttributeTableRows(); @@ -395,6 +433,16 @@ class EditLdapEntry extends React.Component { }); } + componentDidMount () { + getSingleValuedAttributes(this.props.editorLdapServer, + (myAttrs) => { + this.singleValuedAttributes = [...myAttrs]; + }); + this.setState({ + localProps: {...this.props} + }, () => { this.loadEntry() }); + } + onSetPageOc = (_event, pageNumber) => { this.setState({ pageOc: pageNumber, @@ -689,10 +737,10 @@ class EditLdapEntry extends React.Component { generateLdifData = () => { const statementRows = []; - const ldifArray = []; const updateArray = []; const addArray = []; const removeArray = []; + let ldifArray = []; let cleanLdifArray = []; let numOfChanges = 0; let isFilePath = false; @@ -1152,7 +1200,7 @@ class EditLdapEntry extends React.Component { <div> <Bullseye className="ds-margin-top-xlg" key="add-entry-bulleye" > <Title headingLevel="h3" size="lg" key="loading-title"> - Loading ObjectClasses ... + Loading ... </Title> </Bullseye> <Spinner className="ds-center" size="lg" key="loading-spinner" /> @@ -1257,14 +1305,14 @@ class EditLdapEntry extends React.Component { </TextContent> <EditableTable key={editableTableData} - wizardEntryDn={this.props.wizardEntryDn} + wizardEntryDn={this.state.localProps.wizardEntryDn} editableTableData={editableTableData} quickUpdate isAttributeSingleValued={this.isAttributeSingleValued} isAttributeRequired={this.isAttributeRequired} enableNextStep={this.enableNextStep} saveCurrentRows={this.saveCurrentRows} - allObjectclasses={this.props.allObjectclasses} + allObjectclasses={this.state.localProps.allObjectclasses} disableNamingChange /> </> @@ -1322,7 +1370,7 @@ class EditLdapEntry extends React.Component { <Alert variant={resultVariant} isInline - title="Result for Entry Modification" + title="Result for Entry Modification"editEntry > {commandOutput} {this.state.adding && @@ -1404,18 +1452,40 @@ class EditLdapEntry extends React.Component { ]; const title = <> - Entry DN: &nbsp;&nbsp;<strong>{this.props.wizardEntryDn}</strong> + Entry DN: &nbsp;&nbsp;<strong>{this.state.localProps.wizardEntryDn}</strong> </>; - return ( + let editPage = <Wizard - isOpen={this.props.isWizardOpen} - onClose={this.props.toggleOpenWizard} + isOpen={this.state.localProps.isWizardOpen} + onClose={this.state.localProps.toggleOpenWizard} steps={editEntrySteps} title="Edit An LDAP Entry" description={title} onNext={this.onNext} - /> + />; + + if (!this.state.groupGenericEditor && (this.state.isGroupOfNames || this.state.isGroupOfUniqueNames)) { + editPage = + <EditGroup + key={this.state.groupMembers} + groupdn={this.state.localProps.wizardEntryDn} + members={this.state.groupMembers} + useGenericEditor={this.useGroupGenericEditor} + isGroupOfNames={this.state.isGroupOfNames} + isGroupOfUniqueNames={this.state.isGroupOfUniqueNames} + treeViewRootSuffixes={this.state.localProps.treeViewRootSuffixes} + editorLdapServer={this.state.localProps.editorLdapServer} + addNotification={this.state.localProps.addNotification} + openEditEntry={this.openEditEntry} + onReload={this.loadEntry} + />; + } + + return ( + <> + {editPage} + </> ); } } diff --git a/src/cockpit/389-console/src/lib/ldap_editor/wizards/operations/groupTable.jsx b/src/cockpit/389-console/src/lib/ldap_editor/wizards/operations/groupTable.jsx new file mode 100644 index 000000000..846eebe09 --- /dev/null +++ b/src/cockpit/389-console/src/lib/ldap_editor/wizards/operations/groupTable.jsx @@ -0,0 +1,209 @@ +import React from "react"; +import { + Button, + Divider, + Pagination, + PaginationVariant, + SearchInput, +} from '@patternfly/react-core'; +import { + expandable, + Table, + TableHeader, + TableBody, + TableVariant, + sortable, + SortByDirection, +} from '@patternfly/react-table'; +import PropTypes from "prop-types"; + +class GroupTable extends React.Component { + constructor(props) { + super(props); + + this.state = { + page: 1, + perPage: 10, + value: '', + sortBy: {}, + rows: [], + columns: [ + { title: 'Member DN', transforms: [sortable] }, + ], + }; + this.selectedCount = 0; + + this.onSetPage = (_event, pageNumber) => { + this.setState({ + page: pageNumber + }); + }; + + this.onPerPageSelect = (_event, perPage) => { + this.setState({ + perPage: perPage + }); + }; + + this.onSort = this.onSort.bind(this); + this.onSearchChange = this.onSearchChange.bind(this); + } + + componentDidMount() { + let rows = []; + let columns = this.state.columns; + + for (const attrRow of this.props.rows) { + let selected = false; + if (this.props.delMemberList.includes(attrRow)) { + selected = true; + } + rows.push({ + cells: [attrRow], + selected: selected, + }); + } + if (rows.length == 0) { + rows = [{ cells: ['No Members'], disableSelection: true }]; + } + this.setState({ + rows: rows, + columns: columns + }); + } + + onSearchChange(value, event) { + let rows = []; + const val = value.toLowerCase(); + for (const row of this.props.rows) { + if (val !== "" && val != "*" && row.indexOf(val) === -1 ) { + // Not a match, skip it + continue; + } + rows.push({ + cells: [row] + }); + } + if (rows.length == 0) { + rows = [{ cells: ['No Members'], disableSelection: true }]; + } + + this.setState({ + rows: rows, + value: value, + page: 1, + }); + } + + onSort(_event, index, direction) { + const rows = []; + const sortedAttrs = [...this.props.rows]; + + // Sort the referrals and build the new rows + sortedAttrs.sort(); + if (direction !== SortByDirection.asc) { + sortedAttrs.reverse(); + } + for (const attrRow of sortedAttrs) { + rows.push({ cells: [attrRow] }); + } + + this.setState({ + sortBy: { + index, + direction + }, + rows: rows, + page: 1, + }); + } + + actions() { + return [ + { + title: 'View Entry', + onClick: (event, rowId, rowData, extra) => + this.props.viewEntry(rowData.cells[0]) + }, + { + title: 'Edit Entry', + onClick: (event, rowId, rowData, extra) => + this.props.editEntry(rowData.cells[0]) + }, + { + isSeparator: true + }, + { + title: 'Remove Entry', + onClick: (event, rowId, rowData, extra) => + this.props.removeMember(rowData.cells[0]) + } + ]; + } + + render() { + const { columns, rows, perPage, page, sortBy } = this.state; + const extraPrimaryProps = {}; + const canSelectAll = false; + let deleteBtnName = "Remove Selected Members"; + if (this.props.saving) { + deleteBtnName = "Updating group ..."; + extraPrimaryProps.spinnerAriaValueText = "Updating"; + } + + return ( + <div className="ds-margin-top-xlg ds-indent"> + <SearchInput + className="ds-margin-top" + placeholder='Search Members' + value={this.state.value} + onChange={this.onSearchChange} + onClear={(evt) => this.onSearchChange('', evt)} + /> + <Table + className="ds-margin-top" + canSelectAll={canSelectAll} + onSelect={(_event, isSelecting, rowIndex) => { + if (rowIndex !== -1) { + this.props.onSelectMember(this.state.rows[rowIndex].cells[0], isSelecting) + } + }} + aria-label="group table" + cells={columns} + rows={rows} + variant={TableVariant.compact} + sortBy={sortBy} + onSort={this.onSort} + actions={rows.length > 0 ? this.actions() : null} + > + <TableHeader /> + <TableBody /> + </Table> + <Pagination + itemCount={this.props.rows.length} + widgetId="pagination-options-menu-bottom" + perPage={perPage} + page={page} + variant={PaginationVariant.bottom} + onSetPage={this.onSetPage} + onPerPageSelect={this.onPerPageSelect} + /> + <Button + isDisabled={this.props.delMemberList.length === 0 || this.props.saving} + variant="primary" + onClick={this.props.showConfirmBulkDelete} + isLoading={this.props.saving} + spinnerAriaValueText={this.state.saving ? "Updating group ..." : undefined} + {...extraPrimaryProps} + > + {deleteBtnName} + </Button> + <Divider + className="ds-margin-top-lg" + /> + </div> + ); + } +} + +export default GroupTable; diff --git a/src/cockpit/389-console/src/lib/notifications.jsx b/src/cockpit/389-console/src/lib/notifications.jsx index c8dfbff80..0cc133784 100644 --- a/src/cockpit/389-console/src/lib/notifications.jsx +++ b/src/cockpit/389-console/src/lib/notifications.jsx @@ -73,8 +73,8 @@ export class DoubleConfirmModal extends React.Component { </Text> </TextContent> <TextContent> - <Text className="ds-center ds-margin-top-xlg" component={TextVariants.h4}> - {item} + <Text className="ds-center ds-margin-top" component={TextVariants.h4}> + <i>{item}</i> </Text> </TextContent> <Grid className="ds-margin-top-xlg"> @@ -101,7 +101,6 @@ DoubleConfirmModal.propTypes = { handleChange: PropTypes.func, actionHandler: PropTypes.func, spinning: PropTypes.bool, - item: PropTypes.string, checked: PropTypes.bool, mTitle: PropTypes.string, mMsg: PropTypes.string, diff --git a/src/cockpit/389-console/src/lib/replication/replTables.jsx b/src/cockpit/389-console/src/lib/replication/replTables.jsx index 44f7ca18f..2d3221686 100644 --- a/src/cockpit/389-console/src/lib/replication/replTables.jsx +++ b/src/cockpit/389-console/src/lib/replication/replTables.jsx @@ -226,13 +226,15 @@ class ManagerTable extends React.Component { getDeleteButton(name) { return ( - <TrashAltIcon - className="ds-center" - onClick={() => { - this.props.confirmDelete(name); - }} - title="Delete Replication Manager" - /> + <a> + <TrashAltIcon + className="ds-center" + onClick={() => { + this.props.confirmDelete(name); + }} + title="Delete Replication Manager" + /> + </a> ); }
0
cd000871ac580308655a0ac21a3c0acf9ac6c512
389ds/389-ds-base
Issue 49029 - [RFE] improve internal operations logging Description: Edited the test cases by changing the 'op' number to regex, because the values were hardcoded into the test and if there was some more fixing of internal logs that would cause the 'op' number to raise up/lower down then the test would fail. The main goal is to check syntax of internal messages, not to match 'op' numbers. Also changed strings in src/lib389/lib389/dirsrv_log.py to raw strings to stop showing warnings about deprecation. https://pagure.io/389-ds-base/issue/49029 Reviewed by: vashirov (Thanks!)
commit cd000871ac580308655a0ac21a3c0acf9ac6c512 Author: Barbora Smejkalová <[email protected]> Date: Thu May 16 14:21:15 2019 +0200 Issue 49029 - [RFE] improve internal operations logging Description: Edited the test cases by changing the 'op' number to regex, because the values were hardcoded into the test and if there was some more fixing of internal logs that would cause the 'op' number to raise up/lower down then the test would fail. The main goal is to check syntax of internal messages, not to match 'op' numbers. Also changed strings in src/lib389/lib389/dirsrv_log.py to raw strings to stop showing warnings about deprecation. https://pagure.io/389-ds-base/issue/49029 Reviewed by: vashirov (Thanks!) diff --git a/dirsrvtests/tests/suites/ds_logs/ds_logs_test.py b/dirsrvtests/tests/suites/ds_logs/ds_logs_test.py index 4d3dd5962..e471ee537 100644 --- a/dirsrvtests/tests/suites/ds_logs/ds_logs_test.py +++ b/dirsrvtests/tests/suites/ds_logs/ds_logs_test.py @@ -297,16 +297,19 @@ def test_internal_log_server_level_0(topology_st): log.info('Restart the server to flush the logs') topo.restart() - # These comments contain lines we are trying to find without regex + # These comments contain lines we are trying to find without regex (the op numbers are just examples) log.info("Check if access log does not contain internal log of MOD operation") # (Internal) op=2(2)(1) SRCH base="cn=config - assert not topo.ds_access_log.match(r'.*\(Internal\) op=2\(2\)\(1\) SRCH base="cn=config.*') + assert not topo.ds_access_log.match(r'.*\(Internal\) op=[0-9]+\([0-9]+\)\([0-9]+\) SRCH base="cn=config.*') # (Internal) op=2(2)(1) RESULT err=0 tag=48 nentries=1 - assert not topo.ds_access_log.match(r'.*\(Internal\) op=2\(2\)\(1\) RESULT err=0 tag=48 nentries=1.*') + assert not topo.ds_access_log.match(r'.*\(Internal\) op=[0-9]+\([0-9]+\)\([0-9]+\) RESULT err=0 tag=48 nentries=1.*') log.info("Check if the other internal operations are not present") # conn=Internal(0) op=0 - assert not topo.ds_access_log.match(r'.*conn=Internal\(0\) op=0.*') + assert not topo.ds_access_log.match(r'.*conn=Internal\([0-9]+\) op=[0-9]+\([0-9]+\)\([0-9]+\).*') + + log.info('Delete the previous access logs for the next test') + topo.deleteAccessLogs() @pytest.mark.bz1358706 @@ -344,16 +347,16 @@ def test_internal_log_server_level_4(topology_st): log.info('Restart the server to flush the logs') topo.restart() - # These comments contain lines we are trying to find without regex + # These comments contain lines we are trying to find without regex (the op numbers are just examples) log.info("Check if access log contains internal MOD operation in correct format") # (Internal) op=2(2)(1) SRCH base="cn=config - assert topo.ds_access_log.match(r'.*\(Internal\) op=2\(2\)\(1\) SRCH base="cn=config.*') + assert topo.ds_access_log.match(r'.*\(Internal\) op=[0-9]+\([0-9]+\)\([0-9]+\) SRCH base="cn=config.*') # (Internal) op=2(2)(1) RESULT err=0 tag=48 nentries=1 - assert topo.ds_access_log.match(r'.*\(Internal\) op=2\(2\)\(1\) RESULT err=0 tag=48 nentries=1.*') + assert topo.ds_access_log.match(r'.*\(Internal\) op=[0-9]+\([0-9]+\)\([0-9]+\) RESULT err=0 tag=48 nentries=1.*') log.info("Check if the other internal operations have the correct format") # conn=Internal(0) op=0 - assert topo.ds_access_log.match(r'.*conn=Internal\(0\) op=0.*') + assert topo.ds_access_log.match(r'.*conn=Internal\([0-9]+\) op=[0-9]+\([0-9]+\)\([0-9]+\).*') log.info('Delete the previous access logs for the next test') topo.deleteAccessLogs() @@ -393,49 +396,50 @@ def test_internal_log_level_260(topology_st, add_user_log_level_260): log.info('Restart the server to flush the logs') topo.restart() - # These comments contain lines we are trying to find without regex + # These comments contain lines we are trying to find without regex (the op numbers are just examples) log.info("Check the access logs for ADD operation of the user") # op=10 ADD dn="uid=test_user_777,ou=branch1,dc=example,dc=com" - assert topo.ds_access_log.match(r'.*op=10 ADD dn="uid=test_user_777,ou=branch1,dc=example,dc=com".*') + assert topo.ds_access_log.match(r'.*op=[0-9]+ ADD dn="uid=test_user_777,ou=branch1,dc=example,dc=com".*') # (Internal) op=10(1)(1) MOD dn="cn=group,ou=Groups,dc=example,dc=com" - assert topo.ds_access_log.match(r'.*\(Internal\) op=10\(1\)\(1\) MOD dn="cn=group,ou=Groups,dc=example,dc=com".*') + assert topo.ds_access_log.match(r'.*\(Internal\) op=[0-9]+\([0-9]+\)\([0-9]+\) ' + r'MOD dn="cn=group,ou=Groups,dc=example,dc=com".*') # (Internal) op=10(1)(2) SRCH base="cn=group,ou=Groups,dc=example,dc=com" - assert topo.ds_access_log.match(r'.*\(Internal\) op=10\(1\)\(2\) SRCH base="cn=group,' + assert topo.ds_access_log.match(r'.*\(Internal\) op=[0-9]+\([0-9]+\)\([0-9]+\) SRCH base="cn=group,' r'ou=Groups,dc=example,dc=com".*') # (Internal) op=10(1)(2) RESULT err=0 tag=48 nentries=1 - assert topo.ds_access_log.match(r'.*\(Internal\) op=10\(1\)\(2\) RESULT err=0 tag=48 nentries=1*') + assert topo.ds_access_log.match(r'.*\(Internal\) op=[0-9]+\([0-9]+\)\([0-9]+\) RESULT err=0 tag=48 nentries=1*') # (Internal) op=10(1)(1) RESULT err=0 tag=48 - assert topo.ds_access_log.match(r'.*\(Internal\) op=10\(1\)\(1\) RESULT err=0 tag=48.*') + assert topo.ds_access_log.match(r'.*\(Internal\) op=[0-9]+\([0-9]+\)\([0-9]+\) RESULT err=0 tag=48.*') # op=10 RESULT err=0 tag=105 - assert topo.ds_access_log.match(r'.*op=10 RESULT err=0 tag=105.*') + assert topo.ds_access_log.match(r'.*op=[0-9]+ RESULT err=0 tag=105.*') log.info("Check the access logs for MOD operation of the user") # op=12 MODRDN dn="uid=test_user_777,ou=branch1,dc=example,dc=com" ' # 'newrdn="uid=new_test_user_777" newsuperior="dc=example,dc=com" - assert topo.ds_access_log.match(r'.*op=12 MODRDN dn="uid=test_user_777,ou=branch1,dc=example,dc=com" ' + assert topo.ds_access_log.match(r'.*op=[0-9]+ MODRDN dn="uid=test_user_777,ou=branch1,dc=example,dc=com" ' 'newrdn="uid=new_test_user_777" newsuperior="dc=example,dc=com".*') # (Internal) op=12(1)(1) SRCH base="uid=test_user_777, ou=branch1,dc=example,dc=com" - assert topo.ds_access_log.match(r'.*\(Internal\) op=12\(1\)\(1\) SRCH base="uid=test_user_777,' + assert topo.ds_access_log.match(r'.*\(Internal\) op=[0-9]+\([0-9]+\)\([0-9]+\) SRCH base="uid=test_user_777,' 'ou=branch1,dc=example,dc=com".*') # (Internal) op=12(1)(1) RESULT err=0 tag=48 nentries=1 - assert topo.ds_access_log.match(r'.*\(Internal\) op=12\(1\)\(1\) RESULT err=0 tag=48 nentries=1.*') + assert topo.ds_access_log.match(r'.*\(Internal\) op=[0-9]+\([0-9]+\)\([0-9]+\) RESULT err=0 tag=48 nentries=1.*') # op=12 RESULT err=0 tag=109 - assert topo.ds_access_log.match(r'.*op=12 RESULT err=0 tag=109.*') + assert topo.ds_access_log.match(r'.*op=[0-9]+ RESULT err=0 tag=109.*') log.info("Check the access logs for DEL operation of the user") # op=15 DEL dn="uid=new_test_user_777,dc=example,dc=com" - assert topo.ds_access_log.match(r'.*op=15 DEL dn="uid=new_test_user_777,dc=example,dc=com".*') + assert topo.ds_access_log.match(r'.*op=[0-9]+ DEL dn="uid=new_test_user_777,dc=example,dc=com".*') # (Internal) op=15(1)(1) SRCH base="uid=new_test_user_777, dc=example,dc=com" - assert topo.ds_access_log.match(r'.*\(Internal\) op=15\(1\)\(1\) SRCH base="uid=new_test_user_777,' + assert topo.ds_access_log.match(r'.*\(Internal\) op=[0-9]+\([0-9]+\)\([0-9]+\) SRCH base="uid=new_test_user_777,' 'dc=example,dc=com".*') # (Internal) op=15(1)(1) RESULT err=0 tag=48 nentries=1 - assert topo.ds_access_log.match(r'.*\(Internal\) op=15\(1\)\(1\) RESULT err=0 tag=48 nentries=1.*') + assert topo.ds_access_log.match(r'.*\(Internal\) op=[0-9]+\([0-9]+\)\([0-9]+\) RESULT err=0 tag=48 nentries=1.*') # op=15 RESULT err=0 tag=107 - assert topo.ds_access_log.match(r'.*op=15 RESULT err=0 tag=107.*') + assert topo.ds_access_log.match(r'.*op=[0-9]+ RESULT err=0 tag=107.*') log.info("Check if the other internal operations have the correct format") # conn=Internal(0) op=0 - assert topo.ds_access_log.match(r'.*conn=Internal\(0\) op=0.*') + assert topo.ds_access_log.match(r'.*conn=Internal\([0-9]+\) op=[0-9]+\([0-9]+\)\([0-9]+\).*') log.info('Delete the previous access logs for the next test') topo.deleteAccessLogs() @@ -476,48 +480,50 @@ def test_internal_log_level_131076(topology_st, add_user_log_level_131076): log.info('Restart the server to flush the logs') topo.restart() - # These comments contain lines we are trying to find without regex + # These comments contain lines we are trying to find without regex (the op numbers are just examples) log.info("Check the access logs for ADD operation of the user") # op=10 ADD dn="uid=test_user_777,ou=branch1,dc=example,dc=com" - assert not topo.ds_access_log.match(r'.*op=10 ADD dn="uid=test_user_777,ou=branch1,dc=example,dc=com".*') + assert not topo.ds_access_log.match(r'.*op=[0-9]+ ADD dn="uid=test_user_777,ou=branch1,dc=example,dc=com".*') # (Internal) op=10(1)(1) MOD dn="cn=group,ou=Groups,dc=example,dc=com" - assert topo.ds_access_log.match(r'.*\(Internal\) op=10\(1\)\(1\) MOD dn="cn=group,ou=Groups,dc=example,dc=com".*') + assert topo.ds_access_log.match(r'.*\(Internal\) op=[0-9]+\([0-9]+\)\([0-9]+\) ' + r'MOD dn="cn=group,ou=Groups,dc=example,dc=com".*') # (Internal) op=10(1)(2) SRCH base="cn=group,ou=Groups,dc=example,dc=com" - assert topo.ds_access_log.match(r'.*\(Internal\) op=10\(1\)\(2\) SRCH base="cn=group,ou=Groups,dc=example,dc=com".*') + assert topo.ds_access_log.match(r'.*\(Internal\) op=[0-9]+\([0-9]+\)\([0-9]+\) ' + r'SRCH base="cn=group,ou=Groups,dc=example,dc=com".*') # (Internal) op=10(1)(2) RESULT err=0 tag=48 nentries=1*') - assert topo.ds_access_log.match(r'.*\(Internal\) op=10\(1\)\(2\) RESULT err=0 tag=48 nentries=1*') + assert topo.ds_access_log.match(r'.*\(Internal\) op=[0-9]+\([0-9]+\)\([0-9]+\) RESULT err=0 tag=48 nentries=1*') # (Internal) op=10(1)(1) RESULT err=0 tag=48 - assert topo.ds_access_log.match(r'.*\(Internal\) op=10\(1\)\(1\) RESULT err=0 tag=48.*') + assert topo.ds_access_log.match(r'.*\(Internal\) op=[0-9]+\([0-9]+\)\([0-9]+\) RESULT err=0 tag=48.*') # op=10 RESULT err=0 tag=105 - assert not topo.ds_access_log.match(r'.*op=10 RESULT err=0 tag=105.*') + assert not topo.ds_access_log.match(r'.*op=[0-9]+ RESULT err=0 tag=105.*') log.info("Check the access logs for MOD operation of the user") # op=12 MODRDN dn="uid=test_user_777,ou=branch1,dc=example,dc=com" ' # 'newrdn="uid=new_test_user_777" newsuperior="dc=example,dc=com" - assert not topo.ds_access_log.match(r'.*op=12 MODRDN dn="uid=test_user_777,ou=branch1,dc=example,dc=com" ' + assert not topo.ds_access_log.match(r'.*op=[0-9]+ MODRDN dn="uid=test_user_777,ou=branch1,dc=example,dc=com" ' 'newrdn="uid=new_test_user_777" newsuperior="dc=example,dc=com".*') # (Internal) op=12(1)(1) SRCH base="uid=test_user_777, ou=branch1,dc=example,dc=com" - assert topo.ds_access_log.match(r'.*\(Internal\) op=12\(1\)\(1\) SRCH base="uid=test_user_777,' + assert topo.ds_access_log.match(r'.*\(Internal\) op=[0-9]+\([0-9]+\)\([0-9]+\) SRCH base="uid=test_user_777,' 'ou=branch1,dc=example,dc=com".*') # (Internal) op=12(1)(1) RESULT err=0 tag=48 nentries=1 - assert topo.ds_access_log.match(r'.*\(Internal\) op=12\(1\)\(1\) RESULT err=0 tag=48 nentries=1.*') + assert topo.ds_access_log.match(r'.*\(Internal\) op=[0-9]+\([0-9]+\)\([0-9]+\) RESULT err=0 tag=48 nentries=1.*') # op=12 RESULT err=0 tag=109 - assert not topo.ds_access_log.match(r'.*op=12 RESULT err=0 tag=109.*') + assert not topo.ds_access_log.match(r'.*op=[0-9]+ RESULT err=0 tag=109.*') log.info("Check the access logs for DEL operation of the user") # op=15 DEL dn="uid=new_test_user_777,dc=example,dc=com" - assert not topo.ds_access_log.match(r'.*op=15 DEL dn="uid=new_test_user_777,dc=example,dc=com".*') + assert not topo.ds_access_log.match(r'.*op=[0-9]+ DEL dn="uid=new_test_user_777,dc=example,dc=com".*') # (Internal) op=15(1)(1) SRCH base="uid=new_test_user_777, dc=example,dc=com" - assert topo.ds_access_log.match(r'.*\(Internal\) op=15\(1\)\(1\) SRCH base="uid=new_test_user_777,' + assert topo.ds_access_log.match(r'.*\(Internal\) op=[0-9]+\([0-9]+\)\([0-9]+\) SRCH base="uid=new_test_user_777,' 'dc=example,dc=com".*') # (Internal) op=15(1)(1) RESULT err=0 tag=48 nentries=1 - assert topo.ds_access_log.match(r'.*\(Internal\) op=15\(1\)\(1\) RESULT err=0 tag=48 nentries=1.*') + assert topo.ds_access_log.match(r'.*\(Internal\) op=[0-9]+\([0-9]+\)\([0-9]+\) RESULT err=0 tag=48 nentries=1.*') # op=15 RESULT err=0 tag=107 - assert not topo.ds_access_log.match(r'.*op=15 RESULT err=0 tag=107.*') + assert not topo.ds_access_log.match(r'.*op=[0-9]+ RESULT err=0 tag=107.*') log.info("Check if the other internal operations have the correct format") # conn=Internal(0) op=0 - assert topo.ds_access_log.match(r'.*conn=Internal\(0\) op=0.*') + assert topo.ds_access_log.match(r'.*conn=Internal\([0-9]+\) op=[0-9]+\([0-9]+\)\([0-9]+\).*') log.info('Delete the previous access logs for the next test') topo.deleteAccessLogs() @@ -558,56 +564,59 @@ def test_internal_log_level_516(topology_st, add_user_log_level_516): log.info('Restart the server to flush the logs') topo.restart() - # These comments contain lines we are trying to find without regex + # These comments contain lines we are trying to find without regex (the op numbers are just examples) log.info("Check the access logs for ADD operation of the user") # op=10 ADD dn="uid=test_user_777,ou=branch1,dc=example,dc=com" - assert not topo.ds_access_log.match(r'.*op=10 ADD dn="uid=test_user_777,ou=branch1,dc=example,dc=com".*') + assert not topo.ds_access_log.match(r'.*op=[0-9]+ ADD dn="uid=test_user_777,ou=branch1,dc=example,dc=com".*') # (Internal) op=10(1)(1) MOD dn="cn=group,ou=Groups,dc=example,dc=com" - assert topo.ds_access_log.match(r'.*\(Internal\) op=10\(1\)\(1\) MOD dn="cn=group,ou=Groups,dc=example,dc=com".*') + assert topo.ds_access_log.match(r'.*\(Internal\) op=[0-9]+\([0-9]+\)\([0-9]+\) ' + r'MOD dn="cn=group,ou=Groups,dc=example,dc=com".*') # (Internal) op=10(1)(2) SRCH base="cn=group,ou=Groups,dc=example,dc=com" - assert topo.ds_access_log.match(r'.*\(Internal\) op=10\(1\)\(2\) SRCH base="cn=group,ou=Groups,dc=example,dc=com".*') + assert topo.ds_access_log.match(r'.*\(Internal\) op=[0-9]+\([0-9]+\)\([0-9]+\) ' + r'SRCH base="cn=group,ou=Groups,dc=example,dc=com".*') # (Internal) op=10(1)(2) ENTRY dn="cn=group,ou=Groups,dc=example,dc=com" - assert topo.ds_access_log.match(r'.*\(Internal\) op=10\(1\)\(2\) ENTRY dn="cn=group,ou=Groups,dc=example,dc=com".*') + assert topo.ds_access_log.match(r'.*\(Internal\) op=[0-9]+\([0-9]+\)\([0-9]+\) ' + r'ENTRY dn="cn=group,ou=Groups,dc=example,dc=com".*') # (Internal) op=10(1)(2) RESULT err=0 tag=48 nentries=1*') - assert topo.ds_access_log.match(r'.*\(Internal\) op=10\(1\)\(2\) RESULT err=0 tag=48 nentries=1*') + assert topo.ds_access_log.match(r'.*\(Internal\) op=[0-9]+\([0-9]+\)\([0-9]+\) RESULT err=0 tag=48 nentries=1*') # (Internal) op=10(1)(1) RESULT err=0 tag=48 - assert topo.ds_access_log.match(r'.*\(Internal\) op=10\(1\)\(1\) RESULT err=0 tag=48.*') + assert topo.ds_access_log.match(r'.*\(Internal\) op=[0-9]+\([0-9]+\)\([0-9]+\) RESULT err=0 tag=48.*') # op=10 RESULT err=0 tag=105 - assert not topo.ds_access_log.match(r'.*op=10 RESULT err=0 tag=105.*') + assert not topo.ds_access_log.match(r'.*op=[0-9]+ RESULT err=0 tag=105.*') log.info("Check the access logs for MOD operation of the user") # op=12 MODRDN dn="uid=test_user_777,ou=branch1,dc=example,dc=com" ' # 'newrdn="uid=new_test_user_777" newsuperior="dc=example,dc=com" - assert not topo.ds_access_log.match(r'.*op=12 MODRDN dn="uid=test_user_777,ou=branch1,dc=example,dc=com" ' + assert not topo.ds_access_log.match(r'.*op=[0-9]+ MODRDN dn="uid=test_user_777,ou=branch1,dc=example,dc=com" ' 'newrdn="uid=new_test_user_777" newsuperior="dc=example,dc=com".*') # Internal) op=12(1)(1) SRCH base="uid=test_user_777, ou=branch1,dc=example,dc=com" - assert topo.ds_access_log.match(r'.*\(Internal\) op=12\(1\)\(1\) SRCH base="uid=test_user_777,' + assert topo.ds_access_log.match(r'.*\(Internal\) op=[0-9]+\([0-9]+\)\([0-9]+\) SRCH base="uid=test_user_777,' 'ou=branch1,dc=example,dc=com".*') # (Internal) op=12(1)(1) ENTRY dn="uid=test_user_777, ou=branch1,dc=example,dc=com" - assert topo.ds_access_log.match(r'.*\(Internal\) op=12\(1\)\(1\) ENTRY dn="uid=test_user_777,' + assert topo.ds_access_log.match(r'.*\(Internal\) op=[0-9]+\([0-9]+\)\([0-9]+\) ENTRY dn="uid=test_user_777,' 'ou=branch1,dc=example,dc=com".*') # (Internal) op=12(1)(1) RESULT err=0 tag=48 nentries=1 - assert topo.ds_access_log.match(r'.*\(Internal\) op=12\(1\)\(1\) RESULT err=0 tag=48 nentries=1.*') + assert topo.ds_access_log.match(r'.*\(Internal\) op=[0-9]+\([0-9]+\)\([0-9]+\) RESULT err=0 tag=48 nentries=1.*') # op=12 RESULT err=0 tag=109 - assert not topo.ds_access_log.match(r'.*op=12 RESULT err=0 tag=109.*') + assert not topo.ds_access_log.match(r'.*op=[0-9]+ RESULT err=0 tag=109.*') log.info("Check the access logs for DEL operation of the user") # op=15 DEL dn="uid=new_test_user_777,dc=example,dc=com" - assert not topo.ds_access_log.match(r'.*op=15 DEL dn="uid=new_test_user_777,dc=example,dc=com".*') + assert not topo.ds_access_log.match(r'.*op=[0-9]+ DEL dn="uid=new_test_user_777,dc=example,dc=com".*') # (Internal) op=15(1)(1) SRCH base="uid=new_test_user_777, dc=example,dc=com" - assert topo.ds_access_log.match(r'.*\(Internal\) op=15\(1\)\(1\) SRCH base="uid=new_test_user_777,' + assert topo.ds_access_log.match(r'.*\(Internal\) op=[0-9]+\([0-9]+\)\([0-9]+\) SRCH base="uid=new_test_user_777,' 'dc=example,dc=com".*') # (Internal) op=15(1)(1) ENTRY dn="uid=new_test_user_777, dc=example,dc=com" - assert topo.ds_access_log.match(r'.*\(Internal\) op=15\(1\)\(1\) ENTRY dn="uid=new_test_user_777,' + assert topo.ds_access_log.match(r'.*\(Internal\) op=[0-9]+\([0-9]+\)\([0-9]+\) ENTRY dn="uid=new_test_user_777,' 'dc=example,dc=com".*') # (Internal) op=15(1)(1) RESULT err=0 tag=48 nentries=1 - assert topo.ds_access_log.match(r'.*\(Internal\) op=15\(1\)\(1\) RESULT err=0 tag=48 nentries=1.*') + assert topo.ds_access_log.match(r'.*\(Internal\) op=[0-9]+\([0-9]+\)\([0-9]+\) RESULT err=0 tag=48 nentries=1.*') # op=15 RESULT err=0 tag=107 - assert not topo.ds_access_log.match(r'.*op=15 RESULT err=0 tag=107.*') + assert not topo.ds_access_log.match(r'.*op=[0-9]+ RESULT err=0 tag=107.*') log.info("Check if the other internal operations have the correct format") # conn=Internal(0) op=0 - assert topo.ds_access_log.match(r'.*conn=Internal\(0\) op=0.*') + assert topo.ds_access_log.match(r'.*conn=Internal\([0-9]+\) op=[0-9]+\([0-9]+\)\([0-9]+\).*') log.info('Delete the previous access logs for the next test') topo.deleteAccessLogs() diff --git a/src/lib389/lib389/dirsrv_log.py b/src/lib389/lib389/dirsrv_log.py index 1a626c2b9..b23fbe7bb 100644 --- a/src/lib389/lib389/dirsrv_log.py +++ b/src/lib389/lib389/dirsrv_log.py @@ -46,8 +46,8 @@ class DirsrvLog(object): """ self.dirsrv = dirsrv self.log = self.dirsrv.log - self.prog_timestamp = re.compile('\[(?P<day>\d*)\/(?P<month>\w*)\/(?P<year>\d*):(?P<hour>\d*):(?P<minute>\d*):(?P<second>\d*)(.(?P<nanosecond>\d*))+\s(?P<tz>[\+\-]\d*)') # noqa - self.prog_datetime = re.compile('^(?P<timestamp>\[.*\])') + self.prog_timestamp = re.compile(r'\[(?P<day>\d*)\/(?P<month>\w*)\/(?P<year>\d*):(?P<hour>\d*):(?P<minute>\d*):(?P<second>\d*)(.(?P<nanosecond>\d*))+\s(?P<tz>[\+\-]\d*)') # noqa + self.prog_datetime = re.compile(r'^(?P<timestamp>\[.*\])') def _get_log_path(self): """Return the current log file location""" @@ -180,13 +180,13 @@ class DirsrvAccessLog(DirsrvLog): """ super(DirsrvAccessLog, self).__init__(dirsrv) ## We precompile our regex for parse_line to make it faster. - self.prog_m1 = re.compile('^(?P<timestamp>\[.*\])\sconn=(?P<conn>\d*)\sop=(?P<op>\d*)\s(?P<action>\w*)\s(?P<rem>.*)') - self.prog_con = re.compile('^(?P<timestamp>\[.*\])\sconn=(?P<conn>\d*)\sfd=(?P<fd>\d*)\sslot=(?P<slot>\d*)\sconnection\sfrom\s(?P<remote>[^\s]*)\sto\s(?P<local>[^\s]*)') - self.prog_discon = re.compile('^(?P<timestamp>\[.*\])\sconn=(?P<conn>\d*)\sop=(?P<op>\d*)\sfd=(?P<fd>\d*)\s(?P<action>closed)\s-\s(?P<status>\w*)') + self.prog_m1 = re.compile(r'^(?P<timestamp>\[.*\])\sconn=(?P<conn>\d*)\sop=(?P<op>\d*)\s(?P<action>\w*)\s(?P<rem>.*)') + self.prog_con = re.compile(r'^(?P<timestamp>\[.*\])\sconn=(?P<conn>\d*)\sfd=(?P<fd>\d*)\sslot=(?P<slot>\d*)\sconnection\sfrom\s(?P<remote>[^\s]*)\sto\s(?P<local>[^\s]*)') + self.prog_discon = re.compile(r'^(?P<timestamp>\[.*\])\sconn=(?P<conn>\d*)\sop=(?P<op>\d*)\sfd=(?P<fd>\d*)\s(?P<action>closed)\s-\s(?P<status>\w*)') # RESULT regex's (based off action.rem) - self.prog_notes = re.compile('err=(?P<err>\d*)\stag=(?P<tag>\d*)\snentries=(?P<nentries>\d*)\setime=(?P<etime>[0-9.]*)\snotes=(?P<notes>\w*)') - self.prog_repl = re.compile('err=(?P<err>\d*)\stag=(?P<tag>\d*)\snentries=(?P<nentries>\d*)\setime=(?P<etime>[0-9.]*)\scsn=(?P<csn>\w*)') - self.prog_result = re.compile('err=(?P<err>\d*)\stag=(?P<tag>\d*)\snentries=(?P<nentries>\d*)\setime=(?P<etime>[0-9.]*)\s(?P<rem>.*)') + self.prog_notes = re.compile(r'err=(?P<err>\d*)\stag=(?P<tag>\d*)\snentries=(?P<nentries>\d*)\setime=(?P<etime>[0-9.]*)\snotes=(?P<notes>\w*)') + self.prog_repl = re.compile(r'err=(?P<err>\d*)\stag=(?P<tag>\d*)\snentries=(?P<nentries>\d*)\setime=(?P<etime>[0-9.]*)\scsn=(?P<csn>\w*)') + self.prog_result = re.compile(r'err=(?P<err>\d*)\stag=(?P<tag>\d*)\snentries=(?P<nentries>\d*)\setime=(?P<etime>[0-9.]*)\s(?P<rem>.*)') # Lists for each regex type self.full_regexs = [self.prog_m1, self.prog_con, self.prog_discon] self.result_regexs = [self.prog_notes, self.prog_repl, @@ -246,7 +246,7 @@ class DirsrvErrorLog(DirsrvLog): @param diursrv - A DirSrv object """ super(DirsrvErrorLog, self).__init__(dirsrv) - self.prog_m1 = re.compile('^(?P<timestamp>\[.*\])\s(?P<message>.*)') + self.prog_m1 = re.compile(r'^(?P<timestamp>\[.*\])\s(?P<message>.*)') def _get_log_path(self): """Return the current log file location"""
0
4fbfc2e086c226e9a94b9afa8d1fc4efaab3a9aa
389ds/389-ds-base
Ticket 48141 - aci with wildcard and macro not correctly evaluated if an acis contains macros and wildcards the evaluation can fail if the macro part does not align with dn components. Since this alignment is not enforced inman cases, the combination with wild card should also work. To fix the issue a check was introduced if the char before or after the macro is ','. Then the old code path is taken, in other cases a new evaluation routine is added https://fedorahosted.org/389/ticket/48141 Review: noriko, thanks
commit 4fbfc2e086c226e9a94b9afa8d1fc4efaab3a9aa Author: Ludwig Krispenz <[email protected]> Date: Tue Jun 9 09:47:57 2015 +0200 Ticket 48141 - aci with wildcard and macro not correctly evaluated if an acis contains macros and wildcards the evaluation can fail if the macro part does not align with dn components. Since this alignment is not enforced inman cases, the combination with wild card should also work. To fix the issue a check was introduced if the char before or after the macro is ','. Then the old code path is taken, in other cases a new evaluation routine is added https://fedorahosted.org/389/ticket/48141 Review: noriko, thanks diff --git a/ldap/servers/plugins/acl/aclutil.c b/ldap/servers/plugins/acl/aclutil.c index 619f857a8..b97f073f9 100644 --- a/ldap/servers/plugins/acl/aclutil.c +++ b/ldap/servers/plugins/acl/aclutil.c @@ -847,7 +847,13 @@ acl_match_macro_in_target( const char *ndn, char * match_this, if ( strstr(macro_prefix, "=*") != NULL ) { int exact_match = 0; - ndn_prefix_len = acl_match_prefix( macro_prefix, ndn, &exact_match); + if (macro_prefix[macro_prefix_len-1] == ',') { + /* macro aligns with dn components */ + ndn_prefix_len = acl_match_prefix( macro_prefix, ndn, &exact_match); + } else { + /* do a initial * final substring match */ + ndn_prefix_len = acl_match_substr_prefix( macro_prefix, ndn, &exact_match); + } if ( ndn_prefix_len != -1 ) { /* @@ -951,10 +957,14 @@ acl_match_macro_in_target( const char *ndn, char * match_this, * ndn[ndn_prefix_end..mndn_len-macro_suffix_len] * the -1 is because macro_suffix_eln does not include * the coma before the suffix. + * + * there are cases where the macro does end inside a dn component */ matched_val_len = ndn_len-macro_suffix_len- - ndn_prefix_end - 1; + ndn_prefix_end; + if (ndn[ndn_len - macro_suffix_len] == ',') + matched_val_len -= 1; matched_val = (char *)slapi_ch_malloc(matched_val_len + 1); strncpy(matched_val, &ndn[ndn_prefix_end], @@ -971,6 +981,24 @@ acl_match_macro_in_target( const char *ndn, char * match_this, return(ret_val); } +int +acl_match_substr_prefix( char *macro_prefix, const char *ndn, int *exact_match) { + int ret_code = -1; + char *tmp_str = NULL; + int initial, any, final; + + *exact_match = 0; + tmp_str = slapi_ch_strdup(macro_prefix); + any = acl_strstr(tmp_str, "*"); + tmp_str[any] = '\0'; + initial = acl_strstr(ndn, tmp_str); + if (initial >= 0) { + final = acl_strstr(&ndn[initial+strlen(tmp_str)],&tmp_str[any+1]); + if (final > 0) ret_code = initial + strlen(tmp_str) +final + strlen(&tmp_str[any+1]); + } + slapi_ch_free_string(&tmp_str); + return (ret_code); +} /* * Checks to see if macro_prefix is an exact prefix of ndn. * macro_prefix may contain a * component.
0
41ff269732f1d1b9df29b5e24d152dd432aa0e2e
389ds/389-ds-base
Ticket 49134 Remove hardcoded elements from db lock test Bug Description: Autotuning broke the dblock test, that expect our default cache to be hardcoded. Fix Description: Remove the (pointless) check for our dbcache value. https://pagure.io/389-ds-base/issue/49134 Author: wibrown Review by: mreynolds (Thanks!)
commit 41ff269732f1d1b9df29b5e24d152dd432aa0e2e Author: William Brown <[email protected]> Date: Fri Feb 17 16:35:13 2017 +1000 Ticket 49134 Remove hardcoded elements from db lock test Bug Description: Autotuning broke the dblock test, that expect our default cache to be hardcoded. Fix Description: Remove the (pointless) check for our dbcache value. https://pagure.io/389-ds-base/issue/49134 Author: wibrown Review by: mreynolds (Thanks!) diff --git a/dirsrvtests/tests/tickets/ticket48906_test.py b/dirsrvtests/tests/tickets/ticket48906_test.py index aea422703..baa977979 100644 --- a/dirsrvtests/tests/tickets/ticket48906_test.py +++ b/dirsrvtests/tests/tickets/ticket48906_test.py @@ -37,7 +37,6 @@ DBLOCK_ATTR_CONFIG = "nsslapd-db-locks" DBLOCK_ATTR_MONITOR = "nsslapd-db-configured-locks" DBLOCK_ATTR_GUARDIAN = "locks" -DBCACHE_DEFAULT = "33554432" DBCACHE_LDAP_UPDATE = "20000000" DBCACHE_EDIT_UPDATE = "40000000" DBCACHE_ATTR_CONFIG = "nsslapd-dbcachesize" @@ -151,7 +150,6 @@ def test_ticket48906_dblock_default(topology_st): topology_st.standalone.log.info('###################################') _check_monitored_value(topology_st, DBLOCK_DEFAULT) _check_configured_value(topology_st, attr=DBLOCK_ATTR_CONFIG, expected_value=DBLOCK_DEFAULT, required=False) - _check_configured_value(topology_st, attr=DBCACHE_ATTR_CONFIG, expected_value=DBCACHE_DEFAULT, required=False) def test_ticket48906_dblock_ldap_update(topology_st):
0
ea64bb776b54e43e117d516e7e0e818d48287370
389ds/389-ds-base
149510 More ACL system code cleanup. Fix several compiler warnings, simplify some includes.
commit ea64bb776b54e43e117d516e7e0e818d48287370 Author: Rob Crittenden <[email protected]> Date: Mon Mar 7 14:45:22 2005 +0000 149510 More ACL system code cleanup. Fix several compiler warnings, simplify some includes. diff --git a/httpd/src/ntnsapi.c b/httpd/src/ntnsapi.c index 4e545f121..bf3f10736 100644 --- a/httpd/src/ntnsapi.c +++ b/httpd/src/ntnsapi.c @@ -15,7 +15,6 @@ #include <libadmin/libadmin.h> #include <libaccess/aclproto.h> -#include <libaccess/nsadb.h> #include <base/fsmutex.h> #include <i18n.h> #include <base/ereport.h> diff --git a/include/base/crit.h b/include/base/crit.h index ad0ed09ae..03c46baba 100644 --- a/include/base/crit.h +++ b/include/base/crit.h @@ -24,11 +24,6 @@ #include "netsite.h" #endif /* !NETSITE_H */ -/* Define C interface */ -#ifndef PUBLIC_BASE_CRIT_H -#include "public/base/crit.h" -#endif /* !PUBLIC_BASE_CRIT_H */ - /* Define C++ interface */ #ifdef __cplusplus diff --git a/include/base/ereport.h b/include/base/ereport.h index e067a84e3..9ef44e16b 100644 --- a/include/base/ereport.h +++ b/include/base/ereport.h @@ -16,10 +16,6 @@ * Rob McCool */ -#ifndef PUBLIC_BASE_EREPORT_H -#include "public/base/ereport.h" -#endif /* !PUBLIC_BASE_EREPORT_H */ - /* --- Begin function prototypes --- */ #ifdef INTNSAPI diff --git a/include/base/file.h b/include/base/file.h index c4ff47c34..869cf3f87 100644 --- a/include/base/file.h +++ b/include/base/file.h @@ -19,10 +19,6 @@ #include "../netsite.h" #endif /* !NETSITE_H */ -#ifndef PUBLIC_BASE_FILE_H -#include "public/base/file.h" -#endif /* !PUBLIC_BASE_FILE_H */ - /* --- Begin function prototypes --- */ #ifdef INTNSAPI diff --git a/include/base/pool.h b/include/base/pool.h index 8c8bf91b4..b883e24ec 100644 --- a/include/base/pool.h +++ b/include/base/pool.h @@ -30,10 +30,6 @@ #include "netsite.h" #endif /* !NETSITE_H */ -#ifndef PUBLIC_BASE_POOL_H -#include "public/base/pool.h" -#endif /* !PUBLIC_BASE_POOL_H */ - /* --- Begin function prototypes --- */ #ifdef INTNSAPI diff --git a/include/base/shexp.h b/include/base/shexp.h index a1e68c3e9..1ed6cf0d0 100644 --- a/include/base/shexp.h +++ b/include/base/shexp.h @@ -72,10 +72,6 @@ #endif /* USE_REGEX */ #endif /* !MCC_PROXY */ -#ifndef PUBLIC_BASE_SHEXP_H -#include "public/base/shexp.h" -#endif /* !PUBLIC_BASE_SHEXP_H */ - /* --- Begin function prototypes --- */ #ifdef INTNSAPI diff --git a/include/base/systems.h b/include/base/systems.h index 1e77faf23..b1ce1188b 100644 --- a/include/base/systems.h +++ b/include/base/systems.h @@ -256,7 +256,6 @@ #define NEED_SETEID_PROTO /* setegid, seteuid */ #define NET_SOCKETS #define SHMEM_MMAP_FLAGS MAP_SHARED -#define TCPLEN_T size_t #define USE_PIPE /* * define this if your C++ platform has separate inline functions for @@ -449,6 +448,7 @@ typedef void* PASSWD; #include "public/base/systems.h" #endif /* PUBLIC_BASE_SYSTEMS_H */ + /* --- Begin defaults for values not defined above --- */ #ifndef DAEMON_LISTEN_SIZE @@ -465,10 +465,6 @@ typedef void* PASSWD; #define CONSTVALSTRCAST #endif -#ifndef TCPLEN_T -#define TCPLEN_T int -#endif - #ifndef THROW_HACK #define THROW_HACK /* as nothing */ #endif diff --git a/include/base/systhr.h b/include/base/systhr.h index 12cae43ce..7d7efee11 100644 --- a/include/base/systhr.h +++ b/include/base/systhr.h @@ -22,10 +22,6 @@ #ifdef THREAD_ANY -#ifndef PUBLIC_BASE_SYSTHR_H -#include "public/base/systhr.h" -#endif /* !PUBLIC_BASE_SYSTHR_H */ - /* --- Begin function prototypes --- */ #ifdef INTNSAPI diff --git a/include/base/util.h b/include/base/util.h index dfd260383..467247b2c 100644 --- a/include/base/util.h +++ b/include/base/util.h @@ -17,9 +17,10 @@ * Rob McCool */ -#ifndef PUBLIC_BASE_UTIL_H -#include "public/base/util.h" -#endif /* !PUBLIC_BASE_UTIL_H */ +#ifndef PUBLIC_NSAPI_H +#include "public/nsapi.h" +#endif /* !PUBLIC_NSAPI_H */ + /* --- Begin common function prototypes --- */ @@ -68,20 +69,10 @@ NSPR_END_EXTERN_C #define util_strncasecmp INTutil_strncasecmp #define util_localtime INTutil_localtime -#ifdef NEED_STRCASECMP -#define util_strcasecmp INTutil_strcasecmp -#define strcasecmp INTutil_strcasecmp -#endif /* NEED_STRCASECMP */ - #ifdef NEED_STRINGS_H /* usually for strcasecmp */ #include <strings.h> #endif -#ifdef NEED_STRNCASECMP -#define util_strncasecmp INTutil_strncasecmp -#define strncasecmp INTutil_strncasecmp -#endif /* NEED_STRNCASECMP */ - #endif /* INTNSAPI */ #endif /* !BASE_UTIL_H */ diff --git a/include/netsite.h b/include/netsite.h index 716d737a1..e9f443d25 100644 --- a/include/netsite.h +++ b/include/netsite.h @@ -41,69 +41,6 @@ #include "base/systems.h" #endif /* !BASE_SYSTEMS_H */ -#undef MAGNUS_VERSION_STRING - -#ifdef MCC_PROXY -#define MAGNUS_VERSION PROXY_VERSION_DEF -#define MAGNUS_VERSION_STRING PROXY_VERSION_STRING - -#elif defined(NS_CMS) -#define MAGNUS_VERSION CMS_VERSION_DEF -#define MAGNUS_VERSION_STRING CMS_VERSION_STRING - -#elif defined(NS_DS) -#define MAGNUS_VERSION DS_VERSION_DEF -#define MAGNUS_VERSION_STRING DS_VERSION_STRING - -#elif defined(MCC_ADMSERV) -#define MAGNUS_VERSION ADMSERV_VERSION_DEF -#define MAGNUS_VERSION_STRING ADMSERV_VERSION_STRING - -#elif defined(NS_CATALOG) -#define MAGNUS_VERSION CATALOG_VERSION_DEF -#define MAGNUS_VERSION_STRING CATALOG_VERSION_STRING - -#elif defined(NS_RDS) -#define MAGNUS_VERSION RDS_VERSION_DEF -#define MAGNUS_VERSION_STRING RDS_VERSION_STRING - -#elif defined(MCC_HTTPD) - -#ifdef NS_PERSONAL -#define MAGNUS_VERSION PERSONAL_VERSION_DEF -#else -#define MAGNUS_VERSION ENTERPRISE_VERSION_DEF -#endif - -#if defined(XP_UNIX) || defined(USE_ADMSERV) -#if defined(NS_DS) -#define MAGNUS_VERSION_STRING DS_VERSION_STRING -#elif defined(NS_PERSONAL) -#define MAGNUS_VERSION_STRING PERSONAL_VERSION_STRING -#elif defined(NS_CATALOG) -#define MAGNUS_VERSION_STRING CATALOG_VERSION_STRING -#elif defined(NS_RDS) -#define MAGNUS_VERSION_STRING RDS_VERSION_STRING -#elif defined(NS_CMS) -#define MAGNUS_VERSION_STRING CMS_VERSION_STRING -#else -#define MAGNUS_VERSION_STRING ENTERPRISE_VERSION_STRING -#endif -#endif /* XP_UNIX */ - -#elif defined(MCC_NEWS) -#define MAGNUS_VERSION_STRING NEWS_VERSION_STRING - -#elif defined(NS_MAIL) -#define MAGNUS_VERSION MAIL_VERSION_DEF -#define MAGNUS_VERSION_STRING MAIL_VERSION_STRING - -#elif defined(MCC_BATMAN) -#define MAGNUS_VERSION BATMAN_VERSION_DEF -#define MAGNUS_VERSION_STRING BATMAN_VERSION_STRING - -#endif - #ifndef VOID #define VOID void #endif @@ -147,33 +84,6 @@ typedef int boolean; NSPR_BEGIN_EXTERN_C -/* -------------------------- System version on NT------------------------- */ - -/* Encode the server version as a number to be able to provide inexpensive - * dynamic checks on server version - this isn't added in yet. */ - -#define ENTERPRISE_VERSION 1 -#define PERSONAL_VERSION 2 -#define CATALOG_VERSION 3 -#define RDS_VERSION 4 -#define CMS_VERSION 5 -#undef DS_VERSION -#define DS_VERSION 6 - -#define server_fasttrack (!strcmp(MAGNUS_VERSION_STRING, PERSONAL_VERSION_STRING)) -#define server_enterprise (!strcmp(MAGNUS_VERSION_STRING, ENTERPRISE_VERSION_STRING)) - -/* This definition of MAGNUS_VERSION_STRING on NT should be used - * only when building the ns-http DLL */ - -#if defined(MCC_HTTPD) && defined(XP_WIN32) && !defined(USE_ADMSERV) && !defined(MCC_ADMSERV) -#undef MAGNUS_VERSION_STRING -#define MAGNUS_VERSION_STRING INTsystem_version() -#endif /* XP_WIN32 */ - -/* Set server's version dynamically */ -NSAPI_PUBLIC void INTsystem_version_set(char *ptr); - #ifndef APSTUDIO_READONLY_SYMBOLS /* Include the public netsite.h definitions */ diff --git a/include/public/base/systems.h b/include/public/base/systems.h index 64ccd05d7..318206a86 100644 --- a/include/public/base/systems.h +++ b/include/public/base/systems.h @@ -27,9 +27,6 @@ #define ZERO(ptr,len) memset(ptr,0,len) #define NEED_STRCASECMP #define NEED_STRNCASECMP -#if OSVERSION > 4200 -#define TCPLEN_T size_t -#endif /* OSVERSION > 4200 */ #elif defined(BSDI) @@ -168,7 +165,6 @@ #define SEM_FLOCK #define SHMEM_UNIX_MMAP #define ZERO(ptr,len) memset(ptr,0,len) -#define TCPLEN_T size_t #elif defined(Linux) diff --git a/include/public/nsacl/aclapi.h b/include/public/nsacl/aclapi.h index 428ac9a79..b7d9c2d61 100644 --- a/include/public/nsacl/aclapi.h +++ b/include/public/nsacl/aclapi.h @@ -18,9 +18,9 @@ #include "nserrdef.h" #endif /* !PUBLIC_NSACL_NSERRDEF_H */ -#ifndef PUBLIC_BASE_POOL_H -#include "../base/pool.h" -#endif /* !PUBLIC_BASE_POOL_H */ +#ifndef PUBLIC_NSAPI_H +#include "public/nsapi.h" +#endif /* !PUBLIC_NSAPI_H */ #ifndef PUBLIC_NSACL_PLISTDEF_H #include "plistdef.h" diff --git a/include/public/nsacl/plistdef.h b/include/public/nsacl/plistdef.h index b0de83821..50bf741e6 100644 --- a/include/public/nsacl/plistdef.h +++ b/include/public/nsacl/plistdef.h @@ -15,9 +15,9 @@ * lists are a generalization of parameter blocks (pblocks). */ -#ifndef PUBLIC_BASE_POOL_H -#include "../base/pool.h" -#endif /* !PUBLIC_BASE_POOL_H */ +#ifndef PUBLIC_NSAPI_H +#include "public/nsapi.h" +#endif /* !PUBLIC_NSAPI_H */ typedef struct PListStruct_s *PList_t; diff --git a/ldap/clients/dsgw/dsgw.h b/ldap/clients/dsgw/dsgw.h index 909ca833c..224a2f6f9 100644 --- a/ldap/clients/dsgw/dsgw.h +++ b/ldap/clients/dsgw/dsgw.h @@ -32,8 +32,6 @@ #include "../../include/srchpref.h" #if defined( XP_WIN32 ) -#define util_strcasecmp strcasecomp -#define util_strncasecmp strncasecomp #include "base/systems.h" #include "proto-ntutil.h" diff --git a/lib/base/system.cpp b/lib/base/system.cpp index 556d94a43..88bbfe438 100644 --- a/lib/base/system.cpp +++ b/lib/base/system.cpp @@ -15,7 +15,6 @@ #ifdef XP_WIN32 #include <windows.h> -static char *version = "Netscape Server/2.0"; #endif #include "base/systems.h" /* find out if we have malloc pools */ @@ -52,29 +51,6 @@ static int thread_malloc_key = -1; #define DEBUG_FREE_CHAR 'X' #endif /* DEBUG_MALLOC */ - -/* On NT, the server version string is not statically encoded based - * upon a product compile define but dynamically set by the server - * exe at startup. - */ - -NSAPI_PUBLIC char *system_version() -{ -#ifdef XP_WIN32 - return version; -#else /* XP_UNIX */ - return MAGNUS_VERSION_STRING; -#endif /* XP_UNIX */ -} - -NSAPI_PUBLIC void system_version_set(char *server_version) -{ -#ifdef XP_WIN32 - version = PERM_STRDUP(server_version); -#endif -} - - NSAPI_PUBLIC void *system_malloc(int size) { #if defined(MALLOC_POOLS) && defined(MCC_HTTPD) && defined(THREAD_ANY) diff --git a/lib/libaccess/Makefile b/lib/libaccess/Makefile index 8fb857b8f..d7d270cdb 100644 --- a/lib/libaccess/Makefile +++ b/lib/libaccess/Makefile @@ -40,11 +40,7 @@ $(UTESTDEST): OSOBJS = OBJS=$(addprefix $(OBJDEST)/, usi.o \ - attrec.o \ nseframe.o \ - nsdb.o \ - nsuser.o \ - nsgroup.o \ nsautherr.o \ symbols.o \ acltools.o \ @@ -67,23 +63,9 @@ OBJS=$(addprefix $(OBJDEST)/, usi.o \ acleval.o \ oneeval.o \ access_plhash.o \ - aclparse.o \ - aclbuild.o \ aclerror.o \ - nsadb.o \ - nscert.o \ - nsamgmt.o \ - nsgmgmt.o \ - nsdbmgmt.o \ - nsumgmt.o \ $(OSOBJS) \ ) - - -# -# AVA Mapping files. Currently not compiled in (FORTEZZA for reference only). -# -AVAMAPFILES = lex.yy.o y.tab.o avapfile.o avadb.o MODULE_CFLAGS=-I$(BUILD_ROOT)/include -DACL_LIB_INTERNAL $(TESTFLAGS) @@ -128,47 +110,3 @@ flex: $(LEX) -i aclscan.l sed -f yy-sed lex.yy.c > acl.yy.cpp rm lex.yy.c - -# -# more AVA mapping stuff, needs to be made to work with the other lexx/yacc -# code added for 3.0 -# -#ifeq ($(ARCH), WINNT) -#$(OBJDEST)/y.tab.o: $(OBJDEST)/y.tab.c $(VALUES) $(OBJDEST)/y.tab.h -# $(CC) -c $(CFLAGS) $(MCC_INCLUDE) -I$(OBJDEST) -I. $< -Fo$*.o -#else -#$(OBJDEST)/y.tab.o: $(OBJDEST)/y.tab.c $(OBJDEST)/y.tab.h -# $(CC) -c $(CFLAGS) $(MCC_INCLUDE) -I. -o $*.o $< -#endif -# -#ifeq ($(ARCH), WINNT) -#$(OBJDEST)/y.tab.h: wintab.h -# cp wintab.h $(OBJDEST)/y.tab.h -# -#$(OBJDEST)/y.tab.c: winnt.y -# cp winnt.y $(OBJDEST)/y.tab.c -# -#$(OBJDEST)/values.h: winnt.v -# cp winnt.v $(OBJDEST)/values.h -#else -#$(OBJDEST)/y.tab.h $(OBJDEST)/y.tab.c: avaparse.y -# yacc -d avaparse.y -# mv y.tab.h $(OBJDEST)/ -# mv y.tab.c $(OBJDEST)/ -#endif -# -#$(OBJDEST)/lex.yy.o: $(OBJDEST)/lex.yy.c $(OBJDEST)/y.tab.h -#ifeq ($(ARCH), WINNT) -# $(CC) -c $(CFLAGS) $(MCC_INCLUDE) -I$(OBJDEST) -I. $< -Fo$*.o -#else -# $(CC) -c $(CFLAGS) $(MCC_INCLUDE) -I. -o $*.o $< -#endif -# -#ifeq ($(ARCH), WINNT) -#$(OBJDEST)/lex.yy.c: winnt.l -# cp winnt.l $(OBJDEST)/lex.yy.c -#else -#$(OBJDEST)/lex.yy.c: avascan.l -# lex avascan.l -# mv lex.yy.c $(OBJDEST)/ -#endif diff --git a/lib/libaccess/aclerror.cpp b/lib/libaccess/aclerror.cpp index 3f05e2e9f..a3e7f8aa2 100644 --- a/lib/libaccess/aclerror.cpp +++ b/lib/libaccess/aclerror.cpp @@ -12,6 +12,7 @@ */ #include "base/systems.h" +#include "public/nsapi.h" #ifdef NSPR20 #include "prprf.h" #else @@ -42,6 +43,9 @@ #define aclerrfail XP_GetAdminStr(DBT_AclerrfmtAclerrfail) #define aclerrio XP_GetAdminStr(DBT_AclerrfmtAclerrio) +char * NSAuth_Program = "NSAUTH"; +char * ACL_Program = "NSACL"; /* ACL facility name */ + /* * Description (aclErrorFmt) *
0
fa71a0a9e2e82dd5f15b83f764b7f91723d1623d
389ds/389-ds-base
Ticket 49278 - GetEffectiveRights gives false-negative Bug: If geteffective rights was issued for an non existing entry the mechanism to genrate a template entry no longer worked and no results were returned. Fix: Improve the handling in itreating the result set, so that template entries (if requested) are genereated and are not applied to existing entries. Also some code cleanup in iterate() Reviewed by: Thierry, thanks
commit fa71a0a9e2e82dd5f15b83f764b7f91723d1623d Author: Ludwig Krispenz <[email protected]> Date: Thu Jan 11 15:17:56 2018 +0100 Ticket 49278 - GetEffectiveRights gives false-negative Bug: If geteffective rights was issued for an non existing entry the mechanism to genrate a template entry no longer worked and no results were returned. Fix: Improve the handling in itreating the result set, so that template entries (if requested) are genereated and are not applied to existing entries. Also some code cleanup in iterate() Reviewed by: Thierry, thanks diff --git a/ldap/servers/slapd/opshared.c b/ldap/servers/slapd/opshared.c index 24157120e..46dcf6fba 100644 --- a/ldap/servers/slapd/opshared.c +++ b/ldap/servers/slapd/opshared.c @@ -33,6 +33,7 @@ static char *pwpolicy_lock_attrs_all[] = {"passwordRetryCount", static void compute_limits(Slapi_PBlock *pb); static int send_results_ext(Slapi_PBlock *pb, int send_result, int *nentries, int pagesize, unsigned int *pr_stat); static int process_entry(Slapi_PBlock *pb, Slapi_Entry *e, int send_result); +static void send_entry(Slapi_PBlock *pb, Slapi_Entry *e, Slapi_Operation *operation, char **attrs, int attrsonly, int *pnentries); int op_shared_is_allowed_attr(const char *attr_name, int replicated_op) @@ -1040,6 +1041,31 @@ process_entry(Slapi_PBlock *pb, Slapi_Entry *e, int send_result) return 0; } +static void +send_entry(Slapi_PBlock *pb, Slapi_Entry *e, Slapi_Operation *operation, char **attrs, int attrsonly, int *pnentries) +{ + /* + * It's a regular entry, or it's a referral and + * managedsait control is on. In either case, send + * the entry. + */ + switch (send_ldap_search_entry(pb, e, NULL, attrs, attrsonly)) { + case 0: /* entry sent ok */ + (*pnentries)++; + slapi_pblock_set(pb, SLAPI_NENTRIES, pnentries); + break; + case 1: /* entry not sent */ + break; + case -1: /* connection closed */ + /* + * mark the operation as abandoned so the backend + * next entry function gets called again and has + * a chance to clean things up. + */ + operation->o_status = SLAPI_OP_STATUS_ABANDONED; + break; + } +} #if 0 /* Loops through search entries and sends them to the client. @@ -1214,7 +1240,7 @@ iterate(Slapi_PBlock *pb, Slapi_Backend *be, int send_result, int *pnentries, in *pnentries = 0; while (!done) { - Slapi_Entry *gerentry = NULL; + Slapi_Entry *ger_template_entry = NULL; Slapi_Operation *operation; slapi_pblock_get(pb, SLAPI_OPERATION, &operation); @@ -1236,57 +1262,57 @@ iterate(Slapi_PBlock *pb, Slapi_Backend *be, int send_result, int *pnentries, in slapi_pblock_get(pb, SLAPI_SEARCH_RESULT_ENTRY, &e); /* Check for possible get_effective_rights control */ - if (e) { - if (operation->o_flags & OP_FLAG_GET_EFFECTIVE_RIGHTS) { - char *errbuf = NULL; + if (operation->o_flags & OP_FLAG_GET_EFFECTIVE_RIGHTS) { + char *errbuf = NULL; + + if (PAGEDRESULTS_PAGE_END == pr_stat) { + /* + * read ahead -- there is at least more entry. + * undo it and return the PAGE_END + */ + be->be_prev_search_results(pb); + done = 1; + continue; + } + if ( e == NULL ) { char **gerattrs = NULL; char **gerattrsdup = NULL; char **gap = NULL; char *gapnext = NULL; - - if (PAGEDRESULTS_PAGE_END == pr_stat) { - /* - * read ahead -- there is at least more entry. - * undo it and return the PAGE_END + /* we have no more entries + * but we might create a template entry for GER + * so we need to continue, but make sure to stop + * after handling the template entry. + * the template entry is a temporary entry returned by the acl + * plugin in the pblock and will be freed */ - be->be_prev_search_results(pb); - done = 1; - continue; - } + done = 1; + pr_stat = PAGEDRESULTS_SEARCH_END; slapi_pblock_get(pb, SLAPI_SEARCH_GERATTRS, &gerattrs); gerattrsdup = cool_charray_dup(gerattrs); gap = gerattrsdup; - do { + while (gap && *gap) { gapnext = NULL; - if (gap) { - if (*gap && *(gap + 1)) { - gapnext = *(gap + 1); - *(gap + 1) = NULL; - } - slapi_pblock_set(pb, SLAPI_SEARCH_GERATTRS, gap); - rc = plugin_call_acl_plugin(pb, e, attrs, NULL, - SLAPI_ACL_ALL, ACLPLUGIN_ACCESS_GET_EFFECTIVE_RIGHTS, - &errbuf); - if (NULL != gapnext) { - *(gap + 1) = gapnext; - } - } else if (NULL != e) { - rc = plugin_call_acl_plugin(pb, e, attrs, NULL, - SLAPI_ACL_ALL, ACLPLUGIN_ACCESS_GET_EFFECTIVE_RIGHTS, - &errbuf); + if (*(gap + 1)) { + gapnext = *(gap + 1); + *(gap + 1) = NULL; + } + slapi_pblock_set(pb, SLAPI_SEARCH_GERATTRS, gap); + rc = plugin_call_acl_plugin(pb, e, attrs, NULL, + SLAPI_ACL_ALL, ACLPLUGIN_ACCESS_GET_EFFECTIVE_RIGHTS, + &errbuf); + if (NULL != gapnext) { + *(gap + 1) = gapnext; } + gap++; + /* get the template entry, if any */ + slapi_pblock_get(pb, SLAPI_SEARCH_RESULT_ENTRY, &e); if (NULL == e) { - /* get the template entry, if any */ - slapi_pblock_get(pb, SLAPI_SEARCH_RESULT_ENTRY, &e); - if (NULL == e) { - /* everything is ok - don't send the result */ - pr_stat = PAGEDRESULTS_SEARCH_END; - done = 1; - continue; - } - gerentry = e; + /* everything is ok - don't send the result */ + continue; } + ger_template_entry = e; if (rc != LDAP_SUCCESS) { /* Send error result and abort op if the control is critical */ @@ -1294,65 +1320,53 @@ iterate(Slapi_PBlock *pb, Slapi_Backend *be, int send_result, int *pnentries, in "Failed to get effective rights for entry (%s), rc=%d\n", slapi_entry_get_dn_const(e), rc); send_ldap_result(pb, rc, NULL, errbuf, 0, NULL); - slapi_ch_free((void **)&errbuf); - if (gerentry) { - slapi_pblock_set(pb, SLAPI_SEARCH_RESULT_ENTRY, NULL); - slapi_entry_free(gerentry); - gerentry = e = NULL; - } - pr_stat = PAGEDRESULTS_SEARCH_END; rval = -1; - done = 1; - continue; - } - slapi_ch_free((void **)&errbuf); - if (process_entry(pb, e, send_result)) { - /* shouldn't send this entry */ - if (gerentry) { - slapi_pblock_set(pb, SLAPI_SEARCH_RESULT_ENTRY, NULL); - slapi_entry_free(gerentry); - gerentry = e = NULL; + } else { + if (!process_entry(pb, e, send_result)) { + /* should send this entry now*/ + send_entry(pb, e, operation, attrs, attrsonly, pnentries); } - continue; } - /* - * It's a regular entry, or it's a referral and - * managedsait control is on. In either case, send - * the entry. - */ - switch (send_ldap_search_entry(pb, e, NULL, attrs, attrsonly)) { - case 0: /* entry sent ok */ - (*pnentries)++; - slapi_pblock_set(pb, SLAPI_NENTRIES, pnentries); - break; - case 1: /* entry not sent */ - break; - case -1: /* connection closed */ - /* - * mark the operation as abandoned so the backend - * next entry function gets called again and has - * a chance to clean things up. - */ - operation->o_status = SLAPI_OP_STATUS_ABANDONED; - break; - } - if (gerentry) { + slapi_ch_free((void **)&errbuf); + if (ger_template_entry) { slapi_pblock_set(pb, SLAPI_SEARCH_RESULT_ENTRY, NULL); - slapi_entry_free(gerentry); - gerentry = e = NULL; + slapi_entry_free(ger_template_entry); + ger_template_entry = e = NULL; } - } while (gap && ++gap && *gap); + } /* while ger template */ slapi_pblock_set(pb, SLAPI_SEARCH_GERATTRS, gerattrs); cool_charray_free(gerattrsdup); - if (pagesize == *pnentries) { - /* PAGED RESULTS: reached the pagesize */ - /* We don't set "done = 1" here. - * We read ahead next entry to check whether there is - * more entries to return or not. */ - pr_stat = PAGEDRESULTS_PAGE_END; + } else { + /* we are processing geteffective rights for an existing entry */ + rc = plugin_call_acl_plugin(pb, e, attrs, NULL, + SLAPI_ACL_ALL, ACLPLUGIN_ACCESS_GET_EFFECTIVE_RIGHTS, + &errbuf); + if (rc != LDAP_SUCCESS) { + /* Send error result and + abort op if the control is critical */ + slapi_log_err(SLAPI_LOG_ERR, "iterate", + "Failed to get effective rights for entry (%s), rc=%d\n", + slapi_entry_get_dn_const(e), rc); + send_ldap_result(pb, rc, NULL, errbuf, 0, NULL); + rval = -1; + } else { + if (!process_entry(pb, e, send_result)) { + /* should send this entry now*/ + send_entry(pb, e, operation, attrs, attrsonly, pnentries); + if (pagesize == *pnentries) { + /* PAGED RESULTS: reached the pagesize */ + /* We don't set "done = 1" here. + * We read ahead next entry to check whether there is + * more entries to return or not. */ + pr_stat = PAGEDRESULTS_PAGE_END; + } + } } - } else { /* not GET_EFFECTIVE_RIGHTS */ + slapi_ch_free((void **)&errbuf); + } + /* not GET_EFFECTIVE_RIGHTS */ + } else if (e) { if (PAGEDRESULTS_PAGE_END == pr_stat) { /* * read ahead -- there is at least more entry. @@ -1364,46 +1378,21 @@ iterate(Slapi_PBlock *pb, Slapi_Backend *be, int send_result, int *pnentries, in } /* Adding shadow password attrs. */ add_shadow_ext_password_attrs(pb, &e); - if (process_entry(pb, e, send_result)) { - /* shouldn't send this entry */ - struct slapi_entry *pb_pw_entry = slapi_pblock_get_pw_entry(pb); - slapi_entry_free(pb_pw_entry); - slapi_pblock_set_pw_entry(pb, NULL); - continue; - } - - /* - * It's a regular entry, or it's a referral and - * managedsait control is on. In either case, send - * the entry. - */ - switch (send_ldap_search_entry(pb, e, NULL, attrs, attrsonly)) { - case 0: /* entry sent ok */ - (*pnentries)++; - slapi_pblock_set(pb, SLAPI_NENTRIES, pnentries); - break; - case 1: /* entry not sent */ - break; - case -1: /* connection closed */ - /* - * mark the operation as abandoned so the backend - * next entry function gets called again and has - * a chance to clean things up. - */ - operation->o_status = SLAPI_OP_STATUS_ABANDONED; - break; + if (!process_entry(pb, e, send_result)) { + /*this entry was not sent, do it now*/ + send_entry(pb, e, operation, attrs, attrsonly, pnentries); + if (pagesize == *pnentries) { + /* PAGED RESULTS: reached the pagesize */ + /* We don't set "done = 1" here. + * We read ahead next entry to check whether there is + * more entries to return or not. */ + pr_stat = PAGEDRESULTS_PAGE_END; + } } + /* cleanup pw entry . sent or not */ struct slapi_entry *pb_pw_entry = slapi_pblock_get_pw_entry(pb); slapi_entry_free(pb_pw_entry); slapi_pblock_set_pw_entry(pb, NULL); - if (pagesize == *pnentries) { - /* PAGED RESULTS: reached the pagesize */ - /* We don't set "done = 1" here. - * We read ahead next entry to check whether there is - * more entries to return or not. */ - pr_stat = PAGEDRESULTS_PAGE_END; - } - } } else { /* no more entries */ done = 1;
0
8bac1e299a8f03dc123e025f9dfd9abf467cca97
389ds/389-ds-base
Ticket 50161 - Fixed some descriptions in "dsconf backend --help" Description: - Help for "suffix" was no longer correct - Help for "create" changed to "Create a backend database" - Changed descriptions to start with a capital letter for consistency https://pagure.io/389-ds-base/issue/50161 Reviewed by: mhonek, mreynolds
commit 8bac1e299a8f03dc123e025f9dfd9abf467cca97 Author: Marc Muehlfeld <[email protected]> Date: Tue Jan 15 14:49:19 2019 +0100 Ticket 50161 - Fixed some descriptions in "dsconf backend --help" Description: - Help for "suffix" was no longer correct - Help for "create" changed to "Create a backend database" - Changed descriptions to start with a capital letter for consistency https://pagure.io/389-ds-base/issue/50161 Reviewed by: mhonek, mreynolds diff --git a/src/lib389/lib389/cli_conf/backend.py b/src/lib389/lib389/cli_conf/backend.py index ebed52eea..c970e8438 100644 --- a/src/lib389/lib389/cli_conf/backend.py +++ b/src/lib389/lib389/cli_conf/backend.py @@ -595,7 +595,7 @@ def create_parser(subparsers): ##################################################### # Suffix parser ##################################################### - suffix_parser = subcommands.add_parser('suffix', help="Manage a backend suffix, including creating backends") + suffix_parser = subcommands.add_parser('suffix', help="Manage a backend suffix") suffix_subcommands = suffix_parser.add_subparsers(help="action") # List backends/suffixes @@ -857,7 +857,7 @@ def create_parser(subparsers): ####################################################### # Export LDIF ####################################################### - export_parser = subcommands.add_parser('export', help='do an online export of the suffix') + export_parser = subcommands.add_parser('export', help='Do an online export of the suffix') export_parser.set_defaults(func=backend_export) export_parser.add_argument('be_names', nargs='+', help="The backend names or the root suffixes from where to export.") @@ -886,7 +886,7 @@ def create_parser(subparsers): ####################################################### # Create a new backend database ####################################################### - create_parser = subcommands.add_parser('create', help='create') + create_parser = subcommands.add_parser('create', help='Create a backend database') create_parser.set_defaults(func=backend_create) create_parser.add_argument('--parent-suffix', default=False, help="Sets the parent suffix only if this backend is a sub-suffix") @@ -897,6 +897,6 @@ def create_parser(subparsers): ####################################################### # Delete backend ####################################################### - delete_parser = subcommands.add_parser('delete', help='deletes a backend database') + delete_parser = subcommands.add_parser('delete', help='Delete a backend database') delete_parser.set_defaults(func=backend_delete) - delete_parser.add_argument('be_name', help='The backend name or suffix to delete') \ No newline at end of file + delete_parser.add_argument('be_name', help='The backend name or suffix to delete')
0
34ffa6c44734b99c252e7585bb499089ac8e6a67
389ds/389-ds-base
Ticket 47910 - logconv.pl - check that the end time is greater than the start time Bug Description: There is no check if the end time is greater than the start time. This leads to an empty report being generated, when an error should be returned instead. Fix Description: If start and end time are used, validate that the end time is greater than the start time. Also, improved an error message when the tool options are not correctly used. https://fedorahosted.org/389/ticket/47910 Reviewed by: nhosoi(Thanks!)
commit 34ffa6c44734b99c252e7585bb499089ac8e6a67 Author: Mark Reynolds <[email protected]> Date: Mon Jul 20 11:18:12 2015 -0400 Ticket 47910 - logconv.pl - check that the end time is greater than the start time Bug Description: There is no check if the end time is greater than the start time. This leads to an empty report being generated, when an error should be returned instead. Fix Description: If start and end time are used, validate that the end time is greater than the start time. Also, improved an error message when the tool options are not correctly used. https://fedorahosted.org/389/ticket/47910 Reviewed by: nhosoi(Thanks!) diff --git a/ldap/admin/src/logconv.pl b/ldap/admin/src/logconv.pl index d26e91ebe..0038a038d 100755 --- a/ldap/admin/src/logconv.pl +++ b/ldap/admin/src/logconv.pl @@ -148,14 +148,13 @@ while($arg_count <= $#ARGV){ } if($file_count == 0){ - if($reportStatsSecFile or $reportStatsMinFile){ - print "Usage error for option -m or -M, either the output file or access log is missing!\n\n"; - } else { - print "There are no access logs specified!\n\n"; - } + print "There are no access logs specified, or the tool options have not been used correctly!\n"; exit 1; } +# +# Initialize the statistic blocks +# if ($reportStatsSecFile) { $s_stats = new_stats_block($reportStatsSecFile); $reportStats = "-m"; @@ -357,6 +356,19 @@ my %monthname = ( ); +# +# Validate start/end times (if specified) +# +if ($startTime and $endTime){ + # Make sure the end time is not earlier than the start time + my $testStart = convertTimeToSeconds($startTime); + my $testEnd = convertTimeToSeconds($endTime); + if ($testStart > $testEnd){ + print "Start time ($startTime) is greater than end time ($endTime)!\n"; + exit 1; + } +} + my $linesProcessed; my $lineBlockCount; my $cursize = 0;
0
941ed15d730bb365a5b056b37c81eccd10ca3c61
389ds/389-ds-base
Resolves: bug 243639 Description: --with-ldapsdk-bin required for configure argument Fix Description: In m4/mozldap.m4, there is a code to check whether ldapsdk_bindir is specified, but you can't specify it except for --with-ldapsdk argument or using pkg-config. So using --with-ldapsdk-lib and --with-ldapsdk-inc requires the additional argument '--with-ldapsdk-bin'.
commit 941ed15d730bb365a5b056b37c81eccd10ca3c61 Author: Rich Megginson <[email protected]> Date: Mon Jun 11 14:13:55 2007 +0000 Resolves: bug 243639 Description: --with-ldapsdk-bin required for configure argument Fix Description: In m4/mozldap.m4, there is a code to check whether ldapsdk_bindir is specified, but you can't specify it except for --with-ldapsdk argument or using pkg-config. So using --with-ldapsdk-lib and --with-ldapsdk-inc requires the additional argument '--with-ldapsdk-bin'. diff --git a/Makefile.in b/Makefile.in index f1b813e05..37d831c74 100644 --- a/Makefile.in +++ b/Makefile.in @@ -874,6 +874,7 @@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ RANLIB = @RANLIB@ +SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SOLARIS_FALSE = @SOLARIS_FALSE@ diff --git a/aclocal.m4 b/aclocal.m4 index 9064efa9b..c7c1c6fbc 100644 --- a/aclocal.m4 +++ b/aclocal.m4 @@ -1578,10 +1578,27 @@ linux*) # before this can be enabled. hardcode_into_libs=yes + # find out which ABI we are using + libsuff= + case "$host_cpu" in + x86_64*|s390x*|powerpc64*) + echo '[#]line __oline__ "configure"' > conftest.$ac_ext + if AC_TRY_EVAL(ac_compile); then + case `/usr/bin/file conftest.$ac_objext` in + *64-bit*) + libsuff=64 + sys_lib_search_path_spec="/lib${libsuff} /usr/lib${libsuff} /usr/local/lib${libsuff}" + ;; + esac + fi + rm -rf conftest* + ;; + esac + # Append ld.so.conf contents to the search path if test -f /etc/ld.so.conf; then - lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s", \[$]2)); skip = 1; } { if (!skip) print \[$]0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;/^$/d' | tr '\n' ' '` - sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra" + lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \[$]2)); skip = 1; } { if (!skip) print \[$]0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;/^$/d' | tr '\n' ' '` + sys_lib_dlsearch_path_spec="/lib${libsuff} /usr/lib${libsuff} $lt_ld_extra" fi # We used to test for /lib/ld.so.1 and disable shared libraries on @@ -4288,6 +4305,9 @@ CC=$lt_[]_LT_AC_TAGVAR(compiler, $1) # Is the compiler the GNU C compiler? with_gcc=$_LT_AC_TAGVAR(GCC, $1) +gcc_dir=\`gcc -print-file-name=. | $SED 's,/\.$,,'\` +gcc_ver=\`gcc -dumpversion\` + # An ERE matcher. EGREP=$lt_EGREP @@ -4421,11 +4441,11 @@ striplib=$lt_striplib # Dependencies to place before the objects being linked to create a # shared library. -predep_objects=$lt_[]_LT_AC_TAGVAR(predep_objects, $1) +predep_objects=\`echo $lt_[]_LT_AC_TAGVAR(predep_objects, $1) | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\` # Dependencies to place after the objects being linked to create a # shared library. -postdep_objects=$lt_[]_LT_AC_TAGVAR(postdep_objects, $1) +postdep_objects=\`echo $lt_[]_LT_AC_TAGVAR(postdep_objects, $1) | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\` # Dependencies to place before the objects being linked to create a # shared library. @@ -4437,7 +4457,7 @@ postdeps=$lt_[]_LT_AC_TAGVAR(postdeps, $1) # The library search path used internally by the compiler when linking # a shared library. -compiler_lib_search_path=$lt_[]_LT_AC_TAGVAR(compiler_lib_search_path, $1) +compiler_lib_search_path=\`echo $lt_[]_LT_AC_TAGVAR(compiler_lib_search_path, $1) | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\` # Method to check whether dependent libraries are shared objects. deplibs_check_method=$lt_deplibs_check_method @@ -4517,7 +4537,7 @@ variables_saved_for_relink="$variables_saved_for_relink" link_all_deplibs=$_LT_AC_TAGVAR(link_all_deplibs, $1) # Compile-time system search path for libraries -sys_lib_search_path_spec=$lt_sys_lib_search_path_spec +sys_lib_search_path_spec=\`echo $lt_sys_lib_search_path_spec | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\` # Run-time system search path for libraries sys_lib_dlsearch_path_spec=$lt_sys_lib_dlsearch_path_spec @@ -6353,6 +6373,7 @@ do done done done +IFS=$as_save_IFS lt_ac_max=0 lt_ac_count=0 # Add /usr/xpg4/bin/sed as it is typically found on Solaris @@ -6385,6 +6406,7 @@ for lt_ac_sed in $lt_ac_sed_list /usr/xpg4/bin/sed; do done ]) SED=$lt_cv_path_SED +AC_SUBST([SED]) AC_MSG_RESULT([$SED]) ]) diff --git a/configure b/configure index b8c40d75b..67bdf5615 100755 --- a/configure +++ b/configure @@ -465,7 +465,7 @@ ac_includes_default="\ #endif" ac_default_prefix=/opt/$PACKAGE_NAME -ac_subst_vars='SHELL PATH_SEPARATOR PACKAGE_NAME PACKAGE_TARNAME PACKAGE_VERSION PACKAGE_STRING PACKAGE_BUGREPORT exec_prefix prefix program_transform_name bindir sbindir libexecdir datadir sysconfdir sharedstatedir localstatedir libdir includedir oldincludedir infodir mandir build_alias host_alias target_alias DEFS ECHO_C ECHO_N ECHO_T LIBS INSTALL_PROGRAM INSTALL_SCRIPT INSTALL_DATA CYGPATH_W PACKAGE VERSION ACLOCAL AUTOCONF AUTOMAKE AUTOHEADER MAKEINFO install_sh STRIP ac_ct_STRIP INSTALL_STRIP_PROGRAM mkdir_p AWK SET_MAKE am__leading_dot AMTAR am__tar am__untar MAINTAINER_MODE_TRUE MAINTAINER_MODE_FALSE MAINT build build_cpu build_vendor build_os host host_cpu host_vendor host_os CXX CXXFLAGS LDFLAGS CPPFLAGS ac_ct_CXX EXEEXT OBJEXT DEPDIR am__include am__quote AMDEP_TRUE AMDEP_FALSE AMDEPBACKSLASH CXXDEPMODE am__fastdepCXX_TRUE am__fastdepCXX_FALSE CC CFLAGS ac_ct_CC CCDEPMODE am__fastdepCC_TRUE am__fastdepCC_FALSE EGREP LN_S ECHO AR ac_ct_AR RANLIB ac_ct_RANLIB CPP CXXCPP F77 FFLAGS ac_ct_F77 LIBTOOL LIBOBJS debug_defs BUNDLE_TRUE BUNDLE_FALSE enable_pam_passthru_TRUE enable_pam_passthru_FALSE enable_dna_TRUE enable_dna_FALSE enable_ldapi_TRUE enable_ldapi_FALSE enable_bitwise_TRUE enable_bitwise_FALSE configdir sampledatadir propertydir schemadir serverdir serverplugindir scripttemplatedir perldir instconfigdir WINNT_TRUE WINNT_FALSE LIBSOCKET LIBNSL LIBDL LIBCSTD LIBCRUN initdir shared_lib_suffix HPUX_TRUE HPUX_FALSE SOLARIS_TRUE SOLARIS_FALSE PKG_CONFIG ICU_CONFIG NETSNMP_CONFIG nspr_inc nspr_lib nspr_libdir nss_inc nss_lib nss_libdir ldapsdk_inc ldapsdk_lib ldapsdk_libdir ldapsdk_bindir db_inc db_incdir db_lib db_libdir db_bindir db_libver sasl_inc sasl_lib sasl_libdir svrcore_inc svrcore_lib icu_lib icu_inc icu_bin netsnmp_inc netsnmp_lib netsnmp_libdir netsnmp_link brand capbrand vendor LTLIBOBJS' +ac_subst_vars='SHELL PATH_SEPARATOR PACKAGE_NAME PACKAGE_TARNAME PACKAGE_VERSION PACKAGE_STRING PACKAGE_BUGREPORT exec_prefix prefix program_transform_name bindir sbindir libexecdir datadir sysconfdir sharedstatedir localstatedir libdir includedir oldincludedir infodir mandir build_alias host_alias target_alias DEFS ECHO_C ECHO_N ECHO_T LIBS INSTALL_PROGRAM INSTALL_SCRIPT INSTALL_DATA CYGPATH_W PACKAGE VERSION ACLOCAL AUTOCONF AUTOMAKE AUTOHEADER MAKEINFO install_sh STRIP ac_ct_STRIP INSTALL_STRIP_PROGRAM mkdir_p AWK SET_MAKE am__leading_dot AMTAR am__tar am__untar MAINTAINER_MODE_TRUE MAINTAINER_MODE_FALSE MAINT build build_cpu build_vendor build_os host host_cpu host_vendor host_os CXX CXXFLAGS LDFLAGS CPPFLAGS ac_ct_CXX EXEEXT OBJEXT DEPDIR am__include am__quote AMDEP_TRUE AMDEP_FALSE AMDEPBACKSLASH CXXDEPMODE am__fastdepCXX_TRUE am__fastdepCXX_FALSE CC CFLAGS ac_ct_CC CCDEPMODE am__fastdepCC_TRUE am__fastdepCC_FALSE SED EGREP LN_S ECHO AR ac_ct_AR RANLIB ac_ct_RANLIB CPP CXXCPP F77 FFLAGS ac_ct_F77 LIBTOOL LIBOBJS debug_defs BUNDLE_TRUE BUNDLE_FALSE enable_pam_passthru_TRUE enable_pam_passthru_FALSE enable_dna_TRUE enable_dna_FALSE enable_ldapi_TRUE enable_ldapi_FALSE enable_bitwise_TRUE enable_bitwise_FALSE configdir sampledatadir propertydir schemadir serverdir serverplugindir scripttemplatedir perldir instconfigdir WINNT_TRUE WINNT_FALSE LIBSOCKET LIBNSL LIBDL LIBCSTD LIBCRUN initdir shared_lib_suffix HPUX_TRUE HPUX_FALSE SOLARIS_TRUE SOLARIS_FALSE PKG_CONFIG ICU_CONFIG NETSNMP_CONFIG nspr_inc nspr_lib nspr_libdir nss_inc nss_lib nss_libdir ldapsdk_inc ldapsdk_lib ldapsdk_libdir ldapsdk_bindir db_inc db_incdir db_lib db_libdir db_bindir db_libver sasl_inc sasl_lib sasl_libdir svrcore_inc svrcore_lib icu_lib icu_inc icu_bin netsnmp_inc netsnmp_lib netsnmp_libdir netsnmp_link brand capbrand vendor LTLIBOBJS' ac_subst_files='' # Initialize some variables set by options. @@ -1072,6 +1072,7 @@ Optional Packages: --with-ldapsdk=PATH Mozilla LDAP SDK directory --with-ldapsdk-inc=PATH Mozilla LDAP SDK include directory --with-ldapsdk-lib=PATH Mozilla LDAP SDK library directory + --with-ldapsdk-bin=PATH Mozilla LDAP SDK binary directory --with-db=PATH Berkeley DB directory --with-sasl=PATH Use sasl from supplied path --with-sasl-inc=PATH SASL include file directory @@ -3835,6 +3836,7 @@ do done done done +IFS=$as_save_IFS lt_ac_max=0 lt_ac_count=0 # Add /usr/xpg4/bin/sed as it is typically found on Solaris @@ -3869,6 +3871,7 @@ done fi SED=$lt_cv_path_SED + echo "$as_me:$LINENO: result: $SED" >&5 echo "${ECHO_T}$SED" >&6 @@ -4309,7 +4312,7 @@ ia64-*-hpux*) ;; *-*-irix6*) # Find out which ABI we are using. - echo '#line 4312 "configure"' > conftest.$ac_ext + echo '#line 4315 "configure"' > conftest.$ac_ext if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 (eval $ac_compile) 2>&5 ac_status=$? @@ -5444,7 +5447,7 @@ fi # Provide some information about the compiler. -echo "$as_me:5447:" \ +echo "$as_me:5450:" \ "checking for Fortran 77 compiler version" >&5 ac_compiler=`set X $ac_compile; echo $2` { (eval echo "$as_me:$LINENO: \"$ac_compiler --version </dev/null >&5\"") >&5 @@ -6507,11 +6510,11 @@ else -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` - (eval echo "\"\$as_me:6510: $lt_compile\"" >&5) + (eval echo "\"\$as_me:6513: $lt_compile\"" >&5) (eval "$lt_compile" 2>conftest.err) ac_status=$? cat conftest.err >&5 - echo "$as_me:6514: \$? = $ac_status" >&5 + echo "$as_me:6517: \$? = $ac_status" >&5 if (exit $ac_status) && test -s "$ac_outfile"; then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings other than the usual output. @@ -6775,11 +6778,11 @@ else -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` - (eval echo "\"\$as_me:6778: $lt_compile\"" >&5) + (eval echo "\"\$as_me:6781: $lt_compile\"" >&5) (eval "$lt_compile" 2>conftest.err) ac_status=$? cat conftest.err >&5 - echo "$as_me:6782: \$? = $ac_status" >&5 + echo "$as_me:6785: \$? = $ac_status" >&5 if (exit $ac_status) && test -s "$ac_outfile"; then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings other than the usual output. @@ -6879,11 +6882,11 @@ else -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` - (eval echo "\"\$as_me:6882: $lt_compile\"" >&5) + (eval echo "\"\$as_me:6885: $lt_compile\"" >&5) (eval "$lt_compile" 2>out/conftest.err) ac_status=$? cat out/conftest.err >&5 - echo "$as_me:6886: \$? = $ac_status" >&5 + echo "$as_me:6889: \$? = $ac_status" >&5 if (exit $ac_status) && test -s out/conftest2.$ac_objext then # The compiler can only warn and ignore the option if not recognized @@ -8344,10 +8347,31 @@ linux*) # before this can be enabled. hardcode_into_libs=yes + # find out which ABI we are using + libsuff= + case "$host_cpu" in + x86_64*|s390x*|powerpc64*) + echo '#line 8354 "configure"' > conftest.$ac_ext + if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 + (eval $ac_compile) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; then + case `/usr/bin/file conftest.$ac_objext` in + *64-bit*) + libsuff=64 + sys_lib_search_path_spec="/lib${libsuff} /usr/lib${libsuff} /usr/local/lib${libsuff}" + ;; + esac + fi + rm -rf conftest* + ;; + esac + # Append ld.so.conf contents to the search path if test -f /etc/ld.so.conf; then - lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;/^$/d' | tr '\n' ' '` - sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra" + lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;/^$/d' | tr '\n' ' '` + sys_lib_dlsearch_path_spec="/lib${libsuff} /usr/lib${libsuff} $lt_ld_extra" fi # We used to test for /lib/ld.so.1 and disable shared libraries on @@ -9224,7 +9248,7 @@ else lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2 lt_status=$lt_dlunknown cat > conftest.$ac_ext <<EOF -#line 9227 "configure" +#line 9251 "configure" #include "confdefs.h" #if HAVE_DLFCN_H @@ -9324,7 +9348,7 @@ else lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2 lt_status=$lt_dlunknown cat > conftest.$ac_ext <<EOF -#line 9327 "configure" +#line 9351 "configure" #include "confdefs.h" #if HAVE_DLFCN_H @@ -9655,6 +9679,9 @@ CC=$lt_compiler # Is the compiler the GNU C compiler? with_gcc=$GCC +gcc_dir=\`gcc -print-file-name=. | $SED 's,/\.$,,'\` +gcc_ver=\`gcc -dumpversion\` + # An ERE matcher. EGREP=$lt_EGREP @@ -9788,11 +9815,11 @@ striplib=$lt_striplib # Dependencies to place before the objects being linked to create a # shared library. -predep_objects=$lt_predep_objects +predep_objects=\`echo $lt_predep_objects | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\` # Dependencies to place after the objects being linked to create a # shared library. -postdep_objects=$lt_postdep_objects +postdep_objects=\`echo $lt_postdep_objects | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\` # Dependencies to place before the objects being linked to create a # shared library. @@ -9804,7 +9831,7 @@ postdeps=$lt_postdeps # The library search path used internally by the compiler when linking # a shared library. -compiler_lib_search_path=$lt_compiler_lib_search_path +compiler_lib_search_path=\`echo $lt_compiler_lib_search_path | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\` # Method to check whether dependent libraries are shared objects. deplibs_check_method=$lt_deplibs_check_method @@ -9884,7 +9911,7 @@ variables_saved_for_relink="$variables_saved_for_relink" link_all_deplibs=$link_all_deplibs # Compile-time system search path for libraries -sys_lib_search_path_spec=$lt_sys_lib_search_path_spec +sys_lib_search_path_spec=\`echo $lt_sys_lib_search_path_spec | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\` # Run-time system search path for libraries sys_lib_dlsearch_path_spec=$lt_sys_lib_dlsearch_path_spec @@ -11664,11 +11691,11 @@ else -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` - (eval echo "\"\$as_me:11667: $lt_compile\"" >&5) + (eval echo "\"\$as_me:11694: $lt_compile\"" >&5) (eval "$lt_compile" 2>conftest.err) ac_status=$? cat conftest.err >&5 - echo "$as_me:11671: \$? = $ac_status" >&5 + echo "$as_me:11698: \$? = $ac_status" >&5 if (exit $ac_status) && test -s "$ac_outfile"; then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings other than the usual output. @@ -11768,11 +11795,11 @@ else -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` - (eval echo "\"\$as_me:11771: $lt_compile\"" >&5) + (eval echo "\"\$as_me:11798: $lt_compile\"" >&5) (eval "$lt_compile" 2>out/conftest.err) ac_status=$? cat out/conftest.err >&5 - echo "$as_me:11775: \$? = $ac_status" >&5 + echo "$as_me:11802: \$? = $ac_status" >&5 if (exit $ac_status) && test -s out/conftest2.$ac_objext then # The compiler can only warn and ignore the option if not recognized @@ -12300,10 +12327,31 @@ linux*) # before this can be enabled. hardcode_into_libs=yes + # find out which ABI we are using + libsuff= + case "$host_cpu" in + x86_64*|s390x*|powerpc64*) + echo '#line 12334 "configure"' > conftest.$ac_ext + if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 + (eval $ac_compile) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; then + case `/usr/bin/file conftest.$ac_objext` in + *64-bit*) + libsuff=64 + sys_lib_search_path_spec="/lib${libsuff} /usr/lib${libsuff} /usr/local/lib${libsuff}" + ;; + esac + fi + rm -rf conftest* + ;; + esac + # Append ld.so.conf contents to the search path if test -f /etc/ld.so.conf; then - lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;/^$/d' | tr '\n' ' '` - sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra" + lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;/^$/d' | tr '\n' ' '` + sys_lib_dlsearch_path_spec="/lib${libsuff} /usr/lib${libsuff} $lt_ld_extra" fi # We used to test for /lib/ld.so.1 and disable shared libraries on @@ -12687,6 +12735,9 @@ CC=$lt_compiler_CXX # Is the compiler the GNU C compiler? with_gcc=$GCC_CXX +gcc_dir=\`gcc -print-file-name=. | $SED 's,/\.$,,'\` +gcc_ver=\`gcc -dumpversion\` + # An ERE matcher. EGREP=$lt_EGREP @@ -12820,11 +12871,11 @@ striplib=$lt_striplib # Dependencies to place before the objects being linked to create a # shared library. -predep_objects=$lt_predep_objects_CXX +predep_objects=\`echo $lt_predep_objects_CXX | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\` # Dependencies to place after the objects being linked to create a # shared library. -postdep_objects=$lt_postdep_objects_CXX +postdep_objects=\`echo $lt_postdep_objects_CXX | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\` # Dependencies to place before the objects being linked to create a # shared library. @@ -12836,7 +12887,7 @@ postdeps=$lt_postdeps_CXX # The library search path used internally by the compiler when linking # a shared library. -compiler_lib_search_path=$lt_compiler_lib_search_path_CXX +compiler_lib_search_path=\`echo $lt_compiler_lib_search_path_CXX | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\` # Method to check whether dependent libraries are shared objects. deplibs_check_method=$lt_deplibs_check_method @@ -12916,7 +12967,7 @@ variables_saved_for_relink="$variables_saved_for_relink" link_all_deplibs=$link_all_deplibs_CXX # Compile-time system search path for libraries -sys_lib_search_path_spec=$lt_sys_lib_search_path_spec +sys_lib_search_path_spec=\`echo $lt_sys_lib_search_path_spec | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\` # Run-time system search path for libraries sys_lib_dlsearch_path_spec=$lt_sys_lib_dlsearch_path_spec @@ -13338,11 +13389,11 @@ else -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` - (eval echo "\"\$as_me:13341: $lt_compile\"" >&5) + (eval echo "\"\$as_me:13392: $lt_compile\"" >&5) (eval "$lt_compile" 2>conftest.err) ac_status=$? cat conftest.err >&5 - echo "$as_me:13345: \$? = $ac_status" >&5 + echo "$as_me:13396: \$? = $ac_status" >&5 if (exit $ac_status) && test -s "$ac_outfile"; then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings other than the usual output. @@ -13442,11 +13493,11 @@ else -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` - (eval echo "\"\$as_me:13445: $lt_compile\"" >&5) + (eval echo "\"\$as_me:13496: $lt_compile\"" >&5) (eval "$lt_compile" 2>out/conftest.err) ac_status=$? cat out/conftest.err >&5 - echo "$as_me:13449: \$? = $ac_status" >&5 + echo "$as_me:13500: \$? = $ac_status" >&5 if (exit $ac_status) && test -s out/conftest2.$ac_objext then # The compiler can only warn and ignore the option if not recognized @@ -14887,10 +14938,31 @@ linux*) # before this can be enabled. hardcode_into_libs=yes + # find out which ABI we are using + libsuff= + case "$host_cpu" in + x86_64*|s390x*|powerpc64*) + echo '#line 14945 "configure"' > conftest.$ac_ext + if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 + (eval $ac_compile) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; then + case `/usr/bin/file conftest.$ac_objext` in + *64-bit*) + libsuff=64 + sys_lib_search_path_spec="/lib${libsuff} /usr/lib${libsuff} /usr/local/lib${libsuff}" + ;; + esac + fi + rm -rf conftest* + ;; + esac + # Append ld.so.conf contents to the search path if test -f /etc/ld.so.conf; then - lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;/^$/d' | tr '\n' ' '` - sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra" + lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;/^$/d' | tr '\n' ' '` + sys_lib_dlsearch_path_spec="/lib${libsuff} /usr/lib${libsuff} $lt_ld_extra" fi # We used to test for /lib/ld.so.1 and disable shared libraries on @@ -15274,6 +15346,9 @@ CC=$lt_compiler_F77 # Is the compiler the GNU C compiler? with_gcc=$GCC_F77 +gcc_dir=\`gcc -print-file-name=. | $SED 's,/\.$,,'\` +gcc_ver=\`gcc -dumpversion\` + # An ERE matcher. EGREP=$lt_EGREP @@ -15407,11 +15482,11 @@ striplib=$lt_striplib # Dependencies to place before the objects being linked to create a # shared library. -predep_objects=$lt_predep_objects_F77 +predep_objects=\`echo $lt_predep_objects_F77 | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\` # Dependencies to place after the objects being linked to create a # shared library. -postdep_objects=$lt_postdep_objects_F77 +postdep_objects=\`echo $lt_postdep_objects_F77 | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\` # Dependencies to place before the objects being linked to create a # shared library. @@ -15423,7 +15498,7 @@ postdeps=$lt_postdeps_F77 # The library search path used internally by the compiler when linking # a shared library. -compiler_lib_search_path=$lt_compiler_lib_search_path_F77 +compiler_lib_search_path=\`echo $lt_compiler_lib_search_path_F77 | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\` # Method to check whether dependent libraries are shared objects. deplibs_check_method=$lt_deplibs_check_method @@ -15503,7 +15578,7 @@ variables_saved_for_relink="$variables_saved_for_relink" link_all_deplibs=$link_all_deplibs_F77 # Compile-time system search path for libraries -sys_lib_search_path_spec=$lt_sys_lib_search_path_spec +sys_lib_search_path_spec=\`echo $lt_sys_lib_search_path_spec | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\` # Run-time system search path for libraries sys_lib_dlsearch_path_spec=$lt_sys_lib_dlsearch_path_spec @@ -15645,11 +15720,11 @@ else -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` - (eval echo "\"\$as_me:15648: $lt_compile\"" >&5) + (eval echo "\"\$as_me:15723: $lt_compile\"" >&5) (eval "$lt_compile" 2>conftest.err) ac_status=$? cat conftest.err >&5 - echo "$as_me:15652: \$? = $ac_status" >&5 + echo "$as_me:15727: \$? = $ac_status" >&5 if (exit $ac_status) && test -s "$ac_outfile"; then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings other than the usual output. @@ -15913,11 +15988,11 @@ else -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` - (eval echo "\"\$as_me:15916: $lt_compile\"" >&5) + (eval echo "\"\$as_me:15991: $lt_compile\"" >&5) (eval "$lt_compile" 2>conftest.err) ac_status=$? cat conftest.err >&5 - echo "$as_me:15920: \$? = $ac_status" >&5 + echo "$as_me:15995: \$? = $ac_status" >&5 if (exit $ac_status) && test -s "$ac_outfile"; then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings other than the usual output. @@ -16017,11 +16092,11 @@ else -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` - (eval echo "\"\$as_me:16020: $lt_compile\"" >&5) + (eval echo "\"\$as_me:16095: $lt_compile\"" >&5) (eval "$lt_compile" 2>out/conftest.err) ac_status=$? cat out/conftest.err >&5 - echo "$as_me:16024: \$? = $ac_status" >&5 + echo "$as_me:16099: \$? = $ac_status" >&5 if (exit $ac_status) && test -s out/conftest2.$ac_objext then # The compiler can only warn and ignore the option if not recognized @@ -17482,10 +17557,31 @@ linux*) # before this can be enabled. hardcode_into_libs=yes + # find out which ABI we are using + libsuff= + case "$host_cpu" in + x86_64*|s390x*|powerpc64*) + echo '#line 17564 "configure"' > conftest.$ac_ext + if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 + (eval $ac_compile) 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; then + case `/usr/bin/file conftest.$ac_objext` in + *64-bit*) + libsuff=64 + sys_lib_search_path_spec="/lib${libsuff} /usr/lib${libsuff} /usr/local/lib${libsuff}" + ;; + esac + fi + rm -rf conftest* + ;; + esac + # Append ld.so.conf contents to the search path if test -f /etc/ld.so.conf; then - lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;/^$/d' | tr '\n' ' '` - sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra" + lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;/^$/d' | tr '\n' ' '` + sys_lib_dlsearch_path_spec="/lib${libsuff} /usr/lib${libsuff} $lt_ld_extra" fi # We used to test for /lib/ld.so.1 and disable shared libraries on @@ -17869,6 +17965,9 @@ CC=$lt_compiler_GCJ # Is the compiler the GNU C compiler? with_gcc=$GCC_GCJ +gcc_dir=\`gcc -print-file-name=. | $SED 's,/\.$,,'\` +gcc_ver=\`gcc -dumpversion\` + # An ERE matcher. EGREP=$lt_EGREP @@ -18002,11 +18101,11 @@ striplib=$lt_striplib # Dependencies to place before the objects being linked to create a # shared library. -predep_objects=$lt_predep_objects_GCJ +predep_objects=\`echo $lt_predep_objects_GCJ | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\` # Dependencies to place after the objects being linked to create a # shared library. -postdep_objects=$lt_postdep_objects_GCJ +postdep_objects=\`echo $lt_postdep_objects_GCJ | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\` # Dependencies to place before the objects being linked to create a # shared library. @@ -18018,7 +18117,7 @@ postdeps=$lt_postdeps_GCJ # The library search path used internally by the compiler when linking # a shared library. -compiler_lib_search_path=$lt_compiler_lib_search_path_GCJ +compiler_lib_search_path=\`echo $lt_compiler_lib_search_path_GCJ | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\` # Method to check whether dependent libraries are shared objects. deplibs_check_method=$lt_deplibs_check_method @@ -18098,7 +18197,7 @@ variables_saved_for_relink="$variables_saved_for_relink" link_all_deplibs=$link_all_deplibs_GCJ # Compile-time system search path for libraries -sys_lib_search_path_spec=$lt_sys_lib_search_path_spec +sys_lib_search_path_spec=\`echo $lt_sys_lib_search_path_spec | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\` # Run-time system search path for libraries sys_lib_dlsearch_path_spec=$lt_sys_lib_dlsearch_path_spec @@ -18350,6 +18449,9 @@ CC=$lt_compiler_RC # Is the compiler the GNU C compiler? with_gcc=$GCC_RC +gcc_dir=\`gcc -print-file-name=. | $SED 's,/\.$,,'\` +gcc_ver=\`gcc -dumpversion\` + # An ERE matcher. EGREP=$lt_EGREP @@ -18483,11 +18585,11 @@ striplib=$lt_striplib # Dependencies to place before the objects being linked to create a # shared library. -predep_objects=$lt_predep_objects_RC +predep_objects=\`echo $lt_predep_objects_RC | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\` # Dependencies to place after the objects being linked to create a # shared library. -postdep_objects=$lt_postdep_objects_RC +postdep_objects=\`echo $lt_postdep_objects_RC | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\` # Dependencies to place before the objects being linked to create a # shared library. @@ -18499,7 +18601,7 @@ postdeps=$lt_postdeps_RC # The library search path used internally by the compiler when linking # a shared library. -compiler_lib_search_path=$lt_compiler_lib_search_path_RC +compiler_lib_search_path=\`echo $lt_compiler_lib_search_path_RC | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\` # Method to check whether dependent libraries are shared objects. deplibs_check_method=$lt_deplibs_check_method @@ -18579,7 +18681,7 @@ variables_saved_for_relink="$variables_saved_for_relink" link_all_deplibs=$link_all_deplibs_RC # Compile-time system search path for libraries -sys_lib_search_path_spec=$lt_sys_lib_search_path_spec +sys_lib_search_path_spec=\`echo $lt_sys_lib_search_path_spec | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\` # Run-time system search path for libraries sys_lib_dlsearch_path_spec=$lt_sys_lib_dlsearch_path_spec @@ -23807,6 +23909,31 @@ else echo "${ECHO_T}no" >&6 fi; +# check for --with-ldapsdk-bin +echo "$as_me:$LINENO: checking for --with-ldapsdk-bin" >&5 +echo $ECHO_N "checking for --with-ldapsdk-bin... $ECHO_C" >&6 + +# Check whether --with-ldapsdk-bin or --without-ldapsdk-bin was given. +if test "${with_ldapsdk_bin+set}" = set; then + withval="$with_ldapsdk_bin" + + if test -d "$withval" + then + echo "$as_me:$LINENO: result: using $withval" >&5 +echo "${ECHO_T}using $withval" >&6 + ldapsdk_bindir="$withval" + else + echo + { { echo "$as_me:$LINENO: error: $withval not found" >&5 +echo "$as_me: error: $withval not found" >&2;} + { (exit 1); exit 1; }; } + fi + +else + echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6 +fi; + # if LDAPSDK is not found yet, try pkg-config # last resort @@ -23858,8 +23985,8 @@ echo $ECHO_N "checking for mozldap with pkg-config... $ECHO_C" >&6 elif $PKG_CONFIG --exists mozldap; then mozldappkg=mozldap else - { { echo "$as_me:$LINENO: error: LDAPSDK not found, specify with --with-ldapsdk-inc|-lib." >&5 -echo "$as_me: error: LDAPSDK not found, specify with --with-ldapsdk-inc|-lib." >&2;} + { { echo "$as_me:$LINENO: error: LDAPSDK not found, specify with --with-ldapsdk-inc|-lib|-bin." >&5 +echo "$as_me: error: LDAPSDK not found, specify with --with-ldapsdk-inc|-lib|-bin." >&2;} { (exit 1); exit 1; }; } fi ldapsdk_inc=`$PKG_CONFIG --cflags-only-I $mozldappkg` @@ -23871,8 +23998,8 @@ echo "${ECHO_T}using system $mozldappkg" >&6 fi fi if test -z "$ldapsdk_inc" -o -z "$ldapsdk_lib"; then - { { echo "$as_me:$LINENO: error: LDAPSDK not found, specify with --with-ldapsdk-inc|-lib." >&5 -echo "$as_me: error: LDAPSDK not found, specify with --with-ldapsdk-inc|-lib." >&2;} + { { echo "$as_me:$LINENO: error: LDAPSDK not found, specify with --with-ldapsdk-inc|-lib|-bin." >&5 +echo "$as_me: error: LDAPSDK not found, specify with --with-ldapsdk-inc|-lib|-bin." >&2;} { (exit 1); exit 1; }; } fi if test -z "$ldapsdk_bindir" ; then @@ -25858,6 +25985,7 @@ s,@ac_ct_CC@,$ac_ct_CC,;t t s,@CCDEPMODE@,$CCDEPMODE,;t t s,@am__fastdepCC_TRUE@,$am__fastdepCC_TRUE,;t t s,@am__fastdepCC_FALSE@,$am__fastdepCC_FALSE,;t t +s,@SED@,$SED,;t t s,@EGREP@,$EGREP,;t t s,@LN_S@,$LN_S,;t t s,@ECHO@,$ECHO,;t t diff --git a/m4/mozldap.m4 b/m4/mozldap.m4 index 7249c9ea9..9bfd4fa2b 100644 --- a/m4/mozldap.m4 +++ b/m4/mozldap.m4 @@ -70,6 +70,21 @@ AC_ARG_WITH(ldapsdk-lib, [ --with-ldapsdk-lib=PATH Mozilla LDAP SDK library ], AC_MSG_RESULT(no)) +# check for --with-ldapsdk-bin +AC_MSG_CHECKING(for --with-ldapsdk-bin) +AC_ARG_WITH(ldapsdk-bin, [ --with-ldapsdk-bin=PATH Mozilla LDAP SDK binary directory], +[ + if test -d "$withval" + then + AC_MSG_RESULT([using $withval]) + ldapsdk_bindir="$withval" + else + echo + AC_MSG_ERROR([$withval not found]) + fi +], +AC_MSG_RESULT(no)) + # if LDAPSDK is not found yet, try pkg-config # last resort @@ -82,7 +97,7 @@ if test -z "$ldapsdk_inc" -o -z "$ldapsdk_lib" -o -z "$ldapsdk_libdir" -o -z "$l elif $PKG_CONFIG --exists mozldap; then mozldappkg=mozldap else - AC_MSG_ERROR([LDAPSDK not found, specify with --with-ldapsdk[-inc|-lib].]) + AC_MSG_ERROR([LDAPSDK not found, specify with --with-ldapsdk[-inc|-lib|-bin].]) fi ldapsdk_inc=`$PKG_CONFIG --cflags-only-I $mozldappkg` ldapsdk_lib=`$PKG_CONFIG --libs-only-L $mozldappkg` @@ -92,7 +107,7 @@ if test -z "$ldapsdk_inc" -o -z "$ldapsdk_lib" -o -z "$ldapsdk_libdir" -o -z "$l fi fi if test -z "$ldapsdk_inc" -o -z "$ldapsdk_lib"; then - AC_MSG_ERROR([LDAPSDK not found, specify with --with-ldapsdk[-inc|-lib].]) + AC_MSG_ERROR([LDAPSDK not found, specify with --with-ldapsdk[-inc|-lib|-bin].]) fi dnl default path for the ldap c sdk tools (see [210947] for more details) if test -z "$ldapsdk_bindir" ; then
0
bb76673d670ec7651e589edafd82f7fa3aa969cd
389ds/389-ds-base
Issue 6192 - Test failure: test_match_large_valueset Description: When BDB backend is used, nsslapd-cache-autosize needs to be set to 0 first in order to change nsslapd-cachememsize. Also increase the expected etime slightly, as it fails on slower VMs both with BDB and MDB backends. Fixes: https://github.com/389ds/389-ds-base/issues/6192 Reviewed by: @droideck, @tbordaz (Thanks!)
commit bb76673d670ec7651e589edafd82f7fa3aa969cd Author: Viktor Ashirov <[email protected]> Date: Thu Jun 6 21:05:09 2024 +0200 Issue 6192 - Test failure: test_match_large_valueset Description: When BDB backend is used, nsslapd-cache-autosize needs to be set to 0 first in order to change nsslapd-cachememsize. Also increase the expected etime slightly, as it fails on slower VMs both with BDB and MDB backends. Fixes: https://github.com/389ds/389-ds-base/issues/6192 Reviewed by: @droideck, @tbordaz (Thanks!) diff --git a/dirsrvtests/tests/suites/filter/filter_test.py b/dirsrvtests/tests/suites/filter/filter_test.py index 2d77034f8..01dd6c7ca 100644 --- a/dirsrvtests/tests/suites/filter/filter_test.py +++ b/dirsrvtests/tests/suites/filter/filter_test.py @@ -15,7 +15,7 @@ from lib389.tasks import * from lib389.backend import Backends, Backend from lib389.dbgen import dbgen_users, dbgen_groups from lib389.topologies import topology_st -from lib389._constants import PASSWORD, DEFAULT_SUFFIX, DN_DM, SUFFIX +from lib389._constants import PASSWORD, DEFAULT_SUFFIX, DN_DM, SUFFIX, DN_CONFIG_LDBM from lib389.utils import * pytestmark = pytest.mark.tier1 @@ -367,6 +367,9 @@ def test_match_large_valueset(topology_st): be_groups = backends.create(properties={'parent': DEFAULT_SUFFIX, 'nsslapd-suffix': groups_suffix, 'name': groups_backend}) # set the entry cache to 200Mb as the 1K groups of 2K users require at least 170Mb + if get_default_db_lib() == "bdb": + config_ldbm = DSLdapObject(inst, DN_CONFIG_LDBM) + config_ldbm.set('nsslapd-cache-autosize', '0') be_groups.replace('nsslapd-cachememsize', groups_entrycache) except: raise @@ -422,7 +425,7 @@ def test_match_large_valueset(topology_st): etime = float(search_result[1].split('etime=')[1]) log.info("Duration of the search from access log was %f", etime) assert len(entries) == groups_number - assert (etime < 1) + assert (etime < 5) if __name__ == '__main__': # Run isolated
0
4d93699a71acb061c5787d2b8b61a0417ce02808
389ds/389-ds-base
Bug 536703 - Don't send empty mod to AD for mapped DN values When using winsync, setting a mapped DN attribute (such as seeAlso) to a DN outside the scope of the sync agreement causes an empty modify operation to be sent to AD. This causes AD to respond with LDAP error 89, which triggers the update to abort. The problem is that windows_update_remote_entry() uses a flag to determine if it has a modify to send to AD. This flag is set by windows_generate_update_mods(), but the mods are empty since it is detecting that the DN used in seeAlso is not in the scope of the sync agreement. The fix is to only set the modify flag if we actually have mods to send.
commit 4d93699a71acb061c5787d2b8b61a0417ce02808 Author: Nathan Kinder <[email protected]> Date: Fri Jan 22 09:37:08 2010 -0800 Bug 536703 - Don't send empty mod to AD for mapped DN values When using winsync, setting a mapped DN attribute (such as seeAlso) to a DN outside the scope of the sync agreement causes an empty modify operation to be sent to AD. This causes AD to respond with LDAP error 89, which triggers the update to abort. The problem is that windows_update_remote_entry() uses a flag to determine if it has a modify to send to AD. This flag is set by windows_generate_update_mods(), but the mods are empty since it is detecting that the DN used in seeAlso is not in the scope of the sync agreement. The fix is to only set the modify flag if we actually have mods to send. diff --git a/ldap/servers/plugins/replication/windows_protocol_util.c b/ldap/servers/plugins/replication/windows_protocol_util.c index 2c31c4f91..537e453a9 100644 --- a/ldap/servers/plugins/replication/windows_protocol_util.c +++ b/ldap/servers/plugins/replication/windows_protocol_util.c @@ -3818,7 +3818,11 @@ windows_generate_update_mods(Private_Repl_Protocol *prp,Slapi_Entry *remote_entr slapi_mods_add_mod_values(smods,LDAP_MOD_ADD,local_type,valueset_get_valuearray(vs)); } } - *do_modify = 1; + + /* Only set the do_modify flag if smods is not empty */ + if (slapi_mods_get_num_mods(smods) > 0) { + *do_modify = 1; + } } }
0
54ae3dfbe77856812881ae7c2cf59be3b6453b10
389ds/389-ds-base
Issue 50572 - After running cl-dump dbdir/cldb/*ldif.done are not deleted Description: By default, remove ldif.done files after running cl-dump. Add an option '-l' which allows keep the files. Modify 'dsconf replication dump-changelog' command accordingly. Update man files. https://pagure.io/389-ds-base/issue/50572 Reviewed by: firstyear, mreynolds (Thanks!)
commit 54ae3dfbe77856812881ae7c2cf59be3b6453b10 Author: Simon Pichugin <[email protected]> Date: Thu Aug 29 15:51:56 2019 +0200 Issue 50572 - After running cl-dump dbdir/cldb/*ldif.done are not deleted Description: By default, remove ldif.done files after running cl-dump. Add an option '-l' which allows keep the files. Modify 'dsconf replication dump-changelog' command accordingly. Update man files. https://pagure.io/389-ds-base/issue/50572 Reviewed by: firstyear, mreynolds (Thanks!) diff --git a/ldap/admin/src/scripts/cl-dump.pl b/ldap/admin/src/scripts/cl-dump.pl index f4ad5dd33..2e7f20413 100755 --- a/ldap/admin/src/scripts/cl-dump.pl +++ b/ldap/admin/src/scripts/cl-dump.pl @@ -5,7 +5,7 @@ # All rights reserved. # # License: GPL (version 3 or any later version). -# See LICENSE for details. +# See LICENSE for details. # END COPYRIGHT BLOCK ################################################################################### # @@ -13,7 +13,7 @@ # # SYNOPSIS: # cl-dump.pl [-h host] [-p port] [-D bind-dn] -w bind-password | -P bind-cert -# [-r replica-roots] [-o output-file] [-c] [-v] +# [-r replica-roots] [-o output-file] [-c] [-l] [-v] # # cl-dump.pl -i changelog-ldif-file-with-base64encoding [-o output-file] [-c] # @@ -22,7 +22,7 @@ # # OPTIONS: # -c Dump and interpret CSN only. This option can be used with or -# without -i option. +# without -i option. # # -D bind-dn # Directory server's bind DN. Default to "cn=Directory Manager" if @@ -32,6 +32,8 @@ # Directory server's host. Default to the server where the script # is running. # +# -l Preserve generated ldif.done files from changelogdir +# # -i changelog-ldif-file-with-base64encoding # If you already have a ldif-like changelog, but the changes # in that file are encoded, you may use this option to @@ -68,7 +70,7 @@ # all of this nonsense can be omitted if the mozldapsdk and perldap are # installed in the operating system locations (e.g. /usr/lib /usr/lib/perl5) -$usage="Usage: $0 [-h host] [-p port] [-D bind-dn] [-w bind-password | -P bind-cert] [-r replica-roots] [-o output-file] [-c] [-v]\n\n $0 -i changelog-ldif-file-with-base64encoding [-o output-file] [-c]\n"; +$usage="Usage: $0 [-h host] [-p port] [-D bind-dn] [-w bind-password | -P bind-cert] [-r replica-roots] [-o output-file] [-c] [-l] [-v]\n\n $0 -i changelog-ldif-file-with-base64encoding [-o output-file] [-c]\n"; use Getopt::Std; # Parse command line arguments use Mozilla::LDAP::Conn; # LDAP module for Perl @@ -86,7 +88,7 @@ $version = "Directory Server Changelog Dump - Version 1.0"; $| = 1; # Check for legal options - if (!getopts('h:p:D:w:P:r:o:cvi:')) { + if (!getopts('h:p:D:w:P:r:o:clvi:')) { print $usage; exit -1; } @@ -123,7 +125,7 @@ sub validateArgs if ($opt_o && ! open (OUTPUT, ">$opt_o")) { print "Can't create output file $opt_o\n"; $rc = -1; - } + } # Open STDOUT if option -o is missing open (OUTPUT, ">-") if !$opt_o; @@ -194,10 +196,15 @@ sub cl_dump_and_decode else { &cl_decode ($_); } - # Test op -M doesn't work well so we use rename + # Test op -M doesn't work well so we use rename/remove # here to avoid reading the same ldif file more # than once. - rename ($ldif, "$ldif.done"); + if ($opt_l) { + rename ($ldif, "$ldif.done"); + } else { + # Remove the file - default behaviou when '-l' is not specified + unlink ($ldif) + } } &print_header ($replica, "Not Found") if !$gotldif; } diff --git a/man/man1/cl-dump.1 b/man/man1/cl-dump.1 index db736aca9..fbb836a72 100644 --- a/man/man1/cl-dump.1 +++ b/man/man1/cl-dump.1 @@ -20,7 +20,7 @@ cl-dump \- Dump and decode Directory Server replication change log .SH SYNOPSIS .B cl\-dump [\fI\-h host\fR] [\fI\-p port\fR] [\fI\-D bind\(hydn\fR] \-w bind\(hypassword | \-P bind\(hycert - [\fI\-r replica\(hyroots\fR] [\fI\-o output\(hyfile\fR] [\fI\-c\fR] [\fI\-v\fR] + [\fI\-r replica\(hyroots\fR] [\fI\-o output\(hyfile\fR] [\fI\-c\fR] [\fI\-l\fR] [\fI\-v\fR] .PP .B cl\-dump @@ -30,12 +30,12 @@ cl-dump \- Dump and decode Directory Server replication change log Dump and decode Directory Server replication change log .PP .\" TeX users may be more comfortable with the \fB<whatever>\fP and -.\" \fI<whatever>\fP escape sequences to invode bold face and italics, +.\" \fI<whatever>\fP escape sequences to invode bold face and italics, .\" respectively. .SH OPTIONS A summary of options is included below. .TP -.B \-c +.B \-c Dump and interpret CSN only. This option can be used with or without \-i option. .TP @@ -47,6 +47,9 @@ the option is omitted. Directory server's host. Default to the server where the script is running. .TP +.B \-l +Preserve generated ldif.done files from changelogdir +.TP .B \-i changelog\(hyldif\(hyfile\(hywith\(hybase64encoding If you already have a ldif-like changelog, but the changes in that file are encoded, you may use this option to @@ -66,7 +69,7 @@ Specify replica roots whose changelog you want to dump. The replica roots may be separated by comma. All the replica roots would be dumped if the option is omitted. .TP -.B \-v +.B \-v Print the version of this script. .TP .B \-w bind\(hypassword diff --git a/man/man1/cl-dump.pl.1 b/man/man1/cl-dump.pl.1 index 4d63a55b7..6fa96cb2d 100644 --- a/man/man1/cl-dump.pl.1 +++ b/man/man1/cl-dump.pl.1 @@ -20,7 +20,7 @@ cl-dump \- Dump and decode Directory Server replication change log .SH SYNOPSIS .B cl\-dump.pl [\fI\-h host\fR] [\fI\-p port\fR] [\fI\-D bind\(hydn\fR] \-w bind\(hypassword | \-P bind\(hycert - [\fI\-r replica\(hyroots\fR] [\fI\-o output\(hyfile\fR] [\fI\-c\fR] [\fI\-v\fR] + [\fI\-r replica\(hyroots\fR] [\fI\-o output\(hyfile\fR] [\fI\-c\fR] [\fI\-l\fR] [\fI\-v\fR] .PP .B cl\-dump.pl @@ -30,12 +30,12 @@ cl-dump \- Dump and decode Directory Server replication change log Dump and decode Directory Server replication change log .PP .\" TeX users may be more comfortable with the \fB<whatever>\fP and -.\" \fI<whatever>\fP escape sequences to invode bold face and italics, +.\" \fI<whatever>\fP escape sequences to invode bold face and italics, .\" respectively. .SH OPTIONS A summary of options is included below. .TP -.B \-c +.B \-c Dump and interpret CSN only. This option can be used with or without \-i option. .TP @@ -47,6 +47,9 @@ the option is omitted. Directory server's host. Default to the server where the script is running. .TP +.B \-l +Preserve generated ldif.done files from changelogdir +.TP .B \-i changelog\(hyldif\(hyfile\(hywith\(hybase64encoding If you already have a ldif-like changelog, but the changes in that file are encoded, you may use this option to @@ -66,7 +69,7 @@ Specify replica roots whose changelog you want to dump. The replica roots may be separated by comma. All the replica roots would be dumped if the option is omitted. .TP -.B \-v +.B \-v Print the version of this script. .TP .B \-w bind\(hypassword diff --git a/src/lib389/lib389/cli_conf/replication.py b/src/lib389/lib389/cli_conf/replication.py index 3e147e973..eb8297d42 100644 --- a/src/lib389/lib389/cli_conf/replication.py +++ b/src/lib389/lib389/cli_conf/replication.py @@ -894,7 +894,9 @@ def dump_cl(inst, basedn, log, args): log.addHandler(fh) replicas = Replicas(inst) if not args.changelog_ldif: - replicas.process_and_dump_changelog(replica_roots=args.replica_roots, csn_only=args.csn_only) + replicas.process_and_dump_changelog(replica_roots=args.replica_roots, + csn_only=args.csn_only, + preserve_ldif_done=args.preserve_ldif_done) else: try: assert os.path.exists(args.changelog_ldif) @@ -997,6 +999,8 @@ def create_parser(subparsers): repl_set_cl.set_defaults(func=dump_cl) repl_set_cl.add_argument('-c', '--csn-only', action='store_true', help="Dump and interpret CSN only. This option can be used with or without -i option.") + repl_set_cl.add_argument('-l', '--preserve-ldif-done', action='store_true', + help="Preserve generated ldif.done files from changelogdir.") repl_set_cl.add_argument('-i', '--changelog-ldif', help="If you already have a ldif-like changelog, but the changes in that file are encoded," " you may use this option to decode that ldif-like changelog. It should be base64 encoded.") diff --git a/src/lib389/lib389/replica.py b/src/lib389/lib389/replica.py index a67a829cb..21c1ada05 100644 --- a/src/lib389/lib389/replica.py +++ b/src/lib389/lib389/replica.py @@ -1496,7 +1496,7 @@ class Replicas(DSLdapObjects): replica._populate_suffix() return replica - def process_and_dump_changelog(self, replica_roots=[], csn_only=False): + def process_and_dump_changelog(self, replica_roots=[], csn_only=False, preserve_ldif_done=False): """Dump and decode Directory Server replication change log :param replica_roots: Replica suffixes that need to be processed @@ -1541,7 +1541,12 @@ class Replicas(DSLdapObjects): cl_ldif.grep_csn() else: cl_ldif.decode() - os.rename(file_path, f'{file_path}.done') + + if preserve_ldif_done: + os.rename(file_path, f'{file_path}.done') + else: + os.remove(file_path) + if not got_ldif: self._log.info("LDIF file: Not found")
0
3779e920d0618fa928176d672986a24c35344e45
389ds/389-ds-base
fix for trac #173; update ds-logpipe.py docs about -t option
commit 3779e920d0618fa928176d672986a24c35344e45 Author: Jonathan \"Duke\" Leto <[email protected]> Date: Mon Jun 18 13:09:35 2012 -0700 fix for trac #173; update ds-logpipe.py docs about -t option diff --git a/ldap/admin/src/scripts/ds-logpipe.py b/ldap/admin/src/scripts/ds-logpipe.py index 04cef6a48..b2d8304f8 100644 --- a/ldap/admin/src/scripts/ds-logpipe.py +++ b/ldap/admin/src/scripts/ds-logpipe.py @@ -239,7 +239,7 @@ def parse_options(): parser.add_option("-s", "--serverpidfile", type='string', dest='serverpidfile', help='name of file containing the pid of the server to monitor') parser.add_option("-t", "--servertimeout", dest="servertimeout", type='int', - help="timeout in seconds to wait for the serverpid to be alive", default=60) + help="timeout in seconds to wait for the serverpid to be alive. only applies when using -s or --serverpid", default=60) parser.add_option("--serverpid", dest="serverpid", type='int', help="process id of server to monitor", default=0) parser.add_option("-u", "--user", type='string', dest='user', diff --git a/man/man1/ds-logpipe.py.1 b/man/man1/ds-logpipe.py.1 index 53093b2d0..e8f14b00b 100644 --- a/man/man1/ds-logpipe.py.1 +++ b/man/man1/ds-logpipe.py.1 @@ -52,7 +52,7 @@ The pipe and any other files created by the script will be chown()'d to this use If you want the script to exit when a particular directory server exists, specify the full path to the file containing the server pid. The default is usually something like /var/run/dirsrv/slapd-<instancename>.pid where <instancename> is usually the hostname .TP .B \-t|\-\-servertimeout=N -Since the serverpidfile may not exist yet when the script is run, the script will wait by default 60 seconds for the pid file to exist and the server to be started. Use this option to specify a different timeout. +Since the serverpidfile may not exist yet when the script is run, the script will wait by default 60 seconds for the pid file to exist and the server to be started. Use this option to specify a different timeout. The -t option only applies when using -s or --serverpid - otherwise it does nothing. .TP .B \-\-serverpid=P IF the server you want to track is already running, you can specify it using this argument. If the specified pid is not valid, the script will abort.
0
e3981575f29fadd4f02cd5d7aac3f61326dbaf23
389ds/389-ds-base
Issue 5346 - New connection table fails with ASAN failures (#5350) Bug Description: Commit 489b585a67bf9b91c33a93cf8b0c6c7bca398bee contains a buffer overflow that causes asan failures. Fix Decription: Removed the overflow, corrected an incorrect memory allocation and corrected some debug strings. fixes: https://github.com/389ds/389-ds-base/issues/5346 relates: https://github.com/389ds/389-ds-base/issues/4812 Reviewed by: @Firstyear (Thank you)
commit e3981575f29fadd4f02cd5d7aac3f61326dbaf23 Author: James Chapman <[email protected]> Date: Tue Jun 21 11:52:35 2022 +0100 Issue 5346 - New connection table fails with ASAN failures (#5350) Bug Description: Commit 489b585a67bf9b91c33a93cf8b0c6c7bca398bee contains a buffer overflow that causes asan failures. Fix Decription: Removed the overflow, corrected an incorrect memory allocation and corrected some debug strings. fixes: https://github.com/389ds/389-ds-base/issues/5346 relates: https://github.com/389ds/389-ds-base/issues/4812 Reviewed by: @Firstyear (Thank you) diff --git a/ldap/servers/slapd/conntable.c b/ldap/servers/slapd/conntable.c index 9912e4979..0cc2ee5af 100644 --- a/ldap/servers/slapd/conntable.c +++ b/ldap/servers/slapd/conntable.c @@ -132,9 +132,9 @@ connection_table_new(int table_size) ct->size = table_size; ct->list_num = SLAPD_DEFAULT_NUM_LISTENERS; - ct->list_size = table_size/ct->list_num + 1; /* +1 to avoid rounding issue */ + ct->list_size = (table_size+ct->list_num-1)/ct->list_num; /* to avoid rounding issue */ ct->num_active = (int *)slapi_ch_calloc(1, ct->list_num * sizeof(int)); - ct->c = (Connection **)slapi_ch_calloc(1, table_size * sizeof(Connection)); + ct->c = (Connection **)slapi_ch_calloc(1, table_size * sizeof(Connection *)); ct->fd = (struct POLL_STRUCT **)slapi_ch_calloc(1, table_size * sizeof(struct POLL_STRUCT)); ct->table_mutex = PR_NewLock(); /* Allocate the freelist */ @@ -181,13 +181,13 @@ connection_table_new(int table_size) ct->c[ct_list][i].c_fdi = SLAPD_INVALID_SOCKET_INDEX; if (pthread_mutex_init(&(ct->c[ct_list][i].c_mutex), &monitor_attr) != 0) { - slapi_log_err(SLAPI_LOG_ERR, "connection_table_get_connection", "pthread_mutex_init failed\n"); + slapi_log_err(SLAPI_LOG_ERR, "connection_table_new", "pthread_mutex_init failed\n"); exit(1); } ct->c[ct_list][i].c_pdumutex = PR_NewLock(); if (ct->c[ct_list][i].c_pdumutex == NULL) { - slapi_log_err(SLAPI_LOG_ERR, "connection_table_get_connection", "PR_NewLock failed\n"); + slapi_log_err(SLAPI_LOG_ERR, "connection_table_new", "PR_NewLock failed\n"); exit(1); }
0
d7d5d7f0ed55f5edbfa10a5911e8cbf44084e7ae
389ds/389-ds-base
Resolves: bug 479313 Bug Description: Server to Server SASL - DIGEST/MD5 - Can not Stop server Reviewed by: nhosoi (Thanks!) Fix Description: Using ldap_set_option with LDAP_OPT_X_SASL_SECPROPS is not thread safe. ldap_set_option acquires the OPTION lock, but using LDAP_OPT_X_SASL_SECPROPS just calls return rather than calling break to exit the switch and unlock the lock. A mozilla bug has been filed https://bugzilla.mozilla.org/show_bug.cgi?id=473438. The fix is to use LDAP_OPT_X_SASL_SSF_MAX. Platforms tested: RHEL5 Flag Day: no Doc impact: no
commit d7d5d7f0ed55f5edbfa10a5911e8cbf44084e7ae Author: Rich Megginson <[email protected]> Date: Tue Jan 13 22:24:15 2009 +0000 Resolves: bug 479313 Bug Description: Server to Server SASL - DIGEST/MD5 - Can not Stop server Reviewed by: nhosoi (Thanks!) Fix Description: Using ldap_set_option with LDAP_OPT_X_SASL_SECPROPS is not thread safe. ldap_set_option acquires the OPTION lock, but using LDAP_OPT_X_SASL_SECPROPS just calls return rather than calling break to exit the switch and unlock the lock. A mozilla bug has been filed https://bugzilla.mozilla.org/show_bug.cgi?id=473438. The fix is to use LDAP_OPT_X_SASL_SSF_MAX. Platforms tested: RHEL5 Flag Day: no Doc impact: no diff --git a/ldap/servers/slapd/util.c b/ldap/servers/slapd/util.c index 8e4876e91..79df75be0 100644 --- a/ldap/servers/slapd/util.c +++ b/ldap/servers/slapd/util.c @@ -1105,6 +1105,7 @@ slapi_ldap_init( char *ldaphost, int ldapport, int secure, int shared ) return slapi_ldap_init_ext(NULL, ldaphost, ldapport, secure, shared, NULL); } +#include <sasl.h> /* * Does the correct bind operation simple/sasl/cert depending * on the arguments passed in. If the user specified to use @@ -1258,7 +1259,8 @@ slapi_ldap_bind( } else { /* a SASL mech - set the sasl ssf to 0 if using TLS/SSL */ if (secure) { - ldap_set_option(ld, LDAP_OPT_X_SASL_SECPROPS, "maxssf=0"); + sasl_ssf_t max_ssf = 0; + ldap_set_option(ld, LDAP_OPT_X_SASL_SSF_MAX, &max_ssf); } rc = slapd_ldap_sasl_interactive_bind(ld, bindid, creds, mech, serverctrls, returnedctrls, @@ -1282,7 +1284,6 @@ done: /* the following implements the client side of sasl bind, for LDAP server -> LDAP server SASL */ -#include <sasl.h> typedef struct { char *mech;
0
4d96b793803337cc53d254b38a65f95831b6c525
389ds/389-ds-base
Bug 625424 - repl-monitor.pl doesn't work in hub node https://bugzilla.redhat.com/show_bug.cgi?id=625424 Description: repl-monitor.pl has been designed to display the entire replication topology. This patch allows to show the subset of the topology starting from the specified hub.
commit 4d96b793803337cc53d254b38a65f95831b6c525 Author: Noriko Hosoi <[email protected]> Date: Wed Feb 23 15:18:45 2011 -0800 Bug 625424 - repl-monitor.pl doesn't work in hub node https://bugzilla.redhat.com/show_bug.cgi?id=625424 Description: repl-monitor.pl has been designed to display the entire replication topology. This patch allows to show the subset of the topology starting from the specified hub. diff --git a/ldap/admin/src/scripts/repl-monitor.pl.in b/ldap/admin/src/scripts/repl-monitor.pl.in index b8e6d2db2..89b777c10 100755 --- a/ldap/admin/src/scripts/repl-monitor.pl.in +++ b/ldap/admin/src/scripts/repl-monitor.pl.in @@ -511,28 +511,45 @@ sub process_suppliers my ($ridx, $mid, $maxcsn); $mid = ""; + $ismaster = 0; $last_sidx = -1; # global variable for print html page for ($ridx = 0; $ridx <= $#allreplicas; $ridx++) { - # Skip consumers and hubs - next if $allreplicas[$ridx] !~ /:master:(\d+):/i; - $mid = $1; + # Handle masters and hubs + if ($allreplicas[$ridx] =~ /:master:(\d+):/i) { + $mid = $1; - # Skip replicas without agreements defined yet - next if (! grep {$_->{ridx} == $ridx} @allagreements); + # Skip replicas without agreements defined yet + next if (! grep {$_->{ridx} == $ridx} @allagreements); - $maxcsn = &print_master_header ($ridx, $mid); - if ( "$maxcsn" != "none" ) { - &print_consumer_header (); - &print_consumers ($ridx, $mid); + $maxcsn = &print_master_header ($ridx, $mid); + if ( "$maxcsn" != "none" ) { + &print_consumer_header (); + &print_consumers ($ridx, $mid); + } + $ismaster = 1; + } elsif (($ismaster == 0) && ($allreplicas[$ridx] =~ /:hub:(\d+):/i)) { + $mid = $1; + + # Skip replicas without agreements defined yet + next if (! grep {$_->{ridx} == $ridx} @allagreements); + + foreach $key (keys %allruvs) { + if ( $key =~ /$ridx:/) { + my ($myridx, $mymid) = split ( /:/, "$key" ); + $maxcsn = &print_hub_header($myridx, $mymid); + &print_consumer_header (); + &print_consumers ($myridx, $mymid); + } + } } &print_supplier_end; } if ($mid eq "") { - print "<p>The server is not a master or it has no replication agreement\n"; + print "<p>The server is not a master or a hub or it has no replication agreement\n"; } } @@ -544,6 +561,10 @@ sub print_master_header my ($maxcsn) = &to_string_csn ($maxcsnval); my ($sidx, $replicaroot, $replicatype, $serverid) = split (/:/, $allreplicas[$ridx]); + if ( $maxcsn == "" ) { + return $maxcsn; + } + # Print the master name if ( $last_sidx != $sidx ) { my ($ldapurl) = &get_ldap_url ($sidx, $sidx); @@ -570,6 +591,40 @@ sub print_master_header return $maxcsn; } +sub print_hub_header +{ + my ($ridx, $mid) = @_; + my ($myruv) = $allruvs {"$ridx:$mid"}; + my ($maxcsnval) = split ( /;/, "$myruv" ); + my ($maxcsn) = &to_string_csn ($maxcsnval); + my ($sidx, $replicaroot, $replicatype, $serverid) = split (/:/, $allreplicas[$ridx]); + + # Print the master name + if ( $last_sidx != $sidx ) { + my ($ldapurl) = &get_ldap_url ($sidx, $sidx); + &print_legend if ( $last_sidx < 0); + print "<p><p><hr><p>\n"; + print "\n<p><center class=page-subtitle><font color=#0099cc>\n"; + print "Hub:&nbsp $ldapurl</center>\n"; + $last_sidx = $sidx; + } + + # Print the current replica info onthe master + print "\n<p><table border=0 cellspacing=1 cellpadding=6 cols=10 width=100% class=bgColor9>\n"; + + print "\n<tr><td colspan=10><center>\n"; + print "<font class=areatitle>Replica ID:&nbsp;</font>"; + print "<font class=text28>$serverid</font>\n"; + + print "<font class=areatitle>Replica Root:&nbsp;</font>"; + print "<font class=text28>$replicaroot</font>\n"; + + print "<font class=areatitle>Max CSN:&nbsp;</font>"; + print "<font class=text28>$maxcsn</font>\n"; + + return $maxcsn; +} + sub print_consumer_header { #Print the header of consumer
0
f5a02e0ea468336c299ebcc3e66fa642b7016fdf
389ds/389-ds-base
improve txn test index handling Sometimes it is difficult to determine which indexes actually have files, and the txn thread would keep looping forever looking for missing files. This changes the txn thread to retry a few times, then just start skipping missing indexes. The txn thread will log which indexes it uses and which it skipped.
commit f5a02e0ea468336c299ebcc3e66fa642b7016fdf Author: Rich Megginson <[email protected]> Date: Fri Jun 15 16:18:33 2012 -0600 improve txn test index handling Sometimes it is difficult to determine which indexes actually have files, and the txn thread would keep looping forever looking for missing files. This changes the txn thread to retry a few times, then just start skipping missing indexes. The txn thread will log which indexes it uses and which it skipped. diff --git a/ldap/servers/slapd/back-ldbm/dblayer.c b/ldap/servers/slapd/back-ldbm/dblayer.c index d22f96d01..eb3270965 100644 --- a/ldap/servers/slapd/back-ldbm/dblayer.c +++ b/ldap/servers/slapd/back-ldbm/dblayer.c @@ -3888,6 +3888,8 @@ static int txn_test_threadmain(void *param) size_t counter = 0; char keybuf[8192]; char databuf[8192]; + int dbattempts = 0; + int dbmaxretries = 3; PR_ASSERT(NULL != param); li = (struct ldbminfo*)param; @@ -3909,7 +3911,7 @@ wait_for_init: if (priv->dblayer_stop_threads) { goto end; } - + dbattempts++; for (inst_obj = objset_first_obj(li->li_instance_set); inst_obj; inst_obj = objset_next_obj(li->li_instance_set, inst_obj)) { char **idx = NULL; @@ -3917,6 +3919,8 @@ wait_for_init: backend *be = inst->inst_be; if (be->be_state != BE_STATE_STARTED) { + LDAPDebug0Args(LDAP_DEBUG_ANY, + "txn_test_threadmain: backend not started, retrying\n"); object_release(inst_obj); goto wait_for_init; } @@ -3924,6 +3928,8 @@ wait_for_init: for (idx = cfg.indexes; idx && *idx; ++idx) { DB *db = NULL; if (be->be_state != BE_STATE_STARTED) { + LDAPDebug0Args(LDAP_DEBUG_ANY, + "txn_test_threadmain: backend not started, retrying\n"); object_release(inst_obj); goto wait_for_init; } @@ -3931,6 +3937,8 @@ wait_for_init: if (!strcmp(*idx, "id2entry")) { dblayer_get_id2entry(be, &db); if (db == NULL) { + LDAPDebug0Args(LDAP_DEBUG_ANY, + "txn_test_threadmain: id2entry database not found or not ready yet, retrying\n"); object_release(inst_obj); goto wait_for_init; } @@ -3938,15 +3946,35 @@ wait_for_init: struct attrinfo *ai = NULL; ainfo_get(be, *idx, &ai); if (NULL == ai) { - object_release(inst_obj); - goto wait_for_init; - } - if((dblayer_get_index_file(be, ai, &db, 0) != 0) || (db == NULL)){ - if (strcasecmp(*idx, TXN_TEST_IDX_OK_IF_NULL)) { + if (dbattempts >= dbmaxretries) { + LDAPDebug1Arg(LDAP_DEBUG_ANY, + "txn_test_threadmain: index [%s] not found or not ready yet, skipping\n", + *idx); + continue; + } else { + LDAPDebug1Arg(LDAP_DEBUG_ANY, + "txn_test_threadmain: index [%s] not found or not ready yet, retrying\n", + *idx); object_release(inst_obj); goto wait_for_init; } } + if (dblayer_get_index_file(be, ai, &db, 0) || (NULL == db)) { + if ((NULL == db) && strcasecmp(*idx, TXN_TEST_IDX_OK_IF_NULL)) { + if (dbattempts >= dbmaxretries) { + LDAPDebug1Arg(LDAP_DEBUG_ANY, + "txn_test_threadmain: database file for index [%s] not found or not ready yet, skipping\n", + *idx); + continue; + } else { + LDAPDebug1Arg(LDAP_DEBUG_ANY, + "txn_test_threadmain: database file for index [%s] not found or not ready yet, retrying\n", + *idx); + object_release(inst_obj); + goto wait_for_init; + } + } + } } if (db) { ttilist = (txn_test_iter **)slapi_ch_realloc((char *)ttilist, sizeof(txn_test_iter *) * (tticnt + 1)); @@ -3955,6 +3983,9 @@ wait_for_init: } } + LDAPDebug0Args(LDAP_DEBUG_ANY, "txn_test_threadmain: starting main txn stress loop\n"); + print_ttilist(ttilist, tticnt); + while (!priv->dblayer_stop_threads) { retry_txn: init_ttilist(ttilist, tticnt);
0
c574a5401c8a26ed4d760331097d3d2ea2bb3359
389ds/389-ds-base
Fix for #155591: treat an ruv with no min_csn as pristine
commit c574a5401c8a26ed4d760331097d3d2ea2bb3359 Author: David Boreham <[email protected]> Date: Fri May 6 03:33:36 2005 +0000 Fix for #155591: treat an ruv with no min_csn as pristine diff --git a/ldap/servers/plugins/replication/repl5_ruv.c b/ldap/servers/plugins/replication/repl5_ruv.c index effc4af20..6ece36763 100644 --- a/ldap/servers/plugins/replication/repl5_ruv.c +++ b/ldap/servers/plugins/replication/repl5_ruv.c @@ -1857,6 +1857,27 @@ PRBool ruv_has_csns(const RUV *ruv) return retval; } +PRBool ruv_has_both_csns(const RUV *ruv) +{ + PRBool retval = PR_TRUE; + CSN *mincsn = NULL; + CSN *maxcsn = NULL; + + ruv_get_min_csn(ruv, &mincsn); + ruv_get_max_csn(ruv, &maxcsn); + if (mincsn) { + csn_free(&mincsn); + csn_free(&maxcsn); + } else if (maxcsn) { + csn_free(&maxcsn); + retval = PR_FALSE; /* it has a maxcsn but no mincsn */ + } else { + retval = PR_FALSE; /* both min and max are false */ + } + + return retval; +} + /* Check if the first ruv is newer than the second one */ PRBool ruv_is_newer (Object *sruvobj, Object *cruvobj) diff --git a/ldap/servers/plugins/replication/repl5_ruv.h b/ldap/servers/plugins/replication/repl5_ruv.h index a85318b4f..aa4b04db8 100644 --- a/ldap/servers/plugins/replication/repl5_ruv.h +++ b/ldap/servers/plugins/replication/repl5_ruv.h @@ -112,6 +112,7 @@ int ruv_local_contains_supplier(RUV *ruv, ReplicaId rid); /* returns true if the ruv has any csns, false otherwise - used for testing whether or not an RUV is empty */ PRBool ruv_has_csns(const RUV *ruv); +PRBool ruv_has_both_csns(const RUV *ruv); PRBool ruv_is_newer (Object *sruv, Object *cruv); void ruv_force_csn_update (RUV *ruv, CSN *csn); #ifdef __cplusplus diff --git a/ldap/servers/plugins/replication/windows_inc_protocol.c b/ldap/servers/plugins/replication/windows_inc_protocol.c index b5325b923..c3a642efc 100644 --- a/ldap/servers/plugins/replication/windows_inc_protocol.c +++ b/ldap/servers/plugins/replication/windows_inc_protocol.c @@ -1632,7 +1632,14 @@ windows_examine_update_vector(Private_Repl_Protocol *prp, RUV *remote_ruv) } else { - return_value = EXAMINE_RUV_OK; + /* Check for the case where part of the RUV remote is missing */ + if (ruv_has_both_csns(remote_ruv)) + { + return_value = EXAMINE_RUV_OK; + } else + { + return_value = EXAMINE_RUV_PRISTINE_REPLICA; + } } slapi_ch_free((void**)&remote_gen); slapi_ch_free((void**)&local_gen);
0
080cb44f5eaa794375a8e69b6e1ac09fcae9a961
389ds/389-ds-base
Ticket 47620 - Fix logically dead code. Coverity issues: 12419 & 12420 https://fedorahosted.org/389/ticket/47620 Reviewed by: rmeggins(Thanks!)
commit 080cb44f5eaa794375a8e69b6e1ac09fcae9a961 Author: Mark Reynolds <[email protected]> Date: Mon Dec 16 09:48:12 2013 -0500 Ticket 47620 - Fix logically dead code. Coverity issues: 12419 & 12420 https://fedorahosted.org/389/ticket/47620 Reviewed by: rmeggins(Thanks!) diff --git a/ldap/servers/plugins/replication/repl5_agmtlist.c b/ldap/servers/plugins/replication/repl5_agmtlist.c index 7d1c6518c..59eb84f34 100644 --- a/ldap/servers/plugins/replication/repl5_agmtlist.c +++ b/ldap/servers/plugins/replication/repl5_agmtlist.c @@ -278,16 +278,6 @@ agmtlist_modify_callback(Slapi_PBlock *pb, Slapi_Entry *entryBefore, Slapi_Entry } /* Start replica initialization */ - if (val == NULL) - { - PR_snprintf (errortext, SLAPI_DSE_RETURNTEXT_SIZE, "No value supplied for attr (%s)", mods[i]->mod_type); - slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name, "agmtlist_modify_callback: %s\n", - errortext); - *returncode = LDAP_UNWILLING_TO_PERFORM; - rc = SLAPI_DSE_CALLBACK_ERROR; - break; - } - if (strcasecmp (val, "start") == 0) { start_initialize = 1; diff --git a/ldap/servers/plugins/replication/repl5_replica_config.c b/ldap/servers/plugins/replication/repl5_replica_config.c index 9abbbac77..dfe898ae1 100644 --- a/ldap/servers/plugins/replication/repl5_replica_config.c +++ b/ldap/servers/plugins/replication/repl5_replica_config.c @@ -496,7 +496,7 @@ replica_config_modify (Slapi_PBlock *pb, Slapi_Entry* entryBefore, Slapi_Entry* *returncode = LDAP_SUCCESS; } else if (strcasecmp (config_attr, type_replicaProtocolTimeout) == 0 ){ - if (apply_mods && config_attr_value && config_attr_value[0]) + if (apply_mods) { long ptimeout = 0;
0
bbe8f7a9cd477c2e00e721e4420f6a25d478f2ad
389ds/389-ds-base
Run acceptance in the background
commit bbe8f7a9cd477c2e00e721e4420f6a25d478f2ad Author: Nathan Kinder <[email protected]> Date: Wed Apr 6 14:56:43 2005 +0000 Run acceptance in the background diff --git a/ldap/cm/Makefile b/ldap/cm/Makefile index deeb1a48b..0811d9cdb 100644 --- a/ldap/cm/Makefile +++ b/ldap/cm/Makefile @@ -799,7 +799,7 @@ endif # USE_64 else ifeq ($(ARCH), Linux) ifdef BUILD_RPM - $(acceptdir)/accept $(shell echo $(BUILD_SHIP)/$(RPM_FILE_BASE)*$(NSOS_ARCH)$(NSOS_RELEASE).$(RPM_ARCH).$(RPM_FLAVOR).rpm) + $(acceptdir)/accept $(shell echo $(BUILD_SHIP)/$(RPM_FILE_BASE)*$(NSOS_ARCH)$(NSOS_RELEASE).$(RPM_ARCH).$(RPM_FLAVOR).rpm) & endif # BUILD_RPM else $(acceptdir)/accept $(BUILD_SHIP)/$(FTPNAMEGZ) &
0
fc1a997c840ed483aa8e1ef86d805b2def63bcc9
389ds/389-ds-base
Issue 6046 - Make dscreate to work during kickstart installations Description: The with_systemd_running method is added to ensure that systemd is operational (for the start, stop, and status methods). In particular, this makes dscreate work in chroot environments. But is has a broader effect in that it avoids systemctl calls when they are guaranteed to not work. Fixes: https://github.com/389ds/389-ds-base/issues/6046 Reviewed by: @vashirov
commit fc1a997c840ed483aa8e1ef86d805b2def63bcc9 Author: Môshe van der Sterre <[email protected]> Date: Fri Feb 9 20:02:58 2024 +0100 Issue 6046 - Make dscreate to work during kickstart installations Description: The with_systemd_running method is added to ensure that systemd is operational (for the start, stop, and status methods). In particular, this makes dscreate work in chroot environments. But is has a broader effect in that it avoids systemctl calls when they are guaranteed to not work. Fixes: https://github.com/389ds/389-ds-base/issues/6046 Reviewed by: @vashirov diff --git a/src/lib389/lib389/__init__.py b/src/lib389/lib389/__init__.py index 4edea63b7..b4cee81e8 100644 --- a/src/lib389/lib389/__init__.py +++ b/src/lib389/lib389/__init__.py @@ -1105,7 +1105,7 @@ class DirSrv(SimpleLDAPObject, object): if self.status() is True: return - if self.with_systemd(): + if self.with_systemd_running(): self.log.debug("systemd status -> True") # Do systemd things here ... try: @@ -1186,7 +1186,7 @@ class DirSrv(SimpleLDAPObject, object): if self.status() is False: return - if self.with_systemd(): + if self.with_systemd_running(): self.log.debug("systemd status -> True") # Do systemd things here ... subprocess.check_output(["systemctl", "stop", "dirsrv@%s" % self.serverid], stderr=subprocess.STDOUT) @@ -1213,7 +1213,7 @@ class DirSrv(SimpleLDAPObject, object): Will update the self.state parameter. """ - if self.with_systemd(): + if self.with_systemd_running(): self.log.debug("systemd status -> True") # Do systemd things here ... rc = subprocess.call(["systemctl", @@ -1730,6 +1730,17 @@ class DirSrv(SimpleLDAPObject, object): return self.systemd_override return self.ds_paths.with_systemd + def with_systemd_running(self): + if not self.with_systemd(): + return False + cp = subprocess.run(["systemctl", "is-system-running"], + universal_newlines=True, capture_output=True) + # is-system-running can detect the 7 modes (initializing, starting, + # running, degraded, maintenance, stopping, offline) or "unknown". + # To keep things simple, we assume that anything other than "offline" + # means that systemd is usable. + return cp.stdout.strip() != 'offline' + def pid_file(self): if self._containerised: return "/data/run/slapd-localhost.pid"
0
355231234ddeb75095b761abcb15300979838bf3
389ds/389-ds-base
Issue 49585 - Add py3 support to password test suite Description: Added py3 support by explicitly changing strings to bytes. https://pagure.io/389-ds-base/issue/49585 Reviewed by: spichugi
commit 355231234ddeb75095b761abcb15300979838bf3 Author: Akshay Adhikari <[email protected]> Date: Fri Mar 23 16:04:03 2018 +0530 Issue 49585 - Add py3 support to password test suite Description: Added py3 support by explicitly changing strings to bytes. https://pagure.io/389-ds-base/issue/49585 Reviewed by: spichugi diff --git a/dirsrvtests/tests/suites/password/pwdPolicy_attribute_test.py b/dirsrvtests/tests/suites/password/pwdPolicy_attribute_test.py index b3ef61d2d..64c82e47c 100644 --- a/dirsrvtests/tests/suites/password/pwdPolicy_attribute_test.py +++ b/dirsrvtests/tests/suites/password/pwdPolicy_attribute_test.py @@ -67,7 +67,7 @@ def password_policy(topology_st, test_user): try: topology_st.standalone.modify_s(DN_CONFIG, [(ldap.MOD_REPLACE, 'nsslapd-pwpolicy-local', - 'on')]) + b'on')]) except ldap.LDAPError as e: log.error('Failed to set fine-grained policy: error {}'.format( e.message['desc'])) @@ -88,7 +88,7 @@ def password_policy(topology_st, test_user): try: topology_st.standalone.modify_s(OU_PEOPLE, [(ldap.MOD_REPLACE, 'pwdpolicysubentry', - PW_POLICY_CONT_PEOPLE)]) + ensure_bytes(PW_POLICY_CONT_PEOPLE))]) except ldap.LDAPError as e: log.error('Failed to pwdpolicysubentry pw policy ' \ 'policy for {}: error {}'.format(OU_PEOPLE, @@ -110,7 +110,7 @@ def password_policy(topology_st, test_user): try: topology_st.standalone.modify_s(TEST_USER_DN, [(ldap.MOD_REPLACE, 'pwdpolicysubentry', - PW_POLICY_CONT_USER)]) + ensure_bytes(PW_POLICY_CONT_USER))]) except ldap.LDAPError as e: log.error('Failed to pwdpolicysubentry pw policy ' \ 'policy for {}: error {}'.format(TEST_USER_DN, @@ -150,7 +150,7 @@ def test_change_pwd(topology_st, test_user, password_policy, try: topology_st.standalone.modify_s(PW_POLICY_CONT_PEOPLE, [(ldap.MOD_REPLACE, 'passwordChange', - subtree_pwchange)]) + ensure_bytes(subtree_pwchange))]) except ldap.LDAPError as e: log.error('Failed to set passwordChange ' \ 'policy for {}: error {}'.format(PW_POLICY_CONT_PEOPLE, @@ -162,7 +162,7 @@ def test_change_pwd(topology_st, test_user, password_policy, try: topology_st.standalone.modify_s(PW_POLICY_CONT_USER, [(ldap.MOD_REPLACE, 'passwordChange', - user_pwchange)]) + ensure_bytes(user_pwchange))]) except ldap.LDAPError as e: log.error('Failed to set passwordChange ' \ 'policy for {}: error {}'.format(PW_POLICY_CONT_USER, @@ -177,11 +177,11 @@ def test_change_pwd(topology_st, test_user, password_policy, with pytest.raises(exception): topology_st.standalone.modify_s(TEST_USER_DN, [(ldap.MOD_REPLACE, 'userPassword', - 'new_pass')]) + b'new_pass')]) else: topology_st.standalone.modify_s(TEST_USER_DN, [(ldap.MOD_REPLACE, 'userPassword', - 'new_pass')]) + b'new_pass')]) except ldap.LDAPError as e: log.error('Failed to change userpassword for {}: error {}'.format( TEST_USER_DN, e.message['info'])) @@ -191,7 +191,7 @@ def test_change_pwd(topology_st, test_user, password_policy, topology_st.standalone.simple_bind_s(DN_DM, PASSWORD) topology_st.standalone.modify_s(TEST_USER_DN, [(ldap.MOD_REPLACE, 'userPassword', - TEST_USER_PWD)]) + ensure_bytes(TEST_USER_PWD))]) def test_pwd_min_age(topology_st, test_user, password_policy): @@ -228,7 +228,7 @@ def test_pwd_min_age(topology_st, test_user, password_policy): try: topology_st.standalone.modify_s(PW_POLICY_CONT_PEOPLE, [(ldap.MOD_REPLACE, 'passwordminage', - num_seconds)]) + ensure_bytes(num_seconds))]) except ldap.LDAPError as e: log.error('Failed to set passwordminage ' \ 'policy for {}: error {}'.format(PW_POLICY_CONT_PEOPLE, @@ -239,7 +239,7 @@ def test_pwd_min_age(topology_st, test_user, password_policy): try: topology_st.standalone.modify_s(PW_POLICY_CONT_USER, [(ldap.MOD_REPLACE, 'passwordminage', - num_seconds)]) + ensure_bytes(num_seconds))]) except ldap.LDAPError as e: log.error('Failed to set passwordminage ' \ 'policy for {}: error {}'.format(PW_POLICY_CONT_USER, @@ -250,7 +250,7 @@ def test_pwd_min_age(topology_st, test_user, password_policy): try: topology_st.standalone.modify_s(DN_CONFIG, [(ldap.MOD_REPLACE, 'passwordminage', - num_seconds)]) + ensure_bytes(num_seconds))]) except ldap.LDAPError as e: log.error('Failed to set passwordminage ' \ 'policy for {}: error {}'.format(DN_CONFIG, @@ -263,7 +263,7 @@ def test_pwd_min_age(topology_st, test_user, password_policy): topology_st.standalone.simple_bind_s(TEST_USER_DN, TEST_USER_PWD) topology_st.standalone.modify_s(TEST_USER_DN, [(ldap.MOD_REPLACE, 'userPassword', - 'new_pass')]) + b'new_pass')]) except ldap.LDAPError as e: log.error('Failed to change userpassword for {}: error {}'.format( TEST_USER_DN, e.message['info'])) @@ -275,7 +275,7 @@ def test_pwd_min_age(topology_st, test_user, password_policy): with pytest.raises(ldap.CONSTRAINT_VIOLATION): topology_st.standalone.modify_s(TEST_USER_DN, [(ldap.MOD_REPLACE, 'userPassword', - 'new_new_pass')]) + b'new_new_pass')]) log.info('Wait {} second'.format(int(num_seconds) + 2)) time.sleep(int(num_seconds) + 2) @@ -285,7 +285,7 @@ def test_pwd_min_age(topology_st, test_user, password_policy): topology_st.standalone.simple_bind_s(TEST_USER_DN, 'new_pass') topology_st.standalone.modify_s(TEST_USER_DN, [(ldap.MOD_REPLACE, 'userPassword', - TEST_USER_PWD)]) + ensure_bytes(TEST_USER_PWD))]) except ldap.LDAPError as e: log.error('Failed to change userpassword for {}: error {}'.format( TEST_USER_DN, e.message['info'])) @@ -295,7 +295,7 @@ def test_pwd_min_age(topology_st, test_user, password_policy): topology_st.standalone.simple_bind_s(DN_DM, PASSWORD) topology_st.standalone.modify_s(TEST_USER_DN, [(ldap.MOD_REPLACE, 'userPassword', - TEST_USER_PWD)]) + ensure_bytes(TEST_USER_PWD))]) if __name__ == '__main__': diff --git a/dirsrvtests/tests/suites/password/pwdPolicy_inherit_global_test.py b/dirsrvtests/tests/suites/password/pwdPolicy_inherit_global_test.py index 823cfda61..93d6db5ea 100644 --- a/dirsrvtests/tests/suites/password/pwdPolicy_inherit_global_test.py +++ b/dirsrvtests/tests/suites/password/pwdPolicy_inherit_global_test.py @@ -12,9 +12,11 @@ import time import ldap import pytest +from lib389.utils import * from lib389 import Entry from lib389._constants import * from lib389.topologies import topology_st +from lib389.idm.organisationalunit import OrganisationalUnits logging.getLogger(__name__).setLevel(logging.INFO) log = logging.getLogger(__name__) @@ -50,8 +52,9 @@ def test_user(topology_st, request): 'userPassword': PASSWORD}))) log.info('Adding an aci for the bind user') BN_ACI = '(targetattr="*")(version 3.0; acl "pwp test"; allow (all) userdn="ldap:///%s";)' % BN - topology_st.standalone.modify_s(OU_PEOPLE, [(ldap.MOD_ADD, 'aci', BN_ACI)]) - + ous = OrganisationalUnits(topology_st.standalone, DEFAULT_SUFFIX) + ou_people = ous.get('people') + ou_people.add('aci', BN_ACI) except ldap.LDAPError as e: log.error('Failed to add user (%s): error (%s)' % (BN, e.message['desc'])) @@ -60,7 +63,9 @@ def test_user(topology_st, request): def fin(): log.info('Deleting user {}'.format(BN)) topology_st.standalone.delete_s(BN) - topology_st.standalone.modify_s(OU_PEOPLE, [(ldap.MOD_DELETE, 'aci', BN_ACI)]) + ous = OrganisationalUnits(topology_st.standalone, DEFAULT_SUFFIX) + ou_people = ous.get('people') + ou_people.remove('aci', BN_ACI) request.addfinalizer(fin) @@ -76,9 +81,7 @@ def password_policy(topology_st, test_user): log.info('Enable fine-grained policy') try: - topology_st.standalone.modify_s(DN_CONFIG, [(ldap.MOD_REPLACE, - 'nsslapd-pwpolicy-local', - 'on')]) + topology_st.standalone.config.set('nsslapd-pwpolicy-local', 'on') except ldap.LDAPError as e: log.error('Failed to set fine-grained policy: error {}'.format( e.message['desc'])) @@ -97,9 +100,9 @@ def password_policy(topology_st, test_user): log.info('Add pwdpolicysubentry attribute to {}'.format(OU_PEOPLE)) try: - topology_st.standalone.modify_s(OU_PEOPLE, [(ldap.MOD_REPLACE, - 'pwdpolicysubentry', - PWP_CONTAINER_PEOPLE)]) + ous = OrganisationalUnits(topology_st.standalone, DEFAULT_SUFFIX) + ou_people = ous.get('people') + ou_people.set('pwdpolicysubentry', PWP_CONTAINER_PEOPLE) except ldap.LDAPError as e: log.error('Failed to pwdpolicysubentry pw policy ' \ 'policy for {}: error {}'.format(OU_PEOPLE, @@ -108,11 +111,11 @@ def password_policy(topology_st, test_user): log.info("Set the default settings for the policy container.") topology_st.standalone.modify_s(PWP_CONTAINER_PEOPLE, - [(ldap.MOD_REPLACE, 'passwordMustChange', 'off'), - (ldap.MOD_REPLACE, 'passwordExp', 'off'), - (ldap.MOD_REPLACE, 'passwordMinAge', '0'), - (ldap.MOD_REPLACE, 'passwordChange', 'off'), - (ldap.MOD_REPLACE, 'passwordStorageScheme', 'ssha')]) + [(ldap.MOD_REPLACE, 'passwordMustChange', b'off'), + (ldap.MOD_REPLACE, 'passwordExp', b'off'), + (ldap.MOD_REPLACE, 'passwordMinAge', b'0'), + (ldap.MOD_REPLACE, 'passwordChange', b'off'), + (ldap.MOD_REPLACE, 'passwordStorageScheme', b'ssha')]) check_attr_val(topology_st, CONFIG_DN, ATTR_INHERIT_GLOBAL, 'off') check_attr_val(topology_st, CONFIG_DN, ATTR_CHECK_SYNTAX, 'off') @@ -126,7 +129,7 @@ def check_attr_val(topology_st, dn, attr, expected): assert centry[0], 'Failed to get %s' % dn val = centry[0].getValue(attr) - assert val == expected, 'Default value of %s is not %s, but %s' % ( + assert str(val, 'utf-8') == expected, 'Default value of %s is not %s, but %s' % ( attr, expected, val) log.info('Default value of %s is %s' % (attr, expected)) @@ -160,10 +163,8 @@ def test_entry_has_no_restrictions(topology_st, password_policy, test_user, log.info('Set {} to {}'.format(ATTR_INHERIT_GLOBAL, inherit_value)) log.info('Set {} to {}'.format(ATTR_CHECK_SYNTAX, checksyntax_value)) - topology_st.standalone.modify_s(CONFIG_DN, [(ldap.MOD_REPLACE, - ATTR_INHERIT_GLOBAL, inherit_value)]) - topology_st.standalone.modify_s(CONFIG_DN, [(ldap.MOD_REPLACE, - ATTR_CHECK_SYNTAX, checksyntax_value)]) + topology_st.standalone.config.set(ATTR_INHERIT_GLOBAL, inherit_value) + topology_st.standalone.config.set(ATTR_CHECK_SYNTAX, checksyntax_value) # Wait a second for cn=config to apply time.sleep(1) @@ -229,12 +230,10 @@ def test_entry_has_restrictions(topology_st, password_policy, test_user, contain log.info('Set {} to {}'.format(ATTR_INHERIT_GLOBAL, 'on')) log.info('Set {} to {}'.format(ATTR_CHECK_SYNTAX, 'on')) - topology_st.standalone.modify_s(CONFIG_DN, [(ldap.MOD_REPLACE, - ATTR_INHERIT_GLOBAL, 'on')]) - topology_st.standalone.modify_s(CONFIG_DN, [(ldap.MOD_REPLACE, - ATTR_CHECK_SYNTAX, 'on')]) + topology_st.standalone.config.set(ATTR_INHERIT_GLOBAL, 'on') + topology_st.standalone.config.set(ATTR_CHECK_SYNTAX, 'on') topology_st.standalone.modify_s(container, [(ldap.MOD_REPLACE, - 'passwordMinLength', '9')]) + 'passwordMinLength', b'9')]) # Wait a second for cn=config to apply time.sleep(1)
0
d7be25e108a9ef57a4ccae38c88550d2fbe85578
389ds/389-ds-base
Ticket 47451 - dynamic plugins - fix crash caused by invalid plugin config Bug Description: After making an invalid plugin change, that should cause the old plugin entry to be reloaded, the server will crash. Fix Description: If a plugin fails to start after applying invalid config changes, we need to make sure it is removed from the global plugin lists, or else a freed plugin can be deferenced later. Also moved the plugin validation check in dse_modify to happen in the preop stage, so invalid configurations do not persist in the dse.ldif https://fedorahosted.org/389/ticket/47451 Valgrind: passed Reviewed by: nhosoi(Thanks!)
commit d7be25e108a9ef57a4ccae38c88550d2fbe85578 Author: Mark Reynolds <[email protected]> Date: Mon Feb 9 16:23:04 2015 -0500 Ticket 47451 - dynamic plugins - fix crash caused by invalid plugin config Bug Description: After making an invalid plugin change, that should cause the old plugin entry to be reloaded, the server will crash. Fix Description: If a plugin fails to start after applying invalid config changes, we need to make sure it is removed from the global plugin lists, or else a freed plugin can be deferenced later. Also moved the plugin validation check in dse_modify to happen in the preop stage, so invalid configurations do not persist in the dse.ldif https://fedorahosted.org/389/ticket/47451 Valgrind: passed Reviewed by: nhosoi(Thanks!) diff --git a/dirsrvtests/suites/dynamic-plugins/plugin_tests.py b/dirsrvtests/suites/dynamic-plugins/plugin_tests.py index 315547b2e..a5521428f 100644 --- a/dirsrvtests/suites/dynamic-plugins/plugin_tests.py +++ b/dirsrvtests/suites/dynamic-plugins/plugin_tests.py @@ -2174,6 +2174,8 @@ def test_rootdn(inst, args=None): PLUGIN_DN = 'cn=' + PLUGIN_ROOTDN_ACCESS + ',cn=plugins,cn=config' + log.info('Testing ' + PLUGIN_ROOTDN_ACCESS + '...') + ############################################################################ # Configure plugin ############################################################################ @@ -2223,12 +2225,28 @@ def test_rootdn(inst, args=None): # Change the config ############################################################################ + # Bind as the user who can make updates to the config try: inst.simple_bind_s(USER1_DN, 'password') except ldap.LDAPError, e: log.error('test_rootdn: failed to bind as user1') assert False + # First, test that invalid plugin changes are rejected + try: + inst.modify_s(PLUGIN_DN, [(ldap.MOD_REPLACE, 'rootdn-deny-ip', '12.12.ZZZ.12')]) + log.fatal('test_rootdn: Incorrectly allowed to add invalid "rootdn-deny-ip: 12.12.ZZZ.12"') + assert False + except ldap.LDAPError: + pass + + try: + inst.modify_s(PLUGIN_DN, [(ldap.MOD_REPLACE, 'rootdn-allow-host', 'host._.com')]) + log.fatal('test_rootdn: Incorrectly allowed to add invalid "rootdn-allow-host: host._.com"') + assert False + except ldap.LDAPError: + pass + # Remove the restriction try: inst.modify_s(PLUGIN_DN, [(ldap.MOD_DELETE, 'rootdn-allow-ip', None)]) diff --git a/ldap/servers/slapd/dse.c b/ldap/servers/slapd/dse.c index f80178e23..9bb591499 100644 --- a/ldap/servers/slapd/dse.c +++ b/ldap/servers/slapd/dse.c @@ -157,7 +157,7 @@ static struct dse_node *dse_find_node( struct dse* pdse, const Slapi_DN *dn ); static int dse_modify_plugin(Slapi_Entry *pre_entry, Slapi_Entry *post_entry, char *returntext); static int dse_add_plugin(Slapi_Entry *entry, char *returntext); static int dse_delete_plugin(Slapi_Entry *entry, char *returntext); -static void dse_post_modify_plugin(Slapi_Entry *entryBefore, Slapi_Entry *entryAfter, LDAPMod **mods); +static int dse_pre_modify_plugin(Slapi_Entry *entryBefore, Slapi_Entry *entryAfter, LDAPMod **mods); /* richm: In almost all modes e.g. db2ldif, ldif2db, etc. we do not need/want @@ -1916,13 +1916,41 @@ dse_modify(Slapi_PBlock *pb) /* JCM There should only be one exit point from thi } } else { /* - * Check if we are enabling/disabling a plugin + * If we are using dynamic plugins, and we are modifying a plugin + * we need to do some additional checks. First, check if we are + * enabling/disabling a plugin. Then make sure the plugin still + * starts after applying the plugin changes. */ - if((plugin_started = dse_modify_plugin(ec, ecc, returntext)) == -1){ - returncode = LDAP_UNWILLING_TO_PERFORM; - rc = SLAPI_DSE_CALLBACK_ERROR; - } else { - rc = SLAPI_DSE_CALLBACK_OK; + rc = SLAPI_DSE_CALLBACK_OK; + if(config_get_dynamic_plugins() && + slapi_entry_attr_hasvalue(ec, SLAPI_ATTR_OBJECTCLASS, "nsSlapdPlugin") ) + { + if((plugin_started = dse_modify_plugin(ec, ecc, returntext)) == -1){ + returncode = LDAP_UNWILLING_TO_PERFORM; + rc = SLAPI_DSE_CALLBACK_ERROR; + retval = -1; + goto done; + } + /* + * If this is not a internal operation, make sure the plugin + * can be restarted. + */ + if(!internal_op){ + if(dse_pre_modify_plugin(ec, ecc, mods)){ + char *errtext; + slapi_pblock_get(pb, SLAPI_PB_RESULT_TEXT, &errtext); + if (errtext) { + PL_strncpyz(returntext, + "Failed to apply plugin config change, " + "check the errors log for more info.", + sizeof(returntext)); + } + returncode = LDAP_UNWILLING_TO_PERFORM; + rc = SLAPI_DSE_CALLBACK_ERROR; + retval = -1; + goto done; + } + } } } } @@ -2041,44 +2069,20 @@ dse_modify(Slapi_PBlock *pb) /* JCM There should only be one exit point from thi } } } - /* - * Perform postop plugin configuration changes unless this is an internal operation - */ - if(!internal_op){ - if(returncode == LDAP_SUCCESS){ - dse_post_modify_plugin(ec, ecc, mods); - } else if(plugin_started){ - if(plugin_started == 1){ - /* the op failed, turn the plugin off */ - plugin_delete(ecc, returntext, 0 /* not locked */); - } else if (plugin_started == 2){ - /* - * This probably can't happen, but... - * the op failed, turn the plugin back on. - */ - plugin_add(ecc, returntext, 0 /* not locked */); - } - } - } slapi_send_ldap_result( pb, returncode, NULL, returntext[0] ? returntext : NULL, 0, NULL ); return dse_modify_return(retval, ec, ecc); } -static void -dse_post_modify_plugin(Slapi_Entry *entryBefore, Slapi_Entry *entryAfter, LDAPMod **mods) +static int +dse_pre_modify_plugin(Slapi_Entry *entryBefore, Slapi_Entry *entryAfter, LDAPMod **mods) { char *enabled = NULL; int restart_plugin = 1; + int rc = 0; int i; - if (!slapi_entry_attr_hasvalue(entryBefore, SLAPI_ATTR_OBJECTCLASS, "nsSlapdPlugin") || - !config_get_dynamic_plugins() ){ - /* not a plugin, or we aren't applying updates dynamically - just move on */ - return; - } - /* * Only check the mods if the plugin is enabled - no need to restart a plugin if it's not running. */ @@ -2094,14 +2098,15 @@ dse_post_modify_plugin(Slapi_Entry *entryBefore, Slapi_Entry *entryAfter, LDAPMo } if(restart_plugin){ /* for all other plugin config changes, restart the plugin */ if(plugin_restart(entryBefore, entryAfter) != LDAP_SUCCESS){ - slapi_log_error(SLAPI_LOG_FATAL,"dse_post_modify_plugin", "The configuration change " - "for plugin (%s) could not be applied dynamically, and will be ignored until " - "the server is restarted.\n", + slapi_log_error(SLAPI_LOG_FATAL,"dse_pre_modify_plugin", + "The configuration change for plugin (%s) could not be applied.\n", slapi_entry_get_dn(entryBefore)); + rc = -1; } } } slapi_ch_free_string(&enabled); + return rc; } /* @@ -2118,12 +2123,6 @@ dse_modify_plugin(Slapi_Entry *pre_entry, Slapi_Entry *post_entry, char *returnt { int rc = LDAP_SUCCESS; - if (!slapi_entry_attr_hasvalue(post_entry, SLAPI_ATTR_OBJECTCLASS, "nsSlapdPlugin") || - !config_get_dynamic_plugins() ) - { - return rc; - } - if( slapi_entry_attr_hasvalue(pre_entry, "nsslapd-pluginEnabled", "on") && slapi_entry_attr_hasvalue(post_entry, "nsslapd-pluginEnabled", "off") ) { diff --git a/ldap/servers/slapd/plugin.c b/ldap/servers/slapd/plugin.c index b0b18e755..94aba7ffd 100644 --- a/ldap/servers/slapd/plugin.c +++ b/ldap/servers/slapd/plugin.c @@ -99,6 +99,7 @@ static int plugin_delete_check_dependency(struct slapdplugin *plugin_entry, int static char *plugin_get_type_str( int type ); static void plugin_cleanup_list(); static int plugin_remove_plugins(struct slapdplugin *plugin_entry, char *plugin_type); +static void plugin_remove_from_shutdown(struct slapdplugin *plugin_entry); static PLHashTable *global_plugin_dns = NULL; @@ -2310,39 +2311,39 @@ plugin_restart(Slapi_Entry *pentryBefore, Slapi_Entry *pentryAfter) /* We can not restart the critical plugins */ if(plugin_is_critical(pentryBefore)){ LDAPDebug(LDAP_DEBUG_PLUGIN, "plugin_restart: Plugin (%s) is critical to server operation. " - "Any changes will not take effect until the server is restarted.\n", - slapi_entry_get_dn(pentryBefore),0,0); + "Any changes will not take effect until the server is restarted.\n", + slapi_entry_get_dn(pentryBefore),0,0); return 1; /* failure - dse code will log a fatal message */ } slapi_rwlock_wrlock(global_rwlock); slapi_td_set_plugin_locked(); - if(plugin_delete(pentryBefore, returntext, 1) == LDAP_SUCCESS){ - if(plugin_add(pentryAfter, returntext, 1) == LDAP_SUCCESS){ - LDAPDebug(LDAP_DEBUG_PLUGIN, "plugin_restart: Plugin (%s) has been successfully " - "restarted after configuration change.\n", - slapi_entry_get_dn(pentryAfter),0,0); - } else { - LDAPDebug(LDAP_DEBUG_ANY, "plugin_restart: Plugin (%s) failed to restart after " - "configuration change (%s). Reverting to original plugin entry.\n", - slapi_entry_get_dn(pentryAfter), returntext, 0); - if(plugin_add(pentryBefore, returntext, 1) == LDAP_SUCCESS){ - LDAPDebug(LDAP_DEBUG_ANY, "plugin_restart: Plugin (%s) failed to reload " - "original plugin (%s)\n",slapi_entry_get_dn(pentryBefore), returntext, 0); - } - rc = 1; - } - } else { - LDAPDebug(LDAP_DEBUG_ANY,"plugin_restart: failed to disable/stop the plugin (%s): %s\n", - slapi_entry_get_dn(pentryBefore), returntext, 0); - rc = 1; - } + if(plugin_delete(pentryBefore, returntext, 1) == LDAP_SUCCESS){ + if(plugin_add(pentryAfter, returntext, 1) == LDAP_SUCCESS){ + LDAPDebug(LDAP_DEBUG_PLUGIN, "plugin_restart: Plugin (%s) has been successfully " + "restarted after configuration change.\n", + slapi_entry_get_dn(pentryAfter),0,0); + } else { + LDAPDebug(LDAP_DEBUG_ANY, "plugin_restart: Plugin (%s) failed to restart after " + "configuration change (%s). Reverting to original plugin entry.\n", + slapi_entry_get_dn(pentryAfter), returntext, 0); + if(plugin_add(pentryBefore, returntext, 1) != LDAP_SUCCESS){ + LDAPDebug(LDAP_DEBUG_ANY, "plugin_restart: Plugin (%s) failed to reload " + "original plugin (%s)\n",slapi_entry_get_dn(pentryBefore), returntext, 0); + } + rc = 1; + } + } else { + LDAPDebug(LDAP_DEBUG_ANY,"plugin_restart: failed to disable/stop the plugin (%s): %s\n", + slapi_entry_get_dn(pentryBefore), returntext, 0); + rc = 1; + } - slapi_rwlock_unlock(global_rwlock); - slapi_td_set_plugin_unlocked(); + slapi_rwlock_unlock(global_rwlock); + slapi_td_set_plugin_unlocked(); - return rc; + return rc; } static int @@ -2946,6 +2947,11 @@ plugin_setup(Slapi_Entry *plugin_entry, struct slapi_componentid *group, PR_snprintf (returntext, SLAPI_DSE_RETURNTEXT_SIZE,"Init function \"%s\" for \"%s\" plugin in " "library \"%s\" failed.",plugin->plg_initfunc, plugin->plg_name, plugin->plg_libpath); status = -1; + /* + * The init function might have added the plugin to the global list before + * it failed - attempt to remove it just in case it was added. + */ + plugin_remove_plugins(plugin, value); slapi_ch_free((void**)&value); goto PLUGIN_CLEANUP; }
0
024e35c8ba85f6c839758c1475e8421450120f1f
389ds/389-ds-base
Issue 5505 - Fix compiler warning (#5506) relates: https://github.com/389ds/389-ds-base/issues/5505 Reviewed by: @Firstyear (Thanks)
commit 024e35c8ba85f6c839758c1475e8421450120f1f Author: James Chapman <[email protected]> Date: Wed Nov 9 09:49:47 2022 +0000 Issue 5505 - Fix compiler warning (#5506) relates: https://github.com/389ds/389-ds-base/issues/5505 Reviewed by: @Firstyear (Thanks) diff --git a/ldap/servers/plugins/retrocl/retrocl_trim.c b/ldap/servers/plugins/retrocl/retrocl_trim.c index 37e5fbea7..d6b24c8bf 100644 --- a/ldap/servers/plugins/retrocl/retrocl_trim.c +++ b/ldap/servers/plugins/retrocl/retrocl_trim.c @@ -23,7 +23,7 @@ typedef struct _trim_status int ts_s_trimming; /* non-zero if trimming in progress */ PRLock *ts_s_trim_mutex; /* protects ts_s_trimming */ } trim_status; -static trim_status ts = {0L, 0L, 0, 0, NULL}; +static trim_status ts = {0}; /* * All standard changeLogEntry attributes (initialized in get_cleattrs)
0
80f3188a3a9789824128f1f6baede66de8c92c37
389ds/389-ds-base
588867 - entryusn plugin fails on solaris https://bugzilla.redhat.com/show_bug.cgi?id=588867 Fix description: _sparcv9_AtomicAdd, _sparcv9_AtomicSub, and _sparcv9_AtomicSet were not correctly declared. It brought in the implicit function declaration, where the return value were casted to 32-bit integer and the comparison against the 64-bit unsigned integer failed. The comparison was in the endless loop and it caused the server hang.
commit 80f3188a3a9789824128f1f6baede66de8c92c37 Author: Noriko Hosoi <[email protected]> Date: Fri May 21 16:34:24 2010 -0700 588867 - entryusn plugin fails on solaris https://bugzilla.redhat.com/show_bug.cgi?id=588867 Fix description: _sparcv9_AtomicAdd, _sparcv9_AtomicSub, and _sparcv9_AtomicSet were not correctly declared. It brought in the implicit function declaration, where the return value were casted to 32-bit integer and the comparison against the 64-bit unsigned integer failed. The comparison was in the endless loop and it caused the server hang. diff --git a/ldap/servers/slapd/slapi_counter.c b/ldap/servers/slapd/slapi_counter.c index 0f56c8ace..c3f1f4492 100644 --- a/ldap/servers/slapd/slapi_counter.c +++ b/ldap/servers/slapd/slapi_counter.c @@ -42,9 +42,9 @@ #include "slap.h" #ifdef SOLARIS -PRUint64 _sparcv9_AtomicSet_il(PRUint64 *address, PRUint64 newval); -PRUint64 _sparcv9_AtomicAdd_il(PRUint64 *address, PRUint64 val); -PRUint64 _sparcv9_AtomicSub_il(PRUint64 *address, PRUint64 val); +PRUint64 _sparcv9_AtomicSet(PRUint64 *address, PRUint64 newval); +PRUint64 _sparcv9_AtomicAdd(PRUint64 *address, PRUint64 val); +PRUint64 _sparcv9_AtomicSub(PRUint64 *address, PRUint64 val); #endif #ifdef HPUX
0
3246fe7930771c4deb82d979245f1810560f5c40
389ds/389-ds-base
Issue 51165 - add new access log keywords for wtime and optime Description: In addition to the "etime" stat in the access we can also add the time the operation spent in the work queue, and how long the actual operation took. We now have "wtime" and "optime" to track these stats in the access log. Also updated logconf for notes=F (related to a different ticket), and stats for wtime and optime. relates: https://pagure.io/389-ds-base/issue/51165 Reviewed by: ?
commit 3246fe7930771c4deb82d979245f1810560f5c40 Author: Mark Reynolds <[email protected]> Date: Tue Jun 23 16:38:55 2020 -0400 Issue 51165 - add new access log keywords for wtime and optime Description: In addition to the "etime" stat in the access we can also add the time the operation spent in the work queue, and how long the actual operation took. We now have "wtime" and "optime" to track these stats in the access log. Also updated logconf for notes=F (related to a different ticket), and stats for wtime and optime. relates: https://pagure.io/389-ds-base/issue/51165 Reviewed by: ? diff --git a/ldap/admin/src/logconv.pl b/ldap/admin/src/logconv.pl index f4808a101..1ed44a888 100755 --- a/ldap/admin/src/logconv.pl +++ b/ldap/admin/src/logconv.pl @@ -3,7 +3,7 @@ # # BEGIN COPYRIGHT BLOCK # Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. -# Copyright (C) 2013 Red Hat, Inc. +# Copyright (C) 2020 Red Hat, Inc. # All rights reserved. # # License: GPL (version 3 or any later version). @@ -55,7 +55,7 @@ my $reportStats = ""; my $dataLocation = "/tmp"; my $startTLSoid = "1.3.6.1.4.1.1466.20037"; my @statnames=qw(last last_str results srch add mod modrdn moddn cmp del abandon - conns sslconns bind anonbind unbind notesA notesU etime); + conns sslconns bind anonbind unbind notesA notesU notesF etime); my $s_stats; my $m_stats; my $verb = "no"; @@ -211,6 +211,7 @@ my $sslClientBindCount = 0; my $sslClientFailedCount = 0; my $objectclassTopCount= 0; my $pagedSearchCount = 0; +my $invalidFilterCount = 0; my $bindCount = 0; my $filterCount = 0; my $baseCount = 0; @@ -258,7 +259,7 @@ map {$conn{$_} = $_} @conncodes; # hash db-backed hashes my @hashnames = qw(attr rc src rsrc excount conn_hash ip_hash conncount nentries filter base ds6xbadpwd saslmech saslconnop bindlist etime oid - start_time_of_connection end_time_of_connection + start_time_of_connection end_time_of_connection notesf_conn_op notesa_conn_op notesu_conn_op etime_conn_op nentries_conn_op optype_conn_op time_conn_op srch_conn_op del_conn_op mod_conn_op mdn_conn_op cmp_conn_op bind_conn_op unbind_conn_op ext_conn_op @@ -926,7 +927,7 @@ if ($verb eq "yes" || $usage =~ /u/ || $usage =~ /U/){ } while($op > 0){ # The bind op is not the same as the search op that triggered the notes=A. - # We have adjust the key by decrementing the op count until we find the last bind op. + # We have to adjust the key by decrementing the op count until we find the last bind op. $op--; $binddn_key = "$srvRstCnt,$conn,$op"; if (exists($bind_conn_op->{$binddn_key}) && defined($bind_conn_op->{$binddn_key})) { @@ -1049,9 +1050,60 @@ if ($verb eq "yes" || $usage =~ /u/ || $usage =~ /U/){ } } } -} # end of unindexed search report + print "\n"; +} + +print "Invalid Attribute Filters: $invalidFilterCount\n"; +if ($invalidFilterCount > 0 && $verb eq "yes"){ + my $conn_hash = $hashes->{conn_hash}; + my $notesf_conn_op = $hashes->{notesf_conn_op}; + my $time_conn_op = $hashes->{time_conn_op}; + my $etime_conn_op = $hashes->{etime_conn_op}; + my $nentries_conn_op = $hashes->{nentries_conn_op}; + my $filter_conn_op = $hashes->{filter_conn_op}; + my $bind_conn_op = $hashes->{bind_conn_op}; + my $notesCount = 1; + my $unindexedIp; + my $binddn_key; + my %uniqFilt = (); # hash of unique filters + my %uniqFilter = (); # hash of unique filters bind dn + my %uniqBindDNs = (); # hash of unique bind dn's + my %uniqBindFilters = (); # hash of filters for a bind DN + + while (my ($srcnt_conn_op, $count) = each %{$notesf_conn_op}) { + my ($srvRstCnt, $conn, $op) = split(",", $srcnt_conn_op); + my $attrIp = getIPfromConn($conn, $srvRstCnt); + print "\n Invalid Attribute Filter #".$notesCount." (notes=F)\n"; + print " - Date/Time: $time_conn_op->{$srcnt_conn_op}\n"; + print " - Connection Number: $conn\n"; + print " - Operation Number: $op\n"; + print " - Etime: $etime_conn_op->{$srcnt_conn_op}\n"; + print " - Nentries: $nentries_conn_op->{$srcnt_conn_op}\n"; + print " - IP Address: $attrIp\n"; + if (exists($filter_conn_op->{$srcnt_conn_op}) && defined($filter_conn_op->{$srcnt_conn_op})) { + print " - Search Filter: $filter_conn_op->{$srcnt_conn_op}\n"; + $uniqFilt{$filter_conn_op->{$srcnt_conn_op}}++; + } + while($op > 0){ + # The bind op is not the same as the search op that triggered the notes=A. + # We have to adjust the key by decrementing the op count until we find the last bind op. + $op--; + $binddn_key = "$srvRstCnt,$conn,$op"; + if (exists($bind_conn_op->{$binddn_key}) && defined($bind_conn_op->{$binddn_key})) { + print " - Bind DN: $bind_conn_op->{$binddn_key}\n"; + $uniqBindDNs{$bind_conn_op->{$binddn_key}}++; + if( $uniqFilt{$filter_conn_op->{$srcnt_conn_op}} && defined($filter_conn_op->{$srcnt_conn_op})) { + $uniqBindFilters{$bind_conn_op->{$binddn_key}}{$filter_conn_op->{$srcnt_conn_op}}++; + $uniqFilter{$filter_conn_op->{$srcnt_conn_op}}{$bind_conn_op->{$binddn_key}}++; + } + last; + } + } + $notesCount++; + } + print "\n"; +} -print "\n"; print "FDs Taken: $fdTaken\n"; print "FDs Returned: $fdReturned\n"; print "Highest FD Taken: $highestFdTaken\n\n"; @@ -1386,20 +1438,20 @@ if ($usage =~ /l/ || $verb eq "yes"){ } } -######################################### -# # -# Gather and Process the unique etimes # -# # -######################################### +############################################################## +# # +# Gather and Process the unique etimes, wtimes, and optimes # +# # +############################################################## my $first; if ($usage =~ /t/i || $verb eq "yes"){ + # Print the elapsed times (etime) + my $etime = $hashes->{etime}; my @ekeys = keys %{$etime}; - # # print most often etimes - # - print "\n\n----- Top $sizeCount Most Frequent etimes -----\n\n"; + print "\n\n----- Top $sizeCount Most Frequent etimes (elapsed times) -----\n\n"; my $eloop = 0; my $retime = 0; foreach my $et (sort { $etime->{$b} <=> $etime->{$a} } @ekeys) { @@ -1411,16 +1463,84 @@ if ($usage =~ /t/i || $verb eq "yes"){ printf "%-8s %-12s\n", $etime->{ $et }, "etime=$et"; $eloop++; } - # + if ($eloop == 0) { + print "None"; + } # print longest etimes - # - print "\n\n----- Top $sizeCount Longest etimes -----\n\n"; + print "\n\n----- Top $sizeCount Longest etimes (elapsed times) -----\n\n"; $eloop = 0; foreach my $et (sort { $b <=> $a } @ekeys) { if ($eloop == $sizeCount) { last; } printf "%-12s %-10s\n","etime=$et",$etime->{ $et }; $eloop++; } + if ($eloop == 0) { + print "None"; + } + + # Print the wait times (wtime) + + my $wtime = $hashes->{wtime}; + my @wkeys = keys %{$wtime}; + # print most often wtimes + print "\n\n----- Top $sizeCount Most Frequent wtimes (wait times) -----\n\n"; + $eloop = 0; + $retime = 0; + foreach my $et (sort { $wtime->{$b} <=> $wtime->{$a} } @wkeys) { + if ($eloop == $sizeCount) { last; } + if ($retime ne "2"){ + $first = $et; + $retime = "2"; + } + printf "%-8s %-12s\n", $wtime->{ $et }, "wtime=$et"; + $eloop++; + } + if ($eloop == 0) { + print "None"; + } + # print longest wtimes + print "\n\n----- Top $sizeCount Longest wtimes (wait times) -----\n\n"; + $eloop = 0; + foreach my $et (sort { $b <=> $a } @wkeys) { + if ($eloop == $sizeCount) { last; } + printf "%-12s %-10s\n","wtime=$et",$wtime->{ $et }; + $eloop++; + } + if ($eloop == 0) { + print "None"; + } + + # Print the operation times (optime) + + my $optime = $hashes->{optime}; + my @opkeys = keys %{$optime}; + # print most often optimes + print "\n\n----- Top $sizeCount Most Frequent optimes (actual operation times) -----\n\n"; + $eloop = 0; + $retime = 0; + foreach my $et (sort { $optime->{$b} <=> $optime->{$a} } @opkeys) { + if ($eloop == $sizeCount) { last; } + if ($retime ne "2"){ + $first = $et; + $retime = "2"; + } + printf "%-8s %-12s\n", $optime->{ $et }, "optime=$et"; + $eloop++; + } + if ($eloop == 0) { + print "None"; + } + # print longest optimes + print "\n\n----- Top $sizeCount Longest optimes (actual operation times) -----\n\n"; + $eloop = 0; + foreach my $et (sort { $b <=> $a } @opkeys) { + if ($eloop == $sizeCount) { last; } + printf "%-12s %-10s\n","optime=$et",$optime->{ $et }; + $eloop++; + } + if ($eloop == 0) { + print "None"; + } } ####################################### @@ -2152,6 +2272,26 @@ sub parseLineNormal if (m/ RESULT err=/ && m/ notes=[A-Z,]*P/){ $pagedSearchCount++; } + if (m/ RESULT err=/ && m/ notes=[A-Z,]*F/){ + $invalidFilterCount++; + $con = ""; + if ($_ =~ /conn= *([0-9A-Z]+)/i){ + $con = $1; + if ($_ =~ /op= *([0-9\-]+)/i){ $op = $1;} + } + + if($reportStats){ inc_stats('notesF',$s_stats,$m_stats); } + if ($usage =~ /u/ || $usage =~ /U/ || $verb eq "yes"){ + if($_ =~ /etime= *([0-9.]+)/i ){ + if($1 >= $minEtime){ + $hashes->{etime_conn_op}->{"$serverRestartCount,$con,$op"} = $1; + $hashes->{notesf_conn_op}->{"$serverRestartCount,$con,$op"}++; + if ($_ =~ / *([0-9a-z:\/]+)/i){ $hashes->{time_conn_op}->{"$serverRestartCount,$con,$op"} = $1; } + if ($_ =~ /nentries= *([0-9]+)/i ){ $hashes->{nentries_conn_op}->{"$serverRestartCount,$con,$op"} = $1; } + } + } + } + } if (m/ notes=[A-Z,]*A/){ $con = ""; if ($_ =~ /conn= *([0-9A-Z]+)/i){ @@ -2435,6 +2575,16 @@ sub parseLineNormal if ($usage =~ /t/i || $verb eq "yes"){ $hashes->{etime}->{$etime_val}++; } if ($reportStats){ inc_stats_val('etime',$etime_val,$s_stats,$m_stats); } } + if ($_ =~ /wtime= *([0-9.]+)/ ) { + my $wtime_val = $1; + if ($usage =~ /t/i || $verb eq "yes"){ $hashes->{wtime}->{$wtime_val}++; } + if ($reportStats){ inc_stats_val('wtime',$wtime_val,$s_stats,$m_stats); } + } + if ($_ =~ /optime= *([0-9.]+)/ ) { + my $optime_val = $1; + if ($usage =~ /t/i || $verb eq "yes"){ $hashes->{optime}->{$optime_val}++; } + if ($reportStats){ inc_stats_val('optime',$optime_val,$s_stats,$m_stats); } + } if ($_ =~ / tag=101 / || $_ =~ / tag=111 / || $_ =~ / tag=100 / || $_ =~ / tag=115 /){ if ($_ =~ / nentries= *([0-9]+)/i ){ my $nents = $1; @@ -2555,7 +2705,7 @@ sub parseLineNormal } } } - if (/ RESULT err=/ && / tag=97 nentries=0 etime=/ && $_ =~ /dn=\"(.*)\"/i){ + if (/ RESULT err=/ && / tag=97 nentries=0 / && $_ =~ /dn=\"(.*)\"/i){ # Check if this is a sasl bind, if see we need to add the RESULT's dn as a bind dn my $binddn = $1; my ($conn, $op); @@ -2680,6 +2830,7 @@ print_stats_block $stats->{'unbind'}, $stats->{'notesA'}, $stats->{'notesU'}, + $stats->{'notesF'}, $stats->{'etime'}), "\n" ); } else { diff --git a/ldap/servers/slapd/add.c b/ldap/servers/slapd/add.c index 06ca1ee79..52c64fa3c 100644 --- a/ldap/servers/slapd/add.c +++ b/ldap/servers/slapd/add.c @@ -441,6 +441,9 @@ op_shared_add(Slapi_PBlock *pb) internal_op = operation_is_flag_set(operation, OP_FLAG_INTERNAL); pwpolicy = new_passwdPolicy(pb, slapi_entry_get_dn(e)); + /* Set the time we actually started the operation */ + slapi_operation_set_time_started(operation); + /* target spec is used to decide which plugins are applicable for the operation */ operation_set_target_spec(operation, slapi_entry_get_sdn(e)); diff --git a/ldap/servers/slapd/bind.c b/ldap/servers/slapd/bind.c index 310216e89..55f865077 100644 --- a/ldap/servers/slapd/bind.c +++ b/ldap/servers/slapd/bind.c @@ -87,6 +87,10 @@ do_bind(Slapi_PBlock *pb) send_ldap_result(pb, LDAP_OPERATIONS_ERROR, NULL, NULL, 0, NULL); goto free_and_return; } + + /* Set the time we actually started the operation */ + slapi_operation_set_time_started(pb_op); + ber = pb_op->o_ber; /* diff --git a/ldap/servers/slapd/delete.c b/ldap/servers/slapd/delete.c index c0e61adf1..1a7209317 100644 --- a/ldap/servers/slapd/delete.c +++ b/ldap/servers/slapd/delete.c @@ -236,6 +236,9 @@ op_shared_delete(Slapi_PBlock *pb) slapi_pblock_get(pb, SLAPI_OPERATION, &operation); internal_op = operation_is_flag_set(operation, OP_FLAG_INTERNAL); + /* Set the time we actually started the operation */ + slapi_operation_set_time_started(operation); + sdn = slapi_sdn_new_dn_byval(rawdn); dn = slapi_sdn_get_dn(sdn); slapi_pblock_set(pb, SLAPI_DELETE_TARGET_SDN, (void *)sdn); diff --git a/ldap/servers/slapd/modify.c b/ldap/servers/slapd/modify.c index 259bedfff..a186dbde3 100644 --- a/ldap/servers/slapd/modify.c +++ b/ldap/servers/slapd/modify.c @@ -626,6 +626,9 @@ op_shared_modify(Slapi_PBlock *pb, int pw_change, char *old_pw) slapi_pblock_get(pb, SLAPI_SKIP_MODIFIED_ATTRS, &skip_modified_attrs); slapi_pblock_get(pb, SLAPI_CONNECTION, &pb_conn); + /* Set the time we actually started the operation */ + slapi_operation_set_time_started(operation); + if (sdn) { passin_sdn = 1; } else { diff --git a/ldap/servers/slapd/modrdn.c b/ldap/servers/slapd/modrdn.c index 3efe584a7..e04916b83 100644 --- a/ldap/servers/slapd/modrdn.c +++ b/ldap/servers/slapd/modrdn.c @@ -417,6 +417,9 @@ op_shared_rename(Slapi_PBlock *pb, int passin_args) internal_op = operation_is_flag_set(operation, OP_FLAG_INTERNAL); slapi_pblock_get(pb, SLAPI_CONNECTION, &pb_conn); + /* Set the time we actually started the operation */ + slapi_operation_set_time_started(operation); + /* * If ownership has not been passed to this function, we replace the * string input fields within the pblock with strdup'd copies. Why? diff --git a/ldap/servers/slapd/operation.c b/ldap/servers/slapd/operation.c index ff16cd906..4dd3481c7 100644 --- a/ldap/servers/slapd/operation.c +++ b/ldap/servers/slapd/operation.c @@ -651,3 +651,27 @@ slapi_operation_time_expiry(Slapi_Operation *o, time_t timeout, struct timespec { slapi_timespec_expire_rel(timeout, &(o->o_hr_time_rel), expiry); } + +/* Set the time the operation actually started */ +void +slapi_operation_set_time_started(Slapi_Operation *o) +{ + clock_gettime(CLOCK_MONOTONIC, &(o->o_hr_time_started_rel)); +} + +/* The time diff of how long the operation took once it actually started */ +void +slapi_operation_op_time_elapsed(Slapi_Operation *o, struct timespec *elapsed) +{ + struct timespec o_hr_time_now; + clock_gettime(CLOCK_MONOTONIC, &o_hr_time_now); + + slapi_timespec_diff(&o_hr_time_now, &(o->o_hr_time_started_rel), elapsed); +} + +/* The time diff the operation waited in the work queue */ +void +slapi_operation_workq_time_elapsed(Slapi_Operation *o, struct timespec *elapsed) +{ + slapi_timespec_diff(&(o->o_hr_time_started_rel), &(o->o_hr_time_rel), elapsed); +} diff --git a/ldap/servers/slapd/opshared.c b/ldap/servers/slapd/opshared.c index 9fe78655c..c0bc5dcd0 100644 --- a/ldap/servers/slapd/opshared.c +++ b/ldap/servers/slapd/opshared.c @@ -284,6 +284,9 @@ op_shared_search(Slapi_PBlock *pb, int send_result) slapi_pblock_get(pb, SLAPI_SEARCH_TARGET_SDN, &sdn); slapi_pblock_get(pb, SLAPI_OPERATION, &operation); + /* Set the time we actually started the operation */ + slapi_operation_set_time_started(operation); + if (NULL == sdn) { sdn = slapi_sdn_new_dn_byval(base); slapi_pblock_set(pb, SLAPI_SEARCH_TARGET_SDN, sdn); diff --git a/ldap/servers/slapd/result.c b/ldap/servers/slapd/result.c index 0b13c30e9..61efb6f8d 100644 --- a/ldap/servers/slapd/result.c +++ b/ldap/servers/slapd/result.c @@ -1975,6 +1975,8 @@ log_result(Slapi_PBlock *pb, Operation *op, int err, ber_tag_t tag, int nentries CSN *operationcsn = NULL; char csn_str[CSN_STRSIZE + 5]; char etime[ETIME_BUFSIZ] = {0}; + char wtime[ETIME_BUFSIZ] = {0}; + char optime[ETIME_BUFSIZ] = {0}; int pr_idx = -1; int pr_cookie = -1; uint32_t operation_notes; @@ -1982,19 +1984,26 @@ log_result(Slapi_PBlock *pb, Operation *op, int err, ber_tag_t tag, int nentries int32_t op_id; int32_t op_internal_id; int32_t op_nested_count; + struct timespec o_hr_time_end; get_internal_conn_op(&connid, &op_id, &op_internal_id, &op_nested_count); - slapi_pblock_get(pb, SLAPI_PAGED_RESULTS_INDEX, &pr_idx); slapi_pblock_get(pb, SLAPI_PAGED_RESULTS_COOKIE, &pr_cookie); - internal_op = operation_is_flag_set(op, OP_FLAG_INTERNAL); - struct timespec o_hr_time_end; + /* total elapsed time */ slapi_operation_time_elapsed(op, &o_hr_time_end); + snprintf(etime, ETIME_BUFSIZ, "%" PRId64 ".%.09" PRId64 "", (int64_t)o_hr_time_end.tv_sec, (int64_t)o_hr_time_end.tv_nsec); + + /* wait time */ + slapi_operation_workq_time_elapsed(op, &o_hr_time_end); + snprintf(wtime, ETIME_BUFSIZ, "%" PRId64 ".%.09" PRId64 "", (int64_t)o_hr_time_end.tv_sec, (int64_t)o_hr_time_end.tv_nsec); + + /* op time */ + slapi_operation_op_time_elapsed(op, &o_hr_time_end); + snprintf(optime, ETIME_BUFSIZ, "%" PRId64 ".%.09" PRId64 "", (int64_t)o_hr_time_end.tv_sec, (int64_t)o_hr_time_end.tv_nsec); - snprintf(etime, ETIME_BUFSIZ, "%" PRId64 ".%.09" PRId64 "", (int64_t)o_hr_time_end.tv_sec, (int64_t)o_hr_time_end.tv_nsec); operation_notes = slapi_pblock_get_operation_notes(pb); @@ -2025,16 +2034,16 @@ log_result(Slapi_PBlock *pb, Operation *op, int err, ber_tag_t tag, int nentries if (!internal_op) { slapi_log_access(LDAP_DEBUG_STATS, "conn=%" PRIu64 " op=%d RESULT err=%d" - " tag=%" BERTAG_T " nentries=%d etime=%s%s%s" + " tag=%" BERTAG_T " nentries=%d wtime=%s optime=%s etime=%s%s%s" ", SASL bind in progress\n", op->o_connid, op->o_opid, err, tag, nentries, - etime, + wtime, optime, etime, notes_str, csn_str); } else { -#define LOG_SASLMSG_FMT " tag=%" BERTAG_T " nentries=%d etime=%s%s%s, SASL bind in progress\n" +#define LOG_SASLMSG_FMT " tag=%" BERTAG_T " nentries=%d wtime=%s optime=%s etime=%s%s%s, SASL bind in progress\n" slapi_log_access(LDAP_DEBUG_ARGS, connid == 0 ? LOG_CONN_OP_FMT_INT_INT LOG_SASLMSG_FMT : LOG_CONN_OP_FMT_EXT_INT LOG_SASLMSG_FMT, @@ -2043,7 +2052,7 @@ log_result(Slapi_PBlock *pb, Operation *op, int err, ber_tag_t tag, int nentries op_internal_id, op_nested_count, err, tag, nentries, - etime, + wtime, optime, etime, notes_str, csn_str); } } else if (op->o_tag == LDAP_REQ_BIND && err == LDAP_SUCCESS) { @@ -2057,15 +2066,15 @@ log_result(Slapi_PBlock *pb, Operation *op, int err, ber_tag_t tag, int nentries if (!internal_op) { slapi_log_access(LDAP_DEBUG_STATS, "conn=%" PRIu64 " op=%d RESULT err=%d" - " tag=%" BERTAG_T " nentries=%d etime=%s%s%s" + " tag=%" BERTAG_T " nentries=%d wtime=%s optime=%s etime=%s%s%s" " dn=\"%s\"\n", op->o_connid, op->o_opid, err, tag, nentries, - etime, + wtime, optime, etime, notes_str, csn_str, dn ? dn : ""); } else { -#define LOG_BINDMSG_FMT " tag=%" BERTAG_T " nentries=%d etime=%s%s%s dn=\"%s\"\n" +#define LOG_BINDMSG_FMT " tag=%" BERTAG_T " nentries=%d wtime=%s optime=%s etime=%s%s%s dn=\"%s\"\n" slapi_log_access(LDAP_DEBUG_ARGS, connid == 0 ? LOG_CONN_OP_FMT_INT_INT LOG_BINDMSG_FMT : LOG_CONN_OP_FMT_EXT_INT LOG_BINDMSG_FMT, @@ -2074,7 +2083,7 @@ log_result(Slapi_PBlock *pb, Operation *op, int err, ber_tag_t tag, int nentries op_internal_id, op_nested_count, err, tag, nentries, - etime, + wtime, optime, etime, notes_str, csn_str, dn ? dn : ""); } slapi_ch_free((void **)&dn); @@ -2083,15 +2092,15 @@ log_result(Slapi_PBlock *pb, Operation *op, int err, ber_tag_t tag, int nentries if (!internal_op) { slapi_log_access(LDAP_DEBUG_STATS, "conn=%" PRIu64 " op=%d RESULT err=%d" - " tag=%" BERTAG_T " nentries=%d etime=%s%s%s" + " tag=%" BERTAG_T " nentries=%d wtime=%s optime=%s etime=%s%s%s" " pr_idx=%d pr_cookie=%d\n", op->o_connid, op->o_opid, err, tag, nentries, - etime, + wtime, optime, etime, notes_str, csn_str, pr_idx, pr_cookie); } else { -#define LOG_PRMSG_FMT " tag=%" BERTAG_T " nentries=%d etime=%s%s%s pr_idx=%d pr_cookie=%d \n" +#define LOG_PRMSG_FMT " tag=%" BERTAG_T " nentries=%d wtime=%s optime=%s etime=%s%s%s pr_idx=%d pr_cookie=%d \n" slapi_log_access(LDAP_DEBUG_ARGS, connid == 0 ? LOG_CONN_OP_FMT_INT_INT LOG_PRMSG_FMT : LOG_CONN_OP_FMT_EXT_INT LOG_PRMSG_FMT, @@ -2100,7 +2109,7 @@ log_result(Slapi_PBlock *pb, Operation *op, int err, ber_tag_t tag, int nentries op_internal_id, op_nested_count, err, tag, nentries, - etime, + wtime, optime, etime, notes_str, csn_str, pr_idx, pr_cookie); } } else if (!internal_op) { @@ -2114,11 +2123,11 @@ log_result(Slapi_PBlock *pb, Operation *op, int err, ber_tag_t tag, int nentries } slapi_log_access(LDAP_DEBUG_STATS, "conn=%" PRIu64 " op=%d RESULT err=%d" - " tag=%" BERTAG_T " nentries=%d etime=%s%s%s%s\n", + " tag=%" BERTAG_T " nentries=%d wtime=%s optime=%s etime=%s%s%s%s\n", op->o_connid, op->o_opid, err, tag, nentries, - etime, + wtime, optime, etime, notes_str, csn_str, ext_str); if (pbtxt) { /* if !pbtxt ==> ext_str == "". Don't free ext_str. */ @@ -2126,7 +2135,7 @@ log_result(Slapi_PBlock *pb, Operation *op, int err, ber_tag_t tag, int nentries } } else { int optype; -#define LOG_MSG_FMT " tag=%" BERTAG_T " nentries=%d etime=%s%s%s\n" +#define LOG_MSG_FMT " tag=%" BERTAG_T " nentries=%d wtime=%s optime=%s etime=%s%s%s\n" slapi_log_access(LDAP_DEBUG_ARGS, connid == 0 ? LOG_CONN_OP_FMT_INT_INT LOG_MSG_FMT : LOG_CONN_OP_FMT_EXT_INT LOG_MSG_FMT, @@ -2135,7 +2144,7 @@ log_result(Slapi_PBlock *pb, Operation *op, int err, ber_tag_t tag, int nentries op_internal_id, op_nested_count, err, tag, nentries, - etime, + wtime, optime, etime, notes_str, csn_str); /* * If this is an unindexed search we should log it in the error log if diff --git a/ldap/servers/slapd/slap.h b/ldap/servers/slapd/slap.h index 7e0fa61c8..894efd29c 100644 --- a/ldap/servers/slapd/slap.h +++ b/ldap/servers/slapd/slap.h @@ -1541,16 +1541,17 @@ typedef struct slapi_operation_results */ typedef struct op { - BerElement *o_ber; /* ber of the request */ - ber_int_t o_msgid; /* msgid of the request */ - ber_tag_t o_tag; /* tag of the request */ + BerElement *o_ber; /* ber of the request */ + ber_int_t o_msgid; /* msgid of the request */ + ber_tag_t o_tag; /* tag of the request */ struct timespec o_hr_time_rel; /* internal system time op initiated */ struct timespec o_hr_time_utc; /* utc system time op initiated */ - int o_isroot; /* requestor is manager */ + struct timespec o_hr_time_started_rel; /* internal system time op started */ + int o_isroot; /* requestor is manager */ Slapi_DN o_sdn; /* dn bound when op was initiated */ - char *o_authtype; /* auth method used to bind dn */ + char *o_authtype; /* auth method used to bind dn */ int o_ssf; /* ssf for this operation (highest between SASL and TLS/SSL) */ - int o_opid; /* id of this operation */ + int o_opid; /* id of this operation */ PRUint64 o_connid; /* id of conn initiating this op; for logging only */ void *o_handler_data; result_handler o_result_handler; diff --git a/ldap/servers/slapd/slapi-plugin.h b/ldap/servers/slapd/slapi-plugin.h index d6a42af31..be6c98b29 100644 --- a/ldap/servers/slapd/slapi-plugin.h +++ b/ldap/servers/slapd/slapi-plugin.h @@ -8218,13 +8218,29 @@ void slapi_operation_time_elapsed(Slapi_Operation *o, struct timespec *elapsed); */ void slapi_operation_time_initiated(Slapi_Operation *o, struct timespec *initiated); /** - * Given an operation and a timeout, return a populate struct with the expiry - * time of the operation suitable for checking with slapi_timespec_expire_check + * Given an operation, determine the time elapsed since the op + * was actually started. * - * \param Slapi_Operation o - the operation that is in progress - * \param time_t timeout the seconds relative to operation initiation to expiry at. - * \param struct timespec *expiry the timespec to popluate with the relative expiry. + * \param Slapi_Operation o - the operation which is inprogress + * \param struct timespec *elapsed - location where the time difference will be + * placed. + */ +void slapi_operation_op_time_elapsed(Slapi_Operation *o, struct timespec *elapsed); +/** + * Given an operation, determine the time elapsed that the op spent + * in the work queue before actually being dispatched to a worker thread + * + * \param Slapi_Operation o - the operation which is inprogress + * \param struct timespec *elapsed - location where the time difference will be + * placed. + */ +void slapi_operation_workq_time_elapsed(Slapi_Operation *o, struct timespec *elapsed); +/** + * Set the time the operation actually started + * + * \param Slapi_Operation o - the operation which is inprogress */ +void slapi_operation_set_time_started(Slapi_Operation *o); #endif /**
0
cb9a341ae3189d8473bd7548cc159d1a3c4e56aa
389ds/389-ds-base
190724 - Evaluate ACIs before checking password syntax
commit cb9a341ae3189d8473bd7548cc159d1a3c4e56aa Author: Nathan Kinder <[email protected]> Date: Fri May 5 16:12:30 2006 +0000 190724 - Evaluate ACIs before checking password syntax diff --git a/ldap/servers/slapd/add.c b/ldap/servers/slapd/add.c index d8bfe3280..6a38c4c11 100644 --- a/ldap/servers/slapd/add.c +++ b/ldap/servers/slapd/add.c @@ -476,7 +476,20 @@ static void op_shared_add (Slapi_PBlock *pb) { Slapi_Value **present_values; present_values= attr_get_present_values(attr); - + + /* Set the backend in the pblock. The slapi_access_allowed function + * needs this set to work properly. */ + slapi_pblock_set( pb, SLAPI_BACKEND, slapi_be_select( slapi_entry_get_sdn_const(e) ) ); + + /* Check ACI before checking password syntax */ + if ( (err = slapi_access_allowed(pb, e, SLAPI_USERPWD_ATTR, NULL, + SLAPI_ACL_WRITE)) != LDAP_SUCCESS) { + send_ldap_result(pb, err, NULL, + "Insufficient 'write' privilege to the " + "'userPassword' attribute", 0, NULL); + goto done; + } + /* check password syntax */ if (check_pw_syntax(pb, slapi_entry_get_sdn_const(e), present_values, NULL, e, 0) == 0) { diff --git a/ldap/servers/slapd/modify.c b/ldap/servers/slapd/modify.c index 9f5722362..828eb191a 100644 --- a/ldap/servers/slapd/modify.c +++ b/ldap/servers/slapd/modify.c @@ -873,8 +873,11 @@ static void remove_mod (Slapi_Mods *smods, const char *type, Slapi_Mods *smod_un static int op_shared_allow_pw_change (Slapi_PBlock *pb, LDAPMod *mod, char **old_pw, Slapi_Mods *smods) { int isroot, internal_op, repl_op, pwresponse_req = 0; + int res = 0; char *dn; + char *errtxt = NULL; Slapi_DN sdn; + Slapi_Entry *e = NULL; passwdPolicy *pwpolicy; int rc = 0; char ebuf[BUFSIZ]; @@ -902,7 +905,35 @@ static int op_shared_allow_pw_change (Slapi_PBlock *pb, LDAPMod *mod, char **old /* internal operation has root permisions for subtrees it is allowed to access */ if (!internal_op) { - /* Check first if password policy allows users to change their passwords.*/ + /* slapi_acl_check_mods needs an array of LDAPMods, but + * we're really only interested in the one password mod. */ + LDAPMod *mods[2] = { mod, NULL }; + + /* Create a bogus entry with just the target dn. This will + * only be used for checking the ACIs. */ + e = slapi_entry_alloc(); + slapi_entry_init( e, NULL, NULL ); + slapi_sdn_set_dn_byref(slapi_entry_get_sdn(e), dn); + + /* Set the backend in the pblock. The slapi_access_allowed function + * needs this set to work properly. */ + slapi_pblock_set( pb, SLAPI_BACKEND, slapi_be_select( &sdn ) ); + + /* Check if ACIs allow password to be changed */ + if ( (res = slapi_acl_check_mods(pb, e, mods, &errtxt)) != LDAP_SUCCESS) { + /* Write access is denied to userPassword by ACIs */ + if ( pwresponse_req == 1 ) { + slapi_pwpolicy_make_response_control ( pb, -1, -1, + LDAP_PWPOLICY_PWDMODNOTALLOWED ); + } + + send_ldap_result(pb, res, NULL, errtxt, 0, NULL); + slapi_ch_free_string(&errtxt); + rc = -1; + goto done; + } + + /* Check if password policy allows users to change their passwords.*/ if (!pb->pb_op->o_isroot && slapi_sdn_compare(&sdn, &pb->pb_op->o_sdn)==0 && !pb->pb_conn->c_needpw && !pwpolicy->pw_change) { @@ -995,6 +1026,7 @@ static int op_shared_allow_pw_change (Slapi_PBlock *pb, LDAPMod *mod, char **old valuearray_free(&values); done: + slapi_entry_free( e ); slapi_sdn_done (&sdn); delete_passwdPolicy(&pwpolicy); return rc;
0
0f443bf33745a2caa8aedffc2661dba50ced0dac
389ds/389-ds-base
Bump version to 2.0.7
commit 0f443bf33745a2caa8aedffc2661dba50ced0dac Author: Mark Reynolds <[email protected]> Date: Thu Jul 15 13:50:02 2021 -0400 Bump version to 2.0.7 diff --git a/VERSION.sh b/VERSION.sh index 28aec3d8a..89a967f21 100644 --- a/VERSION.sh +++ b/VERSION.sh @@ -10,7 +10,7 @@ vendor="389 Project" # PACKAGE_VERSION is constructed from these VERSION_MAJOR=2 VERSION_MINOR=0 -VERSION_MAINT=6 +VERSION_MAINT=7 # NOTE: VERSION_PREREL is automatically set for builds made out of a git tree VERSION_PREREL= VERSION_DATE=$(date -u +%Y%m%d)
0
ae5c362f688f0c3a758a08bbd07ce55deddf8ced
389ds/389-ds-base
Resolves: bug 486400 Bug Description: During migration, if import fails for some reason, the exact cause of why it was unable to open the LDIF is not logged. Reviewed by: nhosoi (thanks!) Files: see diff Branch: HEAD Fix Description: As discussed in the bug council, the fix is to just report the actual error returned when the open() of the LDIF fails. This reports the errno and a string description of the error in the errors log (which is also output to stderr when running ldif2db). Platforms tested: F9 Flag Day: no Doc impact: no
commit ae5c362f688f0c3a758a08bbd07ce55deddf8ced Author: Nathan Kinder <[email protected]> Date: Tue Mar 3 17:35:59 2009 +0000 Resolves: bug 486400 Bug Description: During migration, if import fails for some reason, the exact cause of why it was unable to open the LDIF is not logged. Reviewed by: nhosoi (thanks!) Files: see diff Branch: HEAD Fix Description: As discussed in the bug council, the fix is to just report the actual error returned when the open() of the LDIF fails. This reports the errno and a string description of the error in the errors log (which is also output to stderr when running ldif2db). Platforms tested: F9 Flag Day: no Doc impact: no diff --git a/ldap/servers/slapd/back-ldbm/import-threads.c b/ldap/servers/slapd/back-ldbm/import-threads.c index c912023c7..7a1bcba1c 100644 --- a/ldap/servers/slapd/back-ldbm/import-threads.c +++ b/ldap/servers/slapd/back-ldbm/import-threads.c @@ -461,8 +461,8 @@ void import_producer(void *param) fd = dblayer_open_huge_file(curr_filename, o_flag, 0); } if (fd < 0) { - import_log_notice(job, "Could not open LDIF file \"%s\"", - curr_filename); + import_log_notice(job, "Could not open LDIF file \"%s\", errno %d (%s)", + curr_filename, errno, slapd_system_strerror(errno)); goto error; } if (fd == STDIN_FILENO) {
0
288953655c3af087c82007d630cf8fb6558e9a9e
389ds/389-ds-base
Bug 584109 - Slapd crashes while parsing DNA configuration https://bugzilla.redhat.com/show_bug.cgi?id=584109 Resolves: bug 584109 Bug Description: Slapd crashes while parsing DNA configuration Fix Description: The dna_parse_config_entry() has been modified to duplicate the shared_cfg_base value to avoid freeing the same memory location twice. Reviewed by: rmeggins (and pushed by)
commit 288953655c3af087c82007d630cf8fb6558e9a9e Author: Endi S. Dewata <[email protected]> Date: Sun Apr 18 04:29:41 2010 -0500 Bug 584109 - Slapd crashes while parsing DNA configuration https://bugzilla.redhat.com/show_bug.cgi?id=584109 Resolves: bug 584109 Bug Description: Slapd crashes while parsing DNA configuration Fix Description: The dna_parse_config_entry() has been modified to duplicate the shared_cfg_base value to avoid freeing the same memory location twice. Reviewed by: rmeggins (and pushed by) diff --git a/ldap/servers/plugins/dna/dna.c b/ldap/servers/plugins/dna/dna.c index 0da8f07c9..b8922d9d0 100644 --- a/ldap/servers/plugins/dna/dna.c +++ b/ldap/servers/plugins/dna/dna.c @@ -840,7 +840,8 @@ dna_parse_config_entry(Slapi_Entry * e, int apply) shared_e = NULL; } - entry->shared_cfg_base = slapi_dn_normalize(value); + entry->shared_cfg_base = slapi_ch_strdup(value); + slapi_dn_normalize(entry->shared_cfg_base); /* We prepend the host & port of this instance as a * multi-part RDN for the shared config entry. */
0
5bfc18a245405229bd7bd2acfee681e68df338d6
389ds/389-ds-base
Ticket 49644 - crash in debug build Description: In a debug build of the server it crashes when searching the cn=config. This is due to a pointer not being initialized before being dereferenced. https://pagure.io/389-ds-base/issue/49644 Reviewed by: mreynolds(one line commit rule)
commit 5bfc18a245405229bd7bd2acfee681e68df338d6 Author: Mark Reynolds <[email protected]> Date: Fri Apr 20 11:05:25 2018 -0400 Ticket 49644 - crash in debug build Description: In a debug build of the server it crashes when searching the cn=config. This is due to a pointer not being initialized before being dereferenced. https://pagure.io/389-ds-base/issue/49644 Reviewed by: mreynolds(one line commit rule) diff --git a/ldap/servers/slapd/back-ldbm/monitor.c b/ldap/servers/slapd/back-ldbm/monitor.c index 06f2b27c5..91abeea90 100644 --- a/ldap/servers/slapd/back-ldbm/monitor.c +++ b/ldap/servers/slapd/back-ldbm/monitor.c @@ -126,7 +126,7 @@ ldbm_back_monitor_instance_search(Slapi_PBlock *pb __attribute__((unused)), #ifdef DEBUG { /* debugging for hash statistics */ - char *x; + char *x = NULL; cache_debug_hash(&(inst->inst_cache), &x); val.bv_val = x; val.bv_len = strlen(x);
0