commit_id
string
repo
string
commit_message
string
diff
string
label
int64
cbc0d49f5f3201f56a39eac919570c7a528f5305
389ds/389-ds-base
Bug 610119 - fix coverify Defect Type: Null pointer dereferences issues 12167 - 12199 https://bugzilla.redhat.com/show_bug.cgi?id=610119 Resolves: bug 610119 Bug description: Fix coverify Defect Type: Null pointer dereferences issues 12167 - 12199 Fix description: Catch possible NULL pointer in vlv_init().
commit cbc0d49f5f3201f56a39eac919570c7a528f5305 Author: Endi S. Dewata <[email protected]> Date: Fri Jul 2 00:00:40 2010 -0500 Bug 610119 - fix coverify Defect Type: Null pointer dereferences issues 12167 - 12199 https://bugzilla.redhat.com/show_bug.cgi?id=610119 Resolves: bug 610119 Bug description: Fix coverify Defect Type: Null pointer dereferences issues 12167 - 12199 Fix description: Catch possible NULL pointer in vlv_init(). diff --git a/ldap/servers/slapd/back-ldbm/vlv.c b/ldap/servers/slapd/back-ldbm/vlv.c index 9d749d6ec..0d282400f 100644 --- a/ldap/servers/slapd/back-ldbm/vlv.c +++ b/ldap/servers/slapd/back-ldbm/vlv.c @@ -345,7 +345,15 @@ vlv_init(ldbm_instance *inst) char *basedn = NULL; const char *searchfilter = "(objectclass=vlvsearch)"; const char *indexfilter = "(objectclass=vlvindex)"; - backend *be= inst->inst_be; + backend *be = NULL; + + if (!inst) { + LDAPDebug(LDAP_DEBUG_ANY, "vlv_init: invalid instance.\n", 0, 0, 0); + return_value = LDAP_OPERATIONS_ERROR; + goto out; + } + + be = inst->inst_be; /* Initialize lock first time through */ if(be->vlvSearchList_lock == NULL) { @@ -368,9 +376,8 @@ vlv_init(ldbm_instance *inst) be->vlvSearchList = NULL; PR_RWLock_Unlock(be->vlvSearchList_lock); } - if (inst == NULL) { - basedn = NULL; - } else { + + { basedn = slapi_create_dn_string("cn=%s,cn=%s,cn=plugins,cn=config", inst->inst_name, inst->inst_li->li_plugin->plg_name); if (NULL == basedn) { @@ -417,6 +424,7 @@ vlv_init(ldbm_instance *inst) slapi_ch_free_string(&basedn); } +out: return return_value; }
0
bce5557406be22ec69eb38e7fd3230efe6143283
389ds/389-ds-base
Ticket 47340 - Deleting a separator ',' in 7-bit check plugin arguments makes the server fail to start with segfault Bug Description: If invalid or missing plugin arguments are present in the config entry, the server will crash at startup. This is because we were not fully validating all argument values. Fix Description: Generate an appropriate error at startup when invalid settings are detected, and gracefully exit. https://fedorahosted.org/389/ticket/47340 Reviewed by: Noriko(Thanks!!)
commit bce5557406be22ec69eb38e7fd3230efe6143283 Author: Mark Reynolds <[email protected]> Date: Mon May 20 15:09:00 2013 -0400 Ticket 47340 - Deleting a separator ',' in 7-bit check plugin arguments makes the server fail to start with segfault Bug Description: If invalid or missing plugin arguments are present in the config entry, the server will crash at startup. This is because we were not fully validating all argument values. Fix Description: Generate an appropriate error at startup when invalid settings are detected, and gracefully exit. https://fedorahosted.org/389/ticket/47340 Reviewed by: Noriko(Thanks!!) diff --git a/ldap/servers/plugins/uiduniq/7bit.c b/ldap/servers/plugins/uiduniq/7bit.c index fbcc53094..ca9792b22 100644 --- a/ldap/servers/plugins/uiduniq/7bit.c +++ b/ldap/servers/plugins/uiduniq/7bit.c @@ -699,6 +699,7 @@ NS7bitAttr_Init(Slapi_PBlock *pb) int premdn = SLAPI_PLUGIN_PRE_MODRDN_FN; BEGIN + int attr_count = 0; int argc; char **argv; @@ -731,12 +732,12 @@ NS7bitAttr_Init(Slapi_PBlock *pb) * Arguments before "," are the 7-bit attribute names. Arguments after * "," are the subtree DN's. */ - if (argc < 1) { err = -1; break; } - for(;strcmp(*argv, ",") != 0 && argc > 0; argc--, argv++) - {}; - if (argc == 0) { err = -1; break; } + if (argc < 1) { err = -2; break; } /* missing arguments */ + for(;*argv && strcmp(*argv, ",") != 0 && argc > 0; attr_count++, argc--, argv++); + if (argc == 0) { err = -3; break; } /* no comma separator */ + if(attr_count == 0){ err = -4; break; } /* no attributes */ argv++; argc--; - + if(argc == 0){ err = -5; break; } /* no suffix */ for(;argc > 0;argc--, argv++) { char *normdn = slapi_create_dn_string_case("%s", *argv); slapi_ch_free_string(argv); @@ -761,9 +762,22 @@ NS7bitAttr_Init(Slapi_PBlock *pb) END if (err) { - slapi_log_error(SLAPI_LOG_PLUGIN, "NS7bitAttr_Init", - "Error: %d\n", err); - err = -1; + if(err == -1){ + slapi_log_error(SLAPI_LOG_PLUGIN, "NS7bitAttr_Init","Error: %d\n", err); + } else if(err == -2){ + slapi_log_error(SLAPI_LOG_FATAL, "NS7bitAttr_Init", + "Invalid plugin arguments - missing arguments\n"); + } else if(err == -3){ + slapi_log_error(SLAPI_LOG_FATAL, "NS7bitAttr_Init", + "Invalid plugin arguments - missing \",\" separator argument\n"); + } else if(err == -4){ + slapi_log_error(SLAPI_LOG_FATAL, "NS7bitAttr_Init", + "Invalid plugin arguments - missing attributes\n"); + } else if(err == -5){ + slapi_log_error(SLAPI_LOG_FATAL, "NS7bitAttr_Init", + "Invalid plugin arguments - missing suffix\n"); + } + err = -1; } else slapi_log_error(SLAPI_LOG_PLUGIN, "NS7bitAttr_Init",
0
b646e4dafe63ea7a4bb471b1fbb06a031c9499a2
389ds/389-ds-base
Pass argument into hashtable_new @8915d8d87 and @4471b7350 modified "usetxn" parameter in "hashtable_new" scope (was a global variable before). But the callers of this function don't pass argument into. Thus, "usetxn" acts as an uninitialized auto variable. Fixes: https://pagure.io/389-ds-base/issue/50057
commit b646e4dafe63ea7a4bb471b1fbb06a031c9499a2 Author: Stanislav Levin <[email protected]> Date: Wed Nov 28 12:49:07 2018 +0300 Pass argument into hashtable_new @8915d8d87 and @4471b7350 modified "usetxn" parameter in "hashtable_new" scope (was a global variable before). But the callers of this function don't pass argument into. Thus, "usetxn" acts as an uninitialized auto variable. Fixes: https://pagure.io/389-ds-base/issue/50057 diff --git a/ldap/servers/plugins/memberof/memberof.h b/ldap/servers/plugins/memberof/memberof.h index cf028453c..f049d384b 100644 --- a/ldap/servers/plugins/memberof/memberof.h +++ b/ldap/servers/plugins/memberof/memberof.h @@ -102,7 +102,7 @@ void *memberof_get_plugin_id(void); void memberof_release_config(void); PRUint64 get_plugin_started(void); void ancestor_hashtable_entry_free(memberof_cached_value *entry); -PLHashTable *hashtable_new(); +PLHashTable *hashtable_new(int usetxn); int memberof_use_txn(); #endif /* _MEMBEROF_H_ */ diff --git a/ldap/servers/plugins/memberof/memberof_config.c b/ldap/servers/plugins/memberof/memberof_config.c index f08139183..89fd012e7 100644 --- a/ldap/servers/plugins/memberof/memberof_config.c +++ b/ldap/servers/plugins/memberof/memberof_config.c @@ -698,8 +698,8 @@ memberof_copy_config(MemberOfConfig *dest, MemberOfConfig *src) /* Allocate our caches here since we only copy the config at the start of an op */ if (memberof_use_txn() == 1){ - dest->ancestors_cache = hashtable_new(); - dest->fixup_cache = hashtable_new(); + dest->ancestors_cache = hashtable_new(1); + dest->fixup_cache = hashtable_new(1); } /* Check if the copy is already up to date */
0
c2c512e4faf4f86d05d94aa2117a1a4910f81dfd
389ds/389-ds-base
Ticket 49269 - Fix coverity errors Desciption: Fix coverity and clanf errors/warnings. Also fix a compiler warning https://pagure.io/389-ds-base/issue/49269 Reviewed by: firstyear(Thanks!)
commit c2c512e4faf4f86d05d94aa2117a1a4910f81dfd Author: Mark Reynolds <[email protected]> Date: Wed May 24 10:56:22 2017 -0400 Ticket 49269 - Fix coverity errors Desciption: Fix coverity and clanf errors/warnings. Also fix a compiler warning https://pagure.io/389-ds-base/issue/49269 Reviewed by: firstyear(Thanks!) diff --git a/ldap/servers/plugins/http/http_impl.c b/ldap/servers/plugins/http/http_impl.c index 7accdf68f..1ca0416c1 100644 --- a/ldap/servers/plugins/http/http_impl.c +++ b/ldap/servers/plugins/http/http_impl.c @@ -591,15 +591,22 @@ static PRStatus sendPostReq(PRFileDesc *fd, const char *path, httpheader **httph PRInt32 http_connection_time_out = 0; int i = 0; int body_len, buflen = 0; + int path_len; if (body) { body_len = strlen(body); } else { body_len = 0; } + if (path) { + path_len = strlen(path); + } else { + path_len = 0; + } + PR_snprintf(body_len_str, sizeof(body_len_str), "%d", body_len); - buflen = (HTTP_POST_STD_LEN + strlen(path) + body_len + strlen(body_len_str)); + buflen = (HTTP_POST_STD_LEN + path_len + body_len + strlen(body_len_str)); for (i = 0; httpheaderArray[i] != NULL; i++) { diff --git a/ldap/servers/plugins/pwdstorage/crypt_pwd.c b/ldap/servers/plugins/pwdstorage/crypt_pwd.c index 03b442aeb..341fc20ad 100644 --- a/ldap/servers/plugins/pwdstorage/crypt_pwd.c +++ b/ldap/servers/plugins/pwdstorage/crypt_pwd.c @@ -108,6 +108,9 @@ crypt_pw_enc_by_hash( const char *pwd, int hash_algo){ algo_salt = slapi_ch_smprintf("$5$%s", salt); } else if (hash_algo == CRYPT_SHA512) { algo_salt = slapi_ch_smprintf("$6$%s", salt); + } else { + /* default to CRYPT_UNIX */ + algo_salt = strdup(salt); } PR_Lock(cryptlock); diff --git a/ldap/servers/plugins/replication/repl_extop.c b/ldap/servers/plugins/replication/repl_extop.c index 51287ca5a..40e66f954 100644 --- a/ldap/servers/plugins/replication/repl_extop.c +++ b/ldap/servers/plugins/replication/repl_extop.c @@ -1158,7 +1158,8 @@ send_response: r_locking_conn = replica_get_locking_conn(r); slapi_log_err(SLAPI_LOG_REPL, repl_plugin_name, "multimaster_extop_StartNSDS50ReplicationRequest - " - "already acquired replica: locking_conn=%d, current connid=%d\n", (int) r_locking_conn, (int) connid); + "already acquired replica: locking_conn=%" PRIu64 ", current connid=%" PRIu64 "\n", + r_locking_conn, connid); if ((r_locking_conn != ULONG_MAX) && (r_locking_conn == connid)) { replica_relinquish_exclusive_access(r, connid, opid); @@ -1174,7 +1175,7 @@ send_response: * that the RA will restart a new session in a clear state */ slapi_log_err(SLAPI_LOG_REPL, repl_plugin_name, "multimaster_extop_StartNSDS50ReplicationRequest - " - "already acquired replica: disconnect conn=%d\n", connid); + "already acquired replica: disconnect conn=%" PRIu64 "\n", connid); slapi_disconnect_server(conn); } diff --git a/ldap/servers/slapd/pw_verify.c b/ldap/servers/slapd/pw_verify.c index 852b027ae..7cdd4c8e2 100644 --- a/ldap/servers/slapd/pw_verify.c +++ b/ldap/servers/slapd/pw_verify.c @@ -118,7 +118,7 @@ pw_validate_be_dn(Slapi_PBlock *pb, Slapi_Entry **referral) } /* We need a slapi_sdn_isanon? */ - if (method == LDAP_AUTH_SIMPLE && cred->bv_len == 0) { + if (method == LDAP_AUTH_SIMPLE && (cred == NULL || cred->bv_len == 0)) { return SLAPI_BIND_ANONYMOUS; } diff --git a/lib/libaccess/oneeval.cpp b/lib/libaccess/oneeval.cpp index dc07ebdcd..d8bdd9a87 100644 --- a/lib/libaccess/oneeval.cpp +++ b/lib/libaccess/oneeval.cpp @@ -658,7 +658,7 @@ ACL_INTEvalTestRights( * place to do it. */ - while (*rights) + while (*rights && rights_cnt < ACL_MAX_TEST_RIGHTS) { rarray_p = &rights_arry[rights_cnt];
0
a123b5466aae3eac4193451ac587d90ef1b61815
389ds/389-ds-base
Bug 666076 - dirsrv crash (1.2.7.5) with multiple simple paged result searches https://bugzilla.redhat.com/show_bug.cgi?id=666076 Resolves: bug 666076 Bug Description: dirsrv crash (1.2.7.5) with multiple simple paged result searches Reviewed by: nkinder, nhosoi (Thanks!) Branch: master Fix Description: Only allow one simple paged results search per-connection at a time. The new function pagedresults_check_or_set_processing() will check the flag in the connection to see if pagedresults processing is in progress. If so, the function will return True and the search will terminate with LDAP_UNWILLING_TO_PERFORM (as per section 3 in RFC 2696, a server is allowed to return unwillingToPerform if there is a limit to the number of outstanding paged search requests from a given client). The processing flag will be reset once the search result has been sent to the client. Since the problem is multiple threads in the same connection accessing the pagedresults data, the workaround is to just set nsslapd-maxthreadsperconn: 1 in cn=config in dse.ldif. Platforms tested: RHEL6 x86_64 Flag Day: no Doc impact: no
commit a123b5466aae3eac4193451ac587d90ef1b61815 Author: Rich Megginson <[email protected]> Date: Thu Jan 13 13:44:15 2011 -0700 Bug 666076 - dirsrv crash (1.2.7.5) with multiple simple paged result searches https://bugzilla.redhat.com/show_bug.cgi?id=666076 Resolves: bug 666076 Bug Description: dirsrv crash (1.2.7.5) with multiple simple paged result searches Reviewed by: nkinder, nhosoi (Thanks!) Branch: master Fix Description: Only allow one simple paged results search per-connection at a time. The new function pagedresults_check_or_set_processing() will check the flag in the connection to see if pagedresults processing is in progress. If so, the function will return True and the search will terminate with LDAP_UNWILLING_TO_PERFORM (as per section 3 in RFC 2696, a server is allowed to return unwillingToPerform if there is a limit to the number of outstanding paged search requests from a given client). The processing flag will be reset once the search result has been sent to the client. Since the problem is multiple threads in the same connection accessing the pagedresults data, the workaround is to just set nsslapd-maxthreadsperconn: 1 in cn=config in dse.ldif. Platforms tested: RHEL6 x86_64 Flag Day: no Doc impact: no diff --git a/ldap/servers/slapd/back-ldbm/ldbm_search.c b/ldap/servers/slapd/back-ldbm/ldbm_search.c index 88af80f34..2ca416fba 100644 --- a/ldap/servers/slapd/back-ldbm/ldbm_search.c +++ b/ldap/servers/slapd/back-ldbm/ldbm_search.c @@ -1201,6 +1201,7 @@ ldbm_back_next_search_entry_ext( Slapi_PBlock *pb, int use_extension ) if ( !use_extension ) { CACHE_RETURN( &inst->inst_cache, &(sr->sr_entry) ); + sr->sr_entry = NULL; } if(sr->sr_vlventry != NULL && !use_extension ) @@ -1239,7 +1240,6 @@ ldbm_back_next_search_entry_ext( Slapi_PBlock *pb, int use_extension ) curtime = current_time(); if ( tlimit != -1 && curtime > stoptime ) { - slapi_send_ldap_result( pb, LDAP_TIMELIMIT_EXCEEDED, NULL, NULL, nentries, urls ); /* in case paged results, clean up the conn */ pagedresults_set_search_result(pb->pb_conn, NULL); slapi_pblock_set( pb, SLAPI_SEARCH_RESULT_SET, NULL ); @@ -1250,13 +1250,13 @@ ldbm_back_next_search_entry_ext( Slapi_PBlock *pb, int use_extension ) slapi_pblock_set( pb, SLAPI_SEARCH_RESULT_ENTRY, NULL ); delete_search_result_set( &sr ); rc = SLAPI_FAIL_GENERAL; + slapi_send_ldap_result( pb, LDAP_TIMELIMIT_EXCEEDED, NULL, NULL, nentries, urls ); goto bail; } /* check lookthrough limit */ if ( llimit != -1 && sr->sr_lookthroughcount >= llimit ) { - slapi_send_ldap_result( pb, LDAP_ADMINLIMIT_EXCEEDED, NULL, NULL, nentries, urls ); /* in case paged results, clean up the conn */ pagedresults_set_search_result(pb->pb_conn, NULL); slapi_pblock_set( pb, SLAPI_SEARCH_RESULT_SET, NULL ); @@ -1267,6 +1267,7 @@ ldbm_back_next_search_entry_ext( Slapi_PBlock *pb, int use_extension ) slapi_pblock_set( pb, SLAPI_SEARCH_RESULT_ENTRY, NULL ); delete_search_result_set( &sr ); rc = SLAPI_FAIL_GENERAL; + slapi_send_ldap_result( pb, LDAP_ADMINLIMIT_EXCEEDED, NULL, NULL, nentries, urls ); goto bail; } @@ -1456,12 +1457,14 @@ ldbm_back_next_search_entry_ext( Slapi_PBlock *pb, int use_extension ) else { CACHE_RETURN ( &inst->inst_cache, &(sr->sr_entry) ); + sr->sr_entry = NULL; } } else { /* Failed the filter test, and this isn't a VLV Search */ CACHE_RETURN( &inst->inst_cache, &(sr->sr_entry) ); + sr->sr_entry = NULL; if (LDAP_UNWILLING_TO_PERFORM == filter_test) { /* Need to catch this error to detect the vattr loop */ slapi_send_ldap_result( pb, filter_test, NULL, @@ -1544,6 +1547,7 @@ delete_search_result_set( back_search_result_set **sr ) { idl_free( (*sr)->sr_candidates ); } + memset( *sr, 0, sizeof( back_search_result_set ) ); slapi_ch_free( (void**)sr ); } diff --git a/ldap/servers/slapd/opshared.c b/ldap/servers/slapd/opshared.c index 1f14341fd..b3e2c4510 100644 --- a/ldap/servers/slapd/opshared.c +++ b/ldap/servers/slapd/opshared.c @@ -226,6 +226,7 @@ op_shared_search (Slapi_PBlock *pb, int send_result) Slapi_Backend *pr_be = NULL; void *pr_search_result = NULL; int pr_search_result_count = 0; + int pr_reset_processing = 0; be_list[0] = NULL; referral_list[0] = NULL; @@ -396,6 +397,12 @@ op_shared_search (Slapi_PBlock *pb, int send_result) &pagesize, &curr_search_count); if (LDAP_SUCCESS == rc) { unsigned int opnote = SLAPI_OP_NOTE_SIMPLEPAGED; + if (pagedresults_check_or_set_processing(pb->pb_conn)) { + send_ldap_result(pb, LDAP_UNWILLING_TO_PERFORM, + NULL, "Simple Paged Results Search already in progress on this connection", 0, NULL); + goto free_and_return_nolock; + } + pr_reset_processing = 1; /* need to reset after we are done with this op */ operation->o_flags |= OP_FLAG_PAGED_RESULTS; pr_be = pagedresults_get_current_be(pb->pb_conn); pr_search_result = pagedresults_get_search_result(pb->pb_conn); @@ -880,6 +887,9 @@ free_and_return: slapi_sdn_done(&sdn); slapi_ch_free_string(&proxydn); slapi_ch_free_string(&proxystr); + if (pr_reset_processing) { + pagedresults_reset_processing(pb->pb_conn); + } } /* Returns 1 if this processing on this entry is finished diff --git a/ldap/servers/slapd/pagedresults.c b/ldap/servers/slapd/pagedresults.c index a1b0333e6..652d4e1a2 100644 --- a/ldap/servers/slapd/pagedresults.c +++ b/ldap/servers/slapd/pagedresults.c @@ -364,6 +364,7 @@ pagedresults_set_timelimit(Connection *conn, time_t timelimit) } /* + * must be called with conn->c_mutex held * return values * 0: not a simple paged result connection * 1: simple paged result and successfully abandoned @@ -385,5 +386,44 @@ pagedresults_cleanup(Connection *conn) } conn->c_search_result_count = 0; conn->c_timelimit = 0; + conn->c_flags &= ~CONN_FLAG_PAGEDRESULTS_PROCESSING; return rc; } + +/* + * check to see if this connection is currently processing + * a pagedresults search - if it is, return True - if not, + * mark that it is processing, and return False + */ +int +pagedresults_check_or_set_processing(Connection *conn) +{ + int ret = 0; + if (conn) { + PR_Lock(conn->c_mutex); + ret = conn->c_flags&CONN_FLAG_PAGEDRESULTS_PROCESSING; + /* if ret is true, the following doesn't do anything */ + conn->c_flags |= CONN_FLAG_PAGEDRESULTS_PROCESSING; + PR_Unlock(conn->c_mutex); + } + return ret; +} + +/* + * mark the connection as being done with pagedresults + * processing - returns True if it was processing, + * False otherwise + */ +int +pagedresults_reset_processing(Connection *conn) +{ + int ret = 0; + if (conn) { + PR_Lock(conn->c_mutex); + ret = conn->c_flags&CONN_FLAG_PAGEDRESULTS_PROCESSING; + /* if ret is false, the following doesn't do anything */ + conn->c_flags &= ~CONN_FLAG_PAGEDRESULTS_PROCESSING; + PR_Unlock(conn->c_mutex); + } + return ret; +} diff --git a/ldap/servers/slapd/proto-slap.h b/ldap/servers/slapd/proto-slap.h index 3d22da5ad..7bd94d470 100644 --- a/ldap/servers/slapd/proto-slap.h +++ b/ldap/servers/slapd/proto-slap.h @@ -1387,6 +1387,8 @@ int pagedresults_get_sort_result_code(Connection *conn); int pagedresults_set_sort_result_code(Connection *conn, int code); int pagedresults_set_timelimit(Connection *conn, time_t timelimit); int pagedresults_cleanup(Connection *conn); +int pagedresults_check_or_set_processing(Connection *conn); +int pagedresults_reset_processing(Connection *conn); /* * sort.c diff --git a/ldap/servers/slapd/slap.h b/ldap/servers/slapd/slap.h index 65ee8cec7..ee02a26e7 100644 --- a/ldap/servers/slapd/slap.h +++ b/ldap/servers/slapd/slap.h @@ -1409,6 +1409,9 @@ typedef struct conn { #define CONN_FLAG_PAGEDRESULTS_UNINDEXED 128 /* If the search is unindexed, * store the info in c_flags */ +#define CONN_FLAG_PAGEDRESULTS_PROCESSING 256 /* there is an operation + * processing a pagedresults search + */ #define CONN_GET_SORT_RESULT_CODE (-1) #define START_TLS_OID "1.3.6.1.4.1.1466.20037"
0
e2a5faf792f179c7e035b23457360b2efbb30159
389ds/389-ds-base
fix hang related to ticket 568
commit e2a5faf792f179c7e035b23457360b2efbb30159 Author: Ludwig Krispenz <[email protected]> Date: Thu May 16 09:16:24 2013 +0200 fix hang related to ticket 568 diff --git a/ldap/servers/slapd/back-ldbm/dblayer.c b/ldap/servers/slapd/back-ldbm/dblayer.c index 2d5f98ff7..99902d9c1 100644 --- a/ldap/servers/slapd/back-ldbm/dblayer.c +++ b/ldap/servers/slapd/back-ldbm/dblayer.c @@ -3744,7 +3744,7 @@ int dblayer_txn_abort_ext(struct ldbminfo *li, back_txn *txn, PRBool use_lock) priv->dblayer_enable_transactions) { int txn_id = db_txn->id(db_txn); - if (log_flush_thread) { + if ( use_lock && log_flush_thread) { PR_Lock(sync_txn_log_flush); txn_in_progress_count--; PR_Unlock(sync_txn_log_flush); @@ -4488,7 +4488,7 @@ static int log_flush_threadmain(void *param) * - no more active transaction, no need to wait * - do_flush indicate that the max waiting interval is exceeded */ - if(trans_batch_count >= trans_batch_limit || trans_batch_count == txn_in_progress_count || do_flush) { + if(trans_batch_count >= trans_batch_limit || trans_batch_count >= txn_in_progress_count || do_flush) { LDAPDebug(LDAP_DEBUG_BACKLDBM, "log_flush_threadmain (working): batchcount: %d, txn_in_progress: %d\n", trans_batch_count, txn_in_progress_count, 0); LOG_FLUSH(priv->dblayer_env->dblayer_DB_ENV,0); for (i=0;i<trans_batch_count;i++)
0
3a5cc4d0b04eb6ecce79939a3ed9dc8bd69bc7c0
389ds/389-ds-base
Ticket 48978 - Fine tune error logging Description: Only report erorr log level adjustments if it's not using the default levels. Also added logging around the changelog RUV construction. https://fedorahosted.org/389/ticket/48978 Reviewed by: nhosoi(Thanks!)
commit 3a5cc4d0b04eb6ecce79939a3ed9dc8bd69bc7c0 Author: Mark Reynolds <[email protected]> Date: Thu Oct 20 15:47:11 2016 -0400 Ticket 48978 - Fine tune error logging Description: Only report erorr log level adjustments if it's not using the default levels. Also added logging around the changelog RUV construction. https://fedorahosted.org/389/ticket/48978 Reviewed by: nhosoi(Thanks!) diff --git a/ldap/servers/plugins/replication/cl5_api.c b/ldap/servers/plugins/replication/cl5_api.c index e31cff218..19ab1be60 100644 --- a/ldap/servers/plugins/replication/cl5_api.c +++ b/ldap/servers/plugins/replication/cl5_api.c @@ -4298,7 +4298,7 @@ static int _cl5WriteRUV (CL5DBFile *file, PRBool purge) /* This is a very slow process since we have to read every changelog entry. Hopefully, this function is not called too often */ -static int _cl5ConstructRUV (const char *replGen, Object *obj, PRBool purge) +static int _cl5ConstructRUV (const char *replGen, Object *obj, PRBool purge) { int rc; CL5Entry entry; @@ -4320,11 +4320,15 @@ static int _cl5ConstructRUV (const char *replGen, Object *obj, PRBool purge) if (rc != RUV_SUCCESS) { slapi_log_err(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5ConstructRUV - " - "Failed to initialize %s RUV for file %s; ruv error - %d\n", + "Failed to initialize %s RUV for file %s; ruv error - %d\n", purge? "purge" : "upper bound", file->name, rc); return CL5_RUV_ERROR; } + slapi_log_err(SLAPI_LOG_NOTICE, repl_plugin_name_cl, + "_cl5ConstructRUV - Rebuilding the replication changelog RUV, " + "this may take several minutes...\n"); + entry.op = &op; rc = _cl5GetFirstEntry (obj, &entry, &iterator, NULL); while (rc == CL5_SUCCESS) @@ -4333,7 +4337,7 @@ static int _cl5ConstructRUV (const char *replGen, Object *obj, PRBool purge) rid = csn_get_replicaid (op.csn); } else { slapi_log_err(SLAPI_LOG_WARNING, repl_plugin_name_cl, "_cl5ConstructRUV - " - "Operation missing csn, moving on to next entry.\n"); + "Operation missing csn, moving on to next entry.\n"); cl5_operation_parameters_done (&op); rc = _cl5GetNextEntry (&entry, iterator); continue; @@ -4341,7 +4345,7 @@ static int _cl5ConstructRUV (const char *replGen, Object *obj, PRBool purge) if(is_cleaned_rid(rid)){ /* skip this entry as the rid is invalid */ slapi_log_err(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5ConstructRUV - " - "Skipping entry because its csn contains a cleaned rid(%d)\n", rid); + "Skipping entry because its csn contains a cleaned rid(%d)\n", rid); cl5_operation_parameters_done (&op); rc = _cl5GetNextEntry (&entry, iterator); continue; @@ -4355,8 +4359,8 @@ static int _cl5ConstructRUV (const char *replGen, Object *obj, PRBool purge) if (rc != RUV_SUCCESS) { slapi_log_err(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5ConstructRUV - " - "Failed to updated %s RUV for file %s; ruv error - %d\n", - purge ? "purge" : "upper bound", file->name, rc); + "Failed to update %s RUV for file %s; ruv error - %d\n", + purge ? "purge" : "upper bound", file->name, rc); rc = CL5_RUV_ERROR; continue; } @@ -4381,6 +4385,10 @@ static int _cl5ConstructRUV (const char *replGen, Object *obj, PRBool purge) ruv_destroy (&file->maxRUV); } + slapi_log_err(SLAPI_LOG_NOTICE, repl_plugin_name_cl, + "_cl5ConstructRUV - Rebuilding replication changelog RUV complete. Result %d (%s)\n", + rc, rc?"Failed to rebuild changelog RUV":"Success"); + return rc; } diff --git a/ldap/servers/slapd/config.c b/ldap/servers/slapd/config.c index 73b5f80ce..fc83a13b3 100644 --- a/ldap/servers/slapd/config.c +++ b/ldap/servers/slapd/config.c @@ -189,7 +189,7 @@ slapd_bootstrap_config(const char *configdir) char syntaxlogging[BUFSIZ]; char plugintracking[BUFSIZ]; char dn_validate_strict[BUFSIZ]; - char moddn_aci[BUFSIZ]; + char moddn_aci[BUFSIZ]; Slapi_DN plug_dn; workpath[0] = loglevel[0] = maxdescriptors[0] = '\0'; @@ -291,9 +291,17 @@ slapd_bootstrap_config(const char *configdir) } else { - slapi_log_err(SLAPI_LOG_ERR, "slapd_bootstrap_config", - "%s: ignoring %s (since -d %d was given on the command line)\n", - CONFIG_LOGLEVEL_ATTRIBUTE, loglevel, config_get_errorlog_level()); + if (strcmp(loglevel, "0") || + config_get_errorlog_level() != SLAPD_DEFAULT_ERRORLOG_LEVEL) + { + /* + * loglevel of zero and SLAPD_DEFAULT_ERRORLOG_LEVEL are the + * same. Only report an error if they are different. + */ + slapi_log_err(SLAPI_LOG_NOTICE, "slapd_bootstrap_config", + "%s: ignoring %s (since -d %d was given on the command line)\n", + CONFIG_LOGLEVEL_ATTRIBUTE, loglevel, config_get_errorlog_level()); + } } }
0
5862d6ceeb64018d9134e1bd9a5e12ca47738bee
389ds/389-ds-base
Fix for coverty issues 12028,12029,12030
commit 5862d6ceeb64018d9134e1bd9a5e12ca47738bee Author: Ludwig Krispenz <[email protected]> Date: Tue Oct 1 14:56:36 2013 +0200 Fix for coverty issues 12028,12029,12030 diff --git a/ldap/servers/plugins/sync/sync_persist.c b/ldap/servers/plugins/sync/sync_persist.c index d35dde976..7cd65c85b 100644 --- a/ldap/servers/plugins/sync/sync_persist.c +++ b/ldap/servers/plugins/sync/sync_persist.c @@ -582,7 +582,7 @@ sync_send_results( void *arg ) char **noattrs = NULL; LDAPControl **ectrls = NULL; Slapi_Entry *ec; - int chg_type; + int chg_type = LDAP_SYNC_NONE; /* deque one element */ PR_Lock( req->req_lock ); diff --git a/ldap/servers/plugins/sync/sync_refresh.c b/ldap/servers/plugins/sync/sync_refresh.c index 14872894f..71a0edd35 100644 --- a/ldap/servers/plugins/sync/sync_refresh.c +++ b/ldap/servers/plugins/sync/sync_refresh.c @@ -457,6 +457,10 @@ sync_read_entry_from_changelog( Slapi_Entry *cl_entry, void *cb_data) int index = 0; Sync_CallBackData *cb = (Sync_CallBackData *) cb_data; + if (cb == NULL) { + return(1); + } + uniqueid = sync_get_attr_value_from_entry (cl_entry, CL_ATTR_UNIQUEID); chgtype = sync_get_attr_value_from_entry (cl_entry, CL_ATTR_CHGTYPE); chgnr = sync_get_attr_value_from_entry (cl_entry, CL_ATTR_CHANGENUMBER); @@ -465,6 +469,7 @@ sync_read_entry_from_changelog( Slapi_Entry *cl_entry, void *cb_data) slapi_log_error (SLAPI_LOG_FATAL, SYNC_PLUGIN_SUBSYSTEM, "Retro Changelog does not provied nsuniquedid." "Check RCL plugin configuration." ); + return(1); } diff --git a/ldap/servers/plugins/sync/sync_util.c b/ldap/servers/plugins/sync/sync_util.c index 9e98561a2..5ec5e5d1f 100644 --- a/ldap/servers/plugins/sync/sync_util.c +++ b/ldap/servers/plugins/sync/sync_util.c @@ -80,8 +80,25 @@ sync_parse_control_value( struct berval *psbvp, ber_int_t *mode, int *reload, ch if ( ber_scanf( ber, "{e", mode ) == LBER_ERROR ) { rc= LDAP_PROTOCOL_ERROR; - } else if ( ber_scanf( ber, "a", cookie ) != LBER_ERROR ) - ber_scanf( ber, "b}", reload ); + } else { + ber_tag_t tag; + ber_len_t len; + tag = ber_peek_tag( ber, &len ); + if ( tag == LDAP_TAG_SYNC_COOKIE ) { + rc = ber_scanf( ber, "a", cookie ); + tag = ber_peek_tag( ber, &len ); + } + if (rc != LBER_ERROR && tag == LDAP_TAG_RELOAD_HINT ) { + rc = ber_scanf( ber, "b", reload ); + } + if (rc != LBER_ERROR) { + rc = ber_scanf( ber, "}"); + } + if (rc == LBER_ERROR) { + + rc= LDAP_PROTOCOL_ERROR; + }; + } /* the ber encoding is no longer needed */ ber_free(ber,1); @@ -147,7 +164,7 @@ sync_create_state_control( Slapi_Entry *e, LDAPControl **ctrlp, int type, Sync_C Slapi_Attr *attr; Slapi_Value *val; - if ( ctrlp == NULL || ( ber = der_alloc()) == NULL ) { + if ( type == LDAP_SYNC_NONE || ctrlp == NULL || ( ber = der_alloc()) == NULL ) { return( LDAP_OPERATIONS_ERROR ); }
0
4881826e1b7996862f5549c7caad28e44f8fda0f
389ds/389-ds-base
Ticket 49926 - Add replication functionality to dsconf Description: Add replication functionality to the dsconf. This includes repl config, agmts, winsync agmts, and cleanallruv/abort cleanallruv Adjusted the backend options to use hyphens for consistency https://pagure.io/389-ds-base/issue/49926 Reviewed by: spichugi & firstyear(Thanks!!)
commit 4881826e1b7996862f5549c7caad28e44f8fda0f Author: Mark Reynolds <[email protected]> Date: Mon Sep 10 10:56:43 2018 -0400 Ticket 49926 - Add replication functionality to dsconf Description: Add replication functionality to the dsconf. This includes repl config, agmts, winsync agmts, and cleanallruv/abort cleanallruv Adjusted the backend options to use hyphens for consistency https://pagure.io/389-ds-base/issue/49926 Reviewed by: spichugi & firstyear(Thanks!!) diff --git a/ldap/servers/plugins/replication/repl5_agmt.c b/ldap/servers/plugins/replication/repl5_agmt.c index 20a0ca9ba..6e60dd681 100644 --- a/ldap/servers/plugins/replication/repl5_agmt.c +++ b/ldap/servers/plugins/replication/repl5_agmt.c @@ -3029,8 +3029,9 @@ agmt_update_maxcsn(Replica *r, Slapi_DN *sdn, int op, LDAPMod **mods, CSN *csn) * temporarily mark it as "unavailable". */ slapi_ch_free_string(&agmt->maxcsn); - agmt->maxcsn = slapi_ch_smprintf("%s;%s;%s;%" PRId64 ";unavailable", slapi_sdn_get_dn(agmt->replarea), - slapi_rdn_get_value_by_ref(slapi_rdn_get_rdn(agmt->rdn)), agmt->hostname, agmt->port); + agmt->maxcsn = slapi_ch_smprintf("%s;%s;%s;%" PRId64 ";unavailable;%s", slapi_sdn_get_dn(agmt->replarea), + slapi_rdn_get_value_by_ref(slapi_rdn_get_rdn(agmt->rdn)), agmt->hostname, + agmt->port, maxcsn); } else if (rid == oprid) { slapi_ch_free_string(&agmt->maxcsn); agmt->maxcsn = slapi_ch_smprintf("%s;%s;%s;%" PRId64 ";%" PRIu16 ";%s", slapi_sdn_get_dn(agmt->replarea), diff --git a/src/lib389/cli/dsconf b/src/lib389/cli/dsconf index ac8af23ca..9b64589ca 100755 --- a/src/lib389/cli/dsconf +++ b/src/lib389/cli/dsconf @@ -26,6 +26,7 @@ from lib389.cli_conf import health as cli_health from lib389.cli_conf import saslmappings as cli_sasl from lib389.cli_conf import pwpolicy as cli_pwpolicy from lib389.cli_conf import backup as cli_backup +from lib389.cli_conf import replication as cli_replication 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 @@ -79,6 +80,7 @@ cli_automember.create_parser(subparsers) cli_sasl.create_parser(subparsers) cli_pwpolicy.create_parser(subparsers) cli_backup.create_parser(subparsers) +cli_replication.create_parser(subparsers) argcomplete.autocomplete(parser) diff --git a/src/lib389/lib389/__init__.py b/src/lib389/lib389/__init__.py index 47d6a2e6a..0bb4378e1 100644 --- a/src/lib389/lib389/__init__.py +++ b/src/lib389/lib389/__init__.py @@ -80,6 +80,7 @@ from lib389.utils import ( formatInfData, ensure_bytes, ensure_str, + ensure_list_str, format_cmd_list) from lib389.paths import Paths from lib389.nss_ssl import NssSsl @@ -3286,21 +3287,28 @@ class DirSrv(SimpleLDAPObject, object): ldif_file, e.errno, e.strerror) raise e - def getConsumerMaxCSN(self, replica_entry): + def getConsumerMaxCSN(self, replica_entry, binddn=None, bindpw=None): """ Attempt to get the consumer's maxcsn from its database """ - host = replica_entry.getValue(AGMT_HOST) - port = replica_entry.getValue(AGMT_PORT) - suffix = replica_entry.getValue(REPL_ROOT) + host = replica_entry.get_attr_val_utf8(AGMT_HOST) + port = replica_entry.get_attr_val_utf8(AGMT_PORT) + suffix = replica_entry.get_attr_val_utf8(REPL_ROOT) error_msg = "Unavailable" + # If we are using LDAPI we need to provide the credentials, otherwise + # use the existing credentials + if binddn is None: + binddn = self.binddn + if bindpw is None: + bindpw = self.bindpw + # Open a connection to the consumer consumer = DirSrv(verbose=self.verbose) args_instance[SER_HOST] = host args_instance[SER_PORT] = int(port) - args_instance[SER_ROOT_DN] = self.binddn - args_instance[SER_ROOT_PW] = self.bindpw + args_instance[SER_ROOT_DN] = binddn + args_instance[SER_ROOT_PW] = bindpw args_standalone = args_instance.copy() consumer.allocate(args_standalone) try: @@ -3317,7 +3325,7 @@ class DirSrv(SimpleLDAPObject, object): # Error consumer.close() return None - rid = replica_entries[0].getValue(REPL_ID) + rid = ensure_str(replica_entries[0].getValue(REPL_ID)) except: # Error consumer.close() @@ -3330,8 +3338,9 @@ class DirSrv(SimpleLDAPObject, object): consumer.close() if not entry: # Error out? + self.log.error("Failed to retrieve database RUV entry from consumer") return error_msg - elements = entry[0].getValues('nsds50ruv') + elements = ensure_list_str(entry[0].getValues('nsds50ruv')) for ruv in elements: if ('replica %s ' % rid) in ruv: ruv_parts = ruv.split() @@ -3345,16 +3354,17 @@ class DirSrv(SimpleLDAPObject, object): consumer.close() return error_msg - def getReplAgmtStatus(self, agmt_entry): + def getReplAgmtStatus(self, agmt_entry, binddn=None, bindpw=None): ''' Return the status message, if consumer is not in synch raise an exception ''' agmt_maxcsn = None - suffix = agmt_entry.getValue(REPL_ROOT) - agmt_name = agmt_entry.getValue('cn') + suffix = agmt_entry.get_attr_val_utf8(REPL_ROOT) + agmt_name = agmt_entry.get_attr_val_utf8('cn') status = "Unknown" rc = -1 + try: entry = self.search_s(suffix, ldap.SCOPE_SUBTREE, REPLICA_RUV_FILTER, [AGMT_MAXCSN]) @@ -3373,7 +3383,8 @@ class DirSrv(SimpleLDAPObject, object): dc=example,dc=com;test_agmt;localhost;389;unavailable ''' - maxcsns = entry[0].getValues(AGMT_MAXCSN) + + maxcsns = ensure_list_str(entry[0].getValues(AGMT_MAXCSN)) for csn in maxcsns: comps = csn.split(';') if agmt_name == comps[1]: @@ -3384,19 +3395,19 @@ class DirSrv(SimpleLDAPObject, object): agmt_maxcsn = comps[5] if agmt_maxcsn: - con_maxcsn = self.getConsumerMaxCSN(agmt_entry) + con_maxcsn = self.getConsumerMaxCSN(agmt_entry, binddn=binddn, bindpw=bindpw) if con_maxcsn: if agmt_maxcsn == con_maxcsn: status = "In Synchronization" rc = 0 else: - # Not in sync - attmpt to discover the cause + # Not in sync - attempt to discover the cause repl_msg = "Unknown" - if agmt_entry.getValue(AGMT_UPDATE_IN_PROGRESS) == 'TRUE': + if agmt_entry.get_attr_val_utf8(AGMT_UPDATE_IN_PROGRESS) == 'TRUE': # Replication is on going - this is normal repl_msg = "Replication still in progress" elif "Can't Contact LDAP" in \ - agmt_entry.getValue(AGMT_UPDATE_STATUS): + agmt_entry.get_attr_val_utf8(AGMT_UPDATE_STATUS): # Consumer is down repl_msg = "Consumer can not be contacted" diff --git a/src/lib389/lib389/_mapped_object.py b/src/lib389/lib389/_mapped_object.py index c347a5fd7..5c0e0b626 100644 --- a/src/lib389/lib389/_mapped_object.py +++ b/src/lib389/lib389/_mapped_object.py @@ -169,7 +169,7 @@ class DSLdapObject(DSLogging): str_attrs[ensure_str(k)] = ensure_list_str(attrs[k]) # ensure all the keys are lowercase - str_attrs = dict((k.lower(), v) for k, v in str_attrs.items()) + str_attrs = dict((k.lower(), v) for k, v in list(str_attrs.items())) response = json.dumps({"type": "entry", "dn": ensure_str(self._dn), "attrs": str_attrs}) @@ -969,7 +969,7 @@ class DSLdapObjects(DSLogging): # This may not work in all cases, especially when we consider plugins. # co = self._entry_to_instance(dn=None, entry=None) - # Make the rdn naming attr avaliable + # Make the rdn naming attr available self._rdn_attribute = co._rdn_attribute (rdn, properties) = self._validate(rdn, properties) # Now actually commit the creation req diff --git a/src/lib389/lib389/_replication.py b/src/lib389/lib389/_replication.py index 7d5157723..caa0c64d5 100644 --- a/src/lib389/lib389/_replication.py +++ b/src/lib389/lib389/_replication.py @@ -83,6 +83,14 @@ class CSN(object): retstr = "equal" return retstr + def get_time_lag(self, oth): + diff = oth.ts - self.ts + if diff < 0: + lag = datetime.timedelta(seconds=-diff) + else: + lag = datetime.timedelta(seconds=diff) + return "{:0>8}".format(str(lag)) + def __repr__(self): return ("%s seq: %s rid: %s" % (time.strftime("%x %X", time.localtime(self.ts)), str(self.seq), str(self.rid))) diff --git a/src/lib389/lib389/agreement.py b/src/lib389/lib389/agreement.py index 9e8d90f21..8d03ef947 100644 --- a/src/lib389/lib389/agreement.py +++ b/src/lib389/lib389/agreement.py @@ -10,13 +10,13 @@ import ldap import re import time import six - +import json +import datetime from lib389._constants import * from lib389.properties import * from lib389._entry import FormatDict -from lib389.utils import normalizeDN, ensure_bytes, ensure_str, ensure_dict_str +from lib389.utils import normalizeDN, ensure_bytes, ensure_str, ensure_dict_str, ensure_list_str from lib389 import Entry, DirSrv, NoSuchEntryError, InvalidArgumentError - from lib389._mapped_object import DSLdapObject, DSLdapObjects @@ -33,16 +33,25 @@ class Agreement(DSLdapObject): :type dn: str """ - def __init__(self, instance, dn=None): + csnpat = r'(.{8})(.{4})(.{4})(.{4})' + csnre = re.compile(csnpat) + + def __init__(self, instance, dn=None, winsync=False): super(Agreement, self).__init__(instance, dn) self._rdn_attribute = 'cn' self._must_attributes = [ 'cn', ] - self._create_objectclasses = [ - 'top', - 'nsds5replicationagreement', - ] + if winsync: + self._create_objectclasses = [ + 'top', + 'nsDSWindowsReplicationAgreement', + ] + else: + self._create_objectclasses = [ + 'top', + 'nsds5replicationagreement', + ] self._protected = False def begin_reinit(self): @@ -59,6 +68,7 @@ class Agreement(DSLdapObject): """ done = False error = False + inprogress = False status = self.get_attr_val_utf8('nsds5ReplicaLastInitStatus') self._log.debug('agreement tot_init status: %s' % status) if not status: @@ -67,33 +77,300 @@ class Agreement(DSLdapObject): error = True elif 'Total update succeeded' in status: done = True + inprogress = False elif 'Replication error' in status: error = True + elif 'Total update in progress' in status: + inprogress = True + elif 'LDAP error' in status: + error = True - return (done, error) + return (done, inprogress, error) def wait_reinit(self, timeout=300): """Wait for a reinit to complete. Returns done and error. A correct reinit will return (True, False). - + :param timeout: timeout value for how long to wait for the reinit + :type timeout: int :returns: tuple(done, error), where done, error are bool. """ done = False error = False count = 0 while done is False and error is False: - (done, error) = self.check_reinit() + (done, inprogress, error) = self.check_reinit() if count > timeout and not done: error = True count = count + 2 time.sleep(2) return (done, error) + def get_agmt_maxcsn(self): + """Get the agreement maxcsn from the database RUV entry + :returns: CSN string if found, otherwise None is returned + """ + from lib389.replica import Replicas + suffix = self.get_attr_val_utf8(REPL_ROOT) + agmt_name = self.get_attr_val_utf8('cn') + replicas = Replicas(self._instance) + replica = replicas.get(suffix) + maxcsns = replica.get_ruv_agmt_maxcsns() + + if maxcsns is None or len(maxcsns) == 0: + self._log.debug('get_agmt_maxcsn - Failed to get agmt maxcsn from RUV') + return None + + for csn in maxcsns: + comps = csn.split(';') + if agmt_name == comps[1]: + # same replica, get maxcsn + if len(comps) < 6: + return None + else: + return comps[5] + + self._log.debug('get_agmt_maxcsn - did not find matching agmt maxcsn from RUV') + return None + + def get_consumer_maxcsn(self, binddn=None, bindpw=None): + """Attempt to get the consumer's maxcsn from its database RUV entry + :param binddn: Specifies a specific bind DN to use when contacting the remote consumer + :type binddn: str + :param bindpw: Password for the bind DN + :type bindpw: str + :returns: CSN string if found, otherwise "Unavailable" is returned + """ + host = self.get_attr_val_utf8(AGMT_HOST) + port = self.get_attr_val_utf8(AGMT_PORT) + suffix = self.get_attr_val_utf8(REPL_ROOT) + protocol = self.get_attr_val_utf8('nsds5replicatransportinfo').lower() + + result_msg = "Unavailable" + + # If we are using LDAPI we need to provide the credentials, otherwise + # use the existing credentials + if binddn is None: + binddn = self._instance.binddn + if bindpw is None: + bindpw = self._instance.bindpw + + # Get the replica id from supplier to compare to the consumer's rid + from lib389.replica import Replicas + replicas = Replicas(self._instance) + replica = replicas.get(suffix) + rid = replica.get_attr_val_utf8(REPL_ID) + + # Open a connection to the consumer + consumer = DirSrv(verbose=self._instance.verbose) + args_instance[SER_HOST] = host + if protocol == "ssl" or protocol == "ldaps": + args_instance[SER_SECURE_PORT] = int(port) + else: + args_instance[SER_PORT] = int(port) + args_instance[SER_ROOT_DN] = binddn + args_instance[SER_ROOT_PW] = bindpw + args_standalone = args_instance.copy() + consumer.allocate(args_standalone) + try: + consumer.open() + except ldap.LDAPError as e: + self._instance.log.debug('Connection to consumer ({}:{}) failed, error: {}'.format(host, port, e)) + return result_msg + + # Search for the tombstone RUV entry + try: + entry = consumer.search_s(suffix, ldap.SCOPE_SUBTREE, + REPLICA_RUV_FILTER, ['nsds50ruv']) + if not entry: + self.log.error("Failed to retrieve database RUV entry from consumer") + else: + elements = ensure_list_str(entry[0].getValues('nsds50ruv')) + for ruv in elements: + if ('replica %s ' % rid) in ruv: + ruv_parts = ruv.split() + if len(ruv_parts) == 5: + result_msg = ruv_parts[4] + break + except ldap.LDAPError as e: + self._instance.log.debug('Failed to search for the suffix ' + + '({}) consumer ({}:{}) failed, error: {}'.format( + suffix, host, port, e)) + consumer.close() + return result_msg + + def get_agmt_status(self, binddn=None, bindpw=None): + """Return the status message + :param binddn: Specifies a specific bind DN to use when contacting the remote consumer + :type binddn: str + :param bindpw: Password for the bind DN + :type bindpw: str + :returns: A status message about the replication agreement + """ + status = "Unknown" + + agmt_maxcsn = self.get_agmt_maxcsn() + if agmt_maxcsn is not None: + con_maxcsn = self.get_consumer_maxcsn(binddn=binddn, bindpw=bindpw) + if con_maxcsn: + if agmt_maxcsn == con_maxcsn: + status = "In Synchronization" + else: + # Not in sync - attempt to discover the cause + repl_msg = "Unknown" + if self.get_attr_val_utf8(AGMT_UPDATE_IN_PROGRESS) == 'TRUE': + # Replication is on going - this is normal + repl_msg = "Replication still in progress" + elif "Can't Contact LDAP" in \ + self.get_attr_val_utf8(AGMT_UPDATE_STATUS): + # Consumer is down + repl_msg = "Consumer can not be contacted" + + status = ("Not in Synchronization: supplier " + + "(%s) consumer (%s) Reason(%s)" % + (agmt_maxcsn, con_maxcsn, repl_msg)) + return status + + def get_lag_time(self, suffix, agmt_name, binddn=None, bindpw=None): + """Get the lag time between the supplier and the consumer + :param suffix: The replication suffix + :type suffix: str + :param agmt_name: The name of the agreement + :type agmt_name: str + :param binddn: Specifies a specific bind DN to use when contacting the remote consumer + :type binddn: str + :param bindpw: Password for the bind DN + :type bindpw: str + :returns: A time-formated string of the the replication lag (HH:MM:SS). + :raises: ValueError - if unable to get consumer's maxcsn + """ + agmt_maxcsn = self.get_agmt_maxcsn() + con_maxcsn = self.get_consumer_maxcsn(binddn=binddn, bindpw=bindpw) + if con_maxcsn is None: + raise ValueError("Unable to get consumer's max csn") + if con_maxcsn == "Unavailable": + return con_maxcsn + + # Extract the csn timstamps and compare them + match = Agreement.csnre.match(agmt_maxcsn) + if match: + agmt_time = int(match.group(1), 16) + match = Agreement.csnre.match(con_maxcsn) + if match: + con_time = int(match.group(1), 16) + diff = con_time - agmt_time + if diff < 0: + lag = datetime.timedelta(seconds=-diff) + else: + lag = datetime.timedelta(seconds=diff) + + # Return a nice formated timestamp + return "{:0>8}".format(str(lag)) + + def status(self, winsync=False, just_status=False, use_json=False, binddn=None, bindpw=None): + """Get the status of a replication agreement + :param winsync: Specifies if the the agreement is a winsync replication agreement + :type winsync: boolean + :param just_status: Just return the status string and not all of the status attributes + :type just_status: boolean + :param use_json: Return the status in a JSON object + :type use_json: boolean + :param binddn: Specifies a specific bind DN to use when contacting the remote consumer + :type binddn: str + :param bindpw: Password for the bind DN + :type bindpw: str + :returns: A status message + :raises: ValueError - if failing to get agmt status + """ + status_attrs_dict = self.get_all_attrs() + status_attrs_dict = dict((k.lower(), v) for k, v in list(status_attrs_dict.items())) + + # We need a bind DN and passwd so we can query the consumer. If this is an LDAPI + # connection, and the consumer does not allow anonymous access to the tombstone + # RUV entry under the suffix, then we can't get the status. So in this case we + # need to provide a DN and password. + if not winsync: + try: + status = self.get_agmt_status(binddn=binddn, bindpw=bindpw) + except ValueError as e: + status = str(e) + if just_status: + if use_json: + return (json.dumps(status)) + else: + return status + + # Get the lag time + suffix = ensure_str(status_attrs_dict['nsds5replicaroot'][0]) + agmt_name = ensure_str(status_attrs_dict['cn'][0]) + lag_time = self.get_lag_time(suffix, agmt_name, binddn=binddn, bindpw=bindpw) + else: + status = "Not available for Winsync agreements" + + # handle the attributes that are not always set in the agreement + if 'nsds5replicaenabled' not in status_attrs_dict: + status_attrs_dict['nsds5replicaenabled'] = ['on'] + if 'nsds5agmtmaxcsn' not in status_attrs_dict: + status_attrs_dict['nsds5agmtmaxcsn'] = ["unavailable"] + if 'nsds5replicachangesskippedsince' not in status_attrs_dict: + status_attrs_dict['nsds5replicachangesskippedsince'] = ["unavailable"] + if 'nsds5beginreplicarefresh' not in status_attrs_dict: + status_attrs_dict['nsds5beginreplicarefresh'] = [""] + if 'nsds5replicalastinitstatus' not in status_attrs_dict: + status_attrs_dict['nsds5replicalastinitstatus'] = ["unavilable"] + if 'nsds5replicachangessentsincestartup' not in status_attrs_dict: + status_attrs_dict['nsds5replicachangessentsincestartup'] = ['0'] + if ensure_str(status_attrs_dict['nsds5replicachangessentsincestartup'][0]) == '': + status_attrs_dict['nsds5replicachangessentsincestartup'] = ['0'] + + # Case sensitive? + if use_json: + result = {'replica-enabled': ensure_str(status_attrs_dict['nsds5replicaenabled'][0]), + 'update-in-progress': ensure_str(status_attrs_dict['nsds5replicaupdateinprogress'][0]), + 'last-update-start': ensure_str(status_attrs_dict['nsds5replicalastupdatestart'][0]), + 'last-update-end': ensure_str(status_attrs_dict['nsds5replicalastupdateend'][0]), + 'number-changes-sent': ensure_str(status_attrs_dict['nsds5replicachangessentsincestartup'][0]), + 'number-changes-skipped:': ensure_str(status_attrs_dict['nsds5replicachangesskippedsince'][0]), + 'last-update-status': ensure_str(status_attrs_dict['nsds5replicalastupdatestatus'][0]), + 'init-in-progress': ensure_str(status_attrs_dict['nsds5beginreplicarefresh'][0]), + 'last-init-start': ensure_str(status_attrs_dict['nsds5replicalastinitstart'][0]), + 'last-init-end': ensure_str(status_attrs_dict['nsds5replicalastinitend'][0]), + 'last-init-status': ensure_str(status_attrs_dict['nsds5replicalastinitstatus'][0]), + 'reap-active': ensure_str(status_attrs_dict['nsds5replicareapactive'][0]), + 'replication-status': status, + 'replication-lag-time': lag_time + } + return (json.dumps(result)) + else: + retstr = ( + "Status for %(cn)s agmt %(nsDS5ReplicaHost)s:" + "%(nsDS5ReplicaPort)s" "\n" + "Replica Enabled: %(nsds5ReplicaEnabled)s" "\n" + "Update In Progress: %(nsds5replicaUpdateInProgress)s" "\n" + "Last Update Start: %(nsds5replicaLastUpdateStart)s" "\n" + "Last Update End: %(nsds5replicaLastUpdateEnd)s" "\n" + "Number Of Changes Sent: %(nsds5replicaChangesSentSinceStartup)s" + "\n" + "Number Of Changes Skipped: %(nsds5replicaChangesSkippedSince" + "Startup)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 + entry_data = ensure_dict_str(status_attrs_dict) + result = retstr % FormatDict(entry_data) + result += "Replication Status: {}\n".format(status) + result += "Replication Lag Time: {}\n".format(lag_time) + return result + def pause(self): """Pause outgoing changes from this server to consumer. Note that this does not pause the consumer, only that changes will not be sent from this master to consumer: the consumer may still - recieve changes from other replication paths! + receive changes from other replication paths! """ self.set('nsds5ReplicaEnabled', 'off') @@ -122,6 +399,34 @@ class Agreement(DSLdapObject): """ return self.get_attr_val_utf8('nsDS5ReplicaWaitForAsyncResults') + +class WinsyncAgreement(Agreement): + """A replication agreement from this server instance to + another instance of directory server. + + - must attributes: [ 'cn' ] + - RDN attribute: 'cn' + + :param instance: An instance + :type instance: lib389.DirSrv + :param dn: Entry DN + :type dn: str + """ + + def __init__(self, instance, dn=None): + super(Agreement, self).__init__(instance, dn) + self._rdn_attribute = 'cn' + self._must_attributes = [ + 'cn', + ] + self._create_objectclasses = [ + 'top', + 'nsDSWindowsReplicationAgreement', + ] + + self._protected = False + + class Agreements(DSLdapObjects): """Represents the set of agreements configured on this instance. There are two possible ways to use this interface. @@ -149,11 +454,15 @@ class Agreements(DSLdapObjects): :type rdn: str """ - def __init__(self, instance, basedn=DN_MAPPING_TREE, rdn=None): + def __init__(self, instance, basedn=DN_MAPPING_TREE, rdn=None, winsync=False): super(Agreements, self).__init__(instance) - self._childobject = Agreement - self._objectclasses = [ 'nsds5replicationagreement' ] - self._filterattrs = [ 'cn', 'nsDS5ReplicaRoot' ] + if winsync: + self._childobject = WinsyncAgreement + self._objectclasses = ['nsDSWindowsReplicationAgreement'] + else: + self._childobject = Agreement + self._objectclasses = ['nsds5replicationagreement'] + self._filterattrs = ['cn', 'nsDS5ReplicaRoot'] if rdn is None: self._basedn = basedn else: @@ -167,6 +476,7 @@ class Agreements(DSLdapObjects): raise ldap.UNWILLING_TO_PERFORM("Refusing to create agreement in %s" % DN_MAPPING_TREE) return super(Agreements, self)._validate(rdn, properties) + class AgreementLegacy(object): """An object that helps to work with agreement entry @@ -194,7 +504,6 @@ class AgreementLegacy(object): :type agreement_dn: str :param just_status: If True, returns just status :type just_status: bool - :returns: str -- See below :raises: NoSuchEntryError - if agreement_dn is an unknown entry @@ -208,7 +517,7 @@ class AgreementLegacy(object): Last Update End: 0 Num. Changes Sent: 1:10/0 Num. changes Skipped: None - Last update Status: 0 Replica acquired successfully: + Last update Status: Error (0) Replica acquired successfully: Incremental update started Init in progress: None Last Init Start: 0 diff --git a/src/lib389/lib389/changelog.py b/src/lib389/lib389/changelog.py index d973a572e..4cb306385 100644 --- a/src/lib389/lib389/changelog.py +++ b/src/lib389/lib389/changelog.py @@ -16,6 +16,7 @@ from lib389 import DirSrv, Entry, InvalidArgumentError from lib389._mapped_object import DSLdapObject from lib389.utils import ds_is_older + class Changelog5(DSLdapObject): """Represents the Directory Server changelog. This is used for replication. Only one changelog is needed for every server. @@ -25,9 +26,9 @@ class Changelog5(DSLdapObject): """ def __init__(self, instance, dn='cn=changelog5,cn=config'): - super(Changelog5,self).__init__(instance, dn) + super(Changelog5, self).__init__(instance, dn) self._rdn_attribute = 'cn' - self._must_attributes = [ 'cn', 'nsslapd-changelogdir' ] + self._must_attributes = ['cn', 'nsslapd-changelogdir'] self._create_objectclasses = [ 'top', 'nsChangelogConfig', @@ -37,7 +38,7 @@ class Changelog5(DSLdapObject): 'top', 'extensibleobject', ] - self._protected = True + self._protected = False def set_max_entries(self, value): """Configure the max entries the changelog can hold. diff --git a/src/lib389/lib389/cli_conf/backend.py b/src/lib389/lib389/cli_conf/backend.py index 660294378..85ecfa499 100644 --- a/src/lib389/lib389/cli_conf/backend.py +++ b/src/lib389/lib389/cli_conf/backend.py @@ -163,12 +163,12 @@ def create_parser(subparsers): help="Specifies the filename of the input LDIF files." "When multiple files are imported, they are imported in the order" "they are specified on the command line.") - import_parser.add_argument('-c', '--chunks_size', type=int, + import_parser.add_argument('-c', '--chunks-size', type=int, help="The number of chunks to have during the import operation.") import_parser.add_argument('-E', '--encrypted', action='store_true', help="Decrypts encrypted data during export. This option is used only" "if database encryption is enabled.") - import_parser.add_argument('-g', '--gen_uniq_id', + import_parser.add_argument('-g', '--gen-uniq-id', help="Generate a unique id. Type none for no unique ID to be generated" "and deterministic for the generated unique ID to be name-based." "By default, a time-based unique ID is generated." @@ -176,11 +176,11 @@ def create_parser(subparsers): "it is also possible to specify the namespace for the server to use." "namespaceId is a string of characters" "in the format 00-xxxxxxxx-xxxxxxxx-xxxxxxxx-xxxxxxxx.") - import_parser.add_argument('-O', '--only_core', action='store_true', + import_parser.add_argument('-O', '--only-core', action='store_true', help="Requests that only the core database is created without attribute indexes.") - import_parser.add_argument('-s', '--include_suffixes', nargs='+', + import_parser.add_argument('-s', '--include-suffixes', nargs='+', help="Specifies the suffixes or the subtrees to be included.") - import_parser.add_argument('-x', '--exclude_suffixes', nargs='+', + import_parser.add_argument('-x', '--exclude-suffixes', nargs='+', help="Specifies the suffixes to be excluded.") export_parser = subcommands.add_parser('export', help='do an online export of the suffix') @@ -190,21 +190,21 @@ def create_parser(subparsers): export_parser.add_argument('-l', '--ldif', help="Gives the filename of the output LDIF file." "If more than one are specified, use a space as a separator") - export_parser.add_argument('-C', '--use_id2entry', action='store_true', help="Uses only the main database file.") + export_parser.add_argument('-C', '--use-id2entry', action='store_true', help="Uses only the main database file.") export_parser.add_argument('-E', '--encrypted', action='store_true', help="""Decrypts encrypted data during export. This option is used only if database encryption is enabled.""") - export_parser.add_argument('-m', '--min_base64', action='store_true', + export_parser.add_argument('-m', '--min-base64', action='store_true', help="Sets minimal base-64 encoding.") - export_parser.add_argument('-N', '--no_seq_num', action='store_true', + export_parser.add_argument('-N', '--no-seq-num', action='store_true', help="Enables you to suppress printing the sequence number.") export_parser.add_argument('-r', '--replication', action='store_true', help="Exports the information required to initialize a replica when the LDIF is imported") - export_parser.add_argument('-u', '--no_dump_uniq_id', action='store_true', + export_parser.add_argument('-u', '--no-dump-uniq-id', action='store_true', help="Requests that the unique ID is not exported.") - export_parser.add_argument('-U', '--not_folded', action='store_true', + export_parser.add_argument('-U', '--not-folded', action='store_true', help="Requests that the output LDIF is not folded.") - export_parser.add_argument('-s', '--include_suffixes', nargs='+', + export_parser.add_argument('-s', '--include-suffixes', nargs='+', help="Specifies the suffixes or the subtrees to be included.") - export_parser.add_argument('-x', '--exclude_suffixes', nargs='+', + export_parser.add_argument('-x', '--exclude-suffixes', nargs='+', help="Specifies the suffixes to be excluded.") diff --git a/src/lib389/lib389/cli_conf/pwpolicy.py b/src/lib389/lib389/cli_conf/pwpolicy.py index 2ec7c98b1..bbbd0609e 100644 --- a/src/lib389/lib389/cli_conf/pwpolicy.py +++ b/src/lib389/lib389/cli_conf/pwpolicy.py @@ -147,7 +147,7 @@ def list_policies(inst, basedn, log, args): result += "%s (%s)\n" % (entrydn, policy_type.lower()) if args.json: - return print(json.dumps(result)) + print(json.dumps(result)) else: log.info(result) diff --git a/src/lib389/lib389/cli_conf/replication.py b/src/lib389/lib389/cli_conf/replication.py new file mode 100644 index 000000000..ac34d50a4 --- /dev/null +++ b/src/lib389/lib389/cli_conf/replication.py @@ -0,0 +1,1046 @@ +# --- 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 json +import ldap +from getpass import getpass +from lib389._constants import * +from lib389.changelog import Changelog5 +from lib389.utils import is_a_dn +from lib389.replica import Replicas, BootstrapReplicationManager +from lib389.tasks import CleanAllRUVTask, AbortCleanAllRUVTask + + +arg_to_attr = { + # replica config + 'replica_id': 'nsds5replicaid', + 'repl_purge_delay': 'nsds5replicapurgedelay', + 'repl_tombstone_purge_interval': 'nsds5replicatombstonepurgeinterval', + 'repl_fast_tombstone_purging': 'nsds5ReplicaPreciseTombstonePurging', + 'repl_bind_group': 'nsds5replicabinddngroup', + 'repl_bind_group_interval': 'nsds5replicabinddngroupcheckinterval', + 'repl_protocol_timeout': 'nsds5replicaprotocoltimeout', + 'repl_backoff_min': 'nsds5replicabackoffmin', + 'repl_backoff_max': 'nsds5replicabackoffmax', + 'repl_release_timeout': 'nsds5replicareleasetimeout', + # Changelog + 'max_entries': 'nsslapd-changelogmaxentries', + 'max_age': 'nsslapd-changelogmaxage', + 'compact_interval': 'nsslapd-changelogcompactdb-interval', + 'trim_interval': 'nsslapd-changelogtrim-interval', + 'encrypt_algo': 'nsslapd-encryptionalgorithm', + 'encrypt_key': 'nssymmetrickey', + # Agreement + 'host': 'nsds5replicahost', + 'port': 'nsds5replicaport', + 'conn_protocol': 'nsds5replicatransportinfo', + 'bind_dn': 'nsds5replicabinddn', + 'bind_passwd': 'nsds5replicacredentials', + 'bind_method': 'nsds5replicabindmethod', + 'frac_list': 'nsds5replicatedattributelist', + 'frac_list_total': 'nsds5replicatedattributelisttotal', + 'strip_list': 'nsds5replicastripattrs', + 'schedule': 'nsds5replicaupdateschedule', + 'conn_timeout': 'nsds5replicatimeout', + 'protocol_timeout': 'nsds5replicaprotocoltimeout', + 'wait_async_results': 'nsds5replicawaitforasyncresults', + 'busy_wait_time': 'nsds5replicabusywaittime', + 'session_pause_time': 'nsds5replicaSessionPauseTime', + 'flow_control_window': 'nsds5replicaflowcontrolwindow', + 'flow_control_pause': 'nsds5replicaflowcontrolpause', + # Additional Winsync Agmt attrs + 'win_subtree': 'nsds7windowsreplicasubtree', + 'ds_subtree': 'nsds7directoryreplicasubtree', + 'sync_users': 'nsds7newwinusersyncenabled', + 'sync_groups': 'nsds7newwingroupsyncenabled', + 'win_domain': 'nsds7windowsDomain', + 'sync_interval': 'winsyncinterval', + 'one_way_sync': 'onewaysync', + 'move_action': 'winsyncmoveAction', + 'ds_filter': 'winsyncdirectoryfilter', + 'win_filter': 'winsyncwindowsfilter', + 'subtree_pair': 'winSyncSubtreePair' + } + + +def get_agmt(inst, args, winsync=False): + agmt_name = args.AGMT_NAME[0] + replicas = Replicas(inst) + replica = replicas.get(args.suffix) + agmts = replica.get_agreements(winsync=winsync) + try: + agmt = agmts.get(agmt_name) + except ldap.NO_SUCH_OBJECT: + raise ValueError("Could not find the agreement \"{}\" for suffix \"{}\"".format(agmt_name, args.suffix)) + return agmt + + +def _args_to_attrs(args): + attrs = {} + for arg in vars(args): + val = getattr(args, arg) + if arg in arg_to_attr and val is not None: + attrs[arg_to_attr[arg]] = val + return attrs + + +# +# Replica config +# +def enable_replication(inst, basedn, log, args): + repl_root = args.suffix + role = args.role.lower() + rid = args.replica_id + + if role == "master": + repl_type = '3' + repl_flag = '1' + elif role == "hub": + repl_type = '2' + repl_flag = '1' + elif role == "consumer": + repl_type = '2' + repl_flag = '0' + else: + # error - unknown type + raise ValueError("Unknown replication role ({}), you must use \"master\", \"hub\", or \"consumer\"".format(role)) + + # Start the propeties and update them as needed + repl_properties = { + 'cn': 'replica', + 'nsDS5ReplicaRoot': repl_root, + 'nsDS5Flags': repl_flag, + 'nsDS5ReplicaType': repl_type, + } + + # Validate master settings + if role == "master": + # Do we have a rid? + if not args.replica_id or args.replica_id is None: + # Error, master needs a rid TODO + raise ValueError('You must specify the replica ID (--replica-id) when enabling a \"master\" replica') + + # is it a number? + try: + rid_num = int(rid) + except ValueError: + raise ValueError("--rid expects a number between 1 and 65534") + + # Is it in range? + if rid_num < 1 or rid_num > 65534: + raise ValueError("--replica-id expects a number between 1 and 65534") + + # rid is good add it to the props + repl_properties['nsDS5ReplicaId'] = rid + + # Bind DN or Bind DN Group? + if args.bind_group_dn: + repl_properties['nsDS5ReplicaBindDNGroup'] = args.bind_group_dn + elif args.bind_dn: + repl_properties['nsDS5ReplicaBindDN'] = args.bind_dn + + # First create the changelog + cl = Changelog5(inst) + try: + cl.create(properties={ + 'cn': 'changelog5', + 'nsslapd-changelogdir': inst.get_changelog_dir() + }) + except ldap.ALREADY_EXISTS: + pass + + # Finally enable replication + replicas = Replicas(inst) + try: + replicas.create(properties=repl_properties) + except ldap.ALREADY_EXISTS: + raise ValueError("Replication is already enabled for this suffix") + + print("Replication successfully enabled for \"{}\"".format(repl_root)) + + +def disable_replication(inst, basedn, log, args): + replicas = Replicas(inst) + try: + replica = replicas.get(args.suffix) + replica.delete() + except ldap.NO_SUCH_OBJECT: + raise ValueError("Backend \"{}\" is not enabled for replication".format(args.suffix)) + print("Replication disabled for \"{}\"".format(args.suffix)) + + +def promote_replica(inst, basedn, log, args): + replicas = Replicas(inst) + replica = replicas.get(args.suffix) + role = args.newrole.lower() + + if role == 'master': + newrole = ReplicaRole.MASTER + if args.rreplica_idid is None: + raise ValueError("You need to provide a replica ID (--replica-id) to promote replica to a master") + elif role == 'hub': + newrole = ReplicaRole.HUB + else: + raise ValueError("Invalid role ({}), you must use either \"master\" or \"hub\"".format(role)) + + replica.promote(newrole, binddn=args.bind_dn, binddn_group=args.bind_group_dn, rid=args.replica_id) + print("Successfully promoted replica to \"{}\"".format(role)) + + +def demote_replica(inst, basedn, log, args): + replicas = Replicas(inst) + replica = replicas.get(args.suffix) + role = args.newrole.lower() + + if role == 'hub': + newrole = ReplicaRole.HUB + elif role == 'consumer': + newrole = ReplicaRole.CONSUMER + else: + raise ValueError("Invalid role ({}), you must use either \"hub\" or \"consumer\"".format(role)) + + replica.demote(newrole) + print("Successfully demoted replica to \"{}\"".format(role)) + + +def get_repl_config(inst, basedn, log, args): + replicas = Replicas(inst) + replica = replicas.get(args.suffix) + if args and args.json: + print(replica.get_all_attrs_json()) + else: + log.info(replica.display()) + + +def set_repl_config(inst, basedn, log, args): + replicas = Replicas(inst) + replica = replicas.get(args.suffix) + attrs = _args_to_attrs(args) + op_count = 0 + + # Add supplier DNs + if args.repl_add_bind_dn is not None: + if not is_a_dn(repl_add_bind_dn): + raise ValueError("The replica bind DN is not a valid DN") + replica.add('nsds5ReplicaBindDN', args.repl_add_bind_dn) + op_count += 1 + + # Remove supplier DNs + if args.repl_del_bind_dn is not None: + replica.remove('nsds5ReplicaBindDN', args.repl_del_bind_dn) + op_count += 1 + + # Add referral + if args.repl_add_ref is not None: + replica.add('nsDS5ReplicaReferral', args.repl_add_ref) + op_count += 1 + + # Remove referral + if args.repl_del_ref is not None: + replica.remove('nsDS5ReplicaReferral', args.repl_del_ref) + op_count += 1 + + # Handle the rest of the changes that use mod_replace + modlist = [] + for attr, value in attrs.items(): + modlist.append((attr, value)) + if len(modlist) > 0: + replica.replace_many(*modlist) + elif op_count == 0: + raise ValueError("There are no changes to set in the replica") + print("Successfully updated replication configuration") + + +def create_cl(inst, basedn, log, args): + cl = Changelog5(inst) + try: + cl.create(properties={ + 'cn': 'changelog5', + 'nsslapd-changelogdir': inst.get_changelog_dir() + }) + except ldap.ALREADY_EXISTS: + raise ValueError("Changelog already exists") + print("Successfully created replication changelog") + + +def delete_cl(inst, basedn, log, args): + cl = Changelog5(inst) + try: + cl.delete() + except ldap.NO_SUCH_OBJECT: + raise ValueError("There is no changelog to delete") + print("Successfully deleted replication changelog") + + +def set_cl(inst, basedn, log, args): + cl = Changelog5(inst) + attrs = _args_to_attrs(args) + modlist = [] + for attr, value in attrs.items(): + modlist.append((attr, value)) + if len(modlist) > 0: + cl.replace_many(*modlist) + else: + raise ValueError("There are no changes to set for the replication changelog") + print("Successfully updated replication changelog") + + +def get_cl(inst, basedn, log, args): + cl = Changelog5(inst) + if args and args.json: + print(cl.get_all_attrs_json()) + else: + log.info(cl.display()) + + +def create_repl_manager(inst, basedn, log, args): + manager_cn = "replication manager" + repl_manager_password = "" + repl_manager_password_confirm = "" + + if args.name: + manager_cn = args.name + + if is_a_dn(manager_cn): + # A full DN was provided, make sure it uses "cn" for the RDN + if manager_cn.split("=", 1)[0].lower() != "cn": + raise ValueError("Replication manager DN must use \"cn\" for the rdn attribute") + manager_dn = manager_cn + else: + manager_dn = "cn={},cn=config".format(manager_cn) + + if args.passwd: + repl_manager_password = args.passwd + else: + # Prompt for password + while 1: + while repl_manager_password == "": + repl_manager_password = getpass("Enter replication manager password: ") + while repl_manager_password_confirm == "": + repl_manager_password_confirm = getpass("Confirm replication manager password: ") + if repl_manager_password_confirm == repl_manager_password: + break + else: + print("Passwords do not match!\n") + repl_manager_password = "" + repl_manager_password_confirm = "" + + manager = BootstrapReplicationManager(inst, dn=manager_dn) + try: + manager.create(properties={ + 'cn': manager_cn, + 'userPassword': repl_manager_password + }) + print ("Successfully created replication manager: " + manager_dn) + except ldap.ALREADY_EXISTS: + log.info("Replication Manager ({}) already exists".format(manager_dn)) + + +def del_repl_manager(inst, basedn, log, args): + if is_a_dn(agmt.name): + manager_dn = args.name + else: + manager_dn = "cn={},cn=config".format(args.name) + manager = BootstrapReplicationManager(inst, dn=manager_dn) + manager.delete() + print("Successfully deleted replication manager: " + manager_dn) + + +# +# Agreements +# +def list_agmts(inst, basedn, log, args): + # List regular DS agreements + replicas = Replicas(inst) + replica = replicas.get(args.suffix) + agmts = replica.get_agreements().list() + + result = {"type": "list", "items": []} + for agmt in agmts: + if args.json: + entry = agmt.get_all_attrs_json() + # Append decoded json object, because we are going to dump it later + result['items'].append(json.loads(entry)) + else: + print(agmt.display()) + if args.json: + print(json.dumps(result)) + + +def add_agmt(inst, basedn, log, args): + repl_root = args.suffix + bind_method = args.bind_method.lower() + replicas = Replicas(inst) + replica = replicas.get(args.suffix) + agmts = replica.get_agreements() + + # Process fractional settings + frac_list = None + if args.frac_list: + frac_list = "(objectclass=*) $ EXCLUDE" + for attr in args.frac_list.split(): + frac_list += " " + attr + + frac_total_list = None + if args.frac_list_total: + frac_total_list = "(objectclass=*) $ EXCLUDE" + for attr in args.frac_list_total.split(): + frac_total_list += " " + attr + + # Required properties + properties = { + 'cn': args.AGMT_NAME[0], + 'nsDS5ReplicaRoot': repl_root, + 'description': args.AGMT_NAME[0], + 'nsDS5ReplicaHost': args.host, + 'nsDS5ReplicaPort': args.port, + 'nsDS5ReplicaBindMethod': bind_method, + 'nsDS5ReplicaTransportInfo': args.conn_protocol + } + + # Add optional properties + if args.bind_dn is not None: + if not is_a_dn(args.bind_dn): + raise ValueError("The replica bind DN is not a valid DN") + properties['nsDS5ReplicaBindDN'] = args.bind_dn + if args.bind_passwd is not None: + properties['nsDS5ReplicaCredentials'] = args.bind_passwd + if args.schedule is not None: + properties['nsds5replicaupdateschedule'] = args.schedule + if frac_list is not None: + properties['nsds5replicatedattributelist'] = frac_list + if frac_total_list is not None: + properties['nsds5replicatedattributelisttotal'] = frac_total_list + if args.strip_list is not None: + properties['nsds5replicastripattrs'] = args.strip_list + + # We do need the bind dn and credentials for none-sasl bind methods + if (bind_method == 'simple' or 'sslclientauth') and (args.bind_dn is None or args.bind_passwd is None): + raise ValueError("You need to set the bind dn (--bind-dn) and the password (--bind-passwd) for bind method ({})".format(bind_method)) + + # Create the agmt + try: + agmts.create(properties=properties) + except ldap.ALREADY_EXISTS: + raise ValueError("A replication agreement with the same name already exists") + + print("Successfully created replication agreement \"{}\"".format(args.AGMT_NAME[0])) + if args.init: + init_agmt(inst, basedn, log, args) + + +def delete_agmt(inst, basedn, log, args): + agmt = get_agmt(inst, args) + agmt.delete() + print("Agreement has been successfully deleted") + + +def enable_agmt(inst, basedn, log, args): + agmt = get_agmt(inst, args) + agmt.resume() + print("Agreement has been enabled") + + +def disable_agmt(inst, basedn, log, args): + agmt = get_agmt(inst, args) + agmt.pause() + print("Agreement has been disabled") + + +def init_agmt(inst, basedn, log, args): + agmt = get_agmt(inst, args) + agmt.begin_reinit() + print("Agreement initialization started...") + + +def check_init_agmt(inst, basedn, log, args): + agmt = get_agmt(inst, args) + (done, inprogress, error) = agmt.check_reinit() + status = "Unknown" + if done: + status = "Agreement successfully initialized." + elif inprogress: + status = "Agreement initialization in progress." + elif error: + status = "Agreement initialization failed." + if args.json: + print(json.dumps(status)) + else: + print(status) + + +def set_agmt(inst, basedn, log, args): + agmt = get_agmt(inst, args) + attrs = _args_to_attrs(args) + modlist = [] + for attr, value in attrs.items(): + modlist.append((attr, value)) + if len(modlist) > 0: + agmt.replace_many(*modlist) + else: + raise ValueError("There are no changes to set in the agreement") + print("Successfully updated agreement") + + +def get_repl_agmt(inst, basedn, log, args): + agmt = get_agmt(inst, args) + if args.json: + print(agmt.get_all_attrs_json()) + else: + print(agmt.display()) + + +def poke_agmt(inst, basedn, log, args): + # Send updates now + agmt = get_agmt(inst, args) + agmt.pause() + agmt.resume() + print("Agreement has been poked") + + +def get_agmt_status(inst, basedn, log, args): + agmt = get_agmt(inst, args) + if args.bind_dn is not None and args.bind_passwd is None: + args.bind_passwd = "" + while args.bind_passwd == "": + args.bind_passwd = getpass("Enter password for \"{}\": ".format(args.bind_dn)) + status = agmt.status(use_json=args.json, binddn=args.bind_dn, bindpw=args.bind_passwd) + print(agmt, status) + + +# +# Winsync agreement specfic functions +# +def list_winsync_agmts(inst, basedn, log, args): + # List regular DS agreements + replicas = Replicas(inst) + replica = replicas.get(args.suffix) + agmts = replica.get_agreements(winsync=True).list() + + result = {"type": "list", "items": []} + for agmt in agmts: + if args.json: + entry = agmt.get_all_attrs_json() + # Append decoded json object, because we are going to dump it later + result['items'].append(json.loads(entry)) + else: + print(agmt.display()) + if args.json: + print(json.dumps(result)) + + +def add_winsync_agmt(inst, basedn, log, args): + replicas = Replicas(inst) + replica = replicas.get(args.suffix) + agmts = replica.get_agreements(winsync=True) + + # Process fractional settings + frac_list = None + if args.frac_list: + frac_list = "(objectclass=*) $ EXCLUDE" + for attr in args.frac_list.split(): + frac_list += " " + attr + + if not is_a_dn(args.bind_dn): + raise ValueError("The replica bind DN is not a valid DN") + + # Required properties + properties = { + 'cn': args.AGMT_NAME[0], + 'nsDS5ReplicaRoot': args.suffix, + 'description': args.AGMT_NAME[0], + 'nsDS5ReplicaHost': args.host, + 'nsDS5ReplicaPort': args.port, + 'nsDS5ReplicaTransportInfo': args.conn_protocol, + 'nsDS5ReplicaBindDN': args.bind_dn, + 'nsDS5ReplicaCredentials': args.bind_passwd, + 'nsds7windowsreplicasubtree': args.win_subtree, + 'nsds7directoryreplicasubtree': args.ds_subtree, + 'nsds7windowsDomain': args.win_domain, + } + + # Add optional properties + if args.sync_users is not None: + properties['nsds7newwinusersyncenabled'] = args.sync_users + if args.sync_groups is not None: + properties['nsds7newwingroupsyncenabled'] = args.sync_groups + if args.sync_interval is not None: + properties['winsyncinterval'] = args.sync_interval + if args.one_way_sync is not None: + properties['onewaysync'] = args.one_way_sync + if args.move_action is not None: + properties['winsyncmoveAction'] = args.move_action + if args.ds_filter is not None: + properties['winsyncdirectoryfilter'] = args.ds_filter + if args.win_filter is not None: + properties['winsyncwindowsfilter'] = args.win_filter + if args.schedule is not None: + properties['nsds5replicaupdateschedule'] = args.schedule + if frac_list is not None: + properties['nsds5replicatedattributelist'] = frac_list + + # Create the agmt + try: + agmts.create(properties=properties) + except ldap.ALREADY_EXISTS: + raise ValueError("A replication agreement with the same name already exists") + + print("Successfully created winsync replication agreement \"{}\"".format(args.AGMT_NAME[0])) + if args.init: + init_winsync_agmt(inst, basedn, log, args) + + +def delete_winsync_agmt(inst, basedn, log, args): + agmt = get_agmt(inst, args, winsync=True) + agmt.delete() + print("Agreement has been successfully deleted") + + +def set_winsync_agmt(inst, basedn, log, args): + agmt = get_agmt(inst, args, winsync=True) + + attrs = _args_to_attrs(args) + modlist = [] + for attr, value in attrs.items(): + modlist.append((attr, value)) + if len(modlist) > 0: + agmt.replace_many(*modlist) + else: + raise ValueError("There are no changes to set in the agreement") + print("Successfully updated agreement") + + +def enable_winsync_agmt(inst, basedn, log, args): + agmt = get_agmt(inst, args, winsync=True) + agmt.resume() + print("Agreement has been enabled") + + +def disable_winsync_agmt(inst, basedn, log, args): + agmt = get_agmt(inst, args, winsync=True) + agmt.pause() + print("Agreement has been disabled") + + +def init_winsync_agmt(inst, basedn, log, args): + agmt = get_agmt(inst, args, winsync=True) + agmt.begin_reinit() + print("Agreement initialization started...") + + +def check_winsync_init_agmt(inst, basedn, log, args): + agmt = get_agmt(inst, args, winsync=True) + (done, inprogress, error) = agmt.check_reinit() + status = "Unknown" + if done: + status = "Agreement successfully initialized." + elif inprogress: + status = "Agreement initialization in progress." + elif error: + status = "Agreement initialization failed." + if args.json: + print(json.dumps(status)) + else: + print(status) + + +def get_winsync_agmt(inst, basedn, log, args): + agmt = get_agmt(inst, args, winsync=True) + if args.json: + print(agmt.get_all_attrs_json()) + else: + print(agmt.display()) + + +def poke_winsync_agmt(inst, basedn, log, args): + # Send updates now + agmt = get_agmt(inst, args, winsync=True) + agmt.pause() + agmt.resume() + print("Agreement has been poked") + + +def get_winsync_agmt_status(inst, basedn, log, args): + agmt = get_agmt(inst, args, winsync=True) + status = agmt.status(winsync=True, use_json=args.json) + print(agmt, status) + + +# +# Tasks +# +def run_cleanallruv(inst, basedn, log, args): + properties = {'replica-base-dn': args.suffix, + 'replica-id': args.replica_id} + if args.force_cleaning: + properties['replica-force-cleaning'] = args.force_cleaning + clean_task = CleanAllRUVTask(inst) + clean_task.create(properties=properties) + + +def abort_cleanallruv(inst, basedn, log, args): + properties = {'replica-base-dn': args.suffix, + 'replica-id': args.replica_id} + if args.certify: + properties['replica-certify-all'] = args.certify + clean_task = AbortCleanAllRUVTask(inst) + clean_task.create(properties=properties) + + +def create_parser(subparsers): + + ############################################ + # Replication Configuration + ############################################ + + repl_parser = subparsers.add_parser('replication', help='Configure replication for a suffix') + repl_subcommands = repl_parser.add_subparsers(help='Replication Configuration') + + repl_enable_parser = repl_subcommands.add_parser('enable', help='Enable replication for a suffix') + repl_enable_parser.set_defaults(func=enable_replication) + repl_enable_parser.add_argument('--suffix', required=True, help='The DN of the suffix to be enabled for replication') + repl_enable_parser.add_argument('--role', required=True, help="The Replication role: \"master\", \"hub\", or \"consumer\"") + repl_enable_parser.add_argument('--replica-id', help="The replication identifier for a \"master\". Values range from 1 - 65534") + repl_enable_parser.add_argument('--bind-group-dn', help="A group entry DN containing members that are \"bind/supplier\" DNs") + repl_enable_parser.add_argument('--bind-dn', help="The Bind or Supplier DN that can make replication updates") + + repl_disable_parser = repl_subcommands.add_parser('disable', help='Disable replication for a suffix') + repl_disable_parser.set_defaults(func=disable_replication) + repl_disable_parser.add_argument('--suffix', required=True, help='The DN of the suffix to have replication disabled') + + repl_promote_parser = repl_subcommands.add_parser('promote', help='Promte replica to a Hub or Master') + repl_promote_parser.set_defaults(func=promote_replica) + repl_promote_parser.add_argument('--suffix', required=True, help="The DN of the replication suffix to promote") + repl_promote_parser.add_argument('--newrole', required=True, help='Promote this replica to a \"hub\" or \"master\"') + repl_promote_parser.add_argument('--replica-id', help="The replication identifier for a \"master\". Values range from 1 - 65534") + repl_promote_parser.add_argument('--bind-group-dn', help="A group entry DN containing members that are \"bind/supplier\" DNs") + repl_promote_parser.add_argument('--bind-dn', help="The Bind or Supplier DN that can make replication updates") + + repl_add_manager_parser = repl_subcommands.add_parser('create-manager', help='Create a replication manager entry') + repl_add_manager_parser.set_defaults(func=create_repl_manager) + repl_add_manager_parser.add_argument('--name', help="The NAME of the new replication manager entry under cn=config: \"cn=NAME,cn=config\"") + repl_add_manager_parser.add_argument('--passwd', help="Password for replication manager. If not provided, you will be prompted for the password") + + repl_del_manager_parser = repl_subcommands.add_parser('delete-manager', help='Delete a replication manager entry') + repl_del_manager_parser.set_defaults(func=del_repl_manager) + repl_del_manager_parser.add_argument('--name', help="The NAME of the replication manager entry under cn=config: \"cn=NAME,cn=config\"") + + repl_demote_parser = repl_subcommands.add_parser('demote', help='Demote replica to a Hub or Consumer') + repl_demote_parser.set_defaults(func=demote_replica) + repl_demote_parser.add_argument('--suffix', required=True, help="Promte this replica to a \"hub\" or \"consumer\"") + repl_demote_parser.add_argument('--newrole', required=True, help="The Replication role: \"hub\", or \"consumer\"") + + repl_get_parser = repl_subcommands.add_parser('get', help='Get replication configuration') + repl_get_parser.set_defaults(func=get_repl_config) + repl_get_parser.add_argument('--suffix', required=True, help='Get the replication configuration for this suffix DN') + + repl_create_cl = repl_subcommands.add_parser('create-changelog', help='Create the replication changelog') + repl_create_cl.set_defaults(func=create_cl) + + repl_delete_cl = repl_subcommands.add_parser('delete-changelog', help='Delete the replication changelog. This will invalidate any existing replication agreements') + repl_delete_cl.set_defaults(func=delete_cl) + + repl_set_cl = repl_subcommands.add_parser('set-changelog', help='Delete the replication changelog. This will invalidate any existing replication agreements') + repl_set_cl.set_defaults(func=set_cl) + repl_set_cl.add_argument('--max-entries', help="The maximum number of entries to get in the replication changelog") + repl_set_cl.add_argument('--max-age', help="The maximum age of a replication changelog entry") + repl_set_cl.add_argument('--compact-interval', help="The replication changelog compaction interval") + repl_set_cl.add_argument('--trim-interval', help="The interval to check if the replication changelog can be trimmed") + repl_set_cl.add_argument('--encrypt-algo', help="The encryption algorithm used to encrypt the replication changelog content. Requires that TLS is enabled in the server") + repl_set_cl.add_argument('--encrypt-key', help="The symmetric key for the replication changelog encryption") + + repl_get_cl = repl_subcommands.add_parser('get-changelog', help='Delete the replication changelog. This will invalidate any existing replication agreements') + repl_get_cl.set_defaults(func=get_cl) + + repl_set_parser = repl_subcommands.add_parser('set', help='Set an attribute in the replication configuration') + repl_set_parser.set_defaults(func=set_repl_config) + repl_set_parser.add_argument('--suffix', required=True, help='The DN of the replication suffix') + repl_set_parser.add_argument('--replica-id', help="The Replication Identifier number") + repl_set_parser.add_argument('--replica-role', help="The Replication role: master, hub, or consumer") + + repl_set_parser.add_argument('--repl-add-bind-dn', help="Add a bind (supplier) DN") + repl_set_parser.add_argument('--repl-del-bind-dn', help="Remove a bind (supplier) DN") + repl_set_parser.add_argument('--repl-add-ref', help="Add a replication referral (for consumers only)") + repl_set_parser.add_argument('--repl-del-ref', help="Remove a replication referral (for conusmers only)") + repl_set_parser.add_argument('--repl-purge-delay', help="The replication purge delay") + repl_set_parser.add_argument('--repl-tombstone-purge-interval', help="The interval in seconds to check for tombstones that can be purged") + repl_set_parser.add_argument('--repl-fast-tombstone-purging', help="Set to \"on\" to improve tombstone purging performance") + repl_set_parser.add_argument('--repl-bind-group', help="A group entry DN containing members that are \"bind/supplier\" DNs") + repl_set_parser.add_argument('--repl-bind-group-interval', help="An interval in seconds to check if the bind group has been updated") + repl_set_parser.add_argument('--repl-protocol-timeout', help="A timeout in seconds on how long to wait before stopping " + "replication when the server is under load") + repl_set_parser.add_argument('--repl-backoff-max', help="The maximum time in seconds a replication agreement should stay in a backoff state " + "while waiting to acquire the consumer. Default is 300 seconds") + repl_set_parser.add_argument('--repl-backoff-min', help="The starting time in seconds a replication agreement should stay in a backoff state " + "while waiting to acquire the consumer. Default is 3 seconds") + repl_set_parser.add_argument('--repl-release-timeout', help="A timeout in seconds a replication master should send " + "updates before it yields its replication session") + + ############################################ + # Replication Agmts + ############################################ + + agmt_parser = subparsers.add_parser('repl-agmt', help='Manage replication agreements') + agmt_subcommands = agmt_parser.add_subparsers(help='Replication Agreement Configuration') + + # List + agmt_list_parser = agmt_subcommands.add_parser('list', help='List all the replication agreements') + agmt_list_parser.set_defaults(func=list_agmts) + agmt_list_parser.add_argument('--suffix', required=True, help='The DN of the suffix to look up replication agreements') + agmt_list_parser.add_argument('--entry', help='Return the entire entry for each agreement') + + # Enable + agmt_enable_parser = agmt_subcommands.add_parser('enable', help='Enable replication agreement') + agmt_enable_parser.set_defaults(func=enable_agmt) + agmt_enable_parser.add_argument('AGMT_NAME', nargs=1, help='The name of the replication agreement') + agmt_enable_parser.add_argument('--suffix', required=True, help="The DN of the replication suffix") + + # Disable + agmt_disable_parser = agmt_subcommands.add_parser('disable', help='Disable replication agreement') + agmt_disable_parser.set_defaults(func=disable_agmt) + agmt_disable_parser.add_argument('AGMT_NAME', nargs=1, help='The name of the replication agreement') + agmt_disable_parser.add_argument('--suffix', required=True, help="The DN of the replication suffix") + + # Initialize + agmt_init_parser = agmt_subcommands.add_parser('init', help='Initialize replication agreement') + agmt_init_parser.set_defaults(func=init_agmt) + agmt_init_parser.add_argument('AGMT_NAME', nargs=1, help='The name of the replication agreement') + agmt_init_parser.add_argument('--suffix', required=True, help="The DN of the replication suffix") + + # Check Initialization progress + agmt_check_init_parser = agmt_subcommands.add_parser('init-status', help='Check the agreement initialization status') + agmt_check_init_parser.set_defaults(func=check_init_agmt) + agmt_check_init_parser.add_argument('AGMT_NAME', nargs=1, help='The name of the replication agreement') + agmt_check_init_parser.add_argument('--suffix', required=True, help="The DN of the replication suffix") + + # Send Updates Now + agmt_poke_parser = agmt_subcommands.add_parser('poke', help='Trigger replication to send updates now') + agmt_poke_parser.set_defaults(func=poke_agmt) + agmt_poke_parser.add_argument('AGMT_NAME', nargs=1, help='The name of the replication agreement') + agmt_poke_parser.add_argument('--suffix', required=True, help="The DN of the replication suffix") + + # Status + agmt_status_parser = agmt_subcommands.add_parser('status', help='Get the current status of the replication agreement') + agmt_status_parser.set_defaults(func=get_agmt_status) + agmt_status_parser.add_argument('AGMT_NAME', nargs=1, help='The name of the replication agreement') + agmt_status_parser.add_argument('--suffix', required=True, help="The DN of the replication suffix") + agmt_status_parser.add_argument('--bind-dn', help="Set the DN to bind to the consumer") + agmt_status_parser.add_argument('--bind-passwd', help="The password for the bind DN") + + # Delete + agmt_del_parser = agmt_subcommands.add_parser('delete', help='Delete replication agreement') + agmt_del_parser.set_defaults(func=delete_agmt) + agmt_del_parser.add_argument('AGMT_NAME', nargs=1, help='The name of the replication agreement') + agmt_del_parser.add_argument('--suffix', required=True, help="The DN of the replication suffix") + + # Create + agmt_add_parser = agmt_subcommands.add_parser('create', help='Initialize replication agreement') + agmt_add_parser.set_defaults(func=add_agmt) + agmt_add_parser.add_argument('AGMT_NAME', nargs=1, help='The name of the replication agreement') + agmt_add_parser.add_argument('--suffix', required=True, help="The DN of the replication suffix") + agmt_add_parser.add_argument('--host', required=True, help="The hostname of the remote replica") + agmt_add_parser.add_argument('--port', required=True, help="The port number of the remote replica") + agmt_add_parser.add_argument('--conn-protocol', required=True, help="The replication connection protocol: LDAP, LDAPS, or StartTLS") + agmt_add_parser.add_argument('--bind-dn', help="The Bind DN the agreement uses to authenticate to the replica") + agmt_add_parser.add_argument('--bind-passwd', help="The credentials for the Bind DN") + agmt_add_parser.add_argument('--bind-method', required=True, help="The bind method: \"SIMPLE\", \"SSLCLIENTAUTH\", \"SASL/DIGEST\", or \"SASL/GSSAPI\"") + agmt_add_parser.add_argument('--frac-list', help="List of attributes to NOT replicate to the consumer during incremental updates") + agmt_add_parser.add_argument('--frac-list-total', help="List of attributes to NOT replicate during a total initialization") + agmt_add_parser.add_argument('--strip-list', help="A list of attributes that are removed from updates only if the event " + "would otherwise be empty. Typically this is set to \"modifiersname\" and \"modifytimestmap\"") + agmt_add_parser.add_argument('--schedule', help="Sets the replication update schedule: 'HHMM-HHMM DDDDDDD' D = 0-6 (Sunday - Saturday).") + agmt_add_parser.add_argument('--conn-timeout', help="The timeout used for replicaton connections") + agmt_add_parser.add_argument('--protocol-timeout', help="A timeout in seconds on how long to wait before stopping " + "replication when the server is under load") + agmt_add_parser.add_argument('--wait-async-results', help="The amount of time in milliseconds the server waits if " + "the consumer is not ready before resending data") + agmt_add_parser.add_argument('--busy-wait-time', help="The amount of time in seconds a supplier should wait after " + "a consumer sends back a busy response before making another " + "attempt to acquire access.") + agmt_add_parser.add_argument('--session-pause-time', help="The amount of time in seconds a supplier should wait between update sessions.") + agmt_add_parser.add_argument('--flow-control-window', help="Sets the maximum number of entries and updates sent by a supplier, which are not acknowledged by the consumer.") + agmt_add_parser.add_argument('--flow-control-pause', help="The time in milliseconds to pause after reaching the number of entries and updates set in \"--flow-control-window\"") + agmt_add_parser.add_argument('--init', action='store_true', default=False, help="Initialize the agreement after creating it.") + + # Set - Note can not use add's parent args because for "set" there are no "required=True" args + agmt_set_parser = agmt_subcommands.add_parser('set', help='Set an attribute in the replication agreement') + agmt_set_parser.set_defaults(func=set_agmt) + agmt_set_parser.add_argument('AGMT_NAME', nargs=1, help='The name of the replication agreement') + agmt_set_parser.add_argument('--suffix', required=True, help="The DN of the replication suffix") + agmt_set_parser.add_argument('--host', help="The hostname of the remote replica") + agmt_set_parser.add_argument('--port', help="The port number of the remote replica") + agmt_set_parser.add_argument('--conn-protocol', help="The replication connection protocol: LDAP, LDAPS, or StartTLS") + agmt_set_parser.add_argument('--bind-dn', help="The Bind DN the agreement uses to authenticate to the replica") + agmt_set_parser.add_argument('--bind-passwd', help="The credentials for the Bind DN") + agmt_set_parser.add_argument('--bind-method', help="The bind method: \"SIMPLE\", \"SSLCLIENTAUTH\", \"SASL/DIGEST\", or \"SASL/GSSAPI\"") + agmt_set_parser.add_argument('--frac-list', help="List of attributes to NOT replicate to the consumer during incremental updates") + agmt_set_parser.add_argument('--frac-list-total', help="List of attributes to NOT replicate during a total initialization") + agmt_set_parser.add_argument('--strip-list', help="A list of attributes that are removed from updates only if the event " + "would otherwise be empty. Typically this is set to \"modifiersname\" and \"modifytimestmap\"") + agmt_set_parser.add_argument('--schedule', help="Sets the replication update schedule: 'HHMM-HHMM DDDDDDD' D = 0-6 (Sunday - Saturday).") + agmt_set_parser.add_argument('--conn-timeout', help="The timeout used for replicaton connections") + agmt_set_parser.add_argument('--protocol-timeout', help="A timeout in seconds on how long to wait before stopping " + "replication when the server is under load") + agmt_set_parser.add_argument('--wait-async-results', help="The amount of time in milliseconds the server waits if " + "the consumer is not ready before resending data") + agmt_set_parser.add_argument('--busy-wait-time', help="The amount of time in seconds a supplier should wait after " + "a consumer sends back a busy response before making another " + "attempt to acquire access.") + agmt_set_parser.add_argument('--session-pause-time', help="The amount of time in seconds a supplier should wait between update sessions.") + agmt_set_parser.add_argument('--flow-control-window', help="Sets the maximum number of entries and updates sent by a supplier, which are not acknowledged by the consumer.") + agmt_set_parser.add_argument('--flow-control-pause', help="The time in milliseconds to pause after reaching the number of entries and updates set in \"--flow-control-window\"") + + # Get + agmt_get_parser = agmt_subcommands.add_parser('get', help='Get replication configuration') + agmt_get_parser.set_defaults(func=get_repl_agmt) + agmt_get_parser.add_argument('AGMT_NAME', nargs=1, help='Get the replication configuration for this suffix DN') + agmt_get_parser.add_argument('--suffix', required=True, help="The DN of the replication suffix") + + ############################################ + # Replication Winsync Agmts + ############################################ + + winsync_parser = subparsers.add_parser('repl-winsync-agmt', help='Manage Winsync Agreements') + winsync_agmt_subcommands = winsync_parser.add_subparsers(help='Replication Winsync Agreement Configuration') + + # List + winsync_agmt_list_parser = winsync_agmt_subcommands.add_parser('list', help='List all the replication winsync agreements') + winsync_agmt_list_parser.set_defaults(func=list_winsync_agmts) + winsync_agmt_list_parser.add_argument('--suffix', required=True, help='The DN of the suffix to look up replication winsync agreements') + + # Enable + winsync_agmt_enable_parser = winsync_agmt_subcommands.add_parser('enable', help='Enable replication winsync agreement') + winsync_agmt_enable_parser.set_defaults(func=enable_winsync_agmt) + winsync_agmt_enable_parser.add_argument('AGMT_NAME', nargs=1, help='The name of the replication winsync agreement') + winsync_agmt_enable_parser.add_argument('--suffix', required=True, help="The DN of the replication winsync suffix") + + # Disable + winsync_agmt_disable_parser = winsync_agmt_subcommands.add_parser('disable', help='Disable replication winsync agreement') + winsync_agmt_disable_parser.set_defaults(func=disable_winsync_agmt) + winsync_agmt_disable_parser.add_argument('AGMT_NAME', nargs=1, help='The name of the replication winsync agreement') + winsync_agmt_disable_parser.add_argument('--suffix', required=True, help="The DN of the replication winsync suffix") + + # Initialize + winsync_agmt_init_parser = winsync_agmt_subcommands.add_parser('init', help='Initialize replication winsync agreement') + winsync_agmt_init_parser.set_defaults(func=init_winsync_agmt) + winsync_agmt_init_parser.add_argument('AGMT_NAME', nargs=1, help='The name of the replication winsync agreement') + winsync_agmt_init_parser.add_argument('--suffix', required=True, help="The DN of the replication winsync suffix") + + # Check Initialization progress + winsync_agmt_check_init_parser = winsync_agmt_subcommands.add_parser('init-status', help='Check the agreement initialization status') + winsync_agmt_check_init_parser.set_defaults(func=check_winsync_init_agmt) + winsync_agmt_check_init_parser.add_argument('AGMT_NAME', nargs=1, help='The name of the replication agreement') + winsync_agmt_check_init_parser.add_argument('--suffix', required=True, help="The DN of the replication suffix") + + # Send Updates Now + winsync_agmt_poke_parser = winsync_agmt_subcommands.add_parser('poke', help='Trigger replication to send updates now') + winsync_agmt_poke_parser.set_defaults(func=poke_winsync_agmt) + winsync_agmt_poke_parser.add_argument('AGMT_NAME', nargs=1, help='The name of the replication winsync agreement') + winsync_agmt_poke_parser.add_argument('--suffix', required=True, help="The DN of the replication winsync suffix") + + # Status + winsync_agmt_status_parser = winsync_agmt_subcommands.add_parser('status', help='Get the current status of the replication agreement') + winsync_agmt_status_parser.set_defaults(func=get_winsync_agmt_status) + winsync_agmt_status_parser.add_argument('AGMT_NAME', nargs=1, help='The name of the replication agreement') + winsync_agmt_status_parser.add_argument('--suffix', required=True, help="The DN of the replication suffix") + + # Delete + winsync_agmt_del_parser = winsync_agmt_subcommands.add_parser('delete', help='Delete replication winsync agreement') + winsync_agmt_del_parser.set_defaults(func=delete_winsync_agmt) + winsync_agmt_del_parser.add_argument('AGMT_NAME', nargs=1, help='The name of the replication winsync agreement') + winsync_agmt_del_parser.add_argument('--suffix', required=True, help="The DN of the replication winsync suffix") + + # Create + winsync_agmt_add_parser = winsync_agmt_subcommands.add_parser('create', help='Initialize replication winsync agreement') + winsync_agmt_add_parser.set_defaults(func=add_winsync_agmt) + winsync_agmt_add_parser.add_argument('AGMT_NAME', nargs=1, help='The name of the replication winsync agreement') + winsync_agmt_add_parser.add_argument('--suffix', required=True, help="The DN of the replication winsync suffix") + winsync_agmt_add_parser.add_argument('--host', required=True, help="The hostname of the AD server") + winsync_agmt_add_parser.add_argument('--port', required=True, help="The port number of the AD server") + winsync_agmt_add_parser.add_argument('--conn-protocol', required=True, help="The replication winsync connection protocol: LDAP, LDAPS, or StartTLS") + winsync_agmt_add_parser.add_argument('--bind-dn', required=True, help="The Bind DN the agreement uses to authenticate to the AD Server") + winsync_agmt_add_parser.add_argument('--bind-passwd', required=True, help="The credentials for the Bind DN") + winsync_agmt_add_parser.add_argument('--frac-list', help="List of attributes to NOT replicate to the consumer during incremental updates") + winsync_agmt_add_parser.add_argument('--schedule', help="Sets the replication update schedule") + winsync_agmt_add_parser.add_argument('--win-subtree', required=True, help="The suffix of the AD Server") + winsync_agmt_add_parser.add_argument('--ds-subtree', required=True, help="The Directory Server suffix") + winsync_agmt_add_parser.add_argument('--win-domain', required=True, help="The AD Domain") + winsync_agmt_add_parser.add_argument('--sync-users', help="Synchronize Users between AD and DS") + winsync_agmt_add_parser.add_argument('--sync-groups', help="Synchronize Groups between AD and DS") + winsync_agmt_add_parser.add_argument('--sync-interval', help="The interval that DS checks AD for changes in entries") + winsync_agmt_add_parser.add_argument('--one-way-sync', help="Sets which direction to perform synchronization: \"toWindows\", \"fromWindows\", \"both\"") + winsync_agmt_add_parser.add_argument('--move-action', help="Sets instructions on how to handle moved or deleted entries: \"none\", \"unsync\", or \"delete\"") + winsync_agmt_add_parser.add_argument('--win-filter', help="Custom filter for finding users in AD Server") + winsync_agmt_add_parser.add_argument('--ds-filter', help="Custom filter for finding AD users in DS Server") + winsync_agmt_add_parser.add_argument('--subtree-pair', help="Set the subtree pair: <DS_SUBTREE>:<WINDOWS_SUBTREE>") + winsync_agmt_add_parser.add_argument('--conn-timeout', help="The timeout used for replicaton connections") + winsync_agmt_add_parser.add_argument('--busy-wait-time', help="The amount of time in seconds a supplier should wait after " + "a consumer sends back a busy response before making another " + "attempt to acquire access.") + winsync_agmt_add_parser.add_argument('--session-pause-time', help="The amount of time in seconds a supplier should wait between update sessions.") + winsync_agmt_add_parser.add_argument('--init', action='store_true', default=False, help="Initialize the agreement after creating it.") + + # Set - Note can not use add's parent args because for "set" there are no "required=True" args + winsync_agmt_set_parser = winsync_agmt_subcommands.add_parser('set', help='Set an attribute in the replication winsync agreement') + winsync_agmt_set_parser.set_defaults(func=set_winsync_agmt) + winsync_agmt_set_parser.add_argument('AGMT_NAME', nargs=1, help='The name of the replication winsync agreement') + winsync_agmt_set_parser.add_argument('--suffix', help="The DN of the replication winsync suffix") + winsync_agmt_set_parser.add_argument('--host', help="The hostname of the AD server") + winsync_agmt_set_parser.add_argument('--port', help="The port number of the AD server") + winsync_agmt_set_parser.add_argument('--conn-protocol', help="The replication winsync connection protocol: LDAP, LDAPS, or StartTLS") + winsync_agmt_set_parser.add_argument('--bind-dn', help="The Bind DN the agreement uses to authenticate to the AD Server") + winsync_agmt_set_parser.add_argument('--bind-passwd', help="The credentials for the Bind DN") + winsync_agmt_set_parser.add_argument('--frac-list', help="List of attributes to NOT replicate to the consumer during incremental updates") + winsync_agmt_set_parser.add_argument('--schedule', help="Sets the replication update schedule") + winsync_agmt_set_parser.add_argument('--win-subtree', help="The suffix of the AD Server") + winsync_agmt_set_parser.add_argument('--ds-subtree', help="The Directory Server suffix") + winsync_agmt_set_parser.add_argument('--win-domain', help="The AD Domain") + winsync_agmt_set_parser.add_argument('--sync-users', help="Synchronize Users between AD and DS") + winsync_agmt_set_parser.add_argument('--sync-groups', help="Synchronize Groups between AD and DS") + winsync_agmt_set_parser.add_argument('--sync-interval', help="The interval that DS checks AD for changes in entries") + winsync_agmt_set_parser.add_argument('--one-way-sync', help="Sets which direction to perform synchronization: \"toWindows\", \"fromWindows\", \"both\"") + winsync_agmt_set_parser.add_argument('--move-action', help="Sets instructions on how to handle moved or deleted entries: \"none\", \"unsync\", or \"delete\"") + winsync_agmt_set_parser.add_argument('--win-filter', help="Custom filter for finding users in AD Server") + winsync_agmt_set_parser.add_argument('--ds-filter', help="Custom filter for finding AD users in DS Server") + winsync_agmt_set_parser.add_argument('--subtree-pair', help="Set the subtree pair: <DS_SUBTREE>:<WINDOWS_SUBTREE>") + winsync_agmt_set_parser.add_argument('--conn-timeout', help="The timeout used for replicaton connections") + winsync_agmt_set_parser.add_argument('--busy-wait-time', help="The amount of time in seconds a supplier should wait after " + "a consumer sends back a busy response before making another " + "attempt to acquire access.") + winsync_agmt_set_parser.add_argument('--session-pause-time', help="The amount of time in seconds a supplier should wait between update sessions.") + + # Get + winsync_agmt_get_parser = winsync_agmt_subcommands.add_parser('get', help='Get replication configuration') + winsync_agmt_get_parser.set_defaults(func=get_winsync_agmt) + winsync_agmt_get_parser.add_argument('AGMT_NAME', nargs=1, help='Get the replication configuration for this suffix DN') + winsync_agmt_get_parser.add_argument('--suffix', required=True, help="The DN of the replication suffix") + + ############################################ + # Replication Tasks (cleanalruv) + ############################################ + + tasks_parser = subparsers.add_parser('repl-tasks', help='Manage local (user/subtree) password policies') + task_subcommands = tasks_parser.add_subparsers(help='Replication Tasks') + + # Cleanallruv + task_cleanallruv = task_subcommands.add_parser('cleanallruv', help='Cleanup old/removed replica IDs') + task_cleanallruv.set_defaults(func=run_cleanallruv) + task_cleanallruv.add_argument('--suffix', required=True, help="The Directory Server suffix") + task_cleanallruv.add_argument('--replica-id', required=True, help="The replica ID to remove/clean") + task_cleanallruv.add_argument('--force-cleaning', action='store_true', default=False, + help="Ignore errors and do a best attempt to clean all the replicas") + + # Abort cleanallruv + task_abort_cleanallruv = task_subcommands.add_parser('abort-cleanallruv', help='Set an attribute in the replication winsync agreement') + task_abort_cleanallruv.set_defaults(func=abort_cleanallruv) + task_abort_cleanallruv.add_argument('--suffix', required=True, help="The Directory Server suffix") + task_abort_cleanallruv.add_argument('--replica-id', required=True, help="The replica ID of the cleaning task to abort") + task_abort_cleanallruv.add_argument('--certify', action='store_true', default=False, + help="Enforce that the abort task completed on all replicas") + + diff --git a/src/lib389/lib389/pwpolicy.py b/src/lib389/lib389/pwpolicy.py index 0f152b9ce..d665d1f72 100644 --- a/src/lib389/lib389/pwpolicy.py +++ b/src/lib389/lib389/pwpolicy.py @@ -7,14 +7,11 @@ # --- END COPYRIGHT BLOCK --- import ldap -import json -from ldap import modlist from lib389._mapped_object import DSLdapObject, DSLdapObjects from lib389.config import Config -from lib389.idm.account import Account, Accounts +from lib389.idm.account import Account from lib389.idm.nscontainer import nsContainers, nsContainer from lib389.cos import CosPointerDefinitions, CosPointerDefinition, CosTemplates -from lib389.utils import ensure_str, ensure_list_str, ensure_bytes USER_POLICY = 1 SUBTREE_POLICY = 2 @@ -146,6 +143,9 @@ class PwPolicyManager(object): # Add policy to the entry user_entry.replace('pwdpolicysubentry', pwp_entry.dn) + # make sure that local policies are enabled + self.set_global_policy({'nsslapd-pwpolicy-local': 'on'}) + return pwp_entry def create_subtree_policy(self, dn, properties): @@ -187,6 +187,9 @@ class PwPolicyManager(object): 'cosTemplateDn': cos_template.dn, 'cn': 'nsPwPolicy_CoS'}) + # make sure that local policies are enabled + self.set_global_policy({'nsslapd-pwpolicy-local': 'on'}) + return pwp_entry def get_pwpolicy_entry(self, dn): diff --git a/src/lib389/lib389/replica.py b/src/lib389/lib389/replica.py index cde310937..348a7b403 100644 --- a/src/lib389/lib389/replica.py +++ b/src/lib389/lib389/replica.py @@ -7,7 +7,6 @@ # --- END COPYRIGHT BLOCK --- import ldap -import os import decimal import time import logging @@ -17,8 +16,6 @@ from itertools import permutations from lib389._constants import * from lib389.properties import * from lib389.utils import normalizeDN, escapeDNValue, ensure_bytes, ensure_str, ensure_list_str, ds_is_older -from lib389._replication import RUV -from lib389.repltools import ReplTools from lib389 import DirSrv, Entry, NoSuchEntryError, InvalidArgumentError from lib389._mapped_object import DSLdapObjects, DSLdapObject from lib389.passwd import password_generate @@ -27,13 +24,10 @@ from lib389.agreement import Agreements from lib389.changelog import Changelog5 from lib389.idm.domain import Domain - from lib389.idm.group import Groups from lib389.idm.services import ServiceAccounts from lib389.idm.organizationalunit import OrganizationalUnits -from lib389.agreement import Agreements - class ReplicaLegacy(object): proxied_methods = 'search_s getEntry'.split() @@ -883,6 +877,7 @@ class RUV(object): return False return True + class Replica(DSLdapObject): """Replica DSLdapObject with: - must attributes = ['cn', 'nsDS5ReplicaType', 'nsDS5ReplicaRoot', @@ -987,29 +982,38 @@ class Replica(DSLdapObject): def _delete_agreements(self): """Delete all the agreements for the suffix - :raises: LDAPError - If failing to delete or search for agreeme :type binddn: strnts + :raises: LDAPError - If failing to delete or search for agreements """ # Get the suffix self._populate_suffix() + + # Delete standard agmts agmts = self.get_agreements() for agmt in agmts.list(): agmt.delete() - def promote(self, newrole, binddn=None, rid=None): + # Delete winysnc agmts + agmts = self.get_agreements(winsync=True) + for agmt in agmts.list(): + agmt.delete() + + def promote(self, newrole, binddn=None, binddn_group=None, rid=None): """Promote the replica to hub or master :param newrole: The new replication role for the replica: MASTER and HUB :type newrole: ReplicaRole :param binddn: The replication bind dn - only applied to master :type binddn: str + :param binddn_group: The replication bind dn group - only applied to master + :type binddn: str :param rid: The replication ID, applies only to promotions to "master" :type rid: int - :returns: None :raises: ValueError - If replica is not promoted """ - if not binddn: + + if binddn is None and binddn_group is None: binddn = defaultProperties[REPLICATION_BIND_DN] # Check the role type @@ -1025,8 +1029,14 @@ class Replica(DSLdapObject): rid = CONSUMER_REPLICAID # Create the changelog + cl = Changelog5(self._instance) try: - self._instance.changelog.create() + cl.create(properties={ + 'cn': 'changelog5', + 'nsslapd-changelogdir': self._instance.get_changelog_dir() + }) + except ldap.ALREADY_EXISTS: + pass except ldap.LDAPError as e: raise ValueError('Failed to create changelog: %s' % str(e)) @@ -1044,7 +1054,10 @@ class Replica(DSLdapObject): # Set bind dn try: - self.set(REPL_BINDDN, binddn) + if binddn: + self.set(REPL_BINDDN, binddn) + else: + self.set(REPL_BIND_GROUP, binddn_group) except ldap.LDAPError as e: raise ValueError('Failed to update replica: ' + str(e)) @@ -1169,12 +1182,13 @@ class Replica(DSLdapObject): return True - def get_agreements(self): + def get_agreements(self, winsync=False): """Return the set of agreements related to this suffix replica - + :param: winsync: If True then return winsync replication agreements, + otherwise return teh standard replication agreements. :returns: Agreements object """ - return Agreements(self._instance, self.dn) + return Agreements(self._instance, self.dn, winsync=winsync) def get_rid(self): """Return the current replicas RID for this suffix @@ -1187,6 +1201,7 @@ class Replica(DSLdapObject): """Return the in memory ruv of this replica suffix. :returns: RUV object + :raises: LDAPError """ self._populate_suffix() @@ -1201,11 +1216,29 @@ class Replica(DSLdapObject): return RUV(data) + def get_ruv_agmt_maxcsns(self): + """Return the in memory ruv of this replica suffix. + + :returns: RUV object + :raises: LDAPError + """ + self._populate_suffix() + + ent = self._instance.search_ext_s( + base=self._suffix, + scope=ldap.SCOPE_SUBTREE, + filterstr='(&(nsuniqueid=ffffffff-ffffffff-ffffffff-ffffffff)(objectclass=nstombstone))', + attrlist=['nsds5agmtmaxcsn'], + serverctrls=self._server_controls, clientctrls=self._client_controls)[0] + + return ensure_list_str(ent.getValues('nsds5agmtmaxcsn')) + def begin_task_cl2ldif(self): """Begin the changelog to ldif task """ self.replace('nsds5task', 'cl2ldif') + class Replicas(DSLdapObjects): """Replica DSLdapObjects for all replicas @@ -1239,6 +1272,7 @@ class Replicas(DSLdapObjects): replica._populate_suffix() return replica + class BootstrapReplicationManager(DSLdapObject): """A Replication Manager credential for bootstrapping the repl process. This is used by the replication manager object to coordinate the initial @@ -1255,7 +1289,8 @@ class BootstrapReplicationManager(DSLdapObject): self._must_attributes = ['cn', 'userPassword'] self._create_objectclasses = [ 'top', - 'netscapeServer' + 'netscapeServer', + 'nsAccount' ] self._protected = False self.common_name = 'replication manager'
0
470454142380b61f22abae8348f731f2360a3868
389ds/389-ds-base
Ticket 50234 - one level search returns not matching entry Bug: if in a onelevel search the IDList for the parentid is smaller than the filter threshold and smaller than the list generated by the search filter then the intersection is aborted and all children are returned. Fix: In the above case we need to set the flag that the filter evaluation cannot be bypassed Reviewed by: William, Thierry. Thanks
commit 470454142380b61f22abae8348f731f2360a3868 Author: Ludwig Krispenz <[email protected]> Date: Thu Feb 21 16:54:52 2019 +0100 Ticket 50234 - one level search returns not matching entry Bug: if in a onelevel search the IDList for the parentid is smaller than the filter threshold and smaller than the list generated by the search filter then the intersection is aborted and all children are returned. Fix: In the above case we need to set the flag that the filter evaluation cannot be bypassed Reviewed by: William, Thierry. Thanks diff --git a/dirsrvtests/tests/tickets/ticket50234_test.py b/dirsrvtests/tests/tickets/ticket50234_test.py new file mode 100644 index 000000000..c605c4531 --- /dev/null +++ b/dirsrvtests/tests/tickets/ticket50234_test.py @@ -0,0 +1,70 @@ +# --- 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 --- +# +import logging +import time +import ldap +import pytest + +from lib389.topologies import topology_st + +from lib389._constants import DEFAULT_SUFFIX + +from lib389.idm.user import UserAccount, UserAccounts +from lib389.idm.organizationalunit import OrganizationalUnit + +log = logging.getLogger(__name__) + +def test_ticket50234(topology_st): + """ + The fix for ticket 50234 + + + The test sequence is: + - create more than 10 entries with objectclass organizational units ou=org{} + - add an Account in one of them, eg below ou=org5 + - do searches with search base ou=org5 and search filter "objectclass=organizationalunit" + - a subtree search should return 1 entry, the base entry + - a onelevel search should return no entry + """ + + log.info('Testing Ticket 50234 - onelvel search returns not matching entry') + + for i in range(1,15): + ou = OrganizationalUnit(topology_st.standalone, "ou=Org{},{}".format(i, DEFAULT_SUFFIX)) + ou.create(properties={'ou': 'Org'.format(i)}) + + properties = { + 'uid': 'Jeff Vedder', + 'cn': 'Jeff Vedder', + 'sn': 'user', + 'uidNumber': '1000', + 'gidNumber': '2000', + 'homeDirectory': '/home/' + 'JeffVedder', + 'userPassword': 'password' + } + user = UserAccount(topology_st.standalone, "cn=Jeff Vedder,ou=org5,{}".format(DEFAULT_SUFFIX)) + user.create(properties=properties) + + # in a subtree search the entry used as search base matches the filter and shoul be returned + ent = topology_st.standalone.getEntry("ou=org5,{}".format(DEFAULT_SUFFIX), ldap.SCOPE_SUBTREE, "(objectclass=organizationalunit)") + + # in a onelevel search the only child is an useraccount which does not match the filter + # no entry should be returned, which would cause getEntry to raise an exception we need to handle + found = 1 + try: + ent = topology_st.standalone.getEntry("ou=org5,{}".format(DEFAULT_SUFFIX), ldap.SCOPE_ONELEVEL, "(objectclass=organizationalunit)") + except ldap.NO_SUCH_OBJECT: + found = 0 + assert (found == 0) + +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/back-ldbm/idl_set.c b/ldap/servers/slapd/back-ldbm/idl_set.c index f9a900f1f..6b6586799 100644 --- a/ldap/servers/slapd/back-ldbm/idl_set.c +++ b/ldap/servers/slapd/back-ldbm/idl_set.c @@ -371,6 +371,7 @@ idl_set_intersect(IDListSet *idl_set, backend *be) result_list = idl_set->head; } else if (idl_set->minimum->b_nids <= FILTER_TEST_THRESHOLD) { result_list = idl_set->minimum; + slapi_be_set_flag(be, SLAPI_BE_FLAG_DONT_BYPASS_FILTERTEST); /* Free the other IDLs which are not the minimum. */ IDList *next = NULL;
0
d316a6717b18cba9826639d82116baa967734f35
389ds/389-ds-base
Change referential integrity to be a betxnpostoperation plugin This changes referential integrity to be a betxnpostoperation plugin Note: this doesn't include the dse.ldif changes, so that will have to be done manually Reviewed by: nkinder (Thanks!)
commit d316a6717b18cba9826639d82116baa967734f35 Author: Rich Megginson <[email protected]> Date: Thu Sep 15 14:46:34 2011 -0600 Change referential integrity to be a betxnpostoperation plugin This changes referential integrity to be a betxnpostoperation plugin Note: this doesn't include the dse.ldif changes, so that will have to be done manually Reviewed by: nkinder (Thanks!) diff --git a/ldap/servers/plugins/referint/referint.c b/ldap/servers/plugins/referint/referint.c index e22a01828..86f1372be 100644 --- a/ldap/servers/plugins/referint/referint.c +++ b/ldap/servers/plugins/referint/referint.c @@ -77,7 +77,7 @@ int referint_postop_del( Slapi_PBlock *pb ); int referint_postop_modrdn( Slapi_PBlock *pb ); int referint_postop_start( Slapi_PBlock *pb); int referint_postop_close( Slapi_PBlock *pb); -int update_integrity(char **argv, char *origDN, char *newrDN, char *newsuperior, int logChanges); +int update_integrity(char **argv, char *origDN, char *newrDN, char *newsuperior, int logChanges, void *txn); void referint_thread_func(void *arg); int GetNextLine(char *dest, int size_dest, PRFileDesc *stream); void writeintegritylog(char *logfilename, char *dn, char *newrdn, char *newsuperior); @@ -122,9 +122,9 @@ referint_postop_init( Slapi_PBlock *pb ) SLAPI_PLUGIN_VERSION_01 ) != 0 || slapi_pblock_set( pb, SLAPI_PLUGIN_DESCRIPTION, (void *)&pdesc ) != 0 || - slapi_pblock_set( pb, SLAPI_PLUGIN_POST_DELETE_FN, + slapi_pblock_set( pb, SLAPI_PLUGIN_BE_TXN_POST_DELETE_FN, (void *) referint_postop_del ) != 0 || - slapi_pblock_set( pb, SLAPI_PLUGIN_POST_MODRDN_FN, + slapi_pblock_set( pb, SLAPI_PLUGIN_BE_TXN_POST_MODRDN_FN, (void *) referint_postop_modrdn ) != 0 || slapi_pblock_set(pb, SLAPI_PLUGIN_START_FN, (void *) referint_postop_start ) != 0 || @@ -151,10 +151,12 @@ referint_postop_del( Slapi_PBlock *pb ) int delay; int logChanges=0; int isrepop = 0; + void *txn = NULL; if ( slapi_pblock_get( pb, SLAPI_IS_REPLICATED_OPERATION, &isrepop ) != 0 || slapi_pblock_get( pb, SLAPI_DELETE_TARGET, &dn ) != 0 || - slapi_pblock_get(pb, SLAPI_PLUGIN_OPRETURN, &oprc) != 0) + slapi_pblock_get(pb, SLAPI_PLUGIN_OPRETURN, &oprc) != 0 || + slapi_pblock_get(pb, SLAPI_TXN, &txn) != 0) { slapi_log_error( SLAPI_LOG_FATAL, REFERINT_PLUGIN_SUBSYSTEM, "referint_postop_del: could not get parameters\n" ); @@ -199,7 +201,7 @@ referint_postop_del( Slapi_PBlock *pb ) }else if(delay == 0){ /* no delay */ /* call function to update references to entry */ - rc = update_integrity(argv, dn, NULL, NULL, logChanges); + rc = update_integrity(argv, dn, NULL, NULL, logChanges, txn); }else{ /* write the entry to integrity log */ writeintegritylog(argv[1],dn, NULL, NULL); @@ -228,12 +230,14 @@ referint_postop_modrdn( Slapi_PBlock *pb ) int delay; int logChanges=0; int isrepop = 0; + void *txn = NULL; if ( slapi_pblock_get( pb, SLAPI_IS_REPLICATED_OPERATION, &isrepop ) != 0 || slapi_pblock_get( pb, SLAPI_MODRDN_TARGET, &dn ) != 0 || slapi_pblock_get( pb, SLAPI_MODRDN_NEWRDN, &newrdn ) != 0 || slapi_pblock_get( pb, SLAPI_MODRDN_NEWSUPERIOR, &newsuperior ) != 0 || - slapi_pblock_get(pb, SLAPI_PLUGIN_OPRETURN, &oprc) != 0 ){ + slapi_pblock_get(pb, SLAPI_PLUGIN_OPRETURN, &oprc) != 0 || + slapi_pblock_get(pb, SLAPI_TXN, &txn) != 0) { slapi_log_error( SLAPI_LOG_FATAL, REFERINT_PLUGIN_SUBSYSTEM, "referint_postop_modrdn: could not get parameters\n" ); @@ -282,7 +286,7 @@ referint_postop_modrdn( Slapi_PBlock *pb ) }else if(delay == 0){ /* no delay */ /* call function to update references to entry */ - rc = update_integrity(argv, dn, newrdn, newsuperior, logChanges); + rc = update_integrity(argv, dn, newrdn, newsuperior, logChanges, txn); }else{ /* write the entry to integrity log */ writeintegritylog(argv[1],dn, newrdn, newsuperior); @@ -313,11 +317,13 @@ int isFatalSearchError(int search_result) } static int -_do_modify(Slapi_PBlock *mod_pb, const char *entryDN, LDAPMod **mods) +_do_modify(Slapi_PBlock *mod_pb, const char *entryDN, LDAPMod **mods, void *txn) { int rc = 0; slapi_pblock_init(mod_pb); + /* set the transaction to use */ + slapi_pblock_set(mod_pb, SLAPI_TXN, txn); /* Use internal operation API */ slapi_modify_internal_set_pb(mod_pb, entryDN, mods, NULL, NULL, @@ -339,7 +345,7 @@ _update_one_per_mod(const char *entryDN, /* DN of the searched entry */ char *norm_origDN, /* normalized original DN */ char *newRDN, /* new RDN from modrdn */ char *newsuperior, /* new superior from modrdn */ - Slapi_PBlock *mod_pb) + Slapi_PBlock *mod_pb, void *txn) { LDAPMod *list_of_mods[3]; char *values_del[2]; @@ -362,7 +368,7 @@ _update_one_per_mod(const char *entryDN, /* DN of the searched entry */ list_of_mods[0] = &attribute1; /* terminate list of mods. */ list_of_mods[1] = NULL; - rc = _do_modify(mod_pb, entryDN, list_of_mods); + rc = _do_modify(mod_pb, entryDN, list_of_mods, txn); if (rc) { slapi_log_error( SLAPI_LOG_FATAL, REFERINT_PLUGIN_SUBSYSTEM, "_update_one_value: entry %s: deleting \"%s: %s\" failed (%d)" @@ -440,7 +446,7 @@ _update_one_per_mod(const char *entryDN, /* DN of the searched entry */ attribute2.mod_values = values_add; list_of_mods[1] = &attribute2; list_of_mods[2] = NULL; - rc = _do_modify(mod_pb, entryDN, list_of_mods); + rc = _do_modify(mod_pb, entryDN, list_of_mods, txn); if (rc) { slapi_log_error( SLAPI_LOG_FATAL, REFERINT_PLUGIN_SUBSYSTEM, "_update_one_value: entry %s: replacing \"%s: %s\" " @@ -469,7 +475,7 @@ _update_one_per_mod(const char *entryDN, /* DN of the searched entry */ attribute2.mod_values = values_add; list_of_mods[1] = &attribute2; list_of_mods[2] = NULL; - rc = _do_modify(mod_pb, entryDN, list_of_mods); + rc = _do_modify(mod_pb, entryDN, list_of_mods, txn); if (rc) { slapi_log_error( SLAPI_LOG_FATAL, REFERINT_PLUGIN_SUBSYSTEM, "_update_one_value: entry %s: replacing \"%s: %s\" " @@ -504,7 +510,7 @@ _update_all_per_mod(const char *entryDN, /* DN of the searched entry */ char *norm_origDN, /* normalized original DN */ char *newRDN, /* new RDN from modrdn */ char *newsuperior, /* new superior from modrdn */ - Slapi_PBlock *mod_pb) + Slapi_PBlock *mod_pb, void *txn) { Slapi_Mods *smods = NULL; char *newDN = NULL; @@ -531,7 +537,7 @@ _update_all_per_mod(const char *entryDN, /* DN of the searched entry */ mods[0] = &attribute1; /* terminate list of mods. */ mods[1] = NULL; - rc = _do_modify(mod_pb, entryDN, mods); + rc = _do_modify(mod_pb, entryDN, mods, txn); if (rc) { slapi_log_error( SLAPI_LOG_FATAL, REFERINT_PLUGIN_SUBSYSTEM, "_update_one_value: entry %s: deleting \"%s: %s\" failed (%d)" @@ -612,7 +618,7 @@ _update_all_per_mod(const char *entryDN, /* DN of the searched entry */ /* else: value does not include the modified DN. Ignore it. */ slapi_ch_free_string(&sval); } - rc = _do_modify(mod_pb, entryDN, slapi_mods_get_ldapmods_byref(smods)); + rc = _do_modify(mod_pb, entryDN, slapi_mods_get_ldapmods_byref(smods), txn); if (rc) { slapi_log_error( SLAPI_LOG_FATAL, REFERINT_PLUGIN_SUBSYSTEM, "_update_all_value: entry %s failed (%d)\n", @@ -633,7 +639,7 @@ _update_all_per_mod(const char *entryDN, /* DN of the searched entry */ int update_integrity(char **argv, char *origDN, - char *newrDN, char *newsuperior, int logChanges) + char *newrDN, char *newsuperior, int logChanges, void *txn) { Slapi_PBlock *search_result_pb = NULL; Slapi_PBlock *mod_pb = slapi_pblock_new(); @@ -654,7 +660,7 @@ update_integrity(char **argv, char *origDN, rc = -1; goto free_and_return; } - + /* for now, just putting attributes to keep integrity on in conf file, until resolve the other timing mode issue */ @@ -688,6 +694,8 @@ update_integrity(char **argv, char *origDN, /* Use new search API */ slapi_pblock_init(search_result_pb); + /* set the parent txn for the search ops */ + slapi_pblock_set(search_result_pb, SLAPI_TXN, txn); slapi_search_internal_set_pb(search_result_pb, search_base, LDAP_SCOPE_SUBTREE, filter, attrs, 0 /* attrs only */, NULL, NULL, referint_plugin_identity, 0); @@ -740,14 +748,14 @@ update_integrity(char **argv, char *origDN, attr, attrName, origDN, norm_origDN, newrDN, newsuperior, - mod_pb); + mod_pb, txn); } else { rc = _update_all_per_mod( slapi_entry_get_dn(search_entries[j]), attr, attrName, origDN, norm_origDN, newrDN, newsuperior, - mod_pb); + mod_pb, txn); } /* Should we stop if one modify returns an error? */ } @@ -955,7 +963,7 @@ referint_thread_func(void *arg) tmpsuperior = slapi_ch_smprintf("%s", ptoken); } - update_integrity(plugin_argv, tmpdn, tmprdn, tmpsuperior, logChanges); + update_integrity(plugin_argv, tmpdn, tmprdn, tmpsuperior, logChanges, NULL); slapi_ch_free_string(&tmpdn); slapi_ch_free_string(&tmprdn);
0
017fda070b86844d4860041a6e42ab12d7588836
389ds/389-ds-base
Ticket 51175 - resolve plugin name leaking Bug Description: Previously pblock.c assumed that all plugin names were static c strings. Rust can't create static C strings, so these were intentionally leaked. Fix Description: Rather than leak these, we do a dup/free through the slapiplugin struct instead, meaning we can use ephemeral, and properly managed strings in rust. This does not affect any other existing code which will still handle the static strings correctly. https://pagure.io/389-ds-base/issue/51175 Author: William Brown <[email protected]> Review by: mreynolds, tbordaz (Thanks!)
commit 017fda070b86844d4860041a6e42ab12d7588836 Author: William Brown <[email protected]> Date: Fri Jun 26 10:27:56 2020 +1000 Ticket 51175 - resolve plugin name leaking Bug Description: Previously pblock.c assumed that all plugin names were static c strings. Rust can't create static C strings, so these were intentionally leaked. Fix Description: Rather than leak these, we do a dup/free through the slapiplugin struct instead, meaning we can use ephemeral, and properly managed strings in rust. This does not affect any other existing code which will still handle the static strings correctly. https://pagure.io/389-ds-base/issue/51175 Author: William Brown <[email protected]> Review by: mreynolds, tbordaz (Thanks!) diff --git a/Makefile.am b/Makefile.am index 3f2164599..4ea239ad5 100644 --- a/Makefile.am +++ b/Makefile.am @@ -1315,6 +1315,7 @@ rust-nsslapd-private.h: @abs_top_builddir@/rs/@rust_target_dir@/librnsslapd.a libslapi_r_plugin_SOURCES = \ src/slapi_r_plugin/src/backend.rs \ src/slapi_r_plugin/src/ber.rs \ + src/slapi_r_plugin/src/charray.rs \ src/slapi_r_plugin/src/constants.rs \ src/slapi_r_plugin/src/dn.rs \ src/slapi_r_plugin/src/entry.rs \ diff --git a/configure.ac b/configure.ac index 4843a82f9..8a029ecb4 100644 --- a/configure.ac +++ b/configure.ac @@ -131,7 +131,7 @@ if test "$enable_debug" = yes ; then debug_defs="-DDEBUG -DMCC_DEBUG" debug_cflags="-g3 -O0 -rdynamic" debug_cxxflags="-g3 -O0 -rdynamic" - debug_rust_defs="-C debuginfo=2" + debug_rust_defs="-C debuginfo=2 -Z macro-backtrace" cargo_defs="" rust_target_dir="debug" else diff --git a/dirsrvtests/tests/suites/basic/basic_test.py b/dirsrvtests/tests/suites/basic/basic_test.py index c85dc4b43..47ba90a4c 100644 --- a/dirsrvtests/tests/suites/basic/basic_test.py +++ b/dirsrvtests/tests/suites/basic/basic_test.py @@ -251,11 +251,11 @@ def test_basic_import_export(topology_st, import_example_ldif): """ log.info('Running test_basic_import_export...') - # # Test online/offline LDIF imports # topology_st.standalone.start() + # topology_st.standalone.config.set('nsslapd-errorlog-level', '1') # Generate a test ldif (50k entries) log.info("Generating LDIF...") @@ -263,6 +263,7 @@ def test_basic_import_export(topology_st, import_example_ldif): import_ldif = ldif_dir + '/basic_import.ldif' dbgen_users(topology_st.standalone, 50000, import_ldif, DEFAULT_SUFFIX) + # Online log.info("Importing LDIF online...") import_task = ImportTask(topology_st.standalone) diff --git a/ldap/servers/slapd/pagedresults.c b/ldap/servers/slapd/pagedresults.c index d8b8798b6..e3444e944 100644 --- a/ldap/servers/slapd/pagedresults.c +++ b/ldap/servers/slapd/pagedresults.c @@ -738,10 +738,10 @@ pagedresults_cleanup(Connection *conn, int needlock) int i; PagedResults *prp = NULL; - slapi_log_err(SLAPI_LOG_TRACE, "pagedresults_cleanup", "=>\n"); + /* slapi_log_err(SLAPI_LOG_TRACE, "pagedresults_cleanup", "=>\n"); */ if (NULL == conn) { - slapi_log_err(SLAPI_LOG_TRACE, "pagedresults_cleanup", "<= Connection is NULL\n"); + /* slapi_log_err(SLAPI_LOG_TRACE, "pagedresults_cleanup", "<= Connection is NULL\n"); */ return 0; } @@ -767,7 +767,7 @@ pagedresults_cleanup(Connection *conn, int needlock) if (needlock) { pthread_mutex_unlock(&(conn->c_mutex)); } - slapi_log_err(SLAPI_LOG_TRACE, "pagedresults_cleanup", "<= %d\n", rc); + /* slapi_log_err(SLAPI_LOG_TRACE, "pagedresults_cleanup", "<= %d\n", rc); */ return rc; } diff --git a/ldap/servers/slapd/pblock.c b/ldap/servers/slapd/pblock.c index cb562e938..7a9578d1a 100644 --- a/ldap/servers/slapd/pblock.c +++ b/ldap/servers/slapd/pblock.c @@ -3341,13 +3341,15 @@ slapi_pblock_set(Slapi_PBlock *pblock, int arg, void *value) if (pblock->pb_plugin->plg_type != SLAPI_PLUGIN_SYNTAX) { return (-1); } - pblock->pb_plugin->plg_syntax_names = (char **)value; + PR_ASSERT(pblock->pb_plugin->plg_syntax_names == NULL); + pblock->pb_plugin->plg_syntax_names = slapi_ch_array_dup((char **)value); break; case SLAPI_PLUGIN_SYNTAX_OID: if (pblock->pb_plugin->plg_type != SLAPI_PLUGIN_SYNTAX) { return (-1); } - pblock->pb_plugin->plg_syntax_oid = (char *)value; + PR_ASSERT(pblock->pb_plugin->plg_syntax_oid == NULL); + pblock->pb_plugin->plg_syntax_oid = slapi_ch_strdup((char *)value); break; case SLAPI_PLUGIN_SYNTAX_FLAGS: if (pblock->pb_plugin->plg_type != SLAPI_PLUGIN_SYNTAX) { @@ -3796,7 +3798,8 @@ slapi_pblock_set(Slapi_PBlock *pblock, int arg, void *value) if (pblock->pb_plugin->plg_type != SLAPI_PLUGIN_MATCHINGRULE) { return (-1); } - pblock->pb_plugin->plg_mr_names = (char **)value; + PR_ASSERT(pblock->pb_plugin->plg_mr_names == NULL); + pblock->pb_plugin->plg_mr_names = slapi_ch_array_dup((char **)value); break; case SLAPI_PLUGIN_MR_COMPARE: if (pblock->pb_plugin->plg_type != SLAPI_PLUGIN_MATCHINGRULE) { diff --git a/ldap/servers/slapd/plugin.c b/ldap/servers/slapd/plugin.c index 282b98738..e6b48de60 100644 --- a/ldap/servers/slapd/plugin.c +++ b/ldap/servers/slapd/plugin.c @@ -2694,6 +2694,13 @@ plugin_free(struct slapdplugin *plugin) if (plugin->plg_type == SLAPI_PLUGIN_PWD_STORAGE_SCHEME || plugin->plg_type == SLAPI_PLUGIN_REVER_PWD_STORAGE_SCHEME) { slapi_ch_free_string(&plugin->plg_pwdstorageschemename); } + if (plugin->plg_type == SLAPI_PLUGIN_SYNTAX) { + slapi_ch_free_string(&plugin->plg_syntax_oid); + slapi_ch_array_free(plugin->plg_syntax_names); + } + if (plugin->plg_type == SLAPI_PLUGIN_MATCHINGRULE) { + slapi_ch_array_free(plugin->plg_mr_names); + } release_componentid(plugin->plg_identity); slapi_counter_destroy(&plugin->plg_op_counter); if (!plugin->plg_group) { diff --git a/ldap/servers/slapd/pw_verify.c b/ldap/servers/slapd/pw_verify.c index 4f0944b73..4ff1fa2fd 100644 --- a/ldap/servers/slapd/pw_verify.c +++ b/ldap/servers/slapd/pw_verify.c @@ -111,6 +111,7 @@ pw_verify_token_dn(Slapi_PBlock *pb) { if (fernet_verify_token(dn, cred->bv_val, key, tok_ttl) != 0) { rc = SLAPI_BIND_SUCCESS; } + slapi_ch_free_string(&key); #endif return rc; } diff --git a/ldap/servers/slapd/tools/pwenc.c b/ldap/servers/slapd/tools/pwenc.c index 1629c06cd..d89225e34 100644 --- a/ldap/servers/slapd/tools/pwenc.c +++ b/ldap/servers/slapd/tools/pwenc.c @@ -34,7 +34,7 @@ int ldap_syslog; int ldap_syslog_level; -int slapd_ldap_debug = LDAP_DEBUG_ANY; +/* int slapd_ldap_debug = LDAP_DEBUG_ANY; */ int detached; FILE *error_logfp; FILE *access_logfp; diff --git a/src/slapi_r_plugin/README.md b/src/slapi_r_plugin/README.md index af9743ec9..1c9bcbf17 100644 --- a/src/slapi_r_plugin/README.md +++ b/src/slapi_r_plugin/README.md @@ -15,7 +15,7 @@ the [Rust Nomicon](https://doc.rust-lang.org/nomicon/index.html) > warning about danger. This document will not detail the specifics of unsafe or the invariants you must adhere to for rust -to work with C. +to work with C. Failure to uphold these invariants will lead to less than optimal consequences. If you still want to see more about the plugin bindings, go on ... @@ -135,7 +135,7 @@ associated functions. Now, you may notice that not all members of the trait are implemented. This is due to a feature of rust known as default trait impls. This allows the trait origin (src/plugin.rs) to provide template versions of these functions. If you "overwrite" them, your implementation is used. Unlike -OO, you may not inherit or call the default function. +OO, you may not inherit or call the default function. If a default is not provided you *must* implement that function to be considered valid. Today (20200422) this only applies to `start` and `close`. @@ -183,7 +183,7 @@ It's important to understand how Rust manages memory both on the stack and the h As a result, this means that we must express in code, assertions about the proper ownership of memory and who is responsible for it (unlike C, where it can be hard to determine who or what is responsible for freeing some value.) Failure to handle this correctly, can and will lead to crashes, leaks or -*hand waving* magical failures that are eXtReMeLy FuN to debug. +*hand waving* magical failures that are `eXtReMeLy FuN` to debug. ### Reference Types diff --git a/src/slapi_r_plugin/src/charray.rs b/src/slapi_r_plugin/src/charray.rs new file mode 100644 index 000000000..d2e44693c --- /dev/null +++ b/src/slapi_r_plugin/src/charray.rs @@ -0,0 +1,32 @@ +use std::ffi::CString; +use std::iter::once; +use std::os::raw::c_char; +use std::ptr; + +pub struct Charray { + pin: Vec<CString>, + charray: Vec<*const c_char>, +} + +impl Charray { + pub fn new(input: &[&str]) -> Result<Self, ()> { + let pin: Result<Vec<_>, ()> = input + .iter() + .map(|s| CString::new(*s).map_err(|_e| ())) + .collect(); + + let pin = pin?; + + let charray: Vec<_> = pin + .iter() + .map(|s| s.as_ptr()) + .chain(once(ptr::null())) + .collect(); + + Ok(Charray { pin, charray }) + } + + pub fn as_ptr(&self) -> *const *const c_char { + self.charray.as_ptr() + } +} diff --git a/src/slapi_r_plugin/src/lib.rs b/src/slapi_r_plugin/src/lib.rs index d7fc22e52..e589057b6 100644 --- a/src/slapi_r_plugin/src/lib.rs +++ b/src/slapi_r_plugin/src/lib.rs @@ -1,9 +1,11 @@ -// extern crate lazy_static; +#[macro_use] +extern crate lazy_static; #[macro_use] pub mod macros; pub mod backend; pub mod ber; +pub mod charray; mod constants; pub mod dn; pub mod entry; @@ -19,6 +21,7 @@ pub mod value; pub mod prelude { pub use crate::backend::{BackendRef, BackendRefTxn}; pub use crate::ber::BerValRef; + pub use crate::charray::Charray; pub use crate::constants::{FilterType, PluginFnType, PluginType, PluginVersion, LDAP_SUCCESS}; pub use crate::dn::{Sdn, SdnRef}; pub use crate::entry::EntryRef; @@ -28,8 +31,7 @@ pub mod prelude { pub use crate::plugin::{register_plugin_ext, PluginIdRef, SlapiPlugin3}; pub use crate::search::{Search, SearchScope}; pub use crate::syntax_plugin::{ - matchingrule_register, name_to_leaking_char, names_to_leaking_char_array, SlapiOrdMr, - SlapiSubMr, SlapiSyntaxPlugin1, + matchingrule_register, SlapiOrdMr, SlapiSubMr, SlapiSyntaxPlugin1, }; pub use crate::task::{task_register_handler_fn, task_unregister_handler_fn, Task, TaskRef}; pub use crate::value::{Value, ValueArray, ValueArrayRef, ValueRef}; diff --git a/src/slapi_r_plugin/src/macros.rs b/src/slapi_r_plugin/src/macros.rs index 030449632..a185470db 100644 --- a/src/slapi_r_plugin/src/macros.rs +++ b/src/slapi_r_plugin/src/macros.rs @@ -249,6 +249,7 @@ macro_rules! slapi_r_syntax_plugin_hooks { paste::item! { use libc; use std::convert::TryFrom; + use std::ffi::CString; #[no_mangle] pub extern "C" fn [<$mod_ident _plugin_init>](raw_pb: *const libc::c_void) -> i32 { @@ -261,15 +262,15 @@ macro_rules! slapi_r_syntax_plugin_hooks { }; // Setup the names/oids that this plugin provides syntaxes for. - - let name_ptr = unsafe { names_to_leaking_char_array(&$hooks_ident::attr_supported_names()) }; - match pb.register_syntax_names(name_ptr) { + // DS will clone these, so they can be ephemeral to this function. + let name_vec = Charray::new($hooks_ident::attr_supported_names().as_slice()).expect("invalid supported names"); + match pb.register_syntax_names(name_vec.as_ptr()) { 0 => {}, e => return e, }; - let name_ptr = unsafe { name_to_leaking_char($hooks_ident::attr_oid()) }; - match pb.register_syntax_oid(name_ptr) { + let attr_oid = CString::new($hooks_ident::attr_oid()).expect("invalid attr oid"); + match pb.register_syntax_oid(attr_oid.as_ptr()) { 0 => {}, e => return e, }; @@ -430,7 +431,8 @@ macro_rules! slapi_r_syntax_plugin_hooks { e => return e, }; - let name_ptr = unsafe { names_to_leaking_char_array(&$hooks_ident::eq_mr_supported_names()) }; + let name_vec = Charray::new($hooks_ident::eq_mr_supported_names().as_slice()).expect("invalid mr supported names"); + let name_ptr = name_vec.as_ptr(); // SLAPI_PLUGIN_MR_NAMES match pb.register_mr_names(name_ptr) { 0 => {}, @@ -672,7 +674,8 @@ macro_rules! slapi_r_syntax_plugin_hooks { e => return e, }; - let name_ptr = unsafe { names_to_leaking_char_array(&$hooks_ident::ord_mr_supported_names()) }; + let name_vec = Charray::new($hooks_ident::ord_mr_supported_names().as_slice()).expect("invalid ord supported names"); + let name_ptr = name_vec.as_ptr(); // SLAPI_PLUGIN_MR_NAMES match pb.register_mr_names(name_ptr) { 0 => {}, diff --git a/src/slapi_r_plugin/src/syntax_plugin.rs b/src/slapi_r_plugin/src/syntax_plugin.rs index e7d5c01bd..86f84bdd8 100644 --- a/src/slapi_r_plugin/src/syntax_plugin.rs +++ b/src/slapi_r_plugin/src/syntax_plugin.rs @@ -1,11 +1,11 @@ use crate::ber::BerValRef; // use crate::constants::FilterType; +use crate::charray::Charray; use crate::error::PluginError; use crate::pblock::PblockRef; use crate::value::{ValueArray, ValueArrayRef}; use std::cmp::Ordering; use std::ffi::CString; -use std::iter::once; use std::os::raw::c_char; use std::ptr; @@ -26,37 +26,6 @@ struct slapi_matchingRuleEntry { mr_compat_syntax: *const *const c_char, } -pub unsafe fn name_to_leaking_char(name: &str) -> *const c_char { - let n = CString::new(name) - .expect("An invalid string has been hardcoded!") - .into_boxed_c_str(); - let n_ptr = n.as_ptr(); - // Now we intentionally leak the name here, and the pointer will remain valid. - Box::leak(n); - n_ptr -} - -pub unsafe fn names_to_leaking_char_array(names: &[&str]) -> *const *const c_char { - let n_arr: Vec<CString> = names - .iter() - .map(|s| CString::new(*s).expect("An invalid string has been hardcoded!")) - .collect(); - let n_arr = n_arr.into_boxed_slice(); - let n_ptr_arr: Vec<*const c_char> = n_arr - .iter() - .map(|v| v.as_ptr()) - .chain(once(ptr::null())) - .collect(); - let n_ptr_arr = n_ptr_arr.into_boxed_slice(); - - // Now we intentionally leak these names here, - let _r_n_arr = Box::leak(n_arr); - let r_n_ptr_arr = Box::leak(n_ptr_arr); - - let name_ptr = r_n_ptr_arr as *const _ as *const *const c_char; - name_ptr -} - // oid - the oid of the matching rule // name - the name of the mr // desc - description @@ -69,20 +38,24 @@ pub unsafe fn matchingrule_register( syntax: &str, compat_syntax: &[&str], ) -> i32 { - let oid_ptr = name_to_leaking_char(oid); - let name_ptr = name_to_leaking_char(name); - let desc_ptr = name_to_leaking_char(desc); - let syntax_ptr = name_to_leaking_char(syntax); - let compat_syntax_ptr = names_to_leaking_char_array(compat_syntax); + // Make everything CStrings that live long enough. + + let oid_cs = CString::new(oid).expect("invalid oid"); + let name_cs = CString::new(name).expect("invalid name"); + let desc_cs = CString::new(desc).expect("invalid desc"); + let syntax_cs = CString::new(syntax).expect("invalid syntax"); + + // We have to do this so the cstrings live long enough. + let compat_syntax_ca = Charray::new(compat_syntax).expect("invalid compat_syntax"); let new_mr = slapi_matchingRuleEntry { - mr_oid: oid_ptr, + mr_oid: oid_cs.as_ptr(), _mr_oidalias: ptr::null(), - mr_name: name_ptr, - mr_desc: desc_ptr, - mr_syntax: syntax_ptr, + mr_name: name_cs.as_ptr(), + mr_desc: desc_cs.as_ptr(), + mr_syntax: syntax_cs.as_ptr(), _mr_obsolete: 0, - mr_compat_syntax: compat_syntax_ptr, + mr_compat_syntax: compat_syntax_ca.as_ptr(), }; let new_mr_ptr = &new_mr as *const _;
0
3dfe80f17c721167b522d1156b84c6e7028106a6
389ds/389-ds-base
Issue i5846 - Crash when lmdb import is aborted (#5881) Problem: Double free occurs in the writer thread queue when an import over lmdb aborts Solution: fix the double free
commit 3dfe80f17c721167b522d1156b84c6e7028106a6 Author: progier389 <[email protected]> Date: Fri Aug 11 17:13:56 2023 +0200 Issue i5846 - Crash when lmdb import is aborted (#5881) Problem: Double free occurs in the writer thread queue when an import over lmdb aborts Solution: fix the double free diff --git a/dirsrvtests/tests/suites/import/import_test.py b/dirsrvtests/tests/suites/import/import_test.py index 79362dc2b..832a27cf6 100644 --- a/dirsrvtests/tests/suites/import/import_test.py +++ b/dirsrvtests/tests/suites/import/import_test.py @@ -15,6 +15,8 @@ import pytest import time import glob import logging +import subprocess +from datetime import datetime from lib389.topologies import topology_st as topo from lib389._constants import DEFAULT_SUFFIX, TaskWarning from lib389.dbgen import dbgen_users @@ -23,6 +25,7 @@ from lib389.index import Indexes from lib389.monitor import Monitor from lib389.backend import Backends from lib389.config import LDBMConfig +from lib389.config import LMDB_LDBMConfig from lib389.utils import ds_is_newer, get_default_db_lib from lib389.idm.user import UserAccount from lib389.idm.account import Accounts @@ -81,22 +84,26 @@ def _search_for_user(topo, no_n0): assert len(accounts.filter('(uid=*)')) == no_n0 +def _import_clean_topo(topo): + """ + Cleanup after import + """ + accounts = Accounts(topo.standalone, DEFAULT_SUFFIX) + for i in accounts.filter('(uid=*)'): + UserAccount(topo.standalone, i.dn).delete() + + ldif_dir = topo.standalone.get_ldif_dir() + import_ldif = ldif_dir + '/basic_import.ldif' + if os.path.exists(import_ldif): + os.remove(import_ldif) + syntax_err_ldif = ldif_dir + '/syntax_err.dif' + if os.path.exists(syntax_err_ldif): + os.remove(syntax_err_ldif) + + @pytest.fixture(scope="function") def _import_clean(request, topo): - def finofaci(): - accounts = Accounts(topo.standalone, DEFAULT_SUFFIX) - for i in accounts.filter('(uid=*)'): - UserAccount(topo.standalone, i.dn).delete() - - ldif_dir = topo.standalone.get_ldif_dir() - import_ldif = ldif_dir + '/basic_import.ldif' - if os.path.exists(import_ldif): - os.remove(import_ldif) - syntax_err_ldif = ldif_dir + '/syntax_err.dif' - if os.path.exists(syntax_err_ldif): - os.remove(syntax_err_ldif) - - request.addfinalizer(finofaci) + request.addfinalizer(lambda: _import_clean_topo(topo)) def _import_offline(topo, no_no): @@ -112,6 +119,7 @@ def _import_offline(topo, no_no): topo.standalone.stop() t1 = time.time() if not topo.standalone.ldif2db('userRoot', None, None, None, import_ldif): + topo.standalone.start() assert False total_time = time.time() - t1 topo.standalone.start() @@ -208,6 +216,26 @@ givenName: return import_ldif1 +def _now(): + """ + Get current time with the format that _check_for_core requires + """ + now = datetime.now() + return now.strftime("%Y-%m-%d %H:%M:%S") + + +def __check_for_core(now): + """ + Check if ns-slapd generated a core since the provided date by looking in the system logs. + """ + cmd = [ 'journalctl' ,'-S', now, '-t', 'audit', '-g', 'ANOM_ABEND.*ns-slapd' ] + result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) + if result.returncode != 1: + # journalctl returns 1 if there is no matching records, and 0 if there are records + log.error('journalctl output is:\n%s' % result.stdout) + raise AssertionError(f'journalctl reported that ns-slapd crashes after {now}') + + def test_import_with_index(topo, _import_clean): """ Add an index, then import via cn=tasks @@ -556,6 +584,49 @@ def test_import_wrong_file_path(topo): assert "The LDIF file does not exist" in str(e.value) [email protected](get_default_db_lib() != "mdb", reason="lmdb specific test") +def test_crash_on_ldif2db_with_lmdb(topo, _import_clean): + """Make an import fail by specifying a too small db size then check that + there is no crash. + + :id: d42585b6-31d0-11ee-8724-482ae39447e5 + :setup: Standalone Instance + :steps: + 1. Configure a small database size + 2. Import an ldif with 1K users + 3. Check that ns-slapd has not aborted + 4. Import an ldif with 500 users + 5. Check that ns-slapd has not aborted + :expectedresults: + 1. Success + 2. Success + 3. Success (ns-slapd should not have aborted) + 4. Import should fail + 5. Success (ns-slapd should not have aborted) + + """ + TINY_MAP_SIZE = 16 * 1024 * 1024 + inst = topo.standalone + handler = LMDB_LDBMConfig(inst) + mapsize = TINY_MAP_SIZE + log.info(f'Set lmdb map size to {mapsize}.') + handler.replace('nsslapd-mdb-max-size', str(mapsize)) + inst.stop() + for dbfile in ['data.mdb', 'INFO.mdb', 'lock.mdb']: + try: + os.remove(f'{inst.dbdir}/{dbfile}') + except FileNotFoundError: + pass + inst.start() + now = _now() + _import_offline(topo, 1000) + __check_for_core(now) + _import_clean_topo(topo) + with pytest.raises(AssertionError): + _import_offline(topo, 500_000) + __check_for_core(now) + + if __name__ == '__main__': # Run isolated # -s for DEBUG mode diff --git a/ldap/servers/slapd/back-ldbm/db-mdb/mdb_import_threads.c b/ldap/servers/slapd/back-ldbm/db-mdb/mdb_import_threads.c index 6da707630..cb21a5e17 100644 --- a/ldap/servers/slapd/back-ldbm/db-mdb/mdb_import_threads.c +++ b/ldap/servers/slapd/back-ldbm/db-mdb/mdb_import_threads.c @@ -4053,13 +4053,7 @@ void dbmdb_dup_writer_slot(struct importqueue *q, void *from_slot, void *to_slot void free_writer_queue_item(WriterQueueData_t **q) { - WriterQueueData_t *n = *q, *f = NULL; - *q = NULL; - while (n) { - f = n; - n = n->next; - slapi_ch_free((void**)&f); - } + slapi_ch_free((void**)q); } WriterQueueData_t *
0
8dd19cc7e6d8d20a83a5fcc7f9db85aa89c996c3
389ds/389-ds-base
Bug 611790 - fix coverify Defect Type: Null pointer dereferences issues 11940 - 12166 https://bugzilla.redhat.com/show_bug.cgi?id=611790 Resolves: bug 611790 Bug description: Fix coverify Defect Type: Null pointer dereferences issues 11940 - 12166 Fix description: Catch possible NULL pointer in replica_new_from_entry() and _replica_configure_ruv().
commit 8dd19cc7e6d8d20a83a5fcc7f9db85aa89c996c3 Author: Endi S. Dewata <[email protected]> Date: Tue Jul 6 12:14:20 2010 -0500 Bug 611790 - fix coverify Defect Type: Null pointer dereferences issues 11940 - 12166 https://bugzilla.redhat.com/show_bug.cgi?id=611790 Resolves: bug 611790 Bug description: Fix coverify Defect Type: Null pointer dereferences issues 11940 - 12166 Fix description: Catch possible NULL pointer in replica_new_from_entry() and _replica_configure_ruv(). diff --git a/ldap/servers/plugins/replication/repl5_replica.c b/ldap/servers/plugins/replication/repl5_replica.c index 1b1af659d..7ca8730fa 100644 --- a/ldap/servers/plugins/replication/repl5_replica.c +++ b/ldap/servers/plugins/replication/repl5_replica.c @@ -179,6 +179,16 @@ replica_new_from_entry (Slapi_Entry *e, char *errortext, PRBool is_add_operation r = (Replica *)slapi_ch_calloc(1, sizeof(Replica)); + if (!r) + { + if (NULL != errortext) + { + PR_snprintf(errortext, SLAPI_DSE_RETURNTEXT_SIZE, "Out of memory"); + } + rc = -1; + goto done; + } + if ((r->repl_lock = PR_NewLock()) == NULL) { if (NULL != errortext) @@ -1873,6 +1883,12 @@ _replica_configure_ruv (Replica *r, PRBool isLocked) /* read ruv state from the ruv tombstone entry */ pb = slapi_pblock_new(); + if (!pb) { + slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name, + "_replica_configure_ruv: Out of memory\n"); + goto done; + } + attrs[0] = (char*)type_ruvElement; attrs[1] = NULL; slapi_search_internal_set_pb(
0
05961eb97ac93f31a131945427a3c1c96bf65c73
389ds/389-ds-base
Issue 5105 - During a bind, if the target entry is not reachable the operation may complete without sending result (#5107) Bug description: A bind operation can skip sending back operation result. This can happen in rare condition like backend is not available or in referral mode or did not define a bind callback. Fix description: Catch those errors condition and send an operation result. relates: https://github.com/389ds/389-ds-base/issues/5105 Reviewed by: Pierre Rogier (thanks !) Platforms tested: F34
commit 05961eb97ac93f31a131945427a3c1c96bf65c73 Author: tbordaz <[email protected]> Date: Fri Jan 14 14:46:34 2022 +0100 Issue 5105 - During a bind, if the target entry is not reachable the operation may complete without sending result (#5107) Bug description: A bind operation can skip sending back operation result. This can happen in rare condition like backend is not available or in referral mode or did not define a bind callback. Fix description: Catch those errors condition and send an operation result. relates: https://github.com/389ds/389-ds-base/issues/5105 Reviewed by: Pierre Rogier (thanks !) Platforms tested: F34 diff --git a/ldap/servers/slapd/pw_verify.c b/ldap/servers/slapd/pw_verify.c index 20ec33211..4f910e949 100644 --- a/ldap/servers/slapd/pw_verify.c +++ b/ldap/servers/slapd/pw_verify.c @@ -64,12 +64,14 @@ pw_verify_be_dn(Slapi_PBlock *pb, Slapi_Entry **referral) int mt_result = slapi_mapping_tree_select(pb, &be, referral, NULL, 0); if (mt_result != LDAP_SUCCESS) { + slapi_send_ldap_result(pb, LDAP_UNAVAILABLE, NULL, NULL, 0, NULL); return SLAPI_BIND_NO_BACKEND; } if (*referral) { /* If we have a referral, this is NULL */ PR_ASSERT(be == NULL); + slapi_send_ldap_result(pb, LDAP_REFERRAL, NULL, NULL, 0, NULL); return SLAPI_BIND_REFERRAL; } @@ -78,6 +80,7 @@ pw_verify_be_dn(Slapi_PBlock *pb, Slapi_Entry **referral) if (be->be_bind == NULL) { /* Selected backend doesn't support binds! */ slapi_be_Unlock(be); + slapi_send_ldap_result(pb, LDAP_OPERATIONS_ERROR, NULL, NULL, 0, NULL); return LDAP_OPERATIONS_ERROR; } slapi_pblock_set(pb, SLAPI_PLUGIN, be->be_database);
0
111774dcc74f9b216f929e641bcc376f20e8c6f2
389ds/389-ds-base
Issue 4534 - libasan read buffer overflow in filtercmp (#4541)
commit 111774dcc74f9b216f929e641bcc376f20e8c6f2 Author: progier389 <[email protected]> Date: Mon Jan 18 15:01:08 2021 +0100 Issue 4534 - libasan read buffer overflow in filtercmp (#4541) diff --git a/dirsrvtests/tests/suites/vlv/regression_test.py b/dirsrvtests/tests/suites/vlv/regression_test.py index 646cd97ba..14539cc78 100644 --- a/dirsrvtests/tests/suites/vlv/regression_test.py +++ b/dirsrvtests/tests/suites/vlv/regression_test.py @@ -84,8 +84,8 @@ def test_bulk_import_when_the_backend_with_vlv_was_recreated(topology_m2): MappingTrees(M2).list()[0].delete() Backends(M2).list()[0].delete() # Recreate the backend and the VLV index on Master 2. - M2.mappingtree.create(DEFAULT_SUFFIX, "userRoot") M2.backend.create(DEFAULT_SUFFIX, {BACKEND_NAME: "userRoot"}) + M2.mappingtree.create(DEFAULT_SUFFIX, "userRoot") # Recreating vlvSrchDn and vlvIndexDn on Master 2. vlv_searches.create( basedn="cn=userRoot,cn=ldbm database,cn=plugins,cn=config", @@ -101,6 +101,8 @@ def test_bulk_import_when_the_backend_with_vlv_was_recreated(topology_m2): repl.test_replication(M2, M1, 30) entries = M2.search_s(DEFAULT_SUFFIX, ldap.SCOPE_SUBTREE, "(cn=*)") assert len(entries) > 0 + entries = M2.search_s(DEFAULT_SUFFIX, ldap.SCOPE_SUBTREE, "(objectclass=*)") + entries = M2.search_s(DEFAULT_SUFFIX, ldap.SCOPE_SUBTREE, "(objectclass=*)") if __name__ == "__main__": diff --git a/ldap/servers/slapd/filtercmp.c b/ldap/servers/slapd/filtercmp.c index 76308d1ea..f7e3ed4d5 100644 --- a/ldap/servers/slapd/filtercmp.c +++ b/ldap/servers/slapd/filtercmp.c @@ -344,6 +344,7 @@ slapi_filter_compare(struct slapi_filter *f1, struct slapi_filter *f2) struct berval *inval1[2], *inval2[2], **outval1, **outval2; int ret; Slapi_Attr sattr; + int cmplen; slapi_log_err(SLAPI_LOG_TRACE, "slapi_filter_compare", "=>\n"); @@ -373,21 +374,26 @@ slapi_filter_compare(struct slapi_filter *f1, struct slapi_filter *f2) } slapi_attr_init(&sattr, f1->f_ava.ava_type); key1 = get_normalized_value(&sattr, &f1->f_ava); + key2 = get_normalized_value(&sattr, &f2->f_ava); + ret = 1; + if (key1 && key2) { + struct berval bvkey1 = { + slapi_value_get_length(key1[0]), + slapi_value_get_string(key1[0]) + }; + struct berval bvkey2 = { + slapi_value_get_length(key2[0]), + slapi_value_get_string(key2[0]) + }; + ret = slapi_berval_cmp(&bvkey1, &bvkey2); + } if (key1) { - key2 = get_normalized_value(&sattr, &f2->f_ava); - if (key2) { - ret = memcmp(slapi_value_get_string(key1[0]), - slapi_value_get_string(key2[0]), - slapi_value_get_length(key1[0])); - valuearray_free(&key1); - valuearray_free(&key2); - attr_done(&sattr); - break; - } valuearray_free(&key1); } + if (key2) { + valuearray_free(&key2); + } attr_done(&sattr); - ret = 1; break; case LDAP_FILTER_PRESENT: ret = (slapi_UTF8CASECMP(f1->f_type, f2->f_type));
0
1989c0eeed09a8d8fdae1e0e2a11c5b5da038636
389ds/389-ds-base
Issue #77 - Refactor docstrings in rST format - part 1 Decsription: With the first part, refactor docstrings in modules: _mapped_object.py, aci.py, agreement.py, backend.py, changelog.py, mappingTree.py, replica.py, repltools.py Format it properly and put to index.rst Add a script for links to the code in the docs. https://pagure.io/lib389/issue/77 Reviewed by: wibrown (Thanks!)
commit 1989c0eeed09a8d8fdae1e0e2a11c5b5da038636 Author: Simon Pichugin <[email protected]> Date: Tue Aug 29 19:29:15 2017 +0200 Issue #77 - Refactor docstrings in rST format - part 1 Decsription: With the first part, refactor docstrings in modules: _mapped_object.py, aci.py, agreement.py, backend.py, changelog.py, mappingTree.py, replica.py, repltools.py Format it properly and put to index.rst Add a script for links to the code in the docs. https://pagure.io/lib389/issue/77 Reviewed by: wibrown (Thanks!) diff --git a/src/lib389/doc/source/accesscontrol.rst b/src/lib389/doc/source/accesscontrol.rst new file mode 100644 index 000000000..2c5a882b4 --- /dev/null +++ b/src/lib389/doc/source/accesscontrol.rst @@ -0,0 +1,6 @@ +Access Control +-------------- + +.. toctree:: + + aci.rst diff --git a/src/lib389/doc/source/aci.rst b/src/lib389/doc/source/aci.rst new file mode 100644 index 000000000..8c7c0f3b2 --- /dev/null +++ b/src/lib389/doc/source/aci.rst @@ -0,0 +1,66 @@ +ACI +========== + +Usage example +------------------ +:: + + ACI_TARGET = ('(targetfilter ="(ou=groups)")(targetattr ="uniqueMember ' + '|| member")') + ACI_ALLOW = ('(version 3.0; acl "Allow test aci";allow (read, search, ' + 'write)') + ACI_SUBJECT = ('(userdn="ldap:///dc=example,dc=com??sub?(ou=engineering)" ' + 'and userdn="ldap:///dc=example,dc=com??sub?(manager=uid=' + 'wbrown,ou=managers,dc=example,dc=com) || ldap:///dc=examp' + 'le,dc=com??sub?(manager=uid=tbrown,ou=managers,dc=exampl' + 'e,dc=com)" );)') + + # Add some entry with ACI + group_dn = 'cn=testgroup,{}'.format(DEFAULT_SUFFIX) + gentry = Entry(group_dn) + gentry.setValues('objectclass', 'top', 'extensibleobject') + gentry.setValues('cn', 'testgroup') + gentry.setValues('aci', ACI_BODY) + standalone.add_s(gentry) + + # Get and parse ACI + acis = standalone.aci.list() + aci = acis[0] + + assert aci.acidata == { + 'allow': [{'values': ['read', 'search', 'write']}], + 'target': [], 'targetattr': [{'values': ['uniqueMember', 'member'], + 'equal': True}], + 'targattrfilters': [], + 'deny': [], + 'acl': [{'values': ['Allow test aci']}], + 'deny_raw_bindrules': [], + 'targetattrfilters': [], + 'allow_raw_bindrules': [{'values': [( + 'userdn="ldap:///dc=example,dc=com??sub?(ou=engineering)" and' + ' userdn="ldap:///dc=example,dc=com??sub?(manager=uid=wbrown,' + 'ou=managers,dc=example,dc=com) || ldap:///dc=example,dc=com' + '??sub?(manager=uid=tbrown,ou=managers,dc=example,dc=com)" ')]}], + 'targetfilter': [{'values': ['(ou=groups)'], 'equal': True}], + 'targetscope': [], + 'version 3.0;': [], + 'rawaci': complex_aci + } + + # You can get a raw ACI + raw_aci = aci.getRawAci() + +Additional information about ACI +---------------------------------- + +- https://access.redhat.com/documentation/en-US/Red_Hat_Directory_Server/10/html/Administration_Guide/Managing_Access_Control-Bind_Rules.html +- https://access.redhat.com/documentation/en-US/Red_Hat_Directory_Server/10/html/Administration_Guide/Managing_Access_Control-Creating_ACIs_Manually.html + +Module documentation +----------------------- + +.. autoclass:: lib389.aci.Aci + :members: + +.. autoclass:: lib389._entry.EntryAci + :members: diff --git a/src/lib389/doc/source/agreement.rst b/src/lib389/doc/source/agreement.rst new file mode 100644 index 000000000..8d449dc0b --- /dev/null +++ b/src/lib389/doc/source/agreement.rst @@ -0,0 +1,27 @@ +Agreement +========== + +Usage example +-------------- +:: + + master = topology.ms["master1"] + consumer = topology.ms["consumer1"] + # Create + repl_agreement = master.agreement.create(suffix=DEFAULT_SUFFIX, + host=consumer.host, + port=consumer.port) + # List + ents = master.agreement.list(suffix=DEFAULT_SUFFIX, + consumer_host=consumer.host, + consumer_port=consumer.port) + # Delete + ents = master1.agreement.delete(suffix=DEFAULT_SUFFIX) + + +Module documentation +---------------------- + +.. autoclass:: lib389.agreement.Agreement + :members: + diff --git a/src/lib389/doc/source/backend.rst b/src/lib389/doc/source/backend.rst new file mode 100644 index 000000000..5b4e1f42a --- /dev/null +++ b/src/lib389/doc/source/backend.rst @@ -0,0 +1,49 @@ +Backend +========== + +Usage example +-------------- +:: + + from lib389.backend import Backends + + backends = Backends(standalone) + backend = backends.create(properties={BACKEND_SUFFIX: 'o=new_suffix', # mandatory + BACKEND_NAME: new_backend, # mandatory + BACKEND_SAMPLE_ENTRIES: '001003006'}) + + # Create sample entries + backend.create_sample_entries(version='001003006') + + backend.delete() + +Backend properties +------------------- + +- BACKEND_NAME - 'somename' +- BACKEND_READONLY - 'on' | 'off' +- BACKEND_REQ_INDEX - 'on' | 'off' +- BACKEND_CACHE_ENTRIES - 1 to (2^32 - 1) on 32-bit systems or (2^63 - 1) + on 64-bit systems or -1, which means limitless +- BACKEND_CACHE_SIZE - 500 kilobytes to (2^32 - 1) + on 32-bit systems and to (2^63 - 1) on 64-bit systems +- BACKEND_DNCACHE_SIZE - 500 kilobytes to (2^32 - 1) + on 32-bit systems and to (2^63 - 1) on 64-bit systems +- BACKEND_DIRECTORY - Any valid path to the database instance +- BACKEND_CHAIN_BIND_DN - DN of the multiplexor +- BACKEND_CHAIN_BIND_PW - password of the multiplexor +- BACKEND_CHAIN_URLS - Any valid remote server LDAP URL +- BACKEND_SUFFIX - 'o=somesuffix' +- BACKEND_SAMPLE_ENTRIES - version of confir i.e. '001003006' + + +Module documentation +----------------------- + +.. autoclass:: lib389.backend.Backends + :members: + :inherited-members: + +.. autoclass:: lib389.backend.Backend + :members: + :inherited-members: diff --git a/src/lib389/doc/source/changelog.rst b/src/lib389/doc/source/changelog.rst new file mode 100644 index 000000000..b51dd20e8 --- /dev/null +++ b/src/lib389/doc/source/changelog.rst @@ -0,0 +1,22 @@ +Changelog +========== + +Usage example +-------------- +:: + + standalone = topology.standalone + # Create + changelog_dn = standalone.changelog.create() + # List + changelog_entries = standalone.changelog.list(changelogdn=changelog_dn) + # Delete + standalone.changelog.delete() + + +Module documentation +---------------------- + +.. autoclass:: lib389.changelog.Changelog + :members: + diff --git a/src/lib389/doc/source/conf.py b/src/lib389/doc/source/conf.py index 62fe1a5e5..c645db21e 100644 --- a/src/lib389/doc/source/conf.py +++ b/src/lib389/doc/source/conf.py @@ -32,6 +32,7 @@ extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.ifconfig', + 'sphinx.ext.linkcode' ] # Add any paths that contain templates here, relative to this directory. @@ -112,7 +113,7 @@ todo_include_todos = False # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. -html_theme = 'alabaster' +html_theme = 'nature' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the @@ -292,3 +293,43 @@ texinfo_documents = [ # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = {'https://docs.python.org/': None} + +import lib389 +import inspect +from os.path import relpath, dirname + +def linkcode_resolve(domain, info): + if domain != 'py': + return None + if not info['module']: + return None + + module_name = info['module'] + fullname = info['fullname'] + file_name = module_name.replace('.', '/') + + # Get the module object + submodule = sys.modules.get(module_name) + if not submodule: + return None + + # Get submodules + next_submodule = submodule + for name in fullname.split('.'): + try: + next_submodule = getattr(next_submodule, name) + except: + return None + + # Get line number for the submodule + try: + _, line = inspect.getsourcelines(next_submodule) + except: + line = None + + if line: + line_fmt = "#_{}".format(line) + else: + line_fmt = "" + + return "https://pagure.io/lib389/blob/master/f/{}.py{}".format(file_name, line_fmt) diff --git a/src/lib389/doc/source/config.rst b/src/lib389/doc/source/config.rst new file mode 100644 index 000000000..8207d42df --- /dev/null +++ b/src/lib389/doc/source/config.rst @@ -0,0 +1,47 @@ +Config +========== + +Usage example +--------------- +:: + + # Set config attribute: + standalone.config.set('passwordStorageScheme', 'SSHA') + + # Reset config attribute (by deleting it): + standalone.config.reset('passwordStorageScheme') + + # Enable/disable logs (error, access, audit): + standalone.config.enable_log('error') + standalone.config.disable_log('access') + + # Set loglevel for errors log. + # If 'update' set to True, it will add the 'vals' to existing values in the loglevel attribute + standalone.config.loglevel(vals=(LOG_DEFAULT,), service='error', update=False) + # You can get log levels from lib389._constants + (LOG_TRACE, + LOG_TRACE_PACKETS, + LOG_TRACE_HEAVY, + LOG_CONNECT, + LOG_PACKET, + LOG_SEARCH_FILTER, + LOG_CONFIG_PARSER, + LOG_ACL, + LOG_ENTRY_PARSER, + LOG_HOUSEKEEPING, + LOG_REPLICA, + LOG_DEFAULT, + LOG_CACHE, + LOG_PLUGIN, + LOG_MICROSECONDS, + LOG_ACL_SUMMARY) = [1 << x for x in (list(range(8)) + list(range(11, 19)))] + + # Set 'nsslapd-accesslog-logbuffering' to 'on' if True, otherwise set it to 'off' + standalone.config.logbuffering(True) + + +Module documentation +----------------------- + +.. autoclass:: lib389.config.Config + :members: diff --git a/src/lib389/doc/source/databases.rst b/src/lib389/doc/source/databases.rst new file mode 100644 index 000000000..3cd1bb108 --- /dev/null +++ b/src/lib389/doc/source/databases.rst @@ -0,0 +1,7 @@ +Configuring Databases +--------------------- + +.. toctree:: + + backend.rst + mappingtree.rst diff --git a/src/lib389/doc/source/dirsrv_log.rst b/src/lib389/doc/source/dirsrv_log.rst new file mode 100644 index 000000000..1d67854b6 --- /dev/null +++ b/src/lib389/doc/source/dirsrv_log.rst @@ -0,0 +1,30 @@ +DirSrv log +========== + +Usage example +-------------- +:: + + # Get array of all lines (including rotated and compresed logs): + standalone.ds_access_log.readlines_archive() + standalone.ds_error_log.readlines_archive() + # Get array of all lines (without rotated and compresed logs): + standalone.ds_access_log.readlines() + standalone.ds_error_log.readlines() + # Get array of lines that match the regex pattern: + standalone.ds_access_log.match_archive('.*fd=.*') + standalone.ds_error_log.match_archive('.*fd=.*') + standalone.ds_access_log.match('.*fd=.*') + standalone.ds_error_log.match('.*fd=.*') + # Break up the log line into the specific fields: + assert(standalone.ds_error_log.parse_line('[27/Apr/2016:13:46:35.775670167 +1000] slapd started. Listening on All Interfaces port 54321 for LDAP requests') == {'timestamp': '[27/Apr/2016:13:46:35.775670167 +1000]', 'message': 'slapd starte d. Listening on All Interfaces port 54321 for LDAP requests', 'datetime': datetime.datetime(2016, 4, 27, 13, 0, 0, 775670, tzinfo=tzoffset(No ne, 36000))}) + + +Module documentation +----------------------- + +.. autoclass:: lib389.dirsrv_log.DirsrvAccessLog + :members: + +.. autoclass:: lib389.dirsrv_log.DirsrvErrorLog + :members: diff --git a/src/lib389/doc/source/domain.rst b/src/lib389/doc/source/domain.rst new file mode 100644 index 000000000..31040deb7 --- /dev/null +++ b/src/lib389/doc/source/domain.rst @@ -0,0 +1,21 @@ +Domain +========== + +Usage example +-------------- +:: + + # After the creating a backend, sometimes you don't need a lot of entries under the created suffix + # So instead of using BACKEND_SAMPLE_ENTRIES you can create simple domain entry using the next object: + from lib389.idm.domain import Domain + domain = Domain(standalone], 'dc=test,dc=com') + domain.create(properties={'dc': 'test', 'description': 'dc=test,dc=com'}) + + # It will be deleted with the 'backend.delete()' + + +Module documentation +----------------------- + +.. autoclass:: lib389.idm.domain.Domain + :members: diff --git a/src/lib389/doc/source/dseldif.rst b/src/lib389/doc/source/dseldif.rst new file mode 100644 index 000000000..0718232ca --- /dev/null +++ b/src/lib389/doc/source/dseldif.rst @@ -0,0 +1,30 @@ +DSE ldif +========== + +Usage example +-------------- +:: + + from lib389.dseldif import DSEldif + + dse_ldif = DSEldif(topo.standalone) + + # Get a list of attribute values under a given entry + config_cn = dse_ldif.get(DN_CONFIG, 'cn') + + # Add an attribute under a given entry + dse_ldif.add(DN_CONFIG, 'someattr', 'someattr_value') + + # Replace attribute values with a new one under a given entry. It will remove all previous 'someattr' values + dse_ldif.replace(DN_CONFIG, 'someattr', 'someattr_value') + + # Delete attributes under a given entry + dse_ldif.delete(DN_CONFIG, 'someattr') + dse_ldif.delete(DN_CONFIG, 'someattr', 'someattr_value') + + +Module documentation +----------------------- + +.. autoclass:: lib389.dseldif.DSEldif + :members: diff --git a/src/lib389/doc/source/group.rst b/src/lib389/doc/source/group.rst new file mode 100644 index 000000000..a916748b7 --- /dev/null +++ b/src/lib389/doc/source/group.rst @@ -0,0 +1,43 @@ +Group +======== + +Usage example +-------------- +:: + + # group and groups additionaly have 'is_member', 'add_member' and 'remove_member' methods + # posixgroup and posixgroups have 'check_member' and 'add_member' + from lib389.idm.group import Groups + from lib389.idm.posixgroup import PosixGroups + + groups = Groups(standalone, DEFAULT_SUFFIX) + posix_groups = PosixGroups(standalone, DEFAULT_SUFFIX) + group_properties = { + 'cn' : 'group1', + 'description' : 'testgroup' + } + group = groups.create(properties=group_properties) + + # So now you can: + # Check the membership - shouldn't we make it consistent? + assert(not group.is_member(testuser.dn)) + assert(not posix_groups.check_member(testuser.dn)) + + group.add_member(testuser.dn) + posix_groups.add_member(testuser.dn) + + # Remove member - add the method to PosixGroups too? + group.remove_member(testuser.dn) + + group.delete(): + + +Module documentation +----------------------- + +.. autoclass:: lib389.idm.group.Groups + :members: + +.. autoclass:: lib389.idm.group.Group + :members: + diff --git a/src/lib389/doc/source/guidelines.rst b/src/lib389/doc/source/guidelines.rst index daf249bb5..6d80c1170 100644 --- a/src/lib389/doc/source/guidelines.rst +++ b/src/lib389/doc/source/guidelines.rst @@ -8,7 +8,6 @@ For a saving place purposes, I'll replace topology_m2.ms["master1"] with master1 , etc. - Basic workflow ============== @@ -167,11 +166,8 @@ Basic workflow commits into one commit. -A ways to make your code better in a pytest way -=============================================== - Fixtures --------- +========= Basic info about fixtures - http://pytest.org/latest/fixture.html#fixtures @@ -207,7 +203,7 @@ Parametrizing Test cases ----------- +========== Parametrizing ~~~~~~~~~~~~~ @@ -351,11 +347,9 @@ Asserting assert 'maximum recursion' in str(excinfo.value) -lib389 and python-ldap functions -================================ Constants ---------- +========== Basic constants ~~~~~~~~~~~~~~~ @@ -391,7 +385,7 @@ If you need a lot of constants, import with * Add, Modify, and Delete Operations ----------------------------------- +=================================== Please, use these methods for the operations that can't be performed by DSLdapObjects. @@ -415,7 +409,7 @@ by DSLdapObjects. Search and Bind Operations --------------------------- +=================================== + By default when an instance is created and opened, it is already authenticated as the Root DN(Directory Manager). @@ -446,7 +440,7 @@ Search and Bind Operations Basic instance operations -------------------------- +=================================== :: @@ -485,7 +479,7 @@ Basic instance operations Setting up SSL/TLS ------------------- +=================================== :: @@ -520,7 +514,7 @@ Setting up SSL/TLS Certification-based authentication ----------------------------------- +=================================== You need to setup and turn on SSL first (use the previous chapter). @@ -568,11 +562,10 @@ You need to setup and turn on SSL first (use the previous chapter). Replication ------------ +=================================== Basic configuration - + After the instance is created, you can enable it for replication and set up a replication agreement. diff --git a/src/lib389/doc/source/identitymanagement.rst b/src/lib389/doc/source/identitymanagement.rst new file mode 100644 index 000000000..391a69120 --- /dev/null +++ b/src/lib389/doc/source/identitymanagement.rst @@ -0,0 +1,10 @@ +Identity Management +------------------- + +.. toctree:: + + user.rst + group.rst + domain.rst + organisationalunit.rst + services.rst diff --git a/src/lib389/doc/source/index.rst b/src/lib389/doc/source/index.rst index 55e10ef8d..e5445f8eb 100644 --- a/src/lib389/doc/source/index.rst +++ b/src/lib389/doc/source/index.rst @@ -17,9 +17,20 @@ Contents ======== .. toctree:: - :maxdepth: 3 + :maxdepth: 2 guidelines.rst + Replication <replication.rst> + Configuring Databases <databases.rst> + Access Control <accesscontrol.rst> + +Work in progress +----------------- +.. toctree:: + :maxdepth: 2 + + Identity Management <identitymanagement.rst> + need_to_be_triaged.rst Contact us diff --git a/src/lib389/doc/source/indexes.rst b/src/lib389/doc/source/indexes.rst new file mode 100644 index 000000000..3980028eb --- /dev/null +++ b/src/lib389/doc/source/indexes.rst @@ -0,0 +1,42 @@ +Indexes +========== + +Usage example +-------------- +:: + + from lib389.index import Indexes + + indexes = Indexes(standalone) + + # create and delete a default index. + index = indexes.create(properties={ + 'cn': 'modifytimestamp', + 'nsSystemIndex': 'false', + 'nsIndexType': 'eq' + }) + + default_index_list = indexes.list() + found = False + for i in default_index_list: + if i.dn.startswith('cn=modifytimestamp'): + found = True + assert found + index.delete() + + default_index_list = indexes.list() + found = False + for i in default_index_list: + if i.dn.startswith('cn=modifytimestamp'): + found = True + assert not found + + +Module documentation +----------------------- + +.. autoclass:: lib389.index.Index + :members: + +.. autoclass:: lib389.index.Indexes + :members: diff --git a/src/lib389/doc/source/ldclt.rst b/src/lib389/doc/source/ldclt.rst new file mode 100644 index 000000000..046a3b507 --- /dev/null +++ b/src/lib389/doc/source/ldclt.rst @@ -0,0 +1,42 @@ +Config +========== + +Usage example +-------------- +:: + + This class will allow general usage of ldclt. It's not meant to expose all the functions. Just use ldclt for that. + # Creates users as user<min through max>. Password will be set to password<number> + # This will automatically work with the bind loadtest. + # Template + # objectClass: top + # objectclass: person + # objectClass: organizationalPerson + # objectClass: inetorgperson + # objectClass: posixAccount + # objectClass: shadowAccount + # sn: user[A] + # cn: user[A] + # givenName: user[A] + # description: description [A] + # userPassword: user[A] + # mail: user[A]@example.com + # uidNumber: 1[A] + # gidNumber: 2[A] + # shadowMin: 0 + # shadowMax: 99999 + # shadowInactive: 30 + # shadowWarning: 7 + # homeDirectory: /home/user[A] + # loginShell: /bin/false + topology.instance.ldclt.create_users('ou=People,{}'.format(DEFAULT_SUFFIX), max=1999) + + # Run the load test for a few rounds + topology.instance.ldclt.bind_loadtest('ou=People,{}'.format(DEFAULT_SUFFIX), max=1999) + + +Module documentation +----------------------- + +.. autoclass:: lib389.ldclt.Ldclt + :members: diff --git a/src/lib389/doc/source/mappingtree.rst b/src/lib389/doc/source/mappingtree.rst new file mode 100644 index 000000000..de6843cd7 --- /dev/null +++ b/src/lib389/doc/source/mappingtree.rst @@ -0,0 +1,31 @@ +Mapping Tree +============= + +Usage example +--------------- +:: + + # In the majority of test cases, it is better to use 'Backends' for the operation, + # because it creates the mapping tree for you. Though if you need to create a mapping tree, you can. + # Just work with it as with usual DSLdapObject and DSLdapObjects + # For instance: + from lib389.mappingTree import MappingTrees + mts = MappingTrees(standalone) + mt = mts.create(properties={ + 'cn': ["dc=newexample,dc=com",], + 'nsslapd-state' : 'backend', + 'nsslapd-backend' : 'someRoot', + }) + # It will be deleted with the 'backend.delete()' + + +Module documentation +----------------------- + +.. autoclass:: lib389.mappingTree.MappingTrees + :members: + :inherited-members: + +.. autoclass:: lib389.mappingTree.MappingTree + :members: + :inherited-members: diff --git a/src/lib389/doc/source/monitor.rst b/src/lib389/doc/source/monitor.rst new file mode 100644 index 000000000..5a02510b2 --- /dev/null +++ b/src/lib389/doc/source/monitor.rst @@ -0,0 +1,19 @@ +Monitor +========== + +Usage example +-------------- +:: + + # Monitor and MonitorLDBM are the simple DSLdapObject things. + # You can use all methods from chapter above to get current server performance detail + version = standalone.monitor.get_attr_val('version') + dbcachehit = standalone.monitorldbm.get_attr_val('dbcachehit') + + +Module documentation +----------------------- + +.. autoclass:: lib389.monitor.Monitor + :members: + diff --git a/src/lib389/doc/source/need_to_be_triaged.rst b/src/lib389/doc/source/need_to_be_triaged.rst new file mode 100644 index 000000000..fbbed0327 --- /dev/null +++ b/src/lib389/doc/source/need_to_be_triaged.rst @@ -0,0 +1,20 @@ +Need to be triaged +------------------- + +.. toctree:: + + backend.rst + config.rst + dirsrv_log.rst + dseldif.rst + paths.rst + indexes.rst + ldclt.rst + mappingtree.rst + monitor.rst + passwd.rst + plugin.rst + rootdse.rst + schema.rst + task.rst + utils.rst diff --git a/src/lib389/doc/source/organisationalunit.rst b/src/lib389/doc/source/organisationalunit.rst new file mode 100644 index 000000000..e232f0855 --- /dev/null +++ b/src/lib389/doc/source/organisationalunit.rst @@ -0,0 +1,41 @@ +Organisational Unit +==================== + +Usage example +-------------- +:: + + # Don't forget that Services requires created rdn='ou=Services' + # This you can create with OrganisationalUnits + + from lib389.idm.organisationalunit import OrganisationalUnits + from lib389.idm.services import ServiceAccounts + + ous = OrganisationalUnits(standalone, DEFAULT_SUFFIX) + services = ServiceAccounts(standalone, DEFAULT_SUFFIX) + + # Create the OU for them + ous.create(properties={ + 'ou': 'Services', + 'description': 'Computer Service accounts which request DS bind', + }) + + # Now, we can create the services from here. + service = services.create(properties={ + 'cn': 'testbind', + 'userPassword': 'Password1' + }) + + conn = service.bind('Password1') + conn.unbind_s() + + +Module documentation +----------------------- + +.. autoclass:: lib389.idm.organisationalunit.OrganisationalUnits + :members: + +.. autoclass:: lib389.idm.organisationalunit.OrganisationalUnit + :members: + diff --git a/src/lib389/doc/source/passwd.rst b/src/lib389/doc/source/passwd.rst new file mode 100644 index 000000000..5b60d6051 --- /dev/null +++ b/src/lib389/doc/source/passwd.rst @@ -0,0 +1,33 @@ +LDCLT +========== + +Usage example +-------------- +:: + + from lib389.passwd import password_hash, password_generate + + bindir = standalone.ds_paths.bin_dir + PWSCHEMES = [ + 'SHA1', + 'SHA256', + 'SHA512', + 'SSHA', + 'SSHA256', + 'SSHA512', + 'PBKDF2_SHA256', + ] + + # Generate password + raw_secure_password = password_generate() + + # Encrypt the password + # default scheme is 'SSHA512' + secure_password = password_hash(raw_secure_password, scheme='SSHA256', bin_dir=bindir) + + +Module documentation +----------------------- + +.. automodule:: lib389.passwd + :members: diff --git a/src/lib389/doc/source/paths.rst b/src/lib389/doc/source/paths.rst new file mode 100644 index 000000000..39680c629 --- /dev/null +++ b/src/lib389/doc/source/paths.rst @@ -0,0 +1,42 @@ +Paths +========== + +Usage example +-------------- +:: + + # You can get any variable from the list bellow. Like this: + product = standalone.ds_paths.product + + variables = [ + 'product', + 'version', + 'user', + 'group', + 'root_dn', + 'prefix', + 'bin_dir', + 'sbin_dir', + 'lib_dir', + 'data_dir', + 'tmp_dir', + 'sysconf_dir', + 'config_dir', + 'schema_dir', + 'cert_dir', + 'local_state_dir', + 'run_dir', + 'lock_dir', + 'log_dir', + 'inst_dir', + 'db_dir', + 'backup_dir', + 'ldif_dir', + 'initconfig_dir', + ] + +Module documentation +----------------------- + +.. autoclass:: lib389.paths.Paths + :members: diff --git a/src/lib389/doc/source/plugin.rst b/src/lib389/doc/source/plugin.rst new file mode 100644 index 000000000..859229167 --- /dev/null +++ b/src/lib389/doc/source/plugin.rst @@ -0,0 +1,35 @@ +Plugin +========== + +You can take plugin constant names here - https://pagure.io/lib389/blob/master/f/lib389/_constants.py#_164 + +Usage example +-------------- +:: + + # Plugin and Plugins additionaly have 'enable', 'disable' and 'status' methods + # Here I show you basic way to work with it. Additional methods of complex plugins will be described in subchapters + + from lib389.plugin import Plugins, ACLPlugin + from lib389._constants import PLUGIN_ACL + + # You can just enable/disable plugins from Plugins interface + plugins = Plugins(standalone) + plugins.enable(PLUGIN_ACL) + + # Or you can first 'get' it and then work with it (make sense if your plugin is a complex one) + aclplugin = ACLPlugin(standalone) + + aclplugin.enable() + + aclplugin.disable() + + # True if nsslapd-pluginEnabled is 'on', False otherwise - change the name? + assert(uniqplugin.status()) + + +Module documentation +----------------------- + +.. automodule:: lib389.plugins + :members: diff --git a/src/lib389/doc/source/replica.rst b/src/lib389/doc/source/replica.rst new file mode 100644 index 000000000..75acdb85b --- /dev/null +++ b/src/lib389/doc/source/replica.rst @@ -0,0 +1,59 @@ +Replica +========== + +Usage example +-------------- +:: + + from lib389.replica import Replicas + + replicas = Replicas(standalone) + # Enable replication + # - changelog will be created + # - replica manager will be with the defaults + # - replica.create() will be executed + replica = replicas.enable(suffix=DEFAULT_SUFFIX, + role=REPLICAROLE_MASTER, + replicaID=REPLICAID_MASTER_1) + # Roles - REPLICAROLE_MASTER, REPLICAROLE_HUB, and REPLICAROLE_CONSUMER + # For masters and hubs you can use the constants REPLICAID_MASTER_X and REPLICAID_HUB_X + # Change X for a number from 1 to 100 - for role REPLICAROLE_MASTER only + + # Disable replication + # - agreements and replica entry will be deleted + # - changelog is not deleted (but should?) + replicas.disable(suffix=DEFAULT_SUFFIX) + + # Get RUV entry + replicas.get_ruv_entry() + + # Get DN + replicas.get_dn(suffix) + + # Promote + replicas.promote(suffix=DEFAULT_SUFFIX, + newrole=REPLICAROLE_MASTER, + binddn=REPL_BINDDN, + rid=REPLICAID_MASTER_1) + # Demote + replicas.demote(suffix=DEFAULT_SUFFIX, + newrole=REPLICAROLE_CONSUMER) + # Test, that replication works + replicas.test(master2) + + # Additional replica object methods + # Get role + replica.get_role() + + replica.deleteAgreements() + +Module documentation +----------------------- + +.. autoclass:: lib389.replica.Replicas + :members: + :inherited-members: + +.. autoclass:: lib389.replica.Replica + :members: + :inherited-members: diff --git a/src/lib389/doc/source/replication.rst b/src/lib389/doc/source/replication.rst new file mode 100644 index 000000000..0a8ab7b85 --- /dev/null +++ b/src/lib389/doc/source/replication.rst @@ -0,0 +1,9 @@ +Replication +----------- + +.. toctree:: + + agreement.rst + changelog.rst + replica.rst + repltools.rst diff --git a/src/lib389/doc/source/repltools.rst b/src/lib389/doc/source/repltools.rst new file mode 100644 index 000000000..ce28197e1 --- /dev/null +++ b/src/lib389/doc/source/repltools.rst @@ -0,0 +1,43 @@ +Replication Tools +================== + +Usage example +-------------- +:: + + from lib389.repltools import ReplTools + + # Gather all the CSN strings from the access and verify all of those CSNs exist on all the other replicas. + # dirsrv_replicas - a list of DirSrv objects. The list must begin with master replicas + # ignoreCSNs - an optional string of csns to be ignored + # if the caller knows that some csns can differ eg.: '57e39e72000000020000|vucsn-57e39e76000000030000' + ReplTools.checkCSNs([master1, master2], ignoreCSNs=None) + + # Find and measure the convergence of entries from a replica, and + # print a report on how fast all the "ops" replicated to the other replicas. + # suffix - Replicated suffix + # ops - A list of "operations" to search for in the access logs + # replica - Dirsrv object where the entries originated + # all_replicas - A list of Dirsrv replicas + # It returns - The longest time in seconds for an operation to fully converge + longest_time = ReplTools.replConvReport(DEFAULT_SUFFIX, ops, master1, [master1, master2]) + + # Take a list of DirSrv Objects and check to see if all of the present + # replication agreements are idle for a particular backend + assert(ReplTools.replIdle([master1, master2], suffix=DEFAULT_SUFFIX)) + defaultProperties = { + REPLICATION_BIND_DN: "cn=replrepl,cn=config", + REPLICATION_BIND_PW + + # Create an entry that will be used to bind as replication manager + ReplTools.createReplManager(standalone, + repl_manager_dn=defaultProperties[REPLICATION_BIND_DN], + repl_manager_pw=defaultProperties[REPLICATION_BIND_PW]) + + +Module documentation +----------------------- + +.. autoclass:: lib389.repltools.ReplTools + :members: + diff --git a/src/lib389/doc/source/rootdse.rst b/src/lib389/doc/source/rootdse.rst new file mode 100644 index 000000000..51ec8b841 --- /dev/null +++ b/src/lib389/doc/source/rootdse.rst @@ -0,0 +1,25 @@ +Root DSE +========== + +Usage example +-------------- +:: + + # Get attribute values of 'supportedSASLMechanisms' + standalone.rootdse.supported_sasl() + + # Returns True or False + assert(standalone.rootdse.supports_sasl_gssapi() + assert(standalone.rootdse.supports_sasl_ldapssotoken() + assert(standalone.rootdse.supports_sasl_plain() + assert(standalone.rootdse.supports_sasl_external() + assert(standalone.rootdse.supports_exop_whoami() + assert(standalone.rootdse.supports_exop_ldapssotoken_request() + assert(standalone.rootdse.supports_exop_ldapssotoken_revoke() + + +Module documentation +----------------------- + +.. autoclass:: lib389.rootdse.RootDSE + :members: diff --git a/src/lib389/doc/source/schema.rst b/src/lib389/doc/source/schema.rst new file mode 100644 index 000000000..bcff16479 --- /dev/null +++ b/src/lib389/doc/source/schema.rst @@ -0,0 +1,62 @@ +Schema +========== + +Usage example +-------------- +:: + + # Get the schema as an LDAP entry + schema = standalone.schema.get_entry() + + # Get the schema as a python-ldap SubSchema object + subschema = standalone.schema.get_subschema() + + # Get a list of the schema files in the instance schemadir + schema_files = standalone.schema.list_files() + + + # Convert the given schema file name to its python-ldap format suitable for passing to ldap.schema.SubSchema() + parsed = standalone.schema.file_to_ldap('/full/path/to/file.ldif') + + # Convert the given schema file name to its python-ldap format ldap.schema.SubSchema object + parsed = standalone.schema.file_to_subschema('/full/path/to/file.ldif') + + # Add a schema element to the schema + standalone.schema.add_schema(attr, val) + + # Delete a schema element from the schema + standalone.schema.del_schema(attr, val) + + # Add 'attributeTypes' definition to the schema + standalone.schema.add_attribute(attributes) + + # Add 'objectClasses' definition to the schema + standalone.schema.add_objectclass(objectclasses) + + # Get a schema nsSchemaCSN attribute + schema_csn = standalone.schema.get_schema_csn() + + # Get a list of ldap.schema.models.ObjectClass objects for all objectClasses supported by this instance + objectclasses = standalone.schema.get_objectclasses() + + # Get a list of ldap.schema.models.AttributeType objects for all attributeTypes supported by this instance + attributetypes = standalone.schema.get_attributetypes() + + # Get a list of the server defined matching rules + matchingrules = standalone.schema.get_matchingrules() + + # Get a single matching rule instance that matches the mr_name. Returns None if the matching rule doesn't exist + matchingrule = standalone.schema.query_matchingrule(matchingrule_name) + + # Get a single ObjectClass instance that matches objectclassname. Returns None if the objectClass doesn't exist + objectclass = standalone.schema.query_objectclass(objectclass_name) + + # Returns a tuple of the AttributeType, and what objectclasses may or must take this attributeType. Returns None if attributetype doesn't + (attributetype, may, must) = standalone.schema.query_attributetype(attributetype_name) + + +Module documentation +----------------------- + +.. autoclass:: lib389.schema.Schema + :members: diff --git a/src/lib389/doc/source/services.rst b/src/lib389/doc/source/services.rst new file mode 100644 index 000000000..b556e8af6 --- /dev/null +++ b/src/lib389/doc/source/services.rst @@ -0,0 +1,40 @@ +Services +========== + +Usage example +-------------- +:: + + # Don't forget that Services requires created rdn='ou=Services' + # This you can create with OrganisationalUnits + + from lib389.idm.organisationalunit import OrganisationalUnits + from lib389.idm.services import ServiceAccounts + + ous = OrganisationalUnits(standalone, DEFAULT_SUFFIX) + services = ServiceAccounts(standalone, DEFAULT_SUFFIX) + + # Create the OU for them + ous.create(properties={ + 'ou': 'Services', + 'description': 'Computer Service accounts which request DS bind', + }) + + # Now, we can create the services from here. + service = services.create(properties={ + 'cn': 'testbind', + 'userPassword': 'Password1' + }) + + conn = service.bind('Password1') + conn.unbind_s() + + +Module documentation +----------------------- + +.. autoclass:: lib389.idm.services.ServiceAccounts + :members: + +.. autoclass:: lib389.idm.services.ServiceAccount + :members: diff --git a/src/lib389/doc/source/task.rst b/src/lib389/doc/source/task.rst new file mode 100644 index 000000000..9adf96ccf --- /dev/null +++ b/src/lib389/doc/source/task.rst @@ -0,0 +1,59 @@ +Indexes +========== + +Besides the predefined tasks (which described in a chapter below) you can create +your own task objects with specifying a DN (https://pagure.io/lib389/blob/master/f/lib389/_constants.py#_134) + +Usage example +-------------- +:: + + from lib389.tasks import Task + + newtask = Task(instance, dn) # Should we create Tasks and put the precious to TasksLegacy? + + newtask.create(rdn, properties, basedn) + + # Check if the task is complete + assert(newtask.is_complete()) + + # Check task's exit code if task is complete, else None + if newtask.is_complete(): + exit_code = newtask.get_exit_code() + + # Wait until task is complete + newtask.wait() + + # If True, waits for the completion of the task before to return + args = {TASK_WAIT: True} + + # Some tasks ca be found only under old object. You can access them with this: + standalone.tasks.importLDIF(DEFAULT_SUFFIX, path_ro_ldif, args) + standalone.tasks.exportLDIF(DEFAULT_SUFFIX, benamebase=None, output_file=path_to_ldif, args) + standalone.tasks.db2bak(backup_dir, args) + standalone.tasks.bak2db(bename=None, backup_dir, args) + standalone.tasks.reindex(suffix=None, benamebase=None, attrname=None, args) + standalone.tasks.fixupMemberOf(suffix=None, benamebase=None, filt=None, args) + standalone.tasks.fixupTombstones(bename=None, args) + standalone.tasks.automemberRebuild(suffix=DEFAULT_SUFFIX, scope='sub', filterstr='objectclass=top', args) + standalone.tasks.automemberExport(suffix=DEFAULT_SUFFIX, scope='sub', fstr='objectclass=top', ldif_out=None, args) + standalone.tasks.automemberMap(ldif_in=None, ldif_out=None, args) + standalone.tasks.fixupLinkedAttrs(linkdn=None, args) + standalone.tasks.schemaReload(schemadir=None, args) + standalone.tasks.fixupWinsyncMembers(suffix=DEFAULT_SUFFIX, fstr='objectclass=top', args) + standalone.tasks.syntaxValidate(suffix=DEFAULT_SUFFIX, fstr='objectclass=top', args) + standalone.tasks.usnTombstoneCleanup(suffix=DEFAULT_SUFFIX, bename=None, maxusn_to_delete=None, args) + standalone.tasks.sysconfigReload(configfile=None, logchanges=None, args) + standalone.tasks.cleanAllRUV(suffix=None, replicaid=None, force=None, args) + standalone.tasks.abortCleanAllRUV(suffix=None, replicaid=None, certify=None, args) + standalone.tasks.upgradeDB(nsArchiveDir=None, nsDatabaseType=None, nsForceToReindex=None, args) + + +Module documentation +----------------------- + +.. autoclass:: lib389.tasks.Tasks + :members: + +.. autoclass:: lib389.tasks.Task + :members: diff --git a/src/lib389/doc/source/user.rst b/src/lib389/doc/source/user.rst new file mode 100644 index 000000000..6d59e9183 --- /dev/null +++ b/src/lib389/doc/source/user.rst @@ -0,0 +1,50 @@ +User Accounts +============= + +Usage example +-------------- +:: + + # There is a basic way to work with it + from lib389.idm.user import UserAccounts + users = UserAccounts(standalone, DEFAULT_SUFFIX) + user_properties = { + 'uid': USER_NAME, + 'cn' : USER_NAME, + 'sn' : USER_NAME, + 'userpassword' : USER_PWD, + 'uidNumber' : '1000', + 'gidNumber' : '2000',1 + 'homeDirectory' : '/home/{}'.format(USER_NAME) + } + testuser = users.create(properties=user_properties) + + # After this you can: + # Get the list of them + users.list() + + # Get some user: + testuser = users.get('testuser') + # or + testuser = users.list()[0] # You can loop through 'for user in users:' + + # Set some attribute to the entry + testuser.set('userPassword', 'password') + + # Bind as the user + conn = testuser.bind('password') # It will create a new connection + conn.modify_s() + conn.unbind_s() + + # Delete + testuser.delete() + + +Module documentation +----------------------- + +.. autoclass:: lib389.idm.user.UserAccounts + :members: + +.. autoclass:: lib389.idm.user.UserAccount + :members: diff --git a/src/lib389/doc/source/utils.rst b/src/lib389/doc/source/utils.rst new file mode 100644 index 000000000..9e7865ff8 --- /dev/null +++ b/src/lib389/doc/source/utils.rst @@ -0,0 +1,23 @@ +Utils +========== + +Usage example +-------------- +:: + + standalone.ldif2db(bename, suffixes, excludeSuffixes, encrypt, import_file) + standalone.db2ldif(bename, suffixes, excludeSuffixes, encrypt, repl_data, outputfile) + standalone.bak2db(archive_dir,bename=None) + standalone.db2bak(archive_dir) + standalone.db2index(bename=None, suffixes=None, attrs=None, vlvTag=None) + standalone.dbscan(bename=None, index=None, key=None, width=None, isRaw=False) + + # Generate a simple ldif file using the dbgen.pl script, and set the ownership and permissions to match the user that the server runs as + standalone.buildLDIF(number_of_entries, path_to_ldif, suffix='dc=example,dc=com') + + +Module documentation +----------------------- + +.. automodule:: lib389.utils + :members: diff --git a/src/lib389/lib389/_entry.py b/src/lib389/lib389/_entry.py index b8cb4c451..d13f458bf 100644 --- a/src/lib389/lib389/_entry.py +++ b/src/lib389/lib389/_entry.py @@ -392,17 +392,22 @@ class Entry(object): class EntryAci(object): + """Breaks down an aci attribute string from 389, into a dictionary + of terms and values. These values can then be manipulated, and + subsequently rebuilt into an aci string. + + :param entry: An entry + :type entry: lib389._entry.Entry + :param rawaci: Aci in a raw form + :type rawaci: str + :param verbose: False by default + :type verbose: bool """ - See https://access.redhat.com/documentation/en-US/Red_Hat_Directory_ - Server/10/html/Administration_Guide/Managing_Access_Control-Bind_Rules. - html - https://access.redhat.com/documentation/en-US/Red_Hat_Directory_Server - /10/html/Administration_Guide/Managing_Access_Control-Creating_ACIs_ - Manually.html - We seperate the keys into 3 groups, and one group that has overlap. - This is so we can not only split the aci, but rebuild it from the - dictionary at a later point in time. - """ + + # We seperate the keys into 3 groups, and one group that has overlap. + # This is so we can not only split the aci, but rebuild it from the + # dictionary at a later point in time. + # These are top level aci comoponent keys _keys = ['targetscope', 'targetattrfilters', @@ -435,9 +440,6 @@ class EntryAci(object): def __init__(self, entry, rawaci, verbose=False): """ - Breaks down an aci attribute string from 389, into a dictionary - of terms and values. These values can then be manipulated, and - subsequently rebuilt into an aci string. """ self.verbose = verbose self.entry = entry @@ -475,13 +477,12 @@ class EntryAci(object): return rawaci def getRawAci(self): - """ - This method will rebuild an aci from the contents of the acidata + """This method will rebuild an aci from the contents of the acidata dict found on the object. - returns an aci attribute string. - + :returns: An aci attribute string. """ + # Rebuild the aci from the .acidata. rawaci = '' # For each key in the outer segment diff --git a/src/lib389/lib389/_mapped_object.py b/src/lib389/lib389/_mapped_object.py index 6b50f83fa..fe84cd43a 100644 --- a/src/lib389/lib389/_mapped_object.py +++ b/src/lib389/lib389/_mapped_object.py @@ -19,7 +19,6 @@ from lib389.utils import ( ensure_list_int ) - # This function filter and term generation provided thanks to # The University of Adelaide. <[email protected]> @@ -64,10 +63,13 @@ def _gen_filter(attrtypes, values, extra=None): class DSLogging(object): - """ - The benefit of this is automatic name detection, and correct application + """The benefit of this is automatic name detection, and correct application of level and verbosity to the object. + + :param verbose: False by default + :type verbose: bool """ + def __init__(self, verbose=False): # Maybe we can think of a way to make this display the instance name or __unicode__? self._log = logging.getLogger(type(self).__name__) @@ -78,11 +80,18 @@ class DSLogging(object): class DSLdapObject(DSLogging): + """A single instance of DSLdapObjects + + :param instance: A instance + :type instance: lib389.DirSrv + :param dn: Entry DN + :type dn: str + :param batch: Not implemented + :type batch: bool + """ # TODO: Automatically create objects when they are requested to have properties added def __init__(self, instance, dn=None, batch=False): - """ - """ self._instance = instance super(DSLdapObject, self).__init__(self._instance.verbose) # This allows some factor objects to be overriden @@ -111,9 +120,19 @@ class DSLdapObject(DSLogging): return self.__unicode__() def raw_entry(self): + """Get an Entry object + + :returns: Entry object + """ + return self._instance.getEntry(self._dn) def exists(self): + """Check if the entry exists + + :returns: True if it exists + """ + try: self._instance.search_s(self._dn, ldap.SCOPE_BASE, attrsonly=1) except ldap.NO_SUCH_OBJECT: @@ -122,10 +141,20 @@ class DSLdapObject(DSLogging): return True def display(self): + """Get an entry but represent it as a string LDIF + + :returns: LDIF formatted string + """ + e = self._instance.getEntry(self._dn) return e.__repr__() def display_attr(self, attr): + """Get all values of given attribute - 'attr: value' + + :returns: Formatted string + """ + out = "" for v in self.get_attr_vals_utf8(attr): out += "%s: %s\n" % (attr, v) @@ -145,14 +174,14 @@ class DSLdapObject(DSLogging): return response def __getattr__(self, name): - """ - This enables a bit of magic to allow us to wrap any function ending with + """This enables a bit of magic to allow us to wrap any function ending with _json to it's form without json, then transformed. It means your function *must* return it's values as a dict of: { attr : [val, val, ...], attr : [], ... } to be supported. """ + if (name.endswith('_json')): int_name = name.replace('_json', '') pfunc = partial(self._jsonify, fn=getattr(self, int_name)) @@ -161,17 +190,34 @@ class DSLdapObject(DSLogging): # We make this a property so that we can over-ride dynamically if needed @property def dn(self): + """Get an object DN + + :returns: DN + """ + return self._dn @property def rdn(self): + """Get an object RDN + + :returns: RDN + """ + # How can we be sure this returns the primary one? return ensure_str(self.get_attr_val(self._rdn_attribute)) def present(self, attr, value=None): + """Assert that some attr, or some attr / value exist on the entry. + + :param attr: an attribute name + :type attr: str + :param value: an attribute value + :type value: str + + :returns: True if attr is present """ - Assert that some attr, or some attr / value exist on the entry. - """ + if self._instance.state != DIRSRV_STATE_ONLINE: raise ValueError("Invalid state. Cannot get presence on instance that is not ONLINE") self._log.debug("%s present(%r) %s" % (self._dn, attr, value)) @@ -183,15 +229,37 @@ class DSLdapObject(DSLogging): return e.hasValue(attr, value) def add(self, key, value): + """Add an attribute with a value + + :param key: an attribute name + :type key: str + :param value: an attribute value + :type value: str + """ + self.set(key, value, action=ldap.MOD_ADD) # Basically what it means; def replace(self, key, value): + """Replace an attribute with a value + + :param key: an attribute name + :type key: str + :param value: an attribute value + :type value: str + """ self.set(key, value, action=ldap.MOD_REPLACE) # This needs to work on key + val, and key def remove(self, key, value): - """Remove a value defined by key""" + """Remove a value defined by key + + :param key: an attribute name + :type key: str + :param value: an attribute value + :type value: str + """ + # Do a mod_delete on the value. self.set(key, value, action=ldap.MOD_DELETE) @@ -200,12 +268,31 @@ class DSLdapObject(DSLogging): If an attribute is multi-valued AND required all values except one will be deleted. + + :param key: an attribute name + :type key: str """ + for val in self.get_attr_vals(key): self.remove(key, val) # maybe this could be renamed? def set(self, key, value, action=ldap.MOD_REPLACE): + """Perform a specified action on a key with value + + :param key: an attribute name + :type key: str + :param value: an attribute value + :type value: str + :param action: - ldap.MOD_REPLACE - by default + - ldap.MOD_ADD + - ldap.MOD_DELETE + :type action: int + + :returns: result of modify_s operation + :raises: ValueError - if instance is not online + """ + self._log.debug("%s set(%r, %r)" % (self._dn, key, value)) if self._instance.state != DIRSRV_STATE_ONLINE: raise ValueError("Invalid state. Cannot set properties on instance that is not ONLINE.") @@ -224,10 +311,11 @@ class DSLdapObject(DSLogging): def apply_mods(self, mods): """Perform modification operation using several mods at once - @param mods - list of tuples: [(action, key, value),] - @raise ValueError - if a provided mod op is invalid - @raise LDAPError + :param mods: [(action, key, value),] + :type mods: list of tuples + :raises: ValueError - if a provided mod op is invalid """ + mod_list = [] for mod in mods: if len(mod) < 2: @@ -256,18 +344,28 @@ class DSLdapObject(DSLogging): @classmethod def compare(cls, obj1, obj2): - """ - Compare if two RDN objects have same attributes and values. + """Compare if two RDN objects have same attributes and values. + This comparison is a loose comparison, not a strict one i.e. "this object *is* this other object" It will just check if the attributes are same. 'nsUniqueId' attribute is not checked intentionally because we want to compare arbitrary objects i.e they may have different 'nsUniqueId' but same attributes. - Example: + + Example:: + cn=user1,ou=a cn=user1,ou=b + Comparision of these two objects should result in same, even though their 'nsUniqueId' attribute differs. - This function returns 'True' if objects have same attributes else returns 'False' + + :param obj1: An entry to check + :type obj1: lib389._mapped_object.DSLdapObject + :param obj2: An entry to check + :type obj2: lib389._mapped_object.DSLdapObject + :returns: True if objects have same attributes else returns False + :raises: ValueError - if obj1 or obj2 don't inherit DSLdapObject """ + # ensuring both the objects are RDN objects if not issubclass(type(obj1), DSLdapObject) or not issubclass(type(obj2), DSLdapObject): raise ValueError("Invalid arguments: Expecting object types that inherits 'DSLdapObject' class") @@ -287,9 +385,10 @@ class DSLdapObject(DSLogging): return True def get_compare_attrs(self): + """Get a dictionary having attributes to be compared + i.e. excluding self._compare_exclude """ - Get a dictionary having attributes to be compared i.e. excluding self._compare_exclude - """ + self._log.debug("%s get_compare_attrs" % (self._dn)) all_attrs_dict = self.get_all_attrs() # removing _compate_exclude attrs from all attrs @@ -298,9 +397,11 @@ class DSLdapObject(DSLogging): return compare_attrs_dict def get_all_attrs(self): + """Get a dictionary having all the attributes of the entry + + :returns: Dict with real attributes and operational attributes """ - Get a dictionary having all the attributes i.e. real attributes + operational attributes - """ + self._log.debug("%s get_all_attrs" % (self._dn)) if self._instance.state != DIRSRV_STATE_ONLINE: raise ValueError("Invalid state. Cannot get properties on instance that is not ONLINE") @@ -320,7 +421,6 @@ class DSLdapObject(DSLogging): return entry.getValuesSet(keys) def get_attr_vals(self, key): - """Get an attribute's values from the dn""" self._log.debug("%s get_attr_vals(%r)" % (self._dn, key)) # We might need to add a state check for NONE dn. if self._instance.state != DIRSRV_STATE_ONLINE: @@ -334,7 +434,6 @@ class DSLdapObject(DSLogging): return entry.getValues(key) def get_attr_val(self, key): - """Get a single attribute value from the dn""" self._log.debug("%s getVal(%r)" % (self._dn, key)) # We might need to add a state check for NONE dn. if self._instance.state != DIRSRV_STATE_ONLINE: @@ -346,21 +445,69 @@ class DSLdapObject(DSLogging): return entry.getValue(key) def get_attr_val_bytes(self, key): + """Get a single attribute value from the entry in bytes type + + :param key: An attribute name + :type key: str + :returns: A single bytes value + :raises: ValueError - if instance is offline + """ + return ensure_bytes(self.get_attr_val(key)) def get_attr_vals_bytes(self, key): + """Get attribute values from the entry in bytes type + + :param key: An attribute name + :type key: str + :returns: A single bytes value + :raises: ValueError - if instance is offline + """ + return ensure_list_bytes(self.get_attr_vals(key)) def get_attr_val_utf8(self, key): + """Get a single attribute value from the entry in utf8 type + + :param key: An attribute name + :type key: str + :returns: A single bytes value + :raises: ValueError - if instance is offline + """ + return ensure_str(self.get_attr_val(key)) def get_attr_vals_utf8(self, key): + """Get attribute values from the entry in utf8 type + + :param key: An attribute name + :type key: str + :returns: A single bytes value + :raises: ValueError - if instance is offline + """ + return ensure_list_str(self.get_attr_vals(key)) def get_attr_val_int(self, key): + """Get a single attribute value from the entry in int type + + :param key: An attribute name + :type key: str + :returns: A single bytes value + :raises: ValueError - if instance is offline + """ + return ensure_int(self.get_attr_val(key)) def get_attr_vals_int(self, key): + """Get attribute values from the entry in int type + + :param key: An attribute name + :type key: str + :returns: A single bytes value + :raises: ValueError - if instance is offline + """ + return ensure_list_int(self.get_attr_vals(key)) # Duplicate, but with many values. IE a dict api. @@ -377,32 +524,40 @@ class DSLdapObject(DSLogging): # If the account can be bound to, this will attempt to do so. We don't check # for exceptions, just pass them back! def bind(self, password=None, *args, **kwargs): + """Open a new connection and bind with the entry. + You can pass arguments that will be passed to openConnection. + + :param password: An entry password + :type password: str + :returns: Connection with a binding as the entry + """ + conn = self._instance.openConnection(*args, **kwargs) conn.simple_bind_s(self.dn, password) return conn def delete(self): - """ - Deletes the object defined by self._dn. + """Deletes the object defined by self._dn. This can be changed with the self._protected flag! """ + self._log.debug("%s delete" % (self._dn)) if not self._protected: # Is there a way to mark this as offline and kill it self._instance.delete_s(self._dn) def _validate(self, rdn, properties, basedn): - """ - Used to validate a create request. + """Used to validate a create request. This way, it can be over-ridden without affecting - the create types + the create types. It also checks that all the values in _must_attribute exist - in some form in the dictionary + in some form in the dictionary. It has the useful trick of returning the dn, so subtypes can use extra properties to create the dn's here for this. """ + if properties is None: raise ldap.UNWILLING_TO_PERFORM('Invalid request to create. Properties cannot be None') if type(properties) != dict: @@ -457,6 +612,18 @@ class DSLdapObject(DSLogging): return (tdn, str_props) def create(self, rdn=None, properties=None, basedn=None): + """Add a new entry + + :param rdn: RDN of the new entry + :type rdn: str + :param properties: Attributes for the new entry + :type properties: dict + :param basedn: Base DN of the new entry + :type rdn: str + + :returns: DSLdapObject of the created entry + """ + assert(len(self._create_objectclasses) > 0) basedn = ensure_str(basedn) self._log.debug('Creating "%s" under %s : %s' % (rdn, basedn, properties)) @@ -476,23 +643,24 @@ class DSLdapObject(DSLogging): return self def lint(self): - """ - Override this to create a linter for a type. This means that we can detect + """Override this to create a linter for a type. This means that we can detect and report common administrative errors in the server from our cli and rest tools. - The structure of a result is: - { - dsle: '<identifier>'. dsle == ds lint error. Will be a code unique to + The structure of a result is:: + + { + dsle: '<identifier>'. dsle == ds lint error. Will be a code unique to this module for the error, IE DSBLE0001. - severity: '[HIGH:MEDIUM:LOW]'. severity of the error. - items: '(dn,dn,dn)'. List of affected DNs or names. - detail: 'msg ...'. An explination of the error. - fix: 'msg ...'. Steps to resolve the error. - } + severity: '[HIGH:MEDIUM:LOW]'. severity of the error. + items: '(dn,dn,dn)'. List of affected DNs or names. + detail: 'msg ...'. An explination of the error. + fix: 'msg ...'. Steps to resolve the error. + } - You should return an array of these dicts, on None if there are no errors. + :returns: An array of these dicts, on None if there are no errors. """ + if not self._lint_functions: return None results = [] @@ -505,6 +673,16 @@ class DSLdapObject(DSLogging): # A challenge of this, is how do we manage indexes? They have two naming attribunes.... class DSLdapObjects(DSLogging): + """The object represents the next idea: "Everything is an instance of something + that exists in this way", i.e. we unite LDAP entries by some + set of parameters with the object. + + :param instance: A instance + :type instance: lib389.DirSrv + :param batch: Not implemented + :type batch: bool + """ + def __init__(self, instance, batch=False): self._childobject = DSLdapObject self._instance = instance @@ -530,6 +708,12 @@ class DSLdapObjects(DSLogging): return self._childobject(instance=self._instance, dn=dn, batch=self._batch) def list(self): + """Get a list of children entries (DSLdapObject, Replica, etc.) using a base DN + and objectClasses of our object (DSLdapObjects, Replicas, etc.) + + :returns: A list of children entries + """ + # Filter based on the objectclasses and the basedn insts = None # This will yield and & filter for objectClass with as many terms as needed. @@ -550,6 +734,17 @@ class DSLdapObjects(DSLogging): return insts def get(self, selector=[], dn=None): + """Get a child entry (DSLdapObject, Replica, etc.) with dn or selector + using a base DN and objectClasses of our object (DSLdapObjects, Replicas, etc.) + + :param dn: DN of wanted entry + :type dn: str + :param selector: An additional filter to objectClasses, i.e. 'backend_name' + :type dn: str + + :returns: A child entry + """ + results = [] if dn is not None: results = self._get_dn(dn) @@ -594,9 +789,8 @@ class DSLdapObjects(DSLogging): ) def _validate(self, rdn, properties): - """ - Validate the factory part of the creation - """ + """Validate the factory part of the creation""" + if properties is None: raise ldap.UNWILLING_TO_PERFORM('Invalid request to create. Properties cannot be None') if type(properties) != dict: @@ -618,7 +812,16 @@ class DSLdapObjects(DSLogging): return (rdn, properties) def create(self, rdn=None, properties=None): - # Create the object + """Create an object under base DN of our entry + + :param rdn: RDN of the new entry + :type rdn: str + :param properties: Attributes for the new entry + :type properties: dict + + :returns: DSLdapObject of the created entry + """ + # Should we inject the rdn to properties? # This may not work in all cases, especially when we consider plugins. # diff --git a/src/lib389/lib389/aci.py b/src/lib389/lib389/aci.py index c37748623..1f0725a90 100644 --- a/src/lib389/lib389/aci.py +++ b/src/lib389/lib389/aci.py @@ -18,9 +18,8 @@ from lib389._constants import * # Helpers to detect common patterns in aci def _aci_any_targetattr_ne(aci): - """ - Returns if any of the targetattr types is a != type - """ + """Returns True if any of the targetattr types is a != type""" + potential = False if 'targetattr' in aci.acidata: for ta in aci.acidata['targetattr']: @@ -31,19 +30,29 @@ def _aci_any_targetattr_ne(aci): class Aci(object): + """An object that helps to work with agreement entry + + :param conn: An instance + :type conn: lib389.DirSrv + """ + def __init__(self, conn): - """ - """ self.conn = conn self.log = conn.log def list(self, basedn, scope=ldap.SCOPE_SUBTREE): - """ - List all acis in the directory server below the basedn confined by + """List all acis in the directory server below the basedn confined by scope. - A set of EntryAcis is returned. + :param basedn: Base DN + :type basedn: str + :param scope: ldap.SCOPE_SUBTREE, ldap.SCOPE_BASE, + ldap.SCOPE_ONELEVEL, ldap.SCOPE_SUBORDINATE + :type scope: int + + :returns: A list of EntryAci objects """ + acis = [] rawacientries = self.conn.search_s(basedn, scope, 'aci=*', ['aci']) for rawacientry in rawacientries: @@ -51,24 +60,30 @@ class Aci(object): return acis def lint(self, basedn, scope=ldap.SCOPE_SUBTREE): - """ - Validate and check for potential aci issues. + """Validate and check for potential aci issues. Given a scope and basedn, this will retrieve all the aci's below. A number of checks are then run on the aci in isolation, and in groups. - returns a tuple of (bool, list( dict )) - - bool represents if the acis pass or fail as a whole. - the list contains a list of warnings about your acis. - the dict is structured as: - { - name: "" # DSALEXXXX - severity: "" # LOW MEDIUM HIGH - detail: "" # explination - } + :param basedn: Base DN + :type basedn: str + :param scope: ldap.SCOPE_SUBTREE, ldap.SCOPE_BASE, + ldap.SCOPE_ONELEVEL, ldap.SCOPE_SUBORDINATE + :type scope: int + + :returns: A tuple of (bool, list( dict )) + - Bool represents if the acis pass or fail as a whole. + - The list contains a list of warnings about your acis. + - The dict is structured as:: + + { + name: "" # DSALEXXXX + severity: "" # LOW MEDIUM HIGH + detail: "" # explination + } """ + result = True # Not thread safe!!! self.warnings = [] @@ -85,9 +100,14 @@ class Aci(object): return (result, self.warnings) def format_lint(self, warnings): + """Takes the array of warnings and returns a formatted string. + + :param warnings: The array of warnings + :type warnings: dict + + :returns: Formatted string or warnings """ - Takes the array of warnings and returns a formatted string. - """ + buf = "-------------------------------------------------------------------------------" for warning in warnings: @@ -113,8 +133,7 @@ Advice: {FIX} # These are the aci lint checks. def _lint_dsale_0001_ne_internal(self, acis): - """ - Check for the presence of "not equals" attributes that will inadvertantly + """Check for the presence of "not equals" attributes that will inadvertantly allow the return / modification of internal attributes. """ @@ -151,8 +170,7 @@ Convert the aci to the form "(targetAttr="x || y || z")". ) def _lint_dsale_0002_ne_mult_subtree(self, acis): - """ - This check will show pairs or more of aci that match the same subtree + """This check will show pairs or more of aci that match the same subtree with a != rute. These can cause the other rule to be invalidated! """ diff --git a/src/lib389/lib389/agreement.py b/src/lib389/lib389/agreement.py index eb7afc73e..822f9a33c 100644 --- a/src/lib389/lib389/agreement.py +++ b/src/lib389/lib389/agreement.py @@ -19,13 +19,18 @@ from lib389 import Entry, DirSrv, NoSuchEntryError, InvalidArgumentError class Agreement(object): + """An object that helps to work with agreement entry + + :param conn: An instance + :type conn: lib389.DirSrv + """ + ALWAYS = '0000-2359 0123456' NEVER = '2358-2359 0' proxied_methods = 'search_s getEntry'.split() def __init__(self, conn): - """@param conn - a DirSrv instance""" self.conn = conn self.log = conn.log @@ -34,26 +39,33 @@ class Agreement(object): return DirSrv.__getattr__(self.conn, name) def status(self, agreement_dn, just_status=False): - """Return a formatted string with the replica status. Looking like: - Status for meTo_localhost.localdomain:50389 agmt - localhost.localdomain:50389 - Update in progress: TRUE - Last Update Start: 20131121132756Z - Last Update End: 0 - Num. Changes Sent: 1:10/0 - Num. changes Skipped: None - Last update Status: 0 Replica acquired successfully: - Incremental update started - Init in progress: None - Last Init Start: 0 - Last Init End: 0 - Last Init Status: None - Reap Active: 0 - @param agreement_dn - DN of the replication agreement - - @returns string containing the status of the replica agreement - - @raise NoSuchEntryError - if agreement_dn is an unknown entry + """Get a formatted string with the replica status + + :param agreement_dn: DN of the replica agreement + :type agreement_dn: str + :param just_status: If True, returns just status + :type just_status: bool + + :returns: str -- See below + :raises: NoSuchEntryError - if agreement_dn is an unknown entry + + :example: + :: + + Status for meTo_localhost.localdomain:50389 agmt + localhost.localdomain:50389 + Update in progress: TRUE + Last Update Start: 20131121132756Z + Last Update End: 0 + Num. Changes Sent: 1:10/0 + Num. changes Skipped: None + Last update Status: 0 Replica acquired successfully: + Incremental update started + Init in progress: None + Last Init Start: 0 + Last Init End: 0 + Last Init Status: None + Reap Active: 0 """ attrlist = ['cn', 'nsds5BeginReplicaRefresh', 'nsds5ReplicaRoot', @@ -103,19 +115,20 @@ class Agreement(object): return result 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]) - - @return None + """Check the interval for schedule replication is valid: + HH [0..23] + MM [0..59] + DAYS [0-6]{1,7} + + :param interval: - 'HHMM-HHMM D+' With D=[0123456]+ + - Agreement.ALWAYS + - Agreement.NEVER + :type interval: str + + :returns: None + :raises: ValueError - if the interval is illegal + """ - @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): @@ -148,16 +161,17 @@ class Agreement(object): def schedule(self, agmtdn=None, interval=ALWAYS): """Schedule the replication agreement - @param agmtdn - DN of the replica agreement - @param interval - in the form - - Agreement.ALWAYS - - Agreement.NEVER - - or 'HHMM-HHMM D+' With D=[0123456]+ - @return - None + :param agmtdn: DN of the replica agreement + :type agmtdn: str + :param interval: - 'HHMM-HHMM D+' With D=[0123456]+ + - Agreement.ALWAYS + - Agreement.NEVER + :type interval: str - @raise ValueError - if interval is not valid - ldap.NO_SUCH_OBJECT - if agmtdn does not exist + :returns: None + :raises: - ValueError - if interval is not valid; + - ldap.NO_SUCH_OBJECT - if agmtdn does not exist """ if not agmtdn: raise InvalidArgumentError("agreement DN is missing") @@ -178,37 +192,25 @@ class Agreement(object): self.conn.modify_s(agmtdn, mod) def getProperties(self, agmnt_dn=None, properties=None): - ''' - returns a dictionary of the requested properties. - If properties is missing, it returns all the properties. - @param agmtdn - is the replica agreement DN - @param properties - is the list of properties name - Supported properties are - RA_NAME - RA_SUFFIX - RA_BINDDN - RA_BINDPW - RA_METHOD - RA_DESCRIPTION - RA_SCHEDULE - RA_TRANSPORT_PROT - RA_FRAC_EXCLUDE - RA_FRAC_EXCLUDE_TOTAL_UPDATE - RA_FRAC_STRIP - RA_CONSUMER_PORT - RA_CONSUMER_HOST - RA_CONSUMER_TOTAL_INIT - RA_TIMEOUT - RA_CHANGES - - @return - returns a dictionary of the properties - - @raise ValueError - if invalid property name - ldap.NO_SUCH_OBJECT - if agmtdn does not exist - InvalidArgumentError - missing mandatory argument - - - ''' + """Get a dictionary of the requested properties. + If properties parameter is missing, it returns all the properties. + + :param agmtdn: DN of the replica agreement + :type agmtdn: str + :param properties: List of properties name + :type properties: list + + :returns: Returns a dictionary of the properties + :raises: - ValueError - if invalid property name + - ldap.NO_SUCH_OBJECT - if agmtdn does not exist + - InvalidArgumentError - missing mandatory argument + + :supported properties are: + RA_NAME, RA_SUFFIX, RA_BINDDN, RA_BINDPW, RA_METHOD, + RA_DESCRIPTION, RA_SCHEDULE, RA_TRANSPORT_PROT, RA_FRAC_EXCLUDE, + RA_FRAC_EXCLUDE_TOTAL_UPDATE, RA_FRAC_STRIP, RA_CONSUMER_PORT, + RA_CONSUMER_HOST, RA_CONSUMER_TOTAL_INIT, RA_TIMEOUT, RA_CHANGES + """ if not agmnt_dn: raise InvalidArgumentError("agmtdn is a mandatory argument") @@ -248,45 +250,33 @@ class Agreement(object): def setProperties(self, suffix=None, agmnt_dn=None, agmnt_entry=None, properties=None): - ''' - Set the properties of the agreement. If an 'agmnt_entry' (Entry) - is provided, it updates the entry, else it updates the entry on - the server. If the 'agmnt_dn' is provided it retrieves the entry - using it, else it retrieve the agreement using the 'suffix'. - - @param suffix : suffix stored in that agreement (online update) - @param agmnt_dn: DN of the agreement (online update) - @param agmnt_entry: Entry of a agreement (offline update) - @param properties: dictionary of properties - Supported properties are - RA_NAME - RA_SUFFIX - RA_BINDDN - RA_BINDPW - RA_METHOD - RA_DESCRIPTION - RA_SCHEDULE - RA_TRANSPORT_PROT - RA_FRAC_EXCLUDE - RA_FRAC_EXCLUDE_TOTAL_UPDATE - RA_FRAC_STRIP - RA_CONSUMER_PORT - RA_CONSUMER_HOST - RA_CONSUMER_TOTAL_INIT - RA_TIMEOUT - RA_CHANGES - - - @return None - - @raise ValueError: if unknown properties - ValueError: if invalid agreement_entry - ValueError: if agmnt_dn or suffix are not associated to a - replica - InvalidArgumentError: If missing mandatory parameter - - - ''' + """Set the properties of the agreement entry. If an 'agmnt_entry' + is provided, it updates the entry, else it updates the entry on + the server. If the 'agmnt_dn' is provided it retrieves the entry + using it, else it retrieve the agreement using the 'suffix'. + + :param suffix: Suffix stored in that agreement (online update) + :type suffix: str + :param agmnt_dn: DN of the agreement (online update) + :type agmnt_dn: str + :param agmnt_entry: Entry of a agreement (offline update) + :type agmnt_entry: lib389.Entry + :param properties: Dictionary of properties + :type properties: dict + + :returns: None + :raises: - ValueError - if invalid properties + - ValueError - if invalid agreement_entry + - ValueError - if agmnt_dn or suffix are not associated to a replica + - InvalidArgumentError - missing mandatory argument + + :supported properties are: + RA_NAME, RA_SUFFIX, RA_BINDDN, RA_BINDPW, RA_METHOD, + RA_DESCRIPTION, RA_SCHEDULE, RA_TRANSPORT_PROT, RA_FRAC_EXCLUDE, + RA_FRAC_EXCLUDE_TOTAL_UPDATE, RA_FRAC_STRIP, RA_CONSUMER_PORT, + RA_CONSUMER_HOST, RA_CONSUMER_TOTAL_INIT, RA_TIMEOUT, RA_CHANGES + """ + # No properties provided if len(properties) == 0: return @@ -355,34 +345,37 @@ class Agreement(object): def list(self, suffix=None, consumer_host=None, consumer_port=None, agmtdn=None): - ''' - Returns the search result of the replica agreement(s) under the - replica (replicaRoot is 'suffix'). - - Either 'suffix' or 'agmtdn' need to be specfied. - 'consumer_host' and 'consumer_port' are either not specified or - specified both. - - If 'agmtdn' is specified, it returns the search result entry of - that replication agreement. - else if consumer host/port are specified it returns the replica - agreements toward that consumer host:port. - Finally if neither 'agmtdn' nor 'consumser host/port' are - specifies it returns all the replica agreements under the replica - (replicaRoot is 'suffix'). - - @param - suffix is the suffix targeted by the total update - @param - consumer_host hostname of the consumer - @param - consumer_port port of the consumer - @param - agmtdn DN of the replica agreement - - @return - search result of the replica agreements - - @raise - InvalidArgument: if missing mandatory argument - (agmtdn or suffix, then host and port) - - ValueError - if some properties are not valid - - NoSuchEntryError - If no replica defined for the suffix - ''' + """Returns the search result of the replica agreement(s) under the + replica (replicaRoot is 'suffix'). + + Either 'suffix' or 'agmtdn' need to be specfied. + 'consumer_host' and 'consumer_port' are either not specified or + specified both. + + If 'agmtdn' is specified, it returns the search result entry of + that replication agreement, else if consumer host/port are specified + it returns the replica agreements toward that consumer host:port. + + Finally if neither 'agmtdn' nor 'consumser host/port' are + specifies it returns all the replica agreements under the replica + (replicaRoot is 'suffix'). + + :param suffix: The suffix targeted by the total update + :type suffix: str + :param consumer_host: Hostname of the consumer + :type consumer_host: str + :param consumer_port: Port of the consumer + :type consumer_port: int + :param agmtdn: DN of the replica agreement + :type agmtdn: str + + :returns: Search result of the replica agreements + :raises: - InvalidArgument - if missing mandatory argument + (agmtdn or suffix, then host and port) + - ValueError - if some properties are not valid + - NoSuchEntryError - If no replica defined for the suffix + """ + if not suffix and not agmtdn: raise InvalidArgumentError("suffix or agmtdn are required") @@ -427,19 +420,23 @@ class Agreement(object): def create(self, suffix=None, host=None, port=None, properties=None, winsync=False): """Create (and return) a replication agreement from self to consumer. - - self is the supplier, - - @param suffix - Replication Root - @param host - Consumer host - @param port - Consumer port - @param winsync - Identifies the agree as a WinSync agreement - @param properties - Agreement properties - @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 ldap.LDAPError - ldap error - + Self is the supplier. + + :param suffix: Replication Root + :type suffix: str + :param host: Consumer host + :type host: str + :param port: Consumer port + :type port: int + :param winsync: Identifies the agree as a WinSync agreement + :type winsync: bool + :param properties: Agreement properties + :type properties: dict + + :returns: DN of the created agreement + :raises: - InvalidArgumentError - If the suffix is missing + - NoSuchEntryError - if a replica doesn't exist for that suffix + - ldap.LDAPError - ldap error """ # Check we have a suffix [ mandatory ] @@ -553,14 +550,19 @@ class Agreement(object): agmtdn=None): """Delete a replication agreement - @param suffix - the suffix that the agreement is configured for - @param consumer_host - of the server that the agreement points to - @param consumer_port - of the server that the agreement points to - @param agmtdn - DN of the replica agreement - - @raise ldap.LDAPError - for ldap operation failures - @raise TypeError - if too many agreements were found - @raise NoSuchEntryError - if no agreements were found + :param suffix: The suffix that the agreement is configured for + :type suffix: str + :param consumer_host: Host of the server that the agreement points to + :type consumer_host: str + :param consumer_port: Port of the server that the agreement points to + :type consumer_port: int + :param agmtdn: DN of the replica agreement + :type agmtdn: str + + :returns: None + :raises: - ldap.LDAPError - for ldap operation failures + - TypeError - if too many agreements were found + - NoSuchEntryError - if no agreements were found """ if not (suffix and consumer_host and consumer_port) and not agmtdn: @@ -587,17 +589,21 @@ class Agreement(object): 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) + - 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: The suffix targeted by the total update [mandatory] + :type suffix: str + :param consumer_host: Hostname of the consumer [mandatory] + :type consumer_host: str + :param consumer_port: Port of the consumer [mandatory] + :type consumer_port: int + + :returns: None + :raises: InvalidArgument - if missing mandatory argument """ + # # check the required parameters are set # @@ -653,17 +659,25 @@ class Agreement(object): def pause(self, agmtdn, interval=NEVER): """Pause this replication agreement. This replication agreement - will send no more changes. Use the resume() method to "unpause". - It tries to disable the replica agreement. If it fails (not - implemented in all version), - It uses the schedule() with interval '2358-2359 0' - @param agmtdn - agreement dn - @param interval - (default NEVER) replication schedule to use + will send no more changes. Use the resume() method to "unpause". + + It tries to disable the replica agreement. If it fails (not + implemented in all version), - @return None + It uses the schedule() with interval '2358-2359 0' - @raise ValueError - if interval is not valid + :param agmtdn: agreement dn + :type agmtdn: str + :param interval: - 'HHMM-HHMM D+' With D=[0123456]+ + - Agreement.ALWAYS + - Agreement.NEVER + - Default is NEVER + :type interval: str + + :returns: None + :raises: ValueError - if interval is not valid """ + self.log.info("Pausing replication %s" % agmtdn) mod = [( ldap.MOD_REPLACE, 'nsds5ReplicaEnabled', ['off'])] @@ -678,19 +692,24 @@ class Agreement(object): time.sleep(5) def resume(self, agmtdn, interval=ALWAYS): - """Resume a paused replication agreement, paused with the "pause" - method. - It tries to enabled the replica agreement. If it fails - (not implemented in all versions), - it uses the schedule() with interval '0000-2359 0123456' - @param agmtdn - agreement dn - @param interval - (default ALWAYS) replication schedule to use - - @return None - - @raise ValueError - if interval is not valid - ldap.NO_SUCH_OBJECT - if agmtdn does not exist + """Resume a paused replication agreement, paused with the "pause" method. + It tries to enabled the replica agreement. If it fails + (not implemented in all versions) + It uses the schedule() with interval '0000-2359 0123456'. + + :param agmtdn: agreement dn + :type agmtdn: str + :param interval: - 'HHMM-HHMM D+' With D=[0123456]+ + - Agreement.ALWAYS + - Agreement.NEVER + - Default is NEVER + :type interval: str + + :returns: None + :raises: - ValueError - if interval is not valid + - ldap.NO_SUCH_OBJECT - if agmtdn does not exist """ + self.log.info("Resuming replication %s" % agmtdn) mod = [( ldap.MOD_REPLACE, 'nsds5ReplicaEnabled', ['on'])] @@ -705,7 +724,16 @@ class Agreement(object): time.sleep(2) def changes(self, agmnt_dn): - """Return a list of changes sent by this agreement.""" + """Get a number of changes sent by this agreement. + + :param agmtdn: agreement dn + :type agmtdn: str + + :returns: Number of changes + :raises: NoSuchEntryError - if agreement entry with changes + attribute is not found + """ + retval = 0 try: ent = self.conn.getEntry(ensure_str(agmnt_dn), ldap.SCOPE_BASE, diff --git a/src/lib389/lib389/backend.py b/src/lib389/lib389/backend.py index 75443b261..6f4c8694e 100644 --- a/src/lib389/lib389/backend.py +++ b/src/lib389/lib389/backend.py @@ -386,6 +386,18 @@ class BackendLegacy(object): class Backend(DSLdapObject): + """Backend DSLdapObject with: + - must attributes = ['cn, 'nsslapd-suffix'] + - RDN attribute is 'cn' + + :param instance: A instance + :type instance: lib389.DirSrv + :param dn: Entry DN + :type dn: str + :param batch: Not implemented + :type batch: bool + """ + _must_attributes = ['nsslapd-suffix', 'cn'] def __init__(self, instance, dn=None, batch=False): @@ -399,6 +411,12 @@ class Backend(DSLdapObject): self._mts = MappingTrees(self._instance) def create_sample_entries(self, version): + """Creates sample entries under nsslapd-suffix value + + :param version: Sample entries version, i.e. 001003006 + :type version: str + """ + self._log.debug('Creating sample entries at version %s....' % version) # Grab the correct sample entry config centries = get_sample_entries(version) @@ -446,6 +464,19 @@ class Backend(DSLdapObject): return (dn, valid_props) def create(self, dn=None, properties=None, basedn=None): + """Add a new backend entry, create mapping tree, + and, if requested, sample entries + + :param rdn: RDN of the new entry + :type rdn: str + :param properties: Attributes and parameters for the new entry + :type properties: dict + :param basedn: Base DN of the new entry + :type rdn: str + + :returns: DSLdapObject of the created entry + """ + sample_entries = properties.pop(BACKEND_SAMPLE_ENTRIES, False) # Okay, now try to make the backend. super(Backend, self).create(dn, properties, basedn) @@ -460,6 +491,13 @@ class Backend(DSLdapObject): return self def delete(self): + """Deletes the backend, it's mapping tree and all related indices. + This can be changed with the self._protected flag! + + :raises: - UnwillingToPerform - if backend is protected + - UnwillingToPerform - if nsslapd-state is not 'backend' + """ + if self._protected: raise ldap.UNWILLING_TO_PERFORM("This is a protected backend!") # First check if the mapping tree has our suffix still. @@ -476,7 +514,7 @@ class Backend(DSLdapObject): except ldap.NO_SUCH_OBJECT: # Righto, it's already gone! Do nothing ... pass - # Delete all our related indcies + # Delete all our related indices self._instance.index.delete_all(bename) # Now remove our children, this is all ldbm config @@ -485,13 +523,13 @@ class Backend(DSLdapObject): super(Backend, self).delete() def _lint_mappingtree(self): - """ - Backend lint + """Backend lint This should check for: * missing mapping tree entries for the backend - * missing indcies if we are local and have log access? + * missing indices if we are local and have log access? """ + # Check for the missing mapping tree. suffix = self.get_attr_val_utf8('nsslapd-suffix') bename = self.get_attr_val_bytes('cn') @@ -506,18 +544,30 @@ class Backend(DSLdapObject): return None def get_monitor(self): + """Get a MonitorBackend(DSLdapObject) for the backend""" + monitor = MonitorBackend(instance=self._instance, dn= "cn=monitor,%s" % self._dn, batch=self._batch) return monitor def get_indexes(self): + """Get an Indexes(DSLdapObject) for the backend""" + indexes = Indexes(self._instance, basedn="cn=index,%s" % self._dn) return indexes - # Future: add reindex task for this be. -# This only does ldbm backends. Chaining backends are a special case -# of this, so they can be subclassed off. + class Backends(DSLdapObjects): + """DSLdapObjects that represents DN_LDBM base DN + This only does ldbm backends. Chaining backends are a special case + of this, so they can be subclassed off. + + :param instance: A instance + :type instance: lib389.DirSrv + :param batch: Not implemented + :type batch: bool + """ + def __init__(self, instance, batch=False): super(Backends, self).__init__(instance=instance, batch=batch) self._objectclasses = [BACKEND_OBJECTCLASS_VALUE] diff --git a/src/lib389/lib389/changelog.py b/src/lib389/lib389/changelog.py index 5affceebc..65f7591a1 100644 --- a/src/lib389/lib389/changelog.py +++ b/src/lib389/lib389/changelog.py @@ -15,18 +15,35 @@ from lib389 import DirSrv, Entry, InvalidArgumentError class Changelog(object): + """An object that helps to work with changelog entry + + :param conn: An instance + :type conn: lib389.DirSrv + """ + proxied_methods = 'search_s getEntry'.split() def __init__(self, conn): - """@param conn - a DirSrv instance""" self.conn = conn self.log = conn.log + self.changelogdir = os.path.join(os.path.dirname(self.conn.dbdir), DEFAULT_CHANGELOG_DB) def __getattr__(self, name): if name in Changelog.proxied_methods: return DirSrv.__getattr__(self.conn, name) def list(self, suffix=None, changelogdn=DN_CHANGELOG): + """Get a changelog entry using changelogdn parameter + + :param suffix: Not used + :type suffix: str + :param changelogdn: DN of the changelog entry, DN_CHANGELOG by default + :type changelogdn: str + + :returns: Search result of the replica agreements. + Enpty list if nothing was found + """ + base = changelogdn filtr = "(objectclass=extensibleobject)" @@ -42,9 +59,11 @@ class Changelog(object): def create(self, dbname=DEFAULT_CHANGELOG_DB): """Add and return the replication changelog entry. - If dbname starts with "/" then it's considered a full path, - otherwise it's relative to self.dbdir + :param dbname: Database name, it will be used for creating + a changelog dir path + :type dbname: str """ + dn = DN_CHANGELOG attribute, changelog_name = dn.split(",")[0].split("=", 1) dirpath = os.path.join(os.path.dirname(self.conn.dbdir), dbname) @@ -60,13 +79,14 @@ class Changelog(object): self.conn.add_s(entry) except ldap.ALREADY_EXISTS: self.log.warn("entry %s already exists" % dn) - return(dn) + return dn def delete(self): - ''' - Delete the changelog entry - @raise LDAPError - ''' + """Delete the changelog entry + + :raises: LDAPError - failed to delete changelog entry + """ + try: self.conn.delete_s(DN_CHANGELOG) except ldap.LDAPError as e: @@ -74,6 +94,25 @@ class Changelog(object): raise def setProperties(self, changelogdn=None, properties=None): + """Set the properties of the changelog entry. + + :param changelogdn: DN of the changelog + :type changelogdn: str + :param properties: Dictionary of properties + :type properties: dict + + :returns: None + :raises: - ValueError - if invalid properties + - ValueError - if changelog entry is not found + - InvalidArgumentError - changelog DN is missing + + :supported properties are: + CHANGELOG_NAME, CHANGELOG_DIR, CHANGELOG_MAXAGE, + CHANGELOG_MAXENTRIES, CHANGELOG_TRIM_INTERVAL, + CHANGELOG_COMPACT_INTV, CHANGELOG_CONCURRENT_WRITES, + CHANGELOG_ENCRYPT_ALG, CHANGELOG_SYM_KEY + """ + if not changelogdn: raise InvalidArgumentError("changelog DN is missing") @@ -106,4 +145,10 @@ class Changelog(object): self.conn.modify_s(ents[0].dn, mods) def getProperties(self, changelogdn=None, properties=None): + """Get a dictionary of the requested properties. + If properties parameter is missing, it returns all the properties. + + NotImplemented + """ + raise NotImplemented diff --git a/src/lib389/lib389/mappingTree.py b/src/lib389/lib389/mappingTree.py index dcad9b311..f319276ce 100644 --- a/src/lib389/lib389/mappingTree.py +++ b/src/lib389/lib389/mappingTree.py @@ -377,7 +377,20 @@ class MappingTreeLegacy(object): else: raise InvalidArgumentError("entry or name are mandatory") + class MappingTree(DSLdapObject): + """Mapping tree DSLdapObject with: + - must attributes = ['cn'] + - RDN attribute is 'cn' + + :param instance: A instance + :type instance: lib389.DirSrv + :param dn: Entry DN + :type dn: str + :param batch: Not implemented + :type batch: bool + """ + _must_attributes = ['cn'] def __init__(self, instance, dn=None, batch=False): @@ -389,6 +402,14 @@ class MappingTree(DSLdapObject): class MappingTrees(DSLdapObjects): + """DSLdapObjects that presents Mapping trees + + :param instance: A instance + :type instance: lib389.DirSrv + :param batch: Not implemented + :type batch: bool + """ + def __init__(self, instance, batch=False): super(MappingTrees, self).__init__(instance=instance, batch=batch) self._objectclasses = [MT_OBJECTCLASS_VALUE] diff --git a/src/lib389/lib389/replica.py b/src/lib389/lib389/replica.py index 6d24a7ac8..cdd0a9729 100644 --- a/src/lib389/lib389/replica.py +++ b/src/lib389/lib389/replica.py @@ -791,16 +791,21 @@ class ReplicaLegacy(object): class Replica(DSLdapObject): - """Replica object. There is one "replica" per backend""" + """Replica DSLdapObject with: + - must attributes = ['cn', 'nsDS5ReplicaType', 'nsDS5ReplicaRoot', + 'nsDS5ReplicaBindDN', 'nsDS5ReplicaId'] + - RDN attribute is 'cn' + - There is one "replica" per backend + + :param instance: A instance + :type instance: lib389.DirSrv + :param dn: Entry DN + :type dn: str + :param batch: Not implemented + :type batch: bool + """ def __init__(self, instance, dn=None, batch=False): - """Init the Replica object - - @param instance - a DirSrv object - @param dn - A DN of the replica entry - @param batch - NOT IMPLELMENTED - """ - super(Replica, self).__init__(instance, dn, batch) self._rdn_attribute = 'cn' self._must_attributes = ['cn', REPL_TYPE, @@ -815,8 +820,9 @@ class Replica(DSLdapObject): def _valid_role(role): """Return True if role is valid - @param role - A string containing the "role" name - @return - True if the role is a valid role name, otherwise return False + :param role: MASTER, HUB and CONSUMER + :type role: ReplicaRole + :returns: True if the role is a valid role object, otherwise return False """ if role != ReplicaRole.MASTER and \ @@ -830,9 +836,11 @@ class Replica(DSLdapObject): def _valid_rid(role, rid=None): """Return True if rid is valid for the replica role - @param role - A string containing the role name - @param rid - Only needed if the role is a "master" - @return - True is rid is valid, otherwise return False + :param role: MASTER, HUB and CONSUMER + :type role: ReplicaRole + :param rid: Only needed if the role is a MASTER + :type rid: int + :returns: True is rid is valid, otherwise return False """ if rid is None: @@ -851,13 +859,13 @@ class Replica(DSLdapObject): """Delete a replica related to the provided suffix. If this replica role was ReplicaRole.HUB or ReplicaRole.MASTER, it - also deletes the changelog associated to that replica. If it + also deletes the changelog associated to that replica. If it exists some replication agreement below that replica, they are deleted. - @return None - @raise InvalidArgumentError - if suffix is missing - ldap.LDAPError - for all other update failures + :returns: None + :raises: - InvalidArgumentError - if suffix is missing + - ldap.LDAPError - for all other update failures """ # Get the suffix @@ -884,7 +892,7 @@ class Replica(DSLdapObject): def deleteAgreements(self): """Delete all the agreements for the suffix - @raise LDAPError - If failing to delete or search for agreements + :raises: LDAPError - If failing to delete or search for agreeme :type binddn: strnts """ # Delete the agreements @@ -906,15 +914,15 @@ class Replica(DSLdapObject): def promote(self, newrole, binddn=None, rid=None): """Promote the replica to hub or master - @param newrole - The new replication role for the replica: - ReplicaRole.MASTER - ReplicaRole.HUB - @param binddn - The replication bind dn - only applied to master - @param rid - The replication ID, applies only to promotions to "master" + :param newrole: The new replication role for the replica: MASTER and HUB + :type newrole: ReplicaRole + :param binddn: The replication bind dn - only applied to master + :type binddn: str + :param rid: The replication ID, applies only to promotions to "master" + :type rid: int - @raise ldap.NO_SUCH_OBJECT - If suffix is not replicated - - @raise ValueError + :returns: None + :raises: ValueError - If replica is not promoted """ if not binddn: @@ -979,11 +987,11 @@ class Replica(DSLdapObject): def demote(self, newrole): """Demote a replica to a hub or consumer - @param suffix - The replication suffix - @param newrole - The new replication role of this replica - ReplicaRole.HUB - ReplicaRole.CONSUMER - @raise ValueError + :param newrole: The new replication role for the replica: CONSUMER and HUB + :type newrole: ReplicaRole + + :returns: None + :raises: ValueError - If replica is not demoted """ # Check the role type @@ -1012,9 +1020,9 @@ class Replica(DSLdapObject): raise ValueError('Failed to update replica: ' + str(e)) def get_role(self): - """Return the replica role: + """Return the replica role - @return: 3 for ReplicaRole.MASTER, 2 for ReplicaRole.HUB, 3 for ReplicaRole.CONSUMER + :returns: ReplicaRole.MASTER, ReplicaRole.HUB, ReplicaRole.CONSUMER """ repltype = self.get_attr_val_int(REPL_TYPE) @@ -1034,9 +1042,10 @@ class Replica(DSLdapObject): def check_init(self, agmtdn): """Check that a total update has completed - @returns tuple - first element is done/not done, 2nd is no error/has - error - @param agmtdn - the agreement dn + :param agmtdn: The agreement DN + :type agmtdn: str + + :returns: A tuple - first element is done/not done, 2nd is no error/has error THIS SHOULD BE IN THE NEW AGREEMENT CLASS """ @@ -1083,8 +1092,10 @@ class Replica(DSLdapObject): def wait_init(self, agmtdn): """Initialize replication and wait for completion. - @oaram agmtdn - agreement dn - @return - 0 if the initialization is complete + :param agmtdn: The agreement DN + :type agmtdn: str + + :returns: 0 if the initialization is complete THIS SHOULD BE IN THE NEW AGREEMENT CLASS """ @@ -1113,7 +1124,11 @@ class Replica(DSLdapObject): def start_async(self, agmtdn): """Initialize replication without waiting. - @param agmtdn - agreement dn + + :param agmtdn: The agreement DN + :type agmtdn: str + + :returns: None THIS SHOULD BE IN THE NEW AGREEMENT CLASS """ @@ -1124,9 +1139,10 @@ class Replica(DSLdapObject): def get_ruv_entry(self): """Return the database RUV entry - @return - The database RUV entry - @raise ValeuError - If suffix is not setup for replication - LDAPError - If there is a problem trying to search for the RUV + + :returns: The database RUV entry + :raises: ValeuError - If suffix is not setup for replication + LDAPError - If there is a problem trying to search for the RUV """ try: @@ -1144,10 +1160,12 @@ class Replica(DSLdapObject): """Make a "dummy" update on the the replicated suffix, and check all the provided replicas to see if they received the update. - @param *replica_dirsrvs - DirSrv instance, DirSrv instance, ... - @return True - if all servers have recevioed the update by this - replica, otherwise return False - @raise LDAPError - when failing to update/search database + :param *replica_dirsrvs: DirSrv instance, DirSrv instance, ... + :type *replica_dirsrvs: list of DirSrv + + :returns: True - if all servers have recevioed the update by this + replica, otherwise return False + :raises: LDAPError - when failing to update/search database """ # Generate a unique test value @@ -1187,15 +1205,15 @@ class Replica(DSLdapObject): class Replicas(DSLdapObjects): - """Class of all the Replicas""" + """Replica DSLdapObjects for all replicas - def __init__(self, instance, batch=False): - """Init Replicas - - @param instance - a DirSrv objectc - @param batch - NOT IMPLELMENTED - """ + :param instance: A instance + :type instance: lib389.DirSrv + :param batch: Not implemented + :type batch: bool + """ + def __init__(self, instance, batch=False): super(Replicas, self).__init__(instance=instance, batch=False) self._objectclasses = [REPLICA_OBJECTCLASS_VALUE] self._filterattrs = [REPL_ROOT] @@ -1203,7 +1221,17 @@ class Replicas(DSLdapObjects): self._basedn = DN_MAPPING_TREE def get(self, selector=[], dn=None): - """Wrap Replicas' "get", and set the suffix after we get the replica """ + """Get a child entry (DSLdapObject, Replica, etc.) with dn or selector + using a base DN and objectClasses of our object (DSLdapObjects, Replicas, etc.) + After getting the replica, update the replica._suffix parameter. + + :param dn: DN of wanted entry + :type dn: str + :param selector: An additional filter to objectClasses, i.e. 'backend_name' + :type dn: str + + :returns: A child entry + """ replica = super(Replicas, self).get(selector, dn) if replica: @@ -1214,22 +1242,23 @@ class Replicas(DSLdapObjects): def enable(self, suffix, role, replicaID=None, args=None): """Enable replication for this suffix - @param suffix - The suffix to enable replication for - @param role - ReplicaRole.MASTER, ReplicaRole.HUB or - ReplicaRole.CONSUMER - @param rid - number that identify the supplier replica - (role=ReplicaRole.MASTER) in the topology. For - hub/consumer (role=ReplicaRole.HUB or - ReplicaRole.CONSUMER), rid value is not used. This - parameter is mandatory for supplier. - - @param args - dictionary of additional replica properties - - @return replica DN - - @raise InvalidArgumentError - if missing mandatory arguments - ValueError - argument with invalid value - LDAPError - failed to add replica entry + :param suffix: The suffix to enable replication for + :type suffix: str + :param role: MASTER, HUB and CONSUMER + :type role: ReplicaRole + :param replicaID: number that identify the supplier replica + (role=ReplicaRole.MASTER) in the topology. + For hub/consumer (role=ReplicaRole.HUB or + ReplicaRole.CONSUMER), rid value is not used. + This parameter is mandatory for supplier. + :type replicaID: int + :param args: A dictionary of additional replica properties + :type args: dict + + :returns: Replica DSLdapObject + :raises: - InvalidArgumentError - if missing mandatory arguments + - ValueError - argument with invalid value + - LDAPError - failed to add replica entry """ # Normalize the suffix @@ -1312,8 +1341,11 @@ class Replicas(DSLdapObjects): def disable(self, suffix): """Disable replication on the suffix specified - @param suffix - Replicated suffix to disable - @raise ValueError is suffix is not being replicated + :param suffix: Replicated suffix to disable + :type suffix: str + + :returns: None + :raises: ValueError is suffix is not being replicated """ try: @@ -1332,17 +1364,17 @@ class Replicas(DSLdapObjects): '(%s) LDAP error (%s)' % (suffix, str(e))) def promote(self, suffix, newrole, binddn=None, rid=None): - """Promote the replica speficied by the suffix to the new role - - @param suffix - The replication suffix - @param newrole - The new replication role for the replica: - ReplicaRole.MASTER - ReplicaRole.HUB + """Promote the replica to hub or master - @param binddn - The replication bind dn - only applied to master - @param rid - The replication ID - applies only promotions to "master" + :param newrole: The new replication role for the replica: MASTER and HUB + :type newrole: ReplicaRole + :param binddn: The replication bind dn - only applied to master + :type binddn: str + :param rid: The replication ID, applies only to promotions to "master" + :type rid: int - @raise ldap.NO_SUCH_OBJECT - If suffix is not replicated + :returns: None + :raises: ValueError - If replica is not promoted """ replica = self.get(suffix) @@ -1353,13 +1385,13 @@ class Replicas(DSLdapObjects): replica.promote(newrole, binddn, rid) def demote(self, suffix, newrole): - """Promote the replica speficied by the suffix to the new role + """Demote a replica to a hub or consumer - @param suffix - The replication suffix - @param newrole - The new replication role of this replica - ReplicaRole.HUB - ReplicaRole.CONSUMER - @raise ldap.NO_SUCH_OBJECT - If suffix is not replicated + :param newrole: The new replication role for the replica: CONSUMER and HUB + :type newrole: ReplicaRole + + :returns: None + :raises: ValueError - If replica is not demoted """ replica = self.get(suffix) @@ -1373,9 +1405,12 @@ class Replicas(DSLdapObjects): """Return the DN of the replica from cn=config, this is also known as the mapping tree entry - @param suffix - the replication suffix to get the mapping tree DN - @return - The DN of the replication entry from cn=config + :param suffix: The replication suffix to get the mapping tree DN + :type suffix: str + + :returns: The DN of the replication entry from cn=config """ + try: replica = self.get(suffix) except ldap.NO_SUCH_OBJECT: @@ -1385,9 +1420,9 @@ class Replicas(DSLdapObjects): def get_ruv_entry(self, suffix): """Return the database RUV entry for the provided suffix - @return - The database RUV entry - @raise ValeuError - If suffix is not setup for replication - LDAPError - If there is a problem trying to search for the RUV + :returns: The database RUV entry + :raises: - ValeuError - If suffix is not setup for replication + - LDAPError - If there is a problem trying to search for the RUV """ try: @@ -1400,11 +1435,14 @@ class Replicas(DSLdapObjects): """Make a "dummy" update on the the replicated suffix, and check all the provided replicas to see if they received the update. - @param suffix - the replicated suffix we want to check - @param *replica_dirsrvs - DirSrv instance, DirSrv instance, ... - @return True - if all servers have recevioed the update by this - replica, otherwise return False - @raise LDAPError - when failing to update/search database + :param suffix: The replicated suffix we want to check + :type suffix: str + :param *replica_dirsrvs: DirSrv instance, DirSrv instance, ... + :type *replica_dirsrvs: list of DirSrv + + :returns: True - if all servers have received the update by this + replica, otherwise return False + :raises: LDAPError - when failing to update/search database """ try: diff --git a/src/lib389/lib389/repltools.py b/src/lib389/lib389/repltools.py index 67eb5c312..180a37d35 100644 --- a/src/lib389/lib389/repltools.py +++ b/src/lib389/lib389/repltools.py @@ -13,26 +13,32 @@ log = logging.getLogger(__name__) # Helper functions def _alphanum_key(s): - """Turn the string into a list of string and number parts. - """ + """Turn the string into a list of string and number parts""" + return [int(c) if c.isdigit() else c for c in re.split('([0-9]+)', s)] def smart_sort(str_list): """Sort the given list in the way that humans expect. - @param str_list - a list of strings to sort + + :param str_list: A list of strings to sort + :type str_list: list """ + str_list.sort(key=_alphanum_key) def _getCSNTime(inst, csn): """Take a CSN and get the access log timestamp in seconds - @param inst - A DirSrv object to check access log - @param csn - A "csn" string that is used to find when the csn was logged in - the access log, and what time in seconds it was logged. - @return - The time is seconds that the operation was logged. + :param inst: An instance to check access log + :type inst: lib389.DirSrv + :param csn: A "csn" string that is used to find when the csn was logged in + the access log, and what time in seconds it was logged. + :type csn: str + + :returns: The time is seconds that the operation was logged """ op_line = inst.ds_access_log.match('.*csn=%s' % csn) @@ -46,9 +52,12 @@ def _getCSNTime(inst, csn): def _getCSNandTime(inst, line): """Take the line and find the CSN from the inst's access logs - @param inst - A DirSrv object to check access log - @param line - A "RESULT" line from the access log that contains a "csn" - @return - a tuple containing the "csn" value and the time in seconds when + :param inst: An instance to check access log + :type inst: lib389.DirSrv + :param line: A "RESULT" line from the access log that contains a "csn" + :type line: str + + :returns: A tuple containing the "csn" value and the time in seconds when it was logged. """ @@ -72,21 +81,22 @@ def _getCSNandTime(inst, line): class ReplTools(object): - """Replication tools - """ + """Replication tools""" @staticmethod def checkCSNs(dirsrv_replicas, ignoreCSNs=None): """Gather all the CSN strings from the access and verify all of those CSNs exist on all the other replicas. - @param dirsrv_replicas - a list of DirSrv objects. The list must begin - with master replicas - @param ignoreCSNs - an optional string of csns to be ignored if - the caller knows that some csns can differ eg.: - '57e39e72000000020000|vucsn-57e39e76000000030000' + :param dirsrv_replicas: A list of DirSrv objects. The list must begin + with master replicas + :type dirsrv_replicas: list of lib389.DirSrv + :param ignoreCSNs: An optional string of csns to be ignored if + the caller knows that some csns can differ eg.: + '57e39e72000000020000|vucsn-57e39e76000000030000' + :type ignoreCSNs: str - @return - True if all the CSNs are present, otherwise False + :returns: True if all the CSNs are present, otherwise False """ csn_logs = [] @@ -128,12 +138,16 @@ class ReplTools(object): print a report on how fast all the "ops" replicated to the other replicas. - @param suffix - Replicated suffix - @param ops - a list of "operations" to search for in the access logs - @param replica - Dirsrv object where the entries originated - @param all_replicas - A list of Dirsrv replicas: - (suppliers, hubs, consumers) - @return - The longest time in seconds for an operation to fully converge + :param suffix: Replicated suffix + :type suffix: str + :param ops: a list of "operations" to search for in the access logs + :type ops: list + :param replica: Instance where the entries originated + :type replica: lib389.DirSrv + :param all_replicas: Suppliers, hubs, consumers + :type all_replicas: list of lib389.DirSrv + + :returns: The longest time in seconds for an operation to fully converge """ highest_time = 0 total_time = 0 @@ -197,10 +211,13 @@ class ReplTools(object): """Take a list of DirSrv Objects and check to see if all of the present replication agreements are idle for a particular backend - @param replicas - List of DirSrv objects that are using replication - @param suffix - The replicated suffix - @raise LDAPError - if unable to search for the replication agreements - @return - True if all the agreements are idle, otherwise False + :param replicas: Suppliers, hubs, consumers + :type replicas: list of lib389.DirSrv + :param suffix: Replicated suffix + :type suffix: str + + :raises: LDAPError: if unable to search for the replication agreements + :returns: True if all the agreements are idle, otherwise False """ IDLE_MSG = ('Replica acquired successfully: Incremental ' + @@ -231,17 +248,21 @@ class ReplTools(object): @staticmethod def createReplManager(server, repl_manager_dn=None, repl_manager_pw=None): - '''Create an entry that will be used to bind as replication manager. - - @param server - A DirSrv object to connect to - @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 - @return None - @raise KeyError - if can not find valid values of Bind DN and Pwd - LDAPError - if we fail to add the replication manager - ''' + """Create an entry that will be used to bind as replication manager. + + :param server: An instance to connect to + :type server: lib389.DirSrv + :param repl_manager_dn: DN of the bind entry. If not provided use + the default one + :type repl_manager_dn: str + :param repl_manager_pw: Password of the entry. If not provide use + the default one + :type repl_manager_pw: str + + :returns: None + :raises: - KeyError - if can not find valid values of Bind DN and Pwd + - LDAPError - if we fail to add the replication manager + """ # check the DN and PW try:
0
2ee49b2fe9f96893809d4dbf2c2362a0e018694f
389ds/389-ds-base
try to fix build breakage on RHEL5
commit 2ee49b2fe9f96893809d4dbf2c2362a0e018694f Author: Rich Megginson <[email protected]> Date: Wed Sep 12 15:20:59 2007 +0000 try to fix build breakage on RHEL5 diff --git a/Makefile.in b/Makefile.in index 93a6a2196..17aac1aea 100644 --- a/Makefile.in +++ b/Makefile.in @@ -850,6 +850,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 8261fda7c..afaae43a5 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 with_fhs_opt configdir sampledatadir propertydir schemadir serverdir serverplugindir scripttemplatedir perldir infdir defaultuser defaultgroup instconfigdir WINNT_TRUE WINNT_FALSE LIBSOCKET LIBNSL LIBDL LIBCSTD LIBCRUN initdir perlexec HPUX_TRUE HPUX_FALSE SOLARIS_TRUE SOLARIS_FALSE PKG_CONFIG ICU_CONFIG NETSNMP_CONFIG PACKAGE_BASE_VERSION 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 with_fhs_opt configdir sampledatadir propertydir schemadir serverdir serverplugindir scripttemplatedir perldir infdir defaultuser defaultgroup instconfigdir WINNT_TRUE WINNT_FALSE LIBSOCKET LIBNSL LIBDL LIBCSTD LIBCRUN initdir perlexec HPUX_TRUE HPUX_FALSE SOLARIS_TRUE SOLARIS_FALSE PKG_CONFIG ICU_CONFIG NETSNMP_CONFIG PACKAGE_BASE_VERSION 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. @@ -3836,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 @@ -3870,6 +3871,7 @@ done fi SED=$lt_cv_path_SED + echo "$as_me:$LINENO: result: $SED" >&5 echo "${ECHO_T}$SED" >&6 @@ -4310,7 +4312,7 @@ ia64-*-hpux*) ;; *-*-irix6*) # Find out which ABI we are using. - echo '#line 4313 "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=$? @@ -5445,7 +5447,7 @@ fi # Provide some information about the compiler. -echo "$as_me:5448:" \ +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 @@ -6508,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:6511: $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:6515: \$? = $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. @@ -6776,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:6779: $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:6783: \$? = $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. @@ -6880,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:6883: $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:6887: \$? = $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 @@ -8345,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 @@ -9225,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 9228 "configure" +#line 9251 "configure" #include "confdefs.h" #if HAVE_DLFCN_H @@ -9325,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 9328 "configure" +#line 9351 "configure" #include "confdefs.h" #if HAVE_DLFCN_H @@ -9656,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 @@ -9789,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. @@ -9805,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 @@ -9885,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 @@ -11665,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:11668: $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:11672: \$? = $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. @@ -11769,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:11772: $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:11776: \$? = $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 @@ -12301,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 @@ -12688,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 @@ -12821,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. @@ -12837,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 @@ -12917,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 @@ -13339,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:13342: $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:13346: \$? = $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. @@ -13443,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:13446: $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:13450: \$? = $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 @@ -14888,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 @@ -15275,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 @@ -15408,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. @@ -15424,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 @@ -15504,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 @@ -15646,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:15649: $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:15653: \$? = $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. @@ -15914,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:15917: $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:15921: \$? = $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. @@ -16018,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:16021: $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:16025: \$? = $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 @@ -17483,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 @@ -17870,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 @@ -18003,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. @@ -18019,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 @@ -18099,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 @@ -18351,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 @@ -18484,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. @@ -18500,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 @@ -18580,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 @@ -25919,6 +26020,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
0
9de5d88e200b1657f69c2c3f602f43f77cde0d60
389ds/389-ds-base
Ticket lib389 3 - python 3 support for betxn test Bug Description: Support python 3 for betxn test. Fix Description: python 3 support for betxn test, including addition of rename supprot for mapped objects. https://pagure.io/lib389/issue/3 Author: wibrown Review by: spichugi (Thanks!)
commit 9de5d88e200b1657f69c2c3f602f43f77cde0d60 Author: William Brown <[email protected]> Date: Mon Nov 6 17:05:30 2017 +1000 Ticket lib389 3 - python 3 support for betxn test Bug Description: Support python 3 for betxn test. Fix Description: python 3 support for betxn test, including addition of rename supprot for mapped objects. https://pagure.io/lib389/issue/3 Author: wibrown Review by: spichugi (Thanks!) diff --git a/dirsrvtests/tests/suites/betxns/betxn_test.py b/dirsrvtests/tests/suites/betxns/betxn_test.py index 175496495..9a6e83583 100644 --- a/dirsrvtests/tests/suites/betxns/betxn_test.py +++ b/dirsrvtests/tests/suites/betxns/betxn_test.py @@ -12,23 +12,17 @@ from lib389.tasks import * from lib389.utils import * from lib389.topologies import topology_st +from lib389.plugins import SevenBitCheckPlugin, AttributeUniquenessPlugin, MemberOfPlugin + +from lib389.idm.user import UserAccounts, TEST_USER_PROPERTIES +from lib389.idm.group import Groups + from lib389._constants import DEFAULT_SUFFIX, PLUGIN_7_BIT_CHECK, PLUGIN_ATTR_UNIQUENESS, PLUGIN_MEMBER_OF logging.getLogger(__name__).setLevel(logging.DEBUG) log = logging.getLogger(__name__) - [email protected](scope='module') -def dynamic_plugins(topology_st): - """Enable dynamic plugins - makes plugin testing much easier""" - try: - topology_st.standalone.modify_s(DN_CONFIG, [(ldap.MOD_REPLACE, 'nsslapd-dynamic-plugins', 'on')]) - except ldap.LDAPError as e: - ldap.error('Failed to enable dynamic plugin!' + e.message['desc']) - assert False - - -def test_betxt_7bit(topology_st, dynamic_plugins): +def test_betxt_7bit(topology_st): """Test that the 7-bit plugin correctly rejects an invalid update :id: 9e2ab27b-eda9-4cd9-9968-a1a8513210fd @@ -51,55 +45,39 @@ def test_betxt_7bit(topology_st, dynamic_plugins): log.info('Running test_betxt_7bit...') - USER_DN = 'uid=test_entry,' + DEFAULT_SUFFIX - eight_bit_rdn = six.u('uid=Fu\u00c4\u00e8') - BAD_RDN = eight_bit_rdn.encode('utf-8') + BAD_RDN = u'uid=Fu\u00c4\u00e8' - # This plugin should on by default, but just in case... - topology_st.standalone.plugins.enable(name=PLUGIN_7_BIT_CHECK) + sevenbc = SevenBitCheckPlugin(topology_st.standalone) + sevenbc.enable() + topology_st.standalone.restart() - # Add our test user - try: - topology_st.standalone.add_s(Entry((USER_DN, {'objectclass': "top extensibleObject".split(), - 'sn': '1', - 'cn': 'test 1', - 'uid': 'test_entry', - 'userpassword': 'password'}))) - except ldap.LDAPError as e: - log.error('Failed to add test user' + USER_DN + ': error ' + e.message['desc']) - assert False + + users = UserAccounts(topology_st.standalone, basedn=DEFAULT_SUFFIX) + user = users.create(properties=TEST_USER_PROPERTIES) # Attempt a modrdn, this should fail + try: - topology_st.standalone.rename_s(USER_DN, BAD_RDN, delold=0) + user.rename(BAD_RDN) log.fatal('test_betxt_7bit: Modrdn operation incorrectly succeeded') assert False except ldap.LDAPError as e: - log.info('Modrdn failed as expected: error ' + e.message['desc']) + log.info('Modrdn failed as expected: error %s' % str(e)) # Make sure the operation did not succeed, attempt to search for the new RDN - try: - entries = topology_st.standalone.search_s(DEFAULT_SUFFIX, ldap.SCOPE_SUBTREE, BAD_RDN) - if entries: - log.fatal('test_betxt_7bit: Incorrectly found the entry using the invalid RDN') - assert False - except ldap.LDAPError as e: - log.fatal('Error while searching for test entry: ' + e.message['desc']) - assert False + + user_check = users.get("testuser") + + assert user_check.dn == user.dn # # Cleanup - remove the user # - try: - topology_st.standalone.delete_s(USER_DN) - except ldap.LDAPError as e: - log.fatal('Failed to delete test entry: ' + e.message['desc']) - assert False - + user.delete() log.info('test_betxt_7bit: PASSED') -def test_betxn_attr_uniqueness(topology_st, dynamic_plugins): +def test_betxn_attr_uniqueness(topology_st): """Test that we can not add two entries that have the same attr value that is defined by the plugin @@ -124,50 +102,40 @@ def test_betxn_attr_uniqueness(topology_st, dynamic_plugins): USER1_DN = 'uid=test_entry1,' + DEFAULT_SUFFIX USER2_DN = 'uid=test_entry2,' + DEFAULT_SUFFIX - topology_st.standalone.plugins.enable(name=PLUGIN_ATTR_UNIQUENESS) + attruniq = AttributeUniquenessPlugin(topology_st.standalone) + attruniq.enable() + topology_st.standalone.restart() - # Add the first entry - try: - topology_st.standalone.add_s(Entry((USER1_DN, {'objectclass': "top extensibleObject".split(), - 'sn': '1', - 'cn': 'test 1', - 'uid': 'test_entry1', - 'userpassword': 'password1'}))) - except ldap.LDAPError as e: - log.fatal('test_betxn_attr_uniqueness: Failed to add test user: ' + - USER1_DN + ', error ' + e.message['desc']) - assert False + users = UserAccounts(topology_st.standalone, basedn=DEFAULT_SUFFIX) + user1 = users.create(properties={ + 'uid': 'testuser1', + 'cn' : 'testuser1', + 'sn' : 'user1', + 'uidNumber' : '1001', + 'gidNumber' : '2001', + 'homeDirectory' : '/home/testuser1' + }) - # Add the second entry with a duplicate uid try: - topology_st.standalone.add_s(Entry((USER2_DN, {'objectclass': "top extensibleObject".split(), - 'sn': '2', - 'cn': 'test 2', - 'uid': 'test_entry2', - 'uid': 'test_entry1', # Duplicate value - 'userpassword': 'password2'}))) + user2 = users.create(properties={ + 'uid': ['testuser2', 'testuser1'], + 'cn' : 'testuser2', + 'sn' : 'user2', + 'uidNumber' : '1002', + 'gidNumber' : '2002', + 'homeDirectory' : '/home/testuser2' + }) log.fatal('test_betxn_attr_uniqueness: The second entry was incorrectly added.') assert False except ldap.LDAPError as e: - log.error('test_betxn_attr_uniqueness: Failed to add test user as expected: ' + - USER1_DN + ', error ' + e.message['desc']) + log.error('test_betxn_attr_uniqueness: Failed to add test user as expected:') - # - # Cleanup - disable plugin, remove test entry - # - topology_st.standalone.plugins.disable(name=PLUGIN_ATTR_UNIQUENESS) - - try: - topology_st.standalone.delete_s(USER1_DN) - except ldap.LDAPError as e: - log.fatal('test_betxn_attr_uniqueness: Failed to delete test entry1: ' + - e.message['desc']) - assert False + user1.delete() log.info('test_betxn_attr_uniqueness: PASSED') -def test_betxn_memberof(topology_st, dynamic_plugins): +def test_betxn_memberof(topology_st): """Test PLUGIN_MEMBER_OF plugin :id: 70d0b96e-b693-4bf7-bbf5-102a66ac5993 @@ -192,55 +160,34 @@ def test_betxn_memberof(topology_st, dynamic_plugins): ENTRY2_DN = 'cn=group2,' + DEFAULT_SUFFIX PLUGIN_DN = 'cn=' + PLUGIN_MEMBER_OF + ',cn=plugins,cn=config' - # Enable and configure memberOf plugin - topology_st.standalone.plugins.enable(name=PLUGIN_MEMBER_OF) - try: - topology_st.standalone.modify_s(PLUGIN_DN, [(ldap.MOD_REPLACE, 'memberofgroupattr', 'member'), - (ldap.MOD_REPLACE, 'memberofAutoAddOC', 'referral')]) - except ldap.LDAPError as e: - log.fatal('test_betxn_memberof: Failed to update config(member): error ' + e.message['desc']) - assert False + memberof = MemberOfPlugin(topology_st.standalone) + memberof.enable() + memberof.set_autoaddoc('referral') + # memberof.add_groupattr('member') # This is already the default. + topology_st.standalone.restart() - # Add our test entries - try: - topology_st.standalone.add_s(Entry((ENTRY1_DN, {'objectclass': "top groupofnames".split(), - 'cn': 'group1'}))) - except ldap.LDAPError as e: - log.error('test_betxn_memberof: Failed to add group1:' + - ENTRY1_DN + ', error ' + e.message['desc']) - assert False + groups = Groups(topology_st.standalone, DEFAULT_SUFFIX) + group1 = groups.create(properties={ + 'cn' : 'group1', + }) - try: - topology_st.standalone.add_s(Entry((ENTRY2_DN, {'objectclass': "top groupofnames".split(), - 'cn': 'group1'}))) - except ldap.LDAPError as e: - log.error('test_betxn_memberof: Failed to add group2:' + - ENTRY2_DN + ', error ' + e.message['desc']) - assert False - - # - # Test mod replace - # - - # Add group2 to group1 - it should fail with objectclass violation - try: - topology_st.standalone.modify_s(ENTRY1_DN, [(ldap.MOD_REPLACE, 'member', ENTRY2_DN)]) - log.fatal('test_betxn_memberof: Group2 was incorrectly allowed to be added to group1') - assert False - except ldap.LDAPError as e: - log.info('test_betxn_memberof: Group2 was correctly rejected (mod replace): error ' + e.message['desc']) + group2 = groups.create(properties={ + 'cn' : 'group2', + }) - # - # Test mod add - # + # We may need to mod groups to not have nsMemberOf ... ? + if not ds_is_older('1.3.7'): + group1.remove('objectClass', 'nsMemberOf') + group2.remove('objectClass', 'nsMemberOf') # Add group2 to group1 - it should fail with objectclass violation try: + group1.add_member(group2.dn) topology_st.standalone.modify_s(ENTRY1_DN, [(ldap.MOD_ADD, 'member', ENTRY2_DN)]) log.fatal('test_betxn_memberof: Group2 was incorrectly allowed to be added to group1') assert False except ldap.LDAPError as e: - log.info('test_betxn_memberof: Group2 was correctly rejected (mod add): error ' + e.message['desc']) + log.info('test_betxn_memberof: Group2 was correctly rejected (mod add): error') # # Done diff --git a/src/lib389/lib389/_mapped_object.py b/src/lib389/lib389/_mapped_object.py index f73cb25f3..c7e4cca03 100644 --- a/src/lib389/lib389/_mapped_object.py +++ b/src/lib389/lib389/_mapped_object.py @@ -538,6 +538,42 @@ class DSLdapObject(DSLogging): conn.simple_bind_s(self.dn, password) return conn + # Modifies the DN of an entry to the new fqdn provided + def rename(self, new_rdn, newsuperior=None): + """Renames the object within the tree. + + If you provide a newsuperior, this will move the object in the tree. + If you only provide a new_rdn, it stays in the same branch, but just + changes the rdn. + + Note, if you use newsuperior, you may move this object outside of the + scope of the related DSLdapObjects manager, which may cause it not to + appear in .get() requests. + + :param new_rdn: RDN of the new entry + :type new_rdn: str + :param newsuperior: New parent DN + :type newsuperior: str + """ + # When we are finished with this, we need to update our DN + # To do this, we probably need to search the new rdn as a filter, + # and the superior as the base (if it changed) + if self._protected: + return + self._instance.rename_s(self._dn, new_rdn, newsuperior, serverctrls=self._server_controls, clientctrls=self._client_controls) + search_base = self._basedn + if newsuperior != None: + # Well, the new DN should be rdn + newsuperior. + self._dn = '%s,%s' % (new_rdn, newsuperior) + else: + old_dn_parts = ldap.explode_dn(self._dn) + # Replace the rdn + old_dn_parts[0] = new_rdn + self._dn = ",".join(old_dn_parts) + assert self.exists() + + # assert we actually got the change right .... + def delete(self): """Deletes the object defined by self._dn. This can be changed with the self._protected flag!
0
23c5c1b65de70763bc4340b83ccb1e471f92984b
389ds/389-ds-base
Bug 621008 - parsing purge RUV from changelog at startup fails The purge RUV contains a single CSN per vector representing the last change trimmed from the changelog from each master. At shutdown this RUV is flushed to the changelog to a special entry and it's read and deleted from the changelog at startup. _cl5ReadRUV() calls ruv_init_from_bervals() which uses get_ruvelement_from_berval() on each berval that was read from the changelog's purge RUV. The problem is that get_ruvelement_from_berval() rejects any vector that doesn't have two CSNs, a minimum and a maximum. Thus, a replica that starts up is always missing a purge vector until the next time trimming occurs and the in-memory purge vector is updated. This can cause replication to continue when changes that still need to be sent to a consumer have been trimmed from the changelog. This patch sets a dummy CSN in the purge RUV, which is parsed correctly. This will cause replication to halt instead of skipping changes that have been trimmed from the changelog, which is the proper thing to do. Thanks to Ulf for contributing this patch!
commit 23c5c1b65de70763bc4340b83ccb1e471f92984b Author: Nathan Kinder <[email protected]> Date: Mon Dec 13 13:22:58 2010 -0800 Bug 621008 - parsing purge RUV from changelog at startup fails The purge RUV contains a single CSN per vector representing the last change trimmed from the changelog from each master. At shutdown this RUV is flushed to the changelog to a special entry and it's read and deleted from the changelog at startup. _cl5ReadRUV() calls ruv_init_from_bervals() which uses get_ruvelement_from_berval() on each berval that was read from the changelog's purge RUV. The problem is that get_ruvelement_from_berval() rejects any vector that doesn't have two CSNs, a minimum and a maximum. Thus, a replica that starts up is always missing a purge vector until the next time trimming occurs and the in-memory purge vector is updated. This can cause replication to continue when changes that still need to be sent to a consumer have been trimmed from the changelog. This patch sets a dummy CSN in the purge RUV, which is parsed correctly. This will cause replication to halt instead of skipping changes that have been trimmed from the changelog, which is the proper thing to do. Thanks to Ulf for contributing this patch! diff --git a/ldap/servers/plugins/replication/cl5_api.c b/ldap/servers/plugins/replication/cl5_api.c index b7c722927..72ebaa0bb 100644 --- a/ldap/servers/plugins/replication/cl5_api.c +++ b/ldap/servers/plugins/replication/cl5_api.c @@ -33,6 +33,7 @@ * * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. * Copyright (C) 2005 Red Hat, Inc. + * Copyright (C) 2010 Hewlett-Packard Development Company, L.P. * All rights reserved. * END COPYRIGHT BLOCK **/ @@ -3425,6 +3426,13 @@ static int _cl5WriteRUV (CL5DBFile *file, PRBool purge) if (purge) { + /* Set the minimum CSN of each vector to a dummy CSN that contains + * just a replica ID, e.g. 00000000000000010000. + * The minimum CSN in a purge RUV is not used so the value doesn't + * matter, but it needs to be set to something so that it can be + * flushed to changelog at shutdown and parsed at startup with the + * regular string-to-RUV parsing routines. */ + ruv_insert_dummy_min_csn(file->purgeRUV); key.data = _cl5GetHelperEntryKey (PURGE_RUV_TIME, csnStr); rc = ruv_to_bervals(file->purgeRUV, &vals); } diff --git a/ldap/servers/plugins/replication/repl5_ruv.c b/ldap/servers/plugins/replication/repl5_ruv.c index d2917ac81..02f9c1b14 100644 --- a/ldap/servers/plugins/replication/repl5_ruv.c +++ b/ldap/servers/plugins/replication/repl5_ruv.c @@ -33,6 +33,7 @@ * * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. * Copyright (C) 2005 Red Hat, Inc. + * Copyright (C) 2010 Hewlett-Packard Development Company, L.P. * All rights reserved. * END COPYRIGHT BLOCK **/ @@ -1946,6 +1947,26 @@ ruv_force_csn_update (RUV *ruv, CSN *csn) } } +/* This routine is used to iterate the elements in a RUV and set each vector's ++ * minimal CSN to a dummy with just the rid set, e.g. 00000000000000010000 */ +void +ruv_insert_dummy_min_csn (RUV *ruv) +{ + RUVElement *r; + int cookie; + + for (r = dl_get_first (ruv->elements, &cookie); r; + r = dl_get_next (ruv->elements, &cookie)) { + if (r->csn && !r->min_csn) { + CSN *dummycsn = csn_new(); + csn_init(dummycsn); + csn_set_replicaid(dummycsn, csn_get_replicaid(r->csn)); + r->min_csn = dummycsn; + } + } +} + + #ifdef TESTING /* Some unit tests for code in this file */ static void diff --git a/ldap/servers/plugins/replication/repl5_ruv.h b/ldap/servers/plugins/replication/repl5_ruv.h index 688f94420..0a0777e7b 100644 --- a/ldap/servers/plugins/replication/repl5_ruv.h +++ b/ldap/servers/plugins/replication/repl5_ruv.h @@ -33,6 +33,7 @@ * * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. * Copyright (C) 2005 Red Hat, Inc. + * Copyright (C) 2010 Hewlett-Packard Development Company, L.P. * All rights reserved. * END COPYRIGHT BLOCK **/ @@ -120,6 +121,7 @@ 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); +void ruv_insert_dummy_min_csn (RUV *ruv); #ifdef __cplusplus } #endif
0
39714d3d7916123b1f1ca86ec43342e29a6f5fec
389ds/389-ds-base
Bug 710377 - Import with chain-on-update crashes ns-slapd If you perform an import using ldif2db for a suffix that is configured to chain-on-update, ns-slapd will crash due to a NULL pointer dereference. The problem is that the chaining backends are not loaded when ns-slapd is run in ldif2db mode. This results in the chaining backend being NULL. To fix this issue, we should return the local backend in the chain-on-update distribution function when we are unable to find a backend by name. We can assume that this only occurs when an import is being done. This should allow one to use ldif2db to do an offline replica initialization when chain-on-update is configured.
commit 39714d3d7916123b1f1ca86ec43342e29a6f5fec Author: Nathan Kinder <[email protected]> Date: Fri Jun 3 11:23:37 2011 -0700 Bug 710377 - Import with chain-on-update crashes ns-slapd If you perform an import using ldif2db for a suffix that is configured to chain-on-update, ns-slapd will crash due to a NULL pointer dereference. The problem is that the chaining backends are not loaded when ns-slapd is run in ldif2db mode. This results in the chaining backend being NULL. To fix this issue, we should return the local backend in the chain-on-update distribution function when we are unable to find a backend by name. We can assume that this only occurs when an import is being done. This should allow one to use ldif2db to do an offline replica initialization when chain-on-update is configured. diff --git a/ldap/servers/plugins/replication/replutil.c b/ldap/servers/plugins/replication/replutil.c index 0da0f573a..b828a2aa1 100644 --- a/ldap/servers/plugins/replication/replutil.c +++ b/ldap/servers/plugins/replication/replutil.c @@ -850,32 +850,49 @@ repl_chain_on_update(Slapi_PBlock *pb, Slapi_DN * target_dn, for (ii = 0; ii < be_count; ++ii) { Slapi_Backend *be = slapi_be_select_by_instance_name(mtn_be_names[ii]); - if (slapi_be_is_flag_set(be,SLAPI_BE_FLAG_REMOTE_DATA)) - { - chaining_backend = ii; - } - else - { - local_backend = ii; - if (mtn_be_states[ii] == SLAPI_BE_STATE_ON) + if (be) { + if (slapi_be_is_flag_set(be,SLAPI_BE_FLAG_REMOTE_DATA)) { - local_online = PR_TRUE; + chaining_backend = ii; + } + else + { + local_backend = ii; + if (mtn_be_states[ii] == SLAPI_BE_STATE_ON) + { + local_online = PR_TRUE; + } } - } #ifdef DEBUG_CHAIN_ON_UPDATE - if (is_internal) { - slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name, "repl_chain_on_update: conn=-1 op=%d be " - "%s is the %s backend and is %s\n", opid, - mtn_be_names[ii], (chaining_backend == ii) ? "chaining" : "local", - (mtn_be_states[ii] == SLAPI_BE_STATE_ON) ? "online" : "offline"); - } else { - slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name, "repl_chain_on_update: conn=%" PRIu64 " op=%d be " - "%s is the %s backend and is %s\n", connid, opid, - mtn_be_names[ii], (chaining_backend == ii) ? "chaining" : "local", - (mtn_be_states[ii] == SLAPI_BE_STATE_ON) ? "online" : "offline"); + if (is_internal) { + slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name, "repl_chain_on_update: conn=-1 op=%d be " + "%s is the %s backend and is %s\n", opid, + mtn_be_names[ii], (chaining_backend == ii) ? "chaining" : "local", + (mtn_be_states[ii] == SLAPI_BE_STATE_ON) ? "online" : "offline"); + } else { + slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name, "repl_chain_on_update: conn=%" PRIu64 " op=%d be " + "%s is the %s backend and is %s\n", connid, opid, + mtn_be_names[ii], (chaining_backend == ii) ? "chaining" : "local", + (mtn_be_states[ii] == SLAPI_BE_STATE_ON) ? "online" : "offline"); - } + } +#endif + } else { + /* A chaining backend will not be found during import. We will just return the + * local backend in this case, which seems like the right thing to do to allow + * offline replication initialization. */ +#ifdef DEBUG_CHAIN_ON_UPDATE + if (is_internal) { + slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name, "repl_chain_on_update: conn=-1 op=%d be " + "%s not found. Assuming it is the chaining backend and we are doing an import.\n", + opid, mtn_be_names[ii]); + } else { + slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name, "repl_chain_on_update: conn=%" PRIu64 " op=%d be " + "%s not found. Assuming it is the chaining backend and we are doing an import.\n", + connid, opid, mtn_be_names[ii]); + } #endif + } } /* if no chaining backends are defined, just use the local one */
0
22a8572c7663dd133a017129f484b16398c4a300
389ds/389-ds-base
Ticket 47437 - Some attributes in cn=config should not be multivalued Description: Many configuration attributes are not defined in the schema, this allows for duplicate attributes, when only one should be allowed. As well as invalid values being added to certain attributes. Adding all the attributes to the schema allows for syntax checking, and enforcing single/multiple valued attributes. https://fedorahosted.org/389/ticket/47437 Successfully tested with freeipa-3.3.3.4 on f20 Reviewed by: rmeggins & tbordaz(Thanks!!)
commit 22a8572c7663dd133a017129f484b16398c4a300 Author: Mark Reynolds <[email protected]> Date: Mon Feb 10 11:18:07 2014 -0500 Ticket 47437 - Some attributes in cn=config should not be multivalued Description: Many configuration attributes are not defined in the schema, this allows for duplicate attributes, when only one should be allowed. As well as invalid values being added to certain attributes. Adding all the attributes to the schema allows for syntax checking, and enforcing single/multiple valued attributes. https://fedorahosted.org/389/ticket/47437 Successfully tested with freeipa-3.3.3.4 on f20 Reviewed by: rmeggins & tbordaz(Thanks!!) diff --git a/ldap/schema/01core389.ldif b/ldap/schema/01core389.ldif index 8fd5e8266..5779d30ea 100644 --- a/ldap/schema/01core389.ldif +++ b/ldap/schema/01core389.ldif @@ -160,6 +160,141 @@ attributeTypes: ( 2.16.840.1.113730.3.1.2165 NAME 'schemaUpdateObjectclassAccept attributeTypes: ( 2.16.840.1.113730.3.1.2166 NAME 'schemaUpdateObjectclassReject' 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.2167 NAME 'schemaUpdateAttributeAccept' 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.2168 NAME 'schemaUpdateAttributeReject' 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.2169 NAME 'nsslapd-pagedsizelimit' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2170 NAME 'nsslapd-accesslog-level' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2171 NAME 'nsslapd-accesslog-maxlogsperdir' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2172 NAME 'nsslapd-accesslog-maxlogsize' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2173 NAME 'nsslapd-errorlog-maxlogsize' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2174 NAME 'nsslapd-auditlog-maxlogsize' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2175 NAME 'nsslapd-accesslog-logrotationsync-enabled' 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.2176 NAME 'nsslapd-errorlog-logrotationsync-enabled' 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.2177 NAME 'nsslapd-auditlog-logrotationsync-enabled' 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.2178 NAME 'nsslapd-accesslog-logrotationsynchour' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2179 NAME 'nsslapd-errorlog-logrotationsynchour' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2180 NAME 'nsslapd-auditlog-logrotationsynchour' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2181 NAME 'nsslapd-accesslog-logrotationsyncmin' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2182 NAME 'nsslapd-errorlog-logrotationsyncmin' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2183 NAME 'nsslapd-audit-logrotationsyncmin' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2184 NAME 'nsslapd-accesslog-logrotationtime' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2185 NAME 'nsslapd-errorlog-logrotationtime' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2186 NAME 'nsslapd-auditlog-logrotationtime' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2187 NAME 'nsslapd-accesslog-logrotationtimeunit' 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.2188 NAME 'nsslapd-errorlog-logrotationtimeunit' 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.2189 NAME 'nsslapd-auditlog-logrotationtimeunit' 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.2190 NAME 'nsslapd-accesslog-logmaxdiskspace' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2191 NAME 'nsslapd-errorlog-logmaxdiskspace' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2192 NAME 'nsslapd-auditlog-logmaxdiskspace' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2193 NAME 'nsslapd-accesslog-logminfreediskspace' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2194 NAME 'nsslapd-errorlog-logminfreediskspace' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2195 NAME 'nsslapd-auditlog-logminfreediskspace' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2196 NAME 'nsslapd-accesslog-logexpirationtime' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2197 NAME 'nsslapd-errorlog-logexpirationtime' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2198 NAME 'nsslapd-auditlog-logexpirationtime' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2199 NAME 'nsslapd-accesslog-logexpirationtimeunit' 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.2200 NAME 'nsslapd-errorlog-logexpirationtimeunit' 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.2201 NAME 'nsslapd-auditlog-logexpirationtimeunit' 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.2202 NAME 'nsslapd-accesslog-logging-enabled' 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.2203 NAME 'nsslapd-errorlog-logging-enabled' 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.2204 NAME 'nsslapd-auditlog-logging-enabled' 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.2205 NAME 'nsslapd-auditlog-logging-hide-unhashed-pw' 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.2206 NAME 'nsslapd-unhashed-pw-switch' 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.2207 NAME 'nsslapd-rootdn' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.12 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2208 NAME 'nsslapd-rootdnpw' 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.2209 NAME 'nsslapd-rootpwstoragescheme' 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.2210 NAME 'nsslapd-auditlog' 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.2211 NAME 'nsslapd-dynamicconf' 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.2212 NAME 'nsslapd-useroc' 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.2213 NAME 'nsslapd-userat' 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.2214 NAME 'nsslapd-svrtab' 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.2215 NAME 'nsslapd-allow-unauthenticated-binds' 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.2216 NAME 'nsslapd-require-secure-binds' 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.2217 NAME 'nsslapd-allow-anonymous-access' 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.2218 NAME 'nsslapd-localssf' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2219 NAME 'nsslapd-minssf' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2220 NAME 'nsslapd-minssf-exclude-rootdse' 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.2221 NAME 'nsslapd-validate-cert' 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.2222 NAME 'nsslapd-localuser' 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.2223 NAME 'nsslapd-localhost' 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.2224 NAME 'nsslapd-port' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2225 NAME 'nsslapd-workingdir' 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.2226 NAME 'nsslapd-listenhost' 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.2227 NAME 'nsslapd-snmp-index' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2228 NAME 'nsslapd-ldapifilepath' 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.2229 NAME 'nsslapd-ldapilisten' 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.2230 NAME 'nsslapd-ldapiautobind' 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.2231 NAME 'nsslapd-ldapimaprootdn' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.12 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2232 NAME 'nsslapd-ldapimaptoentries' 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.2233 NAME 'nsslapd-ldapiuidnumbertype' 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.2234 NAME 'nsslapd-ldapigidnumbertype' 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.2235 NAME 'nsslapd-ldapientrysearchbase' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.12 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2236 NAME 'nsslapd-anonlimitsdn' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.12 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2237 NAME 'nsslapd-counters' 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.2238 NAME 'nsslapd-security' 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.2239 NAME 'nsslapd-SSL3ciphers' 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.2240 NAME 'nsslapd-accesslog' 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.2241 NAME 'nsslapd-errorlog' 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.2242 NAME 'nsslapd-securePort' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2243 NAME 'nsslapd-securelistenhost' 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.2244 NAME 'nnslapd-threadnumber' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2245 NAME 'nsslapd-maxthreadsperconn' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2246 NAME 'nsslapd-maxdescriptors' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2247 NAME 'nsslapd-conntablesize' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2248 NAME 'nsslapd-reservedescriptors' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2249 NAME 'nsslapd-idletimeout' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2250 NAME 'nsslapd-ioblocktimeout' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2251 NAME 'nsslapd-accesscontrol' 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.2252 NAME 'nsslapd-groupevalnestlevel' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2253 NAME 'nsslapd-nagle' 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.2254 NAME 'nsslapd-pwpolicy-local' 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.2255 NAME 'passwordIsGlobalPolicy' 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.2256 NAME 'passwordLegacyPolicy' 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.2257 NAME 'nsslapd-accesslog-logbuffering' 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.2258 NAME 'nsslapd-csnlogging' 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.2259 NAME 'nsslapd-return-exact-case' 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.2260 NAME 'nsslapd-result-tweak' 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.2261 NAME 'nsslapd-attribute-name-exceptions' 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.2262 NAME 'nsslapd-maxbersize' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2263 NAME 'nsslapd-maxsasliosize' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2264 NAME 'nsslapd-max-filter-nest-level' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2265 NAME 'nsslapd-versionstring' 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.2266 NAME 'nsslapd-enquote-sup-oc' 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.2267 NAME 'nsslapd-certmap-basedn' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.12 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2268 NAME 'nsslapd-accesslog-list' 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.2269 NAME 'nsslapd-errorlog-list' 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.2270 NAME 'nsslapd-auditlog-list' 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.2271 NAME 'nsslapd-rewrite-rfc1274' 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.2272 NAME 'nsslapd-plugin-binddn-tracking' 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.2273 NAME 'nsslapd-config' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.12 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2274 NAME 'nsslapd-instancedir' 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.2275 NAME 'nsslapd-schemadir' 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.2276 NAME 'nsslapd-lockdir' 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.2277 NAME 'nsslapd-tmpdir' 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.2278 NAME 'nsslapd-certdir' 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.2279 NAME 'nsslapd-ldifdir' 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.2280 NAME 'nsslapd-bakdir' 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.2281 NAME 'nsslapd-saslpath' 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.2282 NAME 'nsslapd-rundir' 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.2283 NAME 'nsslapd-SSLclientAuth' 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.2284 NAME 'nsslapd-ssl-check-hostname' 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.2285 NAME 'nsslapd-hash-filters' 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.2286 NAME 'nsslapd-outbound-ldap-io-timeout' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2287 NAME 'nsslapd-force-sasl-external' 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.2288 NAME 'nsslapd-defaultnamingcontext' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.12 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2289 NAME 'nsslapd-disk-monitoring' 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.2290 NAME 'nsslapd-disk-monitoring-threshold' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2291 NAME 'nsslapd-disk-monitoring-grace-period' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2292 NAME 'nsslapd-disk-monitoring-logging-critical' 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.2293 NAME 'nsslapd-ndn-cache-enabled' 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.2294 NAME 'nsslapd-ndn-cache-max-size' 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.2295 NAME 'nsslapd-allowed-sasl-mechanisms' 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.2296 NAME 'nsslapd-ignore-virtual-attrs' 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.2297 NAME 'nsslapd-search-return-original-type-switch' 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.2298 NAME 'nsslapd-enable-turbo-mode' 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.2299 NAME 'nsslapd-connection-buffer' 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.2300 NAME 'nsslapd-connection-nocanon' 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.2301 NAME 'nsslapd-plugin-logging' 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.2302 NAME 'nsslapd-listen-backlog-size' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2303 NAME 'nsslapd-ignore-time-skew' 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 # diff --git a/ldap/servers/slapd/libglobs.c b/ldap/servers/slapd/libglobs.c index 8f8fe327c..7abc3b046 100644 --- a/ldap/servers/slapd/libglobs.c +++ b/ldap/servers/slapd/libglobs.c @@ -750,10 +750,10 @@ static struct config_get_and_set { NULL, 0, (void**)&global_slapdFrontendConfig.listenhost, CONFIG_STRING, NULL, NULL/* NULL value is allowed */}, - {CONFIG_SNMP_INDEX_ATTRIBUTE, config_set_snmp_index, - NULL, 0, - (void**) &global_slapdFrontendConfig.snmp_index, - CONFIG_INT, NULL, DEFAULT_SNMP_INDEX}, + {CONFIG_SNMP_INDEX_ATTRIBUTE, config_set_snmp_index, + NULL, 0, + (void**) &global_slapdFrontendConfig.snmp_index, + CONFIG_INT, NULL, DEFAULT_SNMP_INDEX}, {CONFIG_LDAPI_FILENAME_ATTRIBUTE, config_set_ldapi_filename, NULL, 0, (void**)&global_slapdFrontendConfig.ldapi_filename, @@ -1062,21 +1062,21 @@ static struct config_get_and_set { (void**)&global_slapdFrontendConfig.return_orig_type, CONFIG_ON_OFF, (ConfigGetFunc)config_get_return_orig_type_switch, &init_return_orig_type}, {CONFIG_ENABLE_TURBO_MODE, config_set_enable_turbo_mode, - NULL, 0, - (void**)&global_slapdFrontendConfig.enable_turbo_mode, - CONFIG_ON_OFF, (ConfigGetFunc)config_get_enable_turbo_mode, &init_enable_turbo_mode}, + NULL, 0, + (void**)&global_slapdFrontendConfig.enable_turbo_mode, + CONFIG_ON_OFF, (ConfigGetFunc)config_get_enable_turbo_mode, &init_enable_turbo_mode}, {CONFIG_CONNECTION_BUFFER, config_set_connection_buffer, - NULL, 0, - (void**)&global_slapdFrontendConfig.connection_buffer, - CONFIG_INT, (ConfigGetFunc)config_get_connection_buffer, &init_connection_buffer}, + NULL, 0, + (void**)&global_slapdFrontendConfig.connection_buffer, + CONFIG_INT, (ConfigGetFunc)config_get_connection_buffer, &init_connection_buffer}, {CONFIG_CONNECTION_NOCANON, config_set_connection_nocanon, - NULL, 0, - (void**)&global_slapdFrontendConfig.connection_nocanon, - CONFIG_ON_OFF, (ConfigGetFunc)config_get_connection_nocanon, &init_connection_nocanon}, + NULL, 0, + (void**)&global_slapdFrontendConfig.connection_nocanon, + CONFIG_ON_OFF, (ConfigGetFunc)config_get_connection_nocanon, &init_connection_nocanon}, {CONFIG_PLUGIN_LOGGING, config_set_plugin_logging, - NULL, 0, - (void**)&global_slapdFrontendConfig.plugin_logging, - CONFIG_ON_OFF, (ConfigGetFunc)config_get_plugin_logging, &init_plugin_logging}, + NULL, 0, + (void**)&global_slapdFrontendConfig.plugin_logging, + CONFIG_ON_OFF, (ConfigGetFunc)config_get_plugin_logging, &init_plugin_logging}, {CONFIG_LISTEN_BACKLOG_SIZE, config_set_listen_backlog_size, NULL, 0, (void**)&global_slapdFrontendConfig.listen_backlog_size, CONFIG_INT,
0
ee751718a4e99f49c935aef06e309886e1f5beca
389ds/389-ds-base
606920 - anonymous resource limit - nstimelimit - also applied to "cn=directory manager" https://bugzilla.redhat.com/show_bug.cgi?id=606920 Description: When a timelimit (as well as a sizelimit) is successfully retrieved from SLAPIResLimitConnData, the value is always set to pblock. With this change, it sets "no limit (-1)" if the operation is initiated by Directory Manager.
commit ee751718a4e99f49c935aef06e309886e1f5beca Author: Noriko Hosoi <[email protected]> Date: Tue Jun 22 13:55:02 2010 -0700 606920 - anonymous resource limit - nstimelimit - also applied to "cn=directory manager" https://bugzilla.redhat.com/show_bug.cgi?id=606920 Description: When a timelimit (as well as a sizelimit) is successfully retrieved from SLAPIResLimitConnData, the value is always set to pblock. With this change, it sets "no limit (-1)" if the operation is initiated by Directory Manager. diff --git a/ldap/servers/slapd/opshared.c b/ldap/servers/slapd/opshared.c index e07888c06..d06dd2da4 100644 --- a/ldap/servers/slapd/opshared.c +++ b/ldap/servers/slapd/opshared.c @@ -1370,12 +1370,14 @@ compute_limits (Slapi_PBlock *pb) } } - if ( requested_timelimit == 0 ) { - timelimit = ( max_timelimit == -1 ) ? -1 : max_timelimit; + if ( isroot ) { + timelimit = max_timelimit = -1; /* no limit */ + } else if ( requested_timelimit == 0 ) { + timelimit = ( max_timelimit == -1 ) ? -1 : max_timelimit; } else if ( max_timelimit == -1 || requested_timelimit < max_timelimit ) { - timelimit = requested_timelimit; + timelimit = requested_timelimit; } else { - timelimit = max_timelimit; + timelimit = max_timelimit; } set_timelimit: @@ -1399,12 +1401,14 @@ compute_limits (Slapi_PBlock *pb) } } - if ( requested_sizelimit == 0 ) { - sizelimit = ( max_sizelimit == -1 ) ? -1 : max_sizelimit; + if ( isroot ) { + sizelimit = max_sizelimit = -1; + } else if ( requested_sizelimit == 0 ) { + sizelimit = ( max_sizelimit == -1 ) ? -1 : max_sizelimit; } else if ( max_sizelimit == -1 || requested_sizelimit < max_sizelimit ) { - sizelimit = requested_sizelimit; + sizelimit = requested_sizelimit; } else { - sizelimit = max_sizelimit; + sizelimit = max_sizelimit; } slapi_pblock_set(pb, SLAPI_SEARCH_SIZELIMIT, &sizelimit);
0
83f292c9b4e3f68482e9773c30ce96d6129fd68f
389ds/389-ds-base
Ticket 534 - RFE: Add SASL mappings fallback Bug Description: If the mapping fails to find an entry the bind fails without checking if other mappings would also match. Fix Description: Added the fallback functionality. Also added the ability to prioritize the mapping order, and to be able to modify the mappings while the server is up. https://fedorahosted.org/389/ticket/534 Reviewed by: noriko & richm (Thanks!)
commit 83f292c9b4e3f68482e9773c30ce96d6129fd68f Author: Mark Reynolds <[email protected]> Date: Fri Dec 21 17:24:29 2012 -0500 Ticket 534 - RFE: Add SASL mappings fallback Bug Description: If the mapping fails to find an entry the bind fails without checking if other mappings would also match. Fix Description: Added the fallback functionality. Also added the ability to prioritize the mapping order, and to be able to modify the mappings while the server is up. https://fedorahosted.org/389/ticket/534 Reviewed by: noriko & richm (Thanks!) diff --git a/ldap/schema/01core389.ldif b/ldap/schema/01core389.ldif index fb707d361..d22edaab8 100644 --- a/ldap/schema/01core389.ldif +++ b/ldap/schema/01core389.ldif @@ -113,6 +113,7 @@ attributeTypes: ( 2.16.840.1.113730.3.1.9999999 NAME 'nsds5debugreplicatimeout' attributeTypes: ( 2.16.840.1.113730.3.1.2064 NAME 'nsSaslMapRegexString' 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.2065 NAME 'nsSaslMapBaseDNTemplate' 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.2066 NAME 'nsSaslMapFilterTemplate' 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.2142 NAME 'nsSaslMapPriority' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) attributeTypes: ( nsCertfile-oid NAME 'nsCertfile' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 X-ORIGIN 'Netscape' ) attributeTypes: ( nsKeyfile-oid NAME 'nsKeyfile' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 X-ORIGIN 'Netscape' ) attributeTypes: ( nsSSL2-oid NAME 'nsSSL2' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 X-ORIGIN 'Netscape' ) @@ -152,7 +153,7 @@ objectClasses: ( 2.16.840.1.113730.3.2.108 NAME 'nsDS5Replica' DESC 'Netscape de objectClasses: ( 2.16.840.1.113730.3.2.113 NAME 'nsTombstone' DESC 'Netscape defined objectclass' SUP top MAY ( nsParentUniqueId $ nscpEntryDN ) X-ORIGIN 'Netscape Directory Server' ) objectClasses: ( 2.16.840.1.113730.3.2.103 NAME 'nsDS5ReplicationAgreement' DESC 'Netscape defined objectclass' SUP top MUST ( cn ) MAY ( nsds5ReplicaCleanRUVNotified $ nsDS5ReplicaHost $ nsDS5ReplicaPort $ nsDS5ReplicaTransportInfo $ nsDS5ReplicaBindDN $ nsDS5ReplicaCredentials $ nsDS5ReplicaBindMethod $ nsDS5ReplicaRoot $ nsDS5ReplicatedAttributeList $ nsDS5ReplicatedAttributeListTotal $ nsDS5ReplicaUpdateSchedule $ nsds5BeginReplicaRefresh $ description $ nsds50ruv $ nsruvReplicaLastModified $ nsds5ReplicaTimeout $ nsds5replicaChangesSentSinceStartup $ nsds5replicaLastUpdateEnd $ nsds5replicaLastUpdateStart $ nsds5replicaLastUpdateStatus $ nsds5replicaUpdateInProgress $ nsds5replicaLastInitEnd $ nsds5ReplicaEnabled $ nsds5replicaLastInitStart $ nsds5replicaLastInitStatus $ nsds5debugreplicatimeout $ nsds5replicaBusyWaitTime $ nsds5ReplicaStripAttrs $ nsds5replicaSessionPauseTime ) X-ORIGIN 'Netscape Directory Server' ) objectClasses: ( 2.16.840.1.113730.3.2.39 NAME 'nsslapdConfig' DESC 'Netscape defined objectclass' SUP top MAY ( cn ) X-ORIGIN 'Netscape Directory Server' ) -objectClasses: ( 2.16.840.1.113730.3.2.317 NAME 'nsSaslMapping' DESC 'Netscape defined objectclass' SUP top MUST ( cn $ nsSaslMapRegexString $ nsSaslMapBaseDNTemplate $ nsSaslMapFilterTemplate ) X-ORIGIN 'Netscape Directory Server' ) +objectClasses: ( 2.16.840.1.113730.3.2.317 NAME 'nsSaslMapping' DESC 'Netscape defined objectclass' SUP top MUST ( cn $ nsSaslMapRegexString $ nsSaslMapBaseDNTemplate $ nsSaslMapFilterTemplate ) MAY ( nsSaslMapPriority ) X-ORIGIN 'Netscape Directory Server' ) 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' ) diff --git a/ldap/servers/slapd/fe.h b/ldap/servers/slapd/fe.h index 3a985cb70..d21d10808 100644 --- a/ldap/servers/slapd/fe.h +++ b/ldap/servers/slapd/fe.h @@ -190,10 +190,29 @@ int sasl_io_cleanup(Connection *c, void *data); /* * sasl_map.c */ +typedef struct sasl_map_data_ sasl_map_data; +struct sasl_map_data_ { + char *name; + char *regular_expression; + char *template_base_dn; + char *template_search_filter; + int priority; + sasl_map_data *next; /* For linked list */ + sasl_map_data *prev; +}; + +typedef struct _sasl_map_private { + Slapi_RWLock *lock; + sasl_map_data *map_data_list; +} sasl_map_private; + int sasl_map_config_add(Slapi_PBlock *pb, Slapi_Entry* entryBefore, Slapi_Entry* e, int *returncode, char *returntext, void *arg); int sasl_map_config_delete(Slapi_PBlock *pb, Slapi_Entry* entryBefore, Slapi_Entry* e, int *returncode, char *returntext, void *arg); -int sasl_map_domap(char *sasl_user, char *sasl_realm, char **ldap_search_base, char **ldap_search_filter); +int sasl_map_config_modify(Slapi_PBlock *pb, Slapi_Entry* entryBefore, Slapi_Entry* e, int *returncode, char *returntext, void *arg); +int sasl_map_domap(sasl_map_data **map, char *sasl_user, char *sasl_realm, char **ldap_search_base, char **ldap_search_filter); int sasl_map_init(); int sasl_map_done(); +void sasl_map_read_lock(); +void sasl_map_read_unlock(); #endif diff --git a/ldap/servers/slapd/fedse.c b/ldap/servers/slapd/fedse.c index dbfba16a6..5434c7500 100644 --- a/ldap/servers/slapd/fedse.c +++ b/ldap/servers/slapd/fedse.c @@ -1767,7 +1767,7 @@ search_snmp(Slapi_PBlock *pb, Slapi_Entry* entryBefore, Slapi_Entry* e, int *ret int setup_internal_backends(char *configdir) { - int rc = init_schema_dse(configdir); + int rc = init_schema_dse(configdir); Slapi_DN config; slapi_sdn_init_ndn_byref(&config,"cn=config"); @@ -1777,15 +1777,15 @@ setup_internal_backends(char *configdir) rc= init_dse_file(configdir, &config); } - if(rc) - { + if(rc) + { Slapi_DN monitor; Slapi_DN counters; Slapi_DN snmp; Slapi_DN root; - Slapi_Backend *be; - Slapi_DN encryption; - Slapi_DN saslmapping; + Slapi_Backend *be; + Slapi_DN encryption; + Slapi_DN saslmapping; slapi_sdn_init_ndn_byref(&monitor,"cn=monitor"); slapi_sdn_init_ndn_byref(&counters,"cn=counters,cn=monitor"); @@ -1795,50 +1795,51 @@ setup_internal_backends(char *configdir) slapi_sdn_init_ndn_byref(&encryption,"cn=encryption,cn=config"); slapi_sdn_init_ndn_byref(&saslmapping,"cn=mapping,cn=sasl,cn=config"); - /* Search */ - dse_register_callback(pfedse,SLAPI_OPERATION_SEARCH,DSE_FLAG_PREOP,&config,LDAP_SCOPE_BASE,"(objectclass=*)",read_config_dse,NULL); - dse_register_callback(pfedse,SLAPI_OPERATION_SEARCH,DSE_FLAG_PREOP,&monitor,LDAP_SCOPE_BASE,"(objectclass=*)",monitor_info,NULL); - dse_register_callback(pfedse,SLAPI_OPERATION_SEARCH,DSE_FLAG_PREOP,&root,LDAP_SCOPE_BASE,"(objectclass=*)",read_root_dse,NULL); - dse_register_callback(pfedse,SLAPI_OPERATION_SEARCH,DSE_FLAG_PREOP,&monitor,LDAP_SCOPE_SUBTREE,EGG_FILTER,search_easter_egg,NULL); /* Egg */ - dse_register_callback(pfedse,SLAPI_OPERATION_SEARCH,DSE_FLAG_PREOP,&counters,LDAP_SCOPE_BASE,"(objectclass=*)",search_counters,NULL); - dse_register_callback(pfedse,SLAPI_OPERATION_SEARCH,DSE_FLAG_PREOP,&snmp,LDAP_SCOPE_BASE,"(objectclass=*)",search_snmp,NULL); + /* Search */ + dse_register_callback(pfedse,SLAPI_OPERATION_SEARCH,DSE_FLAG_PREOP,&config,LDAP_SCOPE_BASE,"(objectclass=*)",read_config_dse,NULL); + dse_register_callback(pfedse,SLAPI_OPERATION_SEARCH,DSE_FLAG_PREOP,&monitor,LDAP_SCOPE_BASE,"(objectclass=*)",monitor_info,NULL); + dse_register_callback(pfedse,SLAPI_OPERATION_SEARCH,DSE_FLAG_PREOP,&root,LDAP_SCOPE_BASE,"(objectclass=*)",read_root_dse,NULL); + dse_register_callback(pfedse,SLAPI_OPERATION_SEARCH,DSE_FLAG_PREOP,&monitor,LDAP_SCOPE_SUBTREE,EGG_FILTER,search_easter_egg,NULL); /* Egg */ + dse_register_callback(pfedse,SLAPI_OPERATION_SEARCH,DSE_FLAG_PREOP,&counters,LDAP_SCOPE_BASE,"(objectclass=*)",search_counters,NULL); + dse_register_callback(pfedse,SLAPI_OPERATION_SEARCH,DSE_FLAG_PREOP,&snmp,LDAP_SCOPE_BASE,"(objectclass=*)",search_snmp,NULL); dse_register_callback(pfedse,SLAPI_OPERATION_SEARCH,DSE_FLAG_PREOP,&encryption,LDAP_SCOPE_BASE,"(objectclass=*)",search_encryption,NULL); - /* Modify */ - dse_register_callback(pfedse,SLAPI_OPERATION_MODIFY,DSE_FLAG_PREOP,&config,LDAP_SCOPE_BASE,"(objectclass=*)",modify_config_dse,NULL); - dse_register_callback(pfedse,SLAPI_OPERATION_MODIFY,DSE_FLAG_POSTOP,&config,LDAP_SCOPE_BASE,"(objectclass=*)",postop_modify_config_dse,NULL); - dse_register_callback(pfedse,SLAPI_OPERATION_MODIFY,DSE_FLAG_PREOP,&root,LDAP_SCOPE_BASE,"(objectclass=*)",modify_root_dse,NULL); + /* Modify */ + dse_register_callback(pfedse,SLAPI_OPERATION_MODIFY,DSE_FLAG_PREOP,&config,LDAP_SCOPE_BASE,"(objectclass=*)",modify_config_dse,NULL); + dse_register_callback(pfedse,SLAPI_OPERATION_MODIFY,DSE_FLAG_POSTOP,&config,LDAP_SCOPE_BASE,"(objectclass=*)",postop_modify_config_dse,NULL); + dse_register_callback(pfedse,SLAPI_OPERATION_MODIFY,DSE_FLAG_PREOP,&root,LDAP_SCOPE_BASE,"(objectclass=*)",modify_root_dse,NULL); + dse_register_callback(pfedse,SLAPI_OPERATION_MODIFY,DSE_FLAG_PREOP,&saslmapping,LDAP_SCOPE_SUBTREE,"(objectclass=nsSaslMapping)",sasl_map_config_modify,NULL); - /* Delete */ - dse_register_callback(pfedse,SLAPI_OPERATION_DELETE,DSE_FLAG_PREOP,&config,LDAP_SCOPE_BASE,"(objectclass=*)",dont_allow_that,NULL); - dse_register_callback(pfedse,SLAPI_OPERATION_DELETE,DSE_FLAG_PREOP,&monitor,LDAP_SCOPE_BASE,"(objectclass=*)",dont_allow_that,NULL); - dse_register_callback(pfedse,SLAPI_OPERATION_DELETE,DSE_FLAG_PREOP,&counters,LDAP_SCOPE_BASE,"(objectclass=*)",dont_allow_that,NULL); - dse_register_callback(pfedse,SLAPI_OPERATION_DELETE,DSE_FLAG_PREOP,&snmp,LDAP_SCOPE_BASE,"(objectclass=*)",dont_allow_that,NULL); - dse_register_callback(pfedse,SLAPI_OPERATION_DELETE,DSE_FLAG_PREOP,&root,LDAP_SCOPE_BASE,"(objectclass=*)",dont_allow_that,NULL); + /* Delete */ + dse_register_callback(pfedse,SLAPI_OPERATION_DELETE,DSE_FLAG_PREOP,&config,LDAP_SCOPE_BASE,"(objectclass=*)",dont_allow_that,NULL); + dse_register_callback(pfedse,SLAPI_OPERATION_DELETE,DSE_FLAG_PREOP,&monitor,LDAP_SCOPE_BASE,"(objectclass=*)",dont_allow_that,NULL); + dse_register_callback(pfedse,SLAPI_OPERATION_DELETE,DSE_FLAG_PREOP,&counters,LDAP_SCOPE_BASE,"(objectclass=*)",dont_allow_that,NULL); + dse_register_callback(pfedse,SLAPI_OPERATION_DELETE,DSE_FLAG_PREOP,&snmp,LDAP_SCOPE_BASE,"(objectclass=*)",dont_allow_that,NULL); + dse_register_callback(pfedse,SLAPI_OPERATION_DELETE,DSE_FLAG_PREOP,&root,LDAP_SCOPE_BASE,"(objectclass=*)",dont_allow_that,NULL); dse_register_callback(pfedse,SLAPI_OPERATION_DELETE,DSE_FLAG_PREOP,&encryption,LDAP_SCOPE_BASE,"(objectclass=*)",dont_allow_that,NULL); - dse_register_callback(pfedse,SLAPI_OPERATION_DELETE,DSE_FLAG_PREOP,&saslmapping,LDAP_SCOPE_SUBTREE,"(objectclass=nsSaslMapping)",sasl_map_config_delete,NULL); - /* Write */ - dse_register_callback(pfedse,DSE_OPERATION_WRITE,DSE_FLAG_PREOP,&monitor,LDAP_SCOPE_SUBTREE,EGG_FILTER,dont_allow_that,NULL); /* Egg */ + /* Write */ + dse_register_callback(pfedse,DSE_OPERATION_WRITE,DSE_FLAG_PREOP,&monitor,LDAP_SCOPE_SUBTREE,EGG_FILTER,dont_allow_that,NULL); /* Egg */ + /* Add */ dse_register_callback(pfedse,SLAPI_OPERATION_ADD,DSE_FLAG_PREOP,&saslmapping,LDAP_SCOPE_SUBTREE,"(objectclass=nsSaslMapping)",sasl_map_config_add,NULL); - be= be_new_internal(pfedse, "DSE", DSE_BACKEND); - be_addsuffix(be,&root); - be_addsuffix(be,&monitor); - be_addsuffix(be,&config); + be = be_new_internal(pfedse, "DSE", DSE_BACKEND); + be_addsuffix(be,&root); + be_addsuffix(be,&monitor); + be_addsuffix(be,&config); add_internal_entries(); - add_easter_egg_entry(); + add_easter_egg_entry(); slapi_sdn_done(&monitor); slapi_sdn_done(&counters); slapi_sdn_done(&snmp); slapi_sdn_done(&root); slapi_sdn_done(&saslmapping); - } else { + } else { slapi_log_error( SLAPI_LOG_FATAL, "dse", "Please edit the file to correct the reported problems" " and then restart the server.\n" ); @@ -1846,7 +1847,7 @@ setup_internal_backends(char *configdir) } slapi_sdn_done(&config); - return rc; + return rc; } int fedse_create_startOK(char *filename, char *startokfilename, const char *configdir) diff --git a/ldap/servers/slapd/sasl_map.c b/ldap/servers/slapd/sasl_map.c index 7e7cfb832..96905ec5f 100644 --- a/ldap/servers/slapd/sasl_map.c +++ b/ldap/servers/slapd/sasl_map.c @@ -48,25 +48,9 @@ * Map SASL identities to LDAP searches */ -/* - * We maintain a list of mappings to consult - */ - -typedef struct sasl_map_data_ sasl_map_data; -struct sasl_map_data_ { - char *name; - char *regular_expression; - char *template_base_dn; - char *template_search_filter; - sasl_map_data *next; /* For linked list */ -}; - -typedef struct _sasl_map_private { - PRLock *lock; - sasl_map_data *map_data_list; -} sasl_map_private; - static char * configDN = "cn=mapping,cn=sasl,cn=config"; +#define LOW_PRIORITY 100 +#define LOW_PRIORITY_STR "100" /* * DBDB: this is ugly, but right now there is _no_ server-wide @@ -87,7 +71,7 @@ sasl_map_private *sasl_map_get_global_priv() static sasl_map_private *sasl_map_new_private() { - PRLock *new_lock = PR_NewLock(); + Slapi_RWLock *new_lock = slapi_new_rwlock(); sasl_map_private *new_priv = NULL; if (NULL == new_lock) { return NULL; @@ -100,20 +84,23 @@ sasl_map_private *sasl_map_new_private() static void sasl_map_free_private(sasl_map_private **priv) { - PR_DestroyLock((*priv)->lock); + slapi_destroy_rwlock((*priv)->lock); slapi_ch_free((void**)priv); *priv = NULL; } /* This function does a shallow copy on the payload data supplied, so the caller should not free it, and it needs to be allocated using slapi_ch_malloc() */ static -sasl_map_data *sasl_map_new_data(char *name, char *regex, char *dntemplate, char *filtertemplate) +sasl_map_data *sasl_map_new_data(char *name, char *regex, char *dntemplate, char *filtertemplate, int priority) { sasl_map_data *new_dp = (sasl_map_data *) slapi_ch_calloc(1,sizeof(sasl_map_data)); new_dp->name = name; new_dp->regular_expression = regex; new_dp->template_base_dn = dntemplate; new_dp->template_search_filter = filtertemplate; + new_dp->priority = priority; + new_dp->next = NULL; + new_dp->prev = NULL; return new_dp; } @@ -139,31 +126,39 @@ sasl_map_remove_list_entry(sasl_map_private *priv, char *removeme) int ret = 0; int foundit = 0; sasl_map_data *current = NULL; - sasl_map_data *previous = NULL; - PR_Lock(priv->lock); + sasl_map_data *prev = NULL; + sasl_map_data *next = NULL; + + slapi_rwlock_wrlock(priv->lock); current = priv->map_data_list; while (current) { + next = current->next; if (0 == strcmp(current->name,removeme)) { foundit = 1; - if (previous) { + prev = current->prev; + if (prev) { /* Unlink it */ - previous->next = current->next; + if(next){ + next->prev = prev; + } + prev->next = next; } else { /* That was the first list entry */ priv->map_data_list = current->next; + priv->map_data_list->prev = NULL; } /* Payload free */ sasl_map_free_data(&current); /* And no need to look further */ break; } - previous = current; - current = current->next; + current = next; } + slapi_rwlock_unlock(priv->lock); if (!foundit) { ret = -1; } - PR_Unlock(priv->lock); + return ret; } @@ -208,15 +203,21 @@ sasl_map_insert_list_entry(sasl_map_private *priv, sasl_map_data *dp) int ret = 0; int ishere = 0; sasl_map_data *current = NULL; + sasl_map_data *last = NULL; + sasl_map_data *prev = NULL; + if (NULL == dp) { return ret; } - PR_Lock(priv->lock); + + slapi_rwlock_wrlock(priv->lock); + /* Check to see if it's here already */ current = priv->map_data_list; while (current) { if (0 == sasl_map_cmp_data(current, dp)) { ishere = 1; + break; } if (current->next) { current = current->next; @@ -225,15 +226,39 @@ sasl_map_insert_list_entry(sasl_map_private *priv, sasl_map_data *dp) } } if (ishere) { + slapi_rwlock_unlock(priv->lock); return -1; } - /* current now points to the end of the list or NULL */ + + /* insert the map in its proper place */ if (NULL == priv->map_data_list) { priv->map_data_list = dp; } else { - current->next = dp; + current = priv->map_data_list; + while (current) { + last = current; + if(current->priority > dp->priority){ + prev = current->prev; + if(prev){ + prev->next = dp; + dp->prev = prev; + } else { + /* this is now the head of the list */ + priv->map_data_list = dp; + } + current->prev = dp; + dp->next = current; + slapi_rwlock_unlock(priv->lock); + return ret; + } + current = current->next; + } + /* add the map at the end of the list */ + last->next = dp; + dp->prev = last; } - PR_Unlock(priv->lock); + slapi_rwlock_unlock(priv->lock); + return ret; } @@ -342,9 +367,11 @@ static int sasl_map_config_parse_entry(Slapi_Entry *entry, sasl_map_data **new_dp) { int ret = 0; + int priority; char *regex = NULL; char *basedntemplate = NULL; char *filtertemplate = NULL; + char *priority_str = NULL; char *map_name = NULL; *new_dp = NULL; @@ -352,21 +379,43 @@ sasl_map_config_parse_entry(Slapi_Entry *entry, sasl_map_data **new_dp) basedntemplate = slapi_entry_attr_get_charptr( entry, "nsSaslMapBaseDNTemplate" ); filtertemplate = slapi_entry_attr_get_charptr( entry, "nsSaslMapFilterTemplate" ); map_name = slapi_entry_attr_get_charptr( entry, "cn" ); + priority_str = slapi_entry_attr_get_charptr( entry, "nsSaslMapPriority" ); + if(priority_str){ + priority = atoi(priority_str); + } else { + priority = LOW_PRIORITY; + } + if(priority == 0 || priority > LOW_PRIORITY){ + struct berval desc; + struct berval *newval[2] = {0, 0}; + + desc.bv_val = LOW_PRIORITY_STR; + desc.bv_len = strlen(desc.bv_val); + newval[0] = &desc; + if (entry_replace_values(entry, "nsSaslMapPriority", newval) != 0){ + LDAPDebug( LDAP_DEBUG_TRACE, "sasl_map_config_parse_entry: failed to reset priority to (%d)\n", + LOW_PRIORITY,0,0); + } else { + LDAPDebug( LDAP_DEBUG_ANY, "sasl_map_config_parse_entry: resetting nsSaslMapPriority to lowest priority(%d)\n", + LOW_PRIORITY,0,0); + } + priority = LOW_PRIORITY; + } if ( (NULL == map_name) || (NULL == regex) || (NULL == basedntemplate) || (NULL == filtertemplate) ) { /* Invalid entry */ ret = -1; } else { /* Make the new dp */ - *new_dp = sasl_map_new_data(map_name, regex, basedntemplate, filtertemplate); + *new_dp = sasl_map_new_data(map_name, regex, basedntemplate, filtertemplate, priority); } if (ret) { - slapi_ch_free((void **) &map_name); - slapi_ch_free((void **) &regex); - slapi_ch_free((void **) &basedntemplate); - slapi_ch_free((void **) &filtertemplate); + slapi_ch_free_string(&map_name); + slapi_ch_free_string(&regex); + slapi_ch_free_string(&basedntemplate); + slapi_ch_free_string(&filtertemplate); } return ret; } @@ -430,6 +479,35 @@ sasl_map_config_add(Slapi_PBlock *pb, Slapi_Entry* entryBefore, Slapi_Entry* e, return ret; } +int +sasl_map_config_modify(Slapi_PBlock *pb, Slapi_Entry* entryBefore, Slapi_Entry* e, int *returncode, char *returntext, void *arg) +{ + sasl_map_private *priv = sasl_map_get_global_priv(); + sasl_map_data *dp; + char *map_name = NULL; + int ret = SLAPI_DSE_CALLBACK_ERROR; + + if((map_name = slapi_entry_attr_get_charptr( entryBefore, "cn" )) == NULL){ + LDAPDebug( LDAP_DEBUG_TRACE, "sasl_map_config_modify: could not find name of map\n",0,0,0); + return ret; + } + if(sasl_map_remove_list_entry(priv, map_name) == 0){ + ret = sasl_map_config_parse_entry(e, &dp); + if (!ret && dp) { + ret = sasl_map_insert_list_entry(priv, dp); + if(ret == 0){ + ret = SLAPI_DSE_CALLBACK_OK; + } + } + } + if(ret == SLAPI_DSE_CALLBACK_ERROR){ + LDAPDebug( LDAP_DEBUG_TRACE, "sasl_map_config_modify: failed to update map(%s)\n",map_name,0,0); + } + slapi_ch_free_string(&map_name); + + return ret; +} + int sasl_map_config_delete(Slapi_PBlock *pb, Slapi_Entry* entryBefore, Slapi_Entry* e, int *returncode, char *returntext, void *arg) { @@ -485,30 +563,20 @@ int sasl_map_done() } /* Free the map list */ - PR_Lock(priv->lock); + slapi_rwlock_wrlock(priv->lock); dp = priv->map_data_list; while (dp) { sasl_map_data *dp_next = dp->next; sasl_map_free_data(&dp); dp = dp_next; } - PR_Unlock(priv->lock); + slapi_rwlock_unlock(priv->lock); /* Free the private structure */ sasl_map_free_private(&priv); return ret; } -static sasl_map_data* -sasl_map_first(sasl_map_private *priv) -{ - sasl_map_data *result = NULL; - PR_Lock(priv->lock); - result = priv->map_data_list; - PR_Unlock(priv->lock); - return result; -} - static int sasl_map_check(sasl_map_data *dp, char *sasl_user_and_realm, char **ldap_search_base, char **ldap_search_filter) { @@ -610,28 +678,31 @@ sasl_map_str_concat(char *s1, char *s2) * returns 1 if matched, 0 otherwise */ int -sasl_map_domap(char *sasl_user, char *sasl_realm, char **ldap_search_base, char **ldap_search_filter) +sasl_map_domap(sasl_map_data **map, char *sasl_user, char *sasl_realm, char **ldap_search_base, char **ldap_search_filter) { - int ret = 0; - sasl_map_data *this_map = NULL; - char *sasl_user_and_realm = NULL; sasl_map_private *priv = sasl_map_get_global_priv(); + char *sasl_user_and_realm = NULL; + int ret = 0; + + LDAPDebug( LDAP_DEBUG_TRACE, "-> sasl_map_domap\n", 0, 0, 0 ); + if(map == NULL){ + LDAPDebug( LDAP_DEBUG_TRACE, "<- sasl_map_domap: Internal error, mapping is NULL\n",0,0,0); + return ret; + } *ldap_search_base = NULL; *ldap_search_filter = NULL; - LDAPDebug( LDAP_DEBUG_TRACE, "-> sasl_map_domap\n", 0, 0, 0 ); sasl_user_and_realm = sasl_map_str_concat(sasl_user,sasl_realm); /* Walk the list of maps */ - this_map = sasl_map_first(priv); - while (this_map) { - int matched = 0; + if(*map == NULL) + *map = priv->map_data_list; + while (*map) { /* If one matches, then make the search params */ - LDAPDebug( LDAP_DEBUG_TRACE, "sasl_map_domap - trying map [%s]\n", this_map->name, 0, 0 ); - matched = sasl_map_check(this_map, sasl_user_and_realm, ldap_search_base, ldap_search_filter); - if (1 == matched) { - ret = 1; + LDAPDebug( LDAP_DEBUG_TRACE, "sasl_map_domap - trying map [%s]\n", (*map)->name, 0, 0 ); + if((ret = sasl_map_check(*map, sasl_user_and_realm, ldap_search_base, ldap_search_filter))){ + *map = sasl_map_next(*map); break; } - this_map = sasl_map_next(this_map); + *map = sasl_map_next(*map); } if (sasl_user_and_realm) { slapi_ch_free((void**)&sasl_user_and_realm); @@ -640,3 +711,16 @@ sasl_map_domap(char *sasl_user, char *sasl_realm, char **ldap_search_base, char return ret; } +void +sasl_map_read_lock() +{ + sasl_map_private *priv = sasl_map_get_global_priv(); + slapi_rwlock_rdlock(priv->lock); +} + +void +sasl_map_read_unlock() +{ + sasl_map_private *priv = sasl_map_get_global_priv(); + slapi_rwlock_unlock(priv->lock); +} diff --git a/ldap/servers/slapd/saslbind.c b/ldap/servers/slapd/saslbind.c index f9ddbfc5b..6181474c7 100644 --- a/ldap/servers/slapd/saslbind.c +++ b/ldap/servers/slapd/saslbind.c @@ -323,14 +323,15 @@ static Slapi_Entry *ids_sasl_user_to_entry( const char *user_realm ) { - int found = 0; - int attrsonly = 0, scope = LDAP_SCOPE_SUBTREE; LDAPControl **ctrls = NULL; + sasl_map_data *map = NULL; Slapi_Entry *entry = NULL; char **attrs = NULL; - int regexmatch = 0; char *base = NULL; char *filter = NULL; + int attrsonly = 0, scope = LDAP_SCOPE_SUBTREE; + int regexmatch = 0; + int found = 0; /* Check for wildcards in the authid and realm. If we encounter one, * just fail the mapping without performing a costly internal search. */ @@ -345,31 +346,42 @@ static Slapi_Entry *ids_sasl_user_to_entry( } /* New regex-based identity mapping */ - regexmatch = sasl_map_domap((char*)user, (char*)user_realm, &base, &filter); - if (regexmatch) { - ids_sasl_user_search(base, scope, filter, - ctrls, attrs, attrsonly, - &entry, &found); - - if (found == 1) { - LDAPDebug(LDAP_DEBUG_TRACE, "sasl user search found this entry: dn:%s, " - "matching filter=%s\n", entry->e_sdn.dn, filter, 0); - } else if (found == 0) { - LDAPDebug(LDAP_DEBUG_TRACE, "sasl user search found no entries matching " - "filter=%s\n", filter, 0, 0); - } else { - LDAPDebug(LDAP_DEBUG_TRACE, "sasl user search found more than one entry " - "matching filter=%s\n", filter, 0, 0); - if (entry) { - slapi_entry_free(entry); - entry = NULL; + sasl_map_read_lock(); + while(1){ + regexmatch = sasl_map_domap(&map, (char*)user, (char*)user_realm, &base, &filter); + if (regexmatch) { + ids_sasl_user_search(base, scope, filter, + ctrls, attrs, attrsonly, + &entry, &found); + if (found == 1) { + LDAPDebug(LDAP_DEBUG_TRACE, "sasl user search found this entry: dn:%s, " + "matching filter=%s\n", entry->e_sdn.dn, filter, 0); + } else if (found == 0) { + LDAPDebug(LDAP_DEBUG_TRACE, "sasl user search found no entries matching " + "filter=%s\n", filter, 0, 0); + } else { + LDAPDebug(LDAP_DEBUG_TRACE, "sasl user search found more than one entry " + "matching filter=%s\n", filter, 0, 0); + if (entry) { + slapi_entry_free(entry); + entry = NULL; + } } - } - /* Free the filter etc */ - slapi_ch_free_string(&base); - slapi_ch_free_string(&filter); + /* Free the filter etc */ + slapi_ch_free_string(&base); + slapi_ch_free_string(&filter); + + /* If we didn't find an entry, look at the other maps */ + if(found){ + break; + } + } + if(map == NULL){ + break; + } } + sasl_map_read_unlock(); return entry; }
0
5135d9a3da96d779167d7ee731d3e50890bf74ec
389ds/389-ds-base
Bug 671199 - Don't allow other to write to rundir The persmissions on /var/run/dirsrv currently get set to 777 by the setup program. There were some discrepencies with the way the changeOwnerMode subroutine is used that cause 777 to be the mode set when we intended for it to be 770. This patch fixes up the way changeOwnerMode is used to sllow one to reset the group ownership without altering the permissions for other. In addition, this patch makes an upgrade remove any permissions that are set for other on the rundir.
commit 5135d9a3da96d779167d7ee731d3e50890bf74ec Author: Nathan Kinder <[email protected]> Date: Tue Jan 25 14:52:13 2011 -0800 Bug 671199 - Don't allow other to write to rundir The persmissions on /var/run/dirsrv currently get set to 777 by the setup program. There were some discrepencies with the way the changeOwnerMode subroutine is used that cause 777 to be the mode set when we intended for it to be 770. This patch fixes up the way changeOwnerMode is used to sllow one to reset the group ownership without altering the permissions for other. In addition, this patch makes an upgrade remove any permissions that are set for other on the rundir. diff --git a/ldap/admin/src/scripts/10fixrundir.pl b/ldap/admin/src/scripts/10fixrundir.pl index a1e752406..b7a395cd7 100644 --- a/ldap/admin/src/scripts/10fixrundir.pl +++ b/ldap/admin/src/scripts/10fixrundir.pl @@ -6,6 +6,7 @@ sub runinst { my ($inf, $inst, $dseldif, $conn) = @_; my @errs; + my $mode; # see if nsslapd-rundir is defined my $ent = $conn->search("cn=config", "base", "(objectclass=*)"); @@ -24,5 +25,15 @@ sub runinst { } } + # ensure that other doesn't have permissions on rundir + $mode = (stat($inf->{slapd}->{run_dir}))[2] or return ('error_chmoding_file', $inf->{slapd}->{run_dir}, $!); + # mask off permissions for other + $mode &= 07770; + $! = 0; # clear errno + chmod $mode, $inf->{slapd}->{run_dir}; + if ($!) { + return ('error_chmoding_file', $inf->{slapd}->{run_dir}, $!); + } + return (); } diff --git a/ldap/admin/src/scripts/DSCreate.pm.in b/ldap/admin/src/scripts/DSCreate.pm.in index d0dc209a1..bda23a593 100644 --- a/ldap/admin/src/scripts/DSCreate.pm.in +++ b/ldap/admin/src/scripts/DSCreate.pm.in @@ -163,6 +163,7 @@ sub changeOwnerMode { my $mode = shift; my $it = shift; my $gidonly = shift; + my $othermode = shift; my $uid = getpwnam $inf->{General}->{SuiteSpotUserID}; my $gid = -1; # default to leave it alone @@ -172,7 +173,8 @@ sub changeOwnerMode { $gid = getgrnam $inf->{General}->{SuiteSpotGroup}; } - $mode = getMode($inf, $mode, $gidonly); + $mode = getMode($inf, $mode, $othermode); + $! = 0; # clear errno chmod $mode, $it; if ($!) { @@ -238,9 +240,8 @@ sub makeDSDirs { debug(3, "Root user " . $inf->{General}->{SuiteSpotUserID} . " already has access to $inf->{slapd}->{run_dir} - skipping\n"); } else { my $dir = $inf->{slapd}->{run_dir}; - # rwx by user only, or by user & group if a group is defined - @errs = changeOwnerMode($inf, 7, $dir, 7); - debug(3, "Changed owner of $dir to " . $inf->{General}->{SuiteSpotUserID} . ": error @errs\n"); + # rwx by user only, or by user & group if a group is defined. Also only change the group ownership. + @errs = changeOwnerMode($inf, 7, $dir, 1); debug(3, "\t" . `/bin/ls -ld $dir`); } # set the group of the parent dir of config_dir and inst_dir @@ -248,8 +249,8 @@ sub makeDSDirs { for my $kw (qw(inst_dir config_dir)) { my $dir = $inf->{slapd}->{$kw}; my $parent = dirname($dir); - # changeOwnerMode(inf, mode, file, gidonly & default mode); - @errs = changeOwnerMode($inf, 7, $parent, 5); + # changeOwnerMode(inf, mode, file, gidonly, othermode); + @errs = changeOwnerMode($inf, 7, $parent, 1, 5); if (@errs) { return @errs; }
0
2b44a279814d49a0f8f87caebf35c1a6c10023bc
389ds/389-ds-base
Bump version to 1.4.2.1
commit 2b44a279814d49a0f8f87caebf35c1a6c10023bc Author: Mark Reynolds <[email protected]> Date: Tue Sep 17 10:36:30 2019 -0400 Bump version to 1.4.2.1 diff --git a/VERSION.sh b/VERSION.sh index 3d8b8d903..9e53a7938 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=4 -VERSION_MAINT=2.0 +VERSION_MAINT=2.1 # NOTE: VERSION_PREREL is automatically set for builds made out of a git tree VERSION_PREREL= VERSION_DATE=$(date -u +%Y%m%d)
0
58dc93c0a63b60abd13926b3d6dbfbc8e049e023
389ds/389-ds-base
Ticket #319 - ldap-agent crashes on start with signal SIGSEGV Bug Description: If you have two or more slapd instances defined in ldap-agent.conf file, the agent will crash at startup. Fix Description: When using openldap, we were not reseting the buffer length between dse.ldif files. So we end passing in a huge buffer length for the first line of the new file, which leads to invalid memory being read later on. https://fedorahosted.org/389/ticket/319
commit 58dc93c0a63b60abd13926b3d6dbfbc8e049e023 Author: Mark Reynolds <[email protected]> Date: Fri Mar 23 11:44:00 2012 -0400 Ticket #319 - ldap-agent crashes on start with signal SIGSEGV Bug Description: If you have two or more slapd instances defined in ldap-agent.conf file, the agent will crash at startup. Fix Description: When using openldap, we were not reseting the buffer length between dse.ldif files. So we end passing in a huge buffer length for the first line of the new file, which leads to invalid memory being read later on. https://fedorahosted.org/389/ticket/319 diff --git a/ldap/servers/snmp/main.c b/ldap/servers/snmp/main.c index a25588095..53af97223 100644 --- a/ldap/servers/snmp/main.c +++ b/ldap/servers/snmp/main.c @@ -382,6 +382,7 @@ load_config(char *conf_path) /* Open dse.ldif */ #if defined(USE_OPENLDAP) dse_fp = ldif_open(serv_p->dse_ldif, "r"); + buflen = 0; #else dse_fp = fopen(serv_p->dse_ldif, "r"); #endif
0
b6565e21d782ad1f0594e7cc539db2cb85285864
389ds/389-ds-base
Issue 6439 - Fix dsidm service get_dn option Fix for failing 'dsidm service get_dn' option including update of corresponding test. Relates: https://github.com/389ds/389-ds-base/issues/6439 Author: Lenka Doudova Reviewed by: ???
commit b6565e21d782ad1f0594e7cc539db2cb85285864 Author: Lenka Doudova <[email protected]> Date: Mon Jan 6 07:46:14 2025 +0100 Issue 6439 - Fix dsidm service get_dn option Fix for failing 'dsidm service get_dn' option including update of corresponding test. Relates: https://github.com/389ds/389-ds-base/issues/6439 Author: Lenka Doudova Reviewed by: ??? diff --git a/dirsrvtests/tests/suites/clu/dsidm_services_test.py b/dirsrvtests/tests/suites/clu/dsidm_services_test.py index df9d9fc3b..61dd0ac11 100644 --- a/dirsrvtests/tests/suites/clu/dsidm_services_test.py +++ b/dirsrvtests/tests/suites/clu/dsidm_services_test.py @@ -170,7 +170,7 @@ def test_dsidm_service_get_rdn(topology_st, create_test_service): check_value_in_log_and_reset(topology_st, content_list=json_content) [email protected](reason="Will fail because of bz1893667") +#@pytest.mark.xfail(reason="Will fail because of bz1893667") @pytest.mark.skipif(ds_is_older("2.1.0"), reason="Not implemented") def test_dsidm_service_get_dn(topology_st, create_test_service): """ Test dsidm service get_dn option @@ -185,20 +185,25 @@ def test_dsidm_service_get_dn(topology_st, create_test_service): 2. Success """ + service_name = 'test_service' standalone = topology_st.standalone services = ServiceAccounts(standalone, DEFAULT_SUFFIX) - test_service = services.get('test_service') + test_service = services.get(service_name) args = FakeArgs() args.dn = test_service.dn + args.json = False log.info('Empty the log file to prevent false data to check about service') topology_st.logcap.flush() log.info('Test dsidm service get_dn without json') get_dn(standalone, DEFAULT_SUFFIX, topology_st.logcap.log, args) - # check_value_in_log_and_reset(topology_st, content_list=service_content) - # The check_value_in_log_and_reset will have to be updated accordinly after bz1893667 is fixed - # because now I can't determine the output + check_value_in_log_and_reset(topology_st, content_list=service_name) + + log.info('Test dsidm service get_dn with json') + args.json = True + get_dn(standalone, DEFAULT_SUFFIX, topology_st.logcap.log, args) + check_value_in_log_and_reset(topology_st, content_list=service_name) @pytest.mark.skipif(ds_is_older("2.1.0"), reason="Not implemented") diff --git a/src/lib389/lib389/cli_idm/service.py b/src/lib389/lib389/cli_idm/service.py index c2b2c8c84..2429c88ca 100644 --- a/src/lib389/lib389/cli_idm/service.py +++ b/src/lib389/lib389/cli_idm/service.py @@ -35,7 +35,7 @@ def get(inst, basedn, log, args): _generic_get(inst, basedn, log.getChild('_generic_get'), MANY, rdn, args) def get_dn(inst, basedn, log, args): - dn = lambda args: _get_arg( args.dn, msg="Enter dn to retrieve") + dn = _get_arg( args.dn, msg="Enter dn to retrieve") _generic_get_dn(inst, basedn, log.getChild('_generic_get_dn'), MANY, dn, args) def create(inst, basedn, log, args):
0
272bd14ee0396d5cb02dd01b2ecbc294b16a8a7f
389ds/389-ds-base
Ticket 47699: Propagate plugin precedence to all registered function types Bug Description: A plugin can define its nsslapd-pluginprecedence (config), that is number that order the plugins in the plugin list. If a plugin register an other plugin (slapi_register_plugin), this number is not preserved in the new plugin and it gets a default plugin precedence value. Fix Description: When registering a plugin (slapi_register_plugin) a plugin identity is provided that contains the original plugin configuration (with its precedence). The fix consist to set (in slapi_register_plugin_ext ) the precedence to the value store in the plugin identity. It is done in slapi_register_plugin_ext because referencial integrity calls directly slapi_register_plugin_ext. https://fedorahosted.org/389/ticket/47699 Reviewed by: Rich Megginson / Mark Reynolds Platforms tested: F17 Flag Day: no Doc impact: no
commit 272bd14ee0396d5cb02dd01b2ecbc294b16a8a7f Author: Thierry bordaz (tbordaz) <[email protected]> Date: Wed Feb 19 17:03:03 2014 +0100 Ticket 47699: Propagate plugin precedence to all registered function types Bug Description: A plugin can define its nsslapd-pluginprecedence (config), that is number that order the plugins in the plugin list. If a plugin register an other plugin (slapi_register_plugin), this number is not preserved in the new plugin and it gets a default plugin precedence value. Fix Description: When registering a plugin (slapi_register_plugin) a plugin identity is provided that contains the original plugin configuration (with its precedence). The fix consist to set (in slapi_register_plugin_ext ) the precedence to the value store in the plugin identity. It is done in slapi_register_plugin_ext because referencial integrity calls directly slapi_register_plugin_ext. https://fedorahosted.org/389/ticket/47699 Reviewed by: Rich Megginson / Mark Reynolds Platforms tested: F17 Flag Day: no Doc impact: no diff --git a/ldap/servers/slapd/plugin.c b/ldap/servers/slapd/plugin.c index 617909dab..b13ecbb7c 100644 --- a/ldap/servers/slapd/plugin.c +++ b/ldap/servers/slapd/plugin.c @@ -268,6 +268,7 @@ slapi_register_plugin_ext( ) { int ii = 0; + int found_precedence; int rc = 0; Slapi_Entry *e = NULL; char *dn = slapi_ch_smprintf("cn=%s,%s", name, PLUGIN_BASE_DN); @@ -284,7 +285,21 @@ slapi_register_plugin_ext( slapi_entry_attr_set_charptr(e, ATTR_PLUGIN_ENABLED, "off"); slapi_entry_attr_set_charptr(e, ATTR_PLUGIN_INITFN, initsymbol); - slapi_entry_attr_set_int(e, ATTR_PLUGIN_PRECEDENCE, precedence); + /* If the plugin belong to a group, get the precedence from the group */ + found_precedence = precedence; + if ((found_precedence == PLUGIN_DEFAULT_PRECEDENCE) && group_identity) { + struct slapi_componentid * cid = (struct slapi_componentid *) group_identity; + if (cid->sci_plugin && + (cid->sci_plugin->plg_precedence != PLUGIN_DEFAULT_PRECEDENCE)) { + slapi_log_error(SLAPI_LOG_PLUGIN, NULL, + "Plugin precedence (%s) reset to group precedence (%s): %d \n", + name ? name : "", + cid->sci_plugin->plg_name ? cid->sci_plugin->plg_name : "", + cid->sci_plugin->plg_precedence); + found_precedence = cid->sci_plugin->plg_precedence; + } + } + slapi_entry_attr_set_int(e, ATTR_PLUGIN_PRECEDENCE, found_precedence); for (ii = 0; argv && argv[ii]; ++ii) { char argname[64];
0
0552081fe736b5c86d3c7e3d640f8a8b170d1dc6
389ds/389-ds-base
Issue 4973 - installer changes permissions on /run Description: There was a regression when we switched over to using /run that caused the installer to try and create /run which caused the ownership to change. Fixed this by changing the "run_dir" to /run/dirsrv relates: https://github.com/389ds/389-ds-base/issues/4973 Reviewed by: jchapman(Thanks!)
commit 0552081fe736b5c86d3c7e3d640f8a8b170d1dc6 Author: Mark Reynolds <[email protected]> Date: Mon Nov 1 10:42:27 2021 -0400 Issue 4973 - installer changes permissions on /run Description: There was a regression when we switched over to using /run that caused the installer to try and create /run which caused the ownership to change. Fixed this by changing the "run_dir" to /run/dirsrv relates: https://github.com/389ds/389-ds-base/issues/4973 Reviewed by: jchapman(Thanks!) diff --git a/ldap/admin/src/defaults.inf.in b/ldap/admin/src/defaults.inf.in index 084368434..28f908bcd 100644 --- a/ldap/admin/src/defaults.inf.in +++ b/ldap/admin/src/defaults.inf.in @@ -34,7 +34,7 @@ sysconf_dir = @sysconfdir@ initconfig_dir = @initconfigdir@ config_dir = @instconfigdir@/slapd-{instance_name} local_state_dir = @localstatedir@ -run_dir = @localrundir@ +run_dir = @localrundir@/dirsrv # This is the expected location of ldapi. ldapi = @localrundir@/slapd-{instance_name}.socket pid_file = @localrundir@/slapd-{instance_name}.pid diff --git a/src/lib389/lib389/instance/remove.py b/src/lib389/lib389/instance/remove.py index 1a35ddc07..e96db3896 100644 --- a/src/lib389/lib389/instance/remove.py +++ b/src/lib389/lib389/instance/remove.py @@ -52,9 +52,9 @@ def remove_ds_instance(dirsrv, force=False): remove_paths['ldif_dir'] = dirsrv.ds_paths.ldif_dir remove_paths['lock_dir'] = dirsrv.ds_paths.lock_dir remove_paths['log_dir'] = dirsrv.ds_paths.log_dir - # remove_paths['run_dir'] = dirsrv.ds_paths.run_dir remove_paths['inst_dir'] = dirsrv.ds_paths.inst_dir remove_paths['etc_sysconfig'] = "%s/sysconfig/dirsrv-%s" % (dirsrv.ds_paths.sysconf_dir, dirsrv.serverid) + remove_paths['ldapi'] = dirsrv.ds_paths.ldapi tmpfiles_d_path = dirsrv.ds_paths.tmpfiles_d + "/dirsrv-" + dirsrv.serverid + ".conf" @@ -80,14 +80,6 @@ def remove_ds_instance(dirsrv, force=False): ### ANY NEW REMOVAL ACTION MUST BE BELOW THIS LINE!!! - # Remove LDAPI socket file - ldapi_path = os.path.join(dirsrv.ds_paths.run_dir, "slapd-%s.socket" % dirsrv.serverid) - if os.path.exists(ldapi_path): - try: - os.remove(ldapi_path) - except OSError as e: - _log.debug(f"Failed to remove LDAPI socket ({ldapi_path}) Error: {str(e)}") - # Remove these paths: # for path in ('backup_dir', 'cert_dir', 'config_dir', 'db_dir', # 'ldif_dir', 'lock_dir', 'log_dir', 'run_dir'): diff --git a/src/lib389/lib389/instance/setup.py b/src/lib389/lib389/instance/setup.py index 1cded479c..dadc82b3b 100644 --- a/src/lib389/lib389/instance/setup.py +++ b/src/lib389/lib389/instance/setup.py @@ -734,10 +734,6 @@ class SetupDs(object): dse += line.replace('%', '{', 1).replace('%', '}', 1) with open(os.path.join(slapd['config_dir'], 'dse.ldif'), 'w') as file_dse: - if os.path.exists(os.path.dirname(slapd['ldapi'])): - ldapi_path = slapd['ldapi'] - else: - ldapi_path = os.path.join(slapd['run_dir'], "slapd-%s.socket" % slapd['instance_name']) dse_fmt = dse.format( schema_dir=slapd['schema_dir'], lock_dir=slapd['lock_dir'], @@ -762,7 +758,7 @@ class SetupDs(object): db_home_dir=slapd['db_home_dir'], db_lib=slapd['db_lib'], ldapi_enabled="on", - ldapi=ldapi_path, + ldapi=slapd['ldapi'], ldapi_autobind="on", ) file_dse.write(dse_fmt) @@ -864,7 +860,7 @@ class SetupDs(object): SER_ROOT_PW: self._raw_secure_password, SER_DEPLOYED_DIR: slapd['prefix'], SER_LDAPI_ENABLED: 'on', - SER_LDAPI_SOCKET: ldapi_path, + SER_LDAPI_SOCKET: slapd['ldapi'], SER_LDAPI_AUTOBIND: 'on' } @@ -908,13 +904,10 @@ class SetupDs(object): self.log.info("Perform SELinux labeling ...") selinux_paths = ('backup_dir', 'cert_dir', 'config_dir', 'db_dir', 'ldif_dir', 'lock_dir', 'log_dir', 'db_home_dir', - 'schema_dir', 'tmp_dir') + 'run_dir', 'schema_dir', 'tmp_dir') for path in selinux_paths: selinux_restorecon(slapd[path]) - # Don't run restorecon on the entire /run directory - selinux_restorecon(slapd['run_dir'] + '/dirsrv') - selinux_label_port(slapd['port']) # Start the server
0
09ad0d01d363e9ece1e132cb1331a5ab880748de
389ds/389-ds-base
Ticket 49877 - Add log level functionality to UI Description: Add logic to get and save the access & errors log levels in the UI tables https://pagure.io/389-ds-base/issue/49877 Reviewed by: ?
commit 09ad0d01d363e9ece1e132cb1331a5ab880748de Author: Mark Reynolds <[email protected]> Date: Mon Aug 27 15:48:23 2018 -0400 Ticket 49877 - Add log level functionality to UI Description: Add logic to get and save the access & errors log levels in the UI tables https://pagure.io/389-ds-base/issue/49877 Reviewed by: ? diff --git a/src/cockpit/389-console/js/servers.js b/src/cockpit/389-console/js/servers.js index a2bd9e00f..0323d5c7e 100644 --- a/src/cockpit/389-console/js/servers.js +++ b/src/cockpit/389-console/js/servers.js @@ -76,6 +76,11 @@ var create_inf_template = var sasl_table; var pwp_table; +// log levels +var accesslog_levels = [4, 256, 512] +var errorlog_levels = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 2048, + 4096, 8192, 16384, 32768, 65536, 262144, 1048576]; + function load_server_config() { var mark = document.getElementById("server-config-title"); mark.innerHTML = "Configuration for server: <b>" + server_id + "</b>"; @@ -154,6 +159,10 @@ function get_and_set_config () { var cmd = [DSCONF, '-j', 'ldapi://%2fvar%2frun%2f' + server_id + '.socket','config', 'get']; cockpit.spawn(cmd, { superuser: true, "err": "message", "environ": [ENV]}).done(function(data) { var obj = JSON.parse(data); + // Reset tables before populating them + $(".ds-accesslog-table").prop('checked', false); + $(".ds-errorlog-table").prop('checked', false); + for (var attr in obj['attrs']) { var val = obj['attrs'][attr][0]; attr = attr.toLowerCase(); @@ -169,6 +178,23 @@ function get_and_set_config () { } config_values[attr] = val; } + + // Do the log level tables + if (attr == "nsslapd-accesslog-level") { + var level_val = parseInt(val); + for ( var level in accesslog_levels ) { + if (level_val & accesslog_levels[level]) { + $("#accesslog-" + accesslog_levels[level].toString()).prop('checked', true); + } + } + } else if (attr == "nsslapd-errorlog-level") { + var level_val = parseInt(val); + for ( var level in errorlog_levels ) { + if (level_val & errorlog_levels[level]) { + $("#errorlog-" + errorlog_levels[level].toString()).prop('checked', true); + } + } + } } check_inst_alive(); }).fail(function(data) { @@ -320,6 +346,32 @@ function save_config() { } } + // Save access log levels + var access_log_level = 0; + $(".ds-accesslog-table").each(function() { + var val = this.id; + if (this.checked){ + val = parseInt(val.replace("accesslog-", "")); + access_log_level += val; + } + }); + mod['attr'] = "nsslapd-accesslog-level"; + mod['val'] = access_log_level; + mod_list.push(mod); + + // Save error log levels + var error_log_level = 0; + $(".ds-errorlog-table").each(function() { + var val = this.id; + if (this.checked) { + val = parseInt(val.replace("errorlog-", "")); + error_log_level += val; + } + }); + mod['attr'] = "nsslapd-errorlog-level"; + mod['val'] = error_log_level; + mod_list.push(mod); + // Build dsconf commands to apply all the mods if (mod_list.length) { apply_mods(mod_list); diff --git a/src/cockpit/389-console/servers.html b/src/cockpit/389-console/servers.html index 67fc3d0fc..94895a60e 100644 --- a/src/cockpit/389-console/servers.html +++ b/src/cockpit/389-console/servers.html @@ -554,7 +554,7 @@ <hr class="ds-hr-logs"> - <table class="table table-striped table-bordered table-hover ds-loglevel-table" id="errorlog-level-table"> + <table class="table table-striped table-bordered table-hover ds-loglevel-table" id="accesslog-level-table"> <thead> <tr> <th class="ds-table-checkbox"></th> @@ -563,11 +563,15 @@ </thead> <tbody> <tr> - <td class="ds-table-checkbox" id="4"><input type="checkbox"></td> + <td class="ds-table-checkbox"><input class="ds-accesslog-table" id="accesslog-256" type="checkbox"></td> + <td>Default Logging</td> + </tr> + <tr> + <td class="ds-table-checkbox"><input class="ds-accesslog-table" id="accesslog-4"type="checkbox"></td> <td>Internal Operations</td> </tr> <tr> - <td class="ds-table-checkbox" id="512"><input type="checkbox"></td> + <td class="ds-table-checkbox"><input class="ds-accesslog-table" id="accesslog-512" type="checkbox"></td> <td>Entry Access and Referrals</td> </tr> <tbody> @@ -767,63 +771,63 @@ </thead> <tbody> <tr> - <td class="ds-table-checkbox" id="1"><input type="checkbox"></td> + <td class="ds-table-checkbox"><input class="ds-errorlog-table" id="errorlog-1" type="checkbox"></td> <td>Trace Function Calls</td> </tr> <tr> - <td class="ds-table-checkbox" id="2"><input type="checkbox"></td> + <td class="ds-table-checkbox"><input class="ds-errorlog-table" id="errorlog-2" type="checkbox"></td> <td>Packet Handling</td> </tr> <tr> - <td class="ds-table-checkbox" id="4"><input type="checkbox"></td> + <td class="ds-table-checkbox"><input class="ds-errorlog-table" id="errorlog-4" type="checkbox"></td> <td>Heavy Trace Output</td> </tr> <tr> - <td class="ds-table-checkbox" id="8"><input type="checkbox"></td> + <td class="ds-table-checkbox"><input class="ds-errorlog-table" id="errorlog-8" type="checkbox"></td> <td>Connection Management</td> </tr> <tr> - <td class="ds-table-checkbox" id="16"><input type="checkbox"></td> + <td class="ds-table-checkbox"><input class="ds-errorlog-table" id="errorlog-16" type="checkbox"></td> <td>Packets Sent/Received</td> </tr> <tr> - <td class="ds-table-checkbox" id="32"><input type="checkbox"></td> + <td class="ds-table-checkbox"><input class="ds-errorlog-table" id="errorlog-32" type="checkbox"></td> <td>Search Filter Processing</td> </tr> <tr> - <td class="ds-table-checkbox" id="64"><input type="checkbox"></td> + <td class="ds-table-checkbox"><input class="ds-errorlog-table" id="errorlog-64" type="checkbox"></td> <td>Config File Processing</td> </tr> <tr> - <td class="ds-table-checkbox" id="128"><input type="checkbox"></td> + <td class="ds-table-checkbox"><input class="ds-errorlog-table" id="errorlog-128" type="checkbox"></td> <td>Access Control List Processing</td> </tr> <tr> - <td class="ds-table-checkbox" id="2048"><input type="checkbox"></td> + <td class="ds-table-checkbox"><input class="ds-errorlog-table" id="errorlog-2048" type="checkbox"></td> <td>Log Entry Parsing</td> </tr> <tr> - <td class="ds-table-checkbox" id="4096"><input type="checkbox"></td> + <td class="ds-table-checkbox"><input class="ds-errorlog-table" id="errorlog-4096" type="checkbox"></td> <td>Housekeeping</td> </tr> <tr> - <td class="ds-table-checkbox" id="8192"><input type="checkbox"></td> + <td class="ds-table-checkbox"><input class="ds-errorlog-table" id="errorlog-8192" type="checkbox"></td> <td>Replication</td> </tr> <tr> - <td class="ds-table-checkbox" id="32768"><input type="checkbox"></td> + <td class="ds-table-checkbox"><input class="ds-errorlog-table" id="errorlog-32768" type="checkbox"></td> <td>Entry Cache</td> </tr> <tr> - <td class="ds-table-checkbox" id="65536"><input type="checkbox"></td> + <td class="ds-table-checkbox"><input class="ds-errorlog-table" id="errorlog-65536" type="checkbox"></td> <td>Plug-ins</td> </tr> <tr> - <td class="ds-table-checkbox" id="262144"><input type="checkbox"></td> + <td class="ds-table-checkbox"><input class="ds-errorlog-table" id="errorlog-262144" type="checkbox"></td> <td>Access Control Summary</td> </tr> <tr> - <td class="ds-table-checkbox" id="1048576"><input type="checkbox"></td> + <td class="ds-table-checkbox"><input class="ds-errorlog-table" id="errorlog-1048576" type="checkbox"></td> <td>Nunc-Stans Connection Logging</td> </tr> </tbody>
0
393489b64f728156934cbfa1c190588565a2cf67
389ds/389-ds-base
Issue 6188 - Check if nsslapd-haproxy-trusted-ip attribute is returned in default schema Description: Add a test to check if nsslapd-haproxy-trusted-ip is returned in default schema Relates: https://github.com/389ds/389-ds-base/issues/6188 Reviewed by: vashirov (Thanks) Signed-off-by: Sumedh Sidhaye <[email protected]>
commit 393489b64f728156934cbfa1c190588565a2cf67 Author: Sumedh Sidhaye <[email protected]> Date: Wed Sep 4 21:34:19 2024 +0530 Issue 6188 - Check if nsslapd-haproxy-trusted-ip attribute is returned in default schema Description: Add a test to check if nsslapd-haproxy-trusted-ip is returned in default schema Relates: https://github.com/389ds/389-ds-base/issues/6188 Reviewed by: vashirov (Thanks) Signed-off-by: Sumedh Sidhaye <[email protected]> diff --git a/dirsrvtests/tests/suites/basic/haproxy_test.py b/dirsrvtests/tests/suites/basic/haproxy_test.py index 08db0b50e..1d61170dd 100644 --- a/dirsrvtests/tests/suites/basic/haproxy_test.py +++ b/dirsrvtests/tests/suites/basic/haproxy_test.py @@ -60,6 +60,8 @@ def test_haproxy_trust_ip_attribute(topo, setup_test): log.info("Check that nsslapd-haproxy-trusted-ip attribute is present") assert topo.standalone.config.present('nsslapd-haproxy-trusted-ip', '192.168.0.1') + # Check nsslapd-haproxy-trusted-ip attribute is present in schema + assert topo.standalone.schema.query_attributetype('nsslapd-haproxy-trusted-ip') is not None log.info("Delete nsslapd-haproxy-trusted-ip attribute") topo.standalone.config.remove_all('nsslapd-haproxy-trusted-ip')
0
345221c01a64f8f88214ac51e8e2ae3206f0f5aa
389ds/389-ds-base
Bump version to 1.4.0.13
commit 345221c01a64f8f88214ac51e8e2ae3206f0f5aa Author: Mark Reynolds <[email protected]> Date: Thu Jul 19 14:38:15 2018 -0400 Bump version to 1.4.0.13 diff --git a/VERSION.sh b/VERSION.sh index f21cb1c96..90e41a5b6 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=4 -VERSION_MAINT=0.12 +VERSION_MAINT=0.13 # NOTE: VERSION_PREREL is automatically set for builds made out of a git tree VERSION_PREREL= VERSION_DATE=$(date -u +%Y%m%d)
0
3f6d361abb785011546604fdf4c052ce4abb3e47
389ds/389-ds-base
Resolves: bug 480642 Bug Description: HPUX: Server to Server SASL - Unknown Authentication Method Reviewed by: nkinder (Thanks!) Fix Description: On some platforms, we do not install the sasl auth method plugins in a standard location, so we have the nsslapd-saslpath config setting to provide that location in a CB_GETPATH callback provided to sasl_server_init. This works fine for being a SASL server. However, to be an LDAP SASL client, we have to provide that callback to sasl_client_init too. This call happens the first time the mozldap client library is initialized. mozldap has a hardcoded list of sasl callbacks it provides, and does not allow callers to augment that list. So, we simply replace the list with one that contains the CB_GETPATH callback. Platforms tested: HP-UX 11.23 64-bit Flag Day: no Doc impact: no
commit 3f6d361abb785011546604fdf4c052ce4abb3e47 Author: Rich Megginson <[email protected]> Date: Wed Feb 4 18:21:01 2009 +0000 Resolves: bug 480642 Bug Description: HPUX: Server to Server SASL - Unknown Authentication Method Reviewed by: nkinder (Thanks!) Fix Description: On some platforms, we do not install the sasl auth method plugins in a standard location, so we have the nsslapd-saslpath config setting to provide that location in a CB_GETPATH callback provided to sasl_server_init. This works fine for being a SASL server. However, to be an LDAP SASL client, we have to provide that callback to sasl_client_init too. This call happens the first time the mozldap client library is initialized. mozldap has a hardcoded list of sasl callbacks it provides, and does not allow callers to augment that list. So, we simply replace the list with one that contains the CB_GETPATH callback. Platforms tested: HP-UX 11.23 64-bit Flag Day: no Doc impact: no diff --git a/ldap/servers/slapd/util.c b/ldap/servers/slapd/util.c index 79df75be0..0088af402 100644 --- a/ldap/servers/slapd/util.c +++ b/ldap/servers/slapd/util.c @@ -885,6 +885,54 @@ slapi_urlparse_err2string( int err ) return( s ); } +#include <sasl.h> + +/* copied from mozldap libldap/saslbind.c */ +static int +slapd_sasl_fail() +{ + return( SASL_FAIL ); +} + +/* copied from slapd/saslbind.c - not an easy way to share this function + between the two files */ +static int slapd_sasl_getpluginpath(sasl_conn_t *conn, const char **path) +{ + /* Try to get path from config, otherwise check for SASL_PATH environment + * variable. If neither of these are set, default to /usr/lib64/sasl2 on + * 64-bit Linux machines, and /usr/lib/sasl2 on all other platforms. + */ + char *pluginpath = config_get_saslpath(); + if ((!pluginpath) || (*pluginpath == '\0')) { + if (!(pluginpath = getenv("SASL_PATH"))) { +#if defined(LINUX) && defined(__LP64__) + pluginpath = "/usr/lib64/sasl2"; +#else + pluginpath = "/usr/lib/sasl2"; +#endif + } + } + *path = pluginpath; + return SASL_OK; +} + +/* copied from mozldap libldap/saslbind.c - except + SASL_CB_GETPATH added as last item (before SASL_CB_LIST_END + This allows us to set the sasl path used for outgoing + client connections */ +sasl_callback_t slapd_client_callbacks[] = { + { SASL_CB_GETOPT, slapd_sasl_fail, NULL }, + { SASL_CB_GETREALM, NULL, NULL }, + { SASL_CB_USER, NULL, NULL }, + { SASL_CB_CANON_USER, NULL, NULL }, + { SASL_CB_AUTHNAME, NULL, NULL }, + { SASL_CB_PASS, NULL, NULL }, + { SASL_CB_ECHOPROMPT, NULL, NULL }, + { SASL_CB_NOECHOPROMPT, NULL, NULL }, + { SASL_CB_GETPATH, slapd_sasl_getpluginpath, NULL }, + { SASL_CB_LIST_END, NULL, NULL } +}; + /* Perform LDAP init and return an LDAP* handle. If ldapurl is given, that is used as the basis for the protocol, host, port, and whether @@ -914,6 +962,16 @@ slapi_ldap_init_ext( LDAPURLDesc *ludp = NULL; LDAP *ld = NULL; int rc = 0; + extern sasl_callback_t *client_callbacks; + + /* We need to provide a sasl path used for client connections, especially + if the server is not set up to be a sasl server - since mozldap provides + no way to override the default path programatically, we replace its + client callback list with our own so that we can provide a CB_GETPATH + callback */ + if (client_callbacks != slapd_client_callbacks) { + client_callbacks = slapd_client_callbacks; + } /* if ldapurl is given, parse it */ if (ldapurl && ((rc = ldap_url_parse_no_defaults(ldapurl, &ludp, 0)) || @@ -1105,7 +1163,6 @@ 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
0
c1b510f60a509e54eff163003c292ebb1d94fc1a
389ds/389-ds-base
Resolves: bug 468474 Bug Description: migration results in incomplete admin server sie Reviewed by: nkinder (Thanks!) Fix Description: This is a redesign of one of the core pieces of the setup/migration code - the code that adds the LDAP entries in various places. For starters, I removed the code that would implicitly delete existing trees. This is the root cause of this bug, and other similar problems with setup/instance creation that have been reported. We should never implicitly delete entries. Instead, we should explicitly delete entries by using the changetype: delete in an LDIF template file. Another source of problems was that to update an entry, we would delete it and add it back. This caused some configuration settings to be wiped out (e.g. encryption settings). We cannot do this any more. The LDIF template entries have been modified to have two sets of information for each entry that requires update - the entry to add if no entry exists (the full entry) or the changes to make to the entry if it does exist. The code in Util.pm has been changed to ignore duplicate entries and to ignore changes made to entries that do not exist. Another source of problems with migration is that the error checking was not adequate, especially with FileConn and dse.ldif reading. The fix is to add better error checking and reporting in these areas of code, including error messages. Yet another problem is the run_dir handling. On many platforms the run_dir is shared among all DS instances and the admin server. Older versions of the software allowed you to run the servers as root. We have to make sure run_dir is usable by the least privileged user of all of the servers. Platforms tested: RHEL4 Flag Day: no Doc impact: no
commit c1b510f60a509e54eff163003c292ebb1d94fc1a Author: Rich Megginson <[email protected]> Date: Tue Feb 24 14:24:47 2009 +0000 Resolves: bug 468474 Bug Description: migration results in incomplete admin server sie Reviewed by: nkinder (Thanks!) Fix Description: This is a redesign of one of the core pieces of the setup/migration code - the code that adds the LDAP entries in various places. For starters, I removed the code that would implicitly delete existing trees. This is the root cause of this bug, and other similar problems with setup/instance creation that have been reported. We should never implicitly delete entries. Instead, we should explicitly delete entries by using the changetype: delete in an LDIF template file. Another source of problems was that to update an entry, we would delete it and add it back. This caused some configuration settings to be wiped out (e.g. encryption settings). We cannot do this any more. The LDIF template entries have been modified to have two sets of information for each entry that requires update - the entry to add if no entry exists (the full entry) or the changes to make to the entry if it does exist. The code in Util.pm has been changed to ignore duplicate entries and to ignore changes made to entries that do not exist. Another source of problems with migration is that the error checking was not adequate, especially with FileConn and dse.ldif reading. The fix is to add better error checking and reporting in these areas of code, including error messages. Yet another problem is the run_dir handling. On many platforms the run_dir is shared among all DS instances and the admin server. Older versions of the software allowed you to run the servers as root. We have to make sure run_dir is usable by the least privileged user of all of the servers. Platforms tested: RHEL4 Flag Day: no Doc impact: no diff --git a/ldap/admin/src/scripts/DSCreate.pm.in b/ldap/admin/src/scripts/DSCreate.pm.in index efb1fa651..89f0ba00e 100644 --- a/ldap/admin/src/scripts/DSCreate.pm.in +++ b/ldap/admin/src/scripts/DSCreate.pm.in @@ -215,6 +215,28 @@ sub makeDSDirs { return @errs; } } + # run_dir is a special case because it is usually shared among + # all instances and the admin server + # all instances must be able to write to it + # if the SuiteSpotUserID is root or 0, we can just skip + # this because root will have access to it - we really + # shouldn't be using root anyway, primarily just for + # legacy migration support + # if there are two different user IDs that need access + # to this directory, then SuiteSpotGroup must be defined, + # and both users must be members of the SuiteSpotGroup + if (($inf->{General}->{SuiteSpotUserID} eq 'root') || + (defined($inf->{General}->{SuiteSpotUserID}) && + ($inf->{General}->{SuiteSpotUserID} =~ /^0$/))) { + # skip + debug(3, "Root user " . $inf->{General}->{SuiteSpotUserID} . " already has access to $inf->{slapd}->{run_dir} - skipping\n"); + } else { + my $dir = $inf->{slapd}->{run_dir}; + # rwx by user only, or by user & group if a group is defined + @errs = changeOwnerMode($inf, 7, $dir, 7); + debug(3, "Changed owner of $dir to " . $inf->{General}->{SuiteSpotUserID} . ": error @errs\n"); + debug(3, "\t" . `/bin/ls -ld $dir`); + } # set the group of the parent dir of config_dir and inst_dir if (defined($inf->{General}->{SuiteSpotGroup})) { for (qw(inst_dir config_dir)) { @@ -372,7 +394,10 @@ sub createConfigFile { } } - $conn->write($conffile); + if (!$conn->write($conffile)) { + $conn->close(); + return ("error_writing_ldif", $conffile, $!); + } $conn->close(); if (@errs = changeOwnerMode($inf, 6, $conffile)) { @@ -506,11 +531,21 @@ sub initDatabase { my ($fh, $templdif) = tempfile("ldifXXXXXX", SUFFIX => ".ldif", OPEN => 0, DIR => File::Spec->tmpdir); + if (!$templdif) { + return ('error_creating_templdif', $!); + } my $conn = new FileConn; $conn->setNamingContext($inf->{slapd}->{Suffix}); getMappedEntries($mapper, \@ldiffiles, \@errs, \&check_and_add_entry, [$conn]); - $conn->write($templdif); + if (@errs) { + $conn->close(); + return @errs; + } + if (!$conn->write($templdif)) { + $conn->close(); + return ('error_writing_ldif', $templdif, $!); + } $conn->close(); if (@errs) { return @errs; diff --git a/ldap/admin/src/scripts/DSMigration.pm.in b/ldap/admin/src/scripts/DSMigration.pm.in index dd6f74af9..da51d4dfa 100644 --- a/ldap/admin/src/scripts/DSMigration.pm.in +++ b/ldap/admin/src/scripts/DSMigration.pm.in @@ -938,11 +938,15 @@ sub migrateDS { # extract the information needed for ds_newinst.pl my $oldconfigdir = "$mig->{oldsroot}/$inst/config"; my $inf = createInfFromConfig($oldconfigdir, $inst, \@errs); - debug(2, "Using inffile $inf->{filename} created from $oldconfigdir\n"); if (@errs) { $mig->msg(@errs); return 0; } + if (!$inf) { + $mig->msg($FATAL, 'error_opening_dseldif', "$oldconfigdir/dse.ldif", $!); + return 0; + } + debug(2, "Using inffile $inf->{filename} created from $oldconfigdir\n"); # create servers but do not start them until after databases # have been migrated @@ -960,7 +964,16 @@ sub migrateDS { } my $src = new FileConn("$oldconfigdir/dse.ldif", 1); # read-only + if (!$src) { + $mig->msg($FATAL, 'error_opening_dseldif', "$oldconfigdir/dse.ldif", $!); + return 0; + } my $dest = new FileConn("$mig->{configdir}/$inst/dse.ldif"); + if (!$dest) { + $src->close(); + $mig->msg($FATAL, 'error_opening_dseldif', "$mig->{configdir}/$inst/dse.ldif", $!); + return 0; + } @errs = migrateDSInstance($mig, $inst, $src, $dest); $src->close(); diff --git a/ldap/admin/src/scripts/FileConn.pm b/ldap/admin/src/scripts/FileConn.pm index 447f4aaf9..f1ac4d2d6 100644 --- a/ldap/admin/src/scripts/FileConn.pm +++ b/ldap/admin/src/scripts/FileConn.pm @@ -67,7 +67,9 @@ sub new { $self->setNamingContext($_); } $self->setNamingContext(""); # root DSE - $self->read($filename); + if (!$self->read($filename)) { + return; + } return $self; } @@ -90,10 +92,14 @@ sub read { } if (!$self->{filename}) { - return; + return 1; # no filename given - ok + } + + if (!open( MYLDIF, "$filename" )) { + confess "Can't open $filename: $!"; + return 0; } - open( MYLDIF, "$filename" ) || confess "Can't open $filename: $!"; my $in = new Mozilla::LDAP::LDIF(*MYLDIF); $self->{reading} = 1; while ($ent = readOneEntry $in) { @@ -103,6 +109,8 @@ sub read { } delete $self->{reading}; close( MYLDIF ); + + return 1; } sub setNamingContext { @@ -175,16 +183,22 @@ sub write { } if (!$self->{filename} or $self->{readonly} or $self->{reading}) { - return; + return 1; # ok - no filename given - just ignore + } + + if (!open( MYLDIF, ">$filename" )) { + confess "Can't write $filename: $!"; + return 0; } - open( MYLDIF, ">$filename" ) || confess "Can't write $filename: $!"; $self->iterate("", LDAP_SCOPE_SUBTREE, \&writecb, \*MYLDIF); for (keys %{$self->{namingContexts}}) { next if (!$_); # skip "" - we already did that $self->iterate($_, LDAP_SCOPE_SUBTREE, \&writecb, \*MYLDIF); } close( MYLDIF ); + + return 1; } sub setErrorCode { @@ -372,8 +386,7 @@ sub add { if ($self->isNamingContext($ndn) and !exists($self->{$ndn}->{data})) { $self->{$ndn}->{data} = $entry; - $self->write(); - return 1; + return $self->write(); } if (exists($self->{$ndn})) { @@ -415,9 +428,7 @@ sub update { # process omits the deleted attrs via the Entry FETCH, FIRSTKEY, and NEXTKEY # methods $self->{$ndn}->{data} = cloneEntry($entry); - $self->write(); - - return 1; + return $self->write(); } sub delete { @@ -464,8 +475,7 @@ sub delete { # delete this node delete $self->{$ndn}; - $self->write(); - return 1; + return $self->write(); } 1; diff --git a/ldap/admin/src/scripts/Util.pm.in b/ldap/admin/src/scripts/Util.pm.in index 20aea64b7..660461e76 100644 --- a/ldap/admin/src/scripts/Util.pm.in +++ b/ldap/admin/src/scripts/Util.pm.in @@ -40,7 +40,7 @@ package Util; use Mozilla::LDAP::Conn; use Mozilla::LDAP::Utils qw(normalizeDN); -use Mozilla::LDAP::API; # Direct access to C API +use Mozilla::LDAP::API qw(:constant ldap_explode_dn ldap_err2string) ; # Direct access to C API use Mozilla::LDAP::LDIF; require Exporter; @@ -172,85 +172,6 @@ sub delete_all return 0; } -my %ignorelist = ( - "nsslapd-directory", "nsslapd-directory", - "nsslapd-require-index", "nsslapd-require-index", - "nsslapd-readonly", "nsslapd-readonly", - "modifytimestamp", "modifyTimestamp", - "createtimestamp", "createTimestamp", - "installationtimestamp", "installationTimestamp", - "creatorsname", "creatorsName", - "modifiersname", "modifiersName", - "numsubordinates", "numSubordinates" -); - -my %speciallist = ( - "uniquemember", 1, - "aci", 1 -); - -# compare 2 entries -# return 0 if they match 100% (exception: %ignorelist). -# return 1 if they match except %speciallist. -# return -1 if they do not match. -sub comp_entries -{ - my ($e0, $e1) = @_; - my $rc = 0; - foreach my $akey ( keys %{$e0} ) - { - next if ( $ignorelist{lc($akey)} ); - my $aval0 = $e0->{$akey}; - my $aval1 = $e1->{$akey}; - my $a0max = $#{$aval0}; - my $a1max = $#{$aval1}; - my $amin = $#{$aval0}; - if ( $a0max != $a1max ) - { - if ( $speciallist{lc($akey)} ) - { - $rc = 1; - if ( $a0max < $a1max ) - { - $amin = $a0max; - } - else - { - $amin = $a1max; - } - } - else - { - $rc = -1; - return $rc; - } - } - my @sval0 = sort { $a cmp $b } @{$aval0}; - my @sval1 = sort { $a cmp $b } @{$aval1}; - for ( my $i = 0; $i <= $amin; $i++ ) - { - my $isspecial = -1; - if ( $sval0[$i] ne $sval1[$i] ) - { - if ( 0 > $isspecial ) - { - $isspecial = $speciallist{lc($akey)}; - } - if ( $isspecial ) - { - $rc = 1; - } - else - { - $rc = -1; - return $rc; - } - } - } - } - return $rc; -} - # if the entry does not exist on the server, add the entry. # otherwise, do nothing # you can use this as the callback to getMappedEntries, so @@ -272,9 +193,18 @@ sub check_and_add_entry my $sentry = $conn->search($aentry->{dn}, "base", "(objectclass=*)", 0, ("*", "aci")); if ($sentry) { debug(3, "check_and_add_entry: Found entry " . $sentry->getDN() . "\n"); + if (! @ctypes) { # entry exists, and this is not a modify op + debug(3, "check_and_add_entry: skipping entry " . $sentry->getDN() . "\n"); + return 1; # ignore - return success + } } else { debug(3, "check_and_add_entry: Entry not found " . $aentry->{dn} . " error " . $conn->getErrorString() . "\n"); + if (@ctypes) { # uh oh - attempt to del/mod an entry that doesn't exist + debug(3, "check_and_add_entry: attepting to @ctypes the entry " . $aentry->{dn} . + " that does not exist\n"); + return 1; # ignore - return success + } } do { @@ -289,39 +219,7 @@ sub check_and_add_entry my $op = $OP_NONE; if ( 0 > $#ctypes ) # aentry: complete entry { - $op = $OP_ADD; - - my $rc = -1; - if ( $sentry && !$fresh ) - { - $rc = comp_entries( $sentry, $aentry ); - } - if ( 0 == $rc && !$fresh ) - { - # the identical entry exists on the configuration DS. - # no need to add the entry. - $op = $OP_NONE; - goto out; - } - elsif ( (1 == $rc) && !$fresh ) - { - $op = $OP_MOD; - @addtypes = keys %{$aentry}; # add all attrs - } - elsif ( $sentry && $sentry->{dn} ) - { - # $fresh || $rc == -1 - # an entry having the same DN exists, but the attributes do not - # match. remove the entry and the subtree underneath. - debug(1, "Deleting an entry dn: $sentry->{dn} ...\n"); - $rc = delete_all($conn, $sentry); - if ( 0 != $rc ) - { - push @{$errs}, 'error_deleteall_entries', $sentry->{dn}, $conn->getErrorString(); - debug(1, "Error deleting $sentry->{dn}\n"); - return 0; - } - } + $op = $OP_ADD; # just add the entry } else # aentry: modify format { @@ -371,9 +269,13 @@ sub check_and_add_entry } debug(1, "Entry $aentry->{dn} is deleted\n"); } - elsif ( 0 < $op ) # $sentry exists + elsif ( 0 < $op ) # modify op { my $attr; + my @errsToIgnore; + if (@addtypes) { + push @errsToIgnore, LDAP_TYPE_OR_VALUE_EXISTS; + } foreach $attr ( @addtypes ) { foreach my $val ($aentry->getValues($attr)) @@ -388,6 +290,9 @@ sub check_and_add_entry debug(3, "Replacing attr=$attr values=" . $aentry->getValues($attr) . " to entry $aentry->{dn}\n"); $sentry->setValues($attr, @vals); } + if (@deltypes) { + push @errsToIgnore, LDAP_NO_SUCH_ATTRIBUTE; + } foreach $attr ( @deltypes ) { # removeValue takes a single value only @@ -410,11 +315,15 @@ sub check_and_add_entry if ( $rc != 0 ) { my $string = $conn->getErrorString(); - push @{$errs}, 'error_updating_entry', $sentry->{dn}, $string; debug(1, "ERROR: updating an entry $sentry->{dn} failed, error: $string\n"); - $aentry->printLDIF(); - $conn->close(); - return 0; + if (grep /^$rc$/, @errsToIgnore) { + debug(1, "Ignoring error $rc returned by adding @addtypes deleting @deltypes\n"); + } else { + push @{$errs}, 'error_updating_entry', $sentry->{dn}, $string; + $aentry->printLDIF(); + $conn->close(); + return 0; + } } } if ( $sentry ) @@ -793,19 +702,32 @@ sub createInfFromConfig { my $fname = "$configdir/dse.ldif"; my $id; ($id = $inst) =~ s/^slapd-//; - if (! -f $fname) { + if (! -f $fname || ! -r $fname) { push @{$errs}, "error_opening_dseldif", $fname, $!; return 0; } my $conn = new FileConn($fname, 1); + if (!$conn) { + push @{$errs}, "error_opening_dseldif", $fname, $!; + return 0; + } my $ent = $conn->search("cn=config", "base", "(objectclass=*)"); if (!$ent) { push @{$errs}, "error_opening_dseldif", $fname, $!; + $conn->close(); return 0; } my ($outfh, $inffile) = tempfile(SUFFIX => '.inf'); + if (!$outfh || !$inffile) { + push @{$errs}, "error_opening_tempinf", $fname, $!; + if ($outfh) { + close $outfh; + } + $conn->close(); + return 0; + } print $outfh "[General]\n"; print $outfh "FullMachineName = ", $ent->getValues('nsslapd-localhost'), "\n"; print $outfh "SuiteSpotUserID = ", $ent->getValues('nsslapd-localuser'), "\n"; diff --git a/ldap/admin/src/scripts/remove-ds.pl.in b/ldap/admin/src/scripts/remove-ds.pl.in index fadbbe908..492ccc7ee 100755 --- a/ldap/admin/src/scripts/remove-ds.pl.in +++ b/ldap/admin/src/scripts/remove-ds.pl.in @@ -162,6 +162,10 @@ if ( ! -d $configdir ) # read the config file to find out the paths my $dseldif = "@instconfigdir@/$instname/dse.ldif"; my $conn = new FileConn($dseldif); +if (!$conn) { + print STDERR "Error: Could not open config file $dseldif: Error $!\n"; + exit 1; +} my $dn = "cn=config"; my $entry = $conn->search($dn, "base", "(cn=*)", 0); diff --git a/ldap/admin/src/scripts/setup-ds.res.in b/ldap/admin/src/scripts/setup-ds.res.in index fa2562750..a89b1274b 100644 --- a/ldap/admin/src/scripts/setup-ds.res.in +++ b/ldap/admin/src/scripts/setup-ds.res.in @@ -127,3 +127,7 @@ Please remove it first if you really want to recreate it,\ or use a different ServerIdentifier to create another instance.\n error_opening_init_ldif = Could not open the initial LDIF file '%s'.\ The file was not found or could not be read.\n +error_opening_dseldif = Could not open the DSE config file '%s'. Error: %s\n +error_opening_tempinf = Could not create temporary .inf file for config. Error: %s\n +error_writing_ldif = Could not write the LDIF file '%s'. Error: %s\n +error_creating_templdif = Could not create temporary LDIF file. Error: %s\n
0
75e55e26579955adf058e8adcba9a28779583b7b
389ds/389-ds-base
Ticket 49298 - Correct error codes with config restore. Bug Description: The piece of code uses 0 as an error - not 1, and in some cases did not even check the codes or use the correct logic. Fix Description: Cleanup dse_check_file to better check the content of files and communicate issues to the admin. Correct slapd_bootstrap_config to correctly handle the cases of removal and restore. https://pagure.io/389-ds-base/issue/49298 Author: wibrown Review by: mreynoolds & spichugi Signed-off-by: Mark Reynolds <[email protected]>
commit 75e55e26579955adf058e8adcba9a28779583b7b Author: William Brown <[email protected]> Date: Wed Nov 15 13:44:02 2017 +1000 Ticket 49298 - Correct error codes with config restore. Bug Description: The piece of code uses 0 as an error - not 1, and in some cases did not even check the codes or use the correct logic. Fix Description: Cleanup dse_check_file to better check the content of files and communicate issues to the admin. Correct slapd_bootstrap_config to correctly handle the cases of removal and restore. https://pagure.io/389-ds-base/issue/49298 Author: wibrown Review by: mreynoolds & spichugi Signed-off-by: Mark Reynolds <[email protected]> diff --git a/dirsrvtests/tests/suites/config/removed_config_49298_test.py b/dirsrvtests/tests/suites/config/removed_config_49298_test.py new file mode 100644 index 000000000..e65236924 --- /dev/null +++ b/dirsrvtests/tests/suites/config/removed_config_49298_test.py @@ -0,0 +1,81 @@ +# --- 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 +import os +import logging +import subprocess + +from lib389.topologies import topology_st as topo + +DEBUGGING = os.getenv("DEBUGGING", default=False) +if DEBUGGING: + logging.getLogger(__name__).setLevel(logging.DEBUG) +else: + logging.getLogger(__name__).setLevel(logging.INFO) +log = logging.getLogger(__name__) + +def test_restore_config(topo): + """ + Check that if a dse.ldif and backup are removed, that the server still starts. + + :id: e1c38fa7-30bc-46f2-a934-f8336f387581 + :setup: Standalone instance + :steps: + 1. Stop the instance + 2. Delete 'dse.ldif' + 3. Start the instance + :expectedresults: + 1. Steps 1 and 2 succeed. + 2. Server will succeed to start with restored cfg. + """ + topo.standalone.stop() + + dse_path = topo.standalone.get_config_dir() + + log.info(dse_path) + + for i in ('dse.ldif', 'dse.ldif.startOK'): + p = os.path.join(dse_path, i) + os.remove(p) + + # This will pass. + topo.standalone.start() + +def test_removed_config(topo): + """ + Check that if a dse.ldif and backup are removed, that the server + exits better than "segfault". + + :id: b45272d1-c197-473e-872f-07257fcb2ec0 + :setup: Standalone instance + :steps: + 1. Stop the instance + 2. Delete 'dse.ldif', 'dse.ldif.bak', 'dse.ldif.startOK' + 3. Start the instance + :expectedresults: + 1. Steps 1 and 2 succeed. + 2. Server will fail to start, but will not crash. + """ + topo.standalone.stop() + + dse_path = topo.standalone.get_config_dir() + + log.info(dse_path) + + for i in ('dse.ldif', 'dse.ldif.bak', 'dse.ldif.startOK'): + p = os.path.join(dse_path, i) + os.remove(p) + + # We actually can't check the log output, because it can't read dse.ldif, + # don't know where to write it yet! All we want is the server fail to + # start here, rather than infinite run + segfault. + with pytest.raises(subprocess.CalledProcessError): + topo.standalone.start() + + diff --git a/ldap/servers/slapd/config.c b/ldap/servers/slapd/config.c index afe07df84..c8d57e747 100644 --- a/ldap/servers/slapd/config.c +++ b/ldap/servers/slapd/config.c @@ -121,14 +121,13 @@ slapd_bootstrap_config(const char *configdir) "Passed null config directory\n"); return rc; /* Fail */ } - PR_snprintf(configfile, sizeof(configfile), "%s/%s", configdir, - CONFIG_FILENAME); - PR_snprintf(tmpfile, sizeof(tmpfile), "%s/%s.tmp", configdir, - CONFIG_FILENAME); - if ((rc = dse_check_file(configfile, tmpfile)) == 0) { - PR_snprintf(tmpfile, sizeof(tmpfile), "%s/%s.bak", configdir, - CONFIG_FILENAME); - rc = dse_check_file(configfile, tmpfile); + PR_snprintf(configfile, sizeof(configfile), "%s/%s", configdir, CONFIG_FILENAME); + PR_snprintf(tmpfile, sizeof(tmpfile), "%s/%s.bak", configdir, CONFIG_FILENAME); + rc = dse_check_file(configfile, tmpfile); + if (rc == 0) { + /* EVERYTHING IS GOING WRONG, ARRGHHHHHH */ + slapi_log_err(SLAPI_LOG_ERR, "slapd_bootstrap_config", "No valid configurations can be accessed! You must restore %s from backup!\n", configfile); + return 0; } if ((rc = PR_GetFileInfo64(configfile, &prfinfo)) != PR_SUCCESS) { diff --git a/ldap/servers/slapd/dse.c b/ldap/servers/slapd/dse.c index 2634f58be..bce23331c 100644 --- a/ldap/servers/slapd/dse.c +++ b/ldap/servers/slapd/dse.c @@ -609,29 +609,49 @@ dse_check_file(char *filename, char *backupname) if (PR_GetFileInfo64(filename, &prfinfo) == PR_SUCCESS) { if (prfinfo.size > 0) { - return (1); + /* File exists and has content. */ + return 1; } else { + slapi_log_err(SLAPI_LOG_INFO, "dse_check_file", + "The config %s has zero length. Attempting restore ... \n", filename, rc); rc = PR_Delete(filename); } + } else { + slapi_log_err(SLAPI_LOG_INFO, "dse_check_file", + "The config %s can not be accessed. Attempting restore ... (reason: %d)\n", filename, rc); } if (backupname) { + + if (PR_GetFileInfo64(backupname, &prfinfo) != PR_SUCCESS) { + slapi_log_err(SLAPI_LOG_INFO, "dse_check_file", + "The backup %s can not be accessed. Check it exists and permissions.\n", backupname); + return 0; + } + + if (prfinfo.size <= 0) { + slapi_log_err(SLAPI_LOG_ERR, "dse_check_file", + "The backup file %s has zero length, refusing to restore it.\n", backupname); + return 0; + } + rc = PR_Rename(backupname, filename); - } else { - return (0); - } + if (rc != PR_SUCCESS) { + slapi_log_err(SLAPI_LOG_INFO, "dse_check_file", + "The configuration file %s was NOT able to be restored from %s, error %d\n", filename, backupname, rc); + return 0; + } - if (PR_GetFileInfo64(filename, &prfinfo) == PR_SUCCESS && prfinfo.size > 0) { slapi_log_err(SLAPI_LOG_INFO, "dse_check_file", - "The configuration file %s was restored from backup %s\n", filename, backupname); - return (1); + "The configuration file %s was restored from backup %s\n", filename, backupname); + return 1; + } else { - slapi_log_err(SLAPI_LOG_ERR, "dse_check_file", - "The configuration file %s was not restored from backup %s, error %d\n", - filename, backupname, rc); - return (0); + slapi_log_err(SLAPI_LOG_INFO, "dse_check_file", "No backup filename provided.\n"); + return 0; } } + static int dse_read_one_file(struct dse *pdse, const char *filename, Slapi_PBlock *pb, int primary_file) {
0
89033bea42539857ef6c4ae04c1863970f7d28f1
389ds/389-ds-base
Issue 5307 - VERSION_PREREL is not set correctly in CI builds Bug Description: VERSION_PREREL is used to set pre-release version (.a1, .rc1, etc). If the build is done inside the git tree, it is set to VERSION_PREREL=.${VERSION_DATE}git$COMMIT. But since we don't do any Alpha or RC releases, it should be empty by default and populated by date and git commit hash in the development builds. Additionally, in our CI git commands stopped working after git-2.36 resulting in an incorrect VERSION_PREREL. Fix Description: * Set VERSION_PREREL to an empty value * Update GH actions to explicitly add $GITHUB_WORKSPACE directory to a list of safe directories. Fixes: https://github.com/389ds/389-ds-base/issues/5307 Reviewed by: @bsimonova (Thanks!)
commit 89033bea42539857ef6c4ae04c1863970f7d28f1 Author: Viktor Ashirov <[email protected]> Date: Tue May 24 09:13:26 2022 +0200 Issue 5307 - VERSION_PREREL is not set correctly in CI builds Bug Description: VERSION_PREREL is used to set pre-release version (.a1, .rc1, etc). If the build is done inside the git tree, it is set to VERSION_PREREL=.${VERSION_DATE}git$COMMIT. But since we don't do any Alpha or RC releases, it should be empty by default and populated by date and git commit hash in the development builds. Additionally, in our CI git commands stopped working after git-2.36 resulting in an incorrect VERSION_PREREL. Fix Description: * Set VERSION_PREREL to an empty value * Update GH actions to explicitly add $GITHUB_WORKSPACE directory to a list of safe directories. Fixes: https://github.com/389ds/389-ds-base/issues/5307 Reviewed by: @bsimonova (Thanks!) diff --git a/.github/workflows/compile.yml b/.github/workflows/compile.yml index 698beaa5c..378c08308 100644 --- a/.github/workflows/compile.yml +++ b/.github/workflows/compile.yml @@ -53,9 +53,9 @@ jobs: image: ${{ matrix.image }} steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 - name: Checkout and configure - run: cd $GITHUB_WORKSPACE && autoreconf -fvi && ./configure + run: autoreconf -fvi && ./configure env: CC: ${{ matrix.compiler }} CXX: ${{ matrix.cpp-compiler }} diff --git a/.github/workflows/npm.yml b/.github/workflows/npm.yml index dfe793c6f..2a275fd5c 100644 --- a/.github/workflows/npm.yml +++ b/.github/workflows/npm.yml @@ -14,7 +14,7 @@ jobs: image: quay.io/389ds/ci-images:test steps: - name: Checkout - uses: actions/checkout@v2 + uses: actions/checkout@v3 - name: Run NPM Audit CI run: cd $GITHUB_WORKSPACE/src/cockpit/389-console && npx audit-ci --config audit-ci.json diff --git a/.github/workflows/pytest.yml b/.github/workflows/pytest.yml index b12ed9780..ed9dcb9e0 100644 --- a/.github/workflows/pytest.yml +++ b/.github/workflows/pytest.yml @@ -26,14 +26,17 @@ jobs: matrix: ${{ steps.set-matrix.outputs.matrix }} steps: - name: Checkout - uses: actions/checkout@v2 + uses: actions/checkout@v3 + + - name: Add GITHUB_WORKSPACE as a safe directory + run: git config --global --add safe.directory "$GITHUB_WORKSPACE" - name: Get a list of all test suites id: set-matrix run: echo "::set-output name=matrix::$(python3 .github/scripts/generate_matrix.py ${{ github.event.inputs.pytest_tests }})" - name: Build RPMs - run: cd $GITHUB_WORKSPACE && SKIP_AUDIT_CI=1 make -f rpm.mk dist-bz2 rpms + run: SKIP_AUDIT_CI=1 make -f rpm.mk dist-bz2 rpms - name: Tar build artifacts run: tar -cvf dist.tar dist/ @@ -54,7 +57,7 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v2 + uses: actions/checkout@v3 - name: Setup tmate session uses: mxschmitt/action-tmate@v3 diff --git a/VERSION.sh b/VERSION.sh index f80428815..dc9d527d8 100644 --- a/VERSION.sh +++ b/VERSION.sh @@ -12,7 +12,7 @@ VERSION_MAJOR=2 VERSION_MINOR=2 VERSION_MAINT=0 # NOTE: VERSION_PREREL is automatically set for builds made out of a git tree -VERSION_PREREL=0 +VERSION_PREREL= VERSION_DATE=$(date -u +%Y%m%d%H%M) # Set the version and release numbers for local developer RPM builds. We
0
f581979f9660c0806942d50f65d320912ef963ae
389ds/389-ds-base
Issue 4644 - Large updates can reset the CLcache to the beginning of the changelog (#4647) Bug description: The replication agreements are using bulk load to load updates. For bulk load it uses a cursor with DB_MULTIPLE_KEY and DB_NEXT. Before using the cursor, it must be initialized with DB_SET. If during the cursor/DB_SET the CSN refers to an update that is larger than the size of the provided buffer, then the cursor remains not initialized and c_get returns DB_BUFFER_SMALL. The consequence is that the next c_get(DB_MULTIPLE_KEY and DB_NEXT) will return the first record in the changelog DB. This break CLcache. Fix description: The fix is to harden cursor initialization so that if DB_SET fails because of DB_BUFFER_SMALL. It reallocates buf_data and retries a DB_SET. If DB_SET can not be initialized it logs a warning. The patch also changes the behaviour of the fix #4492. #4492 detected a massive (1day) jump prior the starting csn and ended the replication session. If the jump was systematic, for example if the CLcache got broken because of a too large updates, then replication was systematically stopped. This patch suppress the systematically stop, letting RA doing a big jump. From #4492 only remains the warning. relates: https://github.com/389ds/389-ds-base/issues/4644 Reviewed by: Pierre Rogier (Thanks !!!!) Platforms tested: F31
commit f581979f9660c0806942d50f65d320912ef963ae Author: tbordaz <[email protected]> Date: Tue Feb 23 13:42:31 2021 +0100 Issue 4644 - Large updates can reset the CLcache to the beginning of the changelog (#4647) Bug description: The replication agreements are using bulk load to load updates. For bulk load it uses a cursor with DB_MULTIPLE_KEY and DB_NEXT. Before using the cursor, it must be initialized with DB_SET. If during the cursor/DB_SET the CSN refers to an update that is larger than the size of the provided buffer, then the cursor remains not initialized and c_get returns DB_BUFFER_SMALL. The consequence is that the next c_get(DB_MULTIPLE_KEY and DB_NEXT) will return the first record in the changelog DB. This break CLcache. Fix description: The fix is to harden cursor initialization so that if DB_SET fails because of DB_BUFFER_SMALL. It reallocates buf_data and retries a DB_SET. If DB_SET can not be initialized it logs a warning. The patch also changes the behaviour of the fix #4492. #4492 detected a massive (1day) jump prior the starting csn and ended the replication session. If the jump was systematic, for example if the CLcache got broken because of a too large updates, then replication was systematically stopped. This patch suppress the systematically stop, letting RA doing a big jump. From #4492 only remains the warning. relates: https://github.com/389ds/389-ds-base/issues/4644 Reviewed by: Pierre Rogier (Thanks !!!!) Platforms tested: F31 diff --git a/ldap/servers/plugins/replication/cl5_clcache.c b/ldap/servers/plugins/replication/cl5_clcache.c index aa3b2cb54..71186f785 100644 --- a/ldap/servers/plugins/replication/cl5_clcache.c +++ b/ldap/servers/plugins/replication/cl5_clcache.c @@ -365,9 +365,7 @@ clcache_load_buffer(CLC_Buffer *buf, CSN **anchorCSN, int *continue_on_miss, cha } csn_as_string(buf->buf_current_csn, 0, curr); slapi_log_err(loglevel, buf->buf_agmt_name, - "clcache_load_buffer - bulk load cursor (%s) is lower than starting csn %s. Ending session.\n", curr, initial_starting_csn); - /* it just end the session with UPDATE_NO_MORE_UPDATES */ - rc = CLC_STATE_DONE; + "clcache_load_buffer - bulk load cursor (%s) is lower than starting csn %s.\n", curr, initial_starting_csn); } } @@ -408,10 +406,7 @@ clcache_load_buffer(CLC_Buffer *buf, CSN **anchorCSN, int *continue_on_miss, cha } csn_as_string(buf->buf_current_csn, 0, curr); slapi_log_err(loglevel, buf->buf_agmt_name, - "clcache_load_buffer - (DB_SET_RANGE) bulk load cursor (%s) is lower than starting csn %s. Ending session.\n", curr, initial_starting_csn); - rc = DB_NOTFOUND; - - return rc; + "clcache_load_buffer - (DB_SET_RANGE) bulk load cursor (%s) is lower than starting csn %s.\n", curr, initial_starting_csn); } } } @@ -439,6 +434,42 @@ clcache_load_buffer(CLC_Buffer *buf, CSN **anchorCSN, int *continue_on_miss, cha return rc; } +/* Set a cursor to a specific key (buf->buf_key) + * In case buf_data is too small to receive the value, DB_SET fails + * (DB_BUFFER_SMALL). This let the cursor uninitialized that is + * problematic because further cursor DB_NEXT will reset the cursor + * to the beginning of the CL. + * If buf_data is too small, this function reallocates enough space + * + * It returns the return code of cursor->c_get + */ +static int +clcache_cursor_set(DBC *cursor, CLC_Buffer *buf) +{ + int rc; + uint32_t ulen; + uint32_t dlen; + uint32_t size; + + rc = cursor->c_get(cursor, &buf->buf_key, &buf->buf_data, DB_SET); + if (rc == DB_BUFFER_SMALL) { + uint32_t ulen; + + /* Fortunately, buf->buf_data.size has been set by + * c_get() to the actual data size needed. So we can + * reallocate the data buffer and try to set again. + */ + ulen = buf->buf_data.ulen; + buf->buf_data.ulen = (buf->buf_data.size / DEFAULT_CLC_BUFFER_PAGE_SIZE + 1) * DEFAULT_CLC_BUFFER_PAGE_SIZE; + buf->buf_data.data = slapi_ch_realloc(buf->buf_data.data, buf->buf_data.ulen); + slapi_log_err(SLAPI_LOG_REPL, buf->buf_agmt_name, + "clcache_cursor_set - buf data len reallocated %d -> %d bytes (DB_BUFFER_SMALL)\n", + ulen, buf->buf_data.ulen); + rc = cursor->c_get(cursor, &buf->buf_key, &buf->buf_data, DB_SET); + } + return rc; +} + static int clcache_load_buffer_bulk(CLC_Buffer *buf, int flag) { @@ -467,17 +498,24 @@ retry: if (use_flag == DB_NEXT) { /* For bulk read, position the cursor before read the next block */ - rc = cursor->c_get(cursor, - &buf->buf_key, - &buf->buf_data, - DB_SET); + rc = clcache_cursor_set(cursor, buf); } - /* - * Continue if the error is no-mem since we don't need to - * load in the key record anyway with DB_SET. - */ if (0 == rc || DB_BUFFER_SMALL == rc) { + /* + * It should not have failed with DB_BUFFER_SMALL as we tried + * to adjust buf_data in clcache_cursor_set. + * But if it failed with DB_BUFFER_SMALL, there is a risk in clcache_cursor_get + * that the cursor will be reset to the beginning of the changelog. + * Returning an error at this point will stop replication that is + * a risk. So just accept the risk of a reset to the beginning of the CL + * and log an alarming message. + */ + if (rc == DB_BUFFER_SMALL) { + slapi_log_err(SLAPI_LOG_WARNING, buf->buf_agmt_name, + "clcache_load_buffer_bulk - Fail to position on csn=%s from the changelog (too large update ?). Risk of full CL evaluation.\n", + (char *)buf->buf_key.data); + } rc = clcache_cursor_get(cursor, buf, use_flag); } }
0
a16bf1b3c4ff0412c2481baace9b427750c11f8c
389ds/389-ds-base
Ticket 47599 - fix memory leak Coverity 12410 https://fedorahosted.org/389/ticket/47599 Reviewed by: richm(Thanks!)
commit a16bf1b3c4ff0412c2481baace9b427750c11f8c Author: Mark Reynolds <[email protected]> Date: Mon Nov 25 09:36:25 2013 -0500 Ticket 47599 - fix memory leak Coverity 12410 https://fedorahosted.org/389/ticket/47599 Reviewed by: richm(Thanks!) diff --git a/ldap/servers/slapd/back-ldbm/seq.c b/ldap/servers/slapd/back-ldbm/seq.c index 27da2a445..10484fdd2 100644 --- a/ldap/servers/slapd/back-ldbm/seq.c +++ b/ldap/servers/slapd/back-ldbm/seq.c @@ -242,6 +242,7 @@ ldbm_back_seq( Slapi_PBlock *pb ) key.flags = 0; for (retry_count = 0; retry_count < IDL_FETCH_RETRY_COUNT; retry_count++) { err = NEW_IDL_DEFAULT; + idl_free(idl); idl = idl_fetch( be, db, &key, txn.back_txn_txn, ai, &err ); if(err == DB_LOCK_DEADLOCK) { ldbm_nasty("ldbm_back_seq deadlock retry", 1600, err);
0
171e70d98b3b53f9289e263c65cb7a1da8c95484
389ds/389-ds-base
Resolves: bug 251227 Description: update dsktune for 1.1 These are the latest Solaris patches.
commit 171e70d98b3b53f9289e263c65cb7a1da8c95484 Author: Rich Megginson <[email protected]> Date: Thu Aug 9 03:36:14 2007 +0000 Resolves: bug 251227 Description: update dsktune for 1.1 These are the latest Solaris patches. diff --git a/ldap/systools/sol_patches.c b/ldap/systools/sol_patches.c index 01d2f0b28..797d730d7 100644 --- a/ldap/systools/sol_patches.c +++ b/ldap/systools/sol_patches.c @@ -1,219 +1,6 @@ -/* --- 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) 2001 Sun Microsystems, Inc. Used by permission. - * Copyright (C) 2005 Red Hat, Inc. - * All rights reserved. - * --- END COPYRIGHT BLOCK --- */ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - - -/* This list was generated by /u/norikoyasuo/bin/getSolPatches.pl */ -/* on droid.mcom.com */ -/* at Thu Mar 18 18:34:27 2004 GMT */ -/* Here is the information from /etc/release: - Solaris 8 s28_38shwp2 SPARC - Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. - Assembled 21 January 2000 - The following is a list of patches installed on the system */ -/* a patch that is commented out is either a duplicate or */ -/* a patch that is superseded by another patch */ -{108434,14,1,28,0,0,"Jan/16/2004: SunOS 5.8: 32-Bit Shared library patch for C++"}, -{108435,14,1,28,0,0,"Jan/16/2004: SunOS 5.8: 64-Bit Shared library patch for C++"}, -{108528,27,1,28,0,0,"Nov/25/2003: SunOS 5.8: kernel update patch"}, -{108652,77,1,28,0,0,"Jan/26/2004: X11 6.4.1: Xsun patch"}, -{108725,15,1,28,0,0,"Jan/23/2004: SunOS 5.8: st driver patch"}, -{108727,26,1,28,0,0,"Dec/02/2003: SunOS 5.8: /kernel/fs/nfs and /kernel/fs/sparcv9/nfs patch"}, -{108806,17,1,28,0,0,"Aug/12/2003: SunOS 5.8: Sun Quad FastEthernet qfe driver"}, -{108827,20,1,28,0,0,"Mar/20/2002: SunOS 5.8: /usr/lib/libthread.so.1 patch"}, -{108869,22,1,28,0,0,"Aug/19/2003: SunOS 5.8: snmpdx/mibiisa/libssasnmp/snmplib patch"}, -{108875,12,1,28,0,0,"Apr/10/2002: SunOS 5.8: c2audit patch"}, -{108899,4,1,28,0,0,"Feb/18/2003: SunOS 5.8: /usr/bin/ftp patch"}, -{108901,4,1,28,0,0,"Jul/23/2001: SunOS 5.8: /kernel/sys/rpcmod and /kernel/strmod/rpcmod patch"}, -{108919,20,1,28,0,0,"Sep/22/2003: CDE 1.4: dtlogin patch"}, -{108949,7,1,28,0,0,"Dec/07/2001: CDE 1.4: libDtHelp/libDtSvc patch"}, -{108968,8,1,28,0,0,"Jan/22/2003: SunOS 5.8: vol/vold/rmmount/dev_pcmem.so.1 patch"}, -{108974,37,1,28,0,0,"Jan/07/2004: SunOS 5.8: dada, uata, dad, sd, ssd and scsi drivers patch"}, -{108975,8,1,28,0,0,"Apr/18/2003: SunOS 5.8: /usr/bin/rmformat and /usr/sbin/format patch"}, -{108977,2,1,28,0,0,"Apr/18/2003: SunOS 5.8: libsmedia patch"}, -{108981,13,1,28,0,0,"Nov/25/2003: SunOS 5.8: /kernel/drv/hme and /kernel/drv/sparcv9/hme patch"}, -{108985,3,1,28,0,0,"Jun/25/2001: SunOS 5.8: /usr/sbin/in.rshd patch"}, -{108987,13,1,28,0,0,"Apr/07/2003: SunOS 5.8: Patch for patchadd and patchrm"}, -{108989,2,1,28,0,0,"Jul/18/00: SunOS 5.8: /usr/kernel/sys/acctctl and /usr/kernel/sys/exacctsys patch"}, -{108993,31,1,28,0,0,"Dec/10/2003: SunOS 5.8: LDAP2 client, libc, libthread and libnsl libraries patch"}, -{108997,3,1,28,0,0,"Jul/18/00: SunOS 5.8: libexacct and libproject patch"}, -{109007,15,1,28,0,0,"Jan/27/2004: SunOS 5.8: at/atrm/batch/cron patch"}, -{109091,6,1,28,0,0,"Apr/08/2003: SunOS 5.8: /usr/lib/fs/ufs/ufsrestore patch"}, -/* Web-Based Enterprise Management (WBEM) {109134,28,1,28,0,0,"Jun/10/2003: SunOS 5.8: WBEM patch"}, */ -{109147,27,1,28,0,0,"Nov/26/2003: SunOS 5.8: linker patch"}, -{109149,2,1,28,0,0,"Nov/13/2001: SunOS 5.8:: /usr/sbin/mkdevmaps and /usr/sbin/mkdevalloc patch"}, -{109152,2,1,28,0,0,"Mar/27/2003: SunOS 5.8: /usr/4lib/libc.so.x.9 and libdbm patch"}, -{109202,5,1,28,0,0,"Jun/06/2003: SunOS 5.8: /kernel/misc/gld and /kernel/misc/sparcv9/gld patch"}, -{109223,4,1,28,0,0,"Dec/23/2003: SunOS 5.8: kpasswd, libgss.so.1 and libkadm5clnt.so.1 patch"}, -{109234,9,1,28,0,0,"Aug/07/2002: SunOS 5.8: Apache Security and NCA Patch"}, -{109238,2,1,28,0,0,"Sep/17/2001: SunOS 5.8: /usr/bin/sparcv7/ipcs and /usr/bin/sparcv9/ipcs patch"}, -{109277,3,1,28,0,0,"Oct/25/2002: SunOS 5.8: /usr/bin/iostat patch"}, -{109318,34,1,28,0,0,"Nov/14/2003: SunOS 5.8: suninstall Patch"}, -{109320,8,1,28,0,0,"Nov/26/2003: SunOS 5.8: LP Patch"}, -{109324,5,1,28,0,0,"Dec/05/2002: SunOS 5.8: sh/jsh/rsh/pfsh patch"}, -{109326,13,1,28,0,0,"Jan/29/2004: SunOS 5.8: libresolv.so.2 and in.named patch"}, -{109328,3,1,28,0,0,"Oct/29/2002: SunOS 5.8: ypserv, ypxfr and ypxfrd patch"}, -{109354,19,1,28,0,0,"Apr/15/2003: CDE 1.4: dtsession patch"}, -{109458,3,1,28,0,0,"Jan/07/2003: SunOS 5.8: /kernel/strmod/ldterm patch"}, -{109460,10,1,28,0,0,"Aug/04/2003: SunOS 5.8: socal and sf drivers patch"}, -{109470,2,1,28,0,0,"Aug/29/00: CDE 1.4: Actions Patch"}, -{109657,9,1,28,0,0,"Jan/07/2003: SunOS 5.8: isp driver patch"}, -{109667,5,1,28,0,0,"Jun/16/2003: SunOS 5.8: /usr/lib/inet/xntpd and /usr/sbin/ntpdate patch"}, -{109695,3,1,28,0,0,"Jul/23/2001: SunOS 5.8: /etc/smartcard/opencard.properties patch"}, -{109778,14,1,28,0,0,"Jan/26/2004: SunOS 5.8: Misc loc have errors in CTYPE and lv colln monetary"}, -{109783,2,1,28,0,0,"Oct/02/2002: SunOS 5.8: /usr/lib/nfs/nfsd and /usr/lib/nfs/lockd patch"}, -{109793,23,1,28,0,0,"Oct/13/2003: SunOS 5.8: su driver patch"}, -{109805,17,1,28,0,0,"Sep/29/2003: SunOS 5.8: /usr/lib/security/pam_krb5.so.1 patch"}, -{109815,20,1,28,0,0,"Jan/07/2004: SunOS 5.8: se, acebus, pcf8574, pcf8591 and scsb patch"}, -{109862,3,1,28,0,0,"Dec/18/2002: X11 6.4.1 Font Server patch"}, -{109873,22,1,28,0,0,"Dec/04/2003: SunOS 5.8: prtdiag and platform libprtdiag_psr.so.1 patch"}, -{109882,6,1,28,0,0,"Jun/05/2002: SunOS 5.8: eri header files patch"}, -{109883,2,1,28,0,0,"Dec/20/2000: SunOS 5.8: /usr/include/sys/ecppsys.h patch"}, -{109885,14,1,28,0,0,"Oct/01/2003: SunOS 5.8: glm patch"}, -{109887,18,1,28,0,0,"Nov/17/2003: SunOS 5.8: smartcard and usr/sbin/ocfserv patch"}, -{109888,26,1,28,0,0,"Nov/26/2003: SunOS 5.8: platform drivers patch"}, -{109893,4,1,28,0,0,"Dec/24/2002: SunOS 5.8: stc driver patch"}, -{109894,1,1,28,0,0,"Nov/15/2000: SunOS 5.8: /kernel/drv/sparcv9/bpp driver patch"}, -{109896,24,1,28,0,0,"Feb/02/2004: SunOS 5.8: USB and Audio Framework patch"}, -{109898,5,1,28,0,0,"Oct/22/2001: SunOS 5.8: /kernel/drv/arp patch"}, -{109922,4,1,28,0,0,"Jan/22/2003: SunOS 5.8: pcelx and pcser driver patch"}, -{109928,5,1,28,0,0,"Jun/27/2002: SunOS 5.8: pcmem and pcmcia patch"}, -{110068,4,1,28,0,0,"Nov/05/2003: CDE 1.4: PDASync patch"}, -{110075,1,1,28,0,0,"Mar/13/2001: SunOS 5.8: /kernel/drv/devinfo and /kernel/drv/sparcv9/devinfo patch"}, -{110283,6,1,28,0,0,"Nov/26/2002: SunOS 5.8: mkfs and newfs patch"}, -{110286,11,1,28,0,0,"Sep/24/2003: OpenWindows 3.6.2: Tooltalk patch"}, -{110322,2,1,28,0,0,"Aug/19/2002: SunOS 5.8: /usr/lib/netsvc/yp/ypbind patch"}, -{110335,3,1,28,0,0,"Dec/03/2003: CDE 1.4: dtprintinfo patch"}, -{110380,4,1,28,0,0,"Dec/21/2001: SunOS 5.8: ufssnapshots support, libadm patch"}, -{110386,3,1,28,0,0,"Apr/08/2003: SunOS 5.8: RBAC Feature Patch"}, -{110387,5,1,28,0,0,"Aug/19/2003: SunOS 5.8: ufssnapshots support, ufsdump patch"}, -{110389,5,1,28,0,0,"Jan/22/2003: SunOS 5.8: cvc CPU signature"}, -{110453,4,1,28,0,0,"Feb/21/2003: SunOS 5.8: admintool Patch"}, -{110458,2,1,28,0,0,"May/29/2001: SunOS 5.8: libcurses patch"}, -{110460,32,1,28,0,0,"Nov/17/2003: SunOS 5.8: fruid/PICL plug-ins patch"}, -{110461,3,1,28,0,0,"Feb/27/2003: SunOS 5.8: ttcompat patch"}, -{110609,4,1,28,0,0,"Apr/18/2003: SunOS 5.8: cdio.h and command.h USB header patch"}, -/* {110615,4,1,28,0,0,"Jan/23/2002: SunOS 5.8: sendmail patch"}, */ -{110662,12,1,28,0,0,"Apr/24/2003: SunOS 5.8: ksh patch"}, -{110668,4,1,28,0,0,"Apr/08/2003: SunOS 5.8: /usr/sbin/in.telnetd patch"}, -/* rcp to non-solaris {110670,1,1,28,0,0,"Mar/30/2001: SunOS 5.8: usr/sbin/static/rcp patch"}, */ -{110700,1,1,28,0,0,"Jan/08/2001: SunOS 5.8: automount patch"}, -{110820,10,1,28,0,0,"Dec/19/2002: SunOS 5.8: /platform/SUNW,Sun-Fire-15000/kernel/drv/sparcv9/dman patch"}, -{110838,6,1,28,0,0,"Dec/16/2002: SunOS 5.8: /platform/SUNW,Sun-Fire-15000/kernel/drv/sparcv9/axq patch"}, -{110842,11,1,28,0,0,"May/08/2003: SunOS 5.8: hpc3130 driver patch for SUNW,Sun-Fire-880"}, -{110896,2,1,28,0,0,"Jan/03/2003: SunOS 5.8: cachefs/mount patch"}, -{110898,9,1,28,0,0,"Jan/26/2004: SunOS 5.8: csh/pfcsh patch"}, -{110901,1,1,28,0,0,"Mar/02/2001: SunOS 5.8: /kernel/drv/sgen and /kernel/drv/sparcv9/sgen patch"}, -{110903,7,1,28,0,0,"Nov/25/2003: SunOS 5.8: edit, ex, vedit, vi and view patch"}, -{110916,5,1,28,0,0,"Dec/15/2003: SunOS 5.8: sort patch"}, -{110934,14,1,28,0,0,"Aug/05/2003: SunOS 5.8: pkgtrans, pkgadd, pkgchk, pkgmk and libpkg.a patch"}, -/* wtmp {110939,1,1,28,0,0,"Mar/06/2001: SunOS 5.8: /usr/lib/acct/closewtmp patch"}, */ -{110943,2,1,28,0,0,"Nov/14/2003: SunOS 5.8: /usr/bin/tcsh patch"}, -{110945,8,1,28,0,0,"May/29/2003: SunOS 5.8: /usr/sbin/syslogd patch"}, -{110951,5,1,28,0,0,"Nov/14/2003: SunOS 5.8: /usr/sbin/tar and /usr/sbin/static/tar patch"}, -{110953,6,1,28,0,0,"Dec/09/2003: SunOS 5.8: /usr/kernel/drv/llc2 patch"}, -{110955,4,1,28,0,0,"Dec/24/2002: SunOS 5.8: /kernel/strmod/timod patch"}, -{110957,2,1,28,0,0,"Nov/06/2001: SunOS 5.8: /usr/bin/mailx patch"}, -{111023,3,1,28,0,0,"Dec/09/2003: SunOS 5.8: /kernel/fs/mntfs and /kernel/fs/sparcv9/mntfs patch"}, -{111069,1,1,28,0,0,"Aug/02/2001: SunOS 5.8: bsmunconv overwrites root cron tab if cu created /tmp/root"}, -/* uucp {111071,1,1,28,0,0,"Mar/30/2001: SunOS 5.8: cu patch"}, */ -{111085,2,1,28,0,0,"Dec/13/2001: SunOS 5.8: /usr/bin/login patch"}, -{111098,1,1,28,0,0,"Jul/17/2001: SunOS 5.8: ROC timezone should be avoided for political reasons"}, -{111111,3,1,28,0,0,"Mar/28/2002: SunOS 5.8: /usr/bin/nawk patch"}, -{111232,1,1,28,0,0,"Apr/25/2001: SunOS 5.8: patch in.fingerd"}, -{111234,1,1,28,0,0,"Apr/25/2001: SunOS 5.8: patch finger"}, -{111293,4,1,28,0,0,"Sep/25/2001: SunOS 5.8: /usr/lib/libdevinfo.so.1 patch"}, -{111302,2,1,28,0,0,"Sep/11/2002: SunOS 5.8: EDHCP libraries patch"}, -{111310,1,1,28,0,0,"Aug/21/2001: SunOS 5.8: /usr/lib/libdhcpagent.so.1 patch"}, -{111317,5,1,28,0,0,"Dec/10/2003: SunOS 5.8: /sbin/init and /usr/sbin/init patch"}, -{111321,3,1,28,0,0,"Oct/02/2002: SunOS 5.8: klmmod and klmops patch"}, -{111325,2,1,28,0,0,"Jun/14/2002: SunOS 5.8: /usr/lib/saf/ttymon patch"}, -{111327,5,1,28,0,0,"Dec/04/2001: SunOS 5.8: libsocket patch"}, -{111400,2,1,28,0,0,"Jan/28/2004: SunOS 5.8: KCMS configure tool has a security vulnerability"}, -{111504,1,1,28,0,0,"Jun/15/2001: SunOS 5.8: /usr/bin/tip patch"}, -{111548,1,1,28,0,0,"Jun/15/2001: SunOS 5.8: catman, man, whatis, apropos and makewhatis patch"}, -/* uucp {111570,2,1,28,0,0,"Sep/11/2002: SunOS 5.8: uucp patch"}, */ -{111588,4,1,28,0,0,"Dec/24/2002: SunOS 5.8: /kernel/drv/ws and /kernel/fs/specfs patch"}, -/* {111596,3,1,28,0,0,"Feb/28/2003: SunOS 5.8: /usr/lib/netsvc/yp/rpc.yppasswdd patch"}, */ -{111606,4,1,28,0,0,"Jul/30/2003: SunOS 5.8: /usr/sbin/in.ftpd patch"}, -{111624,4,1,28,0,0,"Oct/02/2002: SunOS 5.8: /usr/sbin/inetd patch"}, -{111626,3,1,28,0,0,"Nov/11/2002: OpenWindows 3.6.2: Xview Patch"}, -{111659,6,1,28,0,0,"Mar/04/2002: SunOS 5.8: passwd and pam_unix.so.1 patch"}, -{111826,1,1,28,0,0,"Aug/15/2001: SunOS 5.8: /usr/sbin/sparcv7/whodo & /usr/sbin/sparcv9/whodo patch"}, -{111874,6,1,28,0,0,"Jan/23/2003: SunOS 5.8: usr/bin/mail patch"}, -/* old progreg and Live Upgrade problem {111879,1,1,28,0,0,"Aug/27/2001: SunOS 5.8: Solaris Product Registry patch SUNWwsr"}, */ -{111881,3,1,28,0,0,"Dec/24/2002: SunOS 5.8: /usr/kernel/strmod/telmod patch"}, -{111958,2,1,28,0,0,"May/13/2002: SunOS 5.8: /usr/lib/nfs/statd patch"}, -{112039,1,1,28,0,0,"Sep/17/2001: SunOS 5.8: usr/bin/ckitem patch"}, -{112138,1,1,28,0,0,"Nov/05/2001: SunOS 5.8:: usr/bin/domainname patch"}, -{112161,3,1,28,0,0,"Dec/04/2003: SunOS 5.8: remove libprtdiag_psr.so.1 of SUNW,Netra-T12 SUNW,Netra-T4"}, -{112218,1,1,28,0,0,"Nov/13/2001: SunOS 5.8:: pam_ldap.so.1 patch"}, -{112237,9,1,28,0,0,"Nov/05/2003: SunOS 5.8: mech_krb5.so.1 patch"}, -{112254,1,1,28,0,0,"Feb/27/2002: SunOS 5.8: /kernel/sched/TS patch"}, -{112325,1,1,28,0,0,"Jan/22/2002: SunOS 5.8: /kernel/fs/udfs and /kernel/fs/sparcv9/udfs patch"}, -{112396,2,1,28,0,0,"Mar/28/2002: SunOS 5.8: /usr/bin/fgrep patch"}, -{112425,1,1,28,0,0,"Feb/19/2002: SunOS 5.8: /usr/lib/fs/ufs/mount and /etc/fs/ufs/mount patch"}, -{112459,1,1,28,0,0,"Mar/07/2002: SunOS 5.8: /usr/lib/pt_chmod patch"}, -{112609,2,1,28,0,0,"May/29/2003: SunOS 5.8: /kernel/drv/le and /kernel/drv/sparcv9/le patch"}, -{112611,2,1,28,0,0,"Oct/21/2003: SunOS 5.8: /usr/lib/libz.so.1 patch"}, -{112668,1,1,28,0,0,"May/14/2002: SunOS 5.8: /usr/bin/gzip patch"}, -/* {112792,1,1,28,0,0,"Jul/09/2002: SunOS 5.8: /usr/lib/pcmciad patch"}, */ -{112796,1,1,28,0,0,"May/27/2002: SunOS 5.8: /usr/sbin/in.talkd patch"}, -{112846,1,1,28,0,0,"Jun/17/2002: SunOS 5.8: /usr/lib/netsvc/rwall/rpc.rwalld patch"}, -{113648,3,1,28,0,0,"Dec/10/2003: SunOS 5.8: /usr/sbin/mount patch"}, -{113650,2,1,28,0,0,"May/28/2003: SunOS 5.8: /usr/lib/utmp_update patch"}, -{113685,5,1,28,0,0,"Oct/06/2003: SunOS 5.8: logindmux/ptsl/ms/bufmod/llc1/kb/zs/zsh/ptem patch"}, -{113687,1,1,28,0,0,"Dec/24/2002: SunOS 5.8: /kernel/misc/kbtrans patch"}, -{113792,1,1,28,0,0,"Nov/25/2002: OpenWindows 3.6.2: mailtool patch"}, -{114162,1,1,28,0,0,"Apr/07/2003: SunOS 5.8: /kernel/drv/lofi drivers and /usr/sbin/lofiadm patch"}, -{114673,1,1,28,0,0,"Apr/16/2003: SunOS 5.8: /usr/sbin/wall patch"}, -{114802,2,1,28,0,0,"Jan/08/2004: SunOS 5.8: Patch for assembler"}, -{114984,1,1,28,0,0,"Apr/29/2003: SunOS 5.8: /usr/kernel/fs/namefs patch"}, -{115576,1,1,28,0,0,"Jul/28/2003: SunOS 5.8: /kernel/exec/elfexec and /kernel/exec/sparcv9/elfexec patch"}, -{115797,1,1,28,0,0,"Aug/15/2003: CDE 1.4: dtspcd Patch"}, -{115827,1,1,28,0,0,"Oct/27/2003: SunOS 5.8: /sbin/sulogin and /sbin/netstrategy patch"}, -{116602,1,1,28,0,0,"Dec/10/2003: SunOS 5.8: /sbin/uadmin and /sbin/hostconfig patch"}, -/* This list was generated by /u/norikoyasuo/bin/getSolPatches.pl */ -/* on tmolus.mcom.com */ -/* at Thu Mar 18 10:34:35 2004 GMT */ +/* This list was generated by /tmp/getSolPatches.pl */ +/* on brandywalk.redhat.com */ +/* at Thu Aug 9 03:21:12 2007 GMT */ /* Here is the information from /etc/release: Solaris 9 s9_58shwpl3 SPARC Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. @@ -222,93 +9,175 @@ The following is a list of patches installed on the system */ /* a patch that is commented out is either a duplicate or */ /* a patch that is superseded by another patch */ -{112233,11,1,29,0,0,"Dec/23/2003: SunOS 5.9: Kernel Patch"}, -{112540,18,1,29,0,0,"Sep/02/2003: SunOS 5.9: Expert3D IFB Graphics Patch"}, -{112601,9,1,29,0,0,"Oct/28/2003: SunOS 5.9: PGX32 Graphics"}, +{111711,16,1,29,0,0,"Aug/07/2006: SunOS 5.9: 32-bit Shared library patch for C++"}, +{111712,16,1,29,0,0,"Aug/17/2006: SunOS 5.9: 64-Bit Shared library patch for C++"}, +{112233,12,1,29,0,0,"Apr/21/2004: SunOS 5.9: Kernel Patch"}, +{112540,26,1,29,0,0,"Nov/11/2005: SunOS 5.9: Expert3D IFB Graphics Patch"}, +{112601,10,1,29,0,0,"Feb/15/2006: SunOS 5.9: PGX32 Graphics"}, {112617,2,1,29,0,0,"Jan/15/2003: CDE 1.5: rpc.cmsd patch"}, -{112661,6,1,29,0,0,"Oct/03/2003: SunOS 5.9: IIIM and X Input & Output Method patch"}, -{112764,6,1,29,0,0,"Apr/16/2003: SunOS 5.9: Sun Quad FastEthernet qfe driver"}, -{112785,30,1,29,0,0,"Dec/19/2003: X11 6.6.1: Xsun patch"}, -{112807,7,1,29,0,0,"Sep/25/2003: CDE 1.5: dtlogin patch"}, -{112808,6,1,29,0,0,"Dec/01/2003: CDE1.5: Tooltalk patch"}, -{112817,16,1,29,0,0,"Jan/05/2004: SunOS 5.9: Sun GigaSwift Ethernet 1.0 driver patch"}, -{112834,3,1,29,0,0,"Sep/01/2003: SunOS 5.9: patch scsi"}, -{112874,22,1,29,0,0,"Jan/30/2004: SunOS 5.9: lgroup API libc Patch"}, +{112661,11,1,29,0,0,"Nov/06/2006: SunOS 5.9: IIIM and X Input & Output Method patch"}, +{112764,9,1,29,0,0,"Apr/14/2006: SunOS 5.9: Sun Quad FastEthernet qfe driver"}, +{112785,61,1,29,0,0,"May/03/2007: X11 6.6.1: Xsun patch"}, +{112807,20,1,29,0,0,"May/30/2007: CDE 1.5: dtlogin patch"}, +{112808,10,1,29,0,0,"Feb/21/2007: CDE1.5: Tooltalk patch"}, +{112810,6,1,29,0,0,"Jun/29/2004: CDE 1.5: dtmail patch"}, +{112811,2,1,29,0,0,"Aug/02/2005: OpenWindows 3.7.0: Xview Patch"}, +{112817,29,1,29,0,0,"Jun/26/2006: SunOS 5.9: Sun GigaSwift Ethernet 1.0 driver patch"}, +{112834,6,1,29,0,0,"Mar/02/2005: SunOS 5.9: patch scsi"}, +{112874,38,1,29,0,0,"May/18/2007: SunOS 5.9: libc patch"}, {112875,1,1,29,0,0,"Jun/21/2002: SunOS 5.9: patch /usr/lib/netsvc/rwall/rpc.rwalld"}, -{112902,8,1,29,0,0,"Dec/06/2002: SunOS 5.9: kernel/drv/ip Patch"}, -{112907,2,1,29,0,0,"Oct/13/2003: SunOS 5.9: libgss Patch"}, -{112908,11,1,29,0,0,"Nov/06/2003: SunOS 5.9: krb5 shared object Patch"}, -{112921,3,1,29,0,0,"Jan/20/2004: SunOS 5.9: libkadm5 Patch"}, +{112906,3,1,29,0,0,"Apr/23/2004: SunOS 5.9: ipgpc Patch"}, +{112907,3,1,29,0,0,"Jun/09/2004: SunOS 5.9: libgss Patch"}, +{112908,30,1,29,0,0,"May/30/2007: SunOS 5.9: krb5, gss patch"}, +{112911,7,1,29,0,0,"Jul/01/2004: SunOS 5.9: ifconfig Patch"}, +{112912,1,1,29,0,0,"Sep/13/2002: SunOS 5.9: libinetcfg Patch"}, +{112921,8,1,29,0,0,"May/30/2007: SunOS 5.9: libkadm5 Patch"}, {112922,2,1,29,0,0,"Apr/24/2003: SunOS 5.9: krb5 lib Patch"}, {112923,3,1,29,0,0,"Nov/06/2003: SunOS 5.9: krb5 usr/lib Patch"}, -{112925,3,1,29,0,0,"Nov/06/2003: SunOS 5.9: ktutil kdb5_util kadmin kadmin.local kadmind Patch"}, -{112926,5,1,29,0,0,"Nov/17/2003: SunOS 5.9: smartcard Patch"}, -{112945,21,1,29,0,0,"Jan/28/2004: SunOS 5.9: wbem Patch"}, -{112951,4,1,29,0,0,"Dec/12/2002: SunOS 5.9: patchadd and patchrm Patch"}, -{112960,10,1,29,0,0,"Dec/23/2003: SunOS 5.9: patch libsldap ldap_cachemgr libldap"}, -{112963,10,1,29,0,0,"Oct/14/2003: SunOS 5.9: linker patch"}, -{112964,4,1,29,0,0,"Apr/23/2003: SunOS 5.9: /usr/bin/ksh Patch"}, -{112965,2,1,29,0,0,"Aug/01/2003: SunOS 5.9: patch /kernel/drv/sparcv9/eri"}, -{112970,6,1,29,0,0,"Jan/13/2004: SunOS 5.9: patch libresolv"}, +{112925,6,1,29,0,0,"May/11/2005: SunOS 5.9: ktutil kdb5_util kadmin kadmin.local kadmind Patch"}, +{112926,6,1,29,0,0,"Feb/16/2005: SunOS 5.9: smartcard Patch"}, +{112945,45,1,29,0,0,"May/24/2007: SunOS 5.9: wbem Patch"}, +{112951,13,1,29,0,0,"Apr/26/2006: SunOS 5.9: patchadd and patchrm Patch"}, +{112954,15,1,29,0,0,"Nov/08/2006: SunOS 5.9: uata Driver Patch"}, +{112960,51,1,29,0,0,"May/25/2007: SunOS 5.9: ldap library Patch"}, +{112963,30,1,29,0,0,"Jan/09/2007: SunOS 5.9: linker Patch"}, +{112964,16,1,29,0,0,"Nov/09/2006: SunOS 5.9: ksh patch"}, +{112965,6,1,29,0,0,"Nov/03/2006: SunOS 5.9: eri driver patch"}, +{112970,12,1,29,0,0,"Jun/05/2007: SunOS 5.9: libresolv patch"}, {112975,3,1,29,0,0,"Oct/24/2003: SunOS 5.9: patch /kernel/sys/kaio"}, -{112998,3,1,29,0,0,"May/29/2003: SunOS 5.9: patch /usr/sbin/syslogd"}, +{112998,4,1,29,0,0,"Oct/04/2006: SunOS 5.9: /usr/sbin/syslogd patch"}, {113026,14,1,29,0,0,"Jan/16/2004: SunOS 5.9: /kernel/drv/md Patch"}, {113030,2,1,29,0,0,"Dec/18/2002: SunOS 5.9: /kernel/sys/doorfs Patch"}, -{113033,3,1,29,0,0,"Dec/24/2002: SunOS 5.9: patch /kernel/drv/isp and /kernel/drv/sparcv9/isp"}, -{113068,4,1,29,0,0,"May/16/2003: SunOS 5.9: hpc3130 patch"}, -{113073,5,1,29,0,0,"Sep/25/2003: SunOS 5.9: ufs_log patch"}, -{113077,9,1,29,0,0,"Sep/24/2003: SunOS 5.9: /platform/sun4u/kernal/drv/su Patch"}, +{113033,5,1,29,0,0,"Feb/18/2005: SunOS 5.9: patch /kernel/drv/isp and /kernel/drv/sparcv9/isp"}, +{113068,6,1,29,0,0,"Oct/13/2004: SunOS 5.9: hpc3130 patch"}, +{113072,8,1,29,0,0,"Jul/21/2006: SunOS 5.9: patch /usr/sbin/format"}, +{113073,14,1,29,0,0,"Aug/23/2004: SunOS 5.9: ufs and fsck patch"}, +{113077,22,1,29,0,0,"Jun/01/2007: SunOS 5.9: su driver patch"}, {113096,3,1,29,0,0,"May/01/2003: X11 6.6.1: OWconfig patch"}, -{113146,2,1,29,0,0,"May/01/2003: SunOS 5.9: Apache Security Patch"}, -{113240,5,1,29,0,0,"Jul/08/2003: CDE 1.5: dtsession patch"}, -{113273,4,1,29,0,0,"Oct/08/2003: SunOS 5.9: /usr/lib/ssh/sshd Patch"}, -{113277,17,1,29,0,0,"Oct/24/2003: SunOS 5.9: sd and ssd Patch"}, -{113278,4,1,29,0,0,"Feb/02/2004: SunOS 5.9: NFS Daemon , rpcmod Patch"}, +{113146,8,1,29,0,0,"Nov/30/2006: SunOS 5.9: Apache Security Patch"}, +{113225,8,1,29,0,0,"Feb/16/2007: SunOS 5.9: Timezone commands and zoneinfo database update Patch"}, +{113226,5,1,29,0,0,"Apr/13/2004: SunOS 5.9: hme Driver Patch"}, +{113240,12,1,29,0,0,"Feb/22/2007: CDE 1.5: dtsession patch"}, +{113273,13,1,29,0,0,"Dec/22/2006: SunOS 5.9: /usr/lib/ssh/sshd Patch"}, +{113277,52,1,29,0,0,"Apr/20/2007: SunOS 5.9: st, sd and ssd drivers patch"}, +{113278,16,1,29,0,0,"Jan/16/2007: SunOS 5.9: NFS Daemon, rpcmod Patch"}, {113279,1,1,29,0,0,"Sep/17/2002: SunOS 5.9: klmmod Patch"}, -{113319,17,1,29,0,0,"Dec/15/2003: SunOS 5.9: libnsl nispasswdd patch"}, -{113329,5,1,29,0,0,"Jan/20/2004: SunOS 5.9: lp Patch"}, -{113333,2,1,29,0,0,"Nov/18/2002: SunOS 5.9: libmeta Patch"}, -{113451,6,1,29,0,0,"Jan/22/2004: SunOS 5.9: IKE Patch"}, +{113280,6,1,29,0,0,"Sep/01/2004: SunOS 5.9: patch /usr/bin/cpio"}, +{113318,30,1,29,0,0,"May/23/2007: SunOS 5.9: NFS patch"}, +{113319,24,1,29,0,0,"Jun/28/2006: SunOS 5.9: libnsl, nispasswdd patch"}, +{113322,3,1,29,0,0,"Jan/06/2006: SunOS 5.9: uucp patch"}, +{113329,18,1,29,0,0,"Nov/13/2006: SunOS 5.9: lp Patch"}, +{113335,4,1,29,0,0,"Nov/13/2006: SunOS 5.9: devinfo Patch"}, +{113447,21,1,29,0,0,"Jul/19/2004: SunOS 5.9: libprtdiag_psr Patch"}, +{113451,13,1,29,0,0,"May/23/2007: SunOS 5.9: IKE patch"}, {113454,14,1,29,0,0,"Nov/18/2003: SunOS 5.9: ufs Patch"}, {113464,6,1,29,0,0,"Sep/29/2003: SunOS 5.9: IPMP Headers Patch"}, +{113475,3,1,29,0,0,"May/13/2004: SunOS 5.9: usr/lib/security crypt Patch"}, +{113482,2,1,29,0,0,"Feb/13/2004: SunOS 5.9: sbin/sulogin Patch"}, {113492,4,1,29,0,0,"Dec/24/2003: SunOS 5.9: fsck Patch"}, {113573,3,1,29,0,0,"Aug/12/2003: SunOS 5.9: libpsvc Patch"}, {113574,3,1,29,0,0,"May/23/2003: SunOS 5.9: SUNW,Sun-Fire-880 libpsvc Patch"}, -{113579,1,1,29,0,0,"Nov/08/2002: SunOS 5.9: ypserv/ypxfrd Patch"}, -{113713,11,1,29,0,0,"Nov/04/2003: SunOS 5.9: pkginstall Patch"}, +{113579,12,1,29,0,0,"Feb/20/2007: SunOS 5.9: ypserv/ypxfrd patch"}, +{113713,23,1,29,0,0,"Dec/01/2006: SunOS 5.9: pkg utilities Patch"}, {113718,2,1,29,0,0,"Jun/04/2003: SunOS 5.9: usr/lib/utmp_update Patch"}, +{113798,2,1,29,0,0,"Jan/06/2005: CDE 1.5: libDtSvc patch"}, {113859,3,1,29,0,0,"Dec/24/2003: SunOS 5.9: Sun ONE Directory Server 5.1 patch"}, -{113923,2,1,29,0,0,"Dec/18/2002: X11 6.6.1: security font server patch"}, +{113923,3,1,29,0,0,"Mar/07/2007: X11 6.6.1: security font server patch"}, {113993,6,1,29,0,0,"Sep/15/2003: SunOS 5.9: mkfs Patch"}, {114008,1,1,29,0,0,"Mar/19/2003: SunOS 5.9: cachefsd Patch"}, -{114014,3,1,29,0,0,"Apr/01/2003: SunOS 5.9: libxml, libxslt and Freeware man pages Patch"}, +{114014,15,1,29,0,0,"Apr/23/2007: SunOS 5.9: libxml, libxslt and Freeware man pages Patch"}, {114016,1,1,29,0,0,"May/01/2003: tomcat security patch"}, {114125,1,1,29,0,0,"Aug/13/2003: SunOS 5.9: IKE config.sample patch"}, -{114127,2,1,29,0,0,"Dec/24/2003: SunOS 5.9: abi_libefi.so.1 Patch"}, -{114129,1,1,29,0,0,"Mar/31/2003: SunOS 5.9: multi-terabyte disk support -libuuid patch"}, -{114133,1,1,29,0,0,"Feb/03/2003: SunOS 5.9: mail Patch"}, -{114135,1,1,29,0,0,"Jan/22/2003: SunOS 5.9: at utility Patch"}, -{114332,7,1,29,0,0,"Oct/01/2003: SunOS 5.9: c2audit & *libbsm.so.1 Patch"}, +{114126,2,1,29,0,0,"Aug/27/2003: SunOS 5.9: todds1287 patch"}, +{114127,3,1,29,0,0,"Apr/15/2004: SunOS 5.9: abi_libefi.so.1 and fmthard Patch"}, +{114128,3,1,29,0,0,"Aug/29/2006: SunOS 5.9: sd_lun patch"}, +{114129,2,1,29,0,0,"Apr/15/2004: SunOS 5.9: multi-terabyte disk support -libuuid patch"}, +{114131,3,1,29,0,0,"Jun/02/2005: SunOS 5.9: multi-terabyte disk support - libadm.so.1 patch"}, +{114133,3,1,29,0,0,"Nov/06/2006: SunOS 5.9: mail Patch"}, +{114135,3,1,29,0,0,"Nov/12/2004: SunOS 5.9: at utility Patch"}, +{114153,1,1,29,0,0,"Dec/10/2002: SunOS 5.9: Japanese SunOS 4.x Binary Compatibility(BCP) patch"}, +{114219,11,1,29,0,0,"Apr/14/2005: CDE 1.5: sdtimage patch"}, +{114329,2,1,29,0,0,"Aug/21/2006: SunOS 5.9: pax Patch"}, +{114332,23,1,29,0,0,"Sep/19/2005: SunOS 5.9: c2audit & *libbsm.so.1 Patch"}, +{114344,26,1,29,0,0,"May/31/2007: SunOS 5.9: arp, dlcosmk, ip, and ipgpc Patch"}, +{114356,10,1,29,0,0,"Jan/03/2007: SunOS 5.9: /usr/bin/ssh Patch"}, {114359,1,1,29,0,0,"Mar/03/2003: SunOS 5.9: mc-us3 Patch"}, {114361,1,1,29,0,0,"Apr/30/2003: SunOS 5.9: /kernel/drv/lofi Patch"}, -{114363,2,1,29,0,0,"Jan/27/2004: SunOS 5.9: sort Patch"}, +{114363,3,1,29,0,0,"Jun/02/2005: SunOS 5.9: sort Patch"}, {114375,6,1,29,0,0,"Jul/25/2003: SunOS 5.9: Enchilada/Stiletto - PICL & FRUID"}, {114385,3,1,29,0,0,"Aug/04/2003: SunOS 5.9: Enchilada/Stiletto - pmugpio pmubus driver"}, +{114388,5,1,29,0,0,"Jun/04/2004: SunOS 5.9: dmfe driver patch"}, {114482,4,1,29,0,0,"Sep/02/2003: SunOS 5.9: Product Registry CLI Revision"}, {114495,1,1,29,0,0,"Dec/03/2003: CDE 1.5: dtprintinfo patch"}, -{114564,3,1,29,0,0,"Nov/14/2003: SunOS 5.9: /usr/sbin/in.ftpd Patch"}, +{114503,14,1,29,0,0,"Aug/29/2005: SunOS 5.9: usr/sadm/lib/usermgr/VUserMgr.jar Patch"}, +{114564,12,1,29,0,0,"Mar/29/2007: SunOS 5.9: /usr/sbin/in.ftpd Patch"}, {114569,2,1,29,0,0,"Apr/24/2003: SunOS 5.9: libdbm.so.1 Patch"}, -{114571,1,1,29,0,0,"Apr/04/2003: SunOS 5.9: libc.so.*.9/bcp Patch"}, -{114636,2,1,29,0,0,"Aug/06/2003: SunOS 5.9: KCMS security fix"}, -{114684,2,1,29,0,0,"May/27/2003: SunOS 5.9: samba Patch"}, -{114713,1,1,29,0,0,"Mar/26/2003: SunOS 5.9: newtask Patch"}, -{114721,4,1,29,0,0,"Sep/15/2003: SunOS 5.9: ufsrestore and ufsdump Patch"}, +{114571,2,1,29,0,0,"Apr/28/2004: SunOS 5.9: libc.so.*.9/bcp Patch"}, +{114636,4,1,29,0,0,"Jan/17/2007: SunOS 5.9: kcms_server and kcms_configure patch"}, +{114684,7,1,29,0,0,"Oct/15/2006: SunOS 5.9: Samba Patch"}, +{114713,3,1,29,0,0,"Jan/04/2007: SunOS 5.9: newtask & libproject.so.1 patch"}, +{114721,5,1,29,0,0,"May/17/2004: SunOS 5.9: ufsrestore and ufsdump Patch"}, {114729,1,1,29,0,0,"May/29/2003: SunOS 5.9: usr/sbin/in.telnetd Patch"}, +{114731,9,1,29,0,0,"Jul/06/2006: SunOS 5.9: glm driver patch"}, {114861,1,1,29,0,0,"Apr/22/2003: SunOS 5.9: /usr/sbin/wall"}, {114864,2,1,29,0,0,"Jun/13/2003: SunOS 5.9: Sun-Fire-480R libpsvcpolicy_psr.so.1 Patch"}, -{114971,1,1,29,0,0,"Sep/04/2003: SunOS 5.9: usr/kernel/fs/namefs Patch"}, +{114971,2,1,29,0,0,"Feb/27/2004: SunOS 5.9: usr/kernel/fs/namefs Patch"}, +{115165,3,1,29,0,0,"Jan/15/2004: SunOS 5.9: usr/lib/libnisdb.so.2 Patch"}, {115172,1,1,29,0,0,"Sep/15/2003: SunOS 5.9: kernel/drv/le Patch"}, +{115553,26,1,29,0,0,"May/25/2007: SunOS 5.9: USB Drivers and Framework Patch"}, +{115665,8,1,29,0,0,"Jul/15/2004: SunOS 5.9: Chalupa platform support patch"}, +{115677,2,1,29,0,0,"Apr/07/2006: SunOS 5.9: usr/lib/ldap/idsconfig Patch"}, +{115683,3,1,29,0,0,"Aug/30/2004: SunOS 5.9: Header files Patch"}, {115689,1,1,29,0,0,"Jan/27/2004: SunOS 5.9: /usr/lib/patch/patchutil Patch"}, {115754,2,1,29,0,0,"Oct/21/2003: SunOS 5.9: zlib security Patch"}, +{116047,3,1,29,0,0,"Feb/22/2006: SunOS 5.9: hsfs Patch"}, {116237,1,1,29,0,0,"Nov/26/2003: SunOS 5.9: pfexec Patch"}, {116245,1,1,29,0,0,"Jan/27/2004: SunOS 5.9: uncompress Patch"}, +{116247,1,1,29,0,0,"Dec/09/2003: SunOS 5.9: audit_warn Patch"}, +{116308,1,1,29,0,0,"Feb/03/2004: CDE 1.5: libDtHelp patch"}, +{116340,7,1,29,0,0,"Mar/07/2007: SunOS 5.9: gzip and Freeware info files patch"}, +{116453,2,1,29,0,0,"Jul/16/2004: SunOS 5.9: sadmind patch"}, +{116489,1,1,29,0,0,"May/10/2004: SunOS 5.9: ttymux Patch"}, +{116494,1,1,29,0,0,"Apr/27/2004: SunOS 5.9: libdevice Patch"}, +{116502,3,1,29,0,0,"Dec/05/2005: SunOS 5.9: mountd Patch"}, +{116527,2,1,29,0,0,"Apr/20/2006: SunOS 5.9: timod Patch"}, +{116532,3,1,29,0,0,"Oct/22/2004: SunOS 5.9: mpt Patch"}, +{116538,3,1,29,0,0,"Feb/14/2005: SunOS 5.9: SUNW_disk_link.so Patch"}, +{116548,5,1,29,0,0,"Dec/06/2005: SunOS 5.9: ufsboot Patch"}, +{116559,1,1,29,0,0,"Jul/16/2004: SunOS 5.9: powerd pmconfig patch"}, +{116561,15,1,29,0,0,"Nov/09/2006: SunOS 5.9: Volume System H/W Series platmod patch"}, +{116669,27,1,29,0,0,"Jun/07/2007: SunOS 5.9: md Patch"}, +{116774,3,1,29,0,0,"Nov/12/2004: SunOS 5.9: ping patch"}, +{116807,2,1,29,0,0,"Sep/15/2005: SunOS 5.9: /usr/sadm/lib/smc/lib/preload/jsdk21.jar patch"}, +{117067,5,1,29,0,0,"Dec/25/2006: SunOS 5.9: awk nawk oawk Patch"}, +{117071,1,1,29,0,0,"Apr/26/2004: SunOS 5.9: memory leak in llc1_ioctl()"}, +{117114,2,1,29,0,0,"Aug/09/2004: CDE 1.5: sdtwebclient patch"}, +{117124,12,1,29,0,0,"Mar/03/2006: SunOS 5.9: platmod, drmach, dr, ngdr, & gptwocfg Patch"}, +{117162,1,1,29,0,0,"Aug/25/2004: SunOS 5.9: patch usr/src/uts/common/sys/cpc_impl.h"}, +{117171,17,1,29,0,0,"Jan/21/2005: SunOS 5.9: Kernel Patch"}, +{117418,1,1,29,0,0,"Jul/02/2004: SunOS 5.9: consms patch"}, +{117445,1,1,29,0,0,"Mar/10/2005: SunOS 5.9: newgrp patch"}, +{117455,1,1,29,0,0,"Nov/01/2004: SunOS 5.9: in.rwhod Patch"}, +{117459,1,1,29,0,0,"Feb/14/2005: SunOS 5.9: routing socket module Patch"}, +{117471,3,1,29,0,0,"Jul/28/2006: SunOS 5.9: fifofs Patch"}, +{117477,1,1,29,0,0,"Apr/25/2005: SunOS 5.9: vol Patch"}, +{117480,1,1,29,0,0,"Apr/25/2005: SunOS 5.9: pkgadd Patch"}, +{117485,1,1,29,0,0,"May/04/2005: SunOS 5.9: fn_ctx_x500.so.1 Patch"}, +{118300,2,1,29,0,0,"May/16/2005: X11 6.6.1: libXpm patch"}, +{118305,9,1,29,0,0,"Nov/15/2006: SunOS 5.9: tcp Patch"}, +{118335,7,1,29,0,0,"May/08/2007: SunOS 5.9: sockfs patch"}, +{118535,3,1,29,0,0,"Apr/07/2006: SunOS 5.9: sh/jsh/rsh/pfsh Patch"}, +{118558,39,1,29,0,0,"Jan/11/2007: SunOS 5.9: Kernel Patch"}, +{119433,1,1,29,0,0,"Mar/28/2005: SunOS 5.9: telnet"}, +{119449,1,1,29,0,0,"Jun/17/2005: SunOS 5.9: Perl Patch"}, +{120240,1,1,29,0,0,"Mar/24/2006: SunOS 5.9: ps cmd patch"}, +{121194,1,1,29,0,0,"Nov/22/2005: SunOS 5.9: usr/lib/nfs/statd Patch"}, +{121316,2,1,29,0,0,"Aug/10/2006: SunOS 5.9: kernel/sys/doorfs Patch"}, +{121321,3,1,29,0,0,"Aug/04/2006: SunOS 5.9: ldap Patch"}, +{121992,1,1,29,0,0,"Mar/16/2006: SunOS 5.9: fgrep Patch"}, +{121996,1,1,29,0,0,"Mar/08/2006: SunOS 5.9: S9 perl 5.005_03`s CGI.pm and Safe.pm modules Patch"}, +{122300,8,1,29,0,0,"Jun/08/2007: SunOS 5.9: Kernel Patch"}, +{123056,1,1,29,0,0,"May/25/2006: SunOS 5.9: ldterm patch"}, +{123368,1,1,29,0,0,"Jan/12/2007: SunOS 5.9: tip patch"}, +{123372,2,1,29,0,0,"Feb/06/2007: SunOS 5.9: rm patch"}, +{124830,1,1,29,0,0,"Jan/18/2007: X11 6.6.1: xdm patch"},
0
a5e0fef733f25eec779dbe48bfe6da90abb99cdf
389ds/389-ds-base
Issue 50937 - Update CLI for new backend split configuration Description: In preparation for the move to LMDB the global database configuration has been split into two (or more) entries under cn=config. This patch changes how the gets/sets work to make both of these entries appear as one configuration unit. This is done by dynamically setting the backend configuration entry dn with what is set in nsslapd-backend-implement. relates: https://pagure.io/389-ds-base/issue/50937 Reviewed by: spichugi, tbordaz, and firstyear(Thanks!!!) Make changes via Simon's suggestions Add firstyear's assert
commit a5e0fef733f25eec779dbe48bfe6da90abb99cdf Author: Mark Reynolds <[email protected]> Date: Mon Mar 9 10:04:22 2020 -0400 Issue 50937 - Update CLI for new backend split configuration Description: In preparation for the move to LMDB the global database configuration has been split into two (or more) entries under cn=config. This patch changes how the gets/sets work to make both of these entries appear as one configuration unit. This is done by dynamically setting the backend configuration entry dn with what is set in nsslapd-backend-implement. relates: https://pagure.io/389-ds-base/issue/50937 Reviewed by: spichugi, tbordaz, and firstyear(Thanks!!!) Make changes via Simon's suggestions Add firstyear's assert diff --git a/src/lib389/lib389/_mapped_object.py b/src/lib389/lib389/_mapped_object.py index 5b4a2b324..ce0ebfeb8 100644 --- a/src/lib389/lib389/_mapped_object.py +++ b/src/lib389/lib389/_mapped_object.py @@ -7,7 +7,6 @@ # See LICENSE for details. # --- END COPYRIGHT BLOCK --- -import os import ldap import ldap.dn from ldap import filter as ldap_filter @@ -15,7 +14,7 @@ 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._constants import DIRSRV_STATE_ONLINE from lib389.utils import ( ensure_bytes, ensure_str, ensure_int, ensure_list_bytes, ensure_list_str, ensure_list_int, display_log_value, display_log_data @@ -245,7 +244,7 @@ class DSLdapObject(DSLogging): raise ValueError("Invalid state. Cannot get presence on instance that is not ONLINE") self._log.debug("%s present(%r) %s" % (self._dn, attr, value)) - e = self._instance.search_ext_s(self._dn, ldap.SCOPE_BASE, self._object_filter, attrlist=[attr, ], + self._instance.search_ext_s(self._dn, ldap.SCOPE_BASE, self._object_filter, attrlist=[attr, ], serverctrls=self._server_controls, clientctrls=self._client_controls, escapehatch='i am sure')[0] values = self.get_attr_vals_bytes(attr) @@ -589,6 +588,26 @@ class DSLdapObject(DSLogging): # This could have unforseen consequences ... return attrs_dict + def get_all_attrs_utf8(self, use_json=False): + """Get a dictionary having all the attributes of the entry + + :returns: Dict with real attributes and operational attributes + """ + + self._log.debug("%s get_all_attrs" % (self._dn)) + if self._instance.state != DIRSRV_STATE_ONLINE: + raise ValueError("Invalid state. Cannot get properties on instance that is not ONLINE") + else: + # retrieving real(*) and operational attributes(+) + attrs_entry = self._instance.search_ext_s(self._dn, ldap.SCOPE_BASE, self._object_filter, + attrlist=["*", "+"], serverctrls=self._server_controls, + clientctrls=self._client_controls, escapehatch='i am sure')[0] + # getting dict from 'entry' object + r = {} + for (k, vo) in attrs_entry.data.items(): + r[k] = ensure_list_str(vo) + return r + def get_attrs_vals(self, keys, use_json=False): self._log.debug("%s get_attrs_vals(%r)" % (self._dn, keys)) if self._instance.state != DIRSRV_STATE_ONLINE: diff --git a/src/lib389/lib389/backend.py b/src/lib389/lib389/backend.py index 81706dc88..f13586ea9 100644 --- a/src/lib389/lib389/backend.py +++ b/src/lib389/lib389/backend.py @@ -11,7 +11,7 @@ import copy import ldap from lib389._constants import * from lib389.properties import * -from lib389.utils import normalizeDN, ensure_str, ensure_bytes +from lib389.utils import normalizeDN, ensure_str, ensure_bytes, assert_c from lib389 import Entry # Need to fix this .... @@ -26,7 +26,7 @@ from lib389.cos import (CosTemplates, CosIndirectDefinitions, # We need to be a factor to the backend monitor from lib389.monitor import MonitorBackend from lib389.index import Index, Indexes, VLVSearches, VLVSearch -from lib389.tasks import ImportTask, ExportTask, CleanAllRUVTask, Tasks +from lib389.tasks import ImportTask, ExportTask, Tasks from lib389.encrypted_attributes import EncryptedAttr, EncryptedAttrs @@ -341,11 +341,11 @@ class BackendLegacy(object): def getProperties(self, suffix=None, backend_dn=None, bename=None, properties=None): - raise NotImplemented + raise NotImplementedError def setProperties(self, suffix=None, backend_dn=None, bename=None, properties=None): - raise NotImplemented + raise NotImplementedError def toSuffix(self, entry=None, name=None): ''' @@ -933,9 +933,12 @@ class Backends(DSLdapObjects): class DatabaseConfig(DSLdapObject): - """Chaining Default Config settings DSLdapObject with: - - must attributes = ['cn'] - - RDN attribute is 'cn' + """Backend Database configuration + + The entire database configuration consists of the main global configuration entry, + and the underlying DB library configuration: whither BDB or LMDB. The combined + configuration should be presented as a single entity so the end user does not need + to worry about what library is being used, and just focus on the configuration. :param instance: An instance :type instance: lib389.DirSrv @@ -943,14 +946,96 @@ class DatabaseConfig(DSLdapObject): :type dn: str """ - _must_attributes = ['cn'] - - def __init__(self, instance, dn=None): + def __init__(self, instance, dn="cn=config,cn=ldbm database,cn=plugins,cn=config"): super(DatabaseConfig, self).__init__(instance, dn) self._rdn_attribute = 'cn' self._must_attributes = ['cn'] + self._global_attrs = [ + 'nsslapd-lookthroughlimit', + 'nsslapd-mode', + 'nsslapd-idlistscanlimit', + 'nsslapd-directory', + 'nsslapd-import-cachesize', + 'nsslapd-idl-switch', + 'nsslapd-search-bypass-filter-test', + 'nsslapd-search-use-vlv-index', + 'nsslapd-exclude-from-export', + 'nsslapd-serial-lock', + 'nsslapd-subtree-rename-switch', + 'nsslapd-pagedlookthroughlimit', + 'nsslapd-pagedidlistscanlimit', + 'nsslapd-rangelookthroughlimit', + 'nsslapd-backend-opt-level', + 'nsslapd-backend-implement', + ] + self._db_attrs = { + 'bdb': + [ + 'nsslapd-dbcachesize', + 'nsslapd-db-logdirectory', + 'nsslapd-db-home-directory', + 'nsslapd-db-durable-transaction', + 'nsslapd-db-transaction-wait', + 'nsslapd-db-checkpoint-interval', + 'nsslapd-db-compactdb-interval', + 'nsslapd-db-transaction-batch-val', + 'nsslapd-db-transaction-batch-min-wait', + 'nsslapd-db-transaction-batch-max-wait', + 'nsslapd-db-logbuf-size', + 'nsslapd-db-locks', + 'nsslapd-db-private-import-mem', + 'nsslapd-import-cache-autosize', + 'nsslapd-cache-autosize', + 'nsslapd-cache-autosize-split', + 'nsslapd-import-cachesize', + 'nsslapd-search-bypass-filter-test', + 'nsslapd-serial-lock', + 'nsslapd-db-deadlock-policy', + ], + 'lmdb': [] + } self._create_objectclasses = ['top', 'extensibleObject'] self._protected = True - # Have to set cn=bdb, but when we can choose between bdb and lmdb we'll - # have some hoops to jump through. - self._dn = "cn=bdb,cn=config,cn=ldbm database,cn=plugins,cn=config" + # This could be "bdb" or "lmdb", use what we have configured in the global config + self._db_lib = self.get_attr_val_utf8_l('nsslapd-backend-implement') + self._dn = "cn=config,cn=ldbm database,cn=plugins,cn=config" + self._db_dn = f"cn={self._db_lib},cn=config,cn=ldbm database,cn=plugins,cn=config" + self._globalObj = DSLdapObject(self._instance, dn=self._dn) + self._dbObj = DSLdapObject(self._instance, dn=self._db_dn) + # Assert there is no overlap in different config sets + assert_c(len(set(self._global_attrs).intersection(set(self._db_attrs['bdb']), set(self._db_attrs['lmdb']))) == 0) + + def get(self): + """Get the combined config entries""" + # Get and combine both sets of attributes + global_attrs = self._globalObj.get_attrs_vals_utf8(self._global_attrs) + db_attrs = self._dbObj.get_attrs_vals_utf8(self._db_attrs[self._db_lib]) + combined_attrs = {**global_attrs, **db_attrs} + return combined_attrs + + def display(self): + """Display the combined configuration""" + global_attrs = self._globalObj.get_attrs_vals_utf8(self._global_attrs) + db_attrs = self._dbObj.get_attrs_vals_utf8(self._db_attrs[self._db_lib]) + combined_attrs = {**global_attrs, **db_attrs} + for (k, vo) in combined_attrs.items(): + if len(vo) == 0: + vo = "" + else: + vo = vo[0] + self._instance.log.info(f'{k}: {vo}') + + def set(self, value_pairs): + for attr, val in value_pairs: + attr = attr.lower() + if attr in self._global_attrs: + global_config = DSLdapObject(self._instance, dn=self._dn) + global_config.replace(attr, val) + elif attr in self._db_attrs['bdb']: + db_config = DSLdapObject(self._instance, dn=self._db_dn) + db_config.replace(attr, val) + elif attr in self._db_attrs['lmdb']: + pass + else: + # Unknown attribute + raise ValueError("Can not update database configuration with unknown attribute: " + attr) diff --git a/src/lib389/lib389/cli_conf/backend.py b/src/lib389/lib389/cli_conf/backend.py index 68e389323..75dfc5fdd 100644 --- a/src/lib389/lib389/cli_conf/backend.py +++ b/src/lib389/lib389/cli_conf/backend.py @@ -138,13 +138,13 @@ def backend_list(inst, basedn, log, args): be_list.sort() if args.json: - print(json.dumps({"type": "list", "items": be_list}, indent=4)) + log.info(json.dumps({"type": "list", "items": be_list}, indent=4)) else: if len(be_list) > 0: for be in be_list: - print(be) + log.info(be) else: - print("No backends") + log.info("No backends") def backend_get(inst, basedn, log, args): @@ -200,7 +200,7 @@ def backend_create(inst, basedn, log, args): # Unsupported rdn raise ValueError("Suffix RDN is not supported for creating suffix object. Only 'dc', 'o', 'ou', and 'cn' are supported.") - print("The database was sucessfully created") + log.info("The database was sucessfully created") def _recursively_del_backends(be): @@ -227,7 +227,7 @@ def backend_delete(inst, basedn, log, args, warn=True): _recursively_del_backends(be) be.delete() - print("The database, and any sub-suffixes, were sucessfully deleted") + log.info("The database, and any sub-suffixes, were sucessfully deleted") def backend_import(inst, basedn, log, args): @@ -244,7 +244,7 @@ def backend_import(inst, basedn, log, args): result = task.get_exit_code() if task.is_complete() and result == 0: - print("The import task has finished successfully") + log.info("The import task has finished successfully") else: raise ValueError("Import task failed\n-------------------------\n{}".format(ensure_str(task.get_task_log()))) @@ -272,7 +272,7 @@ def backend_export(inst, basedn, log, args): result = task.get_exit_code() if task.is_complete() and result == 0: - print("The export task has finished successfully") + log.info("The export task has finished successfully") else: raise ValueError("Export task failed\n-------------------------\n{}".format(ensure_str(task.get_task_log()))) @@ -329,15 +329,15 @@ def backend_get_subsuffixes(inst, basedn, log, args): if len(subsuffixes) > 0: subsuffixes.sort() if args.json: - print(json.dumps({"type": "list", "items": subsuffixes}, indent=4)) + log.info(json.dumps({"type": "list", "items": subsuffixes}, indent=4)) else: for sub in subsuffixes: - print(sub) + log.info(sub) else: if args.json: - print(json.dumps({"type": "list", "items": []}, indent=4)) + log.info(json.dumps({"type": "list", "items": []}, indent=4)) else: - print("No sub-suffixes under this backend") + log.info("No sub-suffixes under this backend") def build_node(suffix, be_name, subsuf=False, link=False, replicated=False): @@ -476,15 +476,15 @@ def backend_set(inst, basedn, log, args): be.enable() if args.disable: be.disable() - print("The backend configuration was sucessfully updated") + log.info("The backend configuration was successfully updated") def db_config_get(inst, basedn, log, args): db_cfg = DatabaseConfig(inst) if args.json: - print(db_cfg.get_all_attrs_json()) + log.info(json.dumps({"type": "entry", "attrs": db_cfg.get()}, indent=4)) else: - print(db_cfg.display()) + db_cfg.display() def db_config_set(inst, basedn, log, args): @@ -498,17 +498,18 @@ def db_config_set(inst, basedn, log, args): # We don't support deleting attributes or setting empty values in db continue else: - replace_list.append((attr, value)) + replace_list.append([attr, value]) if len(replace_list) > 0: - db_cfg.replace_many(*replace_list) + db_cfg.set(replace_list) elif not did_something: raise ValueError("There are no changes to set in the database configuration") - print("Successfully updated database configuration") + log.info("Successfully updated database configuration") + def _format_status(log, mtype, json=False): if json: - print(mtype.get_status_json()) + log.info(mtype.get_status_json()) else: status_dict = mtype.get_status() log.info('dn: ' + mtype._dn) @@ -517,6 +518,7 @@ def _format_status(log, mtype, json=False): for vi in v: log.info('{}: {}'.format(k, vi)) + def get_monitor(inst, basedn, log, args): if args.suffix is not None: # Get a suffix/backend monitor entry @@ -535,7 +537,7 @@ def get_monitor(inst, basedn, log, args): def backend_add_index(inst, basedn, log, args): be = _get_backend(inst, args.be_name) be.add_index(args.attr, args.index_type, args.matching_rule, reindex=args.reindex) - print("Successfully added index") + log.info("Successfully added index") def backend_set_index(inst, basedn, log, args): @@ -562,7 +564,7 @@ def backend_set_index(inst, basedn, log, args): if args.reindex: be.reindex(attrs=[args.attr]) - print("Index successfully updated") + log.info("Index successfully updated") def backend_get_index(inst, basedn, log, args): @@ -576,9 +578,9 @@ def backend_get_index(inst, basedn, log, args): # Append decoded json object, because we are going to dump it later results.append(json.loads(entry)) else: - print(index.display()) + log.info(index.display()) if args.json: - print(json.dumps({"type": "list", "items": results}, indent=4)) + log.info(json.dumps({"type": "list", "items": results}, indent=4)) def backend_list_index(inst, basedn, log, args): @@ -593,25 +595,25 @@ def backend_list_index(inst, basedn, log, args): results.append(json.loads(index.get_all_attrs_json())) else: if args.just_names: - print(index.get_attr_val_utf8_l('cn')) + log.info(index.get_attr_val_utf8_l('cn')) else: - print(index.display()) + log.info(index.display()) if args.json: - print(json.dumps({"type": "list", "items": results}, indent=4)) + log.info(json.dumps({"type": "list", "items": results}, indent=4)) def backend_del_index(inst, basedn, log, args): be = _get_backend(inst, args.be_name) for attr in args.attr: be.del_index(attr) - print("Successfully deleted index \"{}\"".format(attr)) + log.info("Successfully deleted index \"{}\"".format(attr)) def backend_reindex(inst, basedn, log, args): be = _get_backend(inst, args.be_name) be.reindex(attrs=args.attr, wait=args.wait) - print("Successfully reindexed database") + log.info("Successfully reindexed database") def backend_attr_encrypt(inst, basedn, log, args): @@ -622,16 +624,16 @@ def backend_attr_encrypt(inst, basedn, log, args): for attr in args.add_attr: be.add_encrypted_attr(attr) if len(args.add_attr) > 1: - print("Successfully added encrypted attributes") + log.info("Successfully added encrypted attributes") else: - print("Successfully added encrypted attribute") + log.info("Successfully added encrypted attribute") if args.del_attr is not None: for attr in args.del_attr: be.del_encrypted_attr(attr) if len(args.del_attr) > 1: - print("Successfully deleted encrypted attributes") + log.info("Successfully deleted encrypted attributes") else: - print("Successfully deleted encrypted attribute") + log.info("Successfully deleted encrypted attribute") if args.list: results = be.get_encrypted_attrs(args.just_names) if args.json: @@ -641,17 +643,17 @@ def backend_attr_encrypt(inst, basedn, log, args): else: for result in results: json_results.append(json.loads(result.get_all_attrs_json())) - print(json.dumps({"type": "list", "items": json_results}, indent=4)) + log.info(json.dumps({"type": "list", "items": json_results}, indent=4)) else: if len(results) == 0: - print("There are no encrypted attributes for this backend") + log.info("There are no encrypted attributes for this backend") else: for attr in results: if args.just_names: - print(attr) + log.info(attr) else: - print(attr.display()) + log.info(attr.display()) def backend_list_vlv(inst, basedn, log, args): @@ -675,24 +677,24 @@ def backend_list_vlv(inst, basedn, log, args): results.append(entry) else: if args.just_names: - print(vlv.get_attr_val_utf8_l('cn')) + log.info(vlv.get_attr_val_utf8_l('cn')) else: raw_entry = vlv.get_attrs_vals(VLV_SEARCH_ATTRS) - print('dn: ' + vlv.dn) + log.info('dn: ' + vlv.dn) for k, v in list(raw_entry.items()): - print('{}: {}'.format(ensure_str(k), ensure_str(v[0]))) + log.info('{}: {}'.format(ensure_str(k), ensure_str(v[0]))) indexes = vlv.get_sorts() sorts = [] - print("Sorts:") + log.info("Sorts:") for idx in indexes: entry = idx.get_attrs_vals(VLV_INDEX_ATTRS) - print(' - dn: ' + idx.dn) + log.info(' - dn: ' + idx.dn) for k, v in list(entry.items()): - print(' - {}: {}'.format(ensure_str(k), ensure_str(v[0]))) - print() + log.info(' - {}: {}'.format(ensure_str(k), ensure_str(v[0]))) + log.info() if args.json: - print(json.dumps({"type": "list", "items": results}, indent=4)) + log.info(json.dumps({"type": "list", "items": results}, indent=4)) def backend_get_vlv(inst, basedn, log, args): @@ -707,9 +709,9 @@ def backend_get_vlv(inst, basedn, log, args): results.append(json.loads(entry)) else: raw_entry = vlv.get_attrs_vals(VLV_SEARCH_ATTRS) - print('dn: ' + vlv._dn) + log.info('dn: ' + vlv._dn) for k, v in list(raw_entry.items()): - print('{}: {}'.format(ensure_str(k), ensure_str(v[0]))) + log.info('{}: {}'.format(ensure_str(k), ensure_str(v[0]))) # Print indexes indexes = vlv.get_sorts() for idx in indexes: @@ -718,14 +720,14 @@ def backend_get_vlv(inst, basedn, log, args): results.append(json.loads(entry)) else: raw_entry = idx.get_attrs_vals(VLV_INDEX_ATTRS) - print('Sorts:') - print(' - dn: ' + idx._dn) + log.info('Sorts:') + log.info(' - dn: ' + idx._dn) for k, v in list(raw_entry.items()): - print(' - {}: {}'.format(ensure_str(k), ensure_str(v[0]))) - print() + log.info(' - {}: {}'.format(ensure_str(k), ensure_str(v[0]))) + log.info() if args.json: - print(json.dumps({"type": "list", "items": results}, indent=4)) + log.info(json.dumps({"type": "list", "items": results}, indent=4)) def backend_create_vlv(inst, basedn, log, args): @@ -735,7 +737,7 @@ def backend_create_vlv(inst, basedn, log, args): 'vlvscope': args.search_scope, 'vlvfilter': args.search_filter} be.add_vlv_search(args.name, props) - print("Successfully created new VLV Search entry, now you can add indexes to it.") + log.info("Successfully created new VLV Search entry, now you can add indexes to it.") def backend_edit_vlv(inst, basedn, log, args): @@ -757,14 +759,14 @@ def backend_edit_vlv(inst, basedn, log, args): raise ValueError("There are no changes to set in the VLV search entry") if args.reindex: vlv_search.reindex() - print("Successfully updated VLV search entry") + log.info("Successfully updated VLV search entry") def backend_del_vlv(inst, basedn, log, args): be = _get_backend(inst, args.be_name) vlv_search = be.get_vlv_searches(vlv_name=args.name) vlv_search.delete_all() - print("Successfully deleted VLV search and its indexes") + log.info("Successfully deleted VLV search and its indexes") def backend_create_vlv_index(inst, basedn, log, args): @@ -773,14 +775,14 @@ def backend_create_vlv_index(inst, basedn, log, args): vlv_search.add_sort(args.index_name, args.sort) if args.index_it: vlv_search.reindex(args.be_name, vlv_index=args.index_name) - print("Successfully created new VLV index entry") + log.info("Successfully created new VLV index entry") def backend_delete_vlv_index(inst, basedn, log, args): be = _get_backend(inst, args.be_name) vlv_search = be.get_vlv_searches(vlv_name=args.parent_name) vlv_search.delete_sort(args.index_name, args.sort) - print("Successfully deleted VLV index entry") + log.info("Successfully deleted VLV index entry") def backend_reindex_vlv(inst, basedn, log, args): @@ -788,7 +790,7 @@ def backend_reindex_vlv(inst, basedn, log, args): suffix = be.get_suffix() vlv_search = be.get_vlv_searches(vlv_name=args.parent_name) vlv_search.reindex(suffix, vlv_index=args.index_name) - print("Successfully reindexed VLV indexes") + log.info("Successfully reindexed VLV indexes") def create_parser(subparsers):
0
dccd54355b8aa92bdd6f59b2d2554a2a6cdf1720
389ds/389-ds-base
Issue 5129 - BUG - Incorrect fn signature in add_index (#5130) Bug Description: Due to an incorrect function signature, it was possible to cause add index to fail by trying to add an empty mr set. Fix Description: Fix the function signature and make the function more robust. fixes: https://github.com/389ds/389-ds-base/issues/5129 Author: William Brown <[email protected]> Review by: @mreynolds389 (thanks!)
commit dccd54355b8aa92bdd6f59b2d2554a2a6cdf1720 Author: Firstyear <[email protected]> Date: Tue Jan 25 09:44:33 2022 +1000 Issue 5129 - BUG - Incorrect fn signature in add_index (#5130) Bug Description: Due to an incorrect function signature, it was possible to cause add index to fail by trying to add an empty mr set. Fix Description: Fix the function signature and make the function more robust. fixes: https://github.com/389ds/389-ds-base/issues/5129 Author: William Brown <[email protected]> Review by: @mreynolds389 (thanks!) diff --git a/src/lib389/lib389/backend.py b/src/lib389/lib389/backend.py index 072085f27..5520834c6 100644 --- a/src/lib389/lib389/backend.py +++ b/src/lib389/lib389/backend.py @@ -719,7 +719,7 @@ class Backend(DSLdapObject): return raise ValueError("Can not delete index because it does not exist") - def add_index(self, attr_name, types, matching_rules=[], reindex=False): + def add_index(self, attr_name, types, matching_rules=None, reindex=False): """ Add an index. :param attr_name - name of the attribute to index @@ -736,7 +736,9 @@ class Backend(DSLdapObject): mrs = [] for mr in matching_rules: mrs.append(mr) - props['nsMatchingRule'] = mrs + # Only add if there are actually rules present in the list. + if len(mrs) > 0: + props['nsMatchingRule'] = mrs new_index.create(properties=props, basedn="cn=index," + self._dn) if reindex:
0
0ffc6a2983a8c76f8043a14ed601099366d5b2b2
389ds/389-ds-base
[185477] ldif2db allows entries without a parent to be imported if idl is NULL, changed add_op_attrs to always set IMPORT_ADD_OP_ATTRS_NO_PARENT in non-error case (err == 0 or err == DB_NOTFOUND)
commit 0ffc6a2983a8c76f8043a14ed601099366d5b2b2 Author: Noriko Hosoi <[email protected]> Date: Thu Mar 16 03:02:33 2006 +0000 [185477] ldif2db allows entries without a parent to be imported if idl is NULL, changed add_op_attrs to always set IMPORT_ADD_OP_ATTRS_NO_PARENT in non-error case (err == 0 or err == DB_NOTFOUND) diff --git a/ldap/servers/slapd/back-ldbm/ldif2ldbm.c b/ldap/servers/slapd/back-ldbm/ldif2ldbm.c index 42c7c06bf..13c8ad899 100644 --- a/ldap/servers/slapd/back-ldbm/ldif2ldbm.c +++ b/ldap/servers/slapd/back-ldbm/ldif2ldbm.c @@ -222,15 +222,15 @@ int add_op_attrs(Slapi_PBlock *pb, struct ldbminfo *li, struct backentry *ep, &err )) != NULL ) { pid = idl_firstid( idl ); idl_free( idl ); - } else if ( 0 != err ) { - if (DB_NOTFOUND != err ) { + } else { + /* empty idl */ + if ( 0 != err && DB_NOTFOUND != err ) { LDAPDebug( LDAP_DEBUG_ANY, "database error %d\n", err, 0, 0 ); slapi_ch_free( (void**)&pdn ); return( -1 ); - } else { - if (NULL != status) { - *status = IMPORT_ADD_OP_ATTRS_NO_PARENT; - } + } + if (NULL != status) { + *status = IMPORT_ADD_OP_ATTRS_NO_PARENT; } } slapi_ch_free( (void**)&pdn );
0
5753df10e1dfed8680f933fb90c0119daf37b19e
389ds/389-ds-base
bump version to 1.3.3.a2
commit 5753df10e1dfed8680f933fb90c0119daf37b19e Author: Rich Megginson <[email protected]> Date: Fri Nov 22 19:23:10 2013 -0700 bump version to 1.3.3.a2 diff --git a/VERSION.sh b/VERSION.sh index 672687a06..df5dd8520 100644 --- a/VERSION.sh +++ b/VERSION.sh @@ -14,7 +14,7 @@ VERSION_MAINT=3 # if this is a PRERELEASE, set VERSION_PREREL # otherwise, comment it out # be sure to include the dot prefix in the prerel -VERSION_PREREL=.a1 +VERSION_PREREL=.a2 # 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
d7eef2fcfbab2ef8aa6ee0bf60f0a9b16ede66e0
389ds/389-ds-base
Issue 4711 - SIGSEV with sync_repl (#4738) Bug description: sync_repl sends back entries identified with a unique identifier that is 'nsuniqueid'. If 'nsuniqueid' is missing, then it may crash Fix description: Check a nsuniqueid is available else returns OP_ERR relates: https://github.com/389ds/389-ds-base/issues/4711 Reviewed by: Pierre Rogier, James Chapman, William Brown (Thanks!) Platforms tested: F33
commit d7eef2fcfbab2ef8aa6ee0bf60f0a9b16ede66e0 Author: tbordaz <[email protected]> Date: Tue Apr 27 09:29:32 2021 +0200 Issue 4711 - SIGSEV with sync_repl (#4738) Bug description: sync_repl sends back entries identified with a unique identifier that is 'nsuniqueid'. If 'nsuniqueid' is missing, then it may crash Fix description: Check a nsuniqueid is available else returns OP_ERR relates: https://github.com/389ds/389-ds-base/issues/4711 Reviewed by: Pierre Rogier, James Chapman, William Brown (Thanks!) Platforms tested: F33 diff --git a/ldap/servers/plugins/sync/sync_util.c b/ldap/servers/plugins/sync/sync_util.c index dc7f49fac..d84705a41 100644 --- a/ldap/servers/plugins/sync/sync_util.c +++ b/ldap/servers/plugins/sync/sync_util.c @@ -165,8 +165,8 @@ sync_create_state_control(Slapi_Entry *e, LDAPControl **ctrlp, int type, Sync_Co BerElement *ber; struct berval *bvp; char *uuid; - Slapi_Attr *attr; - Slapi_Value *val; + Slapi_Attr *attr = NULL; + Slapi_Value *val = NULL; if (type == LDAP_SYNC_NONE || ctrlp == NULL || (ber = der_alloc()) == NULL) { return (LDAP_OPERATIONS_ERROR); @@ -191,6 +191,14 @@ sync_create_state_control(Slapi_Entry *e, LDAPControl **ctrlp, int type, Sync_Co } else { slapi_entry_attr_find(e, SLAPI_ATTR_UNIQUEID, &attr); slapi_attr_first_value(attr, &val); + if ((attr == NULL) || (val == NULL)) { + /* It may happen with entries in special backends + * such like cn=config, cn=shema, cn=monitor... + */ + slapi_log_err(SLAPI_LOG_ERR, SYNC_PLUGIN_SUBSYSTEM, + "sync_create_state_control - Entries are missing nsuniqueid. Unable to proceed.\n"); + return (LDAP_OPERATIONS_ERROR); + } uuid = sync_nsuniqueid2uuid(slapi_value_get_string(val)); }
0
4d128545bb01ea626a79faa6a60152ca277ce05d
389ds/389-ds-base
Resolves: bug 469261 Bug Description: Support server-to-server SASL - part 4 - pta, winsync Reviewed by: nhosoi (Thanks!) Fix Description: Allow pass through auth (PTA) to use starttls. PTA uses the old style argv config params, so I just added an optional starttls (0, 1) to the end of the list, since there is currently no way to encode the startTLS extop in the LDAP URL. NOTE: adding support for true pass through auth for sasl or external cert auth will require a lot of work - not sure it's worth it - anyone other than console users can use chaining backend instead. For windows sync, I just ported the same slapi_ldap_init/slapi_ldap_bind changes made to regular replication to the windows specific code. The Windows code still needs the do_simple_bind function to check the windows password, but it is not used for server to server bind anymore. NOTE: Windows does support startTLS, but I did not test the SASL mechanisms with Windows. Platforms tested: Fedora 9 Flag Day: no Doc impact: yes
commit 4d128545bb01ea626a79faa6a60152ca277ce05d Author: Rich Megginson <[email protected]> Date: Mon Nov 10 23:57:47 2008 +0000 Resolves: bug 469261 Bug Description: Support server-to-server SASL - part 4 - pta, winsync Reviewed by: nhosoi (Thanks!) Fix Description: Allow pass through auth (PTA) to use starttls. PTA uses the old style argv config params, so I just added an optional starttls (0, 1) to the end of the list, since there is currently no way to encode the startTLS extop in the LDAP URL. NOTE: adding support for true pass through auth for sasl or external cert auth will require a lot of work - not sure it's worth it - anyone other than console users can use chaining backend instead. For windows sync, I just ported the same slapi_ldap_init/slapi_ldap_bind changes made to regular replication to the windows specific code. The Windows code still needs the do_simple_bind function to check the windows password, but it is not used for server to server bind anymore. NOTE: Windows does support startTLS, but I did not test the SASL mechanisms with Windows. Platforms tested: Fedora 9 Flag Day: no Doc impact: yes diff --git a/ldap/servers/plugins/passthru/passthru.h b/ldap/servers/plugins/passthru/passthru.h index 6f5a5435e..022a57ae7 100644 --- a/ldap/servers/plugins/passthru/passthru.h +++ b/ldap/servers/plugins/passthru/passthru.h @@ -112,7 +112,7 @@ typedef struct passthruserver { char *ptsrvr_url; /* copy from argv[i] */ char *ptsrvr_hostname; int ptsrvr_port; - int ptsrvr_secure; /* use SSL? */ + int ptsrvr_secure; /* use SSL? or TLS == 2 */ int ptsrvr_ldapversion; int ptsrvr_maxconnections; int ptsrvr_maxconcurrency; diff --git a/ldap/servers/plugins/passthru/ptconfig.c b/ldap/servers/plugins/passthru/ptconfig.c index 28579183c..b7bb13863 100644 --- a/ldap/servers/plugins/passthru/ptconfig.c +++ b/ldap/servers/plugins/passthru/ptconfig.c @@ -101,7 +101,7 @@ static int inited = 0; int passthru_config( int argc, char **argv ) { - int i, j, rc, tosecs, using_def_connlifetime; + int i, j, rc, tosecs, using_def_connlifetime, starttls = 0; char **suffixarray; PassThruServer *prevsrvr, *srvr; PassThruSuffix *suffix, *prevsuffix; @@ -170,11 +170,13 @@ passthru_config( int argc, char **argv ) * parse parameters. format is: * maxconnections,maxconcurrency,timeout,ldapversion * OR maxconnections,maxconcurrency,timeout,ldapversion,lifetime + * OR maxconnections,maxconcurrency,timeout,ldapversion,lifetime,starttls */ *p++ = '\0'; /* p points at space preceding optional arguments */ - rc = sscanf( p, "%d,%d,%d,%d,%d", &srvr->ptsrvr_maxconnections, + rc = sscanf( p, "%d,%d,%d,%d,%d,%d", &srvr->ptsrvr_maxconnections, &srvr->ptsrvr_maxconcurrency, &tosecs, - &srvr->ptsrvr_ldapversion, &srvr->ptsrvr_connlifetime ); + &srvr->ptsrvr_ldapversion, &srvr->ptsrvr_connlifetime, + &starttls); if ( rc < 4 ) { slapi_log_error( SLAPI_LOG_FATAL, PASSTHRU_PLUGIN_SUBSYSTEM, "server parameters should be in the form " @@ -184,8 +186,13 @@ passthru_config( int argc, char **argv ) } else if ( rc < 5 ) { using_def_connlifetime = 1; srvr->ptsrvr_connlifetime = PASSTHRU_DEF_SRVR_CONNLIFETIME; - } else { - using_def_connlifetime = 0; + starttls = 0; + } else if ( rc < 6 ) { + using_def_connlifetime = 0; /* lifetime specified */ + starttls = 0; /* but not starttls */ + } else { /* all 6 args supplied */ + using_def_connlifetime = 0; /* lifetime specified */ + /* and starttls */ } if ( srvr->ptsrvr_ldapversion != LDAP_VERSION2 @@ -241,6 +248,9 @@ passthru_config( int argc, char **argv ) srvr->ptsrvr_port = ludp->lud_port; srvr->ptsrvr_secure = (( ludp->lud_options & LDAP_URL_OPT_SECURE ) != 0 ); + if (starttls) { + srvr->ptsrvr_secure = 2; + } /* * If a space-separated list of hosts is configured for failover, diff --git a/ldap/servers/plugins/replication/repl5_connection.c b/ldap/servers/plugins/replication/repl5_connection.c index 027f8c1c4..03d61897a 100644 --- a/ldap/servers/plugins/replication/repl5_connection.c +++ b/ldap/servers/plugins/replication/repl5_connection.c @@ -991,9 +991,10 @@ conn_connect(Repl_Connection *conn) conn->last_operation = CONN_INIT; conn->last_ldap_error = LDAP_LOCAL_ERROR; slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name, - "%s: Failed to establish %sconnection to the consumer\n", + "%s: Failed to establish %s%sconnection to the consumer\n", agmt_get_long_name(conn->agmt), - secure ? "secure " : ""); + secure ? "secure " : "", + (secure == 2) ? "startTLS " : ""); ber_bvfree(creds); creds = NULL; return return_value; diff --git a/ldap/servers/plugins/replication/windows_connection.c b/ldap/servers/plugins/replication/windows_connection.c index a2c720f09..ffcc8bec0 100644 --- a/ldap/servers/plugins/replication/windows_connection.c +++ b/ldap/servers/plugins/replication/windows_connection.c @@ -102,9 +102,6 @@ static int s_debug_level = 0; static Slapi_Eq_Context repl5_start_debug_timeout(int *setlevel); static void repl5_stop_debug_timeout(Slapi_Eq_Context eqctx, int *setlevel); static void repl5_debug_timeout_callback(time_t when, void *arg); -#ifndef DSE_RETURNTEXT_SIZE -#define SLAPI_DSE_RETURNTEXT_SIZE 512 -#endif #define STATE_CONNECTED 600 #define STATE_DISCONNECTED 601 @@ -1190,21 +1187,14 @@ windows_conn_connect(Repl_Connection *conn) conn->plain = slapi_ch_strdup (plain); if (!pw_ret) slapi_ch_free((void**)&plain); } + /* ugaston: if SSL has been selected in the replication agreement, SSL client * initialisation should be done before ever trying to open any connection at all. */ - if (conn->transport_flags == TRANSPORT_FLAG_TLS) - { - slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name, - "%s: Replication secured by StartTLS not currently supported\n", - agmt_get_long_name(conn->agmt)); - - return_value = CONN_OPERATION_FAILED; - conn->last_ldap_error = LDAP_STRONG_AUTH_NOT_SUPPORTED; - conn->state = STATE_DISCONNECTED; - } else if(conn->transport_flags == TRANSPORT_FLAG_SSL) + if ((conn->transport_flags == TRANSPORT_FLAG_TLS) || + (conn->transport_flags == TRANSPORT_FLAG_SSL)) { /** Make sure the SSL Library has been initialized before anything else **/ @@ -1217,11 +1207,13 @@ windows_conn_connect(Repl_Connection *conn) conn->last_operation = CONN_INIT; ber_bvfree(creds); creds = NULL; - LDAPDebug( LDAP_DEBUG_TRACE, "<= windows_conn_connect\n", 0, 0, 0 ); return CONN_SSL_NOT_ENABLED; - } else + } else if (conn->transport_flags == TRANSPORT_FLAG_SSL) { secure = 1; + } else + { + secure = 2; /* 2 means starttls security */ } } @@ -1230,11 +1222,12 @@ windows_conn_connect(Repl_Connection *conn) /* Now we initialize the LDAP Structure and set options */ slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name, - "%s: Trying %s slapi_ldap_init\n", + "%s: Trying %s%s slapi_ldap_init_ext\n", agmt_get_long_name(conn->agmt), - secure ? "secure" : "non-secure"); + secure ? "secure" : "non-secure", + (secure == 2) ? " startTLS" : ""); - conn->ld = slapi_ldap_init(conn->hostname, conn->port, secure, 0); + conn->ld = slapi_ldap_init_ext(NULL, conn->hostname, conn->port, secure, 0, NULL); if (NULL == conn->ld) { return_value = CONN_OPERATION_FAILED; @@ -1242,9 +1235,10 @@ windows_conn_connect(Repl_Connection *conn) conn->last_operation = CONN_INIT; conn->last_ldap_error = LDAP_LOCAL_ERROR; slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name, - "%s: Failed to establish %sconnection to the consumer\n", + "%s: Failed to establish %s%sconnection to the consumer\n", agmt_get_long_name(conn->agmt), - secure ? "secure " : ""); + secure ? "secure " : "", + (secure == 2) ? "startTLS " : ""); ber_bvfree(creds); creds = NULL; LDAPDebug( LDAP_DEBUG_TRACE, "<= windows_conn_connect\n", 0, 0, 0 ); @@ -1684,6 +1678,26 @@ void windows_conn_set_agmt_changed(Repl_Connection *conn) LDAPDebug( LDAP_DEBUG_TRACE, "<= windows_conn_set_agmt_changed\n", 0, 0, 0 ); } +static const char * +bind_method_to_mech(int bindmethod) +{ + switch (bindmethod) { + case BINDMETHOD_SSL_CLIENTAUTH: + return LDAP_SASL_EXTERNAL; + break; + case BINDMETHOD_SASL_GSSAPI: + return "GSSAPI"; + break; + case BINDMETHOD_SASL_DIGEST_MD5: + return "DIGEST-MD5"; + break; + default: /* anything else */ + return LDAP_SASL_SIMPLE; + } + + return LDAP_SASL_SIMPLE; +} + /* * Check the result of an ldap_simple_bind operation to see we it * contains the expiration controls @@ -1695,101 +1709,26 @@ bind_and_check_pwp(Repl_Connection *conn, char * binddn, char *password) { LDAPControl **ctrls = NULL; - LDAPMessage *res = NULL; - char *errmsg = NULL; LDAP *ld = conn->ld; - int msgid; - int *msgidAdr = &msgid; int rc; + const char *mech = bind_method_to_mech(conn->bindmethod); - char * optype; /* ldap_simple_bind or slapd_SSL_client_bind */ - - LDAPDebug( LDAP_DEBUG_TRACE, "=> windows_conn_set_agmt_changed\n", 0, 0, 0 ); - - if ( conn->transport_flags == TRANSPORT_FLAG_SSL ) - { - char *auth; - optype = "ldap_sasl_bind"; - - if ( conn->bindmethod == BINDMETHOD_SSL_CLIENTAUTH ) - { - rc = slapd_sasl_ext_client_bind(conn->ld, &msgidAdr); - auth = "SSL client authentication"; - - if ( rc == LDAP_SUCCESS ) - { - if (conn->last_ldap_error != rc) - { - conn->last_ldap_error = rc; - slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name, - "%s: Replication bind with %s resumed\n", - agmt_get_long_name(conn->agmt), auth); - } - } - else - { - /* Do not report the same error over and over again */ - if (conn->last_ldap_error != rc) - { - conn->last_ldap_error = rc; - slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name, - "%s: Replication bind with %s failed: LDAP error %d (%s)\n", - agmt_get_long_name(conn->agmt), auth, rc, - ldap_err2string(rc)); - } + LDAPDebug( LDAP_DEBUG_TRACE, "=> bind_and_check_pwp\n", 0, 0, 0 ); - LDAPDebug( LDAP_DEBUG_TRACE, "<= windows_conn_set_agmt_changed - CONN_OPERATION_FAILED\n", 0, 0, 0 ); + rc = slapi_ldap_bind(conn->ld, binddn, password, mech, NULL, + &ctrls, NULL, NULL); - return (CONN_OPERATION_FAILED); - } - } - else - { - if( ( msgid = do_simple_bind( conn, ld, binddn, password ) ) == -1 ) - { - LDAPDebug( LDAP_DEBUG_TRACE, "<= windows_conn_set_agmt_changed - CONN_OPERATION_FAILED\n", 0, 0, 0 ); - return (CONN_OPERATION_FAILED); - } - } - } - else + if ( rc == LDAP_SUCCESS ) { - optype = "ldap_simple_bind"; - if( ( msgid = do_simple_bind( conn, ld, binddn, password ) ) == -1 ) + if (conn->last_ldap_error != rc) { - LDAPDebug( LDAP_DEBUG_TRACE, "<= windows_conn_set_agmt_changed - CONN_OPERATION_FAILED\n", 0, 0, 0 ); - return (CONN_OPERATION_FAILED); + conn->last_ldap_error = rc; + slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name, + "%s: Replication bind with %s auth resumed\n", + agmt_get_long_name(conn->agmt), + mech ? mech : "SIMPLE"); } - } - /* Wait for the result */ - if ( ldap_result( ld, msgid, LDAP_MSG_ALL, NULL, &res ) == -1 ) - { - slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name, - "%s: Received error from consumer for %s operation\n", - - agmt_get_long_name(conn->agmt), optype); - LDAPDebug( LDAP_DEBUG_TRACE, "<= windows_conn_set_agmt_changed - CONN_OPERATION_FAILED\n", 0, 0, 0 ); - - return (CONN_OPERATION_FAILED); - } - /* Don't check ldap_result against 0 because, no timeout is specified */ - - /* Free res as we won't use it any longer */ - if ( ldap_parse_result( ld, res, &rc, NULL, NULL, NULL, &ctrls, 1 /* Free res */) - != LDAP_SUCCESS ) - { - slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name, - "%s: Received error from consumer for %s operation\n", - agmt_get_long_name(conn->agmt), optype); - - LDAPDebug( LDAP_DEBUG_TRACE, "<= windows_conn_set_agmt_changed - CONN_OPERATION_FAILED\n", 0, 0, 0 ); - - return (CONN_OPERATION_FAILED); - } - - if ( rc == LDAP_SUCCESS ) - { if ( ctrls ) { int i; @@ -1820,20 +1759,28 @@ bind_and_check_pwp(Repl_Connection *conn, char * binddn, char *password) ldap_controls_free( ctrls ); } - LDAPDebug( LDAP_DEBUG_TRACE, "<= windows_conn_set_agmt_changed - CONN_OPERATION_SUCCESS\n", 0, 0, 0 ); + LDAPDebug( LDAP_DEBUG_TRACE, "<= bind_and_check_pwp - CONN_OPERATION_SUCCESS\n", 0, 0, 0 ); return (CONN_OPERATION_SUCCESS); } else { - /* errmsg is a pointer directly into the ld structure - do not free */ - rc = ldap_get_lderrno( ld, NULL, &errmsg ); - slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name, - "%s: Replication bind to %s on consumer failed: %d (%s)\n", - agmt_get_long_name(conn->agmt), binddn, rc, errmsg); + ldap_controls_free( ctrls ); + /* Do not report the same error over and over again */ + if (conn->last_ldap_error != rc) + { + char *errmsg = NULL; + conn->last_ldap_error = rc; + /* errmsg is a pointer directly into the ld structure - do not free */ + rc = ldap_get_lderrno( ld, NULL, &errmsg ); + slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name, + "%s: Replication bind with %s auth failed: LDAP error %d (%s) (%s)\n", + agmt_get_long_name(conn->agmt), + mech ? mech : "SIMPLE", rc, + ldap_err2string(rc), errmsg); + } - conn->last_ldap_error = rc; /* specific error */ - LDAPDebug( LDAP_DEBUG_TRACE, "<= windows_conn_set_agmt_changed - CONN_OPERATION_FAILED\n", 0, 0, 0 ); + LDAPDebug( LDAP_DEBUG_TRACE, "<= bind_and_check_pwp - CONN_OPERATION_FAILED\n", 0, 0, 0 ); return (CONN_OPERATION_FAILED); } } @@ -1861,7 +1808,7 @@ windows_check_user_password(Repl_Connection *conn, Slapi_DN *sdn, char *password ldap_parse_result( conn->ld, res, &rc, NULL, NULL, NULL, NULL, 1 /* Free res */); /* rebind as the DN specified in the sync agreement */ - do_simple_bind(conn, conn->ld, conn->binddn, conn->plain); + bind_and_check_pwp(conn, conn->binddn, conn->plain); return rc; } @@ -1886,10 +1833,11 @@ do_simple_bind (Repl_Connection *conn, LDAP *ld, char * binddn, char *password) conn->last_ldap_error = ldaperr; slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name, "%s: Simple bind failed, " - SLAPI_COMPONENT_NAME_LDAPSDK " error %d (%s), " + SLAPI_COMPONENT_NAME_LDAPSDK " error %d (%s) (%s), " SLAPI_COMPONENT_NAME_NSPR " error %d (%s)\n", agmt_get_long_name(conn->agmt), - ldaperr, ldaperrtext ? ldaperrtext : ldap_err2string(ldaperr), + ldaperr, ldap_err2string(ldaperr), + ldaperrtext ? ldaperrtext : "", prerr, slapd_pr_strerror(prerr)); } }
0
82b12c97afd34ecc8acfe54baaf0f32bd83a7edf
389ds/389-ds-base
Ticket 47637 - rsa_null_sha should not be enabled by default Bug Description: rsa_null_sha is enabled by default, this can allow unencrypted traffic over a TLS connection. Fix Description: Disable rsa_null_sha, just like rsa_null_md5, by default. https://fedorahosted.org/389/ticket/47637 Reviewed by: rmeggins(Thanks!)
commit 82b12c97afd34ecc8acfe54baaf0f32bd83a7edf Author: Mark Reynolds <[email protected]> Date: Thu Mar 6 11:07:24 2014 -0500 Ticket 47637 - rsa_null_sha should not be enabled by default Bug Description: rsa_null_sha is enabled by default, this can allow unencrypted traffic over a TLS connection. Fix Description: Disable rsa_null_sha, just like rsa_null_md5, by default. https://fedorahosted.org/389/ticket/47637 Reviewed by: rmeggins(Thanks!) diff --git a/ldap/servers/slapd/ssl.c b/ldap/servers/slapd/ssl.c index 48c3fe97f..8dc39d277 100644 --- a/ldap/servers/slapd/ssl.c +++ b/ldap/servers/slapd/ssl.c @@ -147,8 +147,8 @@ static cipherstruct _conf_ciphers[] = { {"SSL3","fips_des_sha", SSL_RSA_FIPS_WITH_DES_CBC_SHA}, /* ditto */ {"SSL3","rsa_rc4_40_md5", SSL_RSA_EXPORT_WITH_RC4_40_MD5}, {"SSL3","rsa_rc2_40_md5", SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5}, - {"SSL3","rsa_null_md5", SSL_RSA_WITH_NULL_MD5}, - {"SSL3","rsa_null_sha", SSL_RSA_WITH_NULL_SHA}, + {"SSL3","rsa_null_md5", SSL_RSA_WITH_NULL_MD5}, /* disabled by default */ + {"SSL3","rsa_null_sha", SSL_RSA_WITH_NULL_SHA}, /* disabled by default */ {"TLS","tls_rsa_export1024_with_rc4_56_sha", TLS_RSA_EXPORT1024_WITH_RC4_56_SHA}, {"TLS","rsa_rc4_56_sha", TLS_RSA_EXPORT1024_WITH_RC4_56_SHA}, /* ditto */ {"TLS","tls_rsa_export1024_with_des_cbc_sha", TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA}, @@ -282,7 +282,9 @@ _conf_setallciphers(int active, char ***suplist, char ***unsuplist) * them to activate it by name. */ for(x = 0; _conf_ciphers[x].name; x++) { PRBool enabled = active ? PR_TRUE : PR_FALSE; - if(active && !strcmp(_conf_ciphers[x].name, "rsa_null_md5")) { + if(active && (!strcmp(_conf_ciphers[x].name, "rsa_null_md5") || + !strcmp(_conf_ciphers[x].name, "rsa_null_sha"))) + { continue; } if (enabled) { @@ -334,7 +336,12 @@ _conf_setciphers(char *ciphers) slapi_ch_free((void **)&suplist); /* strings inside are static */ return NULL; } -/* Enable all the ciphers by default and the following while loop would disable the user disabled ones This is needed becuase we added a new set of ciphers in the table . Right now there is no support for this from the console */ + /* + * Enable all the ciphers by default and the following while loop would + * disable the user disabled ones. This is needed because we added a new + * set of ciphers in the table. Right now there is no support for this + * from the console + */ _conf_setallciphers(1, &suplist, NULL); t = ciphers;
0
8654301b458218743e8539a649e3cf869be0d985
389ds/389-ds-base
Issue 5598 - (2nd) In 2.x, SRCH throughput drops by 10% because of handling of referral (#5691) Bug description: The first fix 5598 introduce/reveal a leak. My initial understanding of SLAPI_SEARCH_FILTER and SLAPI_SEARCH_FILTER_INTENDED was wrong. Without referral, they are identical (refering to the same filter). In case of referral, SLAPI_SEARCH_FILTER is a craft one that *includes* the original (SLAPI_SEARCH_FILTER_INTENDED). Fix description: If there is no referral, SLAPI_SEARCH_FILTER_INTENDED and SLAPI_SEARCH_FILTER are just identical relates: #5598 Reviewed by: Mark Reynolds, Pierre Rogier(thanks)
commit 8654301b458218743e8539a649e3cf869be0d985 Author: tbordaz <[email protected]> Date: Wed Mar 8 15:40:29 2023 +0100 Issue 5598 - (2nd) In 2.x, SRCH throughput drops by 10% because of handling of referral (#5691) Bug description: The first fix 5598 introduce/reveal a leak. My initial understanding of SLAPI_SEARCH_FILTER and SLAPI_SEARCH_FILTER_INTENDED was wrong. Without referral, they are identical (refering to the same filter). In case of referral, SLAPI_SEARCH_FILTER is a craft one that *includes* the original (SLAPI_SEARCH_FILTER_INTENDED). Fix description: If there is no referral, SLAPI_SEARCH_FILTER_INTENDED and SLAPI_SEARCH_FILTER are just identical relates: #5598 Reviewed by: Mark Reynolds, Pierre Rogier(thanks) diff --git a/ldap/servers/slapd/back-ldbm/ldbm_search.c b/ldap/servers/slapd/back-ldbm/ldbm_search.c index 61e9b11bb..5c39c9ac2 100644 --- a/ldap/servers/slapd/back-ldbm/ldbm_search.c +++ b/ldap/servers/slapd/back-ldbm/ldbm_search.c @@ -1044,7 +1044,7 @@ build_candidate_list(Slapi_PBlock *pb, backend *be, struct backentry *e, const c * - there is no referral on the server * - this is an internal SRCH */ - filter_exec = slapi_filter_dup(filter); + filter_exec = filter; } else { /* make (|(originalfilter)(objectclass=referral)) */ filter_exec = create_subtree_filter(filter, managedsait); diff --git a/ldap/servers/slapd/proto-slap.h b/ldap/servers/slapd/proto-slap.h index 45f23658e..888666c17 100644 --- a/ldap/servers/slapd/proto-slap.h +++ b/ldap/servers/slapd/proto-slap.h @@ -629,7 +629,7 @@ int32_t config_set_ldapssotoken_secret(const char *attrname, char *value, char * int32_t config_set_ldapssotoken_ttl(const char *attrname, char *value, char *errorbuf, int apply); int32_t config_get_ldapssotoken_ttl(void); -int32_t config_get_referral_check_period(); +int32_t config_get_referral_check_period(void); int32_t config_set_referral_check_period(const char *attrname, char *value, char *errorbuf, int apply); int32_t config_get_return_orig_dn(void);
0
58b91ec4cb2b7b4ede0b9cb48bf54c1ca9c34d78
389ds/389-ds-base
Resolves: 439907 Summary: Enhanced SLAPI task API and ported existing tasks to use new API.
commit 58b91ec4cb2b7b4ede0b9cb48bf54c1ca9c34d78 Author: Nathan Kinder <[email protected]> Date: Thu Apr 3 16:52:47 2008 +0000 Resolves: 439907 Summary: Enhanced SLAPI task API and ported existing tasks to use new API. diff --git a/ldap/servers/plugins/memberof/memberof.c b/ldap/servers/plugins/memberof/memberof.c index a1341a7eb..96d9a906a 100644 --- a/ldap/servers/plugins/memberof/memberof.c +++ b/ldap/servers/plugins/memberof/memberof.c @@ -49,10 +49,10 @@ * * To start the memberof task add an entry like: * - * dn: cn=memberof task 2, cn=memberof task, cn=tasks, cn=config + * dn: cn=mytask, cn=memberof task, cn=tasks, cn=config * objectClass: top * objectClass: extensibleObject - * cn: sample task + * cn: mytask * basedn: dc=example, dc=com * filter: (uid=test4) * @@ -75,7 +75,6 @@ #define MEMBEROF_GROUP_ATTR "member" #define MEMBEROF_ATTR "memberof" #define MEMBEROF_GROUP_ATTR_IS_DN 1 -#define MEMBEROF_GROUP_ATTR_TYPE "uid" #define MEMBEROF_GROUP_FILTER "(" MEMBEROF_GROUP_ATTR "=*)" #define MEMBEROF_PLUGIN_SUBSYSTEM "memberof-plugin" /* used for logging */ @@ -92,50 +91,6 @@ typedef struct _memberofstringll void *next; } memberofstringll; - - -/****** secrets *********/ - -/*from FDS slap.h - * until we get a proper api for access - */ -#define TASK_RUNNING_AS_TASK 0x0 - -/*from FDS slapi-private.h - * until we get a proper api for access - */ - - -#define SLAPI_DSE_CALLBACK_OK (1) -#define SLAPI_DSE_CALLBACK_ERROR (-1) -#define SLAPI_DSE_CALLBACK_DO_NOT_APPLY (0) - -/****************************************************************************** - * Online tasks interface (to support import, export, etc) - * After some cleanup, we could consider making these public. - */ -struct _slapi_task { - struct _slapi_task *next; - char *task_dn; - int task_exitcode; /* for the end user */ - int task_state; /* (see above) */ - int task_progress; /* number between 0 and task_work */ - int task_work; /* "units" of work to be done */ - int task_flags; /* (see above) */ - - /* it is the task's responsibility to allocate this memory & free it: */ - char *task_status; /* transient status info */ - char *task_log; /* appended warnings, etc */ - - void *task_private; /* for use by backends */ - TaskCallbackFn cancel; /* task has been cancelled by user */ - TaskCallbackFn destructor; /* task entry is being destroyed */ - int task_refcount; -}; - -/****** secrets ********/ - - /*** function prototypes ***/ /* exported functions */ @@ -169,7 +124,7 @@ static int memberof_add_attr_list(Slapi_PBlock *pb, char *groupdn, Slapi_Attr *a static int memberof_del_attr_list(Slapi_PBlock *pb, char *groupdn, Slapi_Attr *attr); static int memberof_moddn_attr_list(Slapi_PBlock *pb, char *pre_dn, char *post_dn, Slapi_Attr *attr); -static int memberofd_replace_list(Slapi_PBlock *pb, char *group_dn); +static int memberof_replace_list(Slapi_PBlock *pb, char *group_dn); static void memberof_set_plugin_id(void * plugin_id); static void *memberof_get_plugin_id(); static int memberof_compare(const void *a, const void *b); @@ -195,9 +150,10 @@ static int memberof_add_membership(Slapi_PBlock *pb, char *op_this, char *op_to) static int memberof_task_add(Slapi_PBlock *pb, Slapi_Entry *e, Slapi_Entry *eAfter, int *returncode, char *returntext, void *arg); +static void memberof_task_destructor(Slapi_Task *task); static const char *fetch_attr(Slapi_Entry *e, const char *attrname, const char *default_val); -static void memberof_memberof_fixup_task_thread(void *arg); +static void memberof_fixup_task_thread(void *arg); static int memberof_fix_memberof(char *dn, char *filter_str); static int memberof_fix_memberof_callback(Slapi_Entry *e, void *callback_data); @@ -511,6 +467,8 @@ int memberof_postop_modrdn(Slapi_PBlock *pb) memberof_lock(); + /* get a list of member attributes present in the group + * entry that is being renamed. */ if(0 == slapi_entry_attr_find(post_e, MEMBEROF_GROUP_ATTR, &attr)) { memberof_moddn_attr_list(pb, pre_dn, post_dn, attr); @@ -656,7 +614,7 @@ int memberof_postop_modify(Slapi_PBlock *pb) { /* If there are no values in the smod, we should * just do a replace instead. The user is just - * trying to delete all members from this this + * trying to delete all members from this group * entry, which the replace code deals with. */ if (slapi_mod_get_num_values(smod) == 0) { @@ -673,7 +631,7 @@ int memberof_postop_modify(Slapi_PBlock *pb) case LDAP_MOD_REPLACE: { /* replace current values */ - memberofd_replace_list(pb, dn); + memberof_replace_list(pb, dn); break; } @@ -877,6 +835,14 @@ int memberof_modop_one_replace_r(Slapi_PBlock *pb, int mod_op, char *group_dn, { op_str = "ADD"; } + else if(LDAP_MOD_REPLACE == mod_op) + { + op_str = "REPLACE"; + } + else + { + op_str = "UNKNOWN"; + } slapi_log_error( SLAPI_LOG_PLUGIN, MEMBEROF_PLUGIN_SUBSYSTEM, "memberof_modop_one_r: %s %s in %s\n" @@ -1347,7 +1313,7 @@ int memberof_is_group_member(Slapi_Value *groupdn, Slapi_Value *memberdn) return rc; } -/* memberof_memberof_search_callback() +/* memberof_test_membership() * for each attribute in the memberof attribute * determine if the entry is still a member * @@ -1517,7 +1483,7 @@ bail: * Perform replace the group DN list in the memberof attribute of the list of targets * */ -int memberofd_replace_list(Slapi_PBlock *pb, char *group_dn) +int memberof_replace_list(Slapi_PBlock *pb, char *group_dn) { struct slapi_entry *pre_e = NULL; struct slapi_entry *post_e = NULL; @@ -1876,29 +1842,22 @@ void memberof_unlock() slapi_unlock_mutex(memberof_operation_lock); } -/* - * - */ - typedef struct _task_data { char *dn; char *filter_str; - Slapi_Task *task; } task_data; -void memberof_memberof_fixup_task_thread(void *arg) +void memberof_fixup_task_thread(void *arg) { - task_data *td = (task_data *)arg; - Slapi_Task *task = td->task; + Slapi_Task *task = (Slapi_Task *)arg; + task_data *td = NULL; int rc = 0; - task->task_work = 1; - task->task_progress = 0; - task->task_state = SLAPI_TASK_RUNNING; - - slapi_task_status_changed(task); + /* Fetch our task data from the task */ + td = (task_data *)slapi_task_get_data(task); + slapi_task_begin(task, 1); slapi_task_log_notice(task, "Memberof task starts (arg: %s) ...\n", td->filter_str); @@ -1907,20 +1866,10 @@ void memberof_memberof_fixup_task_thread(void *arg) slapi_task_log_notice(task, "Memberof task finished."); slapi_task_log_status(task, "Memberof task finished."); + slapi_task_inc_progress(task); - task->task_progress = 1; - task->task_exitcode = rc; - task->task_state = SLAPI_TASK_FINISHED; - slapi_task_status_changed(task); - - slapi_ch_free_string(&td->dn); - slapi_ch_free_string(&td->filter_str); - - { - /* make the compiler happy */ - void *ptd = td; - slapi_ch_free(&ptd); - } + /* this will queue the destruction of the task */ + slapi_task_finish(task, rc); } /* extract a single value from the entry (as a string) -- if it's not in the @@ -1966,13 +1915,7 @@ int memberof_task_add(Slapi_PBlock *pb, Slapi_Entry *e, goto out; } - /* allocate new task now */ - task = slapi_new_task(slapi_entry_get_ndn(e)); - task->task_state = SLAPI_TASK_SETUP; - task->task_work = 1; - task->task_progress = 0; - - /* create a pblock to pass the necessary info to the task thread */ + /* setup our task data */ mytaskdata = (task_data*)slapi_ch_malloc(sizeof(task_data)); if (mytaskdata == NULL) { @@ -1982,11 +1925,19 @@ int memberof_task_add(Slapi_PBlock *pb, Slapi_Entry *e, } mytaskdata->dn = slapi_ch_strdup(dn); mytaskdata->filter_str = slapi_ch_strdup(filter); - mytaskdata->task = task; + + /* allocate new task now */ + task = slapi_new_task(slapi_entry_get_ndn(e)); + + /* register our destructor for cleaning up our private data */ + slapi_task_set_destructor_fn(task, memberof_task_destructor); + + /* Stash a pointer to our data in the task */ + slapi_task_set_data(task, mytaskdata); /* start the sample task as a separate thread */ - thread = PR_CreateThread(PR_USER_THREAD, memberof_memberof_fixup_task_thread, - (void *)mytaskdata, PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, + thread = PR_CreateThread(PR_USER_THREAD, memberof_fixup_task_thread, + (void *)task, PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, PR_UNJOINABLE_THREAD, SLAPD_DEFAULT_THREAD_STACKSIZE); if (thread == NULL) { @@ -1994,28 +1945,29 @@ int memberof_task_add(Slapi_PBlock *pb, Slapi_Entry *e, "unable to create task thread!\n"); *returncode = LDAP_OPERATIONS_ERROR; rv = SLAPI_DSE_CALLBACK_ERROR; - - slapi_ch_free_string(&mytaskdata->dn); - slapi_ch_free_string(&mytaskdata->filter_str); - - { - void *ptask = mytaskdata; - slapi_ch_free(&ptask); - goto out; - } + slapi_task_finish(task, *returncode); + } else { + rv = SLAPI_DSE_CALLBACK_OK; } - /* thread successful -- don't free the pb, let the thread do that. */ - return SLAPI_DSE_CALLBACK_OK; - out: - if (task) - { - slapi_destroy_task(task); - } return rv; } +void +memberof_task_destructor(Slapi_Task *task) +{ + if (task) { + task_data *mydata = (task_data *)slapi_task_get_data(task); + if (mydata) { + slapi_ch_free_string(&mydata->dn); + slapi_ch_free_string(&mydata->filter_str); + /* Need to cast to avoid a compiler warning */ + slapi_ch_free((void **)&mydata); + } + } +} + int memberof_fix_memberof(char *dn, char *filter_str) { int rc = 0; diff --git a/ldap/servers/slapd/back-ldbm/archive.c b/ldap/servers/slapd/back-ldbm/archive.c index be2c4c63c..a0568b7ab 100644 --- a/ldap/servers/slapd/back-ldbm/archive.c +++ b/ldap/servers/slapd/back-ldbm/archive.c @@ -61,7 +61,7 @@ int ldbm_back_archive2ldbm( Slapi_PBlock *pb ) slapi_pblock_get( pb, SLAPI_BACKEND_INSTANCE_NAME, &backendname); slapi_pblock_get( pb, SLAPI_BACKEND_TASK, &task ); slapi_pblock_get( pb, SLAPI_TASK_FLAGS, &task_flags ); - li->li_flags = run_from_cmdline = (task_flags & TASK_RUNNING_FROM_COMMANDLINE); + li->li_flags = run_from_cmdline = (task_flags & SLAPI_TASK_RUNNING_FROM_COMMANDLINE); if ( !rawdirectory || !*rawdirectory ) { LDAPDebug( LDAP_DEBUG_ANY, "archive2db: no archive name\n", @@ -273,7 +273,7 @@ int ldbm_back_ldbm2archive( Slapi_PBlock *pb ) slapi_pblock_get( pb, SLAPI_PLUGIN_PRIVATE, &li ); slapi_pblock_get( pb, SLAPI_SEQ_VAL, &rawdirectory ); slapi_pblock_get( pb, SLAPI_TASK_FLAGS, &task_flags ); - li->li_flags = run_from_cmdline = (task_flags & TASK_RUNNING_FROM_COMMANDLINE); + li->li_flags = run_from_cmdline = (task_flags & SLAPI_TASK_RUNNING_FROM_COMMANDLINE); slapi_pblock_get( pb, SLAPI_BACKEND_TASK, &task ); diff --git a/ldap/servers/slapd/back-ldbm/back-ldbm.h b/ldap/servers/slapd/back-ldbm/back-ldbm.h index 87e046839..2af305fe6 100644 --- a/ldap/servers/slapd/back-ldbm/back-ldbm.h +++ b/ldap/servers/slapd/back-ldbm/back-ldbm.h @@ -513,10 +513,10 @@ struct ldbminfo { int li_legacy_errcode; /* 615428 -- in case legacy err code is expected */ }; -/* li_flags could store these bits defined in ../slap.h +/* li_flags could store these bits defined in ../slapi-plugin.h * task flag (pb_task_flags) * - * #define TASK_RUNNING_AS_TASK 0x0 - * #define TASK_RUNNING_FROM_COMMANDLINE 0x1 + * SLAPI_TASK_RUNNING_AS_TASK + * SLAPI_TASK_RUNNING_FROM_COMMANDLINE */ /* allow conf w/o CONFIG_FLAG_ALLOW_RUNNING_CHANGE to be updated */ #define LI_FORCE_MOD_CONFIG 0x10 diff --git a/ldap/servers/slapd/back-ldbm/dblayer.c b/ldap/servers/slapd/back-ldbm/dblayer.c index 8f0bc07b4..abd71b85d 100644 --- a/ldap/servers/slapd/back-ldbm/dblayer.c +++ b/ldap/servers/slapd/back-ldbm/dblayer.c @@ -1954,7 +1954,7 @@ int dblayer_instance_start(backend *be, int mode) oflags |= DB_PRIVATE; } PR_Lock(li->li_config_mutex); - if ((li->li_flags & TASK_RUNNING_FROM_COMMANDLINE) && + if ((li->li_flags & SLAPI_TASK_RUNNING_FROM_COMMANDLINE) && (li->li_import_cache_autosize)) /* Autosizing importCache * Need to re-eval every time * to guarantee the memory is @@ -5678,7 +5678,7 @@ int dblayer_restore(struct ldbminfo *li, char *src_dir, Slapi_Task *task, char * * dse_conf_verify may need to have db started, as well. */ /* If no logfiles were stored, then fatal recovery isn't required */ - if (li->li_flags & TASK_RUNNING_FROM_COMMANDLINE) + if (li->li_flags & SLAPI_TASK_RUNNING_FROM_COMMANDLINE) { /* command line mode; no need to run db threads */ dbmode |= DBLAYER_NO_DBTHREADS_MODE; @@ -5707,7 +5707,7 @@ int dblayer_restore(struct ldbminfo *li, char *src_dir, Slapi_Task *task, char * "Warning: Unable to verify the index configuration\n", 0, 0, 0); } - if (li->li_flags & TASK_RUNNING_FROM_COMMANDLINE) { + if (li->li_flags & SLAPI_TASK_RUNNING_FROM_COMMANDLINE) { /* command line: close the database down again */ tmp_rval = dblayer_close(li, dbmode); if (0 != tmp_rval) { diff --git a/ldap/servers/slapd/back-ldbm/import.c b/ldap/servers/slapd/back-ldbm/import.c index 7666dcfe0..533a61c32 100644 --- a/ldap/servers/slapd/back-ldbm/import.c +++ b/ldap/servers/slapd/back-ldbm/import.c @@ -197,29 +197,19 @@ void import_log_notice(ImportJob *job, char *format, ...) buffer, 0); } -static int import_task_destroy(Slapi_Task *task) +static void import_task_destroy(Slapi_Task *task) { - ImportJob *job = (ImportJob *)task->task_private; - - if (task->task_log) { - slapi_ch_free((void **)&task->task_log); - } - - if (task->task_status) { - slapi_ch_free((void **)&task->task_status); - } - + ImportJob *job = (ImportJob *)slapi_task_get_data(task); if (job && job->task_status) { slapi_ch_free((void **)&job->task_status); job->task_status = NULL; } FREE(job); - task->task_private = NULL; - return 0; + slapi_task_set_data(task, NULL); } -static int import_task_abort(Slapi_Task *task) +static void import_task_abort(Slapi_Task *task) { ImportJob *job; @@ -227,9 +217,8 @@ static int import_task_abort(Slapi_Task *task) * DSE lock for modify... */ - if (task->task_state == SLAPI_TASK_FINISHED) { + if (slapi_task_get_state(task) == SLAPI_TASK_FINISHED) { /* too late */ - return 0; } /* @@ -238,14 +227,12 @@ static int import_task_abort(Slapi_Task *task) * because it will free the job. */ - job = (ImportJob *)task->task_private; + job = (ImportJob *)slapi_task_get_data(task); import_abort_all(job, 0); - while (task->task_state != SLAPI_TASK_FINISHED) + while (slapi_task_get_state(task) != SLAPI_TASK_FINISHED) DS_Sleep(PR_MillisecondsToInterval(100)); - - return 0; } @@ -1042,13 +1029,8 @@ static int import_all_done(ImportJob *job, int ret) slapi_ch_free_string(&inst_dirp); } - if (job->task != NULL && 0 == job->task->task_refcount) { - /* exit code */ - job->task->task_exitcode = ret; - job->task->task_state = SLAPI_TASK_FINISHED; - job->task->task_progress = job->task->task_work; - job->task->task_private = NULL; - slapi_task_status_changed(job->task); + if ((job->task != NULL) && (0 == slapi_task_get_refcount(job->task))) { + slapi_task_finish(job->task, ret); } if (job->flags & FLAG_ONLINE) { @@ -1093,7 +1075,7 @@ int import_main_offline(void *arg) ImportWorkerInfo *producer = NULL; if (job->task) - job->task->task_refcount++; + slapi_task_inc_refcount(job->task); PR_ASSERT(inst != NULL); time(&beginning); @@ -1364,13 +1346,11 @@ error: if (0 != ret) { import_log_notice(job, "Import failed."); if (job->task != NULL) { - job->task->task_state = SLAPI_TASK_FINISHED; - job->task->task_exitcode = ret; - slapi_task_status_changed(job->task); + slapi_task_finish(job->task, ret); } } else { if (job->task) - job->task->task_refcount--; + slapi_task_dec_refcount(job->task); import_all_done(job, ret); } @@ -1471,15 +1451,17 @@ int ldbm_back_ldif2ldbm_deluxe(Slapi_PBlock *pb) /* add 1 to account for post-import cleanup (which can take a * significant amount of time) */ + /* NGK - This should eventually be cleaned up to use the public + * task API. */ if (0 == total_files) /* reindexing */ job->task->task_work = 2; else job->task->task_work = total_files + 1; job->task->task_progress = 0; job->task->task_state = SLAPI_TASK_RUNNING; - job->task->task_private = job; - job->task->destructor = import_task_destroy; - job->task->cancel = import_task_abort; + slapi_task_set_data(job->task, job); + slapi_task_set_destructor_fn(job->task, import_task_destroy); + slapi_task_set_cancel_fn(job->task, import_task_abort); job->flags |= FLAG_ONLINE; /* create thread for import_main, so we can return */ diff --git a/ldap/servers/slapd/back-ldbm/ldif2ldbm.c b/ldap/servers/slapd/back-ldbm/ldif2ldbm.c index 827e471ce..e4f82b2f1 100644 --- a/ldap/servers/slapd/back-ldbm/ldif2ldbm.c +++ b/ldap/servers/slapd/back-ldbm/ldif2ldbm.c @@ -568,7 +568,7 @@ int ldbm_back_ldif2ldbm( Slapi_PBlock *pb ) /* hopefully this will go away once import is not run standalone... */ slapi_pblock_get(pb, SLAPI_TASK_FLAGS, &task_flags); - if (task_flags & TASK_RUNNING_FROM_COMMANDLINE) { + if (task_flags & SLAPI_TASK_RUNNING_FROM_COMMANDLINE) { /* initialize UniqueID generator - must be done once backends are started and event queue is initialized but before plugins are started */ Slapi_DN *sdn = slapi_sdn_new_dn_byval ("cn=uniqueid generator,cn=config"); @@ -581,7 +581,7 @@ int ldbm_back_ldif2ldbm( Slapi_PBlock *pb ) return -1; } - li->li_flags |= TASK_RUNNING_FROM_COMMANDLINE; + li->li_flags |= SLAPI_TASK_RUNNING_FROM_COMMANDLINE; ldbm_config_load_dse_info(li); autosize_import_cache(li); } @@ -604,7 +604,7 @@ int ldbm_back_ldif2ldbm( Slapi_PBlock *pb ) /***** prepare & init libdb and dblayer *****/ - if (! (task_flags & TASK_RUNNING_FROM_COMMANDLINE)) { + if (! (task_flags & SLAPI_TASK_RUNNING_FROM_COMMANDLINE)) { /* shutdown this instance of the db */ LDAPDebug(LDAP_DEBUG_ANY, "Bringing %s offline...\n", instance_name, 0, 0); @@ -778,11 +778,11 @@ ldbm_back_ldbm2ldif( Slapi_PBlock *pb ) slapi_pblock_get( pb, SLAPI_TASK_FLAGS, &task_flags ); slapi_pblock_get( pb, SLAPI_DB2LDIF_DECRYPT, &decrypt ); slapi_pblock_get( pb, SLAPI_DB2LDIF_SERVER_RUNNING, &server_running ); - run_from_cmdline = (task_flags & TASK_RUNNING_FROM_COMMANDLINE); + run_from_cmdline = (task_flags & SLAPI_TASK_RUNNING_FROM_COMMANDLINE); dump_replica = pb->pb_ldif_dump_replica; if (run_from_cmdline) { - li->li_flags |= TASK_RUNNING_FROM_COMMANDLINE; + li->li_flags |= SLAPI_TASK_RUNNING_FROM_COMMANDLINE; if (!dump_replica) { we_start_the_backends = 1; } @@ -1298,12 +1298,12 @@ ldbm_back_ldbm2index(Slapi_PBlock *pb) slapi_pblock_get(pb, SLAPI_BACKEND_INSTANCE_NAME, &instance_name); slapi_pblock_get(pb, SLAPI_PLUGIN_PRIVATE, &li); slapi_pblock_get(pb, SLAPI_TASK_FLAGS, &task_flags); - run_from_cmdline = (task_flags & TASK_RUNNING_FROM_COMMANDLINE); + run_from_cmdline = (task_flags & SLAPI_TASK_RUNNING_FROM_COMMANDLINE); slapi_pblock_get(pb, SLAPI_BACKEND_TASK, &task); if (run_from_cmdline) { /* No ldbm backend exists until we process the config info. */ - li->li_flags |= TASK_RUNNING_FROM_COMMANDLINE; + li->li_flags |= SLAPI_TASK_RUNNING_FROM_COMMANDLINE; ldbm_config_load_dse_info(li); txn.back_txn_txn = NULL; /* no transaction */ } @@ -1764,6 +1764,8 @@ ldbm_back_ldbm2index(Slapi_PBlock *pb) percent = (ep->ep_id*100 / (lastid ? lastid : 1)); } if (task) { + /* NGK - This should eventually be cleaned up to use the + * public task API */ task->task_progress = (idl ? idindex : ep->ep_id); task->task_work = (idl ? idl->b_nids : lastid); slapi_task_status_changed(task); @@ -1970,7 +1972,7 @@ int ldbm_back_upgradedb(Slapi_PBlock *pb) slapi_pblock_get(pb, SLAPI_BACKEND_TASK, &task); slapi_pblock_get(pb, SLAPI_DB2LDIF_SERVER_RUNNING, &server_running); - run_from_cmdline = (task_flags & TASK_RUNNING_FROM_COMMANDLINE); + run_from_cmdline = (task_flags & SLAPI_TASK_RUNNING_FROM_COMMANDLINE); slapi_pblock_get(pb, SLAPI_PLUGIN_PRIVATE, &li); if (run_from_cmdline) { @@ -2435,7 +2437,7 @@ void upgradedb_core(Slapi_PBlock *pb, ldbm_instance *inst) int run_from_cmdline = 0; slapi_pblock_get(pb, SLAPI_TASK_FLAGS, &task_flags); - run_from_cmdline = (task_flags & TASK_RUNNING_FROM_COMMANDLINE); + run_from_cmdline = (task_flags & SLAPI_TASK_RUNNING_FROM_COMMANDLINE); be = inst->inst_be; slapi_log_error(SLAPI_LOG_FATAL, "upgrade DB", diff --git a/ldap/servers/slapd/main.c b/ldap/servers/slapd/main.c index 0b5f3e7de..1c1943a62 100644 --- a/ldap/servers/slapd/main.c +++ b/ldap/servers/slapd/main.c @@ -2118,7 +2118,7 @@ slapd_exemode_ldif2db() pb.pb_ldif_files = ldif_file; pb.pb_ldif_include = db2ldif_include; pb.pb_ldif_exclude = db2ldif_exclude; - pb.pb_task_flags = TASK_RUNNING_FROM_COMMANDLINE; + pb.pb_task_flags = SLAPI_TASK_RUNNING_FROM_COMMANDLINE; #ifndef _WIN32 main_setuid(slapdFrontendConfig->localuser); #endif @@ -2245,7 +2245,7 @@ slapd_exemode_db2ldif(int argc, char** argv) pb.pb_ldif_dump_uniqueid = db2ldif_dump_uniqueid; pb.pb_ldif_encrypt = importexport_encrypt; pb.pb_instance_name = *instp; - pb.pb_task_flags = TASK_RUNNING_FROM_COMMANDLINE; + pb.pb_task_flags = SLAPI_TASK_RUNNING_FROM_COMMANDLINE; if (is_slapd_running()) pb.pb_server_running = 1; else @@ -2431,7 +2431,7 @@ static int slapd_exemode_db2index() pb.pb_plugin = plugin; pb.pb_db2index_attrs = db2index_attrs; pb.pb_instance_name = cmd_line_instance_name; - pb.pb_task_flags = TASK_RUNNING_FROM_COMMANDLINE; + pb.pb_task_flags = SLAPI_TASK_RUNNING_FROM_COMMANDLINE; #ifndef _WIN32 main_setuid(slapdFrontendConfig->localuser); #endif @@ -2489,7 +2489,7 @@ slapd_exemode_db2archive() pb.pb_plugin = backend_plugin; pb.pb_instance_name = cmd_line_instance_name; pb.pb_seq_val = archive_name; - pb.pb_task_flags = TASK_RUNNING_FROM_COMMANDLINE; + pb.pb_task_flags = SLAPI_TASK_RUNNING_FROM_COMMANDLINE; #ifndef _WIN32 main_setuid(slapdFrontendConfig->localuser); #endif @@ -2539,7 +2539,7 @@ slapd_exemode_archive2db() pb.pb_plugin = backend_plugin; pb.pb_instance_name = cmd_line_instance_name; pb.pb_seq_val = archive_name; - pb.pb_task_flags = TASK_RUNNING_FROM_COMMANDLINE; + pb.pb_task_flags = SLAPI_TASK_RUNNING_FROM_COMMANDLINE; #ifndef _WIN32 main_setuid(slapdFrontendConfig->localuser); #endif @@ -2601,7 +2601,7 @@ slapd_exemode_upgradedb() pb.pb_plugin = backend_plugin; pb.pb_seq_val = archive_name; pb.pb_seq_type = upgradedb_force; - pb.pb_task_flags = TASK_RUNNING_FROM_COMMANDLINE; + pb.pb_task_flags = SLAPI_TASK_RUNNING_FROM_COMMANDLINE; /* borrowing import code, so need to set up the import variables */ pb.pb_ldif_generate_uniqueid = ldif2db_generate_uniqueid; pb.pb_ldif_namespaceid = ldif2db_namespaceid; @@ -2656,7 +2656,7 @@ slapd_exemode_dbverify() pb.pb_seq_type = dbverify_verbose; pb.pb_plugin = backend_plugin; pb.pb_instance_name = (char *)cmd_line_instance_names; - pb.pb_task_flags = TASK_RUNNING_FROM_COMMANDLINE; + pb.pb_task_flags = SLAPI_TASK_RUNNING_FROM_COMMANDLINE; if ( backend_plugin->plg_dbverify != NULL ) { return_value = (*backend_plugin->plg_dbverify)( &pb ); diff --git a/ldap/servers/slapd/slap.h b/ldap/servers/slapd/slap.h index f1777eb88..0b3305e3b 100644 --- a/ldap/servers/slapd/slap.h +++ b/ldap/servers/slapd/slap.h @@ -1283,6 +1283,27 @@ typedef struct conn { #define SLAPD_POLL_FLAGS (PR_POLL_READ) #endif +/****************************************************************************** + * * Online tasks interface (to support import, export, etc) + * * After some cleanup, we could consider making these public. + * */ +struct slapi_task { + struct slapi_task *next; + char *task_dn; + int task_exitcode; /* for the end user */ + int task_state; /* current state of task */ + int task_progress; /* number between 0 and task_work */ + int task_work; /* "units" of work to be done */ + int task_flags; /* (see above) */ + char *task_status; /* transient status info */ + char *task_log; /* appended warnings, etc */ + void *task_private; /* allow opaque data to be stashed in the task */ + TaskCallbackFn cancel; /* task has been cancelled by user */ + TaskCallbackFn destructor; /* task entry is being destroyed */ + int task_refcount; +} slapi_task; +/* End of interface to support online tasks **********************************/ + typedef struct slapi_pblock { /* common */ Slapi_Backend *pb_backend; @@ -2016,10 +2037,6 @@ extern char *attr_dataversion; #include "intrinsics.h" -/* task flag (pb_task_flags)*/ -#define TASK_RUNNING_AS_TASK 0x0 -#define TASK_RUNNING_FROM_COMMANDLINE 0x1 - /* printkey: import & export */ #define EXPORT_PRINTKEY 0x1 #define EXPORT_NOWRAP 0x2 diff --git a/ldap/servers/slapd/slapi-plugin.h b/ldap/servers/slapd/slapi-plugin.h index f963621e8..b7f5f9276 100644 --- a/ldap/servers/slapd/slapi-plugin.h +++ b/ldap/servers/slapd/slapi-plugin.h @@ -149,9 +149,10 @@ typedef struct slapi_rdn Slapi_RDN; typedef struct slapi_mod Slapi_Mod; typedef struct slapi_mods Slapi_Mods; typedef struct slapi_componentid Slapi_ComponentId; + /* Online tasks interface (to support import, export, etc) */ -typedef struct _slapi_task Slapi_Task; -typedef int (*TaskCallbackFn)(Slapi_Task *task); +typedef struct slapi_task Slapi_Task; +typedef void (*TaskCallbackFn)(Slapi_Task *task); /* * The default thread stacksize for nspr21 is 64k (except on IRIX! It's 32k!). @@ -1206,6 +1207,22 @@ void slapi_register_role_check(roles_check_fn_type check_fn); typedef int (*dseCallbackFn)(Slapi_PBlock *, Slapi_Entry *, Slapi_Entry *, int *, char*, void *); +/* + * Note: DSE callback functions MUST return one of these three values: + * + * SLAPI_DSE_CALLBACK_OK -- no errors occurred; apply changes. + * SLAPI_DSE_CALLBACK_ERROR -- an error occurred; don't apply changes. + * SLAPI_DSE_CALLBACK_DO_NOT_APPLY -- no error, but do not apply changes. + * + * SLAPI_DSE_CALLBACK_DO_NOT_APPLY should only be returned by modify + * callbacks (i.e., those registered with operation==SLAPI_OPERATION_MODIFY). + * A return value of SLAPI_DSE_CALLBACK_DO_NOT_APPLY is treated the same as + * SLAPI_DSE_CALLBACK_ERROR for all other operations. + */ +#define SLAPI_DSE_CALLBACK_OK (1) +#define SLAPI_DSE_CALLBACK_ERROR (-1) +#define SLAPI_DSE_CALLBACK_DO_NOT_APPLY (0) + /****************************************************************************** * Online tasks interface (to support import, export, etc) * After some cleanup, we could consider making these public. @@ -1217,10 +1234,26 @@ typedef int (*dseCallbackFn)(Slapi_PBlock *, Slapi_Entry *, Slapi_Entry *, #define SLAPI_TASK_FINISHED 2 #define SLAPI_TASK_CANCELLED 3 +/* task flag (pb_task_flags)*/ +#define SLAPI_TASK_RUNNING_AS_TASK 0x0 +#define SLAPI_TASK_RUNNING_FROM_COMMANDLINE 0x1 + /* task flags (set by the task-control code) */ #define SLAPI_TASK_DESTROYING 0x01 /* queued event for destruction */ int slapi_task_register_handler(const char *name, dseCallbackFn func); +void slapi_task_begin(Slapi_Task *task, int total_work); +void slapi_task_inc_progress(Slapi_Task *task); +void slapi_task_finish(Slapi_Task *task, int rc); +void slapi_task_cancel(Slapi_Task *task, int rc); +int slapi_task_get_state(Slapi_Task *task); +void slapi_task_set_data(Slapi_Task *task, void *data); +void * slapi_task_get_data(Slapi_Task *task); +void slapi_task_inc_refcount(Slapi_Task *task); +void slapi_task_dec_refcount(Slapi_Task *task); +int slapi_task_get_refcount(Slapi_Task *task); +void slapi_task_set_destructor_fn(Slapi_Task *task, TaskCallbackFn func); +void slapi_task_set_cancel_fn(Slapi_Task *task, TaskCallbackFn func); void slapi_task_status_changed(Slapi_Task *task); void slapi_task_log_status(Slapi_Task *task, char *format, ...) #ifdef __GNUC__ diff --git a/ldap/servers/slapd/slapi-private.h b/ldap/servers/slapd/slapi-private.h index 834ce46db..1225e8d5d 100644 --- a/ldap/servers/slapd/slapi-private.h +++ b/ldap/servers/slapd/slapi-private.h @@ -1059,22 +1059,6 @@ int slapi_uniqueIDGenerateFromNameString(char **uId, * JCMREPL - Added for the replication plugin. */ -/* - * Note: DSE callback functions MUST return one of these three values: - * - * SLAPI_DSE_CALLBACK_OK -- no errors occurred; apply changes. - * SLAPI_DSE_CALLBACK_ERROR -- an error occurred; don't apply changes. - * SLAPI_DSE_CALLBACK_DO_NOT_APPLY -- no error, but do not apply changes. - * - * SLAPI_DSE_CALLBACK_DO_NOT_APPLY should only be returned by modify - * callbacks (i.e., those registered with operation==SLAPI_OPERATION_MODIFY). - * A return value of SLAPI_DSE_CALLBACK_DO_NOT_APPLY is treated the same as - * SLAPI_DSE_CALLBACK_ERROR for all other operations. - */ -#define SLAPI_DSE_CALLBACK_OK (1) -#define SLAPI_DSE_CALLBACK_ERROR (-1) -#define SLAPI_DSE_CALLBACK_DO_NOT_APPLY (0) - /* * Flags for slapi_config_register_callback() and * slapi_config_remove_callback() @@ -1198,30 +1182,6 @@ int slapd_re_init( void ); /***** End of items added for the replication plugin. ***********************/ -/****************************************************************************** - * Online tasks interface (to support import, export, etc) - * After some cleanup, we could consider making these public. - */ -struct _slapi_task { - struct _slapi_task *next; - char *task_dn; - int task_exitcode; /* for the end user */ - int task_state; /* (see above) */ - int task_progress; /* number between 0 and task_work */ - int task_work; /* "units" of work to be done */ - int task_flags; /* (see above) */ - - /* it is the task's responsibility to allocate this memory & free it: */ - char *task_status; /* transient status info */ - char *task_log; /* appended warnings, etc */ - - void *task_private; /* for use by backends */ - TaskCallbackFn cancel; /* task has been cancelled by user */ - TaskCallbackFn destructor; /* task entry is being destroyed */ - int task_refcount; -}; -/* End of interface to support online tasks **********************************/ - void DS_Sleep(PRIntervalTime ticks); /* macro to specify the behavior of upgradedb */ diff --git a/ldap/servers/slapd/task.c b/ldap/servers/slapd/task.c index 13606c1cf..67c93c165 100644 --- a/ldap/servers/slapd/task.c +++ b/ldap/servers/slapd/task.c @@ -47,6 +47,9 @@ #include "slap.h" +/*********************************** + * Static Global Variables + ***********************************/ /* don't panic, this is only used when creating new tasks or removing old * ones... */ @@ -54,7 +57,9 @@ static Slapi_Task *global_task_list = NULL; static PRLock *global_task_lock = NULL; static int shutting_down = 0; - +/*********************************** + * Private Defines + ***********************************/ #define TASK_BASE_DN "cn=tasks, cn=config" #define TASK_IMPORT_DN "cn=import, cn=tasks, cn=config" #define TASK_EXPORT_DN "cn=export, cn=tasks, cn=config" @@ -71,13 +76,398 @@ static int shutting_down = 0; #define DEFAULT_TTL "120" /* seconds */ +#define LOG_BUFFER 256 +/* if the cumul. log gets larger than this, it's truncated: */ +#define MAX_SCROLLBACK_BUFFER 8192 + +#define NEXTMOD(_type, _val) do { \ + modlist[cur].mod_op = LDAP_MOD_REPLACE; \ + modlist[cur].mod_type = (_type); \ + modlist[cur].mod_values = (char **)slapi_ch_malloc(2*sizeof(char *)); \ + modlist[cur].mod_values[0] = (_val); \ + modlist[cur].mod_values[1] = NULL; \ + mod[cur] = &modlist[cur]; \ + cur++; \ +} while (0) + +/*********************************** + * Static Function Prototypes + ***********************************/ +static Slapi_Task *new_task(const char *dn); +static void destroy_task(time_t when, void *arg); static int task_modify(Slapi_PBlock *pb, Slapi_Entry *e, Slapi_Entry *eAfter, int *returncode, char *returntext, void *arg); static int task_deny(Slapi_PBlock *pb, Slapi_Entry *e, Slapi_Entry *eAfter, int *returncode, char *returntext, void *arg); -static int task_generic_destructor(Slapi_Task *task); +static void task_generic_destructor(Slapi_Task *task); +static const char *fetch_attr(Slapi_Entry *e, const char *attrname, + const char *default_val); +static Slapi_Entry *get_internal_entry(Slapi_PBlock *pb, char *dn); +static void modify_internal_entry(char *dn, LDAPMod **mods); + +/*********************************** + * Public Functions + ***********************************/ +/* + * slapi_new_task: create a new task, fill in DN, and setup modify callback + * argument: + * dn: task dn + * result: + * Success: Slapi_Task object + * Failure: NULL + */ +Slapi_Task * +slapi_new_task(const char *dn) +{ + return new_task(dn); +} + +/* slapi_destroy_task: destroy a task + * argument: + * task: task to destroy + * result: + * none + */ +void +slapi_destroy_task(void *arg) +{ + if (arg) { + destroy_task(1, arg); + } +} + +/* + * Sets the initial task state and updated status + */ +void slapi_task_begin(Slapi_Task *task, int total_work) +{ + if (task) { + task->task_work = total_work; + task->task_progress = 0; + task->task_state = SLAPI_TASK_RUNNING; + slapi_task_status_changed(task); + } +} + +/* + * Increments task progress and updates status + */ +void slapi_task_inc_progress(Slapi_Task *task) +{ + if (task) { + task->task_progress++; + slapi_task_status_changed(task); + } +} + +/* + * Sets completed task state and updates status + */ +void slapi_task_finish(Slapi_Task *task, int rc) +{ + if (task) { + task->task_exitcode = rc; + task->task_state = SLAPI_TASK_FINISHED; + slapi_task_status_changed(task); + } +} + +/* + * Cancels a task + */ +void slapi_task_cancel(Slapi_Task *task, int rc) +{ + if (task) { + task->task_exitcode = rc; + task->task_state = SLAPI_TASK_CANCELLED; + slapi_task_status_changed(task); + } +} + +/* + * Get the current state of a task + */ +int slapi_task_get_state(Slapi_Task *task) +{ + if (task) { + return task->task_state; + } +} + +/* this changes the 'nsTaskStatus' value, which is transient (anything logged + * here wipes out any previous status) + */ +void slapi_task_log_status(Slapi_Task *task, char *format, ...) +{ + va_list ap; + + if (! task->task_status) + task->task_status = (char *)slapi_ch_malloc(10 * LOG_BUFFER); + if (! task->task_status) + return; /* out of memory? */ + + va_start(ap, format); + PR_vsnprintf(task->task_status, (10 * LOG_BUFFER), format, ap); + va_end(ap); + slapi_task_status_changed(task); +} + +/* this adds a line to the 'nsTaskLog' value, which is cumulative (anything + * logged here is added to the end) + */ +void slapi_task_log_notice(Slapi_Task *task, char *format, ...) +{ + va_list ap; + char buffer[LOG_BUFFER]; + size_t len; + + va_start(ap, format); + PR_vsnprintf(buffer, LOG_BUFFER, format, ap); + va_end(ap); + + len = 2 + strlen(buffer) + (task->task_log ? strlen(task->task_log) : 0); + if ((len > MAX_SCROLLBACK_BUFFER) && task->task_log) { + size_t i; + char *newbuf; + + /* start from middle of buffer, and find next linefeed */ + i = strlen(task->task_log)/2; + while (task->task_log[i] && (task->task_log[i] != '\n')) + i++; + if (task->task_log[i]) + i++; + len = strlen(task->task_log) - i + 2 + strlen(buffer); + newbuf = (char *)slapi_ch_malloc(len); + if (! newbuf) + return; /* out of memory? */ + strcpy(newbuf, task->task_log + i); + slapi_ch_free((void **)&task->task_log); + task->task_log = newbuf; + } else { + if (! task->task_log) { + task->task_log = (char *)slapi_ch_malloc(len); + task->task_log[0] = 0; + } else { + task->task_log = (char *)slapi_ch_realloc(task->task_log, len); + } + if (! task->task_log) + return; /* out of memory? */ + } + + if (task->task_log[0]) + strcat(task->task_log, "\n"); + strcat(task->task_log, buffer); + + slapi_task_status_changed(task); +} + +/* update attributes in the entry under "cn=tasks" to match the current + * status of the task. */ +void slapi_task_status_changed(Slapi_Task *task) +{ + LDAPMod modlist[20]; + LDAPMod *mod[20]; + int cur = 0, i; + char s1[20], s2[20], s3[20]; + + if (shutting_down) { + /* don't care about task status updates anymore */ + return; + } + + NEXTMOD(TASK_LOG_NAME, task->task_log); + NEXTMOD(TASK_STATUS_NAME, task->task_status); + sprintf(s1, "%d", task->task_exitcode); + sprintf(s2, "%d", task->task_progress); + sprintf(s3, "%d", task->task_work); + NEXTMOD(TASK_PROGRESS_NAME, s2); + NEXTMOD(TASK_WORK_NAME, s3); + /* only add the exit code when the job is done */ + if ((task->task_state == SLAPI_TASK_FINISHED) || + (task->task_state == SLAPI_TASK_CANCELLED)) { + NEXTMOD(TASK_EXITCODE_NAME, s1); + /* make sure the console can tell the task has ended */ + if (task->task_progress != task->task_work) { + task->task_progress = task->task_work; + } + } + + mod[cur] = NULL; + modify_internal_entry(task->task_dn, mod); + + for (i = 0; i < cur; i++) + slapi_ch_free((void **)&modlist[i].mod_values); + if (((task->task_state == SLAPI_TASK_FINISHED) || + (task->task_state == SLAPI_TASK_CANCELLED)) && + !(task->task_flags & SLAPI_TASK_DESTROYING)) { + Slapi_PBlock *pb = slapi_pblock_new(); + Slapi_Entry *e; + int ttl; + time_t expire; + + e = get_internal_entry(pb, task->task_dn); + if (e == NULL) + return; + ttl = atoi(fetch_attr(e, "ttl", DEFAULT_TTL)); + if (ttl > 3600) + ttl = 3600; /* be reasonable. */ + expire = time(NULL) + ttl; + task->task_flags |= SLAPI_TASK_DESTROYING; + /* queue an event to destroy the state info */ + slapi_eq_once(destroy_task, (void *)task, expire); + + slapi_free_search_results_internal(pb); + slapi_pblock_destroy(pb); + } +} + +/* + * Stash some opaque task specific data in the task for later use. + */ +void slapi_task_set_data(Slapi_Task *task, void *data) +{ + if (task) { + task->task_private = data; + } +} + +/* + * Retrieve some opaque task specific data from the task. + */ +void * slapi_task_get_data(Slapi_Task *task) +{ + if (task) { + return task->task_private; + } +} + +/* + * Increment the task reference count + */ +void slapi_task_inc_refcount(Slapi_Task *task) +{ + if (task) { + task->task_refcount++; + } +} + +/* + * Decrement the task reference count + */ +void slapi_task_dec_refcount(Slapi_Task *task) +{ + if (task) { + task->task_refcount--; + } +} + +/* + * Returns the task reference count + */ +int slapi_task_get_refcount(Slapi_Task *task) +{ + if (task) { + return task->task_refcount; + } +} + +/* name is, for example, "import" */ +int slapi_task_register_handler(const char *name, dseCallbackFn func) +{ + char *dn = NULL; + Slapi_PBlock *pb = NULL; + Slapi_Operation *op; + LDAPMod *mods[3]; + LDAPMod mod[3]; + const char *objectclass[3]; + const char *cnvals[2]; + int ret = -1; + int x; + + dn = slapi_ch_smprintf("cn=%s, %s", name, TASK_BASE_DN); + if (dn == NULL) { + goto out; + } + + pb = slapi_pblock_new(); + if (pb == NULL) { + goto out; + } + + /* this is painful :( */ + mods[0] = &mod[0]; + mod[0].mod_op = LDAP_MOD_ADD; + mod[0].mod_type = "objectClass"; + mod[0].mod_values = (char **)objectclass; + objectclass[0] = "top"; + objectclass[1] = "extensibleObject"; + objectclass[2] = NULL; + mods[1] = &mod[1]; + mod[1].mod_op = LDAP_MOD_ADD; + mod[1].mod_type = "cn"; + mod[1].mod_values = (char **)cnvals; + cnvals[0] = name; + cnvals[1] = NULL; + mods[2] = NULL; + slapi_add_internal_set_pb(pb, dn, mods, NULL, + plugin_get_default_component_id(), 0); + x = 1; + slapi_pblock_set(pb, SLAPI_DSE_DONT_WRITE_WHEN_ADDING, &x); + /* Make sure these adds don't appear in the audit and change logs */ + slapi_pblock_get(pb, SLAPI_OPERATION, &op); + operation_set_flag(op, OP_FLAG_ACTION_NOLOG); + + slapi_add_internal_pb(pb); + slapi_pblock_get(pb, SLAPI_PLUGIN_INTOP_RESULT, &x); + if ((x != LDAP_SUCCESS) && (x != LDAP_ALREADY_EXISTS)) { + LDAPDebug(LDAP_DEBUG_ANY, + "Can't create task node '%s' (error %d)\n", + name, x, 0); + ret = x; + goto out; + } + + /* register add callback */ + slapi_config_register_callback(SLAPI_OPERATION_ADD, DSE_FLAG_PREOP, + dn, LDAP_SCOPE_SUBTREE, "(objectclass=*)", func, NULL); + /* deny modify/delete of the root task entry */ + slapi_config_register_callback(SLAPI_OPERATION_MODIFY, DSE_FLAG_PREOP, + dn, LDAP_SCOPE_BASE, "(objectclass=*)", task_deny, NULL); + slapi_config_register_callback(SLAPI_OPERATION_DELETE, DSE_FLAG_PREOP, + dn, LDAP_SCOPE_BASE, "(objectclass=*)", task_deny, NULL); + + ret = 0; + +out: + if (dn) { + slapi_ch_free((void **)&dn); + } + if (pb) { + slapi_pblock_destroy(pb); + } + return ret; +} + +void slapi_task_set_destructor_fn(Slapi_Task *task, TaskCallbackFn func) +{ + if (task) { + task->destructor = func; + } +} + +void slapi_task_set_cancel_fn(Slapi_Task *task, TaskCallbackFn func) +{ + if (task) { + task->cancel = func; + } +} + + +/*********************************** + * Static Helper Functions + ***********************************/ /* create a new task, fill in DN, and setup modify callback */ static Slapi_Task * new_task(const char *dn) @@ -92,7 +482,11 @@ new_task(const char *dn) PR_Unlock(global_task_lock); task->task_dn = slapi_ch_strdup(dn); - task->destructor = task_generic_destructor; + task->task_state = SLAPI_TASK_SETUP; + task->task_flags = SLAPI_TASK_RUNNING_AS_TASK; + task->destructor = NULL; + task->cancel = NULL; + task->task_private = NULL; slapi_config_register_callback(SLAPI_OPERATION_MODIFY, DSE_FLAG_PREOP, dn, LDAP_SCOPE_BASE, "(objectclass=*)", task_modify, (void *)task); slapi_config_register_callback(SLAPI_OPERATION_DELETE, DSE_FLAG_PREOP, dn, @@ -100,8 +494,8 @@ new_task(const char *dn) /* don't add entries under this one */ #if 0 /* don't know why, but this doesn't work. it makes the current add - * operation fail. :( - */ + * * operation fail. :( + * */ slapi_config_register_callback(SLAPI_OPERATION_ADD, DSE_FLAG_PREOP, dn, LDAP_SCOPE_SUBTREE, "(objectclass=*)", task_deny, NULL); #endif @@ -117,8 +511,13 @@ destroy_task(time_t when, void *arg) Slapi_Task *t1; Slapi_PBlock *pb = slapi_pblock_new(); - if (task->destructor != NULL) + /* Call the custom destructor callback if one was provided, + * then perform the internal task destruction. */ + if (task->destructor != NULL) { (*task->destructor)(task); + } + + task_generic_destructor(task); /* if when == 0, we're already locked (called during shutdown) */ if (when != 0) { @@ -141,45 +540,16 @@ destroy_task(time_t when, void *arg) slapi_config_remove_callback(SLAPI_OPERATION_MODIFY, DSE_FLAG_PREOP, task->task_dn, LDAP_SCOPE_BASE, "(objectclass=*)", task_modify); slapi_config_remove_callback(SLAPI_OPERATION_DELETE, DSE_FLAG_PREOP, - task->task_dn, LDAP_SCOPE_BASE, "(objectclass=*)", task_deny); - slapi_delete_internal_set_pb(pb, task->task_dn, NULL, NULL, - (void *)plugin_get_default_component_id(), 0); - - slapi_delete_internal_pb(pb); - slapi_pblock_destroy(pb); - - slapi_ch_free((void **)&task->task_dn); - slapi_ch_free((void **)&task); -} - -/* - * slapi_new_task: create a new task, fill in DN, and setup modify callback - * argument: - * dn: task dn - * result: - * Success: Slapi_Task object - * Failure: NULL - */ -Slapi_Task * -slapi_new_task(const char *dn) -{ - return new_task(dn); -} - -/* slapi_destroy_task: destroy a task - * argument: - * task: task to destroy - * result: - * none - */ -void -slapi_destroy_task(void *arg) -{ - destroy_task(1, arg); -} + task->task_dn, LDAP_SCOPE_BASE, "(objectclass=*)", task_deny); + slapi_delete_internal_set_pb(pb, task->task_dn, NULL, NULL, + (void *)plugin_get_default_component_id(), 0); -/********** some useful helper functions **********/ + slapi_delete_internal_pb(pb); + slapi_pblock_destroy(pb); + slapi_ch_free((void **)&task->task_dn); + slapi_ch_free((void **)&task); +} /* extract a single value from the entry (as a string) -- if it's not in the * entry, the default will be returned (which can be NULL). @@ -268,81 +638,7 @@ static void modify_internal_entry(char *dn, LDAPMod **mods) } while (ret != LDAP_SUCCESS); } - -/********** helper functions for dealing with task logging **********/ - -#define LOG_BUFFER 256 -/* if the cumul. log gets larger than this, it's truncated: */ -#define MAX_SCROLLBACK_BUFFER 8192 - -/* this changes the 'nsTaskStatus' value, which is transient (anything logged - * here wipes out any previous status) - */ -void slapi_task_log_status(Slapi_Task *task, char *format, ...) -{ - va_list ap; - - if (! task->task_status) - task->task_status = (char *)slapi_ch_malloc(10 * LOG_BUFFER); - if (! task->task_status) - return; /* out of memory? */ - - va_start(ap, format); - PR_vsnprintf(task->task_status, (10 * LOG_BUFFER), format, ap); - va_end(ap); - slapi_task_status_changed(task); -} - -/* this adds a line to the 'nsTaskLog' value, which is cumulative (anything - * logged here is added to the end) - */ -void slapi_task_log_notice(Slapi_Task *task, char *format, ...) -{ - va_list ap; - char buffer[LOG_BUFFER]; - size_t len; - - va_start(ap, format); - PR_vsnprintf(buffer, LOG_BUFFER, format, ap); - va_end(ap); - - len = 2 + strlen(buffer) + (task->task_log ? strlen(task->task_log) : 0); - if ((len > MAX_SCROLLBACK_BUFFER) && task->task_log) { - size_t i; - char *newbuf; - - /* start from middle of buffer, and find next linefeed */ - i = strlen(task->task_log)/2; - while (task->task_log[i] && (task->task_log[i] != '\n')) - i++; - if (task->task_log[i]) - i++; - len = strlen(task->task_log) - i + 2 + strlen(buffer); - newbuf = (char *)slapi_ch_malloc(len); - if (! newbuf) - return; /* out of memory? */ - strcpy(newbuf, task->task_log + i); - slapi_ch_free((void **)&task->task_log); - task->task_log = newbuf; - } else { - if (! task->task_log) { - task->task_log = (char *)slapi_ch_malloc(len); - task->task_log[0] = 0; - } else { - task->task_log = (char *)slapi_ch_realloc(task->task_log, len); - } - if (! task->task_log) - return; /* out of memory? */ - } - - if (task->task_log[0]) - strcat(task->task_log, "\n"); - strcat(task->task_log, buffer); - - slapi_task_status_changed(task); -} - -static int task_generic_destructor(Slapi_Task *task) +static void task_generic_destructor(Slapi_Task *task) { if (task->task_log) { slapi_ch_free((void **)&task->task_log); @@ -351,7 +647,6 @@ static int task_generic_destructor(Slapi_Task *task) slapi_ch_free((void **)&task->task_status); } task->task_log = task->task_status = NULL; - return 0; } @@ -553,13 +848,12 @@ static int task_import_add(Slapi_PBlock *pb, Slapi_Entry *e, } /* allocate new task now */ - task = new_task(slapi_entry_get_ndn(e)); + task = slapi_new_task(slapi_entry_get_ndn(e)); if (task == NULL) { LDAPDebug(LDAP_DEBUG_ANY, "unable to allocate new task!\n", 0, 0, 0); rv = LDAP_OPERATIONS_ERROR; goto out; } - task->task_state = SLAPI_TASK_SETUP; memset(&mypb, 0, sizeof(mypb)); mypb.pb_backend = be; @@ -575,7 +869,7 @@ static int task_import_add(Slapi_PBlock *pb, Slapi_Entry *e, mypb.pb_ldif_include = include; mypb.pb_ldif_exclude = exclude; mypb.pb_task = task; - mypb.pb_task_flags = TASK_RUNNING_AS_TASK; + mypb.pb_task_flags = SLAPI_TASK_RUNNING_AS_TASK; if (NULL != encrypt_on_import && 0 == strcasecmp(encrypt_on_import, "true") ) { mypb.pb_ldif_encrypt = 1; } @@ -618,10 +912,7 @@ static void task_export_thread(void *arg) g_incr_active_threadcnt(); for (count = 0, inp = instance_names; *inp; inp++, count++) ; - task->task_work = count; - task->task_progress = 0; - task->task_state = SLAPI_TASK_RUNNING; - slapi_task_status_changed(task); + slapi_task_begin(task, count); for (inp = instance_names; *inp; inp++) { int release_me = 0; @@ -693,8 +984,7 @@ static void task_export_thread(void *arg) if (rv != 0) break; - task->task_progress++; - slapi_task_status_changed(task); + slapi_task_inc_progress(task); } /* free the memory now */ @@ -712,9 +1002,7 @@ static void task_export_thread(void *arg) LDAPDebug(LDAP_DEBUG_ANY, "Export failed.\n", 0, 0, 0); } - task->task_exitcode = rv; - task->task_state = SLAPI_TASK_FINISHED; - slapi_task_status_changed(task); + slapi_task_finish(task, rv); g_decr_active_threadcnt(); } @@ -888,16 +1176,13 @@ static int task_export_add(Slapi_PBlock *pb, Slapi_Entry *e, } /* allocate new task now */ - task = new_task(slapi_entry_get_ndn(e)); + task = slapi_new_task(slapi_entry_get_ndn(e)); if (task == NULL) { LDAPDebug(LDAP_DEBUG_ANY, "unable to allocate new task!\n", 0, 0, 0); *returncode = LDAP_OPERATIONS_ERROR; rv = SLAPI_DSE_CALLBACK_ERROR; goto out; } - task->task_state = SLAPI_TASK_SETUP; - task->task_work = instance_cnt; - task->task_progress = 0; mypb = slapi_pblock_new(); if (mypb == NULL) { @@ -914,7 +1199,7 @@ static int task_export_add(Slapi_PBlock *pb, Slapi_Entry *e, /* horrible hack */ mypb->pb_instance_name = (char *)instance_names; mypb->pb_task = task; - mypb->pb_task_flags = TASK_RUNNING_AS_TASK; + mypb->pb_task_flags = SLAPI_TASK_RUNNING_AS_TASK; if (NULL != decrypt_on_export && 0 == strcasecmp(decrypt_on_export, "true") ) { mypb->pb_ldif_encrypt = 1; } @@ -957,10 +1242,7 @@ static void task_backup_thread(void *arg) int rv; g_incr_active_threadcnt(); - task->task_work = 1; - task->task_progress = 0; - task->task_state = SLAPI_TASK_RUNNING; - slapi_task_status_changed(task); + slapi_task_begin(task, 1); slapi_task_log_notice(task, "Beginning backup of '%s'", pb->pb_plugin->plg_name); @@ -978,11 +1260,7 @@ static void task_backup_thread(void *arg) LDAPDebug(LDAP_DEBUG_ANY, "Backup finished.\n", 0, 0, 0); } - task->task_progress = 1; - task->task_exitcode = rv; - task->task_state = SLAPI_TASK_FINISHED; - slapi_task_status_changed(task); - + slapi_task_finish(task, rv); slapi_ch_free((void **)&pb->pb_seq_val); slapi_pblock_destroy(pb); g_decr_active_threadcnt(); @@ -1048,16 +1326,13 @@ static int task_backup_add(Slapi_PBlock *pb, Slapi_Entry *e, } /* allocate new task now */ - task = new_task(slapi_entry_get_ndn(e)); + task = slapi_new_task(slapi_entry_get_ndn(e)); if (task == NULL) { LDAPDebug(LDAP_DEBUG_ANY, "unable to allocate new task!\n", 0, 0, 0); *returncode = LDAP_OPERATIONS_ERROR; rv = SLAPI_DSE_CALLBACK_ERROR; goto out; } - task->task_state = SLAPI_TASK_SETUP; - task->task_work = 1; - task->task_progress = 0; mypb = slapi_pblock_new(); if (mypb == NULL) { @@ -1068,7 +1343,7 @@ static int task_backup_add(Slapi_PBlock *pb, Slapi_Entry *e, mypb->pb_seq_val = slapi_ch_strdup(archive_dir); mypb->pb_plugin = be->be_database; mypb->pb_task = task; - mypb->pb_task_flags = TASK_RUNNING_AS_TASK; + mypb->pb_task_flags = SLAPI_TASK_RUNNING_AS_TASK; /* start the backup as a separate thread */ thread = PR_CreateThread(PR_USER_THREAD, task_backup_thread, @@ -1102,10 +1377,7 @@ static void task_restore_thread(void *arg) int rv; g_incr_active_threadcnt(); - task->task_work = 1; - task->task_progress = 0; - task->task_state = SLAPI_TASK_RUNNING; - slapi_task_status_changed(task); + slapi_task_begin(task, 1); slapi_task_log_notice(task, "Beginning restore to '%s'", pb->pb_plugin->plg_name); @@ -1123,11 +1395,7 @@ static void task_restore_thread(void *arg) LDAPDebug(LDAP_DEBUG_ANY, "Restore finished.\n", 0, 0, 0); } - task->task_progress = 1; - task->task_exitcode = rv; - task->task_state = SLAPI_TASK_FINISHED; - slapi_task_status_changed(task); - + slapi_task_finish(task, rv); slapi_ch_free((void **)&pb->pb_seq_val); slapi_pblock_destroy(pb); g_decr_active_threadcnt(); @@ -1199,16 +1467,13 @@ static int task_restore_add(Slapi_PBlock *pb, Slapi_Entry *e, } /* allocate new task now */ - task = new_task(slapi_entry_get_ndn(e)); + task = slapi_new_task(slapi_entry_get_ndn(e)); if (task == NULL) { LDAPDebug(LDAP_DEBUG_ANY, "unable to allocate new task!\n", 0, 0, 0); *returncode = LDAP_OPERATIONS_ERROR; rv = SLAPI_DSE_CALLBACK_ERROR; goto out; } - task->task_state = SLAPI_TASK_SETUP; - task->task_work = 1; - task->task_progress = 0; mypb = slapi_pblock_new(); if (mypb == NULL) { @@ -1221,7 +1486,7 @@ static int task_restore_add(Slapi_PBlock *pb, Slapi_Entry *e, if (NULL != instance_name) mypb->pb_instance_name = slapi_ch_strdup(instance_name); mypb->pb_task = task; - mypb->pb_task_flags = TASK_RUNNING_AS_TASK; + mypb->pb_task_flags = SLAPI_TASK_RUNNING_AS_TASK; /* start the restore as a separate thread */ thread = PR_CreateThread(PR_USER_THREAD, task_restore_thread, @@ -1255,10 +1520,7 @@ static void task_index_thread(void *arg) int rv; g_incr_active_threadcnt(); - task->task_work = 1; - task->task_progress = 0; - task->task_state = SLAPI_TASK_RUNNING; - slapi_task_status_changed(task); + slapi_task_begin(task, 1); rv = (*pb->pb_plugin->plg_db2index)(pb); if (rv != 0) { @@ -1267,11 +1529,7 @@ static void task_index_thread(void *arg) LDAPDebug(LDAP_DEBUG_ANY, "Index failed (error %d)\n", rv, 0, 0); } - task->task_progress = task->task_work; - task->task_exitcode = rv; - task->task_state = SLAPI_TASK_FINISHED; - slapi_task_status_changed(task); - + slapi_task_finish(task, rv); charray_free(pb->pb_db2index_attrs); slapi_ch_free((void **)&pb->pb_instance_name); slapi_pblock_destroy(pb); @@ -1353,16 +1611,13 @@ static int task_index_add(Slapi_PBlock *pb, Slapi_Entry *e, } /* allocate new task now */ - task = new_task(slapi_entry_get_ndn(e)); + task = slapi_new_task(slapi_entry_get_ndn(e)); if (task == NULL) { LDAPDebug(LDAP_DEBUG_ANY, "unable to allocate new task!\n", 0, 0, 0); *returncode = LDAP_OPERATIONS_ERROR; rv = SLAPI_DSE_CALLBACK_ERROR; goto out; } - task->task_state = SLAPI_TASK_SETUP; - task->task_work = 1; - task->task_progress = 0; mypb = slapi_pblock_new(); if (mypb == NULL) { @@ -1375,7 +1630,7 @@ static int task_index_add(Slapi_PBlock *pb, Slapi_Entry *e, mypb->pb_instance_name = slapi_ch_strdup(instance_name); mypb->pb_db2index_attrs = indexlist; mypb->pb_task = task; - mypb->pb_task_flags = TASK_RUNNING_AS_TASK; + mypb->pb_task_flags = SLAPI_TASK_RUNNING_AS_TASK; /* start the db2index as a separate thread */ thread = PR_CreateThread(PR_USER_THREAD, task_index_thread, @@ -1460,14 +1715,14 @@ task_upgradedb_add(Slapi_PBlock *pb, Slapi_Entry *e, Slapi_Entry *eAfter, } /* allocate new task now */ - task = new_task(slapi_entry_get_ndn(e)); + task = slapi_new_task(slapi_entry_get_ndn(e)); if (task == NULL) { LDAPDebug(LDAP_DEBUG_ANY, "unable to allocate new task!\n", 0, 0, 0); *returncode = LDAP_OPERATIONS_ERROR; rv = SLAPI_DSE_CALLBACK_ERROR; goto out; } - task->task_state = SLAPI_TASK_SETUP; + /* NGK - This could use some cleanup to use the SLAPI task API, such as slapi_task_begin() */ task->task_work = 1; task->task_progress = 0; @@ -1478,7 +1733,7 @@ task_upgradedb_add(Slapi_PBlock *pb, Slapi_Entry *e, Slapi_Entry *eAfter, mypb.pb_seq_type = SLAPI_UPGRADEDB_FORCE; /* force; reindex all regardless the dbversion */ mypb.pb_seq_val = slapi_ch_strdup(archive_dir); mypb.pb_task = task; - mypb.pb_task_flags = TASK_RUNNING_AS_TASK; + mypb.pb_task_flags = SLAPI_TASK_RUNNING_AS_TASK; rv = (mypb.pb_plugin->plg_upgradedb)(&mypb); if (rv == 0) { @@ -1502,76 +1757,6 @@ out: return SLAPI_DSE_CALLBACK_OK; } -/* update attributes in the entry under "cn=tasks" to match the current - * status of the task. - */ -#define NEXTMOD(_type, _val) do { \ - modlist[cur].mod_op = LDAP_MOD_REPLACE; \ - modlist[cur].mod_type = (_type); \ - modlist[cur].mod_values = (char **)slapi_ch_malloc(2*sizeof(char *)); \ - modlist[cur].mod_values[0] = (_val); \ - modlist[cur].mod_values[1] = NULL; \ - mod[cur] = &modlist[cur]; \ - cur++; \ -} while (0) -void slapi_task_status_changed(Slapi_Task *task) -{ - LDAPMod modlist[20]; - LDAPMod *mod[20]; - int cur = 0, i; - char s1[20], s2[20], s3[20]; - - if (shutting_down) { - /* don't care about task status updates anymore */ - return; - } - - NEXTMOD(TASK_LOG_NAME, task->task_log); - NEXTMOD(TASK_STATUS_NAME, task->task_status); - sprintf(s1, "%d", task->task_exitcode); - sprintf(s2, "%d", task->task_progress); - sprintf(s3, "%d", task->task_work); - NEXTMOD(TASK_PROGRESS_NAME, s2); - NEXTMOD(TASK_WORK_NAME, s3); - /* only add the exit code when the job is done */ - if ((task->task_state == SLAPI_TASK_FINISHED) || - (task->task_state == SLAPI_TASK_CANCELLED)) { - NEXTMOD(TASK_EXITCODE_NAME, s1); - /* make sure the console can tell the task has ended */ - if (task->task_progress != task->task_work) { - task->task_progress = task->task_work; - } - } - - mod[cur] = NULL; - modify_internal_entry(task->task_dn, mod); - - for (i = 0; i < cur; i++) - slapi_ch_free((void **)&modlist[i].mod_values); - - if ((task->task_state == SLAPI_TASK_FINISHED) && - !(task->task_flags & SLAPI_TASK_DESTROYING)) { - Slapi_PBlock *pb = slapi_pblock_new(); - Slapi_Entry *e; - int ttl; - time_t expire; - - e = get_internal_entry(pb, task->task_dn); - if (e == NULL) - return; - ttl = atoi(fetch_attr(e, "ttl", DEFAULT_TTL)); - if (ttl > 3600) - ttl = 3600; /* be reasonable. */ - expire = time(NULL) + ttl; - task->task_flags |= SLAPI_TASK_DESTROYING; - /* queue an event to destroy the state info */ - slapi_eq_once(destroy_task, (void *)task, expire); - - slapi_free_search_results_internal(pb); - slapi_pblock_destroy(pb); - } -} - /* cleanup old tasks that may still be in the DSE from a previous session * (this can happen if the server crashes [no matter how unlikely we like * to think that is].) @@ -1636,84 +1821,6 @@ void task_cleanup(void) slapi_pblock_destroy(pb); } -/* name is, for exmaple, "import" */ -int slapi_task_register_handler(const char *name, dseCallbackFn func) -{ - char *dn = NULL; - Slapi_PBlock *pb = NULL; - Slapi_Operation *op; - LDAPMod *mods[3]; - LDAPMod mod[3]; - const char *objectclass[3]; - const char *cnvals[2]; - int ret = -1; - int x; - - dn = slapi_ch_smprintf("cn=%s, %s", name, TASK_BASE_DN); - if (dn == NULL) { - goto out; - } - - pb = slapi_pblock_new(); - if (pb == NULL) { - goto out; - } - - /* this is painful :( */ - mods[0] = &mod[0]; - mod[0].mod_op = LDAP_MOD_ADD; - mod[0].mod_type = "objectClass"; - mod[0].mod_values = (char **)objectclass; - objectclass[0] = "top"; - objectclass[1] = "extensibleObject"; - objectclass[2] = NULL; - mods[1] = &mod[1]; - mod[1].mod_op = LDAP_MOD_ADD; - mod[1].mod_type = "cn"; - mod[1].mod_values = (char **)cnvals; - cnvals[0] = name; - cnvals[1] = NULL; - mods[2] = NULL; - slapi_add_internal_set_pb(pb, dn, mods, NULL, - plugin_get_default_component_id(), 0); - x = 1; - slapi_pblock_set(pb, SLAPI_DSE_DONT_WRITE_WHEN_ADDING, &x); - /* Make sure these adds don't appear in the audit and change logs */ - slapi_pblock_get(pb, SLAPI_OPERATION, &op); - operation_set_flag(op, OP_FLAG_ACTION_NOLOG); - - slapi_add_internal_pb(pb); - slapi_pblock_get(pb, SLAPI_PLUGIN_INTOP_RESULT, &x); - if ((x != LDAP_SUCCESS) && (x != LDAP_ALREADY_EXISTS)) { - LDAPDebug(LDAP_DEBUG_ANY, - "Can't create task node '%s' (error %d)\n", - name, x, 0); - ret = x; - goto out; - } - - /* register add callback */ - slapi_config_register_callback(SLAPI_OPERATION_ADD, DSE_FLAG_PREOP, - dn, LDAP_SCOPE_SUBTREE, "(objectclass=*)", func, NULL); - /* deny modify/delete of the root task entry */ - slapi_config_register_callback(SLAPI_OPERATION_MODIFY, DSE_FLAG_PREOP, - dn, LDAP_SCOPE_BASE, "(objectclass=*)", task_deny, NULL); - slapi_config_register_callback(SLAPI_OPERATION_DELETE, DSE_FLAG_PREOP, - dn, LDAP_SCOPE_BASE, "(objectclass=*)", task_deny, NULL); - - ret = 0; - -out: - if (dn) { - slapi_ch_free((void **)&dn); - } - if (pb) { - slapi_pblock_destroy(pb); - } - return ret; -} - - void task_init(void) { global_task_lock = PR_NewLock(); diff --git a/ldap/servers/slapd/test-plugins/sampletask.c b/ldap/servers/slapd/test-plugins/sampletask.c index 94f1ade80..357ed5ca2 100644 --- a/ldap/servers/slapd/test-plugins/sampletask.c +++ b/ldap/servers/slapd/test-plugins/sampletask.c @@ -47,7 +47,7 @@ * objectClass: nsSlapdPlugin * objectClass: extensibleObject * cn: sampletask - * nsslapd-pluginPath: <prefix>/usr/lib/<PACKAGE_NAME>/plugins/libsampletask-plugin.so + * nsslapd-pluginPath: libsampletask-plugin * nsslapd-pluginInitfunc: sampletask_init * nsslapd-pluginType: object * nsslapd-pluginEnabled: on @@ -58,26 +58,26 @@ * * 4. create a config task entry in dse.ldif * Task entry: - * dn: cn=sample task, cn=tasks, cn=config + * dn: cn=sampletask, cn=tasks, cn=config * objectClass: top * objectClass: extensibleObject - * cn: sample task + * cn: sampletask * * 5. to invoke the sample task, run the command line: * $ ./ldapmodify -h <host> -p <port> -D "cn=Directory Manager" -w <pw> -a - * dn: cn=sample task 0, cn=sample task, cn=tasks, cn=config + * dn: cn=sampletask 0, cn=sample task, cn=tasks, cn=config * objectClass: top * objectClass: extensibleObject * cn: sample task 0 - * arg0: sample task arg0 + * myarg: sample task myarg * * Result is in the errors log - * [...] - Sample task starts (arg: sample task arg0) ... + * [...] - Sample task starts (arg: sample task myarg) ... * [...] - Sample task finished. */ -#include "slap.h" -#include "slapi-private.h" +#include "slapi-plugin.h" +#include "nspr.h" static int task_sampletask_add(Slapi_PBlock *pb, Slapi_Entry *e, Slapi_Entry *eAfter, int *returncode, char *returntext, @@ -118,33 +118,32 @@ task_sampletask_start(Slapi_PBlock *pb) static void task_sampletask_thread(void *arg) { - Slapi_PBlock *pb = (Slapi_PBlock *)arg; - Slapi_Task *task = pb->pb_task; - int rv; - - task->task_work = 1; - task->task_progress = 0; - task->task_state = SLAPI_TASK_RUNNING; - slapi_task_status_changed(task); - - slapi_task_log_notice(task, "Sample task starts (arg: %s) ...\n", - pb->pb_seq_val); - LDAPDebug(LDAP_DEBUG_ANY, "Sample task starts (arg: %s) ...\n", - pb->pb_seq_val, 0, 0); - /* do real work */ - rv = 0; + Slapi_Task *task = (Slapi_Task *)arg; + char *myarg = NULL; + int i, rv = 0; + int total_work = 3; + + /* fetch our argument from the task */ + myarg = (char *)slapi_task_get_data(task); + + /* update task state to show it's running */ + slapi_task_begin(task, total_work); + slapi_task_log_notice(task, "Sample task starts (arg: %s) ...\n", myarg); + slapi_log_error(SLAPI_LOG_FATAL, "sampletask", "Sample task starts (arg: %s) ...\n", myarg); + + /* real work would be done here */ + for (i = 0; i < total_work; i++) { + PR_Sleep(10000); + slapi_task_inc_progress(task); + } + /* update task state to say we're finished */ slapi_task_log_notice(task, "Sample task finished."); slapi_task_log_status(task, "Sample task finished."); - LDAPDebug(LDAP_DEBUG_ANY, "Sample task finished.\n", 0, 0, 0); - - task->task_progress = 1; - task->task_exitcode = rv; - task->task_state = SLAPI_TASK_FINISHED; - slapi_task_status_changed(task); + slapi_log_error(SLAPI_LOG_FATAL, "sampletask", "Sample task finished.\n"); - slapi_ch_free((void **)&pb->pb_seq_val); - slapi_pblock_destroy(pb); + /* this will queue the destruction of the task */ + slapi_task_finish(task, rv); } /* extract a single value from the entry (as a string) -- if it's not in the @@ -163,6 +162,17 @@ static const char *fetch_attr(Slapi_Entry *e, const char *attrname, return slapi_value_get_string(val); } +static void +task_sampletask_destructor(Slapi_Task *task) +{ + if (task) { + char *myarg = (char *)slapi_task_get_data(task); + if (myarg) { + slapi_ch_free_string(&myarg); + } + } +} + /* * Invoked when the task instance is added by the client (step 5 of the comment) * Get the necessary attributes from the task entry, and spawns a thread to do @@ -178,7 +188,7 @@ task_sampletask_add(Slapi_PBlock *pb, Slapi_Entry *e, int rv = SLAPI_DSE_CALLBACK_OK; Slapi_PBlock *mypb = NULL; Slapi_Task *task = NULL; - const char *arg0; + const char *myarg; *returncode = LDAP_SUCCESS; if ((cn = fetch_attr(e, "cn", NULL)) == NULL) { @@ -188,7 +198,7 @@ task_sampletask_add(Slapi_PBlock *pb, Slapi_Entry *e, } /* get arg(s) */ - if ((arg0 = fetch_attr(e, "arg0", NULL)) == NULL) { + if ((myarg = fetch_attr(e, "myarg", NULL)) == NULL) { *returncode = LDAP_OBJECT_CLASS_VIOLATION; rv = SLAPI_DSE_CALLBACK_ERROR; goto out; @@ -197,46 +207,33 @@ task_sampletask_add(Slapi_PBlock *pb, Slapi_Entry *e, /* allocate new task now */ task = slapi_new_task(slapi_entry_get_ndn(e)); if (task == NULL) { - LDAPDebug(LDAP_DEBUG_ANY, "unable to allocate new task!\n", 0, 0, 0); + slapi_log_error(SLAPI_LOG_FATAL, "sampletask", "unable to allocate new task!\n"); *returncode = LDAP_OPERATIONS_ERROR; rv = SLAPI_DSE_CALLBACK_ERROR; goto out; } - task->task_state = SLAPI_TASK_SETUP; - task->task_work = 1; - task->task_progress = 0; - /* create a pblock to pass the necessary info to the task thread */ - mypb = slapi_pblock_new(); - if (mypb == NULL) { - *returncode = LDAP_OPERATIONS_ERROR; - rv = SLAPI_DSE_CALLBACK_ERROR; - goto out; - } - mypb->pb_seq_val = slapi_ch_strdup(arg0); - mypb->pb_task = task; - mypb->pb_task_flags = TASK_RUNNING_AS_TASK; + /* set a destructor that will clean up myarg for us when the task is complete */ + slapi_task_set_destructor_fn(task, task_sampletask_destructor); + + /* Stash our argument in the task for use by the task thread */ + slapi_task_set_data(task, slapi_ch_strdup(myarg)); /* start the sample task as a separate thread */ thread = PR_CreateThread(PR_USER_THREAD, task_sampletask_thread, - (void *)mypb, PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, + (void *)task, PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, PR_UNJOINABLE_THREAD, SLAPD_DEFAULT_THREAD_STACKSIZE); if (thread == NULL) { - LDAPDebug(LDAP_DEBUG_ANY, - "unable to create sample task thread!\n", 0, 0, 0); + slapi_log_error(SLAPI_LOG_FATAL, "sampletask", + "unable to create sample task thread!\n"); *returncode = LDAP_OPERATIONS_ERROR; rv = SLAPI_DSE_CALLBACK_ERROR; - slapi_ch_free((void **)&mypb->pb_seq_val); - slapi_pblock_destroy(mypb); - goto out; + slapi_task_finish(task, *returncode); + } else { + /* thread successful */ + rv = SLAPI_DSE_CALLBACK_OK; } - /* thread successful -- don't free the pb, let the thread do that. */ - return SLAPI_DSE_CALLBACK_OK; - out: - if (task) { - slapi_destroy_task(task); - } return rv; }
0
c9d65282d05f1b543e171e4b81efb9a4789e778b
389ds/389-ds-base
Ticket 50306 - Move connection config inside struct Description: We are constantly calling configuration get functions during a connection. These calls are expensive, so we should just store all these settings in the conn struct during handle_new_connection() https://pagure.io/389-ds-base/issue/50306 Reviewed by: firstyear(Thanks!)
commit c9d65282d05f1b543e171e4b81efb9a4789e778b Author: Mark Reynolds <[email protected]> Date: Fri Mar 29 12:52:59 2019 -0400 Ticket 50306 - Move connection config inside struct Description: We are constantly calling configuration get functions during a connection. These calls are expensive, so we should just store all these settings in the conn struct during handle_new_connection() https://pagure.io/389-ds-base/issue/50306 Reviewed by: firstyear(Thanks!) diff --git a/dirsrvtests/tests/stress/reliabilty/reliab_conn_test.py b/dirsrvtests/tests/stress/reliabilty/reliab_conn_test.py index c14f88d6f..fbe714259 100644 --- a/dirsrvtests/tests/stress/reliabilty/reliab_conn_test.py +++ b/dirsrvtests/tests/stress/reliabilty/reliab_conn_test.py @@ -6,20 +6,16 @@ import logging import pytest import signal import threading -from lib389 import DirSrv from lib389.tools import DirSrvTools from lib389._constants import * from lib389.properties import * from lib389.tasks import * from lib389.utils import * from lib389.idm.directorymanager import DirectoryManager +from lib389.idm.user import UserAccounts +from lib389.topologies import topology_st -DEBUGGING = os.getenv('DEBUGGING', default=False) - -if DEBUGGING: - logging.getLogger(__name__).setLevel(logging.DEBUG) -else: - logging.getLogger(__name__).setLevel(logging.INFO) +logging.getLogger(__name__).setLevel(logging.DEBUG) log = logging.getLogger(__name__) MAX_CONNS = 10000000 @@ -27,45 +23,7 @@ MAX_THREADS = 20 STOP = False HOSTNAME = DirSrvTools.getLocalhost() PORT = 389 - - -class TopologyStandalone(object): - """The DS Topology Class""" - def __init__(self, standalone): - """Init""" - standalone.open() - self.standalone = standalone - - [email protected](scope="module") -def topology(request): - """Create DS Deployment""" - - # Creating standalone instance ... - standalone = DirSrv(verbose=DEBUGGING) - args_instance[SER_HOST] = HOST_STANDALONE - args_instance[SER_PORT] = PORT_STANDALONE - args_instance[SER_SECURE_PORT] = SECUREPORT_STANDALONE - args_instance[SER_SERVERID_PROP] = SERVERID_STANDALONE - args_instance[SER_CREATION_SUFFIX] = DEFAULT_SUFFIX - args_standalone = args_instance.copy() - standalone.allocate(args_standalone) - instance_standalone = standalone.exists() - if instance_standalone: - standalone.delete() - standalone.create() - standalone.open() - - def fin(): - """If we are debugging just stop the instances, otherwise remove them - """ - if DEBUGGING: - standalone.stop() - else: - standalone.delete() - request.addfinalizer(fin) - - return TopologyStandalone(standalone) +NUNC_STANS = False def signalHandler(signal, frame): @@ -81,35 +39,15 @@ def init(inst): """Set the idle timeout, and add sample entries """ - try: - inst.modify_s(DN_CONFIG, [(ldap.MOD_REPLACE, - 'nsslapd-idletimeout', - '5')]) - except ldap.LDAPError as e: - log.fatal('Failed to set idletimeout: ' + str(e)) - assert False - - try: - inst.modify_s(DN_CONFIG, [(ldap.MOD_REPLACE, - 'nsslapd-enable-nunc-stans', - 'on')]) - except ldap.LDAPError as e: - log.fatal('Failed to enable nunc-stans: ' + str(e)) - assert False + inst.config.set('nsslapd-idletimeout', '5') + if NUNC_STANS: + inst.config.set('nsslapd-enable-nunc-stans', 'on') + inst.restart() + users = UserAccounts(inst, DEFAULT_SUFFIX) for idx in range(0, 9): - user_dn = 'uid=entry%d,%s' % (idx, DEFAULT_SUFFIX) - try: - inst.add_s(Entry((user_dn, - {'objectclass': ['top', 'extensibleObject'], - 'uid': 'entry%d' % idx, - 'cn': 'entry%d' % idx, - 'userpassword': 'password'}))) - except ldap.LDAPError as e: - log.fatal('Failed to add user entry (%s): %s' % (user_dn, str(e))) - assert False - - inst.restart() + user = users.create_test_user(uid=str(idx), gid=str(idx)) + user.reset_password('password') class BindOnlyConn(threading.Thread): @@ -146,7 +84,7 @@ class IdleConn(threading.Thread): """This class opens and closes connections """ def __init__(self, inst): - """Initialize the thread class withte server isntance info""" + """Initialize the thread class with the server instance info""" threading.Thread.__init__(self) self.daemon = True self.inst = inst @@ -160,7 +98,7 @@ class IdleConn(threading.Thread): while idx < (MAX_CONNS / 10) and not STOP: try: conn = self.inst.clone() - conn.simple_bind_s('uid=entry0,dc=example,dc=com', 'password') + conn.simple_bind_s('uid=test_user_0,dc=example,dc=com', 'password') conn.search_s('dc=example,dc=com', ldap.SCOPE_SUBTREE, 'uid=*') time.sleep(10) @@ -217,7 +155,7 @@ class LongConn(threading.Thread): idx += 1 -def test_connection_load(topology): +def test_connection_load(topology_st): """Send the server a variety of connections using many threads: - Open, Bind, Close - Open, Bind, Search, wait to trigger idletimeout, Search, Close @@ -229,7 +167,7 @@ def test_connection_load(topology): # Set the config and add sample entries log.info('Initializing setup...') - init(topology.standalone) + init(topology_st.standalone) # # Bind/Unbind Conn Threads @@ -238,7 +176,7 @@ def test_connection_load(topology): threads = [] idx = 0 while idx < MAX_THREADS: - threads.append(BindOnlyConn(topology.standalone)) + threads.append(BindOnlyConn(topology_st.standalone)) idx += 1 for thread in threads: thread.start() @@ -251,7 +189,7 @@ def test_connection_load(topology): idx = 0 idle_threads = [] while idx < MAX_THREADS: - idle_threads.append(IdleConn(topology.standalone)) + idle_threads.append(IdleConn(topology_st.standalone)) idx += 1 for thread in idle_threads: thread.start() @@ -264,7 +202,7 @@ def test_connection_load(topology): idx = 0 long_threads = [] while idx < MAX_THREADS: - long_threads.append(LongConn(topology.standalone)) + long_threads.append(LongConn(topology_st.standalone)) idx += 1 for thread in long_threads: thread.start() @@ -285,4 +223,3 @@ if __name__ == '__main__': # -s for DEBUG mode CURRENT_FILE = os.path.realpath(__file__) pytest.main("-s %s" % CURRENT_FILE) - diff --git a/dirsrvtests/tests/suites/dynamic_plugins/stress_tests.py b/dirsrvtests/tests/suites/dynamic_plugins/stress_tests.py index b4d3e347d..05c642a92 100644 --- a/dirsrvtests/tests/suites/dynamic_plugins/stress_tests.py +++ b/dirsrvtests/tests/suites/dynamic_plugins/stress_tests.py @@ -15,7 +15,7 @@ import logging import threading import ldap -from lib389 import DirSrv, Entry +from lib389 import Entry from lib389._constants import * from lib389.properties import * from lib389.plugins import ReferentialIntegrityPlugin, MemberOfPlugin diff --git a/ldap/servers/slapd/connection.c b/ldap/servers/slapd/connection.c index 6582475a9..3a7620b9e 100644 --- a/ldap/servers/slapd/connection.c +++ b/ldap/servers/slapd/connection.c @@ -518,11 +518,11 @@ connection_need_new_password(const Connection *conn, const Operation *op, Slapi_ static void connection_dispatch_operation(Connection *conn, Operation *op, Slapi_PBlock *pb) { - int minssf = config_get_minssf(); - int minssf_exclude_rootdse = 0; + int32_t minssf = conn->c_minssf; + int32_t minssf_exclude_rootdse = conn->c_minssf_exclude_rootdse; #ifdef TCP_CORK - int enable_nagle = config_get_nagle(); - int pop_cork = 0; + int32_t enable_nagle = conn->c_enable_nagle; + int32_t pop_cork = 0; #endif /* Set the connid and op_id to be used by internal op logging */ @@ -552,7 +552,6 @@ connection_dispatch_operation(Connection *conn, Operation *op, Slapi_PBlock *pb) * next step and check if the operation is against rootdse or not. * Once found it's not on rootdse, return LDAP_UNWILLING_TO_PERFORM there. */ - minssf_exclude_rootdse = config_get_minssf_exclude_rootdse(); if (!minssf_exclude_rootdse && (conn->c_sasl_ssf < minssf) && (conn->c_ssl_ssf < minssf) && (conn->c_local_ssf < minssf) && (op->o_tag != LDAP_REQ_BIND) && @@ -580,10 +579,10 @@ connection_dispatch_operation(Connection *conn, Operation *op, Slapi_PBlock *pb) * search. */ if ((slapi_sdn_get_dn(&(op->o_sdn)) == NULL) && /* anon access off and something other than BIND, EXTOP, UNBIND or ABANDON */ - (((config_get_anon_access_switch() == SLAPD_ANON_ACCESS_OFF) && (op->o_tag != LDAP_REQ_BIND) && + (((conn->c_anon_access == SLAPD_ANON_ACCESS_OFF) && (op->o_tag != LDAP_REQ_BIND) && (op->o_tag != LDAP_REQ_EXTENDED) && (op->o_tag != LDAP_REQ_UNBIND) && (op->o_tag != LDAP_REQ_ABANDON)) || /* root DSE access only and something other than BIND, EXTOP, UNBIND, ABANDON, or SEARCH */ - ((config_get_anon_access_switch() == SLAPD_ANON_ACCESS_ROOTDSE) && (op->o_tag != LDAP_REQ_BIND) && + ((conn->c_anon_access == SLAPD_ANON_ACCESS_ROOTDSE) && (op->o_tag != LDAP_REQ_BIND) && (op->o_tag != LDAP_REQ_EXTENDED) && (op->o_tag != LDAP_REQ_UNBIND) && (op->o_tag != LDAP_REQ_ABANDON) && (op->o_tag != LDAP_REQ_SEARCH)))) { slapi_log_access(LDAP_DEBUG_STATS, @@ -1053,7 +1052,7 @@ get_next_from_buffer(void *buffer __attribute__((unused)), size_t buffer_size __ if ((LBER_OVERFLOW == *tagp || LBER_DEFAULT == *tagp) && 0 == bytes_scanned && !SLAPD_SYSTEM_WOULD_BLOCK_ERROR(errno)) { if ((LBER_OVERFLOW == *tagp) || (errno == ERANGE)) { - ber_len_t maxbersize = config_get_maxbersize(); + ber_len_t maxbersize = conn->c_maxbersize; ber_len_t tmplen = 0; (void)_ber_get_len(ber, &tmplen); /* openldap does not differentiate between length == 0 @@ -1176,7 +1175,7 @@ connection_read_operation(Connection *conn, Operation *op, ber_tag_t *tag, int * } /* If we still haven't seen a complete PDU, read from the network */ while (*tag == LBER_DEFAULT) { - int ioblocktimeout_waits = config_get_ioblocktimeout() / CONN_TURBO_TIMEOUT_INTERVAL; + int32_t ioblocktimeout_waits = conn->c_maxbersize / CONN_TURBO_TIMEOUT_INTERVAL; /* We should never get here with data remaining in the buffer */ PR_ASSERT(!new_operation || !conn_buffered_data_avail_nolock(conn, &conn_closed)); /* We make a non-blocking read call */ @@ -1624,7 +1623,7 @@ connection_threadmain() g_decr_active_threadcnt(); return; } - maxthreads = config_get_maxthreadsperconn(); + maxthreads = conn->c_max_threads_per_conn; more_data = 0; ret = connection_read_operation(conn, op, &tag, &more_data); if ((ret == CONN_DONE) || (ret == CONN_TIMEDOUT)) { @@ -2195,9 +2194,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) { - log_ber_too_big_error(conn, ber_len, maxbersize); + if (ber_len > conn->c_maxbersize) { + log_ber_too_big_error(conn, ber_len, conn->c_maxbersize); return 1; } return 0; @@ -2213,7 +2211,7 @@ static void log_ber_too_big_error(const Connection *conn, ber_len_t ber_len, ber_len_t maxbersize) { if (0 == maxbersize) { - maxbersize = config_get_maxbersize(); + maxbersize = conn->c_maxbersize; } if (0 == ber_len) { slapi_log_err(SLAPI_LOG_ERR, "log_ber_too_big_error", diff --git a/ldap/servers/slapd/daemon.c b/ldap/servers/slapd/daemon.c index c77e1f15c..143234492 100644 --- a/ldap/servers/slapd/daemon.c +++ b/ldap/servers/slapd/daemon.c @@ -1368,7 +1368,6 @@ setup_pr_read_pds(Connection_Table *ct, PRFileDesc **n_tcps, PRFileDesc **s_tcps static int last_accept_new_connections = -1; PRIntn count = 0; slapdFrontendConfig_t *slapdFrontendConfig = getFrontendConfig(); - int max_threads_per_conn = config_get_maxthreadsperconn(); size_t n_listeners = 0; accept_new_connections = ((ct->size - g_get_current_conn_count()) > slapdFrontendConfig->reservedescriptors); @@ -1512,7 +1511,7 @@ setup_pr_read_pds(Connection_Table *ct, PRFileDesc **n_tcps, PRFileDesc **s_tcps } else if (c->c_sd == SLAPD_INVALID_SOCKET) { connection_table_move_connection_out_of_active_list(ct, c); } else if (c->c_prfd != NULL) { - if ((!c->c_gettingber) && (c->c_threadnumber < max_threads_per_conn)) { + if ((!c->c_gettingber) && (c->c_threadnumber < c->c_max_threads_per_conn)) { int add_fd = 1; /* check timeout for PAGED RESULTS */ if (pagedresults_is_timedout_nolock(c)) { @@ -1533,7 +1532,7 @@ setup_pr_read_pds(Connection_Table *ct, PRFileDesc **n_tcps, PRFileDesc **s_tcps count++; } } else { - if (c->c_threadnumber >= max_threads_per_conn) { + if (c->c_threadnumber >= c->c_max_threads_per_conn) { c->c_maxthreadsblocked++; } c->c_fdi = SLAPD_INVALID_SOCKET_INDEX; @@ -1566,7 +1565,6 @@ handle_pr_read_ready(Connection_Table *ct, PRIntn num_poll __attribute__((unused { Connection *c; time_t curtime = slapi_current_utc_time(); - int maxthreads = config_get_maxthreadsperconn(); #if LDAP_ERROR_LOGGING if (slapd_ldap_debug & LDAP_DEBUG_CONNS) { @@ -1615,7 +1613,7 @@ handle_pr_read_ready(Connection_Table *ct, PRIntn num_poll __attribute__((unused /* This is where the work happens ! */ /* MAB: 25 jan 01, error handling added */ - if ((connection_activity(c, maxthreads)) == -1) { + if ((connection_activity(c, c->c_max_threads_per_conn)) == -1) { /* This might happen as a result of * trying to acquire a closing connection */ @@ -1855,7 +1853,6 @@ ns_connection_post_io_or_closing(Connection *conn) void ns_handle_pr_read_ready(struct ns_job_t *job) { - int maxthreads = config_get_maxthreadsperconn(); Connection *c = (Connection *)ns_job_get_data(job); PR_EnterMonitor(c->c_mutex); @@ -1906,7 +1903,7 @@ ns_handle_pr_read_ready(struct ns_job_t *job) slapi_log_err(SLAPI_LOG_WARNING, "ns_handle_pr_read_ready", "Received idletime out with c->c_idletimeout as 0. Ignoring.\n"); } ns_handle_closure_nomutex(c); - } else if ((connection_activity(c, maxthreads)) == -1) { + } else if ((connection_activity(c, c->c_max_threads_per_conn)) == -1) { /* This might happen as a result of * trying to acquire a closing connection */ @@ -2384,8 +2381,8 @@ handle_new_connection(Connection_Table *ct, int tcps, PRFileDesc *pr_acceptfd, i /* struct sockaddr_in from;*/ PRNetAddr from = {{0}}; PRFileDesc *pr_clonefd = NULL; - ber_len_t maxbersize; slapdFrontendConfig_t *fecfg = getFrontendConfig(); + int32_t maxbersize; if (newconn) { *newconn = NULL; @@ -2413,6 +2410,15 @@ handle_new_connection(Connection_Table *ct, int tcps, PRFileDesc *pr_acceptfd, i conn->c_prfd = pr_clonefd; conn->c_flags &= ~CONN_FLAG_CLOSING; + /* Set per connection static config */ + conn->c_maxbersize = config_get_maxbersize(); + conn->c_ioblocktimeout = config_get_ioblocktimeout(); + conn->c_minssf = config_get_minssf(); + conn->c_enable_nagle = config_get_nagle(); + conn->c_minssf_exclude_rootdse = config_get_minssf_exclude_rootdse(); + conn->c_anon_access = config_get_anon_access_switch(); + conn->c_max_threads_per_conn = config_get_maxthreadsperconn(); + /* Store the fact that this new connection is an SSL connection */ if (secure) { conn->c_flags |= CONN_FLAG_SSL; @@ -2445,7 +2451,7 @@ handle_new_connection(Connection_Table *ct, int tcps, PRFileDesc *pr_acceptfd, i LBER_SOCKBUF_OPT_EXT_IO_FNS, &func_pointers); } #endif /* !USE_OPENLDAP */ - maxbersize = config_get_maxbersize(); + maxbersize = conn->c_maxbersize; #if defined(USE_OPENLDAP) ber_sockbuf_ctrl(conn->c_sb, LBER_SB_OPT_SET_MAX_INCOMING, &maxbersize); #endif diff --git a/ldap/servers/slapd/slap.h b/ldap/servers/slapd/slap.h index 6b80b3e71..75535711b 100644 --- a/ldap/servers/slapd/slap.h +++ b/ldap/servers/slapd/slap.h @@ -1658,12 +1658,20 @@ typedef struct conn /* IO layer push/pop */ Conn_IO_Layer_cb c_push_io_layer_cb; /* callback to push an IO layer on the conn->c_prfd */ Conn_IO_Layer_cb c_pop_io_layer_cb; /* callback to pop an IO layer off of the conn->c_prfd */ - void *c_io_layer_cb_data; /* callback data */ - struct connection_table *c_ct; /* connection table that this connection belongs to */ - ns_thrpool_t *c_tp; /* thread pool for this connection */ - struct ns_job_t *c_job; /* If it exists, the current ns_job_t */ - int c_ns_close_jobs; /* number of current close jobs */ - char *c_ipaddr; /* ip address str - used by monitor */ + void *c_io_layer_cb_data; /* callback data */ + struct connection_table *c_ct; /* connection table that this connection belongs to */ + ns_thrpool_t *c_tp; /* thread pool for this connection */ + struct ns_job_t *c_job; /* If it exists, the current ns_job_t */ + int c_ns_close_jobs; /* number of current close jobs */ + char *c_ipaddr; /* ip address str - used by monitor */ + /* per conn static config */ + ber_len_t c_maxbersize; + int32_t c_ioblocktimeout; + int32_t c_minssf; + int32_t c_enable_nagle; + int32_t c_minssf_exclude_rootdse; + int32_t c_anon_access; + int32_t c_max_threads_per_conn; } Connection; #define CONN_FLAG_SSL 1 /* Is this connection an SSL connection or not ? \ * Used to direct I/O code when SSL is handled differently \
0
7aabfbda73f1895cd571bec7bc0b4ba418538f47
389ds/389-ds-base
Issue 6422 - test_db_home_dir_online_backup CI test break other tests (#6423) test_db_home_dir_online_backup CI test change the dbhome to a directory that is removed at the test completion but the dbhome is not restored. The solution is to use a python context manager to change and restore the dse.ldif Issue: #6422 Reviewed by: @tbordaz , @droideck (Thanks!)
commit 7aabfbda73f1895cd571bec7bc0b4ba418538f47 Author: progier389 <[email protected]> Date: Fri Nov 29 14:08:03 2024 +0100 Issue 6422 - test_db_home_dir_online_backup CI test break other tests (#6423) test_db_home_dir_online_backup CI test change the dbhome to a directory that is removed at the test completion but the dbhome is not restored. The solution is to use a python context manager to change and restore the dse.ldif Issue: #6422 Reviewed by: @tbordaz , @droideck (Thanks!) diff --git a/dirsrvtests/tests/suites/backups/backup_test.py b/dirsrvtests/tests/suites/backups/backup_test.py index 431dfea0f..e4c17b15a 100644 --- a/dirsrvtests/tests/suites/backups/backup_test.py +++ b/dirsrvtests/tests/suites/backups/backup_test.py @@ -43,6 +43,30 @@ BESTRUCT = [ { "bename" : "be3", "suffix": "dc=be3", "nbusers": 1000 }, ] +class DseConfigContextManager: + """Change a config parameter is dse.ldif and restore it afterwards.""" + + def __init__(self, inst, dn, attr, value): + self.inst = inst + self.dn = dn + self.attr = attr + self.value = value + self.oldvalue = None + self.dseldif = DSEldif(inst) + + def __enter__(self): + self.inst.stop() + self.oldvalue = self.dseldif.get(self.dn, self.attr, single=True) + self.dseldif.replace(self.dn, self.attr, self.value) + log.info(f"Switching {self.dn}:{self.attr} to {self.value}") + self.inst.start() + + def __exit__(self, exc_type, exc_value, exc_tb): + self.inst.stop() + log.info(f"Switching {self.dn}:{self.attr} to {self.oldvalue}") + self.dseldif.replace(self.dn, self.attr, self.oldvalue) + self.inst.start() + @pytest.fixture(scope="function") def mytopo(topo, request): @@ -153,14 +177,15 @@ def test_db_home_dir_online_backup(topo): 2. Failure 3. Success """ - bdb_ldbmconfig = BDB_LDBMConfig(topo.standalone) - dseldif = DSEldif(topo.standalone) - topo.standalone.stop() - with tempfile.TemporaryDirectory() as backup_dir: - dseldif.replace(bdb_ldbmconfig.dn, 'nsslapd-db-home-directory', f'{backup_dir}') - topo.standalone.start() - topo.standalone.tasks.db2bak(backup_dir=f'{backup_dir}', args={TASK_WAIT: True}) - assert topo.standalone.ds_error_log.match(f".*Failed renaming {backup_dir}.bak back to {backup_dir}") + inst = topo.standalone + dn = BDB_LDBMConfig(inst).dn + attr = 'nsslapd-db-home-directory' + with tempfile.TemporaryDirectory() as dbhome_dir: + with DseConfigContextManager(inst, dn, attr, dbhome_dir): + backup_dir = str(dbhome_dir) + inst.tasks.db2bak(backup_dir=backup_dir, args={TASK_WAIT: True}) + assert inst.ds_error_log.match(f".*Failed renaming {backup_dir}.bak back to {backup_dir}") + def test_replication(topo_m2): """Test that if the dbhome directory is set causing an online backup to fail, @@ -255,7 +280,7 @@ def test_after_db_log_rotation(topo): '-D', DN_DM, '-w', PASSWORD, '-f', "ou=People", '-e', 'attreplace=description:XXXXXX' ] log.info(f'Running {cmd}') - # Perform modify operations until log file rolls + # Perform modify operations until log file rolls result = subprocess.run(cmd, capture_output=True, text=True, check=True) log.info(f'STDOUT: {result.stdout}') log.info(f'STDERR: {result.stderr}')
0
b94533ed0efc5be790c676688a009f64b7e556dc
389ds/389-ds-base
If USING_VSFTPD is defined, some hacks around pulling components via ftp are used.
commit b94533ed0efc5be790c676688a009f64b7e556dc Author: Rich Megginson <[email protected]> Date: Mon Feb 21 21:08:08 2005 +0000 If USING_VSFTPD is defined, some hacks around pulling components via ftp are used. diff --git a/components.mk b/components.mk index 477088ff7..52b0e486f 100644 --- a/components.mk +++ b/components.mk @@ -89,6 +89,13 @@ else # unix - windows has no lib name prefix, except for nspr LIB_PREFIX = lib endif +# work around vsftpd -L problem +ifeq ($(COMPONENT_PULL_METHOD), FTP) +ifdef USING_VSFTPD +VSFTPD_HACK=1 +endif +endif + # ADMINUTIL library ####################################### ADMINUTIL_VERSION=$(ADMINUTIL_RELDATE)$(SEC_SUFFIX) ADMINUTIL_BASE=$(ADMINUTIL_VERSDIR)/${ADMINUTIL_VERSION} @@ -344,7 +351,11 @@ BINS_TO_PKG_SHARED += $(SECURITY_TOOLS_FULLPATH) # SECURITYLINK += $(OSF1SECURITYHACKOBJ) #endif +ifdef VSFTPD_HACK +SECURITY_FILES=lib,bin/$(subst $(SPACE),$(COMMA)bin/,$(SECURITY_TOOLS)) +else SECURITY_FILES=lib,include,bin/$(subst $(SPACE),$(COMMA)bin/,$(SECURITY_TOOLS)) +endif ifndef SECURITY_PULL_METHOD SECURITY_PULL_METHOD = $(COMPONENT_PULL_METHOD) @@ -356,6 +367,12 @@ ifdef COMPONENT_DEPS $(FTP_PULL) -method $(SECURITY_PULL_METHOD) \ -objdir $(SECURITY_BUILD_DIR) -componentdir $(SECURITY_IMPORT) \ -files $(SECURITY_FILES) +ifdef VSFTPD_HACK +# work around vsftpd -L problem + $(FTP_PULL) -method $(SECURITY_PULL_METHOD) \ + -objdir $(SECURITY_BUILD_DIR) -componentdir $(COMPONENTS_DIR)/nss/$(SECURITY_RELDATE) \ + -files include +endif endif -@if [ ! -f $@ ] ; \ then echo "Error: could not get component NSS file $@" ; \ @@ -778,9 +795,18 @@ endif $(JSS_DEP): $(CLASS_DEST) ifdef COMPONENT_DEPS +ifdef VSFTPD_HACK +# work around vsftpd -L problem + $(FTP_PULL) -method $(JSS_PULL_METHOD) \ + -objdir $(CLASS_DEST)/jss -componentdir $(JSS_RELEASE) \ + -files xpclass.jar + mv $(CLASS_DEST)/jss/xpclass.jar $(CLASS_DEST)/$(JSSJAR) + rm -rf $(CLASS_DEST)/jss +else $(FTP_PULL) -method $(JSS_PULL_METHOD) \ -objdir $(CLASS_DEST) -componentdir $(JSS_RELEASE) \ -files $(JSSJAR) +endif endif -@if [ ! -f $@ ] ; \ then echo "Error: could not get component JSS file $@" ; \ @@ -871,9 +897,19 @@ endif $(SASL_DEP): $(NSCP_DISTDIR_FULL_RTL) ifdef COMPONENT_DEPS +ifdef VSFTPD_HACK + $(FTP_PULL) -method $(SASL_PULL_METHOD) \ + -objdir $(SASL_BUILD_DIR) -componentdir $(SASL_RELEASE) \ + -files lib + $(FTP_PULL) -method $(SASL_PULL_METHOD) \ + -objdir $(SASL_INCLUDE) -componentdir $(SASL_RELEASE)/../public \ + -files .\*.h +else $(FTP_PULL) -method $(SASL_PULL_METHOD) \ -objdir $(SASL_BUILD_DIR) -componentdir $(SASL_RELEASE) \ -files lib,include + +endif endif -@if [ ! -f $@ ] ; \ then echo "Error: could not get component SASL file $@" ; \
0
c7c3d5963243574f8f8cf5f292fba27486a40d4a
389ds/389-ds-base
Ticket 48388 - db2ldif -r segfaults from time to time Bug Description: db2ldif starts all the plugins before generating the ldif file. If the retro changelog is enabled and it starts to trim itself the server can crash when cos tries to process the retrocl triming operations. Fix Description: First, fix the NULL dereferences in COS. Then when doing a "db2ldif -r" only startup the plugins that "db2ldif -r" needs (which is just the replication plugin and its dependencies). Revised the plugin_startall() function to remove unused parameters (start_backends & global_plugins) Also did a little code clean up slapi_utf8casecmp. https://fedorahosted.org/389/ticket/48388 Valgrind: passed Reviewed by: nhosoi(Thanks!)
commit c7c3d5963243574f8f8cf5f292fba27486a40d4a Author: Mark Reynolds <[email protected]> Date: Fri Dec 18 16:38:33 2015 -0500 Ticket 48388 - db2ldif -r segfaults from time to time Bug Description: db2ldif starts all the plugins before generating the ldif file. If the retro changelog is enabled and it starts to trim itself the server can crash when cos tries to process the retrocl triming operations. Fix Description: First, fix the NULL dereferences in COS. Then when doing a "db2ldif -r" only startup the plugins that "db2ldif -r" needs (which is just the replication plugin and its dependencies). Revised the plugin_startall() function to remove unused parameters (start_backends & global_plugins) Also did a little code clean up slapi_utf8casecmp. https://fedorahosted.org/389/ticket/48388 Valgrind: passed Reviewed by: nhosoi(Thanks!) diff --git a/ldap/servers/plugins/cos/cos_cache.c b/ldap/servers/plugins/cos/cos_cache.c index cb5cb6934..8a32630e6 100644 --- a/ldap/servers/plugins/cos/cos_cache.c +++ b/ldap/servers/plugins/cos/cos_cache.c @@ -3034,7 +3034,8 @@ static int cos_cache_attr_compare(const void *e1, const void *e2) cosTemplates *pTemplate1 = (cosTemplates*)pAttr1->pParent; /* Now compare the names of the attributes */ - com_Result = slapi_utf8casecmp((unsigned char*)(*(cosAttributes**)e1)->pAttrName,(unsigned char*)(*(cosAttributes**)e2)->pAttrName); + com_Result = slapi_utf8casecmp((unsigned char*)(*(cosAttributes**)e1)->pAttrName, + (unsigned char*)(*(cosAttributes**)e2)->pAttrName); if(0 == com_Result){ /* Now compare the cosPriorities */ com_Result = pTemplate->cosPriority - pTemplate1->cosPriority; @@ -3047,6 +3048,13 @@ static int cos_cache_attr_compare(const void *e1, const void *e2) static int cos_cache_string_compare(const void *e1, const void *e2) { + if (!e1 && e2) { + return 1; + } else if (e1 && !e2) { + return -1; + } else if (!e1 && !e2) { + return 0; + } return slapi_utf8casecmp((*(unsigned char**)e1),(*(unsigned char**)e2)); } @@ -3054,6 +3062,13 @@ static int cos_cache_template_index_compare(const void *e1, const void *e2) { int ret = 0; + if (!e1 && e2) { + return 1; + } else if (e1 && !e2) { + return -1; + } else if (!e1 && !e2) { + return 0; + } if(0 == slapi_dn_issuffix((const char*)e1,*(const char**)e2)) ret = slapi_utf8casecmp(*(unsigned char**)e2,(unsigned char*)e1); else diff --git a/ldap/servers/slapd/main.c b/ldap/servers/slapd/main.c index 4f9fbfe8e..b048dc530 100644 --- a/ldap/servers/slapd/main.c +++ b/ldap/servers/slapd/main.c @@ -1051,7 +1051,7 @@ main( int argc, char **argv) pw_exp_init (); plugin_print_lists(); - plugin_startall(argc, argv, 1 /* Start Backends */, 1 /* Start Globals */); + plugin_startall(argc, argv, NULL /* specific plugin list */); compute_plugins_started(); if (housekeeping_start((time_t)0, NULL) == NULL) { return_value = 1; @@ -2216,13 +2216,24 @@ slapd_exemode_db2ldif(int argc, char** argv) else pb.pb_server_running = 0; - if (db2ldif_dump_replica) { - eq_init(); /* must be done before plugins started */ - ps_init_psearch_system(); /* must come before plugin_startall() */ - plugin_startall(argc, argv, 1 /* Start Backends */, - 1 /* Start Globals */); - eq_start(); /* must be done after plugins started */ - } + 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); + } pb.pb_ldif_file = NULL; if ( archive_name ) { /* redirect stdout to this file: */ diff --git a/ldap/servers/slapd/plugin.c b/ldap/servers/slapd/plugin.c index 4ab644bc4..2d3a5cedd 100644 --- a/ldap/servers/slapd/plugin.c +++ b/ldap/servers/slapd/plugin.c @@ -1390,6 +1390,47 @@ plugin_free_plugin_dep_config(plugin_dep_config **cfg) } } +/* + * Take a given plugin and recursively set all the plugin dependency names + */ +void +plugin_get_plugin_dependencies(char *plugin_name, char ***names) +{ + entry_and_plugin_t *ep = dep_plugin_entries; + char **depends = NULL; + char *dep_attr = "nsslapd-plugin-depends-on-named"; + int i; + + /* Add the original plugin name to the list */ + if (!charray_inlist(*names, plugin_name)){ + charray_add(names, slapi_ch_strdup(plugin_name)); + } + + /* Find the plugin and grab its dependencies */ + while(ep) + { + if (ep->plugin){ + if(strcasecmp(ep->plugin->plg_name, plugin_name) == 0){ + /* We found our plugin, now grab its dependencies */ + depends = slapi_entry_attr_get_charray(ep->e, dep_attr); + break; + } + } + ep = ep->next; + } + + if (depends){ + /* Add the plugin's dependencies */ + charray_merge_nodup(names, depends, 1); + + /* Add each dependency's dependencies */ + for (i = 0; depends[i]; i++){ + /* recurse */ + plugin_get_plugin_dependencies(depends[i], names); + } + slapi_ch_array_free(depends); + } +} /* * plugin_dependency_startall() @@ -1407,7 +1448,7 @@ plugin_free_plugin_dep_config(plugin_dep_config **cfg) */ static int -plugin_dependency_startall(int argc, char** argv, char *errmsg, int operation) +plugin_dependency_startall(int argc, char** argv, char *errmsg, int operation, char** plugin_list) { int ret = 0; Slapi_PBlock pb; @@ -1419,7 +1460,7 @@ plugin_dependency_startall(int argc, char** argv, char *errmsg, int operation) int i = 0; /* general index iterator */ plugin_dep_type the_plugin_type; int index = 0; - char * value; + char *value = NULL; int plugins_started; int num_plg_started; struct slapdplugin *plugin; @@ -1435,25 +1476,50 @@ plugin_dependency_startall(int argc, char** argv, char *errmsg, int operation) global_plugin_callbacks_enabled = 0; /* Count the plugins so we can allocate memory for the config array */ - while(ep) + while(ep) { total_plugins++; - ep = ep->next; } /* allocate the config array */ config = (plugin_dep_config*)slapi_ch_calloc(total_plugins + 1, sizeof(plugin_dep_config)); - ep = dep_plugin_entries; + if (plugin_list){ + /* We have a plugin list, so we need to reset the plugin count */ + total_plugins = 0; + } /* Collect relevant config */ - while(ep) + while(ep) { plugin = ep->plugin; - if(plugin == 0) + if(plugin == 0){ + ep = ep->next; continue; + } + + if (plugin_list){ + /* + * We have a specific list of plugins to start, skip the others... + */ + int found = 0; + for (i = 0; plugin_list[i]; i++){ + if (strcasecmp(plugin->plg_name, plugin_list[i]) == 0){ + found = 1; + break; + } + } + + if (!found){ + /* Skip this plugin, it's not in the list */ + ep = ep->next; + continue; + } else { + total_plugins++; + } + } pblock_init(&pb); slapi_pblock_set( &pb, SLAPI_ARGC, &argc); @@ -1824,12 +1890,13 @@ plugin_dependency_closeall() * stuff is done with. So this function goes through and starts all plugins */ void -plugin_startall(int argc, char** argv, int start_backends, int start_global) +plugin_startall(int argc, char** argv, char **plugin_list) { /* initialize special plugin structures */ default_plugin_init (); - plugin_dependency_startall(argc, argv, "plugin startup failed\n", SLAPI_PLUGIN_START_FN); + plugin_dependency_startall(argc, argv, "plugin startup failed\n", + SLAPI_PLUGIN_START_FN, plugin_list); } /* diff --git a/ldap/servers/slapd/proto-slap.h b/ldap/servers/slapd/proto-slap.h index 7d965b009..f0a525714 100644 --- a/ldap/servers/slapd/proto-slap.h +++ b/ldap/servers/slapd/proto-slap.h @@ -865,11 +865,14 @@ int plugin_setup(Slapi_Entry *plugin_entry, struct slapi_componentid *group, int plugin_call_exop_plugins( Slapi_PBlock *pb, char *oid ); const char *plugin_extended_op_oid2string( const char *oid ); void plugin_closeall(int close_backends, int close_globals); -void plugin_startall(int argc,char **argv,int start_backends, int start_global); +void plugin_startall(int argc, char **argv, char **plugin_list); +void plugin_get_plugin_dependencies(char *plugin_name, char ***names); struct slapdplugin *get_plugin_list(int plugin_list_index); -PRBool plugin_invoke_plugin_sdn (struct slapdplugin *plugin, int operation, Slapi_PBlock *pb, Slapi_DN *target_spec); +PRBool plugin_invoke_plugin_sdn (struct slapdplugin *plugin, int operation, + Slapi_PBlock *pb, Slapi_DN *target_spec); struct slapdplugin *plugin_get_by_name(char *name); -struct slapdplugin *plugin_get_pwd_storage_scheme(char *name, int len, int index); +struct slapdplugin *plugin_get_pwd_storage_scheme(char *name, int len, + int index); char *plugin_get_pwd_storage_scheme_list(int index); int plugin_add_descriptive_attributes( Slapi_Entry *e, struct slapdplugin *plugin ); diff --git a/ldap/servers/slapd/utf8compare.c b/ldap/servers/slapd/utf8compare.c index 3201df7f9..592f03985 100644 --- a/ldap/servers/slapd/utf8compare.c +++ b/ldap/servers/slapd/utf8compare.c @@ -2115,15 +2115,15 @@ slapi_utf8casecmp(unsigned char *s0, unsigned char *s1) d0 = d1 = NULL; if (s0 == NULL || *s0 == '\0') { - if (s1 == NULL || *s1 == '\0') { - rval = 0; - } else { - rval = -1; /* regardless s1, s0 < s1 */ - } - goto end; + if (s1 == NULL || *s1 == '\0') { + rval = 0; + } else { + rval = -1; /* regardless s1, s0 < s1 */ + } + goto end; } else if (s1 == NULL || *s1 == '\0') { - rval = 1; /* regardless s0, s0 > s1 */ - goto end; + rval = 1; /* regardless s0, s0 > s1 */ + goto end; } has8_s0 = slapi_has8thBit(s0); @@ -2141,9 +2141,9 @@ slapi_utf8casecmp(unsigned char *s0, unsigned char *s1) d0 = slapi_utf8StrToLower(s0); d1 = slapi_utf8StrToLower(s1); if (d0 == NULL || d1 == NULL || /* either is not a UTF-8 string */ - (d0 && *d0 == '\0') || (d1 && *d1 == '\0')) { - rval = strcasecmp((char *)s0, (char *)s1); - goto end; + (d0 && *d0 == '\0') || (d1 && *d1 == '\0')) { + rval = strcasecmp((char *)s0, (char *)s1); + goto end; } p0 = d0; @@ -2157,25 +2157,25 @@ slapi_utf8casecmp(unsigned char *s0, unsigned char *s1) n0 = (unsigned char *)ldap_utf8next((char *)p0); n1 = (unsigned char *)ldap_utf8next((char *)p1); if (n0 > t0 || n1 > t1) { - break; - } + break; + } i0 = n0 - p0; i1 = n1 - p1; - rval = i0 - i1; + rval = i0 - i1; if (rval) { /* length is different */ goto end; - } + } /* i0 == i1: same length */ for (x0 = p0, x1 = p1; x0 < n0; x0++, x1++) { rval = *x0 - *x1; if (rval) { goto end; - } + } } - p0 = n0; p1 = n1; /* goto next */ + p0 = n0; p1 = n1; /* goto next */ } /* finished scanning the shared part and check the leftover */ l0 = t0 - n0;
0
3d8c5863ce389c83359cb6a5e285fd535ac77e86
389ds/389-ds-base
When creating a script, if the destination directory does not exist, just print a notice and skip that script. This is to allow the open source instance creator to skip creating the repl monitor script in admin/admin which does not yet exist.
commit 3d8c5863ce389c83359cb6a5e285fd535ac77e86 Author: Rich Megginson <[email protected]> Date: Tue Mar 15 04:07:49 2005 +0000 When creating a script, if the destination directory does not exist, just print a notice and skip that script. This is to allow the open source instance creator to skip creating the repl monitor script in admin/admin which does not yet exist. diff --git a/ldap/admin/src/create_instance.c b/ldap/admin/src/create_instance.c index 301584c61..c08835422 100644 --- a/ldap/admin/src/create_instance.c +++ b/ldap/admin/src/create_instance.c @@ -736,6 +736,11 @@ char *gen_perl_script(char *s_root, char *cs_path, char *name, char *fmt, ...) FILE *f; va_list args; + if (PR_FAILURE == PR_Access(cs_path, PR_ACCESS_EXISTS)) { + printf("Notice: %s does not exist, skipping %s . . .\n", cs_path, name); + return NULL; + } + PR_snprintf(fn, sizeof(fn), "%s%c%s", cs_path, FILE_PATHSEP, name); PR_snprintf(myperl, sizeof(myperl), "%s%cbin%cslapd%cadmin%cbin%cperl", s_root, FILE_PATHSEP, FILE_PATHSEP, @@ -777,6 +782,11 @@ char *gen_perl_script_auto(char *s_root, char *cs_path, char *name, char fn[PATH_SIZE], ofn[PATH_SIZE]; const char *table[10][2]; + if (PR_FAILURE == PR_Access(cs_path, PR_ACCESS_EXISTS)) { + printf("Notice: %s does not exist, skipping %s . . .\n", cs_path, name); + return NULL; + } + PR_snprintf(ofn, sizeof(ofn), "%s%cbin%cslapd%cadmin%cscripts%ctemplate-%s", s_root, FILE_PATHSEP, FILE_PATHSEP, FILE_PATHSEP, FILE_PATHSEP, FILE_PATHSEP, name);
0
4cd1a24b3ce88968ff5f9a2b87efdc84dee176da
389ds/389-ds-base
Ticket 49372 - filter optimisation improvements for common queries Bug Description: Due to the way we apply indexes to searches and the presence of the "filter test threshold" there are a number of queries which can be made faster if they understood the internals of our idl_set and index mechanisms. However, instead of expecting application authors to do this, we should provide it. Fix Description: In the server we have some cases we want to achieve, and some to avoid: * If a union has an unindexed candidate, we throw away all work and return an ALLIDS idls. * In an intersection, if we have an idl that is less than filter test threshold, we return immediately that idl rather than accessing all others, and perform a filter test. Knowing these two properties, we can now look at improving filters for queries. In a common case, SSSD will give us a query which is a union of host cn and sudoHost rules. However, the sudoHost rules are substring searchs that are not able to be indexed - thus the whole filter becomes an unindexed search. IE: (|(cn=a)(cn=b)(cn= ....)(sudoHost=[*]*)) So in this case we want to move the substring to the first query so that if it's un-indexed, we fail immediately with ALLIDS rather than opening the cn index. For intersection, we often see: (&(objectClass=account)(objectClass=posixAccount)(uid=william)) The issue here is that the idls for account and posixAccount both may contain 100,000 items. Even with idl lookthrough limits, until we start to read these, we don't know if we will exceed that. A better query is: (&(uid=william)(objectClass=account)(objectClass=posixAccount)) Because the uid=william index will contain a single item, this put's us below filter test threshold, and we will not open the objectClass indexes. In fact, in an intersection, it is almost always better to perform simple equalities first: (&(uid=william)(modifyTimestamp>=...)(sn=br*)(objectClass=posixAccount)) In most other cases, we will not greatly benefit from re-arrangement due to the size of the idls involved we won't hit filter test. IE (&(modifyTimestamp>=...)(sn=br*)(objectClass=posixAccount)) Would not be significantly better despite and possible arrangement without knowing the content of sn. So in summary, our rules for improving queries are: * unions-with-substrings should have substrings *first* * intersection-with-equality should have all non-objectclass equality filters *first*. https://pagure.io/389-ds-base/issue/49372 Author: wibrown Review by: lkrispen, mreynolds (Thanks!)
commit 4cd1a24b3ce88968ff5f9a2b87efdc84dee176da Author: William Brown <[email protected]> Date: Wed Sep 6 09:37:16 2017 +1000 Ticket 49372 - filter optimisation improvements for common queries Bug Description: Due to the way we apply indexes to searches and the presence of the "filter test threshold" there are a number of queries which can be made faster if they understood the internals of our idl_set and index mechanisms. However, instead of expecting application authors to do this, we should provide it. Fix Description: In the server we have some cases we want to achieve, and some to avoid: * If a union has an unindexed candidate, we throw away all work and return an ALLIDS idls. * In an intersection, if we have an idl that is less than filter test threshold, we return immediately that idl rather than accessing all others, and perform a filter test. Knowing these two properties, we can now look at improving filters for queries. In a common case, SSSD will give us a query which is a union of host cn and sudoHost rules. However, the sudoHost rules are substring searchs that are not able to be indexed - thus the whole filter becomes an unindexed search. IE: (|(cn=a)(cn=b)(cn= ....)(sudoHost=[*]*)) So in this case we want to move the substring to the first query so that if it's un-indexed, we fail immediately with ALLIDS rather than opening the cn index. For intersection, we often see: (&(objectClass=account)(objectClass=posixAccount)(uid=william)) The issue here is that the idls for account and posixAccount both may contain 100,000 items. Even with idl lookthrough limits, until we start to read these, we don't know if we will exceed that. A better query is: (&(uid=william)(objectClass=account)(objectClass=posixAccount)) Because the uid=william index will contain a single item, this put's us below filter test threshold, and we will not open the objectClass indexes. In fact, in an intersection, it is almost always better to perform simple equalities first: (&(uid=william)(modifyTimestamp>=...)(sn=br*)(objectClass=posixAccount)) In most other cases, we will not greatly benefit from re-arrangement due to the size of the idls involved we won't hit filter test. IE (&(modifyTimestamp>=...)(sn=br*)(objectClass=posixAccount)) Would not be significantly better despite and possible arrangement without knowing the content of sn. So in summary, our rules for improving queries are: * unions-with-substrings should have substrings *first* * intersection-with-equality should have all non-objectclass equality filters *first*. https://pagure.io/389-ds-base/issue/49372 Author: wibrown Review by: lkrispen, mreynolds (Thanks!) diff --git a/dirsrvtests/tests/suites/filter/filter_logic.py b/dirsrvtests/tests/suites/filter/filter_logic.py index 1cb158df4..fda86a57a 100644 --- a/dirsrvtests/tests/suites/filter/filter_logic.py +++ b/dirsrvtests/tests/suites/filter/filter_logic.py @@ -93,14 +93,15 @@ def test_filter_logic_not_eq(topology_st_f): # More not cases? def test_filter_logic_range(topology_st_f): - _check_filter(topology_st_f, '(uid>=user5)', 15, [ + ### REMEMBER: user10 is less than user5 because it's strcmp!!! + _check_filter(topology_st_f, '(uid>=user5)', 5, [ USER5_DN, USER6_DN, USER7_DN, USER8_DN, USER9_DN, + ]) + _check_filter(topology_st_f, '(uid<=user4)', 15, [ + USER0_DN, USER1_DN, USER2_DN, USER3_DN, USER4_DN, USER10_DN, USER11_DN, USER12_DN, USER13_DN, USER14_DN, USER15_DN, USER16_DN, USER17_DN, USER18_DN, USER19_DN ]) - _check_filter(topology_st_f, '(uid<=user4)', 5, [ - USER0_DN, USER1_DN, USER2_DN, USER3_DN, USER4_DN - ]) _check_filter(topology_st_f, '(uid>=ZZZZ)', 0, []) _check_filter(topology_st_f, '(uid<=aaaa)', 0, []) @@ -152,29 +153,21 @@ def test_filter_logic_and_range(topology_st_f): _check_filter(topology_st_f, '(&(uid>=user5)(uid=user0)(sn=0))', 0, []) _check_filter(topology_st_f, '(&(uid>=user5)(uid=user0)(sn=1))', 0, []) # These all take 2-way or k-way cases. - _check_filter(topology_st_f, '(&(uid>=user5)(uid>=user6))', 15, [ - USER5_DN, USER6_DN, USER7_DN, USER8_DN, USER9_DN, - USER10_DN, USER11_DN, USER12_DN, USER13_DN, USER14_DN, - USER15_DN, USER16_DN, USER17_DN, USER18_DN, USER19_DN + _check_filter(topology_st_f, '(&(uid>=user5)(uid>=user6))', 4, [ + USER6_DN, USER7_DN, USER8_DN, USER9_DN, ]) - _check_filter(topology_st_f, '(&(uid>=user5)(uid>=user6)(uid>=user7))', 15, [ - USER5_DN, USER6_DN, USER7_DN, USER8_DN, USER9_DN, - USER10_DN, USER11_DN, USER12_DN, USER13_DN, USER14_DN, - USER15_DN, USER16_DN, USER17_DN, USER18_DN, USER19_DN + _check_filter(topology_st_f, '(&(uid>=user5)(uid>=user6)(uid>=user7))', 3, [ + USER7_DN, USER8_DN, USER9_DN, ]) def test_filter_logic_or_range(topology_st_f): - _check_filter(topology_st_f, '(|(uid>=user5)(uid=user6))', 15, [ + _check_filter(topology_st_f, '(|(uid>=user5)(uid=user6))', 5, [ USER5_DN, USER6_DN, USER7_DN, USER8_DN, USER9_DN, - USER10_DN, USER11_DN, USER12_DN, USER13_DN, USER14_DN, - USER15_DN, USER16_DN, USER17_DN, USER18_DN, USER19_DN ]) - _check_filter(topology_st_f, '(|(uid>=user5)(uid=user0))', 16, [ + _check_filter(topology_st_f, '(|(uid>=user5)(uid=user0))', 6, [ USER0_DN, USER5_DN, USER6_DN, USER7_DN, USER8_DN, USER9_DN, - USER10_DN, USER11_DN, USER12_DN, USER13_DN, USER14_DN, - USER15_DN, USER16_DN, USER17_DN, USER18_DN, USER19_DN ]) def test_filter_logic_and_and_eq(topology_st_f): diff --git a/dirsrvtests/tests/suites/filter/rfc3673_all_oper_attrs_test.py b/dirsrvtests/tests/suites/filter/rfc3673_all_oper_attrs_test.py index cce7aa97d..571e31d44 100644 --- a/dirsrvtests/tests/suites/filter/rfc3673_all_oper_attrs_test.py +++ b/dirsrvtests/tests/suites/filter/rfc3673_all_oper_attrs_test.py @@ -133,8 +133,10 @@ def test_search_basic(topology_st, test_user, user_aci, add_attr, """ if regular_user: + log.info("bound as: %s", TEST_USER_DN) topology_st.standalone.simple_bind_s(TEST_USER_DN, TEST_USER_PWD) else: + log.info("bound as: %s", DN_DM) topology_st.standalone.simple_bind_s(DN_DM, PASSWORD) search_filter = ['+'] @@ -144,9 +146,12 @@ def test_search_basic(topology_st, test_user, user_aci, add_attr, else: expected_attrs = sorted(oper_attr_list) + log.info("suffix: %s filter: %s" % (search_suffix, search_filter)) entries = topology_st.standalone.search_s(search_suffix, ldap.SCOPE_BASE, '(objectclass=*)', search_filter) + log.info("results: %s" % entries) + assert len(entries) > 0 found_attrs = sorted(entries[0].data.keys()) if add_attr == '*': @@ -155,7 +160,7 @@ def test_search_basic(topology_st, test_user, user_aci, add_attr, assert all(attr in found_attrs for attr in ['objectClass', expected_attrs[0]]) else: - assert cmp(found_attrs, expected_attrs) == 0 + assert set(expected_attrs).issubset(set(found_attrs)) if __name__ == '__main__': diff --git a/ldap/admin/src/scripts/ns-slapd-gdb.py b/ldap/admin/src/scripts/ns-slapd-gdb.py index 3273d431d..eb99a6f45 100644 --- a/ldap/admin/src/scripts/ns-slapd-gdb.py +++ b/ldap/admin/src/scripts/ns-slapd-gdb.py @@ -16,9 +16,22 @@ import itertools import re +from enum import IntEnum + import gdb from gdb.FrameDecorator import FrameDecorator +class LDAPFilter(IntEnum): + PRESENT = 0x87 + APPROX = 0xa8 + LE = 0xa6 + GE = 0xa5 + SUBSTRINGS = 0xa4 + EQUALITY = 0xa3 + NOT = 0xa2 + OR = 0xa1 + AND = 0xa0 + class DSAccessLog (gdb.Command): """Display the Directory Server access log.""" def __init__ (self): @@ -114,7 +127,64 @@ class DSIdleFilter(): frame_iter = map(DSIdleFilterDecorator, frame_iter) return frame_iter +class DSFilterPrint (gdb.Command): + """Display a filter's contents""" + def __init__ (self): + super (DSFilterPrint, self).__init__ ("ds-filter-print", gdb.COMMAND_DATA) + + def display_filter(self, filter_element, depth=0): + pad = " " * depth + # Extract the choice, that determines what we access next. + f_choice = filter_element['f_choice'] + f_un = filter_element['f_un'] + f_flags = filter_element['f_flags'] + if f_choice == LDAPFilter.PRESENT: + print("%s(%s=*) flags:%s" % (pad, f_un['f_un_type'], f_flags)) + elif f_choice == LDAPFilter.APPROX: + print("%sAPPROX ???" % pad) + elif f_choice == LDAPFilter.LE: + print("%sLE ???" % pad) + elif f_choice == LDAPFilter.GE: + print("%sGE ???" % pad) + elif f_choice == LDAPFilter.SUBSTRINGS: + f_un_sub = f_un['f_un_sub'] + value = f_un_sub['sf_initial'] + print("%s(%s=%s*) flags:%s" % (pad, f_un_sub['sf_type'], value, f_flags)) + elif f_choice == LDAPFilter.EQUALITY: + f_un_ava = f_un['f_un_ava'] + value = f_un_ava['ava_value']['bv_val'] + print("%s(%s=%s) flags:%s" % (pad, f_un_ava['ava_type'], value, f_flags)) + elif f_choice == LDAPFilter.NOT: + print("%sNOT ???" % pad) + elif f_choice == LDAPFilter.OR: + print("%s(| flags:%s" % (pad, f_flags)) + filter_child = f_un['f_un_complex'].dereference() + self.display_filter(filter_child, depth + 4) + print("%s)" % pad) + elif f_choice == LDAPFilter.AND: + # Our child filter is in f_un_complex. + print("%s(& flags:%s" % (pad, f_flags)) + filter_child = f_un['f_un_complex'].dereference() + self.display_filter(filter_child, depth + 4) + print("%s)" % pad) + else: + print("Corrupted filter, no such value %s" % f_choice) + + f_next = filter_element['f_next'] + if f_next != 0: + self.display_filter(f_next.dereference(), depth) + + def invoke (self, arg, from_tty): + # Select our program state + gdb.newest_frame() + cur_frame = gdb.selected_frame() + # We are given the name of a filter, so we need to look up that symbol. + filter_val = cur_frame.read_var(arg) + filter_root = filter_val.dereference() + self.display_filter(filter_root) + DSAccessLog() DSBacktrace() DSIdleFilter() +DSFilterPrint() diff --git a/ldap/servers/slapd/back-ldbm/ldbm_modrdn.c b/ldap/servers/slapd/back-ldbm/ldbm_modrdn.c index 2c0cb074e..20912ff10 100644 --- a/ldap/servers/slapd/back-ldbm/ldbm_modrdn.c +++ b/ldap/servers/slapd/back-ldbm/ldbm_modrdn.c @@ -2068,8 +2068,13 @@ moddn_get_children(back_txn *ptxn, * being moved */ strcpy(filterstr, "objectclass=*"); filter = slapi_str2filter(filterstr); + /* + * We used to set managedSAIT here, but because the subtree create + * referral step is now in build_candidate_list, we can trust the filter + * we provide here is exactly as we provide it IE no referrals involved. + */ candidates = subtree_candidates(pb, be, slapi_sdn_get_ndn(dn_parentdn), - parententry, filter, 1 /* ManageDSAIT */, + parententry, filter, NULL /* allids_before_scopingp */, &err); slapi_filter_free(filter, 1); } diff --git a/ldap/servers/slapd/back-ldbm/ldbm_search.c b/ldap/servers/slapd/back-ldbm/ldbm_search.c index 02a21bf92..6f41394df 100644 --- a/ldap/servers/slapd/back-ldbm/ldbm_search.c +++ b/ldap/servers/slapd/back-ldbm/ldbm_search.c @@ -32,7 +32,7 @@ /* prototypes */ static int build_candidate_list(Slapi_PBlock *pb, backend *be, struct backentry *e, const char *base, int scope, int *lookup_returned_allidsp, IDList **candidates); static IDList *base_candidates(Slapi_PBlock *pb, struct backentry *e); -static IDList *onelevel_candidates(Slapi_PBlock *pb, backend *be, const char *base, struct backentry *e, Slapi_Filter *filter, int managedsait, int *lookup_returned_allidsp, int *err); +static IDList *onelevel_candidates(Slapi_PBlock *pb, backend *be, const char *base, Slapi_Filter *filter, int *lookup_returned_allidsp, int *err); static back_search_result_set *new_search_result_set(IDList *idl, int vlv, int lookthroughlimit); static void delete_search_result_set(Slapi_PBlock *pb, back_search_result_set **sr); static int can_skip_filter_test(Slapi_PBlock *pb, struct slapi_filter *f, int scope, IDList *idl); @@ -946,13 +946,25 @@ build_candidate_list(Slapi_PBlock *pb, backend *be, struct backentry *e, const c break; case LDAP_SCOPE_ONELEVEL: - *candidates = onelevel_candidates(pb, be, base, e, filter, managedsait, - lookup_returned_allidsp, &err); + /* modify the filter to be: (&(parentid=idofbase)(|(originalfilter)(objectclass=referral))) */ + filter = create_onelevel_filter(filter, e, managedsait); + /* Now optimise the filter for use */ + slapi_filter_optimise(filter); + + *candidates = onelevel_candidates(pb, be, base, filter, lookup_returned_allidsp, &err); + /* Give the optimised filter back to search filter for free */ + slapi_pblock_set(pb, SLAPI_SEARCH_FILTER, filter); break; case LDAP_SCOPE_SUBTREE: - *candidates = subtree_candidates(pb, be, base, e, filter, managedsait, - lookup_returned_allidsp, &err); + /* make (|(originalfilter)(objectclass=referral)) */ + filter = create_subtree_filter(filter, managedsait); + /* Now optimise the filter for use */ + slapi_filter_optimise(filter); + + *candidates = subtree_candidates(pb, be, base, e, filter, lookup_returned_allidsp, &err); + /* Give the optimised filter back to search filter for free */ + slapi_pblock_set(pb, SLAPI_SEARCH_FILTER, filter); break; default: @@ -1011,15 +1023,15 @@ base_candidates(Slapi_PBlock *pb __attribute__((unused)), struct backentry *e) * non-recursively when done with the returned filter. */ static Slapi_Filter * -create_referral_filter(Slapi_Filter *filter, Slapi_Filter **focref, Slapi_Filter **forr) +create_referral_filter(Slapi_Filter *filter) { char *buf = slapi_ch_strdup("objectclass=referral"); - *focref = slapi_str2filter(buf); - *forr = slapi_filter_join(LDAP_FILTER_OR, filter, *focref); + Slapi_Filter *focref = slapi_str2filter(buf); + Slapi_Filter *forr = slapi_filter_join(LDAP_FILTER_OR, filter, focref); slapi_ch_free((void **)&buf); - return *forr; + return forr; } /* @@ -1033,20 +1045,20 @@ create_referral_filter(Slapi_Filter *filter, Slapi_Filter **focref, Slapi_Filter * This function is exported for the VLV code to use. */ Slapi_Filter * -create_onelevel_filter(Slapi_Filter *filter, const struct backentry *baseEntry, int managedsait, Slapi_Filter **fid2kids, Slapi_Filter **focref, Slapi_Filter **fand, Slapi_Filter **forr) +create_onelevel_filter(Slapi_Filter *filter, const struct backentry *baseEntry, int managedsait) { Slapi_Filter *ftop = filter; char buf[40]; if (!managedsait) { - ftop = create_referral_filter(filter, focref, forr); + ftop = create_referral_filter(filter); } sprintf(buf, "parentid=%lu", (u_long)(baseEntry != NULL ? baseEntry->ep_id : 0)); - *fid2kids = slapi_str2filter(buf); - *fand = slapi_filter_join(LDAP_FILTER_AND, ftop, *fid2kids); + Slapi_Filter *fid2kids = slapi_str2filter(buf); + Slapi_Filter *fand = slapi_filter_join(LDAP_FILTER_AND, ftop, fid2kids); - return *fand; + return fand; } /* @@ -1057,38 +1069,16 @@ onelevel_candidates( Slapi_PBlock *pb, backend *be, const char *base, - struct backentry *e, Slapi_Filter *filter, - int managedsait, int *lookup_returned_allidsp, int *err) { - Slapi_Filter *fid2kids = NULL; - Slapi_Filter *focref = NULL; - Slapi_Filter *fand = NULL; - Slapi_Filter *forr = NULL; - Slapi_Filter *ftop = NULL; IDList *candidates; - /* - * modify the filter to be something like this: - * - * (&(parentid=idofbase)(|(originalfilter)(objectclass=referral))) - */ - - ftop = create_onelevel_filter(filter, e, managedsait, &fid2kids, &focref, &fand, &forr); - - /* from here, it's just like subtree_candidates */ - candidates = filter_candidates(pb, be, base, ftop, NULL, 0, err); + candidates = filter_candidates(pb, be, base, filter, NULL, 0, err); *lookup_returned_allidsp = slapi_be_is_flag_set(be, SLAPI_BE_FLAG_DONT_BYPASS_FILTERTEST); - /* free up just the filter stuff we allocated above */ - slapi_filter_free(fid2kids, 0); - slapi_filter_free(fand, 0); - slapi_filter_free(forr, 0); - slapi_filter_free(focref, 0); - return (candidates); } @@ -1103,12 +1093,12 @@ onelevel_candidates( * This function is exported for the VLV code to use. */ Slapi_Filter * -create_subtree_filter(Slapi_Filter *filter, int managedsait, Slapi_Filter **focref, Slapi_Filter **forr) +create_subtree_filter(Slapi_Filter *filter, int managedsait) { Slapi_Filter *ftop = filter; if (!managedsait) { - ftop = create_referral_filter(filter, focref, forr); + ftop = create_referral_filter(filter); } return ftop; @@ -1125,13 +1115,9 @@ subtree_candidates( const char *base, const struct backentry *e, Slapi_Filter *filter, - int managedsait, int *allids_before_scopingp, int *err) { - Slapi_Filter *focref = NULL; - Slapi_Filter *forr = NULL; - Slapi_Filter *ftop = NULL; IDList *candidates; PRBool has_tombstone_filter; int isroot = 0; @@ -1140,13 +1126,8 @@ subtree_candidates( Operation *op = NULL; PRBool is_bulk_import = PR_FALSE; - /* make (|(originalfilter)(objectclass=referral)) */ - ftop = create_subtree_filter(filter, managedsait, &focref, &forr); - /* Fetch a candidate list for the original filter */ - candidates = filter_candidates_ext(pb, be, base, ftop, NULL, 0, err, allidslimit); - slapi_filter_free(forr, 0); - slapi_filter_free(focref, 0); + candidates = filter_candidates_ext(pb, be, base, filter, NULL, 0, err, allidslimit); /* set 'allids before scoping' flag */ if (NULL != allids_before_scopingp) { diff --git a/ldap/servers/slapd/back-ldbm/proto-back-ldbm.h b/ldap/servers/slapd/back-ldbm/proto-back-ldbm.h index 0cee3df62..d8d532394 100644 --- a/ldap/servers/slapd/back-ldbm/proto-back-ldbm.h +++ b/ldap/servers/slapd/back-ldbm/proto-back-ldbm.h @@ -566,9 +566,9 @@ int bedse_add_index_entry(int argc, char **argv); /* * ldbm_search.c */ -Slapi_Filter *create_onelevel_filter(Slapi_Filter *filter, const struct backentry *e, int managedsait, Slapi_Filter **fid2kids, Slapi_Filter **focref, Slapi_Filter **fand, Slapi_Filter **forr); -Slapi_Filter *create_subtree_filter(Slapi_Filter *filter, int managedsait, Slapi_Filter **focref, Slapi_Filter **forr); -IDList *subtree_candidates(Slapi_PBlock *pb, backend *be, const char *base, const struct backentry *e, Slapi_Filter *filter, int managedsait, int *allids_before_scopingp, int *err); +Slapi_Filter *create_onelevel_filter(Slapi_Filter *filter, const struct backentry *e, int managedsait); +Slapi_Filter *create_subtree_filter(Slapi_Filter *filter, int managedsait); +IDList *subtree_candidates(Slapi_PBlock *pb, backend *be, const char *base, const struct backentry *e, Slapi_Filter *filter, int *allids_before_scopingp, int *err); void search_set_tune(struct ldbminfo *li, int val); int search_get_tune(struct ldbminfo *li); int compute_lookthrough_limit(Slapi_PBlock *pb, struct ldbminfo *li); diff --git a/ldap/servers/slapd/back-ldbm/vlv_srch.c b/ldap/servers/slapd/back-ldbm/vlv_srch.c index e9780b590..56a0c2f7a 100644 --- a/ldap/servers/slapd/back-ldbm/vlv_srch.c +++ b/ldap/servers/slapd/back-ldbm/vlv_srch.c @@ -93,13 +93,8 @@ vlvSearch_reinit(struct vlvSearch *p, const struct backentry *base) p->vlv_slapifilter = slapi_str2filter(p->vlv_filter); filter_normalize(p->vlv_slapifilter); /* make (&(parentid=idofbase)(|(originalfilter)(objectclass=referral))) */ - { - Slapi_Filter *fid2kids = NULL; - Slapi_Filter *focref = NULL; - Slapi_Filter *fand = NULL; - Slapi_Filter *forr = NULL; - p->vlv_slapifilter = create_onelevel_filter(p->vlv_slapifilter, base, 0 /* managedsait */, &fid2kids, &focref, &fand, &forr); - } + p->vlv_slapifilter = create_onelevel_filter(p->vlv_slapifilter, base, 0 /* managedsait */); + slapi_filter_optimise(p->vlv_slapifilter); } /* @@ -173,22 +168,16 @@ vlvSearch_init(struct vlvSearch *p, Slapi_PBlock *pb, const Slapi_Entry *e, ldbm /* make (&(parentid=idofbase)(|(originalfilter)(objectclass=referral))) */ { - Slapi_Filter *fid2kids = NULL; - Slapi_Filter *focref = NULL; - Slapi_Filter *fand = NULL; - Slapi_Filter *forr = NULL; - p->vlv_slapifilter = create_onelevel_filter(p->vlv_slapifilter, e, 0 /* managedsait */, &fid2kids, &focref, &fand, &forr); - /* jcm: fid2kids, focref, fand, and forr get freed when we free p->vlv_slapifilter */ + p->vlv_slapifilter = create_onelevel_filter(p->vlv_slapifilter, e, 0 /* managedsait */); + slapi_filter_optimise(p->vlv_slapifilter); CACHE_RETURN(&inst->inst_cache, &e); } } break; case LDAP_SCOPE_SUBTREE: { /* make (|(originalfilter)(objectclass=referral))) */ /* No need for scope-filter since we apply a scope test before the filter test */ - Slapi_Filter *focref = NULL; - Slapi_Filter *forr = NULL; - p->vlv_slapifilter = create_subtree_filter(p->vlv_slapifilter, 0 /* managedsait */, &focref, &forr); - /* jcm: focref and forr get freed when we free p->vlv_slapifilter */ + p->vlv_slapifilter = create_subtree_filter(p->vlv_slapifilter, 0 /* managedsait */); + slapi_filter_optimise(p->vlv_slapifilter); } break; } } diff --git a/ldap/servers/slapd/dse.c b/ldap/servers/slapd/dse.c index 420248c24..2634f58be 100644 --- a/ldap/servers/slapd/dse.c +++ b/ldap/servers/slapd/dse.c @@ -1613,6 +1613,13 @@ dse_search(Slapi_PBlock *pb) /* JCM There should only be one exit point from thi */ isrootdse = slapi_sdn_isempty(basesdn); + /* + * Now optimise the filter for use: note that unlike ldbm_search, + * because we don't change the outer filter container, we don't need + * to set back into pb. + */ + slapi_filter_optimise(filter); + switch (scope) { case LDAP_SCOPE_BASE: { Slapi_Entry *baseentry = NULL; diff --git a/ldap/servers/slapd/filter.c b/ldap/servers/slapd/filter.c index fe3525f34..5e75871f5 100644 --- a/ldap/servers/slapd/filter.c +++ b/ldap/servers/slapd/filter.c @@ -29,7 +29,6 @@ static int get_extensible_filter(BerElement *ber, mr_filter_t *); static int get_filter_internal(Connection *conn, BerElement *ber, struct slapi_filter **filt, char **fstr, int maxdepth, int curdepth, int *subentry_dont_rewrite, int *has_tombstone_filter, int *has_ruv_filter); static int tombstone_check_filter(Slapi_Filter *f); static int ruv_check_filter(Slapi_Filter *f); -static void filter_optimize(Slapi_Filter *f); /* @@ -75,7 +74,12 @@ get_filter(Connection *conn, BerElement *ber, int scope, struct slapi_filter **f slapi_filter_to_string(*filt, logbuf, logbufsize)); } - filter_optimize(*filt); + /* + * Filter optimise has been moved to the onelevel/subtree candidate dispatch. + * this is because they inject referrals or other business, that we can optimise + * and improve. + */ + /* filter_optimize(*filt); */ if (NULL != logbuf) { slapi_log_err(SLAPI_LOG_DEBUG, "get_filter", " after optimize: %s\n", @@ -852,19 +856,22 @@ slapi_filter_join_ex(int ftype, struct slapi_filter *f1, struct slapi_filter *f2 if (add_to->f_list->f_choice == LDAP_FILTER_NOT) { add_this->f_next = add_to->f_list; add_to->f_list = add_this; - filter_compute_hash(add_to); - return_this = add_to; } else { /* find end of list, add the filter */ for (fjoin = add_to->f_list; fjoin != NULL; fjoin = fjoin->f_next) { if (fjoin->f_next == NULL) { fjoin->f_next = add_this; - filter_compute_hash(add_to); - return_this = add_to; break; } } } + /* + * Make sure we sync the filter flags. The origin filters may have flags + * we still need on the outer layer! + */ + add_to->f_flags |= add_this->f_flags; + filter_compute_hash(add_to); + return_this = add_to; } else { fjoin = (struct slapi_filter *)slapi_ch_calloc(1, sizeof(struct slapi_filter)); fjoin->f_choice = ftype; @@ -877,6 +884,8 @@ slapi_filter_join_ex(int ftype, struct slapi_filter *f1, struct slapi_filter *f2 fjoin->f_list = f1; f1->f_next = f2; } + /* Make sure any flags that were set move to the outer parent */ + fjoin->f_flags |= f1->f_flags | f2->f_flags; filter_compute_hash(fjoin); return_this = fjoin; } @@ -1521,47 +1530,175 @@ ruv_check_filter(Slapi_Filter *f) return 0; /* Not a RUV filter */ } +/* + * To help filter optimise we break out the list manipulation + * code. + */ + +static void +filter_prioritise_element(Slapi_Filter **list, Slapi_Filter **head, Slapi_Filter **tail, Slapi_Filter **f_prev, Slapi_Filter **f_cur) { + if (*f_prev != NULL) { + (*f_prev)->f_next = (*f_cur)->f_next; + } else if (*list == *f_cur) { + *list = (*f_cur)->f_next; + } -/* filter_optimize + if (*head == NULL) { + *head = *f_cur; + *tail = *f_cur; + (*f_cur)->f_next = NULL; + } else { + (*f_cur)->f_next = *head; + *head = *f_cur; + } +} + +static void +filter_merge_subfilter(Slapi_Filter **list, Slapi_Filter **f_prev, Slapi_Filter **f_cur, Slapi_Filter **f_next) { + /* Cut our current AND/OR out */ + if (*f_prev != NULL) { + (*f_prev)->f_next = (*f_cur)->f_next; + } else if (*list == *f_cur) { + *list = (*f_cur)->f_next; + } + (*f_next) = (*f_cur)->f_next; + + /* Look ahead to the end of our list, without the f_cur. */ + Slapi_Filter *f_cur_tail = *list; + while (f_cur_tail->f_next != NULL) { + f_cur_tail = f_cur_tail->f_next; + } + /* Now append our descendant into the tail */ + f_cur_tail->f_next = (*f_cur)->f_list; + /* Finally free the remainder */ + slapi_filter_free(*f_cur, 0); +} + +/* slapi_filter_optimise * --------------- - * takes a filter and optimizes it for fast evaluation - * currently this merely ensures that any AND or OR - * does not start with a NOT sub-filter if possible + * takes a filter and optimises it for fast evaluation + * + * Optimisations are: + * * In OR conditions move substrings early to promote fail-fast of unindexed types + * * In AND conditions move eq types (that are not objectClass) early to promote triggering threshold shortcut + * * In OR conditions, merge all direct child OR conditions into the list. (|(|(a)(b))) == (|(a)(b)) + * * in AND conditions, merge all direct child AND conditions into the list. (&(&(a)(b))) == (&(a)(b)) + * + * In the case of the OR and AND merges, we remove the inner filter because the outer one may have flags set. + * + * In the future this could be backend dependent. */ -static void -filter_optimize(Slapi_Filter *f) +void +slapi_filter_optimise(Slapi_Filter *f) { - if (!f) + /* + * Today tombstone searches RELY on filter ordering + * and a filter test threshold quirk. We need to avoid + * touching these cases!!! + */ + if (f == NULL || (f->f_flags & SLAPI_FILTER_TOMBSTONE) != 0) { return; + } switch (f->f_choice) { case LDAP_FILTER_AND: - case LDAP_FILTER_OR: { - /* first optimize children */ - filter_optimize(f->f_list); - - /* optimize this */ - if (f->f_list->f_choice == LDAP_FILTER_NOT) { - Slapi_Filter *f_prev = 0; - Slapi_Filter *f_child = 0; - - /* grab a non not filter to place at start */ - for (f_child = f->f_list; f_child != 0; f_child = f_child->f_next) { - if (f_child->f_choice != LDAP_FILTER_NOT) { - /* we have a winner, do swap */ - if (f_prev) - f_prev->f_next = f_child->f_next; - f_child->f_next = f->f_list; - f->f_list = f_child; + /* Move all equality searches to the head. */ + /* Merge any direct descendant AND queries into us */ + { + Slapi_Filter *f_prev = NULL; + Slapi_Filter *f_cur = NULL; + Slapi_Filter *f_next = NULL; + + Slapi_Filter *f_op_head = NULL; + Slapi_Filter *f_op_tail = NULL; + + f_cur = f->f_list; + while(f_cur != NULL) { + + switch(f_cur->f_choice) { + case LDAP_FILTER_AND: + filter_merge_subfilter(&(f->f_list), &f_prev, &f_cur, &f_next); + f_cur = f_next; + break; + case LDAP_FILTER_EQUALITY: + if (strcasecmp(f_cur->f_avtype, "objectclass") != 0) { + f_next = f_cur->f_next; + /* Cut it out */ + filter_prioritise_element(&(f->f_list), &f_op_head, &f_op_tail, &f_prev, &f_cur); + /* Don't change previous, because we remove this f_cur */ + f_cur = f_next; + break; + } else { + /* Move along */ + f_prev = f_cur; + f_cur = f_cur->f_next; + } + break; + default: + /* Move along */ + f_prev = f_cur; + f_cur = f_cur->f_next; break; } + } - f_prev = f_child; + if (f_op_head != NULL) { + f_op_tail->f_next = f->f_list; + f->f_list = f_op_head; } } - } + /* finally optimize children */ + slapi_filter_optimise(f->f_list); + + break; + + case LDAP_FILTER_OR: + /* Move all substring searches to the head. */ + { + Slapi_Filter *f_prev = NULL; + Slapi_Filter *f_cur = NULL; + Slapi_Filter *f_next = NULL; + + Slapi_Filter *f_op_head = NULL; + Slapi_Filter *f_op_tail = NULL; + + f_cur = f->f_list; + while(f_cur != NULL) { + + switch(f_cur->f_choice) { + case LDAP_FILTER_OR: + filter_merge_subfilter(&(f->f_list), &f_prev, &f_cur, &f_next); + f_cur = f_next; + break; + case LDAP_FILTER_APPROX: + case LDAP_FILTER_GE: + case LDAP_FILTER_LE: + case LDAP_FILTER_SUBSTRINGS: + f_next = f_cur->f_next; + /* Cut it out */ + filter_prioritise_element(&(f->f_list), &f_op_head, &f_op_tail, &f_prev, &f_cur); + /* Don't change previous, because we remove this f_cur */ + f_cur = f_next; + break; + default: + /* Move along */ + f_prev = f_cur; + f_cur = f_cur->f_next; + break; + } + } + if (f_op_head != NULL) { + f_op_tail->f_next = f->f_list; + f->f_list = f_op_head; + } + } + /* finally optimize children */ + slapi_filter_optimise(f->f_list); + + break; + default: - filter_optimize(f->f_next); + slapi_filter_optimise(f->f_next); break; } } diff --git a/ldap/servers/slapd/index_subsystem.c b/ldap/servers/slapd/index_subsystem.c index 47ca90047..49de9e45e 100644 --- a/ldap/servers/slapd/index_subsystem.c +++ b/ldap/servers/slapd/index_subsystem.c @@ -191,6 +191,10 @@ index_subsys_assign_filter_decoders(Slapi_PBlock *pb) char *subsystem = "index_subsys_assign_filter_decoders"; char logbuf[1024]; + if (!theCache) { + return rc; + } + /* extract the filter */ slapi_pblock_get(pb, SLAPI_SEARCH_FILTER, &f); if (f) { diff --git a/ldap/servers/slapd/slapi-private.h b/ldap/servers/slapd/slapi-private.h index 548d5cabb..8eb8196a4 100644 --- a/ldap/servers/slapd/slapi-private.h +++ b/ldap/servers/slapd/slapi-private.h @@ -383,6 +383,7 @@ void ndn_cache_get_stats(PRUint64 *hits, PRUint64 *tries, size_t *size, size_t * int filter_flag_is_set(const Slapi_Filter *f, unsigned char flag); char *slapi_filter_to_string(const Slapi_Filter *f, char *buffer, size_t bufsize); char *slapi_filter_to_string_internal(const struct slapi_filter *f, char *buf, size_t *bufsize); +void slapi_filter_optimise(Slapi_Filter *f); /* operation.c */
0
05907ae05c8a88a64b86747879c002d55d356673
389ds/389-ds-base
Ticket 49532 - coverity issues - fix compiler warnings & clang issues Description: Fixed all the warnings https://pagure.io/389-ds-base/issue/49532 Reviewed by: tbordaz(Thanks!)
commit 05907ae05c8a88a64b86747879c002d55d356673 Author: Mark Reynolds <[email protected]> Date: Fri Jan 12 10:37:18 2018 -0500 Ticket 49532 - coverity issues - fix compiler warnings & clang issues Description: Fixed all the warnings https://pagure.io/389-ds-base/issue/49532 Reviewed by: tbordaz(Thanks!) diff --git a/ldap/servers/slapd/back-ldbm/idl_set.c b/ldap/servers/slapd/back-ldbm/idl_set.c index b68e7ab76..f9a900f1f 100644 --- a/ldap/servers/slapd/back-ldbm/idl_set.c +++ b/ldap/servers/slapd/back-ldbm/idl_set.c @@ -270,7 +270,7 @@ idl_set_union(IDListSet *idl_set, backend *be) * Allocate a new set based on the size of our sets. */ IDList *result_list = idl_alloc(idl_set->total_size); - IDList *idl = idl_set->head; + IDList *idl = NULL; IDList *idl_del = NULL; IDList *prev_idl = NULL; NIDS last_min = 0; @@ -398,7 +398,7 @@ idl_set_intersect(IDListSet *idl_set, backend *be) * we don't care if we have allids here, because we'll ignore it anyway. */ result_list = idl_alloc(idl_set->minimum->b_nids); - IDList *idl = idl_set->head; + IDList *idl = NULL; /* The previous value we inserted. */ NIDS last_min = 0; diff --git a/ldap/servers/slapd/control.c b/ldap/servers/slapd/control.c index 91d8abb95..366ec7897 100644 --- a/ldap/servers/slapd/control.c +++ b/ldap/servers/slapd/control.c @@ -337,7 +337,7 @@ get_ldapmessage_controls_ext( slapi_pblock_set(pb, SLAPI_MANAGEDSAIT, &ctrl_not_found); slapi_pblock_set(pb, SLAPI_PWPOLICY, &ctrl_not_found); slapi_log_err(SLAPI_LOG_CONNS, "get_ldapmessage_controls_ext", "Warning: conn=%" PRIu64 " op=%d contains an empty list of controls\n", - pb_conn->c_connid, pb_op->o_opid); + pb_conn ? pb_conn->c_connid : -1, pb_op ? pb_op->o_opid : -1); } else { /* len, ber_len_t is uint, not int, cannot be != -1, may be better to remove this check. */ if ((tag != LBER_END_OF_SEQORSET) && (len != -1)) { diff --git a/src/nunc-stans/ns/ns_thrpool.c b/src/nunc-stans/ns/ns_thrpool.c index 1d8bb03f1..d95b0c38b 100644 --- a/src/nunc-stans/ns/ns_thrpool.c +++ b/src/nunc-stans/ns/ns_thrpool.c @@ -1587,7 +1587,12 @@ ns_thrpool_shutdown(struct ns_thrpool_t *tp) */ for (size_t i = 0; i < tp->thread_count; i++) { ns_result_t result = ns_add_shutdown_job(tp); - PR_ASSERT(result == NS_SUCCESS); + if (result != NS_SUCCESS) { +#ifdef DEBUG + ns_log(LOG_DEBUG, "ns_thrpool_shutdown - Failed to add shutdown job: error (%d)\n", result); +#endif + PR_ASSERT(0); + } } /* Make sure all threads are woken up to their shutdown jobs. */ pthread_mutex_lock(&(tp->work_q_lock));
0
5fb047137d4079e81baf795d9fdc26f572ec5bf1
389ds/389-ds-base
Issue 50919 - Backend delete fails using dsconf Description: Fix typo in parser argument name relates: https://pagure.io/389-ds-base/issue/50919 Reviewed by: mreynolds(one line commit rule)
commit 5fb047137d4079e81baf795d9fdc26f572ec5bf1 Author: Mark Reynolds <[email protected]> Date: Fri Feb 28 08:06:17 2020 -0500 Issue 50919 - Backend delete fails using dsconf Description: Fix typo in parser argument name relates: https://pagure.io/389-ds-base/issue/50919 Reviewed by: mreynolds(one line commit rule) diff --git a/src/lib389/lib389/cli_conf/backend.py b/src/lib389/lib389/cli_conf/backend.py index aaa6613dc..10208bd12 100644 --- a/src/lib389/lib389/cli_conf/backend.py +++ b/src/lib389/lib389/cli_conf/backend.py @@ -286,7 +286,7 @@ def is_db_link(inst, rdn): if cn == rdn.lower(): return True return False - + def is_db_replicated(inst, suffix): replicas = Replicas(inst) @@ -381,7 +381,7 @@ def backend_build_tree(inst, be_insts, nodes): if be_suffix == node_suffix.lower(): # We have our parent, now find the children mts = be._mts.list() - + for mt in mts: sub_parent = mt.get_attr_val_utf8_l('nsslapd-parent-suffix') sub_be = mt.get_attr_val_utf8_l('nsslapd-backend') @@ -1111,7 +1111,7 @@ def create_parser(subparsers): ####################################################### 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') + delete_parser.add_argument('be_name', help='The backend name or suffix to delete') ####################################################### # Get Suffix Tree (for use in web console)
0
d396eab31583fd8f32484cd55f0c394133afb32b
389ds/389-ds-base
Resolves: bug 425861 Bug Description: Instance creation through console is broken Reviewed by: nhosoi (Thanks!) Fix Description: This was caused by my fix for bug 420751. When I added the as_uid to fix the ACI for the admin user, I did not add the mapping everywhere it was used. Unfortunately, I found that the code I added it to could only be used with a live connection to the new directory server, not a FileConn to the dse.ldif. So I had to add a new function to add this ACI to the new root suffix after the server had been started. Another problem with instance creation was that the org entries were not being added when creating a new instance in the console. The default should be to create them if nothing else was specified. Another problem was that instance creation was leaving temp ldif files around. I also had to make sure ServerAdminID was specified everywhere it was needed by dirserver.map, or this would also have broken ds_remove. Platforms tested: RHEL5 x86_64 Flag Day: Yes - autotool file change in adminserver Doc impact: no
commit d396eab31583fd8f32484cd55f0c394133afb32b Author: Rich Megginson <[email protected]> Date: Mon Dec 17 20:08:46 2007 +0000 Resolves: bug 425861 Bug Description: Instance creation through console is broken Reviewed by: nhosoi (Thanks!) Fix Description: This was caused by my fix for bug 420751. When I added the as_uid to fix the ACI for the admin user, I did not add the mapping everywhere it was used. Unfortunately, I found that the code I added it to could only be used with a live connection to the new directory server, not a FileConn to the dse.ldif. So I had to add a new function to add this ACI to the new root suffix after the server had been started. Another problem with instance creation was that the org entries were not being added when creating a new instance in the console. The default should be to create them if nothing else was specified. Another problem was that instance creation was leaving temp ldif files around. I also had to make sure ServerAdminID was specified everywhere it was needed by dirserver.map, or this would also have broken ds_remove. Platforms tested: RHEL5 x86_64 Flag Day: Yes - autotool file change in adminserver Doc impact: no diff --git a/ldap/admin/src/scripts/DSCreate.pm.in b/ldap/admin/src/scripts/DSCreate.pm.in index b7f037da9..c32864ee1 100644 --- a/ldap/admin/src/scripts/DSCreate.pm.in +++ b/ldap/admin/src/scripts/DSCreate.pm.in @@ -459,10 +459,14 @@ my %suffixTable = ( sub initDatabase { my $inf = shift; + my $istempldif = 0; # If the user has specified an LDIF file to use to initialize the database, # load it now my $ldiffile = $inf->{slapd}->{InstallLdifFile}; - if ($ldiffile && -f $ldiffile) { + if ($ldiffile =~ /none/i) { + debug(1, "No ldif file or org entries specified - no initial database will be created\n"); + return (); + } elsif ($ldiffile && -f $ldiffile) { debug(1, "Loading initial ldif file $ldiffile\n"); } elsif (($inf->{slapd}->{Suffix} =~ /^(.*?)=/) && $suffixTable{$1}) { my @errs; @@ -477,7 +481,8 @@ sub initDatabase { } my @ldiffiles = ($template, "$inf->{General}->{prefix}@templatedir@/template-baseacis.ldif"); - if (exists($inf->{slapd}->{InstallLdifFile}) and + # default is to create org entries unless explicitly set to none + if (!exists($inf->{slapd}->{InstallLdifFile}) or ($inf->{slapd}->{InstallLdifFile} =~ /suggest/i)) { push @ldiffiles, "$inf->{General}->{prefix}@templatedir@/template.ldif"; } @@ -495,6 +500,7 @@ sub initDatabase { } # $templdif now contains the ldif to import $ldiffile = $templdif; + $istempldif = 1; } if (!$ldiffile) { return (); @@ -503,8 +509,12 @@ sub initDatabase { my $cmd = "$inf->{slapd}->{inst_dir}/ldif2db -n userRoot -i \'$ldiffile\'"; $? = 0; # clear error condition my $output = `$cmd 2>&1`; - if ($?) { - return ('error_importing_ldif', $ldiffile, $?, $output); + my $result = $?; + if ($istempldif) { + unlink($ldiffile); + } + if ($result) { + return ('error_importing_ldif', $ldiffile, $result, $output); } debug(1, $output);
0
ff46f533e9c0f4a1d0a82b39ca25dbafa7f32a73
389ds/389-ds-base
Issue 50052 - Fix rpm.mk according to audit-ci change Description: Always run `npm ci` when we run node_modules install. It should be done because we always have to be sure about what we ship in the package is safe and stable. https://pagure.io/389-ds-base/issue/50052 Reviewed by: mreynolds (Thanks!)
commit ff46f533e9c0f4a1d0a82b39ca25dbafa7f32a73 Author: Simon Pichugin <[email protected]> Date: Fri May 31 17:32:07 2019 +0200 Issue 50052 - Fix rpm.mk according to audit-ci change Description: Always run `npm ci` when we run node_modules install. It should be done because we always have to be sure about what we ship in the package is safe and stable. https://pagure.io/389-ds-base/issue/50052 Reviewed by: mreynolds (Thanks!) diff --git a/rpm.mk b/rpm.mk index fbb607685..1b2d02e70 100644 --- a/rpm.mk +++ b/rpm.mk @@ -33,13 +33,13 @@ clean: rm -rf dist rm -rf rpmbuild -$(NODE_MODULES_TEST): +install-node-modules: cd src/cockpit/389-console; make -f node_modules.mk install -build-cockpit: $(NODE_MODULES_TEST) +build-cockpit: install-node-modules cd src/cockpit/389-console; make -f node_modules.mk build-cockpit-plugin -dist-bz2: $(NODE_MODULES_TEST) +dist-bz2: install-node-modules cd src/cockpit/389-console; \ rm -rf cockpit_dist; \ make -f node_modules.mk build-cockpit-plugin; \ @@ -54,7 +54,7 @@ dist-bz2: $(NODE_MODULES_TEST) local-archive: build-cockpit -mkdir -p dist/$(NAME_VERSION) - rsync -a --exclude=node_modules --exclude=dist --exclude=.git --exclude=rpmbuild . dist/$(NAME_VERSION) + rsync -a --exclude=node_modules --exclude=dist --exclude=__pycache__ --exclude=.git --exclude=rpmbuild . dist/$(NAME_VERSION) tarballs: local-archive -mkdir -p dist/sources diff --git a/src/cockpit/389-console/node_modules.mk b/src/cockpit/389-console/node_modules.mk index 9da5e183d..307e8e317 100644 --- a/src/cockpit/389-console/node_modules.mk +++ b/src/cockpit/389-console/node_modules.mk @@ -1,5 +1,5 @@ install: package.json - test -f node_modules/webpack || npm ci + npm ci build-cockpit-plugin: webpack.config.js npm run audit-ci && npm run build && cp -r dist cockpit_dist
0
8ff8cb850be8a93f75aa3007ee2131c026f4962b
389ds/389-ds-base
Ticket 49937 - Log buffer exceeded emergency logging msg is not thread-safe Bug Description: Multiple operations making modificatiosn on a DN that is very large can crash the server, because when we do emergency logging, we close and reopen the errors log withgout hold the error log write lock. This causes the FD pointer to be become invalid and triggers a crash. Fix description: Hold the errors log write lock while closing and reopening the log https://pagure.io/389-ds-base/issue/49937 Reviewed by: vashirov(Thanks!)
commit 8ff8cb850be8a93f75aa3007ee2131c026f4962b Author: Mark Reynolds <[email protected]> Date: Wed Sep 5 14:09:21 2018 -0400 Ticket 49937 - Log buffer exceeded emergency logging msg is not thread-safe Bug Description: Multiple operations making modificatiosn on a DN that is very large can crash the server, because when we do emergency logging, we close and reopen the errors log withgout hold the error log write lock. This causes the FD pointer to be become invalid and triggers a crash. Fix description: Hold the errors log write lock while closing and reopening the log https://pagure.io/389-ds-base/issue/49937 Reviewed by: vashirov(Thanks!) diff --git a/ldap/servers/slapd/log.c b/ldap/servers/slapd/log.c index 2e4ee03a8..7dd71541b 100644 --- a/ldap/servers/slapd/log.c +++ b/ldap/servers/slapd/log.c @@ -2231,11 +2231,11 @@ vslapd_log_emergency_error(LOGFD fp, const char *msg, int locked) if (logging_hr_timestamps_enabled == 1) { struct timespec tsnow; if (clock_gettime(CLOCK_REALTIME, &tsnow) != 0) { - syslog(LOG_EMERG, "vslapd_log_emergency_error, Unable to determine system time for message :: %s", msg); + syslog(LOG_EMERG, "vslapd_log_emergency_error, Unable to determine system time for message :: %s\n", msg); return; } if (format_localTime_hr_log(tsnow.tv_sec, tsnow.tv_nsec, sizeof(tbuf), tbuf, &size) != 0) { - syslog(LOG_EMERG, "vslapd_log_emergency_error, Unable to format system time for message :: %s", msg); + syslog(LOG_EMERG, "vslapd_log_emergency_error, Unable to format system time for message :: %s\n", msg); return; } } else { @@ -2243,14 +2243,14 @@ vslapd_log_emergency_error(LOGFD fp, const char *msg, int locked) time_t tnl; tnl = slapi_current_utc_time(); if (format_localTime_log(tnl, sizeof(tbuf), tbuf, &size) != 0) { - syslog(LOG_EMERG, "vslapd_log_emergency_error, Unable to format system time for message :: %s", msg); + syslog(LOG_EMERG, "vslapd_log_emergency_error, Unable to format system time for message :: %s\n", msg); return; } #ifdef HAVE_CLOCK_GETTIME } #endif - PR_snprintf(buffer, sizeof(buffer), "%s - EMERG - %s", tbuf, msg); + PR_snprintf(buffer, sizeof(buffer), "%s - EMERG - %s\n", tbuf, msg); size = strlen(buffer); if (!locked) { @@ -2531,7 +2531,7 @@ vslapd_log_access(char *fmt, va_list ap) if (SLAPI_LOG_BUFSIZ - blen < vlen) { /* We won't be able to fit the message in! Uh-oh! */ - /* Should we actually just do the snprintf, and warn that message was trunced? */ + /* Should we actually just do the snprintf, and warn that message was truncated? */ log__error_emergency("Insufficent buffer capacity to fit timestamp and message!", 1, 0); return -1; } @@ -4486,6 +4486,13 @@ log__error_emergency(const char *errstr, int reopen, int locked) if (!reopen) { return; } + if (!locked) { + /* + * Take the lock because we are closing and reopening the error log (fd), + * and we don't want any other threads trying to use this fd + */ + LOG_ERROR_LOCK_WRITE(); + } if (NULL != loginfo.log_error_fdes) { LOG_CLOSE(loginfo.log_error_fdes); } @@ -4494,7 +4501,10 @@ log__error_emergency(const char *errstr, int reopen, int locked) PRErrorCode prerr = PR_GetError(); syslog(LOG_ERR, "Failed to reopen errors log file, " SLAPI_COMPONENT_NAME_NSPR " error %d (%s)\n", prerr, slapd_pr_strerror(prerr)); } else { - vslapd_log_emergency_error(loginfo.log_error_fdes, errstr, locked); + vslapd_log_emergency_error(loginfo.log_error_fdes, errstr, 1 /* locked */); + } + if (!locked) { + LOG_ERROR_UNLOCK_WRITE(); } return; }
0
4a5eee63f45ed290375440827c92af9b2347a177
389ds/389-ds-base
Ticket 47750 - Need to refresh cache entry after called betxn postop plugins Bug Description: If deleting an entry triggers multiple betxn plugins, the entry might not be removed the cache - which prevents that same entry(same dn) from being re-added(error 68). For example, the RI and memberOf plugins are enabled. Then we add a user to a group. This adds the memberOf attribute to the entry. We then delete that user, which triggers the RI plugin, which then triggers the memberOf plugin. So the entry that is deleted gets modified in bvetxn postop, and has its its cache entry replaced. This then confuses the cache logic at the end of the delete operation, and the entry is not removed from the cache. Fix Description: Refresh the cache entry after calling the betxn postop plugins. If the entry has changed, return the old old entry and proceed with the new one. https://fedorahosted.org/389/ticket/47750 Reviewed by: nhosoi & rmeggins (Thanks!!)
commit 4a5eee63f45ed290375440827c92af9b2347a177 Author: Mark Reynolds <[email protected]> Date: Tue Dec 16 10:37:02 2014 -0500 Ticket 47750 - Need to refresh cache entry after called betxn postop plugins Bug Description: If deleting an entry triggers multiple betxn plugins, the entry might not be removed the cache - which prevents that same entry(same dn) from being re-added(error 68). For example, the RI and memberOf plugins are enabled. Then we add a user to a group. This adds the memberOf attribute to the entry. We then delete that user, which triggers the RI plugin, which then triggers the memberOf plugin. So the entry that is deleted gets modified in bvetxn postop, and has its its cache entry replaced. This then confuses the cache logic at the end of the delete operation, and the entry is not removed from the cache. Fix Description: Refresh the cache entry after calling the betxn postop plugins. If the entry has changed, return the old old entry and proceed with the new one. https://fedorahosted.org/389/ticket/47750 Reviewed by: nhosoi & rmeggins (Thanks!!) diff --git a/ldap/servers/slapd/back-ldbm/ldbm_delete.c b/ldap/servers/slapd/back-ldbm/ldbm_delete.c index 9c19f0887..eaac39d59 100644 --- a/ldap/servers/slapd/back-ldbm/ldbm_delete.c +++ b/ldap/servers/slapd/back-ldbm/ldbm_delete.c @@ -1261,6 +1261,13 @@ ldbm_back_delete( Slapi_PBlock *pb ) /* delete from cache and clean up */ if (e) { + struct backentry *old_e = e; + + e = cache_find_id(&inst->inst_cache,e->ep_id); + if(e != old_e){ + /* return the old entry, and proceed with the new one */ + CACHE_RETURN(&inst->inst_cache, &old_e); + } if (cache_is_in_cache(&inst->inst_cache, e)) { ep_id = e->ep_id; /* Otherwise, e might have been freed. */ CACHE_REMOVE(&inst->inst_cache, e);
0
fcdeec3b876a28e06bb53a60fe502cb702403931
389ds/389-ds-base
Issue 3527 - Support HAProxy and Instance on the same machine configuration (#6107) Description: Improve how we handle HAProxy connections to work better when the DS and HAProxy are on the same machine. Ensure the client and header destination IPs are checked against the trusted IP list. Additionally, this change will also allow configuration having HAProxy is listening on a different subnet than the one used to forward the request. Related: https://github.com/389ds/389-ds-base/issues/3527 Reviewed by: @progier389, @jchapma (Thanks!)
commit fcdeec3b876a28e06bb53a60fe502cb702403931 Author: Simon Pichugin <[email protected]> Date: Tue Feb 27 16:30:47 2024 -0800 Issue 3527 - Support HAProxy and Instance on the same machine configuration (#6107) Description: Improve how we handle HAProxy connections to work better when the DS and HAProxy are on the same machine. Ensure the client and header destination IPs are checked against the trusted IP list. Additionally, this change will also allow configuration having HAProxy is listening on a different subnet than the one used to forward the request. Related: https://github.com/389ds/389-ds-base/issues/3527 Reviewed by: @progier389, @jchapma (Thanks!) diff --git a/ldap/servers/slapd/connection.c b/ldap/servers/slapd/connection.c index a30511c97..07d629475 100644 --- a/ldap/servers/slapd/connection.c +++ b/ldap/servers/slapd/connection.c @@ -1187,6 +1187,8 @@ connection_read_operation(Connection *conn, Operation *op, ber_tag_t *tag, int * char str_ip[INET6_ADDRSTRLEN + 1] = {0}; char str_haproxy_ip[INET6_ADDRSTRLEN + 1] = {0}; char str_haproxy_destip[INET6_ADDRSTRLEN + 1] = {0}; + int trusted_matches_ip_found = 0; + int trusted_matches_destip_found = 0; struct berval **bvals = NULL; int proxy_connection = 0; @@ -1245,21 +1247,38 @@ connection_read_operation(Connection *conn, Operation *op, ber_tag_t *tag, int * normalize_IPv4(conn->cin_addr, buf_ip, sizeof(buf_ip), str_ip, sizeof(str_ip)); normalize_IPv4(&pr_netaddr_dest, buf_haproxy_destip, sizeof(buf_haproxy_destip), str_haproxy_destip, sizeof(str_haproxy_destip)); + size_t ip_len = strlen(buf_ip); + size_t destip_len = strlen(buf_haproxy_destip); /* Now, reset RC and set it to 0 only if a match is found */ haproxy_rc = -1; - /* Allow only: - * Trusted IP == Original Client IP == HAProxy Header Destination IP */ + /* + * We need to allow a configuration where DS instance and HAProxy are on the same machine. + * In this case, we need to check if + * the HAProxy client IP (which will be a loopback address) matches one of the the trusted IP addresses, + * while still checking that + * the HAProxy header destination IP address matches one of the trusted IP addresses. + * Additionally, this change will also allow configuration having + * HAProxy listening on a different subnet than one used to forward the request. + */ for (size_t i = 0; bvals[i] != NULL; ++i) { - if ((strlen(bvals[i]->bv_val) == strlen(buf_ip)) && - (strlen(bvals[i]->bv_val) == strlen(buf_haproxy_destip)) && - (strncasecmp(bvals[i]->bv_val, buf_ip, strlen(buf_ip)) == 0) && - (strncasecmp(bvals[i]->bv_val, buf_haproxy_destip, strlen(buf_haproxy_destip)) == 0)) { - haproxy_rc = 0; - break; + size_t bval_len = strlen(bvals[i]->bv_val); + + /* Check if the Client IP (HAProxy's machine IP) address matches the trusted IP address */ + if (!trusted_matches_ip_found) { + trusted_matches_ip_found = (bval_len == ip_len) && (strncasecmp(bvals[i]->bv_val, buf_ip, ip_len) == 0); + } + /* Check if the HAProxy header destination IP address matches the trusted IP address */ + if (!trusted_matches_destip_found) { + trusted_matches_destip_found = (bval_len == destip_len) && (strncasecmp(bvals[i]->bv_val, buf_haproxy_destip, destip_len) == 0); } } + + if (trusted_matches_ip_found && trusted_matches_destip_found) { + haproxy_rc = 0; + } + if (haproxy_rc == -1) { slapi_log_err(SLAPI_LOG_CONNS, "connection_read_operation", "HAProxy header received from unknown source.\n"); disconnect_server_nomutex(conn, conn->c_connid, -1, SLAPD_DISCONNECT_PROXY_UNKNOWN, EPROTO);
0
cc8bfec02d2ae6e80f48ce8a505e312471225f00
389ds/389-ds-base
Ticket 50633 - Add cargo vendor support for offline builds Bug Description: At suse/rh we need to be able to build offline. To achieve this we need offline builds. This adds support for these in 389-ds with cargo and rust. Fix Description: This adds cargo vendor support for offline builds, and shows that they work. We add a stub library for librslapd/libslapd so that we can begin to develop features in rust. To build normally: work as usual. To build offline: make -f rpm.mk download-cargo-dependencies ./configure --enable-rust --enable-rust-offline Continue to build as usual. A note to keep in mind is cargo test does not work offline as dev-dependencies are not vendored. The download-cargo-dependencies has been added to dist-bz2 for distributions. https://pagure.io/389-ds-base/pull-request/50633 Author: William Brown <[email protected]> Review by: mhonek (Thanks)
commit cc8bfec02d2ae6e80f48ce8a505e312471225f00 Author: William Brown <[email protected]> Date: Thu Oct 3 14:07:41 2019 +1000 Ticket 50633 - Add cargo vendor support for offline builds Bug Description: At suse/rh we need to be able to build offline. To achieve this we need offline builds. This adds support for these in 389-ds with cargo and rust. Fix Description: This adds cargo vendor support for offline builds, and shows that they work. We add a stub library for librslapd/libslapd so that we can begin to develop features in rust. To build normally: work as usual. To build offline: make -f rpm.mk download-cargo-dependencies ./configure --enable-rust --enable-rust-offline Continue to build as usual. A note to keep in mind is cargo test does not work offline as dev-dependencies are not vendored. The download-cargo-dependencies has been added to dist-bz2 for distributions. https://pagure.io/389-ds-base/pull-request/50633 Author: William Brown <[email protected]> Review by: mhonek (Thanks) diff --git a/.cargo/config b/.cargo/config new file mode 100644 index 000000000..af24cf11b --- /dev/null +++ b/.cargo/config @@ -0,0 +1,8 @@ + + +[source.crates-io] +replace-with = "vendored-sources" + +[source.vendored-sources] +directory = "./vendor" + diff --git a/.gitignore b/.gitignore index e6b941a27..45436c440 100644 --- a/.gitignore +++ b/.gitignore @@ -225,8 +225,10 @@ html/ src/lib389/dist/ src/lib389/man/ src/libsds/target/ +src/librslapd/target/ dist venv .idea src/cockpit/389-console/cockpit_dist/ src/cockpit/389-console/node_modules/ +ldap/servers/slapd/rust-slapi-private.h diff --git a/Makefile.am b/Makefile.am index 54628453c..63f71206e 100644 --- a/Makefile.am +++ b/Makefile.am @@ -33,12 +33,19 @@ NSPR_INCLUDES = $(NSPR_CFLAGS) # Rust inclusions. if RUST_ENABLE +# Rust enabled RUST_ON = 1 CARGO_FLAGS = @cargo_defs@ RUSTC_FLAGS = @asan_rust_defs@ @msan_rust_defs@ @tsan_rust_defs@ @debug_rust_defs@ RUST_LDFLAGS = -ldl -lpthread -lgcc_s -lc -lm -lrt -lutil RUST_DEFINES = -DRUST_ENABLE +if RUST_ENABLE_OFFLINE +RUST_OFFLINE = --locked --offline else +RUST_OFFLINE = +endif +else +# Rust disabled RUST_ON = 0 CARGO_FLAGS = RUSTC_FLAGS = @@ -211,6 +218,10 @@ SLAPD_LDFLAGS = -version-info 1:0:1 BUILT_SOURCES = dberrstrs.h \ $(POLICY_FC) +if RUST_ENABLE +BUILT_SOURCES += rust-slapi-private.h +endif + if enable_posix_winsync LIBPOSIX_WINSYNC_PLUGIN = libposix-winsync-plugin.la endif @@ -269,6 +280,10 @@ CLEANFILES = dberrstrs.h ns-slapd.properties \ doxyfile.stamp ldap/admin/src/scripts/dbmon.sh \ $(NULL) +if RUST_ENABLE +CLEANFILES += rust-slapi-private.h +endif + clean-local: -rm -rf dist -rm -rf $(abs_top_builddir)/html @@ -1172,7 +1187,7 @@ libsds_la_LDFLAGS = $(AM_LDFLAGS) $(SDS_LDFLAGS) if RUST_ENABLE -noinst_LTLIBRARIES = librsds.la +noinst_LTLIBRARIES = librsds.la librslapd.la ### Why does this exist? # @@ -1181,6 +1196,8 @@ noinst_LTLIBRARIES = librsds.la # https://people.gnome.org/~federico/blog/librsvg-build-infrastructure.html # https://gitlab.gnome.org/GNOME/librsvg/blob/master/Makefile.am +### Rust datastructures + RSDS_LIB = @abs_top_builddir@/rs/@rust_target_dir@/librsds.a libsds_la_LIBADD = $(RSDS_LIB) @@ -1193,15 +1210,47 @@ librsds_la_SOURCES = \ librsds_la_EXTRA = src/libsds/Cargo.lock @abs_top_builddir@/rs/@rust_target_dir@/librsds.a: $(librsds_la_SOURCES) - CARGO_TARGET_DIR=$(abs_top_builddir)/rs RUSTC_BOOTSTRAP=1 \ - cargo rustc --manifest-path=$(srcdir)/src/libsds/Cargo.toml \ + RUST_BACKTRACE=1 RUSTC_BOOTSTRAP=1 \ + CARGO_TARGET_DIR=$(abs_top_builddir)/rs \ + cargo rustc $(RUST_OFFLINE) --manifest-path=$(srcdir)/src/libsds/Cargo.toml \ $(CARGO_FLAGS) --verbose -- $(RUSTC_FLAGS) -EXTRA_DIST = $(librsds_la_SOURCES) $(librsds_la_EXTRA) +### Rust lib slapd components +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/lib.rs + +librslapd_la_EXTRA = src/librslapd/Cargo.lock +@abs_top_builddir@/rs/@rust_target_dir@/librslapd.a: $(librslapd_la_SOURCES) + RUST_BACKTRACE=1 RUSTC_BOOTSTRAP=1 \ + CARGO_TARGET_DIR=$(abs_top_builddir)/rs \ + SLAPD_HEADER_DIR=$(abs_top_builddir)/ \ + cargo rustc $(RUST_OFFLINE) --manifest-path=$(srcdir)/src/librslapd/Cargo.toml \ + $(CARGO_FLAGS) --verbose -- $(RUSTC_FLAGS) + +# The header needs the lib build first. +rust-slapi-private.h: @abs_top_builddir@/rs/@rust_target_dir@/librslapd.a + +EXTRA_DIST = $(librsds_la_SOURCES) $(librsds_la_EXTRA) \ + $(librslapd_la_SOURCES) $(librslapd_la_EXTRA) + +## Run rust tests +# cargo does not support offline tests :( +if RUST_ENABLE_OFFLINE +else check-local: - CARGO_TARGET_DIR=$(abs_top_builddir)/rs RUSTC_BOOTSTRAP=1 \ - cargo test --manifest-path=$(srcdir)/src/libsds/Cargo.toml + RUST_BACKTRACE=1 RUSTC_BOOTSTRAP=1 \ + CARGO_TARGET_DIR=$(abs_top_builddir)/rs \ + cargo test $(RUST_OFFLINE) --manifest-path=$(srcdir)/src/libsds/Cargo.toml + RUST_BACKTRACE=1 RUSTC_BOOTSTRAP=1 \ + CARGO_TARGET_DIR=$(abs_top_builddir)/rs \ + SLAPD_HEADER_DIR=$(abs_top_builddir)/ \ + cargo test $(RUST_OFFLINE) --manifest-path=$(srcdir)/src/librslapd/Cargo.toml +endif else # Just build the tqueue in C. @@ -1363,6 +1412,11 @@ libslapd_la_SOURCES = ldap/servers/slapd/add.c \ libslapd_la_CPPFLAGS = $(AM_CPPFLAGS) $(DSPLUGIN_CPPFLAGS) $(SASL_CFLAGS) @db_inc@ $(KERBEROS_CFLAGS) $(PCRE_CFLAGS) $(SDS_CPPFLAGS) $(SVRCORE_INCLUDES) libslapd_la_LIBADD = $(LDAPSDK_LINK) $(SASL_LINK) $(NSS_LINK) $(NSPR_LINK) $(KERBEROS_LIBS) $(PCRE_LIBS) $(THREADLIB) $(SYSTEMD_LIBS) libsds.la libsvrcore.la + +if RUST_ENABLE +libslapd_la_LIBADD += $(RSLAPD_LIB) +endif + libslapd_la_LDFLAGS = $(AM_LDFLAGS) $(SLAPD_LDFLAGS) diff --git a/configure.ac b/configure.ac index 233bc5b3c..64fc2ff44 100644 --- a/configure.ac +++ b/configure.ac @@ -85,19 +85,27 @@ AC_CHECK_FUNCS([clock_gettime], [], AC_MSG_ERROR([unable to locate required symb LT_LIB_DLLOAD # Optional rust component support. +AC_MSG_CHECKING(for --enable-rust-offline) +AC_ARG_ENABLE(rust_offline, AS_HELP_STRING([--enable-rust-offline], [Enable rust building offline. you MUST have run vendor! (default: no)]), + [], [ enable_rust_offline=no ]) +AC_MSG_RESULT($enable_rust_offline) +AM_CONDITIONAL([RUST_ENABLE_OFFLINE],[test "$enable_rust_offline" = yes]) + AC_MSG_CHECKING(for --enable-rust) AC_ARG_ENABLE(rust, AS_HELP_STRING([--enable-rust], [Enable rust language features (default: no)]), [], [ enable_rust=no ]) AC_MSG_RESULT($enable_rust) -if test "$enable_rust" = yes ; then +if test "$enable_rust" = yes -o "$enable_rust_offline" = yes; then AC_CHECK_PROG(CARGO, [cargo], [yes], [no]) AC_CHECK_PROG(RUSTC, [rustc], [yes], [no]) AS_IF([test "$CARGO" != "yes" -o "$RUSTC" != "yes"], [ AC_MSG_FAILURE("Rust based plugins cannot be built cargo=$CARGO rustc=$RUSTC") ]) + + fi -AM_CONDITIONAL([RUST_ENABLE],[test "$enable_rust" = yes]) +AM_CONDITIONAL([RUST_ENABLE],[test "$enable_rust" = yes -o "$enable_rust_offline" = yes]) AC_MSG_CHECKING(for --enable-debug) AC_ARG_ENABLE(debug, AS_HELP_STRING([--enable-debug], [Enable debug features (default: no)]), diff --git a/ldap/servers/slapd/libglobs.c b/ldap/servers/slapd/libglobs.c index 167a3fefe..db61ee0b8 100644 --- a/ldap/servers/slapd/libglobs.c +++ b/ldap/servers/slapd/libglobs.c @@ -133,6 +133,11 @@ #endif #include <sys/resource.h> +#ifdef RUST_ENABLE +#include <rust-slapi-private.h> +#endif + + #define REMOVE_CHANGELOG_CMD "remove" int slapd_ldap_debug = SLAPD_DEFAULT_ERRORLOG_LEVEL; @@ -1533,6 +1538,11 @@ FrontendConfig_init(void) struct rlimit rlp; int64_t maxdescriptors = SLAPD_DEFAULT_MAXDESCRIPTORS; +#ifdef RUST_ENABLE + /* prove rust is working */ + PR_ASSERT(do_nothing_rust() == 0); +#endif + #if SLAPI_CFG_USE_RWLOCK == 1 /* initialize the read/write configuration lock */ if ((cfg->cfg_rwlock = slapi_new_rwlock()) == NULL) { diff --git a/rpm.mk b/rpm.mk index 9eb4500f9..d81e39929 100644 --- a/rpm.mk +++ b/rpm.mk @@ -32,13 +32,23 @@ clean: rm -rf dist rm -rf rpmbuild +update-cargo-dependencies: + cargo update --manifest-path=./src/libsds/Cargo.toml + cargo update --manifest-path=./src/librslapd/Cargo.toml + +download-cargo-dependencies: + cargo vendor --manifest-path=./src/libsds/Cargo.toml + cargo fetch --manifest-path=./src/libsds/Cargo.toml + cargo vendor --manifest-path=./src/librslapd/Cargo.toml + cargo fetch --manifest-path=./src/librslapd/Cargo.toml + install-node-modules: cd src/cockpit/389-console; make -f node_modules.mk install build-cockpit: install-node-modules cd src/cockpit/389-console; make -f node_modules.mk build-cockpit-plugin -dist-bz2: install-node-modules +dist-bz2: install-node-modules download-cargo-dependencies cd src/cockpit/389-console; \ rm -rf cockpit_dist; \ make -f node_modules.mk build-cockpit-plugin; \ diff --git a/src/librslapd/Cargo.toml b/src/librslapd/Cargo.toml new file mode 100644 index 000000000..3111e598a --- /dev/null +++ b/src/librslapd/Cargo.toml @@ -0,0 +1,24 @@ +[package] +name = "librslapd" +version = "0.1.0" +authors = ["William Brown <[email protected]>"] +edition = "2018" +build = "build.rs" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[lib] +path = "src/lib.rs" +name = "rslapd" +crate-type = ["staticlib", "lib"] + +[profile.release] +panic = "abort" +lto = true + + +[dependencies] + +[build-dependencies] +cbindgen = "0.9" + diff --git a/src/librslapd/build.rs b/src/librslapd/build.rs new file mode 100644 index 000000000..4d4c1ce42 --- /dev/null +++ b/src/librslapd/build.rs @@ -0,0 +1,15 @@ +extern crate cbindgen; + +use std::env; + +fn main() { + let crate_dir = env::var("CARGO_MANIFEST_DIR").unwrap(); + let out_dir = env::var("SLAPD_HEADER_DIR").unwrap(); + + cbindgen::Builder::new() + .with_language(cbindgen::Language::C) + .with_crate(crate_dir) + .generate() + .expect("Unable to generate bindings") + .write_to_file(format!("{}/rust-slapi-private.h", out_dir)); +} diff --git a/src/librslapd/src/lib.rs b/src/librslapd/src/lib.rs new file mode 100644 index 000000000..e485f926e --- /dev/null +++ b/src/librslapd/src/lib.rs @@ -0,0 +1,12 @@ +#[no_mangle] +pub extern "C" fn do_nothing_rust() -> usize { + 0 +} + +#[cfg(test)] +mod tests { + #[test] + fn it_works() { + assert_eq!(2 + 2, 4); + } +} diff --git a/src/libsds/Cargo.toml b/src/libsds/Cargo.toml index 6c035aedb..518cc6e94 100644 --- a/src/libsds/Cargo.toml +++ b/src/libsds/Cargo.toml @@ -1,7 +1,8 @@ [package] name = "rsds" version = "0.1.0" -authors = ["William Brown <[email protected]>"] +authors = ["William Brown <[email protected]>"] +edition = "2018" [dependencies] @@ -14,3 +15,4 @@ crate-type = ["staticlib", "lib"] panic = "abort" lto = true +
0
bb596ce2170ca956f9cb80e7727f6ebbd46d4834
389ds/389-ds-base
Ticket #48265 - CI test: added test cases for ticket 48265 Description: Complex filter in a search request doen't work as expected.
commit bb596ce2170ca956f9cb80e7727f6ebbd46d4834 Author: Noriko Hosoi <[email protected]> Date: Thu Sep 3 10:16:05 2015 -0700 Ticket #48265 - CI test: added test cases for ticket 48265 Description: Complex filter in a search request doen't work as expected. diff --git a/dirsrvtests/tickets/ticket48265_test.py b/dirsrvtests/tickets/ticket48265_test.py new file mode 100644 index 000000000..fb695c57b --- /dev/null +++ b/dirsrvtests/tickets/ticket48265_test.py @@ -0,0 +1,130 @@ +# --- 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 threading +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 * + +logging.getLogger(__name__).setLevel(logging.DEBUG) +log = logging.getLogger(__name__) + +installation1_prefix = None + +USER_NUM = 20 +TEST_USER = 'test_user' + +class TopologyStandalone(object): + def __init__(self, standalone): + standalone.open() + self.standalone = standalone + + [email protected](scope="module") +def topology(request): + global installation1_prefix + if installation1_prefix: + args_instance[SER_DEPLOYED_DIR] = installation1_prefix + + # Creating standalone instance ... + standalone = DirSrv(verbose=False) + args_instance[SER_HOST] = HOST_STANDALONE + args_instance[SER_PORT] = PORT_STANDALONE + args_instance[SER_SERVERID_PROP] = SERVERID_STANDALONE + args_instance[SER_CREATION_SUFFIX] = DEFAULT_SUFFIX + args_standalone = args_instance.copy() + standalone.allocate(args_standalone) + instance_standalone = standalone.exists() + if instance_standalone: + standalone.delete() + standalone.create() + standalone.open() + + return TopologyStandalone(standalone) + + +def test_ticket48265_test(topology): + """ + Complex filter issues + Ticket 47521 type complex filter: + (&(|(uid=tuser*)(cn=Test user*))(&(givenname=test*3))([email protected])(&(description=*))) + Ticket 48264 type complex filter: + (&(&(|(l=EU)(l=AP)(l=NA))(|(c=SE)(c=DE)))(|(uid=*test*)(cn=*test*))(l=eu)) + """ + + log.info("Adding %d test entries..." % USER_NUM) + for id in range(USER_NUM): + name = "%s%d" % (TEST_USER, id) + mail = "%[email protected]" % name + secretary = "cn=%s,ou=secretary,%s" % (name, SUFFIX) + topology.standalone.add_s(Entry(("cn=%s,%s" % (name, SUFFIX), { + 'objectclass': "top person organizationalPerson inetOrgPerson".split(), + 'sn': name, + 'cn': name, + 'uid': name, + 'givenname': 'test', + 'mail': mail, + 'description': 'description', + 'secretary': secretary, + 'l': 'MV', + 'title': 'Engineer'}))) + + log.info("Search with Ticket 47521 type complex filter") + for id in range(USER_NUM): + name = "%s%d" % (TEST_USER, id) + mail = "%[email protected]" % name + filter47521 = '(&(|(uid=%s*)(cn=%s*))(&(givenname=test))(mail=%s)(&(description=*)))' % (TEST_USER, TEST_USER, mail) + entry = topology.standalone.search_s(SUFFIX, ldap.SCOPE_SUBTREE, filter47521) + assert len(entry) == 1 + + log.info("Search with Ticket 48265 type complex filter") + for id in range(USER_NUM): + name = "%s%d" % (TEST_USER, id) + mail = "%[email protected]" % name + filter48265 = '(&(&(|(l=AA)(l=BB)(l=MV))(|(title=admin)(title=engineer)))(|(uid=%s)(mail=%s))(description=description))' % (name, mail) + entry = topology.standalone.search_s(SUFFIX, ldap.SCOPE_SUBTREE, filter48265) + assert len(entry) == 1 + + log.info('Test 48265 complete\n') + + +def test_ticket48265_final(topology): + topology.standalone.delete() + log.info('Testcase PASSED') + + +def run_isolated(): + ''' + 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 installation1_prefix + installation1_prefix = None + + topo = topology(True) + log.info('Testing Ticket 48265 - Complex filter in a search request does not work as expected') + + test_ticket48265_test(topo) + + test_ticket48265_final(topo) + + +if __name__ == '__main__': + run_isolated()
0
f983a594b4a76f1e61af55d13c3ed7bef793078e
389ds/389-ds-base
Ticket 48912 - ntUserNtPassword schema Bug Description: FreeRADIOS needs access to an NT hash password to work with pure ldap. We should support this. Fix Description: add ntUserNtPassword to schema for applications to be able to set. https://fedorahosted.org/389/ticket/48912 Author: wibrown Review by: mreynolds (Thanks)
commit f983a594b4a76f1e61af55d13c3ed7bef793078e Author: William Brown <[email protected]> Date: Mon Jul 11 10:37:33 2016 +1000 Ticket 48912 - ntUserNtPassword schema Bug Description: FreeRADIOS needs access to an NT hash password to work with pure ldap. We should support this. Fix Description: add ntUserNtPassword to schema for applications to be able to set. https://fedorahosted.org/389/ticket/48912 Author: wibrown Review by: mreynolds (Thanks) diff --git a/ldap/schema/50ns-directory.ldif b/ldap/schema/50ns-directory.ldif index 062ac9797..1f85398dc 100644 --- a/ldap/schema/50ns-directory.ldif +++ b/ldap/schema/50ns-directory.ldif @@ -77,6 +77,7 @@ attributeTypes: ( 2.16.840.1.113730.3.1.533 NAME 'ntUserCodePage' DESC 'Netscape attributeTypes: ( 2.16.840.1.113730.3.1.534 NAME 'ntUserPrimaryGroupId' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.5 SINGLE-VALUE X-ORIGIN 'Netscape NT Synchronization' ) attributeTypes: ( 2.16.840.1.113730.3.1.535 NAME 'ntUserHomeDirDrive' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 SINGLE-VALUE X-ORIGIN 'Netscape NT Synchronization' ) attributeTypes: ( 2.16.840.1.113730.3.1.536 NAME 'ntGroupAttributes' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.5 SINGLE-VALUE X-ORIGIN 'Netscape NT Synchronization' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2334 NAME 'ntUserNtPassword' DESC 'Netscape defined attribute type, synced or generated NT Password hash' SYNTAX 1.3.6.1.4.1.1466.115.121.1.5 SINGLE-VALUE X-ORIGIN 'Netscape NT Synchronization' ) attributeTypes: ( 2.16.840.1.113730.3.1.54 NAME 'replicaUseSSL' 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.57 NAME 'replicaRoot' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.12 X-ORIGIN 'Netscape Directory Server' ) attributeTypes: ( 2.16.840.1.113730.3.1.58 NAME 'replicaBindDn' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.12 X-ORIGIN 'Netscape Directory Server' ) @@ -84,7 +85,7 @@ attributeTypes: ( 2.16.840.1.113730.3.1.69 NAME 'subtreeACI' DESC 'Netscape defi attributeTypes: ( 2.16.840.1.113730.3.1.2084 NAME 'nsSymmetricKey' DESC 'A symmetric key - currently used by attribute encryption' SYNTAX 1.3.6.1.4.1.1466.115.121.1.40 SINGLE-VALUE X-ORIGIN 'attribute encryption' ) objectClasses: ( 2.16.840.1.113730.3.2.23 NAME 'netscapeDirectoryServer' DESC 'Netscape defined objectclass' SUP top MUST ( objectclass ) X-ORIGIN 'Netscape Directory Server' ) objectClasses: ( nsDirectoryServer-oid NAME 'nsDirectoryServer' DESC 'Netscape defined objectclass' SUP top MUST ( objectclass $ nsServerID ) MAY ( serverHostName $ nsServerPort $ nsSecureServerPort $ nsBindPassword $ nsBindDN $ nsBaseDN ) X-ORIGIN 'Netscape Directory Server' ) -objectClasses: ( 2.16.840.1.113730.3.2.8 NAME 'ntUser' DESC 'Netscape defined objectclass' SUP top MUST ( ntUserDomainId ) MAY ( description $ l $ ou $ seeAlso $ ntUserPriv $ ntUserHomeDir $ ntUserComment $ ntUserFlags $ ntUserScriptPath $ ntUserAuthFlags $ ntUserUsrComment $ ntUserParms $ ntUserWorkstations $ ntUserLastLogon $ ntUserLastLogoff $ ntUserAcctExpires $ ntUserMaxStorage $ ntUserUnitsPerWeek $ ntUserLogonHours $ ntUserBadPwCount $ ntUserNumLogons $ ntUserLogonServer $ ntUserCountryCode $ ntUserCodePage $ ntUserUniqueId $ ntUserPrimaryGroupId $ ntUserProfile $ ntUserHomeDirDrive $ ntUserPasswordExpired $ ntUserCreateNewAccount $ ntUserDeleteAccount $ ntUniqueId) X-ORIGIN 'Netscape NT Synchronization' ) +objectClasses: ( 2.16.840.1.113730.3.2.8 NAME 'ntUser' DESC 'Netscape defined objectclass' SUP top MUST ( ntUserDomainId ) MAY ( description $ l $ ou $ seeAlso $ ntUserPriv $ ntUserHomeDir $ ntUserComment $ ntUserFlags $ ntUserScriptPath $ ntUserAuthFlags $ ntUserUsrComment $ ntUserParms $ ntUserWorkstations $ ntUserLastLogon $ ntUserLastLogoff $ ntUserAcctExpires $ ntUserMaxStorage $ ntUserUnitsPerWeek $ ntUserLogonHours $ ntUserBadPwCount $ ntUserNumLogons $ ntUserLogonServer $ ntUserCountryCode $ ntUserCodePage $ ntUserUniqueId $ ntUserPrimaryGroupId $ ntUserProfile $ ntUserHomeDirDrive $ ntUserPasswordExpired $ ntUserCreateNewAccount $ ntUserDeleteAccount $ ntUniqueId $ ntUserNtPassword ) X-ORIGIN 'Netscape NT Synchronization' ) objectClasses: ( 2.16.840.1.113730.3.2.9 NAME 'ntGroup' DESC 'Netscape defined objectclass' SUP top MUST ( ntUserDomainId ) MAY ( description $ l $ ou $ seeAlso $ ntGroupId $ ntGroupAttributes $ ntGroupCreateNewGroup $ ntGroupDeleteGroup $ ntGroupType $ ntUniqueId $ mail ) X-ORIGIN 'Netscape NT Synchronization' ) objectClasses: ( 2.16.840.1.113730.3.2.82 NAME 'nsChangelog4Config' DESC 'Netscape defined objectclass' SUP top MAY ( cn ) X-ORIGIN 'Netscape Directory Server' ) objectClasses: ( 2.16.840.1.113730.3.2.114 NAME 'nsConsumer4Config' DESC 'Netscape defined objectclass' SUP top MAY ( cn ) X-ORIGIN 'Netscape Directory Server' )
0
f92eb8289632c918e3fc13e88e18e3103cd7851a
389ds/389-ds-base
168322 - Check size of hash needed before base64 encoding password hashes
commit f92eb8289632c918e3fc13e88e18e3103cd7851a Author: Nathan Kinder <[email protected]> Date: Wed Sep 14 23:37:37 2005 +0000 168322 - Check size of hash needed before base64 encoding password hashes diff --git a/ldap/servers/plugins/pwdstorage/ssha_pwd.c b/ldap/servers/plugins/pwdstorage/ssha_pwd.c index b23c2adfc..ac72e46ed 100644 --- a/ldap/servers/plugins/pwdstorage/ssha_pwd.c +++ b/ldap/servers/plugins/pwdstorage/ssha_pwd.c @@ -175,14 +175,14 @@ salted_sha_pw_enc( char *pwd, unsigned int shaLen ) } if (( enc = slapi_ch_malloc( 3 + schemeNameLen + - LDIF_BASE64_LEN(sizeof(hash)))) == NULL ) { + LDIF_BASE64_LEN(shaLen + SHA_SALT_LENGTH))) == NULL ) { return( NULL ); } sprintf( enc, "%c%s%c", PWD_HASH_PREFIX_START, schemeName, PWD_HASH_PREFIX_END ); (void)ldif_base64_encode( hash, enc + 2 + schemeNameLen, - sizeof(hash), -1 ); + (shaLen + SHA_SALT_LENGTH), -1 ); return( enc ); }
0
8e02614813752d70a42db7c7f911e410b5b4eb4c
389ds/389-ds-base
Resolves: 455913 Summary: Don't use Slapi_Mod on the stack.
commit 8e02614813752d70a42db7c7f911e410b5b4eb4c Author: Nathan Kinder <[email protected]> Date: Fri Jul 18 18:11:30 2008 +0000 Resolves: 455913 Summary: Don't use Slapi_Mod on the stack. diff --git a/ldap/servers/plugins/memberof/memberof.c b/ldap/servers/plugins/memberof/memberof.c index a7d8b75bf..17769f4fe 100644 --- a/ldap/servers/plugins/memberof/memberof.c +++ b/ldap/servers/plugins/memberof/memberof.c @@ -2115,24 +2115,25 @@ int memberof_fix_memberof_callback(Slapi_Entry *e, void *callback_data) { Slapi_PBlock *mod_pb = slapi_pblock_new(); Slapi_Value *val = 0; - Slapi_Mod smod; + Slapi_Mod *smod; LDAPMod **mods = (LDAPMod **) slapi_ch_malloc(2 * sizeof(LDAPMod *)); int hint = 0; - slapi_mod_init(&smod, 0); - slapi_mod_set_operation(&smod, LDAP_MOD_REPLACE | LDAP_MOD_BVALUES); - slapi_mod_set_type(&smod, config->memberof_attr); + smod = slapi_mod_new(); + slapi_mod_init(smod, 0); + slapi_mod_set_operation(smod, LDAP_MOD_REPLACE | LDAP_MOD_BVALUES); + slapi_mod_set_type(smod, config->memberof_attr); /* Loop through all of our values and add them to smod */ hint = slapi_valueset_first_value(groups, &val); while (val) { /* this makes a copy of the berval */ - slapi_mod_add_value(&smod, slapi_value_get_berval(val)); + slapi_mod_add_value(smod, slapi_value_get_berval(val)); hint = slapi_valueset_next_value(groups, hint, &val); } - mods[0] = slapi_mod_get_ldapmod_passout(&smod); + mods[0] = slapi_mod_get_ldapmod_passout(smod); mods[1] = 0; slapi_modify_internal_set_pb( @@ -2144,7 +2145,7 @@ int memberof_fix_memberof_callback(Slapi_Entry *e, void *callback_data) slapi_pblock_get(mod_pb, SLAPI_PLUGIN_INTOP_RESULT, &rc); ldap_mods_free(mods, 1); - slapi_mod_done(&smod); + slapi_mod_free(&smod); slapi_pblock_destroy(mod_pb); } else { /* No groups were found, so remove the memberOf attribute
0
b2ef43edddb4316a479ab57d47a82e607404330a
389ds/389-ds-base
Ticket #48662 - db2index with no attribute args fail. Description: commit 5a33dc002205d2167c786dd2c05f23218f28341d for #48662 failed to support the case: db2index -Z SERVERID -n BACKEND When the command line satisfies the condition, it executes indexing all. https://fedorahosted.org/389/ticket/48662 Reviewed by [email protected] (Thank you, William!!)
commit b2ef43edddb4316a479ab57d47a82e607404330a Author: Noriko Hosoi <[email protected]> Date: Tue Apr 26 14:05:46 2016 -0700 Ticket #48662 - db2index with no attribute args fail. Description: commit 5a33dc002205d2167c786dd2c05f23218f28341d for #48662 failed to support the case: db2index -Z SERVERID -n BACKEND When the command line satisfies the condition, it executes indexing all. https://fedorahosted.org/389/ticket/48662 Reviewed by [email protected] (Thank you, William!!) diff --git a/ldap/admin/src/scripts/db2index.in b/ldap/admin/src/scripts/db2index.in index ad28757f1..748c58bcb 100755 --- a/ldap/admin/src/scripts/db2index.in +++ b/ldap/admin/src/scripts/db2index.in @@ -72,8 +72,10 @@ elif [ -z $benameopt ] && [ -z $includeSuffix ]; then fi if [ -z $servid ] && [ $# -lt 2 ]; then print_usage=1 -elif [ "$servid" ] && [ $# -lt 4 ]; then +elif [ -n "$servid" ] && [ $# -lt 4 ]; then print_usage=1 +elif [ -n "$servid" ] && [ $# -eq 4 ]; then + idxall=1 fi servid=`normalize_server_id $initfile`
0
089c1d58cefdf21b9ab2f2f4f46a81d32cbea715
389ds/389-ds-base
Issue 3996 - Add dsidm rename option (#4338) Description: Add rename option to dsidm CLI. user, group, posixgroup, organizationalunit - rename by rdn. account, role - rename by dn. Set Account._protected = False by default so we can run rename and delete operations. Fix typos in dsidm CLI code. Reviewed by: @mreynolds389 and @Firstyear (Thanks!!) Fixes: #4127 Fixes: #3996
commit 089c1d58cefdf21b9ab2f2f4f46a81d32cbea715 Author: Simon Pichugin <[email protected]> Date: Thu Sep 24 10:25:04 2020 +0200 Issue 3996 - Add dsidm rename option (#4338) Description: Add rename option to dsidm CLI. user, group, posixgroup, organizationalunit - rename by rdn. account, role - rename by dn. Set Account._protected = False by default so we can run rename and delete operations. Fix typos in dsidm CLI code. Reviewed by: @mreynolds389 and @Firstyear (Thanks!!) Fixes: #4127 Fixes: #3996 diff --git a/src/lib389/lib389/cli_idm/__init__.py b/src/lib389/lib389/cli_idm/__init__.py index 59aedd907..57273ff81 100644 --- a/src/lib389/lib389/cli_idm/__init__.py +++ b/src/lib389/lib389/cli_idm/__init__.py @@ -7,6 +7,7 @@ # See LICENSE for details. # --- END COPYRIGHT BLOCK --- +import ldap from getpass import getpass import json @@ -115,4 +116,51 @@ def _generic_delete(inst, basedn, log, object_class, dn, args=None): o.delete() log.info('Successfully deleted %s' % dn) + +def _generic_rename_inner(log, o, new_rdn, newsuperior=None, deloldrdn=None): + # The default argument behaviour is defined in _mapped_object.py + arguments = {'new_rdn': new_rdn} + if newsuperior is not None: + arguments['newsuperior'] = newsuperior + if deloldrdn is not None: + arguments['deloldrdn'] = deloldrdn + o.rename(**arguments) + print('Successfully renamed to %s' % o.dn) + + +def _generic_rename(inst, basedn, log, manager_class, selector, args=None): + if not args or not args.new_name: + raise ValueError("Missing a new name argument.") + # Here, we should have already selected the type etc. mc should be a + # type of DSLdapObjects (plural) + mc = manager_class(inst, basedn) + # Get the object singular by selector + o = mc.get(selector) + rdn_attr = ldap.dn.str2dn(o.dn)[0][0][0] + arguments = {'new_rdn': f'{rdn_attr}={args.new_name}'} + if args.keep_old_rdn: + arguments['deloldrdn'] = False + _generic_rename_inner(log, o, **arguments) + + +def _generic_rename_dn(inst, basedn, log, manager_class, dn, args=None): + if not args or not args.new_dn: + raise ValueError("Missing a new DN argument.") + if not ldap.dn.is_dn(args.new_dn): + raise ValueError(f"Specified DN '{args.new_dn}' is not a valid DN") + # Here, we should have already selected the type etc. mc should be a + # type of DSLdapObjects (plural) + mc = manager_class(inst, basedn) + # Get the object singular by dn + o = mc.get(dn=dn) + old_parent = ",".join(ldap.dn.explode_dn(o.dn.lower())[1:]) + new_parent = ",".join(ldap.dn.explode_dn(args.new_dn.lower())[1:]) + new_rdn = ldap.dn.explode_dn(args.new_dn.lower())[0] + arguments = {'new_rdn': new_rdn} + if old_parent != new_parent: + arguments['newsuperior'] = new_parent + if args.keep_old_rdn: + arguments['deloldrdn'] = False + _generic_rename_inner(log, o, **arguments) + # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 diff --git a/src/lib389/lib389/cli_idm/account.py b/src/lib389/lib389/cli_idm/account.py index 3e9f37eed..1dec2b5d0 100644 --- a/src/lib389/lib389/cli_idm/account.py +++ b/src/lib389/lib389/cli_idm/account.py @@ -20,6 +20,7 @@ from lib389.cli_base import ( _get_dn_arg, _warn, ) +from lib389.cli_idm import _generic_rename_dn MANY = Accounts SINGULAR = Account @@ -43,7 +44,12 @@ def delete(inst, basedn, log, args, warn=True): def modify(inst, basedn, log, args, warn=True): dn = _get_dn_arg(args.dn, msg="Enter dn to modify") - _generic_modify_dn(inst, basedn, log.getChild('_generic_modify'), MANY, dn, args) + _generic_modify_dn(inst, basedn, log.getChild('_generic_modify_dn'), MANY, dn, args) + + +def rename(inst, basedn, log, args, warn=True): + dn = _get_dn_arg(args.dn, msg="Enter dn to modify") + _generic_rename_dn(inst, basedn, log.getChild('_generic_rename_dn'), MANY, dn, args) def _print_entry_status(status, dn, log): @@ -148,6 +154,12 @@ like modify, locking and unlocking. To create an account, see "user" subcommand modify_dn_parser.add_argument('dn', nargs=1, help='The dn to get and display') modify_dn_parser.add_argument('changes', nargs='+', help="A list of changes to apply in format: <add|delete|replace>:<attribute>:<value>") + rename_dn_parser = subcommands.add_parser('rename-by-dn', help='rename the object') + rename_dn_parser.set_defaults(func=rename) + rename_dn_parser.add_argument('dn', help='The dn to rename') + rename_dn_parser.add_argument('new_dn', help='A new role dn') + rename_dn_parser.add_argument('--keep-old-rdn', action='store_true', help="Specify whether the old RDN (i.e. 'cn: old_role') should be kept as an attribute of the entry or not") + delete_parser = subcommands.add_parser('delete', help='deletes the account') delete_parser.set_defaults(func=delete) delete_parser.add_argument('dn', nargs='?', help='The dn of the account to delete') diff --git a/src/lib389/lib389/cli_idm/group.py b/src/lib389/lib389/cli_idm/group.py index f283dffc4..018e52633 100644 --- a/src/lib389/lib389/cli_idm/group.py +++ b/src/lib389/lib389/cli_idm/group.py @@ -13,6 +13,7 @@ from lib389.cli_idm import ( _generic_get, _generic_get_dn, _generic_create, + _generic_rename, _generic_delete, _get_arg, _get_attributes, @@ -50,6 +51,10 @@ def modify(inst, basedn, log, args, warn=True): rdn = _get_arg( args.selector, msg="Enter %s to retrieve" % RDN) _generic_modify(inst, basedn, log.getChild('_generic_modify'), MANY, rdn, args) +def rename(inst, basedn, log, args, warn=True): + rdn = _get_arg( args.selector, msg="Enter %s to retrieve" % RDN) + _generic_rename(inst, basedn, log.getChild('_generic_rename'), MANY, rdn, args) + def members(inst, basedn, log, args): cn = _get_arg( args.cn, msg="Enter %s of group" % RDN) groups = MANY(inst, basedn) @@ -107,6 +112,12 @@ def create_parser(subparsers): modify_parser.add_argument('selector', nargs=1, help='The %s to modify' % RDN) modify_parser.add_argument('changes', nargs='+', help="A list of changes to apply in format: <add|delete|replace>:<attribute>:<value>") + rename_parser = subcommands.add_parser('rename', help='rename the object') + rename_parser.set_defaults(func=rename) + rename_parser.add_argument('selector', help='The %s to rename' % RDN) + rename_parser.add_argument('new_name', help='A new group name') + rename_parser.add_argument('--keep-old-rdn', action='store_true', help="Specify whether the old RDN (i.e. 'cn: old_group') should be kept as an attribute of the entry or not") + members_parser = subcommands.add_parser('members', help="List member dns of a group") members_parser.set_defaults(func=members) members_parser.add_argument('cn', nargs='?', help="cn of group to list members of") diff --git a/src/lib389/lib389/cli_idm/organizationalunit.py b/src/lib389/lib389/cli_idm/organizationalunit.py index d2ce82d8a..b052fc2bf 100644 --- a/src/lib389/lib389/cli_idm/organizationalunit.py +++ b/src/lib389/lib389/cli_idm/organizationalunit.py @@ -13,6 +13,7 @@ from lib389.cli_idm import ( _generic_get, _generic_get_dn, _generic_create, + _generic_rename, _generic_delete, _get_arg, _get_attributes, @@ -49,6 +50,10 @@ def modify(inst, basedn, log, args, warn=True): rdn = _get_arg( args.selector, msg="Enter %s to retrieve" % RDN) _generic_modify(inst, basedn, log.getChild('_generic_modify'), MANY, rdn, args) +def rename(inst, basedn, log, args, warn=True): + rdn = _get_arg( args.selector, msg="Enter %s to retrieve" % RDN) + _generic_rename(inst, basedn, log.getChild('_generic_rename'), MANY, rdn, args) + def create_parser(subparsers): ou_parser = subparsers.add_parser('organizationalunit', help='Manage organizational units') @@ -78,5 +83,12 @@ def create_parser(subparsers): modify_parser.add_argument('selector', nargs=1, help='The %s to modify' % RDN) modify_parser.add_argument('changes', nargs='+', help="A list of changes to apply in format: <add|delete|replace>:<attribute>:<value>") + rename_parser = subcommands.add_parser('rename', help='rename the object') + rename_parser.set_defaults(func=rename) + rename_parser.add_argument('selector', help='The %s to rename' % RDN) + rename_parser.add_argument('new_name', help='A new organizational unit name') + rename_parser.add_argument('--keep-old-rdn', action='store_true', help="Specify whether the old RDN (i.e. 'ou: old_ou') should be kept as an attribute of the entry or not") + + # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 diff --git a/src/lib389/lib389/cli_idm/posixgroup.py b/src/lib389/lib389/cli_idm/posixgroup.py index 2a67dc4a3..71f28d84a 100644 --- a/src/lib389/lib389/cli_idm/posixgroup.py +++ b/src/lib389/lib389/cli_idm/posixgroup.py @@ -13,6 +13,7 @@ from lib389.cli_idm import ( _generic_get, _generic_get_dn, _generic_create, + _generic_rename, _generic_delete, _get_arg, _get_attributes, @@ -49,6 +50,10 @@ def modify(inst, basedn, log, args, warn=True): rdn = _get_arg( args.selector, msg="Enter %s to retrieve" % RDN) _generic_modify(inst, basedn, log.getChild('_generic_modify'), MANY, rdn, args) +def rename(inst, basedn, log, args, warn=True): + rdn = _get_arg( args.selector, msg="Enter %s to retrieve" % RDN) + _generic_rename(inst, basedn, log.getChild('_generic_rename'), MANY, rdn, args) + def create_parser(subparsers): posixgroup_parser = subparsers.add_parser('posixgroup', help='Manage posix groups') @@ -78,4 +83,10 @@ def create_parser(subparsers): modify_parser.add_argument('selector', nargs=1, help='The %s to modify' % RDN) modify_parser.add_argument('changes', nargs='+', help="A list of changes to apply in format: <add|delete|replace>:<attribute>:<value>") + rename_parser = subcommands.add_parser('rename', help='rename the object') + rename_parser.set_defaults(func=rename) + rename_parser.add_argument('selector', help='The %s to rename' % RDN) + rename_parser.add_argument('new_name', help='A new posix group name') + rename_parser.add_argument('--keep-old-rdn', action='store_true', help="Specify whether the old RDN (i.e. 'cn: old_group') should be kept as an attribute of the entry or not") + # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 diff --git a/src/lib389/lib389/cli_idm/role.py b/src/lib389/lib389/cli_idm/role.py index ad41a0f49..3bc6ad502 100644 --- a/src/lib389/lib389/cli_idm/role.py +++ b/src/lib389/lib389/cli_idm/role.py @@ -17,6 +17,7 @@ from lib389.cli_base import ( _get_dn_arg, _warn, ) +from lib389.cli_idm import _generic_rename_dn MANY = Roles SINGULAR = Role @@ -40,7 +41,12 @@ def delete(inst, basedn, log, args, warn=True): def modify(inst, basedn, log, args, warn=True): dn = _get_dn_arg(args.dn, msg="Enter dn to modify") - _generic_modify_dn(inst, basedn, log.getChild('_generic_modify'), MANY, dn, args) + _generic_modify_dn(inst, basedn, log.getChild('_generic_modify_dn'), MANY, dn, args) + + +def rename(inst, basedn, log, args, warn=True): + dn = _get_dn_arg(args.dn, msg="Enter dn to modify") + _generic_rename_dn(inst, basedn, log.getChild('_generic_rename_dn'), MANY, dn, args) def entry_status(inst, basedn, log, args): @@ -96,9 +102,15 @@ like modify, locking and unlocking.''') 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 get and display') + modify_dn_parser.add_argument('dn', nargs=1, help='The dn to modify') modify_dn_parser.add_argument('changes', nargs='+', help="A list of changes to apply in format: <add|delete|replace>:<attribute>:<value>") + rename_dn_parser = subcommands.add_parser('rename-by-dn', help='rename the object') + rename_dn_parser.set_defaults(func=rename) + rename_dn_parser.add_argument('dn', help='The dn to rename') + rename_dn_parser.add_argument('new_dn', help='A new account dn') + rename_dn_parser.add_argument('--keep-old-rdn', action='store_true', help="Specify whether the old RDN (i.e. 'cn: old_account') should be kept as an attribute of the entry or not") + delete_parser = subcommands.add_parser('delete', help='deletes the role') delete_parser.set_defaults(func=delete) delete_parser.add_argument('dn', nargs='?', help='The dn of the role to delete') diff --git a/src/lib389/lib389/cli_idm/user.py b/src/lib389/lib389/cli_idm/user.py index 426570af5..ecbab94fb 100644 --- a/src/lib389/lib389/cli_idm/user.py +++ b/src/lib389/lib389/cli_idm/user.py @@ -13,6 +13,7 @@ from lib389.cli_idm import ( _generic_get, _generic_get_dn, _generic_create, + _generic_rename, _generic_delete, _get_arg, _get_attributes, @@ -50,6 +51,10 @@ def modify(inst, basedn, log, args, warn=True): rdn = _get_arg( args.selector, msg="Enter %s to retrieve" % RDN) _generic_modify(inst, basedn, log.getChild('_generic_modify'), MANY, rdn, args) +def rename(inst, basedn, log, args, warn=True): + rdn = _get_arg( args.selector, msg="Enter %s to retrieve" % RDN) + _generic_rename(inst, basedn, log.getChild('_generic_rename'), MANY, rdn, args) + def create_parser(subparsers): user_parser = subparsers.add_parser('user', help='Manage posix users') @@ -75,6 +80,12 @@ def create_parser(subparsers): modify_parser.add_argument('selector', nargs=1, help='The %s to modify' % RDN) modify_parser.add_argument('changes', nargs='+', help="A list of changes to apply in format: <add|delete|replace>:<attribute>:<value>") + rename_parser = subcommands.add_parser('rename', help='rename the object') + rename_parser.set_defaults(func=rename) + rename_parser.add_argument('selector', help='The %s to modify' % RDN) + rename_parser.add_argument('new_name', help='A new user name') + rename_parser.add_argument('--keep-old-rdn', action='store_true', help="Specify whether the old RDN (i.e. 'cn: old_user')should be kept as an attribute of the entry or not") + delete_parser = subcommands.add_parser('delete', help='deletes the object') delete_parser.set_defaults(func=delete) delete_parser.add_argument('dn', nargs='?', help='The dn to delete') diff --git a/src/lib389/lib389/idm/account.py b/src/lib389/lib389/idm/account.py index 666b6231e..d44b416a5 100644 --- a/src/lib389/lib389/idm/account.py +++ b/src/lib389/lib389/idm/account.py @@ -44,6 +44,10 @@ class Account(DSLdapObject): :type dn: str """ + def __init__(self, instance, dn=None): + super(Account, self).__init__(instance, dn) + self._protected = False + def _format_status_message(self, message, create_time, modify_time, last_login_time, limit, role_dn=None): params = {} now = time.time()
0
e3efedecc1abc385a51f12aa11d2279ee1ac1a9d
389ds/389-ds-base
Resolves: #475338 Summary: LOG: the intenal type of maxlogsize, maxdiskspace and minfreespace should be 64-bit integer Description: support nsslapd-*log-maxlogsize, nsslapd-*log-logmaxdiskspace and nsslapd-*log-logminfreediskspace larger than 2GB.
commit e3efedecc1abc385a51f12aa11d2279ee1ac1a9d Author: Noriko Hosoi <[email protected]> Date: Wed Dec 10 06:23:24 2008 +0000 Resolves: #475338 Summary: LOG: the intenal type of maxlogsize, maxdiskspace and minfreespace should be 64-bit integer Description: support nsslapd-*log-maxlogsize, nsslapd-*log-logmaxdiskspace and nsslapd-*log-logminfreediskspace larger than 2GB. diff --git a/ldap/servers/slapd/log.c b/ldap/servers/slapd/log.c index 60817001b..37d5b7bed 100644 --- a/ldap/servers/slapd/log.c +++ b/ldap/servers/slapd/log.c @@ -121,9 +121,9 @@ static int log__delete_audit_logfile(); static int log__access_rotationinfof(char *pathname); static int log__error_rotationinfof(char *pathname); static int log__audit_rotationinfof(char *pathname); -static int log__extract_logheader (FILE *fp, long *f_ctime, int *f_size); +static int log__extract_logheader (FILE *fp, long *f_ctime, PRInt64 *f_size); static int log__check_prevlogs (FILE *fp, char *filename); -static int log__getfilesize(LOGFD fp); +static PRInt64 log__getfilesize(LOGFD fp); static int log__enough_freespace(char *path); static int vslapd_log_error(LOGFD fp, char *subsystem, char *fmt, va_list ap, int locked ); @@ -767,9 +767,9 @@ int log_set_logsize(const char *attrname, char *logsize_str, int logtype, char *returntext, int apply) { int rv = LDAP_SUCCESS; - int mdiskspace= 0; - int max_logsize; - int logsize; + PRInt64 mdiskspace= 0; /* in bytes */ + PRInt64 max_logsize; /* in bytes */ + int logsize; /* in megabytes */ slapdFrontendConfig_t *fe_cfg = getFrontendConfig(); if (!apply || !logsize_str || !*logsize_str) @@ -778,7 +778,7 @@ log_set_logsize(const char *attrname, char *logsize_str, int logtype, char *retu logsize = atoi(logsize_str); /* convert it to bytes */ - max_logsize = logsize * LOG_MB_IN_BYTES; + max_logsize = (PRInt64)logsize * LOG_MB_IN_BYTES; if (max_logsize <= 0) { max_logsize = -1; @@ -831,11 +831,11 @@ log_set_logsize(const char *attrname, char *logsize_str, int logtype, char *retu default: rv = 1; } - /* logsize will be in n MB. Convert it to bytes */ + /* logsize is in MB */ if (rv == 2) { LDAPDebug (LDAP_DEBUG_ANY, "Invalid value for Maximum log size:" - "Maxlogsize:%d MB Maxdisksize:%d MB\n", + "Maxlogsize:%d (MB) exceeds Maxdisksize:%d (MB)\n", logsize, mdiskspace/LOG_MB_IN_BYTES,0); rv = LDAP_OPERATIONS_ERROR; @@ -1244,9 +1244,9 @@ int log_set_maxdiskspace(const char *attrname, char *maxdiskspace_str, int logtype, char *errorbuf, int apply) { int rv = 0; - int mlogsize; - int maxdiskspace; - int s_maxdiskspace; + PRInt64 mlogsize; /* in bytes */ + PRInt64 maxdiskspace; /* in bytes */ + int s_maxdiskspace; /* in megabytes */ slapdFrontendConfig_t *fe_cfg = getFrontendConfig(); @@ -1261,8 +1261,7 @@ log_set_maxdiskspace(const char *attrname, char *maxdiskspace_str, int logtype, if (!apply || !maxdiskspace_str || !*maxdiskspace_str) return rv; - maxdiskspace = atoi(maxdiskspace_str); - s_maxdiskspace = maxdiskspace; + s_maxdiskspace = atoi(maxdiskspace_str); /* Disk space are in MB but store in bytes */ switch (logtype) { @@ -1282,44 +1281,42 @@ log_set_maxdiskspace(const char *attrname, char *maxdiskspace_str, int logtype, rv = 1; mlogsize = -1; } - maxdiskspace *= LOG_MB_IN_BYTES; + maxdiskspace = (PRInt64)s_maxdiskspace * LOG_MB_IN_BYTES; if (maxdiskspace < 0) { maxdiskspace = -1; - } - else if (maxdiskspace < mlogsize) { + } else if (maxdiskspace < mlogsize) { rv = LDAP_OPERATIONS_ERROR; PR_snprintf( errorbuf, SLAPI_DSE_RETURNTEXT_SIZE, - "%s: maxdiskspace \"%d\" is less than max log size \"%d\"", - attrname, maxdiskspace, mlogsize ); + "%s: \"%d (MB)\" is less than max log size \"%d (MB)\"", + attrname, s_maxdiskspace, (int)(mlogsize/LOG_MB_IN_BYTES) ); } switch (logtype) { case SLAPD_ACCESS_LOG: if (rv== 0 && apply) { - loginfo.log_access_maxdiskspace = maxdiskspace; - fe_cfg->accesslog_maxdiskspace = s_maxdiskspace ; + loginfo.log_access_maxdiskspace = maxdiskspace; /* in bytes */ + fe_cfg->accesslog_maxdiskspace = s_maxdiskspace; /* in megabytes */ } LOG_ACCESS_UNLOCK_WRITE(); break; case SLAPD_ERROR_LOG: if (rv== 0 && apply) { - loginfo.log_error_maxdiskspace = maxdiskspace; - fe_cfg->errorlog_maxdiskspace = s_maxdiskspace; + loginfo.log_error_maxdiskspace = maxdiskspace; /* in bytes */ + fe_cfg->errorlog_maxdiskspace = s_maxdiskspace; /* in megabytes */ } LOG_ERROR_UNLOCK_WRITE(); break; case SLAPD_AUDIT_LOG: if (rv== 0 && apply) { - loginfo.log_audit_maxdiskspace = maxdiskspace; - fe_cfg->auditlog_maxdiskspace = s_maxdiskspace; + loginfo.log_audit_maxdiskspace = maxdiskspace; /* in bytes */ + fe_cfg->auditlog_maxdiskspace = s_maxdiskspace; /* in megabytes */ } LOG_AUDIT_UNLOCK_WRITE(); break; default: PR_snprintf( errorbuf, SLAPI_DSE_RETURNTEXT_SIZE, - "%s: invalid maximum log disk size:" - "Maxdiskspace:%d MB Maxlogsize:%d MB \n", - attrname, maxdiskspace, mlogsize); + "%s: invalid log type (%d) for setting maximum disk space: %d MB\n", + attrname, logtype, s_maxdiskspace); rv = LDAP_OPERATIONS_ERROR; } return rv; @@ -1335,8 +1332,8 @@ int log_set_mindiskspace(const char *attrname, char *minfreespace_str, int logtype, char *errorbuf, int apply) { int rv=LDAP_SUCCESS; - int minfreespaceB; - int minfreespace; + int minfreespace; /* in megabytes */ + PRInt64 minfreespaceB; /* in bytes */ slapdFrontendConfig_t *fe_cfg = getFrontendConfig(); @@ -1357,7 +1354,7 @@ log_set_mindiskspace(const char *attrname, char *minfreespace_str, int logtype, /* Disk space are in MB but store in bytes */ if (minfreespace >= 1 ) { - minfreespaceB = minfreespace * LOG_MB_IN_BYTES; + minfreespaceB = (PRInt64)minfreespace * LOG_MB_IN_BYTES; switch (logtype) { case SLAPD_ACCESS_LOG: LOG_ACCESS_LOCK_WRITE( ); @@ -2115,13 +2112,13 @@ log__open_accesslogfile(int logfile_state, int locked) ** in the array stack. */ if (loginfo.log_access_fdes != NULL) { - struct logfileinfo *log; - char newfile[BUFSIZ]; - int f_size; + struct logfileinfo *log; + char newfile[BUFSIZ]; + PRInt64 f_size; /* get rid of the old one */ if ((f_size = log__getfilesize(loginfo.log_access_fdes)) == -1) { - /* Then assume that we have the max size */ + /* Then assume that we have the max size (in bytes) */ f_size = loginfo.log_access_maxlogsize; } @@ -2158,15 +2155,13 @@ log__open_accesslogfile(int logfile_state, int locked) } } - /* open a new log file */ if (! LOG_OPEN_APPEND(fp, loginfo.log_access_file, loginfo.log_access_mode)) { int oserr = errno; loginfo.log_access_fdes = NULL; if (!locked) LOG_ACCESS_UNLOCK_WRITE(); - LDAPDebug( LDAP_DEBUG_ANY, "access file open %s failed errno %d (%s)\n", - loginfo.log_access_file, - oserr, slapd_system_strerror(oserr)); + LDAPDebug(LDAP_DEBUG_ANY, "access file open %s failed errno %d (%s)\n", + loginfo.log_access_file, oserr, slapd_system_strerror(oserr)); return LOG_UNABLE_TO_OPENFILE; } @@ -2198,8 +2193,9 @@ log__open_accesslogfile(int logfile_state, int locked) logp = loginfo.log_access_logchain; while ( logp) { log_convert_time (logp->l_ctime, tbuf, 1 /*short*/); - PR_snprintf(buffer, sizeof(buffer), "LOGINFO:%s%s.%s (%lu) (%u)\n", - PREVLOGFILE, loginfo.log_access_file, tbuf, logp->l_ctime, logp->l_size); + PR_snprintf(buffer, sizeof(buffer), "LOGINFO:%s%s.%s (%lu) (%" + NSPRI64 "d)\n", PREVLOGFILE, loginfo.log_access_file, tbuf, + logp->l_ctime, logp->l_size); LOG_WRITE(fpinfo, buffer, strlen(buffer), 0); logp = logp->l_next; } @@ -2236,8 +2232,9 @@ log__needrotation(LOGFD fp, int logtype) time_t log_createtime= 0; time_t syncclock = 0; int type = LOG_CONTINUE; - int f_size = 0; - int maxlogsize, nlogs; + PRInt64 f_size = 0; + PRInt64 maxlogsize; + int nlogs; int rotationtime_secs = -1; int sync_enabled = 0, timeunit = 0; @@ -2316,22 +2313,24 @@ log__needrotation(LOGFD fp, int logtype) } log_rotate: - /* - ** Don't send messages to the error log whilst we're rotating it. - ** This'll lead to a recursive call to the logging function, and - ** an assertion trying to relock the write lock. - */ + /* + ** Don't send messages to the error log whilst we're rotating it. + ** This'll lead to a recursive call to the logging function, and + ** an assertion trying to relock the write lock. + */ if (logtype!=SLAPD_ERROR_LOG) - { - if (type == LOG_SIZE_EXCEEDED) { - LDAPDebug (LDAP_DEBUG_TRACE, - "LOGINFO:End of Log because size exceeded(Max:%d bytes) (Is:%d bytes)\n", maxlogsize, f_size, 0); - } else if ( type == LOG_EXPIRED) { - LDAPDebug(LDAP_DEBUG_TRACE, - "LOGINFO:End of Log because time exceeded(Max:%d secs) (Is:%ld secs)\n", - rotationtime_secs, curr_time - log_createtime,0); - } - } + { + if (type == LOG_SIZE_EXCEEDED) { + LDAPDebug (LDAP_DEBUG_TRACE, + "LOGINFO:End of Log because size exceeded(Max:%" + NSPRI64 "d bytes) (Is:%" NSPRI64 "d bytes)\n", + maxlogsize, f_size, 0); + } else if ( type == LOG_EXPIRED) { + LDAPDebug(LDAP_DEBUG_TRACE, + "LOGINFO:End of Log because time exceeded(Max:%d secs) (Is:%ld secs)\n", + rotationtime_secs, curr_time - log_createtime,0); + } + } return (type == LOG_CONTINUE) ? LOG_CONTINUE : LOG_ROTATE; } @@ -2349,18 +2348,18 @@ static int log__delete_access_logfile() { - struct logfileinfo *logp = NULL; - struct logfileinfo *delete_logp = NULL; - struct logfileinfo *p_delete_logp = NULL; - struct logfileinfo *prev_logp = NULL; - int total_size=0; - time_t cur_time; - int f_size; - int numoflogs=loginfo.log_numof_access_logs; - int rv = 0; - char *logstr; - char buffer[BUFSIZ]; - char tbuf[TBUFSIZE]; + struct logfileinfo *logp = NULL; + struct logfileinfo *delete_logp = NULL; + struct logfileinfo *p_delete_logp = NULL; + struct logfileinfo *prev_logp = NULL; + PRInt64 total_size=0; + time_t cur_time; + PRInt64 f_size; + int numoflogs=loginfo.log_numof_access_logs; + int rv = 0; + char *logstr; + char buffer[BUFSIZ]; + char tbuf[TBUFSIZE]; /* If we have only one log, then will delete this one */ if (loginfo.log_access_maxnumlogs == 1) { @@ -2629,7 +2628,7 @@ static int log__access_rotationinfof(char *pathname) { long f_ctime; - int f_size; + PRInt64 f_size; int main_log = 1; time_t now; FILE *fp; @@ -2782,14 +2781,17 @@ done: * size info of all the old log files. ******************************************************************************/ static int -log__extract_logheader (FILE *fp, long *f_ctime, int *f_size) +log__extract_logheader (FILE *fp, long *f_ctime, PRInt64 *f_size) { char buf[BUFSIZ]; char *p, *s, *next; + if (NULL == f_ctime || NULL == f_size) { + return LOG_ERROR; + } *f_ctime = 0L; - *f_size = 0; + *f_size = 0L; if ( fp == NULL) return LOG_ERROR; @@ -2817,11 +2819,11 @@ log__extract_logheader (FILE *fp, long *f_ctime, int *f_size) *s = '\0'; /* Now p must hold the ctime value */ - *f_ctime = atoi(p); + *f_ctime = strtol(p, (char **)NULL, 0); if ((p = strchr(next, '(')) == NULL) { /* that's fine -- it means we have no size info */ - *f_size = 0; + *f_size = 0L; return LOG_CONTINUE; } @@ -2833,7 +2835,7 @@ log__extract_logheader (FILE *fp, long *f_ctime, int *f_size) *next = '\0'; /* Now p must hold the size value */ - *f_size = atoi(p); + *f_size = strtoll(p, (char **)NULL, 0); /* check if the Previous Log file really exists */ if ((p = strstr(buf, PREVLOGFILE)) != NULL) { @@ -2867,7 +2869,7 @@ log__extract_logheader (FILE *fp, long *f_ctime, int *f_size) * probably a safe assumption for now. */ #ifdef XP_WIN32 -static int +static PRInt64 log__getfilesize(LOGFD fp) { struct stat info; @@ -2876,10 +2878,10 @@ log__getfilesize(LOGFD fp) if ((rv = fstat(fileno(fp), &info)) != 0) { return -1; } - return info.st_size; + return (PRInt64)info.st_size; } #else -static int +static PRInt64 log__getfilesize(LOGFD fp) { PRFileInfo info; @@ -2887,7 +2889,7 @@ log__getfilesize(LOGFD fp) if (PR_GetOpenFileInfo (fp, &info) == PR_FAILURE) { return -1; } - return info.size; + return (PRInt64)info.size; /* type of size is off_t */ } #endif @@ -3049,18 +3051,18 @@ static int log__delete_error_logfile(int locked) { - struct logfileinfo *logp = NULL; - struct logfileinfo *delete_logp = NULL; - struct logfileinfo *p_delete_logp = NULL; - struct logfileinfo *prev_logp = NULL; - int total_size=0; - time_t cur_time; - int f_size; - int numoflogs=loginfo.log_numof_error_logs; - int rv = 0; - char *logstr; - char buffer[BUFSIZ]; - char tbuf[TBUFSIZE]; + struct logfileinfo *logp = NULL; + struct logfileinfo *delete_logp = NULL; + struct logfileinfo *p_delete_logp = NULL; + struct logfileinfo *prev_logp = NULL; + PRInt64 total_size=0; + time_t cur_time; + PRInt64 f_size; + int numoflogs=loginfo.log_numof_error_logs; + int rv = 0; + char *logstr; + char buffer[BUFSIZ]; + char tbuf[TBUFSIZE]; /* If we have only one log, then will delete this one */ @@ -3222,18 +3224,18 @@ delete_logfile: static int log__delete_audit_logfile() { - struct logfileinfo *logp = NULL; - struct logfileinfo *delete_logp = NULL; - struct logfileinfo *p_delete_logp = NULL; - struct logfileinfo *prev_logp = NULL; - int total_size=0; - time_t cur_time; - int f_size; - int numoflogs=loginfo.log_numof_audit_logs; - int rv = 0; - char *logstr; - char buffer[BUFSIZ]; - char tbuf[TBUFSIZE]; + struct logfileinfo *logp = NULL; + struct logfileinfo *delete_logp = NULL; + struct logfileinfo *p_delete_logp = NULL; + struct logfileinfo *prev_logp = NULL; + PRInt64 total_size=0; + time_t cur_time; + PRInt64 f_size; + int numoflogs=loginfo.log_numof_audit_logs; + int rv = 0; + char *logstr; + char buffer[BUFSIZ]; + char tbuf[TBUFSIZE]; /* If we have only one log, then will delete this one */ if (loginfo.log_audit_maxnumlogs == 1) { @@ -3378,7 +3380,7 @@ static int log__error_rotationinfof( char *pathname) { long f_ctime; - int f_size; + PRInt64 f_size; int main_log = 1; time_t now; FILE *fp; @@ -3465,7 +3467,7 @@ static int log__audit_rotationinfof( char *pathname) { long f_ctime; - int f_size; + PRInt64 f_size; int main_log = 1; time_t now; FILE *fp; @@ -3607,9 +3609,9 @@ log__open_errorlogfile(int logfile_state, int locked) ** in the array stack. */ if (loginfo.log_error_fdes != NULL) { - struct logfileinfo *log; - char newfile[BUFSIZ]; - int f_size; + struct logfileinfo *log; + char newfile[BUFSIZ]; + PRInt64 f_size; /* get rid of the old one */ if ((f_size = log__getfilesize(loginfo.log_error_fdes)) == -1) { @@ -3704,8 +3706,9 @@ log__open_errorlogfile(int logfile_state, int locked) logp = loginfo.log_error_logchain; while (logp) { log_convert_time (logp->l_ctime, tbuf, 1 /*short */); - PR_snprintf(buffer, sizeof(buffer), "LOGINFO:%s%s.%s (%lu) (%u)\n", - PREVLOGFILE, loginfo.log_error_file, tbuf, logp->l_ctime, logp->l_size); + PR_snprintf(buffer, sizeof(buffer), "LOGINFO:%s%s.%s (%lu) (%" + NSPRI64 "d)\n", PREVLOGFILE, loginfo.log_error_file, tbuf, + logp->l_ctime, logp->l_size); LOG_WRITE(fpinfo, buffer, strlen(buffer), 0); logp = logp->l_next; } @@ -3747,9 +3750,9 @@ log__open_auditlogfile(int logfile_state, int locked) ** in the array stack. */ if (loginfo.log_audit_fdes != NULL) { - struct logfileinfo *log; - char newfile[BUFSIZ]; - int f_size; + struct logfileinfo *log; + char newfile[BUFSIZ]; + PRInt64 f_size; /* get rid of the old one */ @@ -3758,7 +3761,6 @@ log__open_auditlogfile(int logfile_state, int locked) f_size = loginfo.log_audit_maxlogsize; } - /* Check if I have to delete any old file, delete it if it is required. */ while (log__delete_audit_logfile()); @@ -3785,7 +3787,6 @@ log__open_auditlogfile(int logfile_state, int locked) } } - /* open a new log file */ if (! LOG_OPEN_APPEND(fp, loginfo.log_audit_file, loginfo.log_audit_mode)) { LDAPDebug(LDAP_DEBUG_ANY, "WARNING: can't open file %s. " @@ -3825,8 +3826,9 @@ log__open_auditlogfile(int logfile_state, int locked) logp = loginfo.log_audit_logchain; while ( logp) { log_convert_time (logp->l_ctime, tbuf, 1 /*short */); - PR_snprintf(buffer, sizeof(buffer), "LOGINFO:%s%s.%s (%d) (%d)\n", - PREVLOGFILE, loginfo.log_audit_file, tbuf, (int)logp->l_ctime, logp->l_size); + PR_snprintf(buffer, sizeof(buffer), "LOGINFO:%s%s.%s (%lu) (%" + NSPRI64 "d)\n", PREVLOGFILE, loginfo.log_audit_file, tbuf, + logp->l_ctime, logp->l_size); LOG_WRITE(fpinfo, buffer, strlen(buffer), 0); logp = logp->l_next; } @@ -4041,15 +4043,17 @@ log_reverse_convert_time(char *tbuf) int check_log_max_size( char *maxdiskspace_str, char *mlogsize_str, - int maxdiskspace, - int mlogsize, + int maxdiskspace, /* in megabytes */ + int mlogsize, /* in megabytes */ char * returntext, int logtype) { slapdFrontendConfig_t *slapdFrontendConfig = getFrontendConfig(); int rc = LDAP_SUCCESS; - int current_mlogsize = -1; - int current_maxdiskspace = -1; + int current_mlogsize = -1; /* in megabytes */ + int current_maxdiskspace = -1; /* in megabytes */ + PRInt64 mlogsizeB; /* in bytes */ + PRInt64 maxdiskspaceB; /* in bytes */ switch (logtype) { @@ -4070,35 +4074,40 @@ check_log_max_size( char *maxdiskspace_str, current_maxdiskspace = -1; } - if ( maxdiskspace == -1 ) + if ( maxdiskspace == -1 ) { maxdiskspace = current_maxdiskspace; - if ( mlogsize == -1 ) + } + maxdiskspaceB = (PRInt64)maxdiskspace * LOG_MB_IN_BYTES; + + if ( mlogsize == -1 ) { mlogsize = current_mlogsize; + } + mlogsizeB = (PRInt64)mlogsize * LOG_MB_IN_BYTES; if ( maxdiskspace < mlogsize ) { /* fail */ PR_snprintf ( returntext, SLAPI_DSE_RETURNTEXT_SIZE, - "%s: maxdiskspace \"%d\" is less than max log size \"%d\"", - maxdiskspace_str, maxdiskspace*LOG_MB_IN_BYTES, mlogsize*LOG_MB_IN_BYTES ); + "%s: maxdiskspace \"%d (MB)\" is less than max log size \"%d (MB)\"", + maxdiskspace_str, maxdiskspace, mlogsize ); rc = LDAP_OPERATIONS_ERROR; } switch (logtype) { case SLAPD_ACCESS_LOG: - loginfo.log_access_maxlogsize = mlogsize * LOG_MB_IN_BYTES; - loginfo.log_access_maxdiskspace = maxdiskspace * LOG_MB_IN_BYTES; + loginfo.log_access_maxlogsize = mlogsizeB; + loginfo.log_access_maxdiskspace = maxdiskspaceB; break; case SLAPD_ERROR_LOG: - loginfo.log_error_maxlogsize = mlogsize * LOG_MB_IN_BYTES; - loginfo.log_error_maxdiskspace = maxdiskspace * LOG_MB_IN_BYTES; + loginfo.log_error_maxlogsize = mlogsizeB; + loginfo.log_error_maxdiskspace = maxdiskspaceB; break; case SLAPD_AUDIT_LOG: - loginfo.log_audit_maxlogsize = mlogsize * LOG_MB_IN_BYTES; - loginfo.log_audit_maxdiskspace = maxdiskspace * LOG_MB_IN_BYTES; + loginfo.log_audit_maxlogsize = mlogsizeB; + loginfo.log_audit_maxdiskspace = maxdiskspaceB; break; default: - break; + break; } return rc; diff --git a/ldap/servers/slapd/log.h b/ldap/servers/slapd/log.h index 8fea00bdc..37d92b84e 100644 --- a/ldap/servers/slapd/log.h +++ b/ldap/servers/slapd/log.h @@ -116,9 +116,9 @@ typedef PRFileDesc *LOGFD; struct logfileinfo { - int l_size; /* size is in KB */ - time_t l_ctime; /* log creation time*/ - struct logfileinfo *l_next; /* next log */ + PRInt64 l_size; /* size is in bytes */ + time_t l_ctime; /* log creation time*/ + struct logfileinfo *l_next; /* next log */ }; typedef struct logfileinfo LogFileInfo; @@ -127,7 +127,7 @@ struct logbufinfo { char *current; /* current pointer into buffer */ size_t maxsize; /* size of buffer */ PRLock *lock; /* lock for access logging */ - PRInt32 refcount; /* Reference count for buffer copies */ + PRInt32 refcount; /* Reference count for buffer copies */ }; typedef struct logbufinfo LogBufferInfo; @@ -136,7 +136,7 @@ struct logging_opts { int log_access_state; int log_access_mode; /* access mode */ int log_access_maxnumlogs; /* Number of logs */ - int log_access_maxlogsize; /* max log size in bytes*/ + PRInt64 log_access_maxlogsize; /* max log size in bytes*/ int log_access_rotationtime; /* time in units. */ int log_access_rotationunit; /* time in units. */ int log_access_rotationtime_secs; /* time in seconds */ @@ -144,8 +144,8 @@ struct logging_opts { int log_access_rotationsynchour; /* 0-23 */ int log_access_rotationsyncmin; /* 0-59 */ time_t log_access_rotationsyncclock; /* clock in seconds */ - int log_access_maxdiskspace; /* space in bytes */ - int log_access_minfreespace; /* free space in bytes */ + PRInt64 log_access_maxdiskspace; /* space in bytes */ + PRInt64 log_access_minfreespace; /* free space in bytes */ int log_access_exptime; /* time */ int log_access_exptimeunit; /* unit time */ int log_access_exptime_secs; /* time in secs */ @@ -163,7 +163,7 @@ struct logging_opts { int log_error_state; int log_error_mode; /* access mode */ int log_error_maxnumlogs; /* Number of logs */ - int log_error_maxlogsize; /* max log size in bytes*/ + PRInt64 log_error_maxlogsize; /* max log size in bytes*/ int log_error_rotationtime; /* time in units. */ int log_error_rotationunit; /* time in units. */ int log_error_rotationtime_secs; /* time in seconds */ @@ -171,8 +171,8 @@ struct logging_opts { int log_error_rotationsynchour; /* 0-23 */ int log_error_rotationsyncmin; /* 0-59 */ time_t log_error_rotationsyncclock; /* clock in seconds */ - int log_error_maxdiskspace; /* space in bytes */ - int log_error_minfreespace; /* free space in bytes */ + PRInt64 log_error_maxdiskspace; /* space in bytes */ + PRInt64 log_error_minfreespace; /* free space in bytes */ int log_error_exptime; /* time */ int log_error_exptimeunit; /* unit time */ int log_error_exptime_secs; /* time in secs */ @@ -189,7 +189,7 @@ struct logging_opts { int log_audit_state; int log_audit_mode; /* access mode */ int log_audit_maxnumlogs; /* Number of logs */ - int log_audit_maxlogsize; /* max log size in bytes*/ + PRInt64 log_audit_maxlogsize; /* max log size in bytes*/ int log_audit_rotationtime; /* time in units. */ int log_audit_rotationunit; /* time in units. */ int log_audit_rotationtime_secs; /* time in seconds */ @@ -197,8 +197,8 @@ struct logging_opts { int log_audit_rotationsynchour; /* 0-23 */ int log_audit_rotationsyncmin; /* 0-59 */ time_t log_audit_rotationsyncclock; /* clock in seconds */ - int log_audit_maxdiskspace; /* space in bytes */ - int log_audit_minfreespace; /* free space in bytes */ + PRInt64 log_audit_maxdiskspace; /* space in bytes */ + PRInt64 log_audit_minfreespace; /* free space in bytes */ int log_audit_exptime; /* time */ int log_audit_exptimeunit; /* unit time */ int log_audit_exptime_secs; /* time in secs */
0
22eb878880eb98336e0c173d6d1db9e1d9c9da07
389ds/389-ds-base
Resolves: #460613 Summary: Approximate Search '~=' Returns unexpected result Change description: increasing the maximum length of "phonetic" string from 4 to 6. The length 4 is sometimes too short to distinguish long words. For instance, the sample string Queensland is converted to KNSLNT if there is no limitation; Consulting is to KNSLTNK. By cutting them at the 5th character, the 2 strings are considered to sound like each other.
commit 22eb878880eb98336e0c173d6d1db9e1d9c9da07 Author: Noriko Hosoi <[email protected]> Date: Mon Jan 12 19:18:38 2009 +0000 Resolves: #460613 Summary: Approximate Search '~=' Returns unexpected result Change description: increasing the maximum length of "phonetic" string from 4 to 6. The length 4 is sometimes too short to distinguish long words. For instance, the sample string Queensland is converted to KNSLNT if there is no limitation; Consulting is to KNSLTNK. By cutting them at the 5th character, the 2 strings are considered to sound like each other. diff --git a/ldap/servers/plugins/syntaxes/phonetic.c b/ldap/servers/plugins/syntaxes/phonetic.c index a974ebdab..4801cc70f 100644 --- a/ldap/servers/plugins/syntaxes/phonetic.c +++ b/ldap/servers/plugins/syntaxes/phonetic.c @@ -68,7 +68,7 @@ utf8iswordbreak( const char* s ) case 0x00A0: /* non-breaking space */ case 0x3000: /* ideographic space */ case 0xFEFF: /* zero-width non-breaking space */ - return 1; + return 1; default: break; } return 0; @@ -77,61 +77,61 @@ utf8iswordbreak( const char* s ) char * first_word( char *s ) { - if ( s == NULL ) { - return( NULL ); - } - - while ( iswordbreak( s ) ) { - if ( *s == '\0' ) { - return( NULL ); - } else { - LDAP_UTF8INC( s ); - } - } - - return( s ); + if ( s == NULL ) { + return( NULL ); + } + + while ( iswordbreak( s ) ) { + if ( *s == '\0' ) { + return( NULL ); + } else { + LDAP_UTF8INC( s ); + } + } + + return( s ); } char * next_word( char *s ) { - if ( s == NULL ) { - return( NULL ); - } - - while ( ! iswordbreak( s ) ) { - LDAP_UTF8INC( s ); - } - - while ( iswordbreak( s ) ) { - if ( *s == '\0' ) { - return( NULL ); - } else { - LDAP_UTF8INC( s ); - } - } - - return( s ); + if ( s == NULL ) { + return( NULL ); + } + + while ( ! iswordbreak( s ) ) { + LDAP_UTF8INC( s ); + } + + while ( iswordbreak( s ) ) { + if ( *s == '\0' ) { + return( NULL ); + } else { + LDAP_UTF8INC( s ); + } + } + + return( s ); } char * word_dup( char *w ) { - char *s, *ret; - char save; + char *s, *ret; + char save; - for ( s = w; !iswordbreak( s ); LDAP_UTF8INC( s )) - ; /* NULL */ - save = *s; - *s = '\0'; - ret = slapi_ch_strdup( w ); - *s = save; + for ( s = w; !iswordbreak( s ); LDAP_UTF8INC( s )) + ; /* NULL */ + save = *s; + *s = '\0'; + ret = slapi_ch_strdup( w ); + *s = save; - return( ret ); + return( ret ); } #ifndef MAXPHONEMELEN -#define MAXPHONEMELEN 4 +#define MAXPHONEMELEN 6 #endif #if defined(SOUNDEX) @@ -140,11 +140,11 @@ word_dup( char *w ) char * phonetic( char *s ) { - char code, adjacent, ch; - char *p; - char **c; - int i, cmax; - char phoneme[MAXPHONEMELEN + 1]; + char code, adjacent, ch; + char *p; + char **c; + int i, cmax; + char phoneme[MAXPHONEMELEN + 1]; p = s; if ( p == NULL || *p == '\0' ) { @@ -152,18 +152,18 @@ phonetic( char *s ) } adjacent = '0'; - phoneme[0] = TOUPPER(*p); + phoneme[0] = TOUPPER(*p); - phoneme[1] = '\0'; + phoneme[1] = '\0'; for ( i = 0; i < 99 && (! iswordbreak(p)); LDAP_UTF8INC( p )) { - ch = TOUPPER (*p); + ch = TOUPPER (*p); code = '0'; switch (ch) { case 'B': case 'F': - case 'P': + case 'P': case 'V': code = (adjacent != '1') ? '1' : '0'; break; @@ -196,18 +196,18 @@ phonetic( char *s ) } if ( i == 0 ) { - adjacent = code; - i++; - } else if ( code != '0' ) { - if ( i == MAXPHONEMELEN ) - break; + adjacent = code; + i++; + } else if ( code != '0' ) { + if ( i == MAXPHONEMELEN ) + break; adjacent = phoneme[i] = code; i++; } } - if ( i > 0 ) - phoneme[i] = '\0'; + if ( i > 0 ) + phoneme[i] = '\0'; return( slapi_ch_strdup( phoneme ) ); } @@ -224,274 +224,274 @@ phonetic( char *s ) /* Character coding array */ static char vsvfn[26] = { - 1, 16, 4, 16, 9, 2, 4, 16, 9, 2, 0, 2, 2, - /* A B C D E F G H I J K L M */ - 2, 1, 4, 0, 2, 4, 4, 1, 0, 0, 0, 8, 0}; - /* N O P Q R S T U V W X Y Z */ + 1, 16, 4, 16, 9, 2, 4, 16, 9, 2, 0, 2, 2, + /* A B C D E F G H I J K L M */ + 2, 1, 4, 0, 2, 4, 4, 1, 0, 0, 0, 8, 0}; + /* N O P Q R S T U V W X Y Z */ /* Macros to access character coding array */ -#define vowel(x) ((x) != '\0' && vsvfn[(x) - 'A'] & 1) /* AEIOU */ -#define same(x) ((x) != '\0' && vsvfn[(x) - 'A'] & 2) /* FJLMNR */ -#define varson(x) ((x) != '\0' && vsvfn[(x) - 'A'] & 4) /* CGPST */ -#define frontv(x) ((x) != '\0' && vsvfn[(x) - 'A'] & 8) /* EIY */ -#define noghf(x) ((x) != '\0' && vsvfn[(x) - 'A'] & 16) /* BDH */ +#define vowel(x) ((x) != '\0' && vsvfn[(x) - 'A'] & 1) /* AEIOU */ +#define same(x) ((x) != '\0' && vsvfn[(x) - 'A'] & 2) /* FJLMNR */ +#define varson(x) ((x) != '\0' && vsvfn[(x) - 'A'] & 4) /* CGPST */ +#define frontv(x) ((x) != '\0' && vsvfn[(x) - 'A'] & 8) /* EIY */ +#define noghf(x) ((x) != '\0' && vsvfn[(x) - 'A'] & 16) /* BDH */ char * phonetic( char *Word ) { - char *n, *n_start, *n_end; /* pointers to string */ - char *metaph_end; /* pointers to metaph */ - char ntrans[42]; /* word with uppercase letters */ - int KSflag; /* state flag for X -> KS */ - char buf[MAXPHONEMELEN + 2]; - char *Metaph; - - /* - * Copy Word to internal buffer, dropping non-alphabetic characters - * and converting to upper case - */ - n = ntrans + 4; n_end = ntrans + 35; - while (!iswordbreak( Word ) && n < n_end) { - if (isascii(*Word)) { - if (isalpha(*Word)) { - *n++ = TOUPPER(*Word); - } - ++Word; - } else { - auto const size_t len = LDAP_UTF8COPY(n, Word); - n += len; Word += len; - } - } - Metaph = buf; - *Metaph = '\0'; - if (n == ntrans + 4) { - return( slapi_ch_strdup( buf ) ); /* Return if null */ - } - n_end = n; /* Set n_end to end of string */ - - /* ntrans[0] will always be == 0 */ - ntrans[0] = '\0'; - ntrans[1] = '\0'; - ntrans[2] = '\0'; - ntrans[3] = '\0'; - *n++ = 0; - *n++ = 0; - *n++ = 0; - *n = 0; /* Pad with nulls */ - n = ntrans + 4; /* Assign pointer to start */ - - /* Check for PN, KN, GN, AE, WR, WH, and X at start */ - switch (*n) { - case 'P': - case 'K': - case 'G': - /* 'PN', 'KN', 'GN' becomes 'N' */ - if (*(n + 1) == 'N') - *n++ = 0; - break; - case 'A': - /* 'AE' becomes 'E' */ - if (*(n + 1) == 'E') - *n++ = 0; - break; - case 'W': - /* 'WR' becomes 'R', and 'WH' to 'H' */ - if (*(n + 1) == 'R') - *n++ = 0; - else if (*(n + 1) == 'H') { - *(n + 1) = *n; - *n++ = 0; - } - break; - case 'X': - /* 'X' becomes 'S' */ - *n = 'S'; - break; - } - - /* - * Now, loop step through string, stopping at end of string or when - * the computed 'metaph' is MAXPHONEMELEN characters long - */ - - KSflag = 0; /* state flag for KS translation */ - for (metaph_end = Metaph + MAXPHONEMELEN, n_start = n; - n <= n_end && Metaph < metaph_end; n++) { - if (KSflag) { - KSflag = 0; - *Metaph++ = 'S'; - } else if (!isascii(*n)) { - *Metaph++ = *n; - } else { - /* Drop duplicates except for CC */ - if (*(n - 1) == *n && *n != 'C') - continue; - /* Check for F J L M N R or first letter vowel */ - if (same(*n) || (n == n_start && vowel(*n))) { - *Metaph++ = *n; - } else { - switch (*n) { - case 'B': - - /* - * B unless in -MB - */ - if (n < (n_end - 1) && *(n - 1) != 'M') { - *Metaph++ = *n; - } - break; - case 'C': - - /* - * X if in -CIA-, -CH- else S if in - * -CI-, -CE-, -CY- else dropped if - * in -SCI-, -SCE-, -SCY- else K - */ - if (*(n - 1) != 'S' || !frontv(*(n + 1))) { - if (*(n + 1) == 'I' && *(n + 2) == 'A') { - *Metaph++ = 'X'; - } else if (frontv(*(n + 1))) { - *Metaph++ = 'S'; - } else if (*(n + 1) == 'H') { - *Metaph++ = ((n == n_start && !vowel(*(n + 2))) - || *(n - 1) == 'S') - ? (char) 'K' : (char) 'X'; - } else { - *Metaph++ = 'K'; - } - } - break; - case 'D': - - /* - * J if in DGE or DGI or DGY else T - */ - *Metaph++ = (*(n + 1) == 'G' && frontv(*(n + 2))) - ? (char) 'J' : (char) 'T'; - break; - case 'G': - - /* - * F if in -GH and not B--GH, D--GH, - * -H--GH, -H---GH else dropped if - * -GNED, -GN, -DGE-, -DGI-, -DGY- - * else J if in -GE-, -GI-, -GY- and - * not GG else K - */ - if ((*(n + 1) != 'J' || vowel(*(n + 2))) && - (*(n + 1) != 'N' || ((n + 1) < n_end && - (*(n + 2) != 'E' || *(n + 3) != 'D'))) && - (*(n - 1) != 'D' || !frontv(*(n + 1)))) - *Metaph++ = (frontv(*(n + 1)) && - *(n + 2) != 'G') ? (char) 'G' : (char) 'K'; - else if (*(n + 1) == 'H' && !noghf(*(n - 3)) && - *(n - 4) != 'H') - *Metaph++ = 'F'; - break; - case 'H': - - /* - * H if before a vowel and not after - * C, G, P, S, T else dropped - */ - if (!varson(*(n - 1)) && (!vowel(*(n - 1)) || - vowel(*(n + 1)))) - *Metaph++ = 'H'; - break; - case 'K': - - /* - * dropped if after C else K - */ - if (*(n - 1) != 'C') - *Metaph++ = 'K'; - break; - case 'P': - - /* - * F if before H, else P - */ - *Metaph++ = *(n + 1) == 'H' ? - (char) 'F' : (char) 'P'; - break; - case 'Q': - - /* - * K - */ - *Metaph++ = 'K'; - break; - case 'S': - - /* - * X in -SH-, -SIO- or -SIA- else S - */ - *Metaph++ = (*(n + 1) == 'H' || - (*(n + 1) == 'I' && (*(n + 2) == 'O' || - *(n + 2) == 'A'))) - ? (char) 'X' : (char) 'S'; - break; - case 'T': - - /* - * X in -TIA- or -TIO- else 0 (zero) - * before H else dropped if in -TCH- - * else T - */ - if (*(n + 1) == 'I' && (*(n + 2) == 'O' || - *(n + 2) == 'A')) - *Metaph++ = 'X'; - else if (*(n + 1) == 'H') - *Metaph++ = '0'; - else if (*(n + 1) != 'C' || *(n + 2) != 'H') - *Metaph++ = 'T'; - break; - case 'V': - - /* - * F - */ - *Metaph++ = 'F'; - break; - case 'W': - - /* - * W after a vowel, else dropped - */ - case 'Y': - - /* - * Y unless followed by a vowel - */ - if (vowel(*(n + 1))) - *Metaph++ = *n; - break; - case 'X': - - /* - * KS - */ - if (n == n_start) - *Metaph++ = 'S'; - else { - *Metaph++ = 'K'; /* Insert K, then S */ - KSflag = 1; - } - break; - case 'Z': - - /* - * S - */ - *Metaph++ = 'S'; - break; - } - } - } - } - - *Metaph = 0; /* Null terminate */ - return( slapi_ch_strdup( buf ) ); + char *n, *n_start, *n_end; /* pointers to string */ + char *metaph_end; /* pointers to metaph */ + char ntrans[42]; /* word with uppercase letters */ + int KSflag; /* state flag for X -> KS */ + char buf[MAXPHONEMELEN + 2]; + char *Metaph; + + /* + * Copy Word to internal buffer, dropping non-alphabetic characters + * and converting to upper case + */ + n = ntrans + 4; n_end = ntrans + 35; + while (!iswordbreak( Word ) && n < n_end) { + if (isascii(*Word)) { + if (isalpha(*Word)) { + *n++ = TOUPPER(*Word); + } + ++Word; + } else { + auto const size_t len = LDAP_UTF8COPY(n, Word); + n += len; Word += len; + } + } + Metaph = buf; + *Metaph = '\0'; + if (n == ntrans + 4) { + return( slapi_ch_strdup( buf ) ); /* Return if null */ + } + n_end = n; /* Set n_end to end of string */ + + /* ntrans[0] will always be == 0 */ + ntrans[0] = '\0'; + ntrans[1] = '\0'; + ntrans[2] = '\0'; + ntrans[3] = '\0'; + *n++ = 0; + *n++ = 0; + *n++ = 0; + *n = 0; /* Pad with nulls */ + n = ntrans + 4; /* Assign pointer to start */ + + /* Check for PN, KN, GN, AE, WR, WH, and X at start */ + switch (*n) { + case 'P': + case 'K': + case 'G': + /* 'PN', 'KN', 'GN' becomes 'N' */ + if (*(n + 1) == 'N') + *n++ = 0; + break; + case 'A': + /* 'AE' becomes 'E' */ + if (*(n + 1) == 'E') + *n++ = 0; + break; + case 'W': + /* 'WR' becomes 'R', and 'WH' to 'H' */ + if (*(n + 1) == 'R') + *n++ = 0; + else if (*(n + 1) == 'H') { + *(n + 1) = *n; + *n++ = 0; + } + break; + case 'X': + /* 'X' becomes 'S' */ + *n = 'S'; + break; + } + + /* + * Now, loop step through string, stopping at end of string or when + * the computed 'metaph' is MAXPHONEMELEN characters long + */ + + KSflag = 0; /* state flag for KS translation */ + for (metaph_end = Metaph + MAXPHONEMELEN, n_start = n; + n <= n_end && Metaph < metaph_end; n++) { + if (KSflag) { + KSflag = 0; + *Metaph++ = 'S'; + } else if (!isascii(*n)) { + *Metaph++ = *n; + } else { + /* Drop duplicates except for CC */ + if (*(n - 1) == *n && *n != 'C') + continue; + /* Check for F J L M N R or first letter vowel */ + if (same(*n) || (n == n_start && vowel(*n))) { + *Metaph++ = *n; + } else { + switch (*n) { + case 'B': + + /* + * B unless in -MB + */ + if (n < (n_end - 1) && *(n - 1) != 'M') { + *Metaph++ = *n; + } + break; + case 'C': + + /* + * X if in -CIA-, -CH- else S if in + * -CI-, -CE-, -CY- else dropped if + * in -SCI-, -SCE-, -SCY- else K + */ + if (*(n - 1) != 'S' || !frontv(*(n + 1))) { + if (*(n + 1) == 'I' && *(n + 2) == 'A') { + *Metaph++ = 'X'; + } else if (frontv(*(n + 1))) { + *Metaph++ = 'S'; + } else if (*(n + 1) == 'H') { + *Metaph++ = ((n == n_start && !vowel(*(n + 2))) + || *(n - 1) == 'S') + ? (char) 'K' : (char) 'X'; + } else { + *Metaph++ = 'K'; + } + } + break; + case 'D': + + /* + * J if in DGE or DGI or DGY else T + */ + *Metaph++ = (*(n + 1) == 'G' && frontv(*(n + 2))) + ? (char) 'J' : (char) 'T'; + break; + case 'G': + + /* + * F if in -GH and not B--GH, D--GH, + * -H--GH, -H---GH else dropped if + * -GNED, -GN, -DGE-, -DGI-, -DGY- + * else J if in -GE-, -GI-, -GY- and + * not GG else K + */ + if ((*(n + 1) != 'J' || vowel(*(n + 2))) && + (*(n + 1) != 'N' || ((n + 1) < n_end && + (*(n + 2) != 'E' || *(n + 3) != 'D'))) && + (*(n - 1) != 'D' || !frontv(*(n + 1)))) + *Metaph++ = (frontv(*(n + 1)) && + *(n + 2) != 'G') ? (char) 'G' : (char) 'K'; + else if (*(n + 1) == 'H' && !noghf(*(n - 3)) && + *(n - 4) != 'H') + *Metaph++ = 'F'; + break; + case 'H': + + /* + * H if before a vowel and not after + * C, G, P, S, T else dropped + */ + if (!varson(*(n - 1)) && (!vowel(*(n - 1)) || + vowel(*(n + 1)))) + *Metaph++ = 'H'; + break; + case 'K': + + /* + * dropped if after C else K + */ + if (*(n - 1) != 'C') + *Metaph++ = 'K'; + break; + case 'P': + + /* + * F if before H, else P + */ + *Metaph++ = *(n + 1) == 'H' ? + (char) 'F' : (char) 'P'; + break; + case 'Q': + + /* + * K + */ + *Metaph++ = 'K'; + break; + case 'S': + + /* + * X in -SH-, -SIO- or -SIA- else S + */ + *Metaph++ = (*(n + 1) == 'H' || + (*(n + 1) == 'I' && (*(n + 2) == 'O' || + *(n + 2) == 'A'))) + ? (char) 'X' : (char) 'S'; + break; + case 'T': + + /* + * X in -TIA- or -TIO- else 0 (zero) + * before H else dropped if in -TCH- + * else T + */ + if (*(n + 1) == 'I' && (*(n + 2) == 'O' || + *(n + 2) == 'A')) + *Metaph++ = 'X'; + else if (*(n + 1) == 'H') + *Metaph++ = '0'; + else if (*(n + 1) != 'C' || *(n + 2) != 'H') + *Metaph++ = 'T'; + break; + case 'V': + + /* + * F + */ + *Metaph++ = 'F'; + break; + case 'W': + + /* + * W after a vowel, else dropped + */ + case 'Y': + + /* + * Y unless followed by a vowel + */ + if (vowel(*(n + 1))) + *Metaph++ = *n; + break; + case 'X': + + /* + * KS + */ + if (n == n_start) + *Metaph++ = 'S'; + else { + *Metaph++ = 'K'; /* Insert K, then S */ + KSflag = 1; + } + break; + case 'Z': + + /* + * S + */ + *Metaph++ = 'S'; + break; + } + } + } + } + + *Metaph = 0; /* Null terminate */ + return( slapi_ch_strdup( buf ) ); } #endif /* METAPHONE */
0
0be6d3ea6db632fb8a232ebd50a0be52a3b1cf93
389ds/389-ds-base
Bug Description: Disable plugins had a copy and paste error that prevented plugins from actaully being disabled. Fix Description: When disabling plugins, use the "off" value
commit 0be6d3ea6db632fb8a232ebd50a0be52a3b1cf93 Author: Mark Reynolds <[email protected]> Date: Tue Dec 16 11:55:00 2014 -0500 Bug Description: Disable plugins had a copy and paste error that prevented plugins from actaully being disabled. Fix Description: When disabling plugins, use the "off" value diff --git a/src/lib389/lib389/plugins.py b/src/lib389/lib389/plugins.py index 5e847c78f..f8e4dc3ad 100644 --- a/src/lib389/lib389/plugins.py +++ b/src/lib389/lib389/plugins.py @@ -102,5 +102,5 @@ class Plugins(object): if len(ents) != 1: raise ValueError("%s is unknown") - self.conn.modify_s(dn, [(ldap.MOD_REPLACE, PLUGIN_PROPNAME_TO_ATTRNAME[PLUGIN_ENABLE], PLUGINS_ENABLE_ON_VALUE)]) + self.conn.modify_s(dn, [(ldap.MOD_REPLACE, PLUGIN_PROPNAME_TO_ATTRNAME[PLUGIN_ENABLE], PLUGINS_ENABLE_OFF_VALUE)])
0
8639c035050484bd5a8f31bb70874d593cd1585e
389ds/389-ds-base
Ticket 147 - Internal Password Policy usage very inefficient Bug Description: When updating a userpassword, the passwordPolicy struct is allocated & freed 5 to 7 times. Fix Description: Store the passwordPolicy struct in the pblock, and when we try and create a new policy struct, return the one in the pblock. https://fedorahosted.org/389/ticket/147 Reviewed by: richm(Thanks!)
commit 8639c035050484bd5a8f31bb70874d593cd1585e Author: Mark Reynolds <[email protected]> Date: Mon Oct 22 16:17:42 2012 -0400 Ticket 147 - Internal Password Policy usage very inefficient Bug Description: When updating a userpassword, the passwordPolicy struct is allocated & freed 5 to 7 times. Fix Description: Store the passwordPolicy struct in the pblock, and when we try and create a new policy struct, return the one in the pblock. https://fedorahosted.org/389/ticket/147 Reviewed by: richm(Thanks!) diff --git a/ldap/servers/slapd/log.c b/ldap/servers/slapd/log.c index e62248528..ecfdb19d7 100644 --- a/ldap/servers/slapd/log.c +++ b/ldap/servers/slapd/log.c @@ -2581,7 +2581,7 @@ log__delete_rotated_logs() log_convert_time (logp->l_ctime, tbuf, 1); PR_snprintf (buffer, sizeof(buffer), "%s.%s", loginfo.log_access_file, tbuf); - LDAPDebug(LDAP_DEBUG_ANY,"Deleted Rotated Log: %s\n",buffer,0,0); /* MARK */ + LDAPDebug(LDAP_DEBUG_ANY,"Deleted Rotated Log: %s\n",buffer,0,0); if (PR_Delete(buffer) != PR_SUCCESS) { logp = logp->l_next; diff --git a/ldap/servers/slapd/modify.c b/ldap/servers/slapd/modify.c index da742da86..424badb63 100644 --- a/ldap/servers/slapd/modify.c +++ b/ldap/servers/slapd/modify.c @@ -1256,7 +1256,6 @@ static int op_shared_allow_pw_change (Slapi_PBlock *pb, LDAPMod *mod, char **old done: slapi_entry_free( e ); slapi_sdn_done (&sdn); - delete_passwdPolicy(&pwpolicy); slapi_ch_free_string(&proxydn); slapi_ch_free_string(&proxystr); return rc; diff --git a/ldap/servers/slapd/passwd_extop.c b/ldap/servers/slapd/passwd_extop.c index 3c050d69f..b103a14bd 100644 --- a/ldap/servers/slapd/passwd_extop.c +++ b/ldap/servers/slapd/passwd_extop.c @@ -869,7 +869,6 @@ free_and_return: slapi_pblock_set(pb, SLAPI_TARGET_SDN, NULL); slapi_pblock_set( pb, SLAPI_ORIGINAL_TARGET, NULL ); slapi_ch_free_string(&authmethod); - delete_passwdPolicy(&pwpolicy); slapi_entry_free(referrals); if ( targetEntry != NULL ){ diff --git a/ldap/servers/slapd/pblock.c b/ldap/servers/slapd/pblock.c index 9895d492f..d7a726d5d 100644 --- a/ldap/servers/slapd/pblock.c +++ b/ldap/servers/slapd/pblock.c @@ -111,10 +111,11 @@ pblock_done( Slapi_PBlock *pb ) { if(pb->pb_op!=NULL) { - operation_free(&pb->pb_op,pb->pb_conn); + operation_free(&pb->pb_op,pb->pb_conn); } - slapi_ch_free((void**)&(pb->pb_vattr_context)); - slapi_ch_free((void**)&(pb->pb_result_text)); + delete_passwdPolicy(&pb->pwdpolicy); + slapi_ch_free((void**)&(pb->pb_vattr_context)); + slapi_ch_free((void**)&(pb->pb_result_text)); } void diff --git a/ldap/servers/slapd/pw.c b/ldap/servers/slapd/pw.c index 04ad2ce93..9135a52a1 100644 --- a/ldap/servers/slapd/pw.c +++ b/ldap/servers/slapd/pw.c @@ -200,7 +200,6 @@ char* slapi_encode_ext (Slapi_PBlock *pb, const Slapi_DN *sdn, char *value, char { pwpolicy = new_passwdPolicy(pb, (char*)slapi_sdn_get_ndn(sdn) ); pws_enc = pwpolicy->pw_storagescheme->pws_enc; - delete_passwdPolicy(&pwpolicy); if (pws_enc == NULL) { @@ -357,8 +356,6 @@ pw_encodevals_ext( Slapi_PBlock *pb, const Slapi_DN *sdn, Slapi_Value **vals ) if (pwpolicy->pw_storagescheme) { pws_enc = pwpolicy->pw_storagescheme->pws_enc; } - - delete_passwdPolicy(&pwpolicy); } /* Password scheme encryption function was not found */ @@ -678,7 +675,6 @@ update_pw_info ( Slapi_PBlock *pb , char *old_pw) { slapi_ch_free((void**)&prev_exp_date_str); pw_apply_mods(sdn, &smods); slapi_mods_done(&smods); - delete_passwdPolicy(&pwpolicy); return 0; } @@ -695,12 +691,9 @@ update_pw_info ( Slapi_PBlock *pb , char *old_pw) { } else { pw_apply_mods(sdn, &smods); slapi_mods_done(&smods); - delete_passwdPolicy(&pwpolicy); return 0; } - delete_passwdPolicy(&pwpolicy); - timestr = format_genTime ( pw_exp_date ); slapi_mods_add_string(&smods, LDAP_MOD_REPLACE, "passwordExpirationTime", timestr); slapi_ch_free((void **)&timestr); @@ -735,7 +728,6 @@ check_pw_minage ( Slapi_PBlock *pb, const Slapi_DN *sdn, struct berval **vals) /* retrieve the entry */ e = get_entry ( pb, dn ); if ( e == NULL ) { - delete_passwdPolicy(&pwpolicy); return ( -1 ); } /* get passwordAllowChangeTime attribute */ @@ -763,14 +755,12 @@ check_pw_minage ( Slapi_PBlock *pb, const Slapi_DN *sdn, struct berval **vals) "within password minimum age", 0, NULL ); slapi_entry_free( e ); slapi_ch_free((void **) &cur_time_str ); - delete_passwdPolicy(&pwpolicy); return ( 1 ); } slapi_ch_free((void **) &cur_time_str ); } slapi_entry_free( e ); } - delete_passwdPolicy(&pwpolicy); return ( 0 ); } @@ -847,12 +837,10 @@ check_pw_syntax_ext ( Slapi_PBlock *pb, const Slapi_DN *sdn, Slapi_Value **vals, LDAP_PWPOLICY_INVALIDPWDSYNTAX ); } pw_send_ldap_result ( pb, LDAP_CONSTRAINT_VIOLATION, NULL, errormsg, 0, NULL ); - delete_passwdPolicy(&pwpolicy); return( 1 ); } else { /* We want to skip syntax checking since this is a pre-hashed * password from replication or the root DN. */ - delete_passwdPolicy(&pwpolicy); return( 0 ); } } @@ -869,7 +857,6 @@ check_pw_syntax_ext ( Slapi_PBlock *pb, const Slapi_DN *sdn, Slapi_Value **vals, LDAP_PWPOLICY_PWDTOOSHORT ); } pw_send_ldap_result ( pb, LDAP_CONSTRAINT_VIOLATION, NULL, errormsg, 0, NULL ); - delete_passwdPolicy(&pwpolicy); return ( 1 ); } @@ -984,7 +971,6 @@ check_pw_syntax_ext ( Slapi_PBlock *pb, const Slapi_DN *sdn, Slapi_Value **vals, LDAP_PWPOLICY_INVALIDPWDSYNTAX ); } pw_send_ldap_result ( pb, LDAP_CONSTRAINT_VIOLATION, NULL, errormsg, 0, NULL ); - delete_passwdPolicy(&pwpolicy); return ( 1 ); } } @@ -995,7 +981,6 @@ check_pw_syntax_ext ( Slapi_PBlock *pb, const Slapi_DN *sdn, Slapi_Value **vals, /* retrieve the entry */ e = get_entry ( pb, dn ); if ( e == NULL ) { - delete_passwdPolicy(&pwpolicy); return ( -1 ); } @@ -1015,7 +1000,6 @@ check_pw_syntax_ext ( Slapi_PBlock *pb, const Slapi_DN *sdn, Slapi_Value **vals, LDAP_CONSTRAINT_VIOLATION, NULL, "password in history", 0, NULL ); slapi_entry_free( e ); - delete_passwdPolicy(&pwpolicy); return ( 1 ); } } @@ -1033,7 +1017,6 @@ check_pw_syntax_ext ( Slapi_PBlock *pb, const Slapi_DN *sdn, Slapi_Value **vals, LDAP_CONSTRAINT_VIOLATION ,NULL, "password in history", 0, NULL); slapi_entry_free( e ); - delete_passwdPolicy(&pwpolicy); return ( 1 ); } } else @@ -1044,7 +1027,6 @@ check_pw_syntax_ext ( Slapi_PBlock *pb, const Slapi_DN *sdn, Slapi_Value **vals, LDAP_CONSTRAINT_VIOLATION ,NULL, "password in history", 0, NULL); slapi_entry_free( e ); - delete_passwdPolicy(&pwpolicy); return ( 1 ); } } @@ -1073,13 +1055,10 @@ check_pw_syntax_ext ( Slapi_PBlock *pb, const Slapi_DN *sdn, Slapi_Value **vals, slapi_entry_free( e ); } - delete_passwdPolicy(&pwpolicy); return 1; } } - delete_passwdPolicy(&pwpolicy); - if ( mod_op ) { /* free e only when called by modify operation */ slapi_entry_free( e ); @@ -1110,7 +1089,6 @@ update_pw_history( Slapi_PBlock *pb, const Slapi_DN *sdn, char *old_pw ) /* retrieve the entry */ e = get_entry ( pb, dn ); if ( e == NULL ) { - delete_passwdPolicy(&pwpolicy); return ( 1 ); } @@ -1176,7 +1154,6 @@ update_pw_history( Slapi_PBlock *pb, const Slapi_DN *sdn, char *old_pw ) slapi_ch_free((void **) &str ); slapi_ch_free((void **) &history_str ); slapi_entry_free( e ); - delete_passwdPolicy(&pwpolicy); return 0; } @@ -1415,8 +1392,6 @@ add_password_attrs( Slapi_PBlock *pb, Operation *op, Slapi_Entry *e ) slapi_entry_attr_merge( e, "passwordallowchangetime", bvals ); slapi_ch_free((void **) &bv.bv_val ); } - - delete_passwdPolicy(&pwpolicy); } static int @@ -1551,6 +1526,11 @@ new_passwdPolicy(Slapi_PBlock *pb, const char *dn) slapdFrontendConfig_t *slapdFrontendConfig; int optype = -1; + /* If we already allocated a pw policy, return it */ + if(pb && pb->pwdpolicy){ + return pb->pwdpolicy; + } + slapdFrontendConfig = getFrontendConfig(); pwdpolicy = (passwdPolicy *)slapi_ch_calloc(1, sizeof(passwdPolicy)); @@ -1838,6 +1818,9 @@ new_passwdPolicy(Slapi_PBlock *pb, const char *dn) if (pw_entry) { slapi_entry_free(pw_entry); } + if(pb){ + pb->pwdpolicy = pwdpolicy; + } return pwdpolicy; } else if ( e ) { slapi_entry_free( e ); @@ -1845,15 +1828,18 @@ new_passwdPolicy(Slapi_PBlock *pb, const char *dn) } done: - /* If we are here, that means we need to load the passwdPolicy + /* + * If we are here, that means we need to load the passwdPolicy * structure from slapdFrontendconfig */ - *pwdpolicy = slapdFrontendConfig->pw_policy; pwdscheme = (struct pw_scheme *)slapi_ch_calloc(1, sizeof(struct pw_scheme)); *pwdscheme = *slapdFrontendConfig->pw_storagescheme; pwdscheme->pws_name = strdup( slapdFrontendConfig->pw_storagescheme->pws_name ); pwdpolicy->pw_storagescheme = pwdscheme; + if(pb){ + pb->pwdpolicy = pwdpolicy; + } return pwdpolicy; @@ -2194,14 +2180,9 @@ slapi_check_account_lock ( Slapi_PBlock *pb, Slapi_Entry * bind_target_entry, in notlocked: /* account is not locked. */ - if(check_password_policy) - delete_passwdPolicy(&pwpolicy); - return ( 0 ); + return (0); locked: - if(check_password_policy) - delete_passwdPolicy(&pwpolicy); return (1); - } /* The idea here is that these functions could allow us to have password diff --git a/ldap/servers/slapd/pw_mgmt.c b/ldap/servers/slapd/pw_mgmt.c index c0055fc95..05ecae1ce 100644 --- a/ldap/servers/slapd/pw_mgmt.c +++ b/ldap/servers/slapd/pw_mgmt.c @@ -107,7 +107,6 @@ need_new_pw( Slapi_PBlock *pb, long *t, Slapi_Entry *e, int pwresponse_req ) pw_apply_mods(sdn, &smods); } slapi_mods_done(&smods); - delete_passwdPolicy(&pwpolicy); return ( 0 ); } @@ -152,7 +151,6 @@ skip: } pw_apply_mods(sdn, &smods); slapi_mods_done(&smods); - delete_passwdPolicy(&pwpolicy); return ( 0 ); } @@ -191,7 +189,6 @@ skip: if (pb->pb_conn->c_needpw == 1) { slapi_add_pwd_control ( pb, LDAP_CONTROL_PWEXPIRED, 0); } - delete_passwdPolicy(&pwpolicy); return ( 0 ); } @@ -218,7 +215,6 @@ skip: /* Apply current modifications */ pw_apply_mods(sdn, &smods); slapi_mods_done(&smods); - delete_passwdPolicy(&pwpolicy); return (-1); } slapi_ch_free((void **) &cur_time_str ); @@ -279,7 +275,6 @@ skip: if (pb->pb_conn->c_needpw == 1) { slapi_add_pwd_control ( pb, LDAP_CONTROL_PWEXPIRED, 0); } - delete_passwdPolicy(&pwpolicy); return (2); } @@ -289,7 +284,6 @@ skip: if (pb->pb_conn->c_needpw == 1) { slapi_add_pwd_control ( pb, LDAP_CONTROL_PWEXPIRED, 0); } - delete_passwdPolicy(&pwpolicy); /* passes checking, return 0 */ return( 0 ); } diff --git a/ldap/servers/slapd/pw_retry.c b/ldap/servers/slapd/pw_retry.c index 68a6bd944..0082d0f0c 100644 --- a/ldap/servers/slapd/pw_retry.c +++ b/ldap/servers/slapd/pw_retry.c @@ -136,7 +136,6 @@ int set_retry_cnt_and_time ( Slapi_PBlock *pb, int count, time_t cur_time ) { slapi_pblock_get( pb, SLAPI_TARGET_SDN, &sdn ); dn = slapi_sdn_get_dn(sdn); pwpolicy = new_passwdPolicy(pb, dn); - slapi_mods_init(&smods, 0); reset_time = time_plus_sec ( cur_time, @@ -150,7 +149,6 @@ int set_retry_cnt_and_time ( Slapi_PBlock *pb, int count, time_t cur_time ) { pw_apply_mods(sdn, &smods); slapi_mods_done(&smods); - delete_passwdPolicy(&pwpolicy); return rc; } @@ -190,7 +188,6 @@ int set_retry_cnt_mods(Slapi_PBlock *pb, Slapi_Mods *smods, int count) rc = LDAP_CONSTRAINT_VIOLATION; } } - delete_passwdPolicy(&pwpolicy); return rc; } diff --git a/ldap/servers/slapd/result.c b/ldap/servers/slapd/result.c index 09d6b90b2..e124d0b94 100644 --- a/ldap/servers/slapd/result.c +++ b/ldap/servers/slapd/result.c @@ -555,7 +555,6 @@ log_and_return: log_result( pb, operation, err, tag, nentries ); } - delete_passwdPolicy (&pwpolicy); LDAPDebug( LDAP_DEBUG_TRACE, "<= send_ldap_result\n", 0, 0, 0 ); } diff --git a/ldap/servers/slapd/slap.h b/ldap/servers/slapd/slap.h index 33607cb34..5ac181915 100644 --- a/ldap/servers/slapd/slap.h +++ b/ldap/servers/slapd/slap.h @@ -1514,6 +1514,37 @@ struct slapi_task { } slapi_task; /* End of interface to support online tasks **********************************/ +typedef struct passwordpolicyarray { + int pw_change; /* 1 - indicates that users are allowed to change the pwd */ + int pw_must_change; /* 1 - indicates that users must change pwd upon reset */ + int pw_syntax; + int pw_minlength; + int pw_mindigits; + int pw_minalphas; + int pw_minuppers; + int pw_minlowers; + int pw_minspecials; + int pw_min8bit; + int pw_maxrepeats; + int pw_mincategories; + int pw_mintokenlength; + int pw_exp; + long pw_maxage; + long pw_minage; + long pw_warning; + int pw_history; + int pw_inhistory; + int pw_lockout; + int pw_maxfailure; + int pw_unlock; + long pw_lockduration; + long pw_resetfailurecount; + int pw_gracelimit; + int pw_is_legacy; + int pw_track_update_time; + struct pw_scheme *pw_storagescheme; +} passwdPolicy; + typedef struct slapi_pblock { /* common */ Slapi_Backend *pb_backend; @@ -1666,6 +1697,7 @@ typedef struct slapi_pblock { int pb_syntax_filter_normalized; /* the syntax filter types/values are already normalized */ void *pb_syntax_filter_data; /* extra data to pass to a syntax plugin function */ int pb_paged_results_index; /* stash SLAPI_PAGED_RESULTS_INDEX */ + passwdPolicy *pwdpolicy; } slapi_pblock; /* index if substrlens */ @@ -2033,37 +2065,6 @@ typedef struct _slapdEntryPoints { #define MAX_ALLOWED_TIME_IN_SECS 2147483647 -typedef struct passwordpolicyarray { - int pw_change; /* 1 - indicates that users are allowed to change the pwd */ - int pw_must_change; /* 1 - indicates that users must change pwd upon reset */ - int pw_syntax; - int pw_minlength; - int pw_mindigits; - int pw_minalphas; - int pw_minuppers; - int pw_minlowers; - int pw_minspecials; - int pw_min8bit; - int pw_maxrepeats; - int pw_mincategories; - int pw_mintokenlength; - int pw_exp; - long pw_maxage; - long pw_minage; - long pw_warning; - int pw_history; - int pw_inhistory; - int pw_lockout; - int pw_maxfailure; - int pw_unlock; - long pw_lockduration; - long pw_resetfailurecount; - int pw_gracelimit; - int pw_is_legacy; - int pw_track_update_time; - struct pw_scheme *pw_storagescheme; -} passwdPolicy; - typedef struct _slapdFrontendConfig { Slapi_RWLock *cfg_rwlock; /* read/write lock to serialize access */ struct pw_scheme *rootpwstoragescheme;
0
e92ef06ca32689a87e4c0c9eb15b1df0f442d98e
389ds/389-ds-base
HP-UX IPF Porting changes
commit e92ef06ca32689a87e4c0c9eb15b1df0f442d98e Author: Nathan Kinder <[email protected]> Date: Mon Apr 18 20:45:01 2005 +0000 HP-UX IPF Porting changes diff --git a/config/HP-UX.mk b/config/HP-UX.mk index c8bc0bfc1..d0031d37c 100644 --- a/config/HP-UX.mk +++ b/config/HP-UX.mk @@ -95,6 +95,10 @@ DSO_LDFLAGS = DSO_CFLAGS = +z ifdef SERVER_BUILD +ifeq ($(OS_RELEASE),B.11.23) +SERVER_CFLAGS = +DD32 -Wl,-E,-N +else SERVER_CFLAGS = +DA1.0 -Wl,-E,-N +endif STATIC_JAVA = yes endif diff --git a/httpd/autobuild b/httpd/autobuild index 65e10aa87..dd5f67c4b 100755 --- a/httpd/autobuild +++ b/httpd/autobuild @@ -62,7 +62,12 @@ elif [ "$UNAME" = "SOLARISx86" ]; then elif [ "$UNAME" = "HPUX" ]; then PATH=/usr/local/hpux/bin:/usr/bin/X11:$PATH; export PATH GTAR=/share/builds/f/gtar/bin/hpux-gtar - HTTPDLIB=libnshttpd.sl + ARCH=`uname -m` + if [ "$ARCH" = "ia64" ]; then + HTTPDLIB=libnshttpd.so + else + HTTPDLIB=libnshttpd.sl + fi elif [ "$UNAME" = "BSDI" ]; then PATH=/usr/local/bin:/usr/X11/bin:$PATH; export PATH diff --git a/ldap/admin/src/DSAdmin.pm b/ldap/admin/src/DSAdmin.pm index 1f492b08d..503134fee 100644 --- a/ldap/admin/src/DSAdmin.pm +++ b/ldap/admin/src/DSAdmin.pm @@ -88,7 +88,12 @@ BEGIN { $dll_suffix = "_shr.a"; } elsif ( $os eq "HP-UX" ) { + $arch = &uname("-p"); + if ( $arch eq "ia64" ) { + $dll_suffix = ".so"; + } else { $dll_suffix = ".sl"; + } } elsif ( $os eq "WINNT" ) { $dll_suffix = ".dll"; diff --git a/ldap/admin/src/create_instance.c b/ldap/admin/src/create_instance.c index c4b5a71a2..fffcb2d4f 100644 --- a/ldap/admin/src/create_instance.c +++ b/ldap/admin/src/create_instance.c @@ -99,7 +99,11 @@ #include <netinet/in.h> /* sockaddr_in */ #include <arpa/inet.h> /* inet_addr */ #ifdef HPUX +#ifdef __ia64 +#define SHLIB_EXT "so" +#else #define SHLIB_EXT "sl" +#endif #else #define SHLIB_EXT "so" #endif @@ -3092,7 +3096,11 @@ char *ds_gen_confs(char *sroot, server_config_s *cf, shared_lib = ".dll"; #else #ifdef HPUX +#ifdef __ia64 + shared_lib = ".so"; +#else shared_lib = ".sl"; +#endif #else #ifdef AIX #if OSVERSION >= 4200 diff --git a/ldap/admin/src/ds_remove.c b/ldap/admin/src/ds_remove.c index 674ac4991..f5cb4fc37 100644 --- a/ldap/admin/src/ds_remove.c +++ b/ldap/admin/src/ds_remove.c @@ -135,7 +135,7 @@ int main(int argc, char *argv[]) char *installroot; int isRunning; #ifndef __LP64__ -#ifdef hpux +#if defined(__hpux) && !defined(__ia64) _main(); #endif #endif diff --git a/ldap/admin/src/instindex.cpp b/ldap/admin/src/instindex.cpp index 7613ddaec..5557fdbfa 100644 --- a/ldap/admin/src/instindex.cpp +++ b/ldap/admin/src/instindex.cpp @@ -75,7 +75,11 @@ printInfo(int argc, char *argv[], char *envp[], FILE* fp) fprintf(fp, "#####################################\n"); } +#if defined (__hpux) && defined (__ia64) +int main(int argc, char *argv[], char *envp[]) +#else int main(int argc, char *argv[], char * /*envp*/ []) +#endif { char *rm = getenv("REQUEST_METHOD"); int status = 0; diff --git a/ldap/admin/src/migrateTo4 b/ldap/admin/src/migrateTo4 index f6969ea15..dcf63eb52 100644 --- a/ldap/admin/src/migrateTo4 +++ b/ldap/admin/src/migrateTo4 @@ -83,7 +83,12 @@ BEGIN { $dll_suffix = "_shr.a"; } elsif ( $os eq "HP-UX" ) { + $arch = &uname("-p"); + if ( $arch eq "ia64" ) { + $dll_suffix = ".so"; + } else { $dll_suffix = ".sl"; + } } elsif ( $os eq "WINNT" ) { $dll_suffix = ".dll"; diff --git a/ldap/admin/src/scripts/template-migrate50to51 b/ldap/admin/src/scripts/template-migrate50to51 index 2160024db..0feb4aca6 100644 --- a/ldap/admin/src/scripts/template-migrate50to51 +++ b/ldap/admin/src/scripts/template-migrate50to51 @@ -117,7 +117,12 @@ BEGIN { $dll_suffix = "_shr.a"; } elsif ( $os eq "HP-UX" ) { + $arch = &uname("-p"); + if ( $arch eq "ia64" ) { + $dll_suffix = ".so"; + } else { $dll_suffix = ".sl"; + } } elsif ( $os eq "WINNT" ) { $dll_suffix = ".dll"; diff --git a/ldap/admin/src/scripts/template-migrateTo5 b/ldap/admin/src/scripts/template-migrateTo5 index fd4db3165..f7bcd5aa6 100755 --- a/ldap/admin/src/scripts/template-migrateTo5 +++ b/ldap/admin/src/scripts/template-migrateTo5 @@ -136,7 +136,12 @@ BEGIN { $dll_suffix = "_shr.a"; } elsif ( $os eq "HP-UX" ) { + $arch = &uname("-p"); + if ( $arch eq "ia64" ) { + $dll_suffix = ".so"; + } else { $dll_suffix = ".sl"; + } } elsif ( $os eq "WINNT" ) { $dll_suffix = ".dll"; diff --git a/ldap/admin/src/upgradeServer b/ldap/admin/src/upgradeServer index 2c6008d31..1aeeedf5c 100755 --- a/ldap/admin/src/upgradeServer +++ b/ldap/admin/src/upgradeServer @@ -65,7 +65,12 @@ SWITCH: { } if ($os eq "HP-UX") { $LIB_PATH = "SHLIB_PATH" ; - $shlibsuf = ".sl"; + my $arch = &uname("-p"); + if ($arch eq "ia64") { + $shlibsuf = ".so"; + } else { + $shlibsuf = ".sl"; + } last SWITCH ; } if ($isNT) { diff --git a/ldap/clients/dsgw/dosearch.c b/ldap/clients/dsgw/dosearch.c index a32740814..33ef4f5f8 100644 --- a/ldap/clients/dsgw/dosearch.c +++ b/ldap/clients/dsgw/dosearch.c @@ -57,9 +57,11 @@ int main( argc, argv, env ) char *ldapquery = NULL; #ifndef __LP64__ #ifdef HPUX +#ifndef __ia64 /* call the static constructors in libnls */ _main(); #endif +#endif #endif /* * Parse out the GET args, if any. See the comments under diff --git a/ldap/clients/dsgw/edit.c b/ldap/clients/dsgw/edit.c index 72c0e5db3..a22288414 100644 --- a/ldap/clients/dsgw/edit.c +++ b/ldap/clients/dsgw/edit.c @@ -86,9 +86,11 @@ int main( argc, argv, env ) dn = NULL; #ifndef __LP64__ #ifdef HPUX +#ifndef __ia64 /* call the static constructors in libnls */ _main(); #endif +#endif #endif if (( tmplname = getenv( "QUERY_STRING" )) != NULL && *tmplname != '\0' ) { diff --git a/ldap/cm/newinst/Makefile b/ldap/cm/newinst/Makefile index f8222ec30..0e2f977fd 100644 --- a/ldap/cm/newinst/Makefile +++ b/ldap/cm/newinst/Makefile @@ -136,6 +136,10 @@ ifeq ($(NSOS_RELEASE),B.11.11) MODERNHP=1 endif +ifeq ($(NSOS_RELEASE),B.11.23) + MODERNHP=1 +endif + ifeq ($(MODERNHP),1) CURSES=-lHcurses else diff --git a/ldap/nsldap.mk b/ldap/nsldap.mk index 0436187ee..6d62f84ed 100644 --- a/ldap/nsldap.mk +++ b/ldap/nsldap.mk @@ -600,7 +600,11 @@ CB_DLL = chainingdb-plugin$(DLL_PRESUFFIX) # Admin server dynamic library location. # ifeq ($(ARCH), HPUX) +ifeq ($(OS_TEST), ia64) +ADMSONAME=ns-admin.so +else ADMSONAME=ns-admin.sl +endif else ifeq ($(ARCH), SOLARIS) ADMSONAME=ns-admin.$(DLL_SUFFIX) @@ -823,7 +827,11 @@ endif # Passed to every compile (cc or gcc). This is where you put -O or -g, etc. ifneq ($(ARCH), WINNT) ifdef BUILD_OPT +ifeq ($(ARCH) $(NSOS_RELEASE), HPUX B.11.23) +EXTRACFLAGS=+O3 +else EXTRACFLAGS=-O +endif else EXTRACFLAGS=-g endif @@ -1183,7 +1191,14 @@ ifeq ($(ARCH), HPUX) # HP-UX platform-specifics # +ifeq ($(NSOS_RELEASE), B.11.23) +# -Ae is removed from PLATFORMCFLAGS, because CC and CXX share +# same CFLAGS, -AP is added to CXX, and -Ae can not coexist with +# -AP, so add -Ae to the front of CC +CC=cc -Ae +else CC=cc +endif PLATFORM=hpux # ranlib not needed under HP-UX @@ -1217,7 +1232,12 @@ SONAMEFLAG_PREFIX=-Wl,+h # -Ae means 'enforce ansi BUT allow the use of long-long'. we need this # for 64-bit file support. +ifneq ($(NSOS_RELEASE),B.11.23) PLATFORMCFLAGS= -Dhpux -D$(PLATFORM) -D_HPUX_SOURCE -D_REENTRANT -Ae +else +PLATFORMCFLAGS= -Dhpux -D$(PLATFORM) -D_HPUX_SOURCE -D_REENTRANT +THREADSLIB=-lpthread +endif #aCC doesn't recognize -Ae so this will be used with aCC ACC_PLATFORMCFLAGS= -Dhpux -D$(PLATFORM) -D_HPUX_SOURCE -D_REENTRANT diff --git a/ldap/servers/plugins/replication/cl5_api.c b/ldap/servers/plugins/replication/cl5_api.c index cff5b5dae..4b02299cb 100644 --- a/ldap/servers/plugins/replication/cl5_api.c +++ b/ldap/servers/plugins/replication/cl5_api.c @@ -156,7 +156,11 @@ * The value 0 means use the default stacksize. */ #if defined (OSF1) || defined (__LP64__) || defined (_LP64) /* 64-bit architectures need bigger stacks */ +#if defined(__hpux) && defined(__ia64) +#define DEFAULT_THREAD_STACKSIZE 524288L +#else #define DEFAULT_THREAD_STACKSIZE 131072L +#endif #else #define DEFAULT_THREAD_STACKSIZE 0 #endif diff --git a/ldap/servers/plugins/replication/repl5_protocol.c b/ldap/servers/plugins/replication/repl5_protocol.c index 27af7249d..867af479b 100644 --- a/ldap/servers/plugins/replication/repl5_protocol.c +++ b/ldap/servers/plugins/replication/repl5_protocol.c @@ -343,7 +343,11 @@ prot_start(Repl_Protocol *rp) if (NULL != rp) { if (PR_CreateThread(PR_USER_THREAD, prot_thread_main, (void *)rp, +#if defined(__hpux) && defined(__ia64) + PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, PR_UNJOINABLE_THREAD, 524288L ) == NULL) +#else PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, PR_UNJOINABLE_THREAD, SLAPD_DEFAULT_THREAD_STACKSIZE) == NULL) +#endif { PRErrorCode prerr = PR_GetError(); diff --git a/ldap/servers/plugins/retrocl/retrocl.h b/ldap/servers/plugins/retrocl/retrocl.h index 237c95ff1..63f0d4bad 100644 --- a/ldap/servers/plugins/retrocl/retrocl.h +++ b/ldap/servers/plugins/retrocl/retrocl.h @@ -77,7 +77,11 @@ typedef struct _cnumRet { */ #define CHANGELOGDB_TRIM_INTERVAL 300*1000 /* 5 minutes */ +#if defined(__hpux) && defined(__ia64) +#define RETROCL_DLL_DEFAULT_THREAD_STACKSIZE 524288L +#else #define RETROCL_DLL_DEFAULT_THREAD_STACKSIZE 131072L +#endif #define RETROCL_BE_CACHEMEMSIZE "2097152" #define RETROCL_BE_CACHESIZE "-1" #define RETROCL_PLUGIN_NAME "DSRetroclPlugin" diff --git a/ldap/servers/slapd/Makefile b/ldap/servers/slapd/Makefile index 968df6f03..64858b213 100644 --- a/ldap/servers/slapd/Makefile +++ b/ldap/servers/slapd/Makefile @@ -88,6 +88,15 @@ endif endif endif +ifeq ($(ARCH), HPUX) +ifeq ($(OS_TEST),ia64) +LDAP_DONT_USE_SMARTHEAP=1 +ifeq ($(DEBUG), optimize) +CFLAGS+=+O3 +endif +endif +endif + # Don't use smartheap for debug builds ifeq ($(DEBUG), full) LDAP_DONT_USE_SMARTHEAP=1 @@ -189,10 +198,14 @@ LDFLAGS+=$(ARCH_CFLAGS) ifeq ($(DEBUG), full) ifeq ($(USE_64), 1) EXTRA_LIBS_TEMP:=$(EXTRA_LIBS) +ifneq ($(OS_TEST), ia64) EXTRA_LIBS += /opt/langtools/lib/pa20_64/end.o +endif else EXTRA_LIBS_TEMP:=$(EXTRA_LIBS) +ifneq ($(OS_TEST), ia64) EXTRA_LIBS += /opt/langtools/lib/end.o +endif endif #USE_64 endif #DEBUG # Always put libpthread at the beginning of the library list, otherwise NSPR gets upset (very) diff --git a/ldap/servers/slapd/main.c b/ldap/servers/slapd/main.c index 379c55bec..3eb207fcc 100644 --- a/ldap/servers/slapd/main.c +++ b/ldap/servers/slapd/main.c @@ -647,7 +647,7 @@ main( int argc, char **argv) Slapi_Backend *be = NULL; int init_ssl; #ifndef __LP64__ -#if defined(__hpux) +#if defined(__hpux) && !defined(__ia64) /* for static constructors */ _main(); #endif diff --git a/ldap/servers/slapd/tools/migratecred.c b/ldap/servers/slapd/tools/migratecred.c index f2c75da34..6b9f94ea2 100644 --- a/ldap/servers/slapd/tools/migratecred.c +++ b/ldap/servers/slapd/tools/migratecred.c @@ -152,7 +152,11 @@ main( int argc, char **argv) shared_lib = ".dll"; #else #ifdef HPUX +#ifdef __ia64 + shared_lib = ".so"; +#else shared_lib = ".sl"; +#endif #else #ifdef AIX #if OSVERSION >= 4200 diff --git a/ldap/systools/idsktune.c b/ldap/systools/idsktune.c index f0990785b..2d70f75a2 100644 --- a/ldap/systools/idsktune.c +++ b/ldap/systools/idsktune.c @@ -49,7 +49,7 @@ static char *build_date = "04-APRIL-2005"; #define IDDS_LINUX_SYSCTL 1 #endif -#if defined(__sun) || defined(__sun__) || defined(_AIX) || defined(__hppa) || defined(_nec_ews_svr4) || defined(__osf__) || defined(__sgi) || defined(sgi) +#if defined(__sun) || defined(__sun__) || defined(_AIX) || defined(__hpux) || defined(_nec_ews_svr4) || defined(__osf__) || defined(__sgi) || defined(sgi) #define IDDS_SYSV_INCLUDE 1 #endif @@ -68,7 +68,7 @@ static char *build_date = "04-APRIL-2005"; #include <errno.h> #include <ctype.h> #if !defined(_WIN32) && !defined(__VMS) && !defined(IDDS_LINUX_INCLUDE) && !defined(IDDS_BSD_INCLUDE) -#if defined(__hppa) && defined(f_type) +#if defined(__hpux) && defined(f_type) #undef f_type #endif #include <sys/statvfs.h> @@ -118,7 +118,7 @@ extern char *optarg; #define IDDS_MNTENT_MNTTAB "/etc/mtab" #endif -#if defined(__hppa) +#if defined(__hpux) #include <sys/pstat.h> #include <mntent.h> @@ -235,7 +235,7 @@ int mem_rec = 1024; #define NAME_TCP_SMALLEST_ANON_PORT "tcp_smallest_anon_port" #endif -#if defined(__hppa) +#if defined(__hpux) #define NAME_NDD_CFG_FILE "/etc/rc.config.d/nddconf" #define NAME_TCP_TIME_WAIT_INTERVAL "tcp_time_wait_interval" #define NAME_TCP_CONN_REQ_MAX_Q "tcp_conn_request_max" @@ -251,7 +251,7 @@ int mem_rec = 1024; #define NAME_TCP_SMALLEST_ANON_PORT "net.inet.ip.portrange.hifirst" #endif -#if defined(__sun) || defined(__hppa) || defined(IDDS_BSD_SYSCTL) || defined(IDDS_LINUX_SYSCTL) +#if defined(__sun) || defined(__hpux) || defined(IDDS_BSD_SYSCTL) || defined(IDDS_LINUX_SYSCTL) long ndd_tcp_conn_req_max_q = 0; long ndd_tcp_conn_req_max_q0 = 0; @@ -300,7 +300,7 @@ struct iii_pinfo { #endif -#if defined(__hppa) +#if defined(__hpux) struct pst_dynamic pst_dyn; struct pst_static pst_stt; struct pst_vminfo pst_vmm; @@ -1403,7 +1403,7 @@ static void gen_tests (void) phys_mb = (l * pk) / 1024; } #else -#if defined(__hppa) +#if defined(__hpux) hp_check_qpk(); if (pstat_getdynamic(&pst_dyn,sizeof(pst_dyn),1,0) == -1 || pstat_getstatic(&pst_stt,sizeof(pst_stt),1,0) == -1 || @@ -1490,7 +1490,7 @@ static void gen_tests (void) if (flag_html) printf("</P>\n"); } else if (client == 0 && swap_mb && swap_mb < phys_mb) { -#if defined(_AIX) || defined(__hppa) || defined(__sun) +#if defined(_AIX) || defined(__hpux) || defined(__sun) #else if (flag_html) printf("<P>\n"); printf("%s: There is %dMB of physical memory but only %dMB of swap space.\n\n", @@ -1545,7 +1545,7 @@ static void gen_tests (void) -#if defined(__sun) || defined(__hppa) || defined(IDDS_BSD_SYSCTL) || defined(IDDS_LINUX_SYSCTL) +#if defined(__sun) || defined(__hpux) || defined(IDDS_BSD_SYSCTL) || defined(IDDS_LINUX_SYSCTL) static int ndd_get_tcp (char *a,long *vPtr) { @@ -1554,7 +1554,7 @@ static int ndd_get_tcp (char *a,long *vPtr) #if defined(__sun) sprintf(buf,"/usr/sbin/ndd /dev/tcp %s",a); #else -#if defined(__hppa) +#if defined(__hpux) sprintf(buf,"/usr/bin/ndd /dev/tcp %s",a); #else #if defined(IDDS_BSD_SYSCTL) || defined(IDDS_LINUX_SYSCTL) @@ -1791,7 +1791,7 @@ static void sysconfig_tests (void) } #endif -#if defined(__hppa) +#if defined(__hpux) #include <dirent.h> #define HP_PATCH_DIR "/var/adm/sw/products" @@ -2045,7 +2045,7 @@ static void sun_check_network_device(void) } #endif -#if defined(__sun) || defined(__hppa) || defined(IDDS_BSD_SYSCTL) || defined(IDDS_LINUX_SYSCTL) +#if defined(__sun) || defined(__hpux) || defined(IDDS_BSD_SYSCTL) || defined(IDDS_LINUX_SYSCTL) static void ndd_tests (void) { @@ -2454,7 +2454,7 @@ static void ndd_tests (void) } #endif -#if defined(__sun) || defined(__hppa) +#if defined(__sun) || defined(__hpux) if (1) { if (ndd_get_tcp("tcp_deferred_ack_interval",&ndd_tcp_deferred_ack_interval) == 0) { if (ndd_tcp_deferred_ack_interval > 5) { @@ -2668,7 +2668,7 @@ static int check_fs_options(char *reqdir,char mntbuf[MAXPATHLEN]) mep = &m; if (getmntent(fp,mep) != 0) break; #else -#if defined(__hppa) || defined(IDDS_LINUX_INCLUDE) +#if defined(__hpux) || defined(IDDS_LINUX_INCLUDE) mep = getmntent(fp); if (mep == NULL) break; #else @@ -2708,7 +2708,7 @@ static int check_fs_options(char *reqdir,char mntbuf[MAXPATHLEN]) if (fp) fclose (fp); -#if defined(__hppa) +#if defined(__hpux) if (found == 0) { int largefile_missing = 0; @@ -2904,7 +2904,7 @@ static void check_mem_size(int ro,char *rn) } if (m_change_needed) { -#if defined(__hppa) +#if defined(__hpux) printf("NOTICE : use kmtune or sam Kernel Configuration Parameters to change the maxdsiz\nand maxdsiz_64bit parameters.\n"); #endif printf("\n"); @@ -2937,7 +2937,7 @@ static void limits_tests(void) printf("set rlim_fd_max=4096\n"); if (flag_html) printf("</PRE><P>\n"); #else -#if defined(__hppa) +#if defined(__hpux) printf("Additional file descriptors,\nup to 60000, are available by editing /stand/system and regenerating the kernel.\n"); if (flag_html) printf("</P><PRE>\n"); printf("maxfiles_lim 4096\n"); @@ -2965,7 +2965,7 @@ static void limits_tests(void) printf("WARNING: There are only %ld file descriptors (soft limit) available, which\nlimit the number of simultaneous connections. ",r.rlim_cur); } -#if defined(__sun) || defined(__hppa) +#if defined(__sun) || defined(__hpux) printf("Additional file descriptors,\nup to %ld (hard limit), are available by issuing \'ulimit\' (\'limit\' for tcsh)\ncommand with proper arguments.\n", r.rlim_max); if (flag_html) printf("</P><PRE>\n"); printf("ulimit -n 4096\n"); @@ -3004,7 +3004,7 @@ static void limits_tests(void) static void ids_get_platform(char *buf) { -#if defined(IDDS_LINUX_INCLUDE) || defined(__osf__) || defined(_AIX) || defined(__hppa) || defined(IDDS_BSD_INCLUDE) +#if defined(IDDS_LINUX_INCLUDE) || defined(__osf__) || defined(_AIX) || defined(__hpux) || defined(IDDS_BSD_INCLUDE) struct utsname u; #endif #if defined(_WIN32) @@ -3013,13 +3013,13 @@ static void ids_get_platform(char *buf) char osbuf[128]; #endif -#if defined(__hppa) || defined(_AIX) +#if defined(__hpux) || defined(_AIX) char model[128]; char procstr[128]; char oslevel[128]; #endif -#if defined(__hppa) +#if defined(__hpux) long cpuvers, cputype; #endif @@ -3106,7 +3106,7 @@ static void ids_get_platform(char *buf) sprintf(buf,"%s-unknown-%s%s", u.machine,u.sysname,u.release); #else -#if defined(__hppa) +#if defined(__hpux) uname(&u); confstr(_CS_MACHINE_MODEL,model,128); cpuvers = sysconf(_SC_CPU_VERSION); @@ -3126,6 +3126,11 @@ static void ids_get_platform(char *buf) case CPU_PA_RISC2_0: sprintf(procstr,"hppa2.0/%d",cputype); break; +#if defined(__ia64) + case CPU_IA64_ARCHREV_0: + sprintf(procstr,"hpia0/%d",cputype); + break; +#endif default: sprintf(procstr,"hppa_0x%x/%d",cpuvers,cputype); break; @@ -3299,11 +3304,11 @@ int main(int argc,char *argv[]) gen_tests(); -#if defined(__sun) || defined(__hppa) || defined(IDDS_BSD_SYSCTL) || defined(IDDS_LINUX_SYSCTL) +#if defined(__sun) || defined(__hpux) || defined(IDDS_BSD_SYSCTL) || defined(IDDS_LINUX_SYSCTL) ndd_tests(); #endif -#if defined(__hppa) +#if defined(__hpux) hp_pthreads_tests(); #endif diff --git a/lib/base/systhr.cpp b/lib/base/systhr.cpp index d9b695210..134ae2b4d 100644 --- a/lib/base/systhr.cpp +++ b/lib/base/systhr.cpp @@ -66,8 +66,11 @@ typedef struct { #if defined (USE_NSPR) - +#if defined(__hpux) && defined(__ia64) +#define DEFAULT_STACKSIZE (256*1024) +#else #define DEFAULT_STACKSIZE (64*1024) +#endif static unsigned long _systhr_stacksize = DEFAULT_STACKSIZE; diff --git a/lib/ldaputil/init.c b/lib/ldaputil/init.c index 935ec081a..371d6972c 100644 --- a/lib/ldaputil/init.c +++ b/lib/ldaputil/init.c @@ -56,7 +56,11 @@ #define FILE_PATHSEP '/' #endif #ifdef HPUX +#ifdef __ia64 +#define DLL_SUFFIX ".so" +#else #define DLL_SUFFIX ".sl" +#endif #else #define DLL_SUFFIX ".so" #endif diff --git a/nsarch b/nsarch index 5fc4cca3a..332ea0b01 100755 --- a/nsarch +++ b/nsarch @@ -467,6 +467,15 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in NS_RELEASE="${HPUX_REV}" ns_printf exit 0 ;; + ia64:HP-UX:*:*) + HP_ARCH=hpia + HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'` + GNU_NAME="${HP_ARCH}-hp-hpux${HPUX_REV}" + NS_NAME="HPUX" + NS_PRETTY_NAME="HP-UX" + NS_RELEASE="${HPUX_REV}" + ns_printf + exit 0 ;; 3050*:HI-UX:*:*) sed 's/^ //' << EOF >dummy.c #include <unistd.h> diff --git a/nsconfig.mk b/nsconfig.mk index 648f994fb..3cfcaac5c 100644 --- a/nsconfig.mk +++ b/nsconfig.mk @@ -272,6 +272,16 @@ else NSCONFIG = $(NSOS_ARCH)$(NSOS_RELEASE)_$(NSOS_TEST1)_$(GCC_VERSION) NSCONFIG_NOTAG = $(NSCONFIG) else + ifeq ($(NSOS_ARCH),HP-UX) + NSOS_TEST1 := $(shell uname -m) + ifeq ($(NSOS_TEST1), ia64) + NSCONFIG = $(NSOS_ARCH)$(NSOS_RELEASE)_$(NSOS_TEST1) + NSCONFIG_NOTAG = $(NSOS_ARCH)$(NSOS_RELEASE_NOTAG)_$(NSOS_TEST1) + else + NSCONFIG = $(NSOS_ARCH)$(NSOS_RELEASE) + NSCONFIG_NOTAG = $(NSOS_ARCH)$(NSOS_RELEASE_NOTAG) + endif + else ifeq ($(NSOS_TEST1),i86pc) NSCONFIG = $(NSOS_ARCH)$(NSOS_RELEASE)_$(NSOS_TEST1) NSCONFIG_NOTAG = $(NSOS_ARCH)$(NSOS_RELEASE_NOTAG)_$(NSOS_TEST1) @@ -279,6 +289,7 @@ else NSCONFIG = $(NSOS_ARCH)$(NSOS_RELEASE) NSCONFIG_NOTAG = $(NSOS_ARCH)$(NSOS_RELEASE_NOTAG) endif + endif endif endif @@ -508,23 +519,50 @@ PEER_ARCH=bsdi else ifeq ($(ARCH), HPUX) +ifeq ($(NSOS_TEST1), ia64) +DLL_SUFFIX=so +else DLL_SUFFIX=sl +endif #-D_POSIX_C_SOURCE=199506L turns kernel threads on for HPUX11 CC=cc -Ae -D_POSIX_C_SOURCE=199506L ifeq ($(BUILD_MODULE), HTTP_ADMIN) +ifeq ($(NSOS_RELEASE),B.11.23) +CXX=aCC -AP -DHPUX_ACC -D__STDC_EXT__ -D_POSIX_C_SOURCE=199506L -ext +else CXX=aCC -DHPUX_ACC -D__STDC_EXT__ -D_POSIX_C_SOURCE=199506L -ext +endif +else +ifeq ($(NSOS_RELEASE),B.11.23) +CXX=aCC -AP -DHPUX_ACC -D__STDC_EXT__ -D_POSIX_C_SOURCE=199506L -ext else CXX=aCC -DHPUX_ACC -D__STDC_EXT__ -D_POSIX_C_SOURCE=199506L -ext endif +endif CCC=$(CXX) ARCH_DEBUG=-g +ifeq ($(NSOS_RELEASE),B.11.23) +# optimization level changes actually is due to the aCC changes, +# it is applicable to 11i v1 also, but conditional compile here +# anyway. +ARCH_OPT=+O3 +else ARCH_OPT=-O +endif # Compile everything pos-independent in case we need to put it in shared lib +ifeq ($(NSOS_RELEASE),B.11.23) +ifdef USE_64 + ARCH_CFLAGS=-D_HPUX_SOURCE +DD64 +DSblended +Z +else + ARCH_CFLAGS=-D_HPUX_SOURCE +DD32 +DSblended +Z +endif +else ifdef USE_64 ARCH_CFLAGS=-D_HPUX_SOURCE +DA2.0W +DS2.0 +Z else ARCH_CFLAGS=-D_HPUX_SOURCE +DAportable +DS1.1 +Z endif +endif # NSPR uses fpsetmask which I'm told is in the math lib EXTRA_LIBS= -ldld -lm ifeq ($(NSOS_RELEASE), B.10.10) @@ -543,6 +581,10 @@ ifeq ($(NSOS_RELEASE), B.11.11) MODERNHP=1 endif +ifeq ($(NSOS_RELEASE), B.11.23) + MODERNHP=1 +endif + ifeq ($(MODERNHP), 1) ifeq ($(NSOS_RELEASE), B.11.00) ARCH_CFLAGS+=-DHPUX11 -DHPUX11_00 @@ -550,6 +592,9 @@ endif ifeq ($(NSOS_RELEASE), B.11.11) ARCH_CFLAGS+=-DHPUX11 -DHPUX11_11 endif +ifeq ($(NSOS_RELEASE), B.11.23) + ARCH_CFLAGS+=-DHPUX11 -DHPUX11_11 +endif # Debug with HPUX "dde" - makes the server single process - avoids fork()ing. # Can also be used for non HPUX if desired. #ARCH_CFLAGS+=-DUSE_DDE_DEBUG diff --git a/nsdefs.mk b/nsdefs.mk index 8e21ada3c..cbd3ce0fb 100644 --- a/nsdefs.mk +++ b/nsdefs.mk @@ -53,6 +53,8 @@ else BUILD_ARCH := $(shell $(BUILD_ROOT)/nsarch) endif +NSOS_TEST1 := $(shell uname -m) + USE_HCL=1 PUMPKIN_AGE := 120 @@ -79,6 +81,18 @@ endif ifdef USE_64 NS64TAG=_64 +else + ifeq ($(BUILD_ARCH), HPUX) + ifeq ($(NSOS_TEST1),ia64) + NS64TAG=_32 + endif + endif +endif + +ifeq ($(BUILD_ARCH), HPUX) + ifeq ($(NSOS_TEST1),ia64) + NSOS_TEST1_TAG=_$(NSOS_TEST1) + endif endif # Check if we're on RHEL @@ -209,7 +223,7 @@ RTSUFFIX=-d endif endif endif -BASIC_OBJDIR=$(BUILD_ROOT)/built/$(ARCH)$(NS64TAG)-$(SECURITY)-$(DEBUG)$(RTSUFFIX)-$(B_FORTEZZA) +BASIC_OBJDIR=$(BUILD_ROOT)/built/$(ARCH)$(NSOS_TEST1_TAG)$(NS64TAG)-$(SECURITY)-$(DEBUG)$(RTSUFFIX)-$(B_FORTEZZA) # # -- Directory Server Section ----------------------------------------------- @@ -235,7 +249,7 @@ ifeq ($(findstring RHEL, $(BUILD_ARCH)), RHEL) NS_BUILD_FLAVOR = $(BUILD_ARCH)$(NS64TAG)-$(SECURITY)$(SSL_PREFIX)-$(DEBUG)$(RTSUFFIX)-$(BUILD_FORTEZZA)$(BUILD_PTHREADS)-$(DIR) ARCHPROCESSOR = $(BUILD_ARCH) else - NS_BUILD_FLAVOR = $(ARCH)$(NS64TAG)-$(SECURITY)$(SSL_PREFIX)-$(DEBUG)$(RTSUFFIX)-$(BUILD_FORTEZZA)$(BUILD_PTHREADS)-$(DIR) + NS_BUILD_FLAVOR = $(ARCH)$(NSOS_TEST1_TAG)$(NS64TAG)-$(SECURITY)$(SSL_PREFIX)-$(DEBUG)$(RTSUFFIX)-$(BUILD_FORTEZZA)$(BUILD_PTHREADS)-$(DIR) endif NC_BUILD_FLAVOR = $(NSCONFIG)$(NSOBJDIR_TAG).OBJ ifeq ($(ARCH), WINNT) @@ -243,7 +257,7 @@ ifeq ($(PROCESSOR), ALPHA) ARCHPROCESSOR=$(ARCH)$(PROCESSOR) endif endif -COMMON_OBJDIR=$(BUILD_ROOT)/built/$(ARCHPROCESSOR)$(NS64TAG)-$(SECURITY)$(SSL_PREFIX)-$(DEBUG)$(RTSUFFIX)-$(BUILD_FORTEZZA)$(BUILD_PTHREADS)-$(DIR) +COMMON_OBJDIR=$(BUILD_ROOT)/built/$(ARCHPROCESSOR)$(NSOS_TEST1_TAG)$(NS64TAG)-$(SECURITY)$(SSL_PREFIX)-$(DEBUG)$(RTSUFFIX)-$(BUILD_FORTEZZA)$(BUILD_PTHREADS)-$(DIR) COMMON_OBJDIR_32=$(BUILD_ROOT)/built/$(ARCHPROCESSOR)-$(SECURITY)$(SSL_PREFIX)-$(DEBUG)$(RTSUFFIX)-$(BUILD_FORTEZZA)$(BUILD_PTHREADS)-$(DIR) OBJDIR=$(COMMON_OBJDIR) OBJDIR_32=$(COMMON_OBJDIR_32)
0
7962fb59d109d06de437d658e713edf99d6acd19
389ds/389-ds-base
Allow error on result side to propagate pack to sending side
commit 7962fb59d109d06de437d658e713edf99d6acd19 Author: David Boreham <[email protected]> Date: Wed May 4 23:58:51 2005 +0000 Allow error on result side to propagate pack to sending side diff --git a/ldap/servers/plugins/replication/repl5_inc_protocol.c b/ldap/servers/plugins/replication/repl5_inc_protocol.c index 933a78a9c..276ab4f06 100644 --- a/ldap/servers/plugins/replication/repl5_inc_protocol.c +++ b/ldap/servers/plugins/replication/repl5_inc_protocol.c @@ -98,6 +98,7 @@ typedef struct result_data int stop_result_thread; /* Flag used to tell the result thread to exit */ int last_message_id_sent; int last_message_id_received; + int result; /* The UPDATE_TRANSIENT_ERROR etc */ } result_data; /* Various states the incremental protocol can pass through */ @@ -263,6 +264,7 @@ static void repl5_inc_result_threadmain(void *param) int finished = 0; int message_id = 0; + slapi_log_error(SLAPI_LOG_REPL, NULL, "repl5_inc_result_threadmain starting\n"); while (!finished) { repl5_inc_operation *op = NULL; @@ -336,25 +338,11 @@ static void repl5_inc_result_threadmain(void *param) } conn_get_error_ex(conn, &operation_code, &connection_error, &ldap_error_string); - /* Back out of harmless errors here */ - if (ignore_error_and_keep_going(connection_error)) - { - char *op_string = slapi_op_type_to_string(operation_code); - slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name, - "%s: Ignoring error %d: %s for %s operation\n", - agmt_get_long_name(rd->prp->agmt), - connection_error, ldap_error_string ? ldap_error_string : "NULL", - op_string ? op_string : "NULL"); - connection_error = 0; - conres = 0; - } - if (connection_error) - { - repl5_inc_log_operation_failure(op ? op->operation_type : 0, connection_error, ldap_error_string, agmt_get_long_name(rd->prp->agmt)); - } - res = repl5_inc_update_from_op_result(rd->prp, conres, connection_error, csn_str, uniqueid, replica_id, &finished, &(rd->num_changes_sent)); - if (0 != conres) + slapi_log_error(SLAPI_LOG_REPL, NULL, "repl5_inc_result_threadmain: result %d, %d, %d, %s\n", operation_code,connection_error,conres,ldap_error_string); + rd->result = repl5_inc_update_from_op_result(rd->prp, conres, connection_error, csn_str, uniqueid, replica_id, &finished, &(rd->num_changes_sent)); + if (rd->result) { + slapi_log_error(SLAPI_LOG_REPL, NULL, "repl5_inc_result_threadmain: got op result %d\n", rd->result); /* If so then we need to take steps to abort the update process */ PR_Lock(rd->lock); rd->abort = 1; @@ -374,6 +362,7 @@ static void repl5_inc_result_threadmain(void *param) repl5_inc_op_free(op); } } + slapi_log_error(SLAPI_LOG_REPL, NULL, "repl5_inc_result_threadmain exiting\n"); } static result_data * @@ -1914,6 +1903,12 @@ send_updates(Private_Repl_Protocol *prp, RUV *remote_update_vector, PRUint32 *nu return_value = UPDATE_YIELD; finished = 1; } + /* See if the result thread has hit a problem */ + if (!finished && rd->abort) + { + return_value = rd->result; + finished = 1; + } } while (!finished); /* Terminate the results reading thread */
0
a3d35219a31e97a5f1093e2f461cb0e3a67cdacc
389ds/389-ds-base
Issue 6254 - Enabling replication for a sub suffix crashes browser (#6255) Bug Description: Web Console: Enabling replication for a sub-suffix causes TypeError: this.props.data.nsds5replicabinddn is not iterable. Fix Description: Make sure that loadSuffixTree is run for subsuffixes, too. Set defaults if data is absent. Fixes: https://github.com/389ds/389-ds-base/issues/6254 Reviewed by: @progier389 (Thanks!)
commit a3d35219a31e97a5f1093e2f461cb0e3a67cdacc Author: Simon Pichugin <[email protected]> Date: Tue Jul 9 18:09:28 2024 -0700 Issue 6254 - Enabling replication for a sub suffix crashes browser (#6255) Bug Description: Web Console: Enabling replication for a sub-suffix causes TypeError: this.props.data.nsds5replicabinddn is not iterable. Fix Description: Make sure that loadSuffixTree is run for subsuffixes, too. Set defaults if data is absent. Fixes: https://github.com/389ds/389-ds-base/issues/6254 Reviewed by: @progier389 (Thanks!) diff --git a/src/cockpit/389-console/src/lib/replication/replConfig.jsx b/src/cockpit/389-console/src/lib/replication/replConfig.jsx index ab24894d3..6c9b8ca69 100644 --- a/src/cockpit/389-console/src/lib/replication/replConfig.jsx +++ b/src/cockpit/389-console/src/lib/replication/replConfig.jsx @@ -40,8 +40,8 @@ export class ReplConfig extends React.Component { saveBtnDisabled: true, isExpanded: false, // Config Settings - nsds5replicabinddn: this.props.data.nsds5replicabinddn, - nsds5replicabinddngroup: this.props.data.nsds5replicabinddngroup, + nsds5replicabinddn: this.props.data?.nsds5replicabinddn || [], + nsds5replicabinddngroup: this.props.data?.nsds5replicabinddngroup || "", nsds5replicabinddngroupcheckinterval: Number(this.props.data.nsds5replicabinddngroupcheckinterval) === 0 ? -1 : Number(this.props.data.nsds5replicabinddngroupcheckinterval), nsds5replicareleasetimeout: Number(this.props.data.nsds5replicareleasetimeout), nsds5replicapurgedelay: Number(this.props.data.nsds5replicapurgedelay) === 0 ? 604800 : Number(this.props.data.nsds5replicapurgedelay), @@ -52,8 +52,8 @@ export class ReplConfig extends React.Component { nsds5replicabackoffmax: Number(this.props.data.nsds5replicabackoffmax) === 0 ? 300 : Number(this.props.data.nsds5replicabackoffmax), nsds5replicakeepaliveupdateinterval: Number(this.props.data.nsds5replicakeepaliveupdateinterval) === 0 ? 3600 : Number(this.props.data.nsds5replicakeepaliveupdateinterval), // Original settings - _nsds5replicabinddn: this.props.data.nsds5replicabinddn, - _nsds5replicabinddngroup: this.props.data.nsds5replicabinddngroup, + _nsds5replicabinddn: this.props.data?.nsds5replicabinddn || [], + _nsds5replicabinddngroup: this.props.data?.nsds5replicabinddngroup || "", _nsds5replicabinddngroupcheckinterval: Number(this.props.data.nsds5replicabinddngroupcheckinterval) === 0 ? -1 : Number(this.props.data.nsds5replicabinddngroupcheckinterval), _nsds5replicareleasetimeout: this.props.data.nsds5replicareleasetimeout, _nsds5replicapurgedelay: Number(this.props.data.nsds5replicapurgedelay) === 0 ? 604800 : Number(this.props.data.nsds5replicapurgedelay), diff --git a/src/cockpit/389-console/src/replication.jsx b/src/cockpit/389-console/src/replication.jsx index 9bd03b2b2..4c84a8003 100644 --- a/src/cockpit/389-console/src/replication.jsx +++ b/src/cockpit/389-console/src/replication.jsx @@ -162,8 +162,11 @@ export class Replication extends React.Component { } if (treeBranch[sub].children.length === 0) { delete treeBranch[sub].children; + } else { + this.processBranch(treeBranch[sub].children); } - this.processBranch(treeBranch[sub].children); + // Load replication data for this suffix + this.loadReplSuffix(treeBranch[sub].id); } } @@ -528,7 +531,7 @@ export class Replication extends React.Component { nsds5flags: config.attrs.nsds5flags[0], nsds5replicatype: config.attrs.nsds5replicatype[0], nsds5replicaid: 'nsds5replicaid' in config.attrs ? config.attrs.nsds5replicaid[0] : "", - nsds5replicabinddn: 'nsds5replicabinddn' in config.attrs ? config.attrs.nsds5replicabinddn : "", + nsds5replicabinddn: 'nsds5replicabinddn' in config.attrs ? config.attrs.nsds5replicabinddn : [], nsds5replicabinddngroup: 'nsds5replicabinddngroup' in config.attrs ? config.attrs.nsds5replicabinddngroup[0] : "", nsds5replicabinddngroupcheckinterval: 'nsds5replicabinddngroupcheckinterval' in config.attrs ? config.attrs.nsds5replicabinddngroupcheckinterval[0] : "", nsds5replicareleasetimeout: 'nsds5replicareleasetimeout' in config.attrs ? config.attrs.nsds5replicareleasetimeout[0] : "", @@ -671,7 +674,7 @@ export class Replication extends React.Component { nsds5flags: config.attrs.nsds5flags[0], nsds5replicatype: config.attrs.nsds5replicatype[0], nsds5replicaid: 'nsds5replicaid' in config.attrs ? config.attrs.nsds5replicaid[0] : "", - nsds5replicabinddn: 'nsds5replicabinddn' in config.attrs ? config.attrs.nsds5replicabinddn : "", + nsds5replicabinddn: 'nsds5replicabinddn' in config.attrs ? config.attrs.nsds5replicabinddn : [], nsds5replicabinddngroup: 'nsds5replicabinddngroup' in config.attrs ? config.attrs.nsds5replicabinddngroup[0] : "", nsds5replicabinddngroupcheckinterval: 'nsds5replicabinddngroupcheckinterval' in config.attrs ? config.attrs.nsds5replicabinddngroupcheckinterval[0] : "", nsds5replicareleasetimeout: 'nsds5replicareleasetimeout' in config.attrs ? config.attrs.nsds5replicareleasetimeout[0] : "",
0
bf919d1d0eefabb60155063dd22aa08b8a7d9938
389ds/389-ds-base
Initial commit with DSModuleProxy. In order to keep implementation of class DSInstance organized, we implement all functionality as functions in separate modules. All functions accept DSInstance object as their first argument by rule. Even though it`s beneficial to define everythin as function in separate module, in runtime it`s nicer to have methods on DSInstance. ModuleProxy serves two purposes: - takes modules and all functions within and adds them to DSInstance as methods - creates separate namespaces for all modules within DSInstance
commit bf919d1d0eefabb60155063dd22aa08b8a7d9938 Author: Jan Rusnacko <[email protected]> Date: Thu Oct 10 18:19:15 2013 +0200 Initial commit with DSModuleProxy. In order to keep implementation of class DSInstance organized, we implement all functionality as functions in separate modules. All functions accept DSInstance object as their first argument by rule. Even though it`s beneficial to define everythin as function in separate module, in runtime it`s nicer to have methods on DSInstance. ModuleProxy serves two purposes: - takes modules and all functions within and adds them to DSInstance as methods - creates separate namespaces for all modules within DSInstance diff --git a/src/lib389/lib389/__init__.py b/src/lib389/lib389/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/src/lib389/lib389/ds_instance.py b/src/lib389/lib389/ds_instance.py new file mode 100644 index 000000000..7545eee77 --- /dev/null +++ b/src/lib389/lib389/ds_instance.py @@ -0,0 +1,82 @@ +import os, re, sys + +class DSDecorator(object): + """ Implements decorator that can be instantiated during runtime. + + Accepts function and instance of DSInstance. When called, + it will call passed function with instance of DSInstance + passed as the first argument. + """ + def __init__(self, fun, ds_instance): + self.fun = fun + self.ds_instance = ds_instance + + def __call__(self, *args, **kwargs): + if args is None and kwargs is None: + return self.fun(self.ds_instance) + elif args is not None and kwargs is None: + return self.fun(self.ds_instance, *args) + elif args is None and kwargs is not None: + return self.fun(self.ds_instance, **kwargs) + else: + return self.fun(self.ds_instance, *args, **kwargs) + +class DSModuleProxy(object): + """ Proxy with DS-decorated functions from modules in directory. + + DSModuleProxy object acts as a proxy to functions defined in modules + stored in directory. Proxy itself can have other proxies as + attributes, so returned object follows the structure of passed + directory. All funcions from all modules are decorated with + DSDecorator - DSInstance object will be passed to them as first + argument. + + Kudos to Milan Falesnik <[email protected]> + """ + + def __init__(self, module_name): + self.name = module_name + + @classmethod + def populate_with_proxies(cls, ds, obj, directory): + """ + Returns a proxy with decorated functions from modules in directory. + """ + if not os.path.isdir(directory): + raise RuntimeError("Last argument %s was not directory" % directory) + for item in os.listdir(directory): + + # case when item is directory + if os.path.isdir(directory + "/" + item): + # Recursively call self on all subdirectories + proxy = cls(item) + cls.populate_with_proxies(ds, proxy, directory + "/" + item) + setattr(obj, item, proxy) + + # case when item is python module + elif (os.path.isfile(directory + "/" + item) and + re.match(r'(.*\/)?[^_/].*[^_/]\.py$', item)): + + # get the module object corresponding to processed file + item = item.replace('.py', '') + to_import = (directory + "/" + item).replace('/','.') + __import__(to_import) + module = sys.modules[to_import] + proxy = cls(item) + + # for each function from module create decorated one and keep it + for attr in dir(module): + fun = getattr(module, attr) + if callable(fun): + decorated = DSDecorator(fun, ds) + setattr(proxy, attr, decorated) + setattr(obj, item, proxy) + + else: + # skip anything that is not directory or python module + pass + +class DSInstance(object): + + def __init__(self): + DSModuleProxy.populate_with_proxies(self, self, 'dsmodules') diff --git a/src/lib389/tests/__init__.py b/src/lib389/tests/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/src/lib389/tests/conftest.py b/src/lib389/tests/conftest.py new file mode 100644 index 000000000..763774c85 --- /dev/null +++ b/src/lib389/tests/conftest.py @@ -0,0 +1,106 @@ + +import string +import os +import sys +import pytest +from tempfile import mkdtemp +from shutil import rmtree + +def ldrop(numchar, inputstr): + """ + Drop numchar characters from the beginning of each line in inputstring. + """ + return "\n".join([x[numchar:] for x in string.split(inputstr, "\n")]) + [email protected] +def fake_ds_class(): + """ + Returns fake DSInstance-like class + """ + class FakeDSInstance(object): + def return_one(self): + return 1 + + return FakeDSInstance + [email protected](scope="module") +def fake_ds_modules(request): + """ + Returns path to directory containing fake modules. + """ + + # module_dir contains fake ds modules, that can be used for testing + module_dir = mkdtemp() + old_cwd = os.getcwd() + + # when fixture is destroyed, we change back to old cwd + # and delete fake module dir + def fin(): + os.chdir(old_cwd) + rmtree(module_dir) + request.addfinalizer(fin) + + # make module_dir a python package + with open(module_dir + "/__init__.py", 'a'): + os.utime(module_dir + "/__init__.py", None) + + # create module module_dir/repl.py with few functions + with open(module_dir + "/repl.py", "w") as repl_file: + repl_module = """ + def with_no_arg(ds): + return ds + + def with_one_arg(ds, arg): + return ds, arg + + def return_argument_given(ds, arg): + return arg + + def with_kwarg(ds, kwarg=2): + return kwarg + + def with_all(ds, arg1, arg2, kwarg1=1, kwarg2=2): + return arg1, arg2, kwarg1, kwarg2 + + """ + # Drop 12 chars from left and write to file + repl_file.write(ldrop(12, repl_module)) + + os.mkdir(module_dir + "/plugin") + + # make module_dir/plugin a python package + with open(module_dir + "/plugin/__init__.py", 'a'): + os.utime(module_dir + "/plugin/__init__.py", None) + + # create module module_dir/plugin/automember.py with few functions + with open(module_dir + "/plugin/automember.py", "w") as automem_file: + automember_module = """ + def with_no_arg(ds): + return ds + + def with_one_arg(ds, arg): + return ds, arg + + def calling_ds_method(ds, arg): + return (ds, ds.return_one(), arg) + + def calling_repl(ds, arg1, arg2): + return ds.repl.return_argument_given(1) + arg1 + arg2 + + def calling_repl_with_kwarg2(ds): + return ds.repl.with_kwarg() + + def calling_repl_with_kwarg1(ds): + return ds.repl.with_kwarg(kwarg=1) + + def with_all(ds, arg1, arg2, kwarg1=1, kwarg2=2): + a, b, c, d = ds.repl.with_all(1, 4, kwarg1=3) + return a + arg1, b + arg2, c + kwarg1, d + kwarg2 + + """ + # Drop 12 chars from left and write to file + automem_file.write(ldrop(12, automember_module)) + + os.chdir(os.path.dirname(module_dir)) + sys.path.append(os.path.dirname(module_dir)) + return module_dir diff --git a/src/lib389/tests/test_module_proxy.py b/src/lib389/tests/test_module_proxy.py new file mode 100644 index 000000000..e21271e2f --- /dev/null +++ b/src/lib389/tests/test_module_proxy.py @@ -0,0 +1,45 @@ + +import os +from lib389.ds_instance import DSModuleProxy + +def test_module_proxy_fun_with_no_arg(fake_ds_class, fake_ds_modules): + ds_inst = fake_ds_class() + DSModuleProxy.populate_with_proxies(ds_inst, ds_inst, os.path.basename(fake_ds_modules)) + assert ds_inst.repl.with_no_arg() == ds_inst + +def test_module_proxy_fun_with_one_arg(fake_ds_class, fake_ds_modules): + ds_inst = fake_ds_class() + DSModuleProxy.populate_with_proxies(ds_inst, ds_inst, os.path.basename(fake_ds_modules)) + assert ds_inst.repl.with_one_arg(1) == (ds_inst, 1) + +def test_module_proxy_plugin_fun_with_no_arg(fake_ds_class, fake_ds_modules): + ds_inst = fake_ds_class() + DSModuleProxy.populate_with_proxies(ds_inst, ds_inst, os.path.basename(fake_ds_modules)) + assert ds_inst.plugin.automember.with_no_arg() == ds_inst + +def test_module_proxy_plugin_fun_with_one_arg(fake_ds_class, fake_ds_modules): + ds_inst = fake_ds_class() + DSModuleProxy.populate_with_proxies(ds_inst, ds_inst, os.path.basename(fake_ds_modules)) + assert ds_inst.plugin.automember.with_one_arg(2) == (ds_inst, 2) + +def test_module_proxy_plugin_call_ds_method(fake_ds_class, fake_ds_modules): + ds_inst = fake_ds_class() + DSModuleProxy.populate_with_proxies(ds_inst, ds_inst, os.path.basename(fake_ds_modules)) + assert ds_inst.plugin.automember.calling_ds_method(2) == (ds_inst, 1, 2) + +def test_module_proxy_plugin_call_another_module(fake_ds_class, fake_ds_modules): + ds_inst = fake_ds_class() + DSModuleProxy.populate_with_proxies(ds_inst, ds_inst, os.path.basename(fake_ds_modules)) + assert ds_inst.plugin.automember.calling_repl(2, 3) == 6 + +def test_module_proxy_plugin_call_another_module_kwarg(fake_ds_class, fake_ds_modules): + ds_inst = fake_ds_class() + DSModuleProxy.populate_with_proxies(ds_inst, ds_inst, os.path.basename(fake_ds_modules)) + assert ds_inst.plugin.automember.calling_repl_with_kwarg1() == 1 + assert ds_inst.plugin.automember.calling_repl_with_kwarg2() == 2 + +def test_module_proxy_plugin_call_with_all(fake_ds_class, fake_ds_modules): + ds_inst = fake_ds_class() + DSModuleProxy.populate_with_proxies(ds_inst, ds_inst, os.path.basename(fake_ds_modules)) + assert ds_inst.plugin.automember.with_all(0, 3, 2, 1) == (1, 7, 5, 3) +
0
11974a08f7bb083a48590cdc26652934fa74c0cb
389ds/389-ds-base
Ticket 49435 - Fix NS race condition on loaded test systems Bug Description: During a test run, on a heavily loaded systems some events would time out before they could occur correctly. Fix Description: Change the structure of events to mitigate a deref performance hit, and add a ns_job_wait conditional that allows blocking on a job to complete so that tests do not require time based checks. https://pagure.io/389-ds-base/issue/49435 Author: wibrown Review by: mreynolds (Thanks!)
commit 11974a08f7bb083a48590cdc26652934fa74c0cb Author: William Brown <[email protected]> Date: Mon Nov 6 08:56:01 2017 +1000 Ticket 49435 - Fix NS race condition on loaded test systems Bug Description: During a test run, on a heavily loaded systems some events would time out before they could occur correctly. Fix Description: Change the structure of events to mitigate a deref performance hit, and add a ns_job_wait conditional that allows blocking on a job to complete so that tests do not require time based checks. https://pagure.io/389-ds-base/issue/49435 Author: wibrown Review by: mreynolds (Thanks!) diff --git a/src/nunc-stans/include/nunc-stans.h b/src/nunc-stans/include/nunc-stans.h index 386a8d283..192e38ec3 100644 --- a/src/nunc-stans/include/nunc-stans.h +++ b/src/nunc-stans/include/nunc-stans.h @@ -77,6 +77,10 @@ typedef enum _ns_result_t { * This occurs when a lower level OS issue occurs, generally thread related. */ NS_THREAD_FAILURE = 5, + /** + * The job is being deleted + */ + NS_DELETING = 6, } ns_result_t; /** @@ -836,6 +840,14 @@ ns_job_type_t ns_job_get_output_type(struct ns_job_t *job); */ ns_result_t ns_job_set_done_cb(struct ns_job_t *job, ns_job_func_t func); +/** + * Block until a job is completed. This returns the next state of the job as as a return. + * + * \param job The job to set the callback for. + * \retval ns_job_state_t The next state the job will move to. IE, WAITING, DELETED, ARMED. + */ +ns_result_t ns_job_wait(struct ns_job_t *job); + /** * Creates a new thread pool * diff --git a/src/nunc-stans/ns/ns_event_fw.h b/src/nunc-stans/ns/ns_event_fw.h index 436b28269..88997b24d 100644 --- a/src/nunc-stans/ns/ns_event_fw.h +++ b/src/nunc-stans/ns/ns_event_fw.h @@ -80,7 +80,8 @@ typedef enum _ns_job_state { interface between the app/thread pool/event framework */ typedef struct ns_job_t { - pthread_mutex_t *monitor; + pthread_mutex_t monitor; + pthread_cond_t notify; struct ns_thrpool_t *tp; ns_job_func_t func; struct ns_job_data_t *data; diff --git a/src/nunc-stans/ns/ns_thrpool.c b/src/nunc-stans/ns/ns_thrpool.c index 2ad0bd799..1d8bb03f1 100644 --- a/src/nunc-stans/ns/ns_thrpool.c +++ b/src/nunc-stans/ns/ns_thrpool.c @@ -214,7 +214,7 @@ job_queue_cleanup(void *arg) static void internal_ns_job_done(ns_job_t *job) { - pthread_mutex_lock(job->monitor); + pthread_mutex_lock(&(job->monitor)); #ifdef DEBUG ns_log(LOG_DEBUG, "internal_ns_job_done %x state %d moving to NS_JOB_DELETED\n", job, job->state); #endif @@ -239,9 +239,9 @@ internal_ns_job_done(ns_job_t *job) job->done_cb(job); } - pthread_mutex_unlock(job->monitor); - pthread_mutex_destroy(job->monitor); - ns_free(job->monitor); + pthread_mutex_unlock(&(job->monitor)); + pthread_mutex_destroy(&(job->monitor)); + pthread_cond_destroy(&(job->notify)); ns_free(job); } @@ -250,7 +250,7 @@ internal_ns_job_done(ns_job_t *job) static void internal_ns_job_rearm(ns_job_t *job) { - pthread_mutex_lock(job->monitor); + pthread_mutex_lock(&(job->monitor)); PR_ASSERT(job->state == NS_JOB_NEEDS_ARM); /* Don't think I need to check persistence here, it could be the first arm ... */ #ifdef DEBUG @@ -267,7 +267,7 @@ internal_ns_job_rearm(ns_job_t *job) /* Prevents an un-necessary queue / dequeue to the event_q */ work_q_notify(job); } - pthread_mutex_unlock(job->monitor); + pthread_mutex_unlock(&(job->monitor)); } static void @@ -281,7 +281,7 @@ work_job_execute(ns_job_t *job) * DELETED! Crashes abound, you have been warned ... */ PR_ASSERT(job); - pthread_mutex_lock(job->monitor); + pthread_mutex_lock(&(job->monitor)); #ifdef DEBUG ns_log(LOG_DEBUG, "work_job_execute %x state %d moving to NS_JOB_RUNNING\n", job, job->state); #endif @@ -303,7 +303,12 @@ work_job_execute(ns_job_t *job) #ifdef DEBUG ns_log(LOG_DEBUG, "work_job_execute %x state %d job func complete, sending to job_done...\n", job, job->state); #endif - pthread_mutex_unlock(job->monitor); + /* + * Let waiters know we are done, they'll pick up once + * we unlock. + */ + pthread_cond_signal(&(job->notify)); + pthread_mutex_unlock(&(job->monitor)); internal_ns_job_done(job); /* MUST NOT ACCESS JOB AGAIN.*/ } else if (job->state == NS_JOB_NEEDS_ARM) { @@ -311,7 +316,8 @@ work_job_execute(ns_job_t *job) ns_log(LOG_DEBUG, "work_job_execute %x state %d job func complete, sending to rearm...\n", job, job->state); #endif /* Rearm the job! */ - pthread_mutex_unlock(job->monitor); + /* We *don't* notify here because we ARE NOT done! */ + pthread_mutex_unlock(&(job->monitor)); internal_ns_job_rearm(job); } else { #ifdef DEBUG @@ -321,7 +327,12 @@ work_job_execute(ns_job_t *job) PR_ASSERT(!NS_JOB_IS_PERSIST(job->job_type)); /* We are now idle, set waiting. */ job->state = NS_JOB_WAITING; - pthread_mutex_unlock(job->monitor); + /* + * Let waiters know we are done, they'll pick up once + * we unlock. + */ + pthread_cond_signal(&(job->notify)); + pthread_mutex_unlock(&(job->monitor)); } /* MUST NOT ACCESS JOB AGAIN */ } @@ -338,7 +349,7 @@ static void work_q_notify(ns_job_t *job) { PR_ASSERT(job); - pthread_mutex_lock(job->monitor); + pthread_mutex_lock(&(job->monitor)); #ifdef DEBUG ns_log(LOG_DEBUG, "work_q_notify %x state %d\n", job, job->state); #endif @@ -346,12 +357,12 @@ work_q_notify(ns_job_t *job) if (job->state != NS_JOB_ARMED) { /* Maybe we should return some error here? */ ns_log(LOG_ERR, "work_q_notify %x state %d is not ARMED, cannot queue!\n", job, job->state); - pthread_mutex_unlock(job->monitor); + pthread_mutex_unlock(&(job->monitor)); return; } /* MUST NOT ACCESS job after enqueue. So we stash tp.*/ ns_thrpool_t *ltp = job->tp; - pthread_mutex_unlock(job->monitor); + pthread_mutex_unlock(&(job->monitor)); sds_lqueue_enqueue(ltp->work_q, (void *)job); pthread_mutex_lock(&(ltp->work_q_lock)); pthread_cond_signal(&(ltp->work_q_cv)); @@ -411,13 +422,13 @@ static void update_event(ns_job_t *job) { PR_ASSERT(job); - pthread_mutex_lock(job->monitor); + pthread_mutex_lock(&(job->monitor)); #ifdef DEBUG ns_log(LOG_DEBUG, "update_event %x state %d\n", job, job->state); #endif PR_ASSERT(job->state == NS_JOB_NEEDS_DELETE || job->state == NS_JOB_ARMED); if (job->state == NS_JOB_NEEDS_DELETE) { - pthread_mutex_unlock(job->monitor); + pthread_mutex_unlock(&(job->monitor)); internal_ns_job_done(job); return; } else if (NS_JOB_IS_IO(job->job_type) || job->ns_event_fw_fd) { @@ -426,7 +437,7 @@ update_event(ns_job_t *job) } else { job->tp->ns_event_fw->ns_event_fw_mod_io(job->tp->ns_event_fw_ctx, job); } - pthread_mutex_unlock(job->monitor); + pthread_mutex_unlock(&(job->monitor)); /* We need these returns to prevent a race on the next else if condition when we release job->monitor */ return; } else if (NS_JOB_IS_TIMER(job->job_type) || job->ns_event_fw_time) { @@ -435,7 +446,7 @@ update_event(ns_job_t *job) } else { job->tp->ns_event_fw->ns_event_fw_mod_timer(job->tp->ns_event_fw_ctx, job); } - pthread_mutex_unlock(job->monitor); + pthread_mutex_unlock(&(job->monitor)); return; } else if (NS_JOB_IS_SIGNAL(job->job_type) || job->ns_event_fw_sig) { if (!job->ns_event_fw_sig) { @@ -443,15 +454,15 @@ update_event(ns_job_t *job) } else { job->tp->ns_event_fw->ns_event_fw_mod_signal(job->tp->ns_event_fw_ctx, job); } - pthread_mutex_unlock(job->monitor); + pthread_mutex_unlock(&(job->monitor)); return; } else { /* It's a "run now" job. */ if (NS_JOB_IS_THREAD(job->job_type)) { - pthread_mutex_unlock(job->monitor); + pthread_mutex_unlock(&(job->monitor)); work_q_notify(job); } else { - pthread_mutex_unlock(job->monitor); + pthread_mutex_unlock(&(job->monitor)); event_q_notify(job); } } @@ -602,14 +613,14 @@ event_cb(ns_job_t *job) */ /* There is no guarantee this won't be called once we start to enter the shutdown, especially with timers .... */ - pthread_mutex_lock(job->monitor); + pthread_mutex_lock(&(job->monitor)); PR_ASSERT(job->state == NS_JOB_ARMED || job->state == NS_JOB_NEEDS_DELETE); if (job->state == NS_JOB_ARMED && NS_JOB_IS_THREAD(job->job_type)) { #ifdef DEBUG ns_log(LOG_DEBUG, "event_cb %x state %d threaded, send to work_q\n", job, job->state); #endif - pthread_mutex_unlock(job->monitor); + pthread_mutex_unlock(&(job->monitor)); work_q_notify(job); } else if (job->state == NS_JOB_NEEDS_DELETE) { #ifdef DEBUG @@ -620,14 +631,14 @@ event_cb(ns_job_t *job) * It's here because it's been QUEUED for deletion and *may* be coming * from the thrpool destroy thread! */ - pthread_mutex_unlock(job->monitor); + pthread_mutex_unlock(&(job->monitor)); } else { #ifdef DEBUG ns_log(LOG_DEBUG, "event_cb %x state %d non-threaded, execute right meow\n", job, job->state); #endif /* Not threaded, execute now! */ - pthread_mutex_unlock(job->monitor); + pthread_mutex_unlock(&(job->monitor)); work_job_execute(job); /* MUST NOT ACCESS JOB FROM THIS POINT */ } @@ -682,12 +693,12 @@ static ns_job_t * new_ns_job(ns_thrpool_t *tp, PRFileDesc *fd, ns_job_type_t job_type, ns_job_func_t func, struct ns_job_data_t *data) { ns_job_t *job = ns_calloc(1, sizeof(ns_job_t)); - job->monitor = ns_calloc(1, sizeof(pthread_mutex_t)); pthread_mutexattr_t *monitor_attr = ns_calloc(1, sizeof(pthread_mutexattr_t)); pthread_mutexattr_init(monitor_attr); pthread_mutexattr_settype(monitor_attr, PTHREAD_MUTEX_RECURSIVE); - assert(pthread_mutex_init(job->monitor, monitor_attr) == 0); + assert(pthread_mutex_init(&(job->monitor), monitor_attr) == 0); + assert(pthread_cond_init(&(job->notify), NULL) == 0); ns_free(monitor_attr); job->tp = tp; @@ -746,14 +757,14 @@ ns_job_done(ns_job_t *job) /* Get the shutdown state ONCE at the start, atomically */ int32_t shutdown_state = ns_thrpool_is_shutdown(job->tp); - pthread_mutex_lock(job->monitor); + pthread_mutex_lock(&(job->monitor)); if (job->state == NS_JOB_NEEDS_DELETE || job->state == NS_JOB_DELETED) { /* Just return if the job has been marked for deletion */ #ifdef DEBUG ns_log(LOG_DEBUG, "ns_job_done %x tp shutdown -> %x state %d return early\n", job, shutdown_state, job->state); #endif - pthread_mutex_unlock(job->monitor); + pthread_mutex_unlock(&(job->monitor)); return NS_SUCCESS; } @@ -762,7 +773,7 @@ ns_job_done(ns_job_t *job) #ifdef DEBUG ns_log(LOG_DEBUG, "ns_job_done %x tp shutdown -> false state %d failed to mark as done\n", job, job->state); #endif - pthread_mutex_unlock(job->monitor); + pthread_mutex_unlock(&(job->monitor)); return NS_INVALID_STATE; } @@ -773,13 +784,13 @@ ns_job_done(ns_job_t *job) ns_log(LOG_DEBUG, "ns_job_done %x tp shutdown -> false state %d setting to async NS_JOB_NEEDS_DELETE\n", job, job->state); #endif job->state = NS_JOB_NEEDS_DELETE; - pthread_mutex_unlock(job->monitor); + pthread_mutex_unlock(&(job->monitor)); } else if (!shutdown_state) { #ifdef DEBUG ns_log(LOG_DEBUG, "ns_job_done %x tp shutdown -> false state %d setting NS_JOB_NEEDS_DELETE and queuing\n", job, job->state); #endif job->state = NS_JOB_NEEDS_DELETE; - pthread_mutex_unlock(job->monitor); + pthread_mutex_unlock(&(job->monitor)); event_q_notify(job); } else { #ifdef DEBUG @@ -787,7 +798,7 @@ ns_job_done(ns_job_t *job) #endif job->state = NS_JOB_NEEDS_DELETE; /* We are shutting down, just remove it! */ - pthread_mutex_unlock(job->monitor); + pthread_mutex_unlock(&(job->monitor)); internal_ns_job_done(job); } return NS_SUCCESS; @@ -849,12 +860,12 @@ ns_add_io_job(ns_thrpool_t *tp, PRFileDesc *fd, ns_job_type_t job_type, ns_job_f return NS_ALLOCATION_FAILURE; } - pthread_mutex_lock(_job->monitor); + pthread_mutex_lock(&(_job->monitor)); #ifdef DEBUG ns_log(LOG_DEBUG, "ns_add_io_job state %d moving to NS_JOB_ARMED\n", (_job)->state); #endif _job->state = NS_JOB_NEEDS_ARM; - pthread_mutex_unlock(_job->monitor); + pthread_mutex_unlock(&(_job->monitor)); internal_ns_job_rearm(_job); /* fill in a pointer to the job for the caller if requested */ @@ -889,12 +900,12 @@ ns_add_timeout_job(ns_thrpool_t *tp, struct timeval *tv, ns_job_type_t job_type, return NS_ALLOCATION_FAILURE; } - pthread_mutex_lock(_job->monitor); + pthread_mutex_lock(&(_job->monitor)); #ifdef DEBUG ns_log(LOG_DEBUG, "ns_add_timeout_job state %d moving to NS_JOB_ARMED\n", (_job)->state); #endif _job->state = NS_JOB_NEEDS_ARM; - pthread_mutex_unlock(_job->monitor); + pthread_mutex_unlock(&(_job->monitor)); internal_ns_job_rearm(_job); /* fill in a pointer to the job for the caller if requested */ @@ -944,14 +955,14 @@ ns_add_io_timeout_job(ns_thrpool_t *tp, PRFileDesc *fd, struct timeval *tv, ns_j if (!_job) { return NS_ALLOCATION_FAILURE; } - pthread_mutex_lock(_job->monitor); + pthread_mutex_lock(&(_job->monitor)); _job->tv = *tv; #ifdef DEBUG ns_log(LOG_DEBUG, "ns_add_io_timeout_job state %d moving to NS_JOB_ARMED\n", (_job)->state); #endif _job->state = NS_JOB_NEEDS_ARM; - pthread_mutex_unlock(_job->monitor); + pthread_mutex_unlock(&(_job->monitor)); internal_ns_job_rearm(_job); /* fill in a pointer to the job for the caller if requested */ @@ -982,12 +993,12 @@ ns_add_signal_job(ns_thrpool_t *tp, int32_t signum, ns_job_type_t job_type, ns_j return NS_ALLOCATION_FAILURE; } - pthread_mutex_lock(_job->monitor); + pthread_mutex_lock(&(_job->monitor)); #ifdef DEBUG ns_log(LOG_DEBUG, "ns_add_signal_job state %d moving to NS_JOB_ARMED\n", (_job)->state); #endif _job->state = NS_JOB_NEEDS_ARM; - pthread_mutex_unlock(_job->monitor); + pthread_mutex_unlock(&(_job->monitor)); internal_ns_job_rearm(_job); /* fill in a pointer to the job for the caller if requested */ @@ -1038,9 +1049,9 @@ ns_add_shutdown_job(ns_thrpool_t *tp) if (!_job) { return NS_ALLOCATION_FAILURE; } - pthread_mutex_lock(_job->monitor); + pthread_mutex_lock(&(_job->monitor)); _job->state = NS_JOB_NEEDS_ARM; - pthread_mutex_unlock(_job->monitor); + pthread_mutex_unlock(&(_job->monitor)); internal_ns_job_rearm(_job); return NS_SUCCESS; } @@ -1061,13 +1072,13 @@ void * ns_job_get_data(ns_job_t *job) { PR_ASSERT(job); - pthread_mutex_lock(job->monitor); + pthread_mutex_lock(&(job->monitor)); PR_ASSERT(job->state != NS_JOB_DELETED); if (job->state != NS_JOB_DELETED) { - pthread_mutex_unlock(job->monitor); + pthread_mutex_unlock(&(job->monitor)); return job->data; } else { - pthread_mutex_unlock(job->monitor); + pthread_mutex_unlock(&(job->monitor)); return NULL; } } @@ -1076,14 +1087,14 @@ ns_result_t ns_job_set_data(ns_job_t *job, void *data) { PR_ASSERT(job); - pthread_mutex_lock(job->monitor); + pthread_mutex_lock(&(job->monitor)); PR_ASSERT(job->state == NS_JOB_WAITING || job->state == NS_JOB_RUNNING); if (job->state == NS_JOB_WAITING || job->state == NS_JOB_RUNNING) { job->data = data; - pthread_mutex_unlock(job->monitor); + pthread_mutex_unlock(&(job->monitor)); return NS_SUCCESS; } else { - pthread_mutex_unlock(job->monitor); + pthread_mutex_unlock(&(job->monitor)); return NS_INVALID_STATE; } } @@ -1092,13 +1103,13 @@ ns_thrpool_t * ns_job_get_tp(ns_job_t *job) { PR_ASSERT(job); - pthread_mutex_lock(job->monitor); + pthread_mutex_lock(&(job->monitor)); PR_ASSERT(job->state != NS_JOB_DELETED); if (job->state != NS_JOB_DELETED) { - pthread_mutex_unlock(job->monitor); + pthread_mutex_unlock(&(job->monitor)); return job->tp; } else { - pthread_mutex_unlock(job->monitor); + pthread_mutex_unlock(&(job->monitor)); return NULL; } } @@ -1107,13 +1118,13 @@ ns_job_type_t ns_job_get_output_type(ns_job_t *job) { PR_ASSERT(job); - pthread_mutex_lock(job->monitor); + pthread_mutex_lock(&(job->monitor)); PR_ASSERT(job->state == NS_JOB_RUNNING); if (job->state == NS_JOB_RUNNING) { - pthread_mutex_unlock(job->monitor); + pthread_mutex_unlock(&(job->monitor)); return job->output_job_type; } else { - pthread_mutex_unlock(job->monitor); + pthread_mutex_unlock(&(job->monitor)); return 0; } } @@ -1122,13 +1133,13 @@ ns_job_type_t ns_job_get_type(ns_job_t *job) { PR_ASSERT(job); - pthread_mutex_lock(job->monitor); + pthread_mutex_lock(&(job->monitor)); PR_ASSERT(job->state != NS_JOB_DELETED); if (job->state != NS_JOB_DELETED) { - pthread_mutex_unlock(job->monitor); + pthread_mutex_unlock(&(job->monitor)); return job->job_type; } else { - pthread_mutex_unlock(job->monitor); + pthread_mutex_unlock(&(job->monitor)); return 0; } } @@ -1137,13 +1148,13 @@ PRFileDesc * ns_job_get_fd(ns_job_t *job) { PR_ASSERT(job); - pthread_mutex_lock(job->monitor); + pthread_mutex_lock(&(job->monitor)); PR_ASSERT(job->state != NS_JOB_DELETED); if (job->state != NS_JOB_DELETED) { - pthread_mutex_unlock(job->monitor); + pthread_mutex_unlock(&(job->monitor)); return job->fd; } else { - pthread_mutex_unlock(job->monitor); + pthread_mutex_unlock(&(job->monitor)); return NULL; } } @@ -1152,18 +1163,40 @@ ns_result_t ns_job_set_done_cb(struct ns_job_t *job, ns_job_func_t func) { PR_ASSERT(job); - pthread_mutex_lock(job->monitor); + pthread_mutex_lock(&(job->monitor)); PR_ASSERT(job->state == NS_JOB_WAITING || job->state == NS_JOB_RUNNING); if (job->state == NS_JOB_WAITING || job->state == NS_JOB_RUNNING) { job->done_cb = func; - pthread_mutex_unlock(job->monitor); + pthread_mutex_unlock(&(job->monitor)); return NS_SUCCESS; } else { - pthread_mutex_unlock(job->monitor); + pthread_mutex_unlock(&(job->monitor)); return NS_INVALID_STATE; } } +ns_result_t +ns_job_wait(struct ns_job_t *job) { + PR_ASSERT(job); + pthread_mutex_lock(&(job->monitor)); + if (job->state == NS_JOB_WAITING) { + /* It's done */ + pthread_mutex_unlock(&(job->monitor)); + return NS_SUCCESS; + } else { + pthread_cond_wait(&(job->notify), &(job->monitor)); + ns_job_state_t result = job->state; + pthread_mutex_unlock(&(job->monitor)); + if (result == NS_JOB_WAITING) { + return NS_SUCCESS; + } else if (result == NS_JOB_NEEDS_DELETE) { + return NS_DELETING; + } else { + PR_ASSERT(1 == 0); + return NS_INVALID_STATE; + } + } +} /* * This is a convenience function - use if you need to re-arm the same event @@ -1173,7 +1206,7 @@ ns_result_t ns_job_rearm(ns_job_t *job) { PR_ASSERT(job); - pthread_mutex_lock(job->monitor); + pthread_mutex_lock(&(job->monitor)); PR_ASSERT(job->state == NS_JOB_WAITING || job->state == NS_JOB_RUNNING); if (ns_thrpool_is_shutdown(job->tp)) { @@ -1186,7 +1219,7 @@ ns_job_rearm(ns_job_t *job) #endif job->state = NS_JOB_NEEDS_ARM; internal_ns_job_rearm(job); - pthread_mutex_unlock(job->monitor); + pthread_mutex_unlock(&(job->monitor)); return NS_SUCCESS; } else if (!NS_JOB_IS_PERSIST(job->job_type) && job->state == NS_JOB_RUNNING) { /* For this to be called, and NS_JOB_RUNNING, we *must* be the callback thread! */ @@ -1195,10 +1228,10 @@ ns_job_rearm(ns_job_t *job) ns_log(LOG_DEBUG, "ns_rearm_job %x state %d setting NS_JOB_NEEDS_ARM\n", job, job->state); #endif job->state = NS_JOB_NEEDS_ARM; - pthread_mutex_unlock(job->monitor); + pthread_mutex_unlock(&(job->monitor)); return NS_SUCCESS; } else { - pthread_mutex_unlock(job->monitor); + pthread_mutex_unlock(&(job->monitor)); return NS_INVALID_STATE; } /* Unreachable code .... */ @@ -1254,7 +1287,7 @@ setup_event_q_wakeup(ns_thrpool_t *tp) NS_JOB_READ | NS_JOB_PERSIST | NS_JOB_PRESERVE_FD, wakeup_cb, NULL); - pthread_mutex_lock(job->monitor); + pthread_mutex_lock(&(job->monitor)); /* The event_queue wakeup is ready, arm it. */ #ifdef DEBUG @@ -1267,7 +1300,7 @@ setup_event_q_wakeup(ns_thrpool_t *tp) /* Stash the wakeup job in tp so we can release it later. */ tp->event_q_wakeup_job = job; - pthread_mutex_unlock(job->monitor); + pthread_mutex_unlock(&(job->monitor)); } /* Initialize the thrpool config */ @@ -1463,7 +1496,7 @@ ns_thrpool_destroy(struct ns_thrpool_t *tp) * and use it to wake up the event loop. */ - pthread_mutex_lock(tp->event_q_wakeup_job->monitor); + pthread_mutex_lock(&(tp->event_q_wakeup_job->monitor)); // tp->event_q_wakeup_job->job_type |= NS_JOB_THREAD; /* This triggers the job to "run", which will cause a shutdown cascade */ @@ -1471,7 +1504,7 @@ ns_thrpool_destroy(struct ns_thrpool_t *tp) ns_log(LOG_DEBUG, "ns_thrpool_destroy %x state %d moving to NS_JOB_NEEDS_DELETE\n", tp->event_q_wakeup_job, tp->event_q_wakeup_job->state); #endif tp->event_q_wakeup_job->state = NS_JOB_NEEDS_DELETE; - pthread_mutex_unlock(tp->event_q_wakeup_job->monitor); + pthread_mutex_unlock(&(tp->event_q_wakeup_job->monitor)); /* Has to be event_q_notify, not internal_job_done */ event_q_notify(tp->event_q_wakeup_job); diff --git a/src/nunc-stans/test/test_nuncstans.c b/src/nunc-stans/test/test_nuncstans.c index 629377a89..afe3c02fc 100644 --- a/src/nunc-stans/test/test_nuncstans.c +++ b/src/nunc-stans/test/test_nuncstans.c @@ -55,14 +55,21 @@ /* We need the internal headers for state checks */ #include "../ns/ns_event_fw.h" +#include <assert.h> + +#include <time.h> + #ifdef HAVE_STDLIB_H #include <stdlib.h> #endif static int cb_check = 0; -static PRLock *cb_lock = NULL; -static PRCondVar *cb_cond = NULL; + +static pthread_mutex_t cb_lock; +static pthread_cond_t cb_cond; +// static PRLock *cb_lock = NULL; +// static PRCondVar *cb_cond = NULL; void ns_test_logger(int priority __attribute__((unused)), const char *fmt, va_list varg) @@ -71,6 +78,19 @@ ns_test_logger(int priority __attribute__((unused)), const char *fmt, va_list va vprintf(fmt, varg); } +static int +cond_wait_rel(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex, const struct timespec *restrict reltime) { + struct timespec now; + struct timespec abswait; + + clock_gettime(CLOCK_REALTIME, &now); + + abswait.tv_sec = now.tv_sec + reltime->tv_sec; + abswait.tv_nsec = now.tv_nsec + reltime->tv_nsec; + + return pthread_cond_timedwait(cond, mutex, &abswait); +} + /* All our other tests will use this in some form. */ static int ns_test_setup(void **state) @@ -81,8 +101,8 @@ ns_test_setup(void **state) /* Reset the callback check */ cb_check = 0; /* Create the cond var the CB check will use. */ - cb_lock = PR_NewLock(); - cb_cond = PR_NewCondVar(cb_lock); + assert(pthread_mutex_init(&cb_lock, NULL) == 0); + assert(pthread_cond_init(&cb_cond, NULL) == 0); ns_thrpool_config_init(&ns_config); @@ -105,8 +125,8 @@ ns_test_teardown(void **state) ns_thrpool_destroy(tp); - PR_DestroyCondVar(cb_cond); - PR_DestroyLock(cb_lock); + pthread_cond_destroy(&cb_cond); + pthread_mutex_destroy(&cb_lock); return 0; } @@ -114,24 +134,23 @@ ns_test_teardown(void **state) static void ns_init_test_job_cb(struct ns_job_t *job __attribute__((unused))) { + pthread_mutex_lock(&cb_lock); cb_check += 1; - PR_Lock(cb_lock); - PR_NotifyCondVar(cb_cond); - PR_Unlock(cb_lock); + pthread_cond_signal(&cb_cond); + pthread_mutex_unlock(&cb_lock); } static void ns_init_disarm_job_cb(struct ns_job_t *job) { if (ns_job_done(job) == NS_SUCCESS) { + pthread_mutex_lock(&cb_lock); cb_check = 1; + pthread_cond_signal(&cb_cond); + pthread_mutex_unlock(&cb_lock); } else { assert_int_equal(1, 0); } - PR_Lock(cb_lock); - PR_NotifyCondVar(cb_cond); - /* Disarm ourselves */ - PR_Unlock(cb_lock); } static void @@ -146,20 +165,20 @@ ns_init_test(void **state) { struct ns_thrpool_t *tp = *state; struct ns_job_t *job = NULL; + struct timespec timeout = {1, 0}; - PR_Lock(cb_lock); + pthread_mutex_lock(&cb_lock); assert_int_equal( ns_add_job(tp, NS_JOB_NONE | NS_JOB_THREAD, ns_init_test_job_cb, NULL, &job), 0); - PR_WaitCondVar(cb_cond, PR_SecondsToInterval(1)); - PR_Unlock(cb_lock); + assert(cond_wait_rel(&cb_cond, &cb_lock, &timeout) == 0); + pthread_mutex_unlock(&cb_lock); assert_int_equal(cb_check, 1); /* Once the job is done, it's not in the event queue, and it's complete */ - /* We have to stall momentarily to let the work_job_execute release the job to us */ - PR_Sleep(PR_SecondsToInterval(1)); + assert(ns_job_wait(job) == NS_SUCCESS); assert_int_equal(ns_job_done(job), NS_SUCCESS); } @@ -169,19 +188,20 @@ ns_set_data_test(void **state) /* Add a job with data */ struct ns_thrpool_t *tp = *state; struct ns_job_t *job = NULL; + struct timespec timeout = {1, 0}; char *data = malloc(6); strcpy(data, "first"); - PR_Lock(cb_lock); + pthread_mutex_lock(&cb_lock); assert_int_equal( ns_add_job(tp, NS_JOB_NONE | NS_JOB_THREAD, ns_init_test_job_cb, data, &job), NS_SUCCESS); /* Let the job run */ - PR_WaitCondVar(cb_cond, PR_SecondsToInterval(1)); - PR_Unlock(cb_lock); + assert(cond_wait_rel(&cb_cond, &cb_lock, &timeout) == 0); + pthread_mutex_unlock(&cb_lock); /* Check that the data is correct */ char *retrieved = (char *)ns_job_get_data(job); @@ -193,16 +213,14 @@ ns_set_data_test(void **state) data = malloc(7); strcpy(data, "second"); - while (job->state != NS_JOB_WAITING) { - PR_Sleep(PR_MillisecondsToInterval(50)); - } + assert(ns_job_wait(job) == NS_SUCCESS); ns_job_set_data(job, data); /* Rearm, and let it run again. */ - PR_Lock(cb_lock); + pthread_mutex_lock(&cb_lock); ns_job_rearm(job); - PR_WaitCondVar(cb_cond, PR_SecondsToInterval(1)); - PR_Unlock(cb_lock); + assert(cond_wait_rel(&cb_cond, &cb_lock, &timeout) == 0); + pthread_mutex_unlock(&cb_lock); /* Make sure it's now what we expect */ retrieved = (char *)ns_job_get_data(job); @@ -218,9 +236,7 @@ ns_set_data_test(void **state) * waiting. we might need a load barrier here ... */ - while (job->state != NS_JOB_WAITING) { - PR_Sleep(PR_MillisecondsToInterval(50)); - } + assert(ns_job_wait(job) == NS_SUCCESS); assert_int_equal(ns_job_done(job), NS_SUCCESS); } @@ -230,8 +246,9 @@ ns_job_done_cb_test(void **state) { struct ns_thrpool_t *tp = *state; struct ns_job_t *job = NULL; + struct timespec timeout = {1, 0}; - PR_Lock(cb_lock); + pthread_mutex_lock(&cb_lock); assert_int_equal( ns_create_job(tp, NS_JOB_NONE | NS_JOB_THREAD, ns_init_do_nothing_cb, &job), NS_SUCCESS); @@ -240,8 +257,8 @@ ns_job_done_cb_test(void **state) /* Remove it */ assert_int_equal(ns_job_done(job), NS_SUCCESS); - PR_WaitCondVar(cb_cond, PR_SecondsToInterval(1)); - PR_Unlock(cb_lock); + assert(cond_wait_rel(&cb_cond, &cb_lock, &timeout) == 0); + pthread_mutex_unlock(&cb_lock); assert_int_equal(cb_check, 1); } @@ -250,16 +267,15 @@ static void ns_init_rearm_job_cb(struct ns_job_t *job) { if (ns_job_rearm(job) != NS_SUCCESS) { + pthread_mutex_lock(&cb_lock); cb_check = 1; /* we failed to re-arm as expected, let's go away ... */ assert_int_equal(ns_job_done(job), NS_SUCCESS); + pthread_cond_signal(&cb_cond); + pthread_mutex_unlock(&cb_lock); } else { assert_int_equal(1, 0); } - PR_Lock(cb_lock); - PR_NotifyCondVar(cb_cond); - /* Disarm ourselves */ - PR_Unlock(cb_lock); } static void @@ -268,8 +284,9 @@ ns_job_persist_rearm_ignore_test(void **state) /* Test that rearm ignores the persistent job. */ struct ns_thrpool_t *tp = *state; struct ns_job_t *job = NULL; + struct timespec timeout = {1, 0}; - PR_Lock(cb_lock); + pthread_mutex_lock(&cb_lock); assert_int_equal( ns_create_job(tp, NS_JOB_NONE | NS_JOB_THREAD | NS_JOB_PERSIST, ns_init_rearm_job_cb, &job), NS_SUCCESS); @@ -281,8 +298,8 @@ ns_job_persist_rearm_ignore_test(void **state) * should see only 1 in the cb_check. */ - PR_WaitCondVar(cb_cond, PR_SecondsToInterval(1)); - PR_Unlock(cb_lock); + assert(cond_wait_rel(&cb_cond, &cb_lock, &timeout) == 0); + pthread_mutex_unlock(&cb_lock); /* If we fail to rearm, this is set to 1 Which is what we want. */ assert_int_equal(cb_check, 1); @@ -294,6 +311,7 @@ ns_job_persist_disarm_test(void **state) /* Make a persistent job */ struct ns_thrpool_t *tp = *state; struct ns_job_t *job = NULL; + struct timespec timeout = {2, 0}; assert_int_equal( ns_create_job(tp, NS_JOB_NONE | NS_JOB_PERSIST, ns_init_disarm_job_cb, &job), @@ -302,9 +320,9 @@ ns_job_persist_disarm_test(void **state) assert_int_equal(ns_job_rearm(job), NS_SUCCESS); /* In the callback it should disarm */ - PR_Lock(cb_lock); - PR_WaitCondVar(cb_cond, PR_SecondsToInterval(1)); - PR_Unlock(cb_lock); + pthread_mutex_lock(&cb_lock); + assert(cond_wait_rel(&cb_cond, &cb_lock, &timeout) == 0); + pthread_mutex_unlock(&cb_lock); /* Make sure it did */ assert_int_equal(cb_check, 1); } @@ -329,14 +347,13 @@ ns_job_persist_disarm_test(void **state) static void ns_init_race_done_job_cb(struct ns_job_t *job) { - cb_check += 1; ns_job_done(job); /* We need to sleep to let the job race happen */ PR_Sleep(PR_SecondsToInterval(2)); - PR_Lock(cb_lock); - PR_NotifyCondVar(cb_cond); - /* Disarm ourselves */ - PR_Unlock(cb_lock); + pthread_mutex_lock(&cb_lock); + cb_check += 1; + pthread_cond_signal(&cb_cond); + pthread_mutex_unlock(&cb_lock); } static void @@ -344,14 +361,15 @@ ns_job_race_done_test(void **state) { struct ns_thrpool_t *tp = *state; struct ns_job_t *job = NULL; + struct timespec timeout = {5, 0}; - PR_Lock(cb_lock); + pthread_mutex_lock(&cb_lock); assert_int_equal( ns_add_job(tp, NS_JOB_NONE | NS_JOB_THREAD, ns_init_race_done_job_cb, NULL, &job), NS_SUCCESS); - PR_WaitCondVar(cb_cond, PR_SecondsToInterval(5)); - PR_Unlock(cb_lock); + assert(cond_wait_rel(&cb_cond, &cb_lock, &timeout) == 0); + pthread_mutex_unlock(&cb_lock); assert_int_equal(cb_check, 1); } @@ -365,8 +383,9 @@ ns_job_signal_cb_test(void **state) { struct ns_thrpool_t *tp = *state; struct ns_job_t *job = NULL; + struct timespec timeout = {1, 0}; - PR_Lock(cb_lock); + pthread_mutex_lock(&cb_lock); assert_int_equal( ns_add_signal_job(tp, SIGUSR1, NS_JOB_SIGNAL, ns_init_test_job_cb, NULL, &job), NS_SUCCESS); @@ -376,8 +395,8 @@ ns_job_signal_cb_test(void **state) /* Send the signal ... */ raise(SIGUSR1); - PR_WaitCondVar(cb_cond, PR_SecondsToInterval(1)); - PR_Unlock(cb_lock); + assert(cond_wait_rel(&cb_cond, &cb_lock, &timeout) == 0); + pthread_mutex_unlock(&cb_lock); assert_int_equal(cb_check, 1); @@ -408,12 +427,11 @@ ns_job_neg_timeout_test(void **state) static void ns_timer_job_cb(struct ns_job_t *job) { - cb_check += 1; ns_job_done(job); - PR_Lock(cb_lock); - PR_NotifyCondVar(cb_cond); - /* Disarm ourselves */ - PR_Unlock(cb_lock); + pthread_mutex_lock(&cb_lock); + cb_check += 1; + pthread_cond_signal(&cb_cond); + pthread_mutex_unlock(&cb_lock); } static void @@ -421,16 +439,19 @@ ns_job_timer_test(void **state) { struct ns_thrpool_t *tp = *state; struct ns_job_t *job = NULL; - struct timeval tv = {2, 0}; + struct timeval tv = {3, 0}; + struct timespec timeout = {2, 0}; - PR_Lock(cb_lock); + pthread_mutex_lock(&cb_lock); assert_true(ns_add_timeout_job(tp, &tv, NS_JOB_THREAD, ns_timer_job_cb, NULL, &job) == NS_SUCCESS); - PR_WaitCondVar(cb_cond, PR_SecondsToInterval(1)); + cond_wait_rel(&cb_cond, &cb_lock, &timeout); + // pthread_mutex_unlock(&cb_lock); assert_int_equal(cb_check, 0); - PR_WaitCondVar(cb_cond, PR_SecondsToInterval(2)); - PR_Unlock(cb_lock); + // pthread_mutex_lock(&cb_lock); + cond_wait_rel(&cb_cond, &cb_lock, &timeout); + pthread_mutex_unlock(&cb_lock); assert_int_equal(cb_check, 1); } @@ -441,7 +462,9 @@ ns_job_timer_test(void **state) static void ns_timer_persist_job_cb(struct ns_job_t *job) { + pthread_mutex_lock(&cb_lock); cb_check += 1; + pthread_mutex_unlock(&cb_lock); if (cb_check < 10) { ns_job_rearm(job); } else { @@ -456,16 +479,19 @@ ns_job_timer_persist_test(void **state) struct ns_job_t *job = NULL; struct timeval tv = {1, 0}; - PR_Lock(cb_lock); assert_true(ns_add_timeout_job(tp, &tv, NS_JOB_THREAD, ns_timer_persist_job_cb, NULL, &job) == NS_SUCCESS); PR_Sleep(PR_SecondsToInterval(5)); + pthread_mutex_lock(&cb_lock); assert_true(cb_check <= 6); + pthread_mutex_unlock(&cb_lock); PR_Sleep(PR_SecondsToInterval(6)); + pthread_mutex_lock(&cb_lock); assert_int_equal(cb_check, 10); + pthread_mutex_unlock(&cb_lock); } int
0
389190a52e2281092e009010d33441c4ad6a9617
389ds/389-ds-base
Ticket 49369 - merge svrcore into 389-ds-base Bug Description: In order to keep our project simple and clear it's a good idea to keep our dependencies together. As the only consumers and maintainers of svrcore, we shouldmake it part of our project! Fix Description: Merge svrcore and it's history to 389-ds-base https://pagure.io/389-ds-base/issue/49369 Author: wibrown Review by: ???
commit 389190a52e2281092e009010d33441c4ad6a9617 Author: William Brown <[email protected]> Date: Wed Feb 28 08:59:46 2018 +1000 Ticket 49369 - merge svrcore into 389-ds-base Bug Description: In order to keep our project simple and clear it's a good idea to keep our dependencies together. As the only consumers and maintainers of svrcore, we shouldmake it part of our project! Fix Description: Merge svrcore and it's history to 389-ds-base https://pagure.io/389-ds-base/issue/49369 Author: wibrown Review by: ??? diff --git a/Makefile.am b/Makefile.am index a47201a54..9ba52b9bd 100644 --- a/Makefile.am +++ b/Makefile.am @@ -26,7 +26,6 @@ CMOCKA_INCLUDES = @cmocka_inc@ PROFILING_DEFINES = @profiling_defs@ NSPR_INCLUDES = @nspr_inc@ -SVRCORE_INCLUDES = @svrcore_inc@ SASL_INCLUDES = @sasl_inc@ EVENT_INCLUDES = @event_inc@ @@ -70,6 +69,8 @@ endif NUNCSTANS_INCLUDES = -I$(srcdir)/src/nunc-stans/include/ NUNC_STANS_ON = 1 +SVRCORE_INCLUDES = -I$(srcdir)/src/svrcore/src/ + # the -U undefines these symbols - should use the corresponding DS_ ones instead - see configure.ac DS_DEFINES = -DBUILD_NUM=$(BUILDNUM) -DVENDOR="\"$(vendor)\"" -DBRAND="\"$(brand)\"" -DCAPBRAND="\"$(capbrand)\"" \ -UPACKAGE_VERSION -UPACKAGE_TARNAME -UPACKAGE_STRING -UPACKAGE_BUGREPORT @@ -142,7 +143,6 @@ ldaplib_defs = @ldaplib_defs@ DB_LINK = @db_lib@ -ldb-@db_libver@ SASL_LINK = @sasl_lib@ -lsasl2 -SVRCORE_LINK = @svrcore_lib@ -lsvrcore ICU_LINK = @icu_lib@ -licui18n -licuuc -licudata PCRE_LINK = @pcre_lib@ -lpcre NETSNMP_LINK = @netsnmp_lib@ @netsnmp_link@ @@ -331,6 +331,7 @@ bin_PROGRAMS = dbscan \ server_LTLIBRARIES = libsds.la libnunc-stans.la libldaputil.la libslapd.la libns-dshttpd.la +lib_LTLIBRARIES = libsvrcore.la # this is how to add optional plugins if enable_pam_passthru @@ -934,7 +935,8 @@ cockpitcss_DATA = src/cockpit/389-console/css/ds.css \ pkgconfig_DATA = src/pkgconfig/dirsrv.pc \ src/pkgconfig/libsds.pc \ - src/pkgconfig/nunc-stans.pc + src/pkgconfig/nunc-stans.pc \ + src/pkgconfig/svrcore.pc #------------------------ # header files @@ -946,6 +948,8 @@ serverinc_HEADERS = ldap/servers/plugins/replication/repl-session-plugin.h \ src/nunc-stans/include/nunc-stans.h \ src/libsds/include/sds.h +include_HEADERS = src/svrcore/src/svrcore.h + #------------------------ # man pages #------------------------ @@ -1117,6 +1121,26 @@ libldaputil_la_LDFLAGS = $(AM_LDFLAGS) # #//////////////////////////////////////////////////////////////// +#------------------------ +# libsvrcore +#------------------------ +libsvrcore_la_SOURCES = \ + src/svrcore/src/alt.c \ + src/svrcore/src/cache.c \ + src/svrcore/src/errors.c \ + src/svrcore/src/file.c \ + src/svrcore/src/ntgetpin.c \ + src/svrcore/src/ntresource.h \ + src/svrcore/src/pin.c \ + src/svrcore/src/pk11.c \ + src/svrcore/src/std.c \ + src/svrcore/src/systemd-ask-pass.c \ + src/svrcore/src/std-systemd.c \ + src/svrcore/src/user.c + +libsvrcore_la_LDFLAGS = $(AM_LDFLAGS) +libsvrcore_la_CPPFLAGS = $(AM_CPPFLAGS) $(SVRCORE_INCLUDES) $(DSPLUGIN_CPPFLAGS) + #------------------------ # libsds #------------------------ @@ -1363,8 +1387,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@ $(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_CPPFLAGS = $(AM_CPPFLAGS) $(DSPLUGIN_CPPFLAGS) $(SASL_INCLUDES) @db_inc@ @kerberos_inc@ @pcre_inc@ $(SDS_CPPFLAGS) $(SVRCORE_INCLUDES) +libslapd_la_LIBADD = $(LDAPSDK_LINK) $(SASL_LINK) $(NSS_LINK) $(NSPR_LINK) $(KERBEROS_LINK) $(PCRE_LINK) $(THREADLIB) $(SYSTEMD_LINK) libsds.la libsvrcore.la libslapd_la_LDFLAGS = $(AM_LDFLAGS) $(SLAPD_LDFLAGS) @@ -1616,7 +1640,7 @@ libpbe_plugin_la_SOURCES = ldap/servers/plugins/rever/pbe.c \ ldap/servers/plugins/rever/rever.c libpbe_plugin_la_CPPFLAGS = $(AM_CPPFLAGS) $(DSPLUGIN_CPPFLAGS) $(SVRCORE_INCLUDES) -libpbe_plugin_la_LIBADD = libslapd.la $(NSS_LINK) +libpbe_plugin_la_LIBADD = libslapd.la libsvrcore.la $(NSS_LINK) libpbe_plugin_la_DEPENDENCIES = libslapd.la libpbe_plugin_la_LDFLAGS = -avoid-version @@ -2006,7 +2030,7 @@ ldif_LDADD = $(NSPR_LINK) $(NSS_LINK) $(LDAPSDK_LINK_NOTHR) $(SASL_LINK) migratecred_SOURCES = ldap/servers/slapd/tools/migratecred.c migratecred_CPPFLAGS = $(AM_CPPFLAGS) $(DSPLUGIN_CPPFLAGS) -migratecred_LDADD = libslapd.la $(NSPR_LINK) $(NSS_LINK) $(SVRCORE_LINK) $(LDAPSDK_LINK) $(SASL_LINK) +migratecred_LDADD = libslapd.la libsvrcore.la $(NSPR_LINK) $(NSS_LINK) $(LDAPSDK_LINK) $(SASL_LINK) migratecred_DEPENDENCIES = libslapd.la #------------------------ @@ -2015,7 +2039,7 @@ migratecred_DEPENDENCIES = libslapd.la mmldif_SOURCES = ldap/servers/slapd/tools/mmldif.c mmldif_CPPFLAGS = $(AM_CPPFLAGS) $(DSPLUGIN_CPPFLAGS) -mmldif_LDADD = libslapd.la $(NSPR_LINK) $(NSS_LINK) $(SVRCORE_LINK) $(LDAPSDK_LINK_NOTHR) $(SASL_LINK) +mmldif_LDADD = libslapd.la libsvrcore.la $(NSPR_LINK) $(NSS_LINK) $(LDAPSDK_LINK_NOTHR) $(SASL_LINK) mmldif_DEPENDENCIES = libslapd.la #------------------------ @@ -2067,8 +2091,8 @@ ns_slapd_SOURCES = ldap/servers/slapd/abandon.c \ $(GETSOCKETPEER) ns_slapd_CPPFLAGS = $(AM_CPPFLAGS) $(DSPLUGIN_CPPFLAGS) $(SASL_INCLUDES) $(SVRCORE_INCLUDES) -ns_slapd_LDADD = libnunc-stans.la libslapd.la libldaputil.la $(LDAPSDK_LINK) $(NSS_LINK) $(LIBADD_DL) \ - $(NSPR_LINK) $(SASL_LINK) $(SVRCORE_LINK) $(LIBNSL) $(LIBSOCKET) $(THREADLIB) $(SYSTEMD_LINK) $(EVENT_LINK) +ns_slapd_LDADD = libnunc-stans.la libslapd.la libldaputil.la libsvrcore.la $(LDAPSDK_LINK) $(NSS_LINK) $(LIBADD_DL) \ + $(NSPR_LINK) $(SASL_LINK) $(LIBNSL) $(LIBSOCKET) $(THREADLIB) $(SYSTEMD_LINK) $(EVENT_LINK) ns_slapd_DEPENDENCIES = libslapd.la libnunc-stans.la # We need to link ns-slapd with the C++ compiler on HP-UX since we load # some C++ shared libraries (such as icu). @@ -2084,7 +2108,7 @@ endif pwdhash_SOURCES = ldap/servers/slapd/tools/pwenc.c pwdhash_CPPFLAGS = $(AM_CPPFLAGS) $(DSPLUGIN_CPPFLAGS) -pwdhash_LDADD = libslapd.la $(NSPR_LINK) $(NSS_LINK) $(SVRCORE_LINK) $(LDAPSDK_LINK) $(SASL_LINK) +pwdhash_LDADD = libslapd.la libsvrcore.la $(NSPR_LINK) $(NSS_LINK) $(LDAPSDK_LINK) $(SASL_LINK) pwdhash_DEPENDENCIES = libslapd.la #------------------------ @@ -2128,14 +2152,14 @@ test_slapd_SOURCES = test/main.c \ test/plugins/pwdstorage/pbkdf2.c # We need to link a lot of plugins for this test. -test_slapd_LDADD = libslapd.la \ +test_slapd_LDADD = libslapd.la \ libpwdstorage-plugin.la \ $(NSS_LINK) $(NSPR_LINK) test_slapd_LDFLAGS = $(AM_CPPFLAGS) $(CMOCKA_LINKS) ### WARNING: Slap.h needs cert.h, which requires the -I/lib/ldaputil!!! ### WARNING: Slap.h pulls ssl.h, which requires nss!!!! # We need to pull in plugin header paths too: -test_slapd_CPPFLAGS = $(AM_CPPFLAGS) $(DSPLUGIN_CPPFLAGS) $(DSINTERNAL_CPPFLAGS) \ +test_slapd_CPPFLAGS = $(AM_CPPFLAGS) $(DSPLUGIN_CPPFLAGS) $(DSINTERNAL_CPPFLAGS) \ -I$(srcdir)/ldap/servers/plugins/pwdstorage test_libsds_SOURCES = src/libsds/test/test_sds.c \ @@ -2388,7 +2412,7 @@ rpms: rpmbrprep srpm: rpmbrprep cd $(RPMBUILD); \ rpmbuild --define "_topdir $(RPMBUILD)" \ - -bs SPECS/389-ds-base.spec + -bs SPECS/389-ds-base.spec if HAVE_DOXYGEN diff --git a/configure.ac b/configure.ac index 0ed57e11d..8330542ff 100644 --- a/configure.ac +++ b/configure.ac @@ -802,7 +802,6 @@ m4_include(m4/openldap.m4) m4_include(m4/mozldap.m4) m4_include(m4/db.m4) m4_include(m4/sasl.m4) -m4_include(m4/svrcore.m4) m4_include(m4/icu.m4) m4_include(m4/netsnmp.m4) m4_include(m4/kerberos.m4) @@ -863,7 +862,7 @@ AC_DEFINE([LDAP_ERROR_LOGGING], [1], [LDAP error logging flag]) # AC_CONFIG_FILES([ldap/admin/src/defaults.inf]) -AC_CONFIG_FILES([src/pkgconfig/dirsrv.pc src/pkgconfig/nunc-stans.pc src/pkgconfig/libsds.pc]) +AC_CONFIG_FILES([src/pkgconfig/dirsrv.pc src/pkgconfig/nunc-stans.pc src/pkgconfig/libsds.pc src/pkgconfig/svrcore.pc]) AC_CONFIG_FILES([Makefile rpm/389-ds-base.spec ]) diff --git a/m4/svrcore.m4 b/m4/svrcore.m4 deleted file mode 100644 index f50f4a91a..000000000 --- a/m4/svrcore.m4 +++ /dev/null @@ -1,112 +0,0 @@ -# BEGIN COPYRIGHT BLOCK -# Copyright (C) 2007 Red Hat, Inc. -# All rights reserved. -# -# License: GPL (version 3 or any later version). -# See LICENSE for details. -# END COPYRIGHT BLOCK -# -# Configure paths for SVRCORE - -AC_CHECKING(for SVRCORE) - -AC_MSG_CHECKING(for --with-svrcore) -AC_ARG_WITH(svrcore, - AS_HELP_STRING([--with-svrcore@<:@=PATH@:>@],[Use system installed SVRCORE - optional path for SVRCORE]), - dnl = Look in the standard system locations - [ - if test "$withval" = "yes"; then - AC_MSG_RESULT(yes) - - elif test "$withval" = "no"; then - AC_MSG_RESULT(no) - AC_MSG_ERROR([SVRCORE is required.]) - - dnl = Check the user provided location - elif test -d "$withval" -a -d "$withval/lib" -a -d "$withval/include" ; then - AC_MSG_RESULT([using $withval]) - - if test -f "$withval/include/svrcore.h"; then - svrcore_inc="-I$withval/include" - else - AC_MSG_ERROR(svrcore.h not found) - fi - - svrcore_lib="-L$withval/lib" - else - AC_MSG_RESULT(yes) - AC_MSG_ERROR([SVRCORE not found in $withval]) - fi - ], - AC_MSG_RESULT(yes)) - -AC_MSG_CHECKING(for --with-svrcore-inc) -AC_ARG_WITH(svrcore-inc, - AS_HELP_STRING([--with-svrcore-inc=PATH],[SVRCORE include file directory]), - [ - if test -f "$withval"/svrcore.h; then - AC_MSG_RESULT([using $withval]) - svrcore_inc="-I$withval" - else - echo - AC_MSG_ERROR([$withval/svrcore.h not found]) - fi - ], - AC_MSG_RESULT(no)) - -AC_MSG_CHECKING(for --with-svrcore-lib) -AC_ARG_WITH(svrcore-lib, - AS_HELP_STRING([--with-svrcore-lib=PATH],[SVRCORE library directory]), - [ - if test -d "$withval"; then - AC_MSG_RESULT([using $withval]) - svrcore_lib="-L$withval" - else - echo - AC_MSG_ERROR([$withval not found]) - fi - ], - AC_MSG_RESULT(no)) - -dnl svrcore not given - look for pkg-config -if test -z "$svrcore_inc" -o -z "$svrcore_lib"; then - AC_PATH_PROG(PKG_CONFIG, pkg-config) - AC_MSG_CHECKING(for SVRCORE with pkg-config) - if test -n "$PKG_CONFIG"; then - if $PKG_CONFIG --exists svrcore; then - svrcore_inc=`$PKG_CONFIG --cflags-only-I svrcore` - svrcore_lib=`$PKG_CONFIG --libs-only-L svrcore` - AC_MSG_RESULT([using system svrcore]) - fi - fi -fi - -if test -z "$svrcore_inc" -o -z "$svrcore_lib"; then -dnl just see if SVRCORE is already a system library - AC_CHECK_LIB([svrcore], [SVRCORE_GetRegisteredPinObj], [havesvrcore=1], - [], [$nss_inc $nspr_inc $nss_lib -lnss3 -lsoftokn3 $nspr_lib -lplds4 -lplc4 -lnspr4]) - if test -n "$havesvrcore" ; then -dnl just see if SVRCORE is already a system header file - save_cppflags="$CPPFLAGS" - CPPFLAGS="$nss_inc $nspr_inc" - AC_CHECK_HEADER([svrcore.h], [havesvrcore=1], [havesvrcore=]) - CPPFLAGS="$save_cppflags" - fi -dnl for SVRCORE to be present, both the library and the header must exist - if test -z "$havesvrcore" ; then - AC_MSG_ERROR([SVRCORE not found, specify with --with-svrcore.]) - fi -fi - -dnl = Check for svrcore.h in the normal locations -if test -z "$svrcore_inc" -o -z "$svrcore_lib"; then - if test -f /usr/include/svrcore.h; then - svrcore_inc="-I/usr/include" - svrcore_lib="-L/usr/lib" - else - AC_MSG_ERROR([SVRCORE not found, specify with --with-svrcore.]) - fi -fi - -AC_SUBST(svrcore_inc) -AC_SUBST(svrcore_lib) diff --git a/rpm/389-ds-base.spec.in b/rpm/389-ds-base.spec.in index 7a93ee35b..ebe1bcd26 100644 --- a/rpm/389-ds-base.spec.in +++ b/rpm/389-ds-base.spec.in @@ -22,6 +22,9 @@ %global use_perl __PERL_ON__ +%define nspr_version 4.6 +%define nss_version 3.11 + %if %{use_asan} %global use_tcmalloc 0 %global variant base-asan @@ -64,7 +67,6 @@ Provides: ldif2ldbm # Attach the buildrequires to the top level package: BuildRequires: nspr-devel BuildRequires: nss-devel -BuildRequires: svrcore-devel >= 4.1.2 BuildRequires: openldap-devel BuildRequires: libdb-devel BuildRequires: cyrus-sasl-devel @@ -95,6 +97,8 @@ BuildRequires: libasan BuildRequires: cargo BuildRequires: rust %endif +BuildRequires: pkgconfig +BuildRequires: pkgconfig(systemd) # Needed to support regeneration of the autotool artifacts. BuildRequires: autoconf BuildRequires: automake @@ -180,6 +184,9 @@ Please see http://seclists.org/oss-sec/2016/q1/363 for more information. %package libs Summary: Core libraries for 389 Directory Server (%{variant}) Group: System Environment/Daemons +Provides: svrcore = 4.1.4 +Obsoletes: svrcore <= 4.1.3 +Conflicts: svrcore # You can work this out by running LDD on libslapd.so to see what it needs in # isolation. Requires: nss @@ -205,11 +212,13 @@ package to be installed with just the -libs package and without the main package %package devel Summary: Development libraries for 389 Directory Server (%{variant}) Group: Development/Libraries +Provides: svrcore-devel = 4.1.4 +Obsoletes: svrcore-devel <= 4.1.3 +Conflicts: svrcore-devel Requires: %{name}-libs = %{version}-%{release} Requires: pkgconfig Requires: nspr-devel Requires: nss-devel -Requires: svrcore-devel Requires: openldap-devel # systemd-libs contains the headers iirc. Requires: systemd-libs @@ -277,7 +286,7 @@ CLANG_FLAGS="--enable-clang" %{?with_tmpfiles_d: TMPFILES_FLAG="--with-tmpfiles-d=%{with_tmpfiles_d}"} # hack hack hack https://bugzilla.redhat.com/show_bug.cgi?id=833529 -NSSARGS="--with-svrcore-inc=%{_includedir} --with-svrcore-lib=%{_libdir} --with-nss-lib=%{_libdir} --with-nss-inc=%{_includedir}/nss3" +NSSARGS="--with-nss-lib=%{_libdir} --with-nss-inc=%{_includedir}/nss3" %if %{use_asan} && !%{use_rust} ASAN_FLAGS="--enable-asan --enable-debug" @@ -354,6 +363,8 @@ rm -f $RPM_BUILD_ROOT%{_libdir}/%{pkgname}/*.a rm -f $RPM_BUILD_ROOT%{_libdir}/%{pkgname}/*.la rm -f $RPM_BUILD_ROOT%{_libdir}/%{pkgname}/plugins/*.a rm -f $RPM_BUILD_ROOT%{_libdir}/%{pkgname}/plugins/*.la +rm -f $RPM_BUILD_ROOT%{_libdir}/libsvrcore.a +rm -f $RPM_BUILD_ROOT%{_libdir}/libsvrcore.la %if %{use_perl} @@ -564,18 +575,24 @@ fi %defattr(-,root,root,-) %doc LICENSE LICENSE.GPLv3+ LICENSE.openssl README.devel %{_mandir}/man3/* +%{_includedir}/svrcore.h %{_includedir}/%{pkgname} +%{_libdir}/libsvrcore.so %{_libdir}/%{pkgname}/libslapd.so %{_libdir}/%{pkgname}/libns-dshttpd.so %{_libdir}/%{pkgname}/libnunc-stans.so %{_libdir}/%{pkgname}/libsds.so %{_libdir}/%{pkgname}/libldaputil.so -%{_libdir}/pkgconfig/* +%{_libdir}/pkgconfig/svrcore.pc +%{_libdir}/pkgconfig/dirsrv.pc +%{_libdir}/pkgconfig/libsds.pc +%{_libdir}/pkgconfig/nunc-stans.pc %files libs %defattr(-,root,root,-) %doc LICENSE LICENSE.GPLv3+ LICENSE.openssl README.devel %dir %{_libdir}/%{pkgname} +%{_libdir}/libsvrcore.so.* %{_libdir}/%{pkgname}/libslapd.so.* %{_libdir}/%{pkgname}/libns-dshttpd-*.so %{_libdir}/%{pkgname}/libnunc-stans.so.* diff --git a/src/svrcore/svrcore.pc.in b/src/pkgconfig/svrcore.pc.in similarity index 68% rename from src/svrcore/svrcore.pc.in rename to src/pkgconfig/svrcore.pc.in index a54aeffb9..b09d62944 100644 --- a/src/svrcore/svrcore.pc.in +++ b/src/pkgconfig/svrcore.pc.in @@ -5,7 +5,7 @@ includedir=@includedir@ Name: svrcore Description: Svrcore - Secure PIN handling using NSS crypto -Version: @VERSION@ -Requires: @NSPR_NAME@ >= @NSPR_MIN_VER@ , @NSS_NAME@ >= @NSS_MIN_VER@ +Version: @PACKAGE_VERSION@ +Requires: nspr, nss Libs: -lsvrcore Cflags: -I${includedir}
0
d5c5097b9cb6dcbba4b48a758dc1f31bd8565fae
389ds/389-ds-base
Issue 4389 - errors log with incorrectly formatted message parent_update_on_childchange Description: The arguemtns were incorrect for the logging line Fixes: https://github.com/389ds/389-ds-base/issues/4389 Reviewed by: mreynolds(one line commit rule)
commit d5c5097b9cb6dcbba4b48a758dc1f31bd8565fae Author: Mark Reynolds <[email protected]> Date: Tue Oct 20 14:53:01 2020 -0400 Issue 4389 - errors log with incorrectly formatted message parent_update_on_childchange Description: The arguemtns were incorrect for the logging line Fixes: https://github.com/389ds/389-ds-base/issues/4389 Reviewed by: mreynolds(one line commit rule) diff --git a/ldap/servers/slapd/back-ldbm/parents.c b/ldap/servers/slapd/back-ldbm/parents.c index 4583885f1..31107591e 100644 --- a/ldap/servers/slapd/back-ldbm/parents.c +++ b/ldap/servers/slapd/back-ldbm/parents.c @@ -103,8 +103,8 @@ parent_update_on_childchange(modify_context *mc, int op, size_t *new_sub_count) if (!already_present) { /* This means that there was a conflict. Before coming to this point, * the entry to be deleted was deleted... */ - slapi_log_err(SLAPI_LOG_ERR, "parent_update_on_childchange - " - "Parent %s has no children. (op 0x%x, repl_op 0x%x)\n", + slapi_log_err(SLAPI_LOG_ERR, "parent_update_on_childchange", + "Parent %s has no children. (op 0x%x, repl_op 0x%x)\n", slapi_entry_get_dn(mc->old_entry->ep_entry), op, repl_op); slapi_mods_free(&smods); return -1;
0
02d23f06d21576a3e4919dcabe6901840e05e500
389ds/389-ds-base
Ticket - 49623-cont cenotaph errors on modrdn operations Bug: In modrdn operations a cenotaph entries are created to track the time when an entry had existed. But in cases where rentries were renamed in cycles reusing the dns again and again this failed with an error: "faild to add cenotaph" Fix: Previous versions of cenotaphs with the same dn are not used (or maybe in very unlikely scenarios) so there is no need to change the dn construction to be able to keep all versions of the same cenotaph. Instead, if the creation of the cenotaph fails because it already exists, the existin cenotaph is moodified with the lifespan data of the cenotaph that was tried to add. Reviewed by: Thierry, thanks
commit 02d23f06d21576a3e4919dcabe6901840e05e500 Author: Ludwig Krispenz <[email protected]> Date: Tue Feb 11 09:47:45 2020 +0100 Ticket - 49623-cont cenotaph errors on modrdn operations Bug: In modrdn operations a cenotaph entries are created to track the time when an entry had existed. But in cases where rentries were renamed in cycles reusing the dns again and again this failed with an error: "faild to add cenotaph" Fix: Previous versions of cenotaphs with the same dn are not used (or maybe in very unlikely scenarios) so there is no need to change the dn construction to be able to keep all versions of the same cenotaph. Instead, if the creation of the cenotaph fails because it already exists, the existin cenotaph is moodified with the lifespan data of the cenotaph that was tried to add. Reviewed by: Thierry, thanks diff --git a/dirsrvtests/tests/tickets/ticket49623_2_test.py b/dirsrvtests/tests/tickets/ticket49623_2_test.py new file mode 100644 index 000000000..1d3167d49 --- /dev/null +++ b/dirsrvtests/tests/tickets/ticket49623_2_test.py @@ -0,0 +1,66 @@ +# --- BEGIN COPYRIGHT BLOCK --- +# Copyright (C) 2020 Red Hat, Inc. +# All rights reserved. +# +# License: GPL (version 3 or any later version). +# See LICENSE for details. +# --- END COPYRIGHT BLOCK --- +# +import os +import ldap +import pytest +import subprocess +from lib389.tasks import * +from lib389.utils import * +from lib389.topologies import topology_m1 +from lib389.idm.user import UserAccounts +from lib389._constants import DEFAULT_SUFFIX +from contextlib import contextmanager + +pytestmark = pytest.mark.tier1 + +logging.getLogger(__name__).setLevel(logging.DEBUG) +log = logging.getLogger(__name__) + + [email protected] [email protected] +def test_modrdn_loop(topology_m1): + """Test that renaming the same entry multiple times reusing the same + RDN multiple times does not result in cenotaph error messages + + :id: 631b2be9-5c03-44c7-9853-a87c923d5b30 + + :setup: Single master instance + + :steps: 1. Add an entry with RDN start rdn + 2. Rename the entry to rdn change + 3. Rename the entry to start again + 4. Rename the entry to rdn change + 5. check for cenotaph error messages + :expectedresults: + 1. No error messages + """ + + topo = topology_m1.ms['master1'] + TEST_ENTRY_RDN_START = 'start' + TEST_ENTRY_RDN_CHANGE = 'change' + TEST_ENTRY_NAME = 'tuser' + users = UserAccounts(topo, DEFAULT_SUFFIX) + user_properties = { + 'uid': TEST_ENTRY_RDN_START, + 'cn': TEST_ENTRY_NAME, + 'sn': TEST_ENTRY_NAME, + 'uidNumber': '1001', + 'gidNumber': '2001', + 'homeDirectory': '/home/{}'.format(TEST_ENTRY_NAME) + } + + tuser = users.create(properties=user_properties) + tuser.rename('uid={}'.format(TEST_ENTRY_RDN_CHANGE), newsuperior=None, deloldrdn=True) + tuser.rename('uid={}'.format(TEST_ENTRY_RDN_START), newsuperior=None, deloldrdn=True) + tuser.rename('uid={}'.format(TEST_ENTRY_RDN_CHANGE), newsuperior=None, deloldrdn=True) + + log.info("Check the log messages for cenotaph error") + error_msg = ".*urp_fixup_add_cenotaph - failed to add cenotaph, err= 68" + assert not topo.ds_error_log.match(error_msg) diff --git a/ldap/servers/plugins/replication/urp.c b/ldap/servers/plugins/replication/urp.c index d0a486d05..79a817c90 100644 --- a/ldap/servers/plugins/replication/urp.c +++ b/ldap/servers/plugins/replication/urp.c @@ -852,7 +852,7 @@ urp_post_delete_operation(Slapi_PBlock *pb) } static int -urp_fixup_add_cenotaph (Slapi_PBlock *pb, char *sessionid, CSN *opcsn) +urp_fixup_add_cenotaph(Slapi_PBlock *pb, char *sessionid, CSN *opcsn) { Slapi_PBlock *add_pb; Slapi_Entry *cenotaph = NULL; @@ -890,7 +890,7 @@ urp_fixup_add_cenotaph (Slapi_PBlock *pb, char *sessionid, CSN *opcsn) /* slapi_sdn_free(&pre_sdn); */ cenotaph = slapi_entry_alloc(); - slapi_entry_init(cenotaph, newdn, NULL); + slapi_entry_init(cenotaph, slapi_ch_strdup(newdn), NULL); dncsn = (CSN *)entry_get_dncsn (pre_entry); slapi_entry_add_string(cenotaph, SLAPI_ATTR_OBJECTCLASS, "extensibleobject"); @@ -912,12 +912,46 @@ urp_fixup_add_cenotaph (Slapi_PBlock *pb, char *sessionid, CSN *opcsn) OP_FLAG_REPL_FIXUP|OP_FLAG_NOOP|OP_FLAG_CENOTAPH_ENTRY|SLAPI_OP_FLAG_BYPASS_REFERRALS); slapi_add_internal_pb(add_pb); slapi_pblock_get(add_pb, SLAPI_PLUGIN_INTOP_RESULT, &ret); + slapi_pblock_destroy(add_pb); + + if (ret == LDAP_ALREADY_EXISTS) { + /* the cenotaph already exists, probably because of a loop + * in renaming entries. Update it with new csns + */ + slapi_log_err(SLAPI_LOG_REPL, sessionid, + "urp_fixup_add_cenotaph - cenotaph (%s) already exists, updating\n", newdn); + Slapi_PBlock *mod_pb = slapi_pblock_new(); + Slapi_Mods smods; + Slapi_DN *sdn = slapi_sdn_new_dn_byval(newdn); + slapi_mods_init(&smods, 4); + slapi_mods_add_string(&smods, LDAP_MOD_REPLACE, "cenotaphfrom", csn_as_string(dncsn, PR_FALSE, csnstr)); + slapi_mods_add_string(&smods, LDAP_MOD_REPLACE, "cenotaphto", csn_as_string(opcsn, PR_FALSE, csnstr)); + slapi_mods_add_string(&smods, LDAP_MOD_REPLACE, "nstombstonecsn", csn_as_string(opcsn, PR_FALSE, csnstr)); + + slapi_modify_internal_set_pb_ext( + mod_pb, + sdn, + slapi_mods_get_ldapmods_byref(&smods), + NULL, /* Controls */ + NULL, + repl_get_plugin_identity(PLUGIN_MULTIMASTER_REPLICATION), + OP_FLAG_REPL_FIXUP|OP_FLAG_NOOP|OP_FLAG_CENOTAPH_ENTRY|SLAPI_OP_FLAG_BYPASS_REFERRALS); + + slapi_modify_internal_pb(mod_pb); + slapi_pblock_get(mod_pb, SLAPI_PLUGIN_INTOP_RESULT, &ret); + if (ret != LDAP_SUCCESS) { + slapi_log_err(SLAPI_LOG_ERR, sessionid, + "urp_fixup_add_cenotaph - failed to modify cenotaph, err= %d\n", ret); + } + slapi_mods_done(&smods); + slapi_sdn_free(&sdn); + slapi_pblock_destroy(mod_pb); - if (ret != LDAP_SUCCESS) { + } else if (ret != LDAP_SUCCESS) { slapi_log_err(SLAPI_LOG_ERR, sessionid, "urp_fixup_add_cenotaph - failed to add cenotaph, err= %d\n", ret); } - slapi_pblock_destroy(add_pb); + slapi_ch_free_string(&newdn); return ret; }
0
07af8260f8866299d3d242dc480bcf7f1e52bd69
389ds/389-ds-base
Ticket 332 - minor quoting issue in a few scripts. Description: In monitor and ldif2ldap a variable needed to be quoted. https://fedorahosted.org/389/ticket/332
commit 07af8260f8866299d3d242dc480bcf7f1e52bd69 Author: Mark Reynolds <[email protected]> Date: Wed Mar 6 14:45:07 2013 -0500 Ticket 332 - minor quoting issue in a few scripts. Description: In monitor and ldif2ldap a variable needed to be quoted. https://fedorahosted.org/389/ticket/332 diff --git a/ldap/admin/src/scripts/ldif2ldap.in b/ldap/admin/src/scripts/ldif2ldap.in index 4bbc1b534..2ce1cdebb 100755 --- a/ldap/admin/src/scripts/ldif2ldap.in +++ b/ldap/admin/src/scripts/ldif2ldap.in @@ -99,7 +99,7 @@ protocol=$revised_protocol # if [ "$security" == "on" ]; then if [ "$protocol" == "STARTTLS" ] || [ "$protocol" == "" ]; then - if [ $error == "yes" ]; then + if [ "$error" == "yes" ]; then echo "Using the next most secure protocol(STARTTLS)" fi if [ "$openldap" == "yes" ]; then @@ -116,7 +116,7 @@ fi # if [ "$security" == "on" ]; then if [ "$protocol" == "LDAPS" ] || [ "$protocol" == "" ]; then - if [ $error == "yes" ]; then + if [ "$error" == "yes" ]; then echo "Using the next most secure protocol(LDAPS)" fi if [ "$openldap" == "yes" ]; then @@ -134,12 +134,12 @@ fi if [ "$ldapi" == "on" ] && [ "$openldap" == "yes" ]; then if [ "$protocol" == "LDAPI" ] || [ "$protocol" == "" ]; then if [ "$(id -u)" == "0" ] && [ "$autobind" == "on" ]; then - if [ $error == "yes" ]; then + if [ "$error" == "yes" ]; then echo "Using the next most secure protocol(LDAPI/AUTOBIND)" fi ldapmodify -H $ldapiURL -Y EXTERNAL -a -f $input_file 2>/dev/null else - if [ $error == "yes" ]; then + if [ "$error" == "yes" ]; then echo "Using the next most secure protocol(LDAPI)" fi ldapmodify -x -H $ldapiURL -D $rootdn -w $passwd -a -f $input_file @@ -157,7 +157,7 @@ fi # LDAP # if [ "$protocol" == "LDAP" ] || [ "$protocol" == "" ]; then - if [ $error == "yes" ]; then + if [ "$error" == "yes" ]; then echo "Using the next most secure protocol(LDAP)" fi if [ "$openldap" == "yes" ]; then diff --git a/ldap/admin/src/scripts/monitor.in b/ldap/admin/src/scripts/monitor.in index 93ac140ac..abe036626 100755 --- a/ldap/admin/src/scripts/monitor.in +++ b/ldap/admin/src/scripts/monitor.in @@ -104,7 +104,7 @@ protocol=$revised_protocol # if [ "$security" == "on" ]; then if [ "$protocol" == "STARTTLS" ] || [ "$protocol" == "" ]; then - if [ $error == "yes" ]; then + if [ "$error" == "yes" ]; then echo "Using the next most secure protocol(STARTTLS)" fi if [ "$openldap" == "yes" ]; then @@ -121,7 +121,7 @@ fi # if [ "$security" == "on" ]; then if [ "$protocol" == "LDAPS" ] || [ "$protocol" == "" ]; then - if [ $error == "yes" ]; then + if [ "$error" == "yes" ]; then echo "Using the next most secure protocol(LDAPS)" fi if [ "$openldap" == "yes" ]; then @@ -139,11 +139,14 @@ fi if [ "$ldapi" == "on" ] && [ "$openldap" == "yes" ]; then if [ "$protocol" == "LDAPI" ] || [ "$protocol" == "" ]; then if [ "$(id -u)" == "0" ] && [ "$autobind" == "on" ]; then - if [ $error == "yes" ]; then + if [ "$error" == "yes" ]; then echo "Using the next most secure protocol(LDAPI/AUTOBIND)" fi ldapsearch -LLL -H "$ldapiURL" -b "$MDN" -s base -Y EXTERNAL "objectClass=*" 2>/dev/null else + if [ "$error" == "yes" ]; then + echo "Using the next most secure protocol(LDAPI)" + fi ldapsearch -x -LLL -H "$ldapiURL" -b "$MDN" -s base $dn $passwd "objectClass=*" fi exit $? @@ -154,7 +157,7 @@ fi # LDAP # if [ "$protocol" == "LDAP" ] || [ "$protocol" == "" ]; then - if [ $error == "yes" ]; then + if [ "$error" == "yes" ]; then echo "Using the next most secure protocol(LDAP)" fi if [ "$openldap" == "yes" ]; then
0
b28271331d91db291542d1e42562bf9c24d8c522
389ds/389-ds-base
Issue 5162 - Fix dsctl tls ca-certfiicate add-cert arg requirement Description: Incorrectly added "required=True" to positional arg nickname when adding ca-cert. relates: https://github.com/389ds/389-ds-base/issues/5162 Reviewed by: ?
commit b28271331d91db291542d1e42562bf9c24d8c522 Author: Mark Reynolds <[email protected]> Date: Tue Nov 15 13:49:11 2022 -0500 Issue 5162 - Fix dsctl tls ca-certfiicate add-cert arg requirement Description: Incorrectly added "required=True" to positional arg nickname when adding ca-cert. relates: https://github.com/389ds/389-ds-base/issues/5162 Reviewed by: ? diff --git a/src/lib389/lib389/cli_ctl/tls.py b/src/lib389/lib389/cli_ctl/tls.py index 91320b1d5..c5a896aac 100644 --- a/src/lib389/lib389/cli_ctl/tls.py +++ b/src/lib389/lib389/cli_ctl/tls.py @@ -120,8 +120,7 @@ def create_parser(subparsers): ) import_ca_parser.add_argument('cert_path', help="The path to the x509 cert to import as a server CA") - import_ca_parser.add_argument('nickname', nargs='+', required=True, - help="The name of the certificate once imported") + import_ca_parser.add_argument('nickname', nargs='+', help="The name of the certificate once imported") import_ca_parser.set_defaults(func=import_ca) import_server_cert_parser = subcommands.add_parser(
0
fc69ddb943513568ac86942ed441773fa13b4db1
389ds/389-ds-base
Issue 4591 - RFE - improve openldap_to_ds help and features (#4607) Bug Description: Improve the --help page, and finish wiring in some features. Fix Description: Wire in exclusion of attributes/schema for migration. fixes: https://github.com/389ds/389-ds-base/issues/4591 Author: William Brown <[email protected]> Review by: @mreynolds389, @droideck
commit fc69ddb943513568ac86942ed441773fa13b4db1 Author: Firstyear <[email protected]> Date: Thu Feb 11 15:12:38 2021 +1000 Issue 4591 - RFE - improve openldap_to_ds help and features (#4607) Bug Description: Improve the --help page, and finish wiring in some features. Fix Description: Wire in exclusion of attributes/schema for migration. fixes: https://github.com/389ds/389-ds-base/issues/4591 Author: William Brown <[email protected]> Review by: @mreynolds389, @droideck diff --git a/src/lib389/cli/openldap_to_ds b/src/lib389/cli/openldap_to_ds index c2dcd057a..a9fae3344 100755 --- a/src/lib389/cli/openldap_to_ds +++ b/src/lib389/cli/openldap_to_ds @@ -23,7 +23,7 @@ from lib389.cli_base import ( from lib389.cli_base.dsrc import dsrc_to_ldap, dsrc_arg_concat from lib389._constants import DSRC_HOME -from lib389.migrate.openldap.config import olConfig +from lib389.migrate.openldap.config import olConfig, olOverlayType_from_str from lib389.migrate.ldif import LdifMetadata from lib389.migrate.plan import Migration @@ -37,6 +37,15 @@ so some features still may require hand migration, or can not be migrated at all intends to migrate the majority of major content such as database data, index configuration, schema and some overlays (plugins). +Content we can migrate: + +* Schema +* Database content (from ldif backup) +* Database indexes +* MemberOf Overlay (memberof) +* Referential Integrity Overlay (refint) +* Attribute Unique Overlay (unique) + Some content that can *not* be migrated include some overlays (plugins), access controls and replication configuration. Examples of plugins that can not be migrated: @@ -48,7 +57,7 @@ and replication configuration. Examples of plugins that can not be migrated: * Proxy Cache (No equivalent plugin, 389-ds supports read-only replicas) * Password Policy (Built into 389-ds, requires manual migration) * Rewrite/Remap (No equivalent plugin) -* Sync Provider (Requires manual migration to Content Sync Plugin) +* Sync Provider (Requires manual migration to Replication OR Content Sync Plugin) * Value Sorting (No equivalent plugin) This must be run on the server running the 389 Directory Instance as it requires filesystem @@ -110,27 +119,17 @@ parser.add_argument('--confirm', help="Confirm that you want to apply these migration actions to the 389-ds instance. By default no actions are taken." ) parser.add_argument('--ignore-overlay', nargs='*', - help="Ignore the following openldap overlays from having their configuration migrated to equivalent 389-ds plugins." + help="Ignore the following openldap overlays from having their configuration migrated to equivalent 389-ds plugins. Valid options are memberof, refint, unique.", + default=[] ) parser.add_argument('--ignore-schema-oid', nargs='*', - help="Ignore the following openldap schema attribute or class OIDS from being migrated to 389-ds. This *may* create inconsistent schema which could cause the migration to fail. Use with caution." + help="Ignore the following openldap schema attribute or class OIDS from being migrated to 389-ds. This *may* create inconsistent schema which could cause the migration to fail. Use with caution.", + default=[] ) parser.add_argument('--ignore-attribute', nargs='*', - help="Ignore the following attributes from entries that are loaded from the ldif. For example, you may not want to import userPassword hashes." -) -parser.add_argument('--no-overlays', - default=True, action='store_false', - help="Do not migrate any openldap overlays to equivalent 389-ds plugins." -) -parser.add_argument('--no-schema', - default=True, action='store_false', - help="Do not migrate the schema from openldap to 389-ds. This may cause the ldif import to fail." + help="Ignore the following attributes from entries that are loaded from the ldif. For example, you may not want to import userPassword hashes.", + default=[] ) -parser.add_argument('--no-indexes', - default=True, action='store_false', - help="Do not create any indexes in 389-ds as defined in openldap slapd.d" -) - # General options parser.add_argument('-D', '--binddn', help="The 389 Directory Server account to bind as for executing migration operations", @@ -166,11 +165,15 @@ def signal_handler(signal, frame): print('\n\nExiting...') sys.exit(0) -def do_migration(inst, log, args): +def do_migration(inst, log, args, skip_overlays): log.debug("do_migration -- begin preparation --") log.debug("Instance isLocal: %s" % inst.isLocal) # Do the thing + # Map some args out. + skip_schema_oids = args.ignore_schema_oid + skip_entry_attributes = args.ignore_attribute + # Parse the openldap config config = olConfig(args.slapd_config, log) @@ -179,8 +182,9 @@ def do_migration(inst, log, args): # Create the migration plan. migration = Migration(config, inst, ldifmeta.get_suffixes(), - # skip_schema_oids=['1.3.6.1.4.1.5322.13.1.1'], - # skip_overlays=[olOverlayType.UNIQUE], + skip_schema_oids, + skip_overlays, + skip_entry_attributes, ) # Present it for review. @@ -219,6 +223,13 @@ if __name__ == '__main__': log.debug("Inspired by works of: ITS, The University of Adelaide") log.debug("Called with: %s", args) + # Do some initial parsing. Matters for overlays. + skip_overlays = [ + olOverlayType_from_str(x) + for x in args.ignore_overlay + if olOverlayType_from_str(x) + ] + # Now that we have our args, see how they relate with our instance. dsrc_inst = dsrc_to_ldap(DSRC_HOME, args.instance, log.getChild('dsrc')) @@ -232,7 +243,7 @@ if __name__ == '__main__': try: inst = connect_instance(dsrc_inst=dsrc_inst, verbose=args.verbose, args=args) - result = do_migration(inst, log, args) + result = do_migration(inst, log, args, skip_overlays) except Exception as e: log.debug(e, exc_info=True) msg = format_error_to_dict(e) diff --git a/src/lib389/lib389/migrate/openldap/config.py b/src/lib389/lib389/migrate/openldap/config.py index 7bcf753de..b709e7c60 100644 --- a/src/lib389/lib389/migrate/openldap/config.py +++ b/src/lib389/lib389/migrate/openldap/config.py @@ -48,6 +48,17 @@ class olOverlayType(Enum): REFINT = 2 UNIQUE = 3 +def olOverlayType_from_str(instr): + instr = instr.upper().strip() + if instr == "MEMBEROF": + return olOverlayType.MEMBEROF + elif instr == "REFINT": + return olOverlayType.REFINT + elif instr == "UNIQUE": + return olOverlayType.UNIQUE + else: + return olOverlayType.UNKNOWN + class olOverlay(object): def __init__(self, path, name, log): diff --git a/src/lib389/lib389/migrate/plan.py b/src/lib389/lib389/migrate/plan.py index 3982c1f93..e04da86a0 100644 --- a/src/lib389/lib389/migrate/plan.py +++ b/src/lib389/lib389/migrate/plan.py @@ -98,7 +98,8 @@ class DatabaseReindex(MigrationAction): log.info(f" * Database Reindex -> {self.suffix}") class ImportTransformer(LDIFParser): - def __init__(self, f_import, f_outport): + def __init__(self, f_import, f_outport, exclude_attributes_set): + self.exclude_attributes_set = exclude_attributes_set self.f_outport = f_outport self.writer = LDIFWriter(self.f_outport) super().__init__(f_import) @@ -116,35 +117,29 @@ class ImportTransformer(LDIFParser): # If mo present, as nsMemberOf. try: mo_a = amap['memberof'] - # If mo_a was found, then mo is present, extend the oc. + # If mo_a was found, then mo is present, extend the oc to make it valid. entry[oc_a] += [b'nsMemberOf'] except: # Not found pass - # strip entryCSN - try: - ecsn_a = amap['entrycsn'] - entry.pop(ecsn_a) - except: - # No ecsn, skip - pass - - # strip sco - try: - sco_a = amap['structuralobjectclass'] - entry.pop(sco_a) - except: - # No sco, skip - pass + # Strip anything in the exclude set. + for attr in self.exclude_attributes_set: + try: + ecsn_a = amap[attr] + entry.pop(ecsn_a) + except: + # Not found, move on. + pass # Write it out self.writer.unparse(dn, entry) class DatabaseLdifImport(MigrationAction): - def __init__(self, suffix, ldif_path): + def __init__(self, suffix, ldif_path, exclude_attributes_set): self.suffix = suffix self.ldif_path = ldif_path + self.exclude_attributes_set = exclude_attributes_set def apply(self, inst): # Create a unique op id. @@ -153,7 +148,7 @@ class DatabaseLdifImport(MigrationAction): with open(self.ldif_path, 'r') as f_import: with open(op_path, 'w') as f_outport: - p = ImportTransformer(f_import, f_outport) + p = ImportTransformer(f_import, f_outport, self.exclude_attributes_set) p.parse() be = Backends(inst).get(self.suffix) @@ -167,7 +162,7 @@ class DatabaseLdifImport(MigrationAction): return f"DatabaseLdifImport -> {self.suffix} {self.ldif_path}" def display_plan(self, log): - log.info(f" * Database Import Ldif -> {self.suffix} from {self.ldif_path}") + log.info(f" * Database Import Ldif -> {self.suffix} from {self.ldif_path} - excluding entry attributes = [{self.exclude_attributes_set}]") def display_post(self, log): log.info(f" * [ ] - Review Database Imported Content is Correct -> {self.suffix}") @@ -426,7 +421,7 @@ class PluginUnknownManual(MigrationAction): class Migration(object): - def __init__(self, olconfig, inst, ldifs=None, skip_schema_oids=[], skip_overlays=[]): + def __init__(self, olconfig, inst, ldifs=None, skip_schema_oids=[], skip_overlays=[], skip_entry_attributes=[]): """Generate a migration plan from an openldap config, the instance to migrate too and an optional dictionary of { suffix: ldif_path }. @@ -499,6 +494,10 @@ class Migration(object): '0.9.2342.19200300.100.4.22', ]) + self._skip_entry_attributes = set( + ['entrycsn', 'structuralobjectclass'] + + [x.lower() for x in skip_entry_attributes] + ) self._gen_migration_plan() def __unicode__(self): @@ -633,7 +632,7 @@ class Migration(object): if self.ldifs is None: return for (suffix, ldif_path) in self.ldifs.items(): - self.plan.append(DatabaseLdifImport(suffix, ldif_path)) + self.plan.append(DatabaseLdifImport(suffix, ldif_path, self._skip_entry_attributes)) def _gen_migration_plan(self): """Order of this module is VERY important!!!
0
cbed8a2780469cdbf298c30e7f10da01c4356d03
389ds/389-ds-base
Bug 514955 - Make DNA handle multiple mods DNA doesn't handle multiple mods to a managed attribute in the same modify operation properly. If an operation such as deleting a managed value triggers generation, we aren't checking if another mod in the same operation is actually adding a new value. This triggers us to generate a value when we really shouldn't. The fix is to unset the generate flag if we find a subsequent mod to the same managed type. It will be reset if we truly need to generate a new value.
commit cbed8a2780469cdbf298c30e7f10da01c4356d03 Author: Nathan Kinder <[email protected]> Date: Fri Jul 31 22:53:48 2009 -0700 Bug 514955 - Make DNA handle multiple mods DNA doesn't handle multiple mods to a managed attribute in the same modify operation properly. If an operation such as deleting a managed value triggers generation, we aren't checking if another mod in the same operation is actually adding a new value. This triggers us to generate a value when we really shouldn't. The fix is to unset the generate flag if we find a subsequent mod to the same managed type. It will be reset if we truly need to generate a new value. diff --git a/ldap/servers/plugins/dna/dna.c b/ldap/servers/plugins/dna/dna.c index b198ef3a3..b8e21f0e3 100644 --- a/ldap/servers/plugins/dna/dna.c +++ b/ldap/servers/plugins/dna/dna.c @@ -2683,15 +2683,24 @@ static int dna_pre_op(Slapi_PBlock * pb, int modtype) /* This is either adding or replacing a value */ struct berval *bv = slapi_mod_get_first_value(smod); + /* If generate is already set, a previous mod in + * this same modify operation either removed all + * values or set the magic value. It's possible + * that this mod is adding a valid value, which + * means we would not want to generate a new value. + * It is safe to unset generate since it will be + * reset here if necessary. */ + generate = 0; + /* If we have a value, see if it's the magic value. */ if (bv) { int len = strlen(config_entry->generate); if (len == bv->bv_len) { if (!slapi_UTF8NCASECMP(bv->bv_val, config_entry->generate, - len)) + len)) { generate = 1; - break; + } } } else { /* This is a replace with no new values, so we need @@ -2783,9 +2792,7 @@ static int dna_pre_op(Slapi_PBlock * pb, int modtype) bailmod: if (LDAP_CHANGETYPE_MODIFY == modtype) { - /* these are the mods you made, really, - * I didn't change them, honest, just had a quick look - */ + /* Put the updated mods back into place. */ mods = slapi_mods_get_ldapmods_passout(smods); slapi_pblock_set(pb, SLAPI_MODIFY_MODS, mods); slapi_mods_free(&smods);
0
8b3f4ca6d3c28262ece7079eb77968be445f3cab
389ds/389-ds-base
Ticket 50989 - ignore pid when it is ourself in protect_db Bug Description: In protect_db.c, there are some cases (especially containers) where a pid number can be re-used. Following a bad shutdown, the lock files in /run/lock/{export,import,server}/* remain, and the pid they hold could be allocated to ourself. When this occurs, the server fails to start. Fix Description: If the pid of the lock file is our own pid, that is proof that the previous pid/lock file can not exist, and therfore it is safe to proceed with the startup. https://pagure.io/389-ds-base/issue/50989 Author: William Brown <[email protected]> Review by: tbordaz (Thanks!)
commit 8b3f4ca6d3c28262ece7079eb77968be445f3cab Author: William Brown <[email protected]> Date: Mon Mar 30 12:37:23 2020 +1000 Ticket 50989 - ignore pid when it is ourself in protect_db Bug Description: In protect_db.c, there are some cases (especially containers) where a pid number can be re-used. Following a bad shutdown, the lock files in /run/lock/{export,import,server}/* remain, and the pid they hold could be allocated to ourself. When this occurs, the server fails to start. Fix Description: If the pid of the lock file is our own pid, that is proof that the previous pid/lock file can not exist, and therfore it is safe to proceed with the startup. https://pagure.io/389-ds-base/issue/50989 Author: William Brown <[email protected]> Review by: tbordaz (Thanks!) diff --git a/ldap/servers/slapd/protect_db.c b/ldap/servers/slapd/protect_db.c index ccde08b07..c4d50d845 100644 --- a/ldap/servers/slapd/protect_db.c +++ b/ldap/servers/slapd/protect_db.c @@ -251,7 +251,19 @@ sample_and_update(char *dir_name) * didn't put it there */ continue; } - if (is_process_up(pid)) { + if (pid == getpid()) { + /* + * We have re-used our pid number, and we are now checking for ourself! + * + * pagure: https://pagure.io/389-ds-base/issue/50989 + * + * This situation is common in containers, where the process name space means we + * may be checking ourself, and have low pids that get re-used. Worse, we cant + * actually check the pid of any other instance in a different container. + * So at the very least in THIS case, we ignore it, since we are the pid + * that has the lock, and it's probably a left over from a bad startup. + */ + } else if (is_process_up(pid)) { result = (long)pid; } else { PR_snprintf(file_name, MAXPATHLEN, "%s/%s", dir_name, entry->name);
0
9bdd9ec3fa3adf20ec84e7e3c9317034f9fc3bcf
389ds/389-ds-base
Issue 4649 - crash in sync_repl when a MODRDN create a cenotaph (#4652) Bug description: When an operation is flagged OP_FLAG_NOOP, it skips BETXN plugins but calls POST plugins. For sync_repl, betxn (sync_update_persist_betxn_pre_op) creates an operation extension to be consumed by the post (sync_update_persist_op). In case of OP_FLAG_NOOP, there is no operation extension. Fix description: Test that the operation is OP_FLAG_NOOP if the operation extension is missing relates: https://github.com/389ds/389-ds-base/issues/4649 Reviewed by: William Brown (thanks) Platforms tested: F31
commit 9bdd9ec3fa3adf20ec84e7e3c9317034f9fc3bcf Author: tbordaz <[email protected]> Date: Tue Feb 23 08:58:37 2021 +0100 Issue 4649 - crash in sync_repl when a MODRDN create a cenotaph (#4652) Bug description: When an operation is flagged OP_FLAG_NOOP, it skips BETXN plugins but calls POST plugins. For sync_repl, betxn (sync_update_persist_betxn_pre_op) creates an operation extension to be consumed by the post (sync_update_persist_op). In case of OP_FLAG_NOOP, there is no operation extension. Fix description: Test that the operation is OP_FLAG_NOOP if the operation extension is missing relates: https://github.com/389ds/389-ds-base/issues/4649 Reviewed by: William Brown (thanks) Platforms tested: F31 diff --git a/dirsrvtests/tests/suites/syncrepl_plugin/basic_test.py b/dirsrvtests/tests/suites/syncrepl_plugin/basic_test.py index 04c0a0985..5db9dc929 100644 --- a/dirsrvtests/tests/suites/syncrepl_plugin/basic_test.py +++ b/dirsrvtests/tests/suites/syncrepl_plugin/basic_test.py @@ -18,6 +18,7 @@ from lib389.idm.organizationalunit import OrganizationalUnits, OrganizationalUni from lib389.idm.user import nsUserAccounts, UserAccounts from lib389.idm.group import Groups from lib389.topologies import topology_st as topology +from lib389.topologies import topology_m2 as topo_m2 from lib389.paths import Paths from lib389.utils import ds_is_older from lib389.plugins import RetroChangelogPlugin, ContentSyncPlugin, AutoMembershipPlugin, MemberOfPlugin, MemberOfSharedConfig, AutoMembershipDefinitions, MEPTemplates, MEPConfigs, ManagedEntriesPlugin, MEPTemplate @@ -526,3 +527,65 @@ def test_sync_repl_cookie_with_failure(topology, init_sync_repl_plugins, request testgroup.delete() request.addfinalizer(fin) + +def test_sync_repl_cenotaph(topo_m2, request): + """Test the creation of a cenotaph while a + sync repl client is running + + :id: 8ca1724a-cf42-4880-bf0f-be451f9bd3b4 + :setup: MMR with 2 masters + :steps: + 1. Enable retroCL/content_sync + 2. Run a sync repl client + 3. create users + 4. do a MODRDN of a user entry => creation of cenotaph + 5. stop sync repl client + :expectedresults: + 1. Should succeeds + 2. Should succeeds + 3. Should succeeds + 4. Should succeeds + 5. Should succeeds + """ + m1 = topo_m2.ms["master1"] + # Enable/configure retroCL + plugin = RetroChangelogPlugin(m1) + plugin.disable() + plugin.enable() + plugin.set('nsslapd-attribute', 'nsuniqueid:targetuniqueid') + + # Enable sync plugin + plugin = ContentSyncPlugin(m1) + plugin.enable() + # Restart DS + m1.restart() + + # create a sync repl client and wait 5 seconds to be sure it is running + sync_repl = Sync_persist(m1) + sync_repl.start() + time.sleep(5) + + # create users + users = UserAccounts(m1, DEFAULT_SUFFIX) + users_set = [] + for i in range(10001, 10003): + users_set.append(users.create_test_user(uid=i)) + + # rename the entry that would trigger the creation of a cenotaph + users_set[0].rename("uid=foo") + + # stop the server to get the sync_repl result set (exit from while loop). + # Only way I found to acheive that. + # and wait a bit to let sync_repl thread time to set its result before fetching it. + m1.stop() + time.sleep(2) + + def fin(): + m1.restart() + for user in users_set: + try: + user.delete() + except: + pass + + request.addfinalizer(fin) diff --git a/ldap/servers/plugins/sync/sync_persist.c b/ldap/servers/plugins/sync/sync_persist.c index ce3aea846..0a27e2169 100644 --- a/ldap/servers/plugins/sync/sync_persist.c +++ b/ldap/servers/plugins/sync/sync_persist.c @@ -203,7 +203,9 @@ sync_update_persist_op(Slapi_PBlock *pb, Slapi_Entry *e, Slapi_Entry *eprev, ber slapi_pblock_get(pb, SLAPI_TARGET_SDN, &sdn); if (NULL == e) { - /* Ignore this operation (for example case of failure of the operation) */ + /* Ignore this operation (for example case of failure of the operation + * or operation resulting in an empty Mods)) + */ ignore_op_pl(pb); return; } @@ -229,7 +231,15 @@ sync_update_persist_op(Slapi_PBlock *pb, Slapi_Entry *e, Slapi_Entry *eprev, ber prim_op = get_thread_primary_op(); ident = sync_persist_get_operation_extension(pb); PR_ASSERT(prim_op); - PR_ASSERT(ident); + + if ((ident == NULL) && operation_is_flag_set(pb_op, OP_FLAG_NOOP)) { + /* This happens for URP (add cenotaph, fixup rename, tombstone resurrect) + * As a NOOP betxn plugins are not called and operation ext is not created + */ + slapi_log_err(SLAPI_LOG_PLUGIN, SYNC_PLUGIN_SUBSYSTEM, "Skip noop operation (0x%lx)\n", + (ulong) pb_op); + return; + } /* First mark the operation as completed/failed * the param to be used once the operation will be pushed * on the listeners queue
0
9110d2b4a74a6e8ed86d6e844dd6b517a87156af
389ds/389-ds-base
Ticket 48377 - Move jemalloc license to /usr/share/licences Description: Move jemalloc license (COPYING.jemalloc) to /usr/share/licences also added nss version dependancy that was missing https://pagure.io/389-ds-base/issue/48377 Reviewed by: mreynolds(one line commit rule)
commit 9110d2b4a74a6e8ed86d6e844dd6b517a87156af Author: Mark Reynolds <[email protected]> Date: Tue Jul 17 11:48:05 2018 -0400 Ticket 48377 - Move jemalloc license to /usr/share/licences Description: Move jemalloc license (COPYING.jemalloc) to /usr/share/licences also added nss version dependancy that was missing https://pagure.io/389-ds-base/issue/48377 Reviewed by: mreynolds(one line commit rule) diff --git a/rpm/389-ds-base.spec.in b/rpm/389-ds-base.spec.in index 53e36b013..7d99feb7a 100644 --- a/rpm/389-ds-base.spec.in +++ b/rpm/389-ds-base.spec.in @@ -66,7 +66,7 @@ Provides: ldif2ldbm # Attach the buildrequires to the top level package: BuildRequires: nspr-devel -BuildRequires: nss-devel +BuildRequires: nss-devel >= 3.34 BuildRequires: openldap-devel BuildRequires: libdb-devel BuildRequires: cyrus-sasl-devel @@ -147,6 +147,7 @@ Requires: openldap-clients # this is needed to setup SSL if you are not using the # administration server package Requires: nss-tools +Requires: nss >= 3.34 # these are not found by the auto-dependency method # they are required to support the mandatory LDAP SASL mechs Requires: cyrus-sasl-gssapi @@ -182,7 +183,6 @@ Please see http://seclists.org/oss-sec/2016/q1/363 for more information. %endif - %package libs Summary: Core libraries for 389 Directory Server (%{variant}) Group: System Environment/Daemons @@ -191,7 +191,7 @@ Obsoletes: svrcore <= 4.1.3 Conflicts: svrcore # You can work this out by running LDD on libslapd.so to see what it needs in # isolation. -Requires: nss +Requires: nss >= 3.34 Requires: nspr Requires: openldap Requires: libevent @@ -254,7 +254,7 @@ Conflicts: svrcore-devel Requires: %{name}-libs = %{version}-%{release} Requires: pkgconfig Requires: nspr-devel -Requires: nss-devel +Requires: nss-devel >= 3.34 Requires: openldap-devel # systemd-libs contains the headers iirc. Requires: systemd-libs @@ -292,6 +292,7 @@ Requires: python%{python3_pkgversion}-pyasn1-modules Requires: python%{python3_pkgversion}-dateutil Requires: python%{python3_pkgversion}-argcomplete %{?python_provide:%python_provide python%{python3_pkgversion}-lib389} + %description -n python%{python3_pkgversion}-lib389 This module contains tools and libraries for accessing, testing, and configuring the 389 Directory Server. @@ -592,7 +593,8 @@ exit 0 %files %defattr(-,root,root,-) %if %{bundle_jemalloc} -%doc LICENSE LICENSE.GPLv3+ LICENSE.openssl README.jemalloc COPYING.jemalloc +%doc LICENSE LICENSE.GPLv3+ LICENSE.openssl README.jemalloc +%license COPYING.jemalloc %else %doc LICENSE LICENSE.GPLv3+ LICENSE.openssl %endif
0
6a0ed40b25a6dd4aaf3774a70199e8842499b42d
389ds/389-ds-base
Ticket 47427 - Overflow in nsslapd-disk-monitoring-threshold Bug Description: The threshold setting was being stored as an "int" instead of a PRUint64. Config setting validation was also incomplete. Fix Description: Changed the data type to PRUint64 from int, and improved the config validation, and logging. https://fedorahosted.org/389/ticket/47427 Reviewed by: richm & nhosoi(Thanks!!)
commit 6a0ed40b25a6dd4aaf3774a70199e8842499b42d Author: Mark Reynolds <[email protected]> Date: Wed Jul 10 15:41:47 2013 -0400 Ticket 47427 - Overflow in nsslapd-disk-monitoring-threshold Bug Description: The threshold setting was being stored as an "int" instead of a PRUint64. Config setting validation was also incomplete. Fix Description: Changed the data type to PRUint64 from int, and improved the config validation, and logging. https://fedorahosted.org/389/ticket/47427 Reviewed by: richm & nhosoi(Thanks!!) diff --git a/ldap/servers/slapd/daemon.c b/ldap/servers/slapd/daemon.c index 817fea793..a14cf356d 100644 --- a/ldap/servers/slapd/daemon.c +++ b/ldap/servers/slapd/daemon.c @@ -641,16 +641,16 @@ disk_mon_get_dirs(char ***list, int logs_critical){ * directory. */ char * -disk_mon_check_diskspace(char **dirs, PRInt64 threshold, PRInt64 *disk_space) +disk_mon_check_diskspace(char **dirs, PRUint64 threshold, PRUint64 *disk_space) { #ifdef LINUX struct statfs buf; #else struct statvfs buf; #endif - PRInt64 worst_disk_space = threshold; - PRInt64 freeBytes = 0; - PRInt64 blockSize = 0; + PRUint64 worst_disk_space = threshold; + PRUint64 freeBytes = 0; + PRUint64 blockSize = 0; char *worst_dir = NULL; int hit_threshold = 0; int i = 0; @@ -707,10 +707,10 @@ disk_monitoring_thread(void *nothing) char errorbuf[BUFSIZ]; char **dirs = NULL; char *dirstr = NULL; - PRInt64 previous_mark = 0; - PRInt64 disk_space = 0; - PRInt64 threshold = 0; - PRInt64 halfway = 0; + PRUint64 previous_mark = 0; + PRUint64 disk_space = 0; + PRUint64 threshold = 0; + PRUint64 halfway = 0; time_t start = 0; time_t now = 0; int deleted_rotated_logs = 0; @@ -792,7 +792,7 @@ disk_monitoring_thread(void *nothing) * Check if we are already critical */ if(disk_space < 4096){ /* 4 k */ - LDAPDebug(LDAP_DEBUG_ANY, "Disk space is critically low on disk (%s), remaining space: %d Kb. " + LDAPDebug(LDAP_DEBUG_ANY, "Disk space is critically low on disk (%s), remaining space: %" NSPRIu64 " Kb. " "Signaling slapd for shutdown...\n", dirstr , (disk_space / 1024), 0); g_set_shutdown( SLAPI_SHUTDOWN_EXIT ); return; @@ -802,7 +802,7 @@ disk_monitoring_thread(void *nothing) * if logging is not critical */ if(verbose_logging != 0 && verbose_logging != LDAP_DEBUG_ANY){ - LDAPDebug(LDAP_DEBUG_ANY, "Disk space is low on disk (%s), remaining space: %d Kb, " + LDAPDebug(LDAP_DEBUG_ANY, "Disk space is low on disk (%s), remaining space: %" NSPRIu64 " Kb, " "temporarily setting error loglevel to zero.\n", dirstr, (disk_space / 1024), 0); /* Setting the log level back to zero, actually sets the value to LDAP_DEBUG_ANY */ @@ -814,11 +814,11 @@ disk_monitoring_thread(void *nothing) * access/audit logs, log another error, and continue. */ if(!logs_disabled && !logging_critical){ - LDAPDebug(LDAP_DEBUG_ANY, "Disk space is too low on disk (%s), remaining space: %d Kb, " - "disabling access and audit logging.\n", dirstr, (disk_space / 1024), 0); - config_set_accesslog_enabled(LOGGING_OFF); - config_set_auditlog_enabled(LOGGING_OFF); - logs_disabled = 1; + LDAPDebug(LDAP_DEBUG_ANY, "Disk space is too low on disk (%s), remaining space: %" NSPRIu64 " Kb, " + "disabling access and audit logging.\n", dirstr, (disk_space / 1024), 0); + config_set_accesslog_enabled(LOGGING_OFF); + config_set_auditlog_enabled(LOGGING_OFF); + logs_disabled = 1; continue; } /* @@ -826,17 +826,17 @@ disk_monitoring_thread(void *nothing) * access/audit logging, then delete the rotated logs, log another error, and continue. */ if(!deleted_rotated_logs && !logging_critical){ - LDAPDebug(LDAP_DEBUG_ANY, "Disk space is too low on disk (%s), remaining space: %d Kb, " - "deleting rotated logs.\n", dirstr, (disk_space / 1024), 0); - log__delete_rotated_logs(); - deleted_rotated_logs = 1; + LDAPDebug(LDAP_DEBUG_ANY, "Disk space is too low on disk (%s), remaining space: %" NSPRIu64 " Kb, " + "deleting rotated logs.\n", dirstr, (disk_space / 1024), 0); + log__delete_rotated_logs(); + deleted_rotated_logs = 1; continue; } /* * Ok, we've done what we can, log a message if we continue to lose available disk space */ if(disk_space < previous_mark){ - LDAPDebug(LDAP_DEBUG_ANY, "Disk space is too low on disk (%s), remaining space: %d Kb\n", + LDAPDebug(LDAP_DEBUG_ANY, "Disk space is too low on disk (%s), remaining space: %" NSPRIu64 " Kb\n", dirstr, (disk_space / 1024), 0); } /* @@ -848,7 +848,7 @@ disk_monitoring_thread(void *nothing) * */ if(disk_space < halfway){ - LDAPDebug(LDAP_DEBUG_ANY, "Disk space on (%s) is too far below the threshold(%d bytes). " + LDAPDebug(LDAP_DEBUG_ANY, "Disk space on (%s) is too far below the threshold(%" NSPRIu64 " bytes). " "Waiting %d minutes for disk space to be cleaned up before shutting slapd down...\n", dirstr, threshold, (grace_period / 60)); time(&start); @@ -870,7 +870,7 @@ disk_monitoring_thread(void *nothing) /* * Excellent, we are back to acceptable levels, reset everything... */ - LDAPDebug(LDAP_DEBUG_ANY, "Available disk space is now acceptable (%d bytes). Aborting" + LDAPDebug(LDAP_DEBUG_ANY, "Available disk space is now acceptable (%" NSPRIu64 " bytes). Aborting" " shutdown, and restoring the log settings.\n",disk_space,0,0); if(logs_disabled && using_accesslog){ config_set_accesslog_enabled(LOGGING_ON); @@ -890,7 +890,7 @@ disk_monitoring_thread(void *nothing) /* * Disk space is critical, log an error, and shut it down now! */ - LDAPDebug(LDAP_DEBUG_ANY, "Disk space is critically low on disk (%s), remaining space: %d Kb." + LDAPDebug(LDAP_DEBUG_ANY, "Disk space is critically low on disk (%s), remaining space: %" NSPRIu64 " Kb." " Signaling slapd for shutdown...\n", dirstr, (disk_space / 1024), 0); g_set_shutdown( SLAPI_SHUTDOWN_DISKFULL ); return; @@ -907,7 +907,7 @@ disk_monitoring_thread(void *nothing) /* * If disk space was freed up we would of detected in the above while loop. So shut it down. */ - LDAPDebug(LDAP_DEBUG_ANY, "Disk space is still too low (%d Kb). Signaling slapd for shutdown...\n", + LDAPDebug(LDAP_DEBUG_ANY, "Disk space is still too low (%" NSPRIu64 " Kb). Signaling slapd for shutdown...\n", (disk_space / 1024), 0, 0); g_set_shutdown( SLAPI_SHUTDOWN_DISKFULL ); diff --git a/ldap/servers/slapd/libglobs.c b/ldap/servers/slapd/libglobs.c index 12a1e03fe..c1f92ee44 100644 --- a/ldap/servers/slapd/libglobs.c +++ b/ldap/servers/slapd/libglobs.c @@ -1667,17 +1667,19 @@ config_set_disk_threshold( const char *attrname, char *value, char *errorbuf, in { slapdFrontendConfig_t *slapdFrontendConfig = getFrontendConfig(); int retVal = LDAP_SUCCESS; - long threshold = 0; + PRUint64 threshold = 0; char *endp = NULL; if ( config_value_is_null( attrname, value, errorbuf, 0 )) { return LDAP_OPERATIONS_ERROR; } - threshold = strtol(value, &endp, 10); + errno = 0; + threshold = strtoll(value, &endp, 10); - if ( *endp != '\0' || threshold < 2048 ) { - PR_snprintf ( errorbuf, SLAPI_DSE_RETURNTEXT_SIZE, "%s: \"%s\" is invalid, threshold must be greater than 2048 and less then %ld", + if ( *endp != '\0' || threshold <= 4096 || errno == ERANGE ) { + PR_snprintf ( errorbuf, SLAPI_DSE_RETURNTEXT_SIZE, + "%s: \"%s\" is invalid, threshold must be greater than 4096 and less then %llu", attrname, value, LONG_MAX ); retVal = LDAP_OPERATIONS_ERROR; return retVal; @@ -4370,7 +4372,7 @@ config_get_disk_grace_period(){ return retVal; } -long +PRUint64 config_get_disk_threshold(){ slapdFrontendConfig_t *slapdFrontendConfig = getFrontendConfig(); long retVal; diff --git a/ldap/servers/slapd/proto-slap.h b/ldap/servers/slapd/proto-slap.h index 447d7d522..25663d255 100644 --- a/ldap/servers/slapd/proto-slap.h +++ b/ldap/servers/slapd/proto-slap.h @@ -554,7 +554,7 @@ void config_set_accesslog_enabled(int value); void config_set_auditlog_enabled(int value); int config_get_accesslog_logging_enabled(); int config_get_disk_monitoring(); -long config_get_disk_threshold(); +PRUint64 config_get_disk_threshold(); int config_get_disk_grace_period(); int config_get_disk_logging_critical(); int config_get_ndn_cache_count(); diff --git a/ldap/servers/slapd/slap.h b/ldap/servers/slapd/slap.h index f836b16ac..fff464654 100644 --- a/ldap/servers/slapd/slap.h +++ b/ldap/servers/slapd/slap.h @@ -2327,7 +2327,7 @@ typedef struct _slapdFrontendConfig { /* disk monitoring */ slapi_onoff_t disk_monitoring; - int disk_threshold; + PRUint64 disk_threshold; int disk_grace_period; slapi_onoff_t disk_logging_critical;
0
b96806c00fe5bb63d19f37989c15461121b09078
389ds/389-ds-base
Ticket 48996 - remove unused variable. Bug Description: During the cleanup I forgot to remove the enable_listeners variable Fix Description: Remove it. https://fedorahosted.org/389/ticket/48996 Author: wibrown Review by: One line rule.
commit b96806c00fe5bb63d19f37989c15461121b09078 Author: William Brown <[email protected]> Date: Thu Oct 6 10:45:31 2016 +1000 Ticket 48996 - remove unused variable. Bug Description: During the cleanup I forgot to remove the enable_listeners variable Fix Description: Remove it. https://fedorahosted.org/389/ticket/48996 Author: wibrown Review by: One line rule. diff --git a/ldap/servers/slapd/connection.c b/ldap/servers/slapd/connection.c index 7a054c579..11f9acf5b 100644 --- a/ldap/servers/slapd/connection.c +++ b/ldap/servers/slapd/connection.c @@ -168,8 +168,6 @@ connection_done(Connection *conn) void connection_cleanup(Connection *conn) { - int enable_listeners = 0; - bind_credentials_clear( conn, PR_FALSE /* do not lock conn */, PR_TRUE /* clear external creds. */ ); slapi_ch_free((void**)&conn->c_authtype); @@ -186,7 +184,6 @@ connection_cleanup(Connection *conn) if (conn->c_prfd) { PR_Close(conn->c_prfd); - enable_listeners = 1; /* re-enable listeners disabled due to no fds */ } conn->c_sd= SLAPD_INVALID_SOCKET;
0
a30a9e0d6f74774e3c5a0bbe11347d13dc37ddb4
389ds/389-ds-base
Issue 5789 - Improve ds-replcheck error handling Description: When replication is not fully configured the tool outputs vague messages. These should be cleaned up to indicate that replication was not initialized. Also added healthcheck. Relates: https://github.com/389ds/389-ds-base/issues/5789 Reviewed by: tbordaz, spichugi, progier (Thanks!!!)
commit a30a9e0d6f74774e3c5a0bbe11347d13dc37ddb4 Author: Mark Reynolds <[email protected]> Date: Tue Jun 6 12:49:50 2023 -0400 Issue 5789 - Improve ds-replcheck error handling Description: When replication is not fully configured the tool outputs vague messages. These should be cleaned up to indicate that replication was not initialized. Also added healthcheck. Relates: https://github.com/389ds/389-ds-base/issues/5789 Reviewed by: tbordaz, spichugi, progier (Thanks!!!) diff --git a/ldap/admin/src/scripts/ds-replcheck b/ldap/admin/src/scripts/ds-replcheck index f411f357a..efa13ffe8 100755 --- a/ldap/admin/src/scripts/ds-replcheck +++ b/ldap/admin/src/scripts/ds-replcheck @@ -1,7 +1,7 @@ #!/usr/bin/python3 # --- BEGIN COPYRIGHT BLOCK --- -# Copyright (C) 2021 Red Hat, Inc. +# Copyright (C) 2023 Red Hat, Inc. # All rights reserved. # # License: GPL (version 3 or any later version). @@ -216,17 +216,17 @@ def get_ruv_state(opts): mtime = get_ruv_time(opts['supplier_ruv'], opts['rid']) rtime = get_ruv_time(opts['replica_ruv'], opts['rid']) if mtime == -1: - repl_state = "Replication State: Replica ID ({}) not found in Supplier's RUV".format(opts['rid']) + repl_state = f"Replication State: Replica ID ({opts['rid']}) not found in Supplier's RUV" elif rtime == -1: - repl_state = "Replication State: Replica ID ({}) not found in Replica's RUV (not initialized?)".format(opts['rid']) + repl_state = f"Replication State: Replica ID ({opts['rid']}) not found in Replica's RUV (not initialized?)" elif mtime == 0: repl_state = "Replication State: Supplier has not seen any updates" elif rtime == 0: repl_state = "Replication State: Replica has not seen any changes from the Supplier" elif mtime > rtime: - repl_state = "Replication State: Replica is behind Supplier by: {} seconds".format(mtime - rtime) + repl_state = f"Replication State: Replica is behind Supplier by: {mtime - rtime} seconds" elif mtime < rtime: - repl_state = "Replication State: Replica is ahead of Supplier by: {} seconds".format(rtime - mtime) + repl_state = f"Replication State: Replica is ahead of Supplier by: {rtime - mtime} seconds" else: repl_state = "Replication State: Supplier and Replica are in perfect synchronization" @@ -928,7 +928,7 @@ def check_for_diffs(mentries, mglue, rentries, rglue, report, opts): return report -def validate_suffix(ldapnode, suffix, hostname): +def validate_suffix(ldapnode, suffix, hostname, port): """Validate that the suffix exists :param ldapnode - The LDAP object :param suffix - The suffix to validate @@ -938,10 +938,11 @@ def validate_suffix(ldapnode, suffix, hostname): try: ldapnode.search_s(suffix, ldap.SCOPE_BASE) except ldap.NO_SUCH_OBJECT: - print("Error: Failed to validate suffix in {}. {} does not exist.".format(hostname, suffix)) + print(f"Error: Failed to validate suffix in {hostname}:{port}. {suffix} " + + "does not exist. Replica might need to be initialized.") return False except ldap.LDAPError as e: - print("Error: failed to validate suffix in {} ({}). ".format(hostname, str(e))) + print(f"Error: failed to validate suffix in {hostname}:{port} ({str(e)}). ") return False # Check suffix is replicated @@ -949,10 +950,10 @@ def validate_suffix(ldapnode, suffix, hostname): replica_filter = "(&(objectclass=nsds5replica)(nsDS5ReplicaRoot=%s))" % suffix supplier_replica = ldapnode.search_s("cn=config",ldap.SCOPE_SUBTREE,replica_filter) if (len(supplier_replica) != 1): - print("Error: Failed to validate suffix in {}. {} is not replicated.".format(hostname, suffix)) + print(f"Error: Failed to validate suffix in {hostname}:{port}. {suffix} is not replicated.") return False except ldap.LDAPError as e: - print("Error: failed to validate suffix in {} ({}). ".format(hostname, str(e))) + print(f"Error: failed to validate suffix in {hostname}:{port} ({str(e)}). ") return False return True @@ -1034,10 +1035,10 @@ def connect_to_replicas(opts): # Validate suffix if opts['verbose']: print ("Validating suffix ...") - if not validate_suffix(supplier, opts['suffix'], opts['mhost']): + if not validate_suffix(supplier, opts['suffix'], opts['mhost'], opts['mport']): sys.exit(1) - if not validate_suffix(replica,opts['suffix'], opts['rhost']): + if not validate_suffix(replica,opts['suffix'], opts['rhost'], opts['rport']): sys.exit(1) # Get the RUVs @@ -1048,8 +1049,11 @@ def connect_to_replicas(opts): if len(supplier_ruv) > 0: opts['supplier_ruv'] = ensure_list_str(supplier_ruv[0][1]['nsds50ruv']) else: - print("Error: Supplier does not have an RUV entry") + print("Error: Supplier does not have an RUV entry. It might need to be initialized.") sys.exit(1) + except ldap.NO_SUCH_OBJECT: + print("Error: Supplier does not have an RUV entry. It might need to be initialized.") + sys.exit(1) except ldap.LDAPError as e: print("Error: Failed to get Supplier RUV entry: {}".format(str(e))) sys.exit(1) @@ -1061,8 +1065,11 @@ def connect_to_replicas(opts): if len(replica_ruv) > 0: opts['replica_ruv'] = ensure_list_str(replica_ruv[0][1]['nsds50ruv']) else: - print("Error: Replica does not have an RUV entry") + print("Error: Replica does not have an RUV entry. It might need to be initialized.") sys.exit(1) + except ldap.NO_SUCH_OBJECT: + print("Error: Replica does not have an RUV entry. It might need to be initialized.") + sys.exit(1) except ldap.LDAPError as e: print("Error: Failed to get Replica RUV entry: {}".format(str(e))) sys.exit(1) diff --git a/src/cockpit/389-console/src/lib/replication/replTasks.jsx b/src/cockpit/389-console/src/lib/replication/replTasks.jsx index 9387af325..d592995f8 100644 --- a/src/cockpit/389-console/src/lib/replication/replTasks.jsx +++ b/src/cockpit/389-console/src/lib/replication/replTasks.jsx @@ -345,7 +345,7 @@ export class ReplRUV extends React.Component { if (localRID == "") { localRUV = - <div className="ds-indent"> + <div className="ds-indent ds-margin-top"> <i> There is no local RUV, the database might not have been initialized yet. </i> diff --git a/src/cockpit/389-console/src/replication.jsx b/src/cockpit/389-console/src/replication.jsx index 0f9d2297a..59d3e4d9a 100644 --- a/src/cockpit/389-console/src/replication.jsx +++ b/src/cockpit/389-console/src/replication.jsx @@ -880,7 +880,8 @@ export class Replication extends React.Component { }) .fail(err => { const errMsg = JSON.parse(err); - if (errMsg.desc !== "No such object") { + if (errMsg.desc !== "No such object" && + !errMsg.desc.includes('There is no RUV for suffix')) { this.props.addNotification( "error", `Error loading suffix RUV - ${errMsg.desc}` diff --git a/src/lib389/lib389/cli_conf/replication.py b/src/lib389/lib389/cli_conf/replication.py index abd4b2226..b6f9861c1 100644 --- a/src/lib389/lib389/cli_conf/replication.py +++ b/src/lib389/lib389/cli_conf/replication.py @@ -112,10 +112,15 @@ def _args_to_attrs(args): # def get_ruv(inst, basedn, log, args): replicas = Replicas(inst) - replica = replicas.get(args.suffix) + try: + replica = replicas.get(args.suffix) + except ldap.NO_SUCH_OBJECT: + raise ValueError(f"Suffix '{args.suffix}' is not configured for replication.") ruv = replica.get_ruv() ruv_dict = ruv.format_ruv() ruvs = ruv_dict['ruvs'] + if len(ruvs) == 0: + raise ValueError(f"There is no RUV for suffix {args.suffix}. Replica is not initialized.") if args and args.json: log.info(json.dumps({"type": "list", "items": ruvs}, indent=4)) else: diff --git a/src/lib389/lib389/config.py b/src/lib389/lib389/config.py index 3028ca9c2..a7f1b545e 100644 --- a/src/lib389/lib389/config.py +++ b/src/lib389/lib389/config.py @@ -210,7 +210,7 @@ class Config(DSLdapObject): yield report def _lint_passwordscheme(self): - allowed_schemes = ['SSHA512', 'PBKDF2-SHA512', 'GOST_YESCRYPT'] + allowed_schemes = ['PBKDF2-SHA512', 'PBKDF2_SHA256', 'PBKDF2_SHA512', 'GOST_YESCRYPT'] 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: diff --git a/src/lib389/lib389/lint.py b/src/lib389/lib389/lint.py index ce23d5c12..0219801f4 100644 --- a/src/lib389/lib389/lint.py +++ b/src/lib389/lib389/lint.py @@ -310,6 +310,16 @@ because the consumer server is not reachable.""", 'fix': """Check if the consumer is running, and also check the errors log for more information.""" } +DSREPLLE0006 = { + 'dsle': 'DSREPLLE0006', + 'severity': 'MEDIUM', + 'description': 'Replication has not been initilaized', + 'items': ['Replication'], + 'detail': """The replication for "SUFFIX" does not appear to be initialzied, +because there is no RUV found for the suffix.""", + 'fix': """Initialize this replica from a primary supplier replica""" +} + # Replication changelog DSCLLE0001 = { 'dsle': 'DSCLLE0001', diff --git a/src/lib389/lib389/replica.py b/src/lib389/lib389/replica.py index 1ea9fedcb..e899ed45f 100644 --- a/src/lib389/lib389/replica.py +++ b/src/lib389/lib389/replica.py @@ -45,7 +45,7 @@ from lib389.idm.services import ServiceAccounts from lib389.idm.organizationalunit import OrganizationalUnits from lib389.conflicts import ConflictEntries from lib389.lint import (DSREPLLE0001, DSREPLLE0002, DSREPLLE0003, DSREPLLE0004, - DSREPLLE0005, DSCLLE0001) + DSREPLLE0005, DSREPLLE0006, DSCLLE0001) class ReplicaLegacy(object): @@ -1283,6 +1283,20 @@ class Replica(DSLdapObject): report['check'] = f'replication:conflicts' yield report + def _lint_no_ruv(self): + # No RUV means replica has not been initialized + replicas = Replicas(self._instance).list() + for replica in replicas: + ruv = replica.get_ruv() + ruv_dict = ruv.format_ruv() + ruvs = ruv_dict['ruvs'] + suffix = replica.get_suffix() + if len(ruvs) == 0: + report = copy.deepcopy(DSREPLLE0006) + report['detail'] = report['detail'].replace('SUFFIX', suffix) + report['check'] = 'replication' + yield report + def _validate(self, rdn, properties, basedn): (tdn, str_props) = super(Replica, self)._validate(rdn, properties, basedn) # We override the tdn here. We use the MT for the suffix. @@ -1649,8 +1663,8 @@ class Replica(DSLdapObject): serverctrls=self._server_controls, clientctrls=self._client_controls, escapehatch='i am sure')[0] data = ensure_list_str(ent.getValues('nsds50ruv')) - except IndexError: - # There is no ruv entry, it's okay + except (IndexError, ldap.NO_SUCH_OBJECT): + # There are no ruv elements, it's okay pass return RUV(data)
0
0fe78df27bea0ed29f5f74266bc530832e0d8906
389ds/389-ds-base
Ticket 47813 - managed entry plugin fails to update member pointer on modrdn operation Bug Description: A modrdn on an existing managed entry failed to update the entry pointer becuase part of the update is to add the managed entry objectclass - which already exists in the managed entry. This caused the new pointer value to not be added to the managed entry. Fix Description: During a modrdn operation perform the objectclass addition in a separate operation, as we don't know if the entry already has the objectclass or not. https://fedorahosted.org/389/ticket/47813 TET: passed Jenkins: passed Reviewed by: rmeggins(Thanks!)
commit 0fe78df27bea0ed29f5f74266bc530832e0d8906 Author: Mark Reynolds <[email protected]> Date: Mon Jun 9 12:27:04 2014 -0400 Ticket 47813 - managed entry plugin fails to update member pointer on modrdn operation Bug Description: A modrdn on an existing managed entry failed to update the entry pointer becuase part of the update is to add the managed entry objectclass - which already exists in the managed entry. This caused the new pointer value to not be added to the managed entry. Fix Description: During a modrdn operation perform the objectclass addition in a separate operation, as we don't know if the entry already has the objectclass or not. https://fedorahosted.org/389/ticket/47813 TET: passed Jenkins: passed Reviewed by: rmeggins(Thanks!) diff --git a/ldap/servers/plugins/mep/mep.c b/ldap/servers/plugins/mep/mep.c index 6dbddbca5..76ba827e6 100644 --- a/ldap/servers/plugins/mep/mep.c +++ b/ldap/servers/plugins/mep/mep.c @@ -1442,38 +1442,57 @@ mep_add_managed_entry(struct configEntry *config, /* Add forward link to origin entry. */ LDAPMod oc_mod; LDAPMod pointer_mod; - LDAPMod *mods[3]; + LDAPMod *mods[2]; char *oc_vals[2]; char *pointer_vals[2]; /* Clear out the pblock for reuse. */ slapi_pblock_init(mod_pb); - /* Add the origin entry objectclass. */ + /* + * Add the origin entry objectclass. Do not check the result + * as we could be here because of a modrdn operation - in which + * case the objectclass already exists. + */ oc_vals[0] = MEP_ORIGIN_OC; oc_vals[1] = 0; oc_mod.mod_op = LDAP_MOD_ADD; oc_mod.mod_type = SLAPI_ATTR_OBJECTCLASS; oc_mod.mod_values = oc_vals; + mods[0] = &oc_mod; + mods[1] = NULL; - /* Add a pointer to the managed entry. */ + /* add the objectclass */ + slapi_modify_internal_set_pb_ext(mod_pb, slapi_entry_get_sdn(origin), + mods, 0, 0, mep_get_plugin_id(), 0); + slapi_modify_internal_pb(mod_pb); + slapi_pblock_get(mod_pb, SLAPI_PLUGIN_INTOP_RESULT, &result); + if (result != LDAP_SUCCESS && result != LDAP_TYPE_OR_VALUE_EXISTS){ + slapi_log_error(SLAPI_LOG_FATAL, MEP_PLUGIN_SUBSYSTEM, + "mep_add_managed_entry: Failed to add managed entry " + "objectclass in origin entry \"%s\", error (%s)\n", + slapi_entry_get_dn(origin), ldap_err2string(result)); + goto bail; + } + slapi_pblock_init(mod_pb); + + /* + * Now, add a pointer to the managed entry. + */ pointer_vals[0] = managed_dn; pointer_vals[1] = 0; pointer_mod.mod_op = LDAP_MOD_ADD; pointer_mod.mod_type = MEP_MANAGED_ENTRY_TYPE; pointer_mod.mod_values = pointer_vals; + mods[0] = &pointer_mod; + mods[1] = NULL; - mods[0] = &oc_mod; - mods[1] = &pointer_mod; - mods[2] = 0; - - /* Perform the modify operation. */ slapi_log_error(SLAPI_LOG_PLUGIN, MEP_PLUGIN_SUBSYSTEM, "Adding %s pointer to \"%s\" in entry \"%s\"\n.", MEP_MANAGED_ENTRY_TYPE, managed_dn, slapi_entry_get_dn(origin)); - slapi_modify_internal_set_pb_ext(mod_pb, - slapi_entry_get_sdn(origin), - mods, 0, 0, mep_get_plugin_id(), 0); + + slapi_modify_internal_set_pb_ext(mod_pb, slapi_entry_get_sdn(origin), + mods, 0, 0, mep_get_plugin_id(), 0); slapi_modify_internal_pb(mod_pb); slapi_pblock_get(mod_pb, SLAPI_PLUGIN_INTOP_RESULT, &result);
0
9d736d685f285fcfcaeb7d56ebc508b2522776ef
389ds/389-ds-base
Issue 48081 - Add new CI tests for password Description: Added new tests in the password suite, performing extended password modify operations. https://pagure.io/389-ds-base/issue/48081 Reviewed by: spichugi(Thanks!)
commit 9d736d685f285fcfcaeb7d56ebc508b2522776ef Author: Akshay Adhikari <[email protected]> Date: Wed Oct 3 16:47:05 2018 +0530 Issue 48081 - Add new CI tests for password Description: Added new tests in the password suite, performing extended password modify operations. https://pagure.io/389-ds-base/issue/48081 Reviewed by: spichugi(Thanks!) diff --git a/dirsrvtests/tests/suites/password/pwdModify_test.py b/dirsrvtests/tests/suites/password/pwdModify_test.py new file mode 100644 index 000000000..3a554cb3c --- /dev/null +++ b/dirsrvtests/tests/suites/password/pwdModify_test.py @@ -0,0 +1,267 @@ +# 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 pytest +import subprocess +import re +from ldap.controls import LDAPControl +from lib389._constants import * +from lib389.tasks import * +from lib389.utils import * +from lib389.topologies import topology_st as topo +from lib389.idm.user import UserAccounts, TEST_USER_PROPERTIES +from lib389.idm.organizationalunit import OrganizationalUnits +from lib389.idm.nscontainer import nsContainers +from lib389.pwpolicy import PwPolicyManager + +DEBUGGING = os.getenv("DEBUGGING", default=False) +if DEBUGGING: + logging.getLogger(__name__).setLevel(logging.DEBUG) +else: + logging.getLogger(__name__).setLevel(logging.INFO) +log = logging.getLogger(__name__) + + +OLD_PASSWD = 'password' +NEW_PASSWD = 'newpassword' +SHORT_PASSWD = 'wd' +TESTPEOPLE_OU = "TestPeople_bug834047" + + [email protected](scope="function") +def pwd_policy_setup(topo, request): + """ + Setup to set passwordStorageScheme as CLEAR + passwordHistory to on + passwordStorageScheme to SSHA + passwordHistory off + """ + log.info("Change the pwd storage type to clear and change the password once to refresh it(for the rest of tests") + topo.standalone.config.set('passwordStorageScheme', 'CLEAR') + assert topo.standalone.passwd_s(user_2.dn, OLD_PASSWD, NEW_PASSWD) + topo.standalone.config.set('passwordHistory', 'on') + + def fin(): + topo.standalone.simple_bind_s(DN_DM, PASSWORD) + topo.standalone.config.set('passwordStorageScheme', 'SSHA') + topo.standalone.config.set('passwordHistory', 'off') + request.addfinalizer(fin) + + +def test_pwd_modify_with_different_operation(topo): + """Performing various password modify operation, + make sure that password is actually modified + + :id: e36d68a8-0960-48e4-932c-6c2f64abaebc + :setup: Standalone instance and TLS enabled + :steps: + 1. Attempt for Password change for an entry that does not exists + 2. Attempt for Password change for an entry that exists + 3. Attempt for Password change to old for an entry that exists + 4. Attempt for Password Change with Binddn as testuser but with wrong old password + 5. Attempt for Password Change with Binddn as testuser + 6. Attempt for Password Change without giving newpassword + 7. Checking password change Operation using a Non-Secure connection + 8. Testuser attempts to change password for testuser2(userPassword attribute is Set) + 9. Directory Manager attempts to change password for testuser2(userPassword attribute is Set) + 10. Create a password syntax policy. Attempt to change to password that violates that policy + 11. userPassword mod with control results in ber decode error + + :expectedresults: + 1. Operation should be successful + 2. Operation should be successful + 3. Operation should be successful + 4. Operation should not be successful + 5. Operation should be successful + 6. Operation should be successful + 7. Operation should not be successful + 8. Operation should not be successful + 9. Operation should be successful + 10. Operation should violates the policy + 11. Operation should be successful + """ + topo.standalone.enable_tls() + os.environ["LDAPTLS_CACERTDIR"] = topo.standalone.get_ssca_dir() + users = UserAccounts(topo.standalone, DEFAULT_SUFFIX) + TEST_USER_PROPERTIES['userpassword'] = OLD_PASSWD + global user + user = users.create(properties=TEST_USER_PROPERTIES) + with pytest.raises(ldap.NO_SUCH_OBJECT): + log.info("Attempt for Password change for an entry that does not exists") + assert topo.standalone.passwd_s('uid=testuser1,ou=People,dc=example,dc=com', OLD_PASSWD, NEW_PASSWD) + log.info("Attempt for Password change for an entry that exists") + assert topo.standalone.passwd_s(user.dn, OLD_PASSWD, NEW_PASSWD) + log.info("Attempt for Password change to old for an entry that exists") + assert topo.standalone.passwd_s(user.dn, NEW_PASSWD, OLD_PASSWD) + log.info("Attempt for Password Change with Binddn as testuser but with wrong old password") + topo.standalone.simple_bind_s(user.dn, OLD_PASSWD) + with pytest.raises(ldap.INVALID_CREDENTIALS): + topo.standalone.passwd_s(user.dn, NEW_PASSWD, NEW_PASSWD) + log.info("Attempt for Password Change with Binddn as testuser") + assert topo.standalone.passwd_s(user.dn, OLD_PASSWD, NEW_PASSWD) + log.info("Attempt for Password Change without giving newpassword") + assert topo.standalone.passwd_s(user.dn, None, OLD_PASSWD) + assert user.get_attr_val_utf8('uid') == 'testuser' + log.info("Change password to NEW_PASSWD i.e newpassword") + assert topo.standalone.passwd_s(user.dn, None, NEW_PASSWD) + assert topo.standalone.passwd_s(user.dn, NEW_PASSWD, None) + log.info("Check binding with old/new password") + password = [OLD_PASSWD, NEW_PASSWD] + for pass_val in password: + with pytest.raises(ldap.INVALID_CREDENTIALS): + topo.standalone.simple_bind_s(user.dn, pass_val) + log.info("Change password back to OLD_PASSWD i.e password") + topo.standalone.simple_bind_s(DN_DM, PASSWORD) + assert topo.standalone.passwd_s(user.dn, None, NEW_PASSWD) + log.info("Checking password change Operation using a Non-Secure connection") + conn = ldap.initialize("ldap://%s:%s" % (HOST_STANDALONE, PORT_STANDALONE)) + with pytest.raises(ldap.CONFIDENTIALITY_REQUIRED): + conn.passwd_s(user.dn, NEW_PASSWD, OLD_PASSWD) + log.info("Testuser attempts to change password for testuser2(userPassword attribute is Set)") + global user_2 + users = UserAccounts(topo.standalone, DEFAULT_SUFFIX) + user_2 = users.create(properties={ + 'uid': 'testuser2', + 'cn': 'testuser2', + 'sn': 'testuser2', + 'uidNumber': '3000', + 'gidNumber': '4000', + 'homeDirectory': '/home/testuser2', + 'userPassword': OLD_PASSWD + }) + topo.standalone.simple_bind_s(user.dn, NEW_PASSWD) + with pytest.raises(ldap.INSUFFICIENT_ACCESS): + assert topo.standalone.passwd_s(user_2.dn, OLD_PASSWD, NEW_PASSWD) + log.info("Directory Manager attempts to change password for testuser2(userPassword attribute is Set)") + topo.standalone.simple_bind_s(DN_DM, PASSWORD) + assert topo.standalone.passwd_s(user_2.dn, OLD_PASSWD, NEW_PASSWD) + log.info("Changing userPassword attribute to Undefined for testuser2") + topo.standalone.modify_s(user_2.dn, [(ldap.MOD_REPLACE, 'userPassword', None)]) + log.info("Testuser attempts to change password for testuser2(userPassword attribute is Undefined)") + with pytest.raises(ldap.INSUFFICIENT_ACCESS): + topo.standalone.simple_bind_s(user.dn, NEW_PASSWD) + assert topo.standalone.passwd_s(user_2.dn, None, NEW_PASSWD) + log.info("Directory Manager attempts to change password for testuser2(userPassword attribute is Undefined)") + topo.standalone.simple_bind_s(DN_DM, PASSWORD) + assert topo.standalone.passwd_s(user_2.dn, None, OLD_PASSWD) + log.info("Create a password syntax policy. Attempt to change to password that violates that policy") + topo.standalone.config.set('PasswordCheckSyntax', 'on') + with pytest.raises(ldap.CONSTRAINT_VIOLATION): + assert topo.standalone.passwd_s(user_2.dn, OLD_PASSWD, SHORT_PASSWD) + log.info("Reset password syntax policy") + topo.standalone.config.set('PasswordCheckSyntax', 'off') + log.info("userPassword mod with control results in ber decode error") + topo.standalone.simple_bind_s(DN_DM, PASSWORD) + assert topo.standalone.modify_ext_s(user.dn, [(ldap.MOD_REPLACE, 'userpassword', b'abcdefg')], + serverctrls=[LDAPControl('2.16.840.1.113730.3.4.2', 1, None)]) + log.info("Reseting the testuser's password") + topo.standalone.passwd_s(user.dn, 'abcdefg', NEW_PASSWD) + + +def test_pwd_modify_with_password_policy(topo, pwd_policy_setup): + """Performing various password modify operation, + with passwordStorageScheme as CLEAR + passwordHistory to on + + :id: 200bf0fd-20ab-4dde-849e-54067e98b917 + :setup: Standalone instance (TLS enabled) with pwd_policy_setup + :steps: + 1. Change the password and check that a new entry has been added to the history + 2. Try changing password to one stored in history + 3. Change the password several times in a row, and try binding after each change + 4. Try to bind using short password + + :expectedresults: + 1. Operation should be successful + 2. Operation should be unsuccessful + 3. Operation should be successful + 4. Operation should be unsuccessful + """ + log.info("Change the password and check that a new entry has been added to the history") + topo.standalone.passwd_s(user_2.dn, NEW_PASSWD, OLD_PASSWD) + regex = re.search('Z(.+)', user_2.get_attr_val_utf8('passwordhistory')) + assert NEW_PASSWD == regex.group(1) + log.info("Try changing password to one stored in history. Should fail") + with pytest.raises(ldap.CONSTRAINT_VIOLATION): + assert topo.standalone.passwd_s(user_2.dn, OLD_PASSWD, NEW_PASSWD) + log.info("Change the password several times in a row, and try binding after each change") + topo.standalone.passwd_s(user.dn, NEW_PASSWD, OLD_PASSWD) + assert topo.standalone.simple_bind_s(user.dn, OLD_PASSWD) + topo.standalone.passwd_s(user.dn, OLD_PASSWD, SHORT_PASSWD) + assert topo.standalone.simple_bind_s(user.dn, SHORT_PASSWD) + with pytest.raises(ldap.CONSTRAINT_VIOLATION): + topo.standalone.passwd_s(user.dn, SHORT_PASSWD, OLD_PASSWD) + + +def test_pwd_modify_with_subsuffix(topo): + """Performing various password modify operation. + + :id: 2255b4e6-3546-4ec5-84a5-cd8b3d894ac5 + :setup: Standalone instance (TLS enabled) + :steps: + 1. Add a new SubSuffix & password policy + 2. Add two New users under the SubEntry + 3. Change password of uid=test_user0,ou=TestPeople_bug834047,dc=example,dc=com to newpassword + 4. Try to delete password- case when password is specified + 5. Try to delete password- case when password is not specified + + :expectedresults: + 1. Operation should be successful + 2. Operation should be successful + 3. Operation should be successful + 4. Operation should be successful + 5. Operation should be successful + """ + + log.info("Add a new SubSuffix") + ous = OrganizationalUnits(topo.standalone, DEFAULT_SUFFIX) + ou_temp = ous.create(properties={'ou': TESTPEOPLE_OU}) + + log.info("Add the container & create password policies") + policy = PwPolicyManager(topo.standalone) + policy.create_subtree_policy(ou_temp.dn, properties={ + 'passwordHistory': 'on', + 'passwordInHistory': '6', + 'passwordChange': 'on', + 'passwordStorageScheme': 'CLEAR'}) + + log.info("Add two New users under the SubEntry") + user = UserAccounts(topo.standalone, DEFAULT_SUFFIX, rdn='ou=TestPeople_bug834047') + test_user0 = user.create(properties={ + 'uid': 'test_user0', + 'cn': 'test0', + 'sn': 'test0', + 'uidNumber': '3002', + 'gidNumber': '4002', + 'homeDirectory': '/home/test_user0', + 'userPassword': OLD_PASSWD + }) + test_user1 = user.create(properties={ + 'uid': 'test_user1', + 'cn': 'test1', + 'sn': 'test1', + 'uidNumber': '3003', + 'gidNumber': '4003', + 'homeDirectory': '/home/test_user3', + 'userPassword': OLD_PASSWD + }) + log.info(f"Changing password of {test_user0.dn} to newpassword") + topo.standalone.simple_bind_s(test_user0.dn, OLD_PASSWD) + topo.standalone.modify_s(test_user0.dn, [(ldap.MOD_REPLACE, 'userPassword', ensure_bytes(NEW_PASSWD))]) + topo.standalone.simple_bind_s(test_user0.dn, NEW_PASSWD) + log.info("Try to delete password- case when password is specified") + topo.standalone.modify_s(test_user0.dn, [(ldap.MOD_DELETE, 'userPassword', ensure_bytes(NEW_PASSWD))]) + topo.standalone.simple_bind_s(test_user1.dn, OLD_PASSWD) + log.info("Try to delete password- case when password is not specified") + topo.standalone.modify_s(test_user1.dn, [(ldap.MOD_DELETE, 'userPassword', None)]) + + +if __name__ == '__main__': + # Run isolated + # -s for DEBUG mode + CURRENT_FILE = os.path.realpath(__file__) + pytest.main(["-s", CURRENT_FILE])
0
cafc4eb7a16e5ee4b90922fa0000e86d35290030
389ds/389-ds-base
Ticket 47588 - Compiler warnings building on F19 This addresses a few compiler warnings that show up when building on F19. The issues are minor (unused typedef and an incorrect usage of memset in some debugging ifdef'd code).
commit cafc4eb7a16e5ee4b90922fa0000e86d35290030 Author: Nathan Kinder <[email protected]> Date: Fri Nov 8 11:01:19 2013 -0800 Ticket 47588 - Compiler warnings building on F19 This addresses a few compiler warnings that show up when building on F19. The issues are minor (unused typedef and an incorrect usage of memset in some debugging ifdef'd code). diff --git a/ldap/servers/slapd/pw.c b/ldap/servers/slapd/pw.c index 8d7375361..37fef74bb 100644 --- a/ldap/servers/slapd/pw.c +++ b/ldap/servers/slapd/pw.c @@ -447,7 +447,6 @@ pw_rever_decode(char *cipher, char **plain, const char * attr_name) { if (slapi_attr_types_equivalent(L_attr, attr_name)) { - typedef int (*CMPFP)(char *, char *); typedef char * (*ENCFP)(char *); pwsp = (struct pw_scheme *) slapi_ch_calloc (1, sizeof(struct pw_scheme)); @@ -523,7 +522,6 @@ pw_rever_encode(Slapi_Value **vals, char * attr_name) { if (slapi_attr_types_equivalent(L_attr, attr_name)) { - typedef int (*CMPFP)(char *, char *); typedef char * (*ENCFP)(char *); pwsp = (struct pw_scheme *) slapi_ch_calloc (1, sizeof(struct pw_scheme)); diff --git a/lib/base/pool.cpp b/lib/base/pool.cpp index 657e8c6c5..433fc58c5 100644 --- a/lib/base/pool.cpp +++ b/lib/base/pool.cpp @@ -209,7 +209,7 @@ _free_block(block_t *block) PERM_FREE(block->data); #ifdef POOL_ZERO_DEBUG - memset(block, 0xa, sizeof(block)); + memset(block, 0xa, sizeof(block_t)); #endif /* POOL_ZERO_DEBUG */ PERM_FREE(block); @@ -340,7 +340,7 @@ pool_destroy(pool_handle_t *pool_handle) crit_exit(known_pools_lock); #ifdef POOL_ZERO_DEBUG - memset(pool, 0xa, sizeof(pool)); + memset(pool, 0xa, sizeof(pool_t)); #endif /* POOL_ZERO_DEBUG */ PERM_FREE(pool);
0
ba5900eeb9a53e1fbe347a9de40d242d173daf7e
389ds/389-ds-base
Ticket 49806 - Add SASL functionality to CLI/UI Description: Add SASL functionality to dsconf and UI Improved installer to load the template-sasl ldif file. Also cleaned up some of the "clear form" functions to be more efficient using jquery. https://pagure.io/389-ds-base/issue/49806 Reviewed by: spichugi(Thanks!)
commit ba5900eeb9a53e1fbe347a9de40d242d173daf7e Author: Mark Reynolds <[email protected]> Date: Wed Jul 11 15:48:34 2018 -0400 Ticket 49806 - Add SASL functionality to CLI/UI Description: Add SASL functionality to dsconf and UI Improved installer to load the template-sasl ldif file. Also cleaned up some of the "clear form" functions to be more efficient using jquery. https://pagure.io/389-ds-base/issue/49806 Reviewed by: spichugi(Thanks!) diff --git a/src/cockpit/389-console/index.html b/src/cockpit/389-console/index.html index 211693baa..3900cb45e 100644 --- a/src/cockpit/389-console/index.html +++ b/src/cockpit/389-console/index.html @@ -407,36 +407,36 @@ <div class="ds-inline"> <div> <label for="create-inst-serverid" class="ds-config-label" title="The instance name, this is what gets appended to \"slapi-\""> - Instance Name</label><input class="ds-input" type="text" id="create-inst-serverid" placeholder="Your_Instance_Name" required /> + Instance Name</label><input class="ds-input ds-inst-input" type="text" id="create-inst-serverid" placeholder="Your_Instance_Name" required /> </div> <div> <label for="create-inst-port" class="ds-config-label" title="The server port number"> - Port</label><input class="ds-input" type="text" value="389" id="create-inst-port" required /> + Port</label><input class="ds-input ds-inst-input" type="text" value="389" id="create-inst-port" required /> </div> <div> <label for="create-inst-secureport" class="ds-config-label" title="The secure port number for TLS connections"> - Secure Port</label><input class="ds-input" type="text" value="636" id="create-inst-secureport" required /> + Secure Port</label><input class="ds-input ds-inst-input" type="text" value="636" id="create-inst-secureport" required /> </div> <div> <label for="create-inst-rootdn" class="ds-config-label" title="The DN for the unrestricted user"> - Directory Manager DN</label><input class="ds-input" value="cn=Directory Manager" type="text" id="create-inst-rootdn" required /> + Directory Manager DN</label><input class="ds-input ds-inst-input" value="cn=Directory Manager" type="text" id="create-inst-rootdn" required /> </div> <div> <label for="rootdn-pw" class="ds-config-label" title="Directory Manager password.">Directory Manager Password</label><input - class="ds-input" type="password" placeholder="Enter password" id="rootdn-pw" name="name" required> + class="ds-input ds-inst-input" type="password" placeholder="Enter password" id="rootdn-pw" name="name" required> </div> <div> <label for="rootdn-pw-confirm" class="ds-config-label" title="Confirm password">Confirm Password</label><input - class="ds-input" type="password" placeholder="Confirm password" id="rootdn-pw-confirm" name="name" required> + class="ds-input ds-inst-input" type="password" placeholder="Confirm password" id="rootdn-pw-confirm" name="name" required> </div> <hr> <div> <label for="backend-name" class="ds-config-label" title="The backend name, like 'userroot'">Backend Name (optional)</label><input - class="ds-input" type="text" id="backend-name"> + class="ds-input ds-inst-input" type="text" id="backend-name"> </div> <div> <label for="backend-suffix" class="ds-config-label" title="Database suffix, like 'dc=example,dc=com'">Backend Suffix (optional)</label><input - class="ds-input" type="text" id="backend-suffix"> + class="ds-input ds-inst-input" type="text" id="backend-suffix"> </div> <div> <label for="create-sample-entries" class="ds-config-label" title="Create sample entries in the suffix">Create Sample Entries </label><input @@ -509,6 +509,9 @@ <div id="not-running" class="all-pages ds-center" hidden> <h3>This server instance is not running, either start it from the <b>Actions</b> dropdown menu, or choose a different instance</h3> </div> + <div id="no-connect" class="all-pages ds-center" hidden> + <h3>This server instance is running, but we can not connect to it. Check LDAPI is properly configured on this instance.</h3> + </div> <div id="server-content" class="all-pages" hidden> </div> diff --git a/src/cockpit/389-console/js/backend.js b/src/cockpit/389-console/js/backend.js index 4750dafb3..2c5a3fd50 100644 --- a/src/cockpit/389-console/js/backend.js +++ b/src/cockpit/389-console/js/backend.js @@ -442,7 +442,7 @@ $(document).ready( function() { } - $(".index-type").attr('readonly', 'readonly'); + $(".index-type").attr('readonly', true); if ( $("#manual-cache").is(":checked") ){ $("#auto-cache-form").hide(); diff --git a/src/cockpit/389-console/js/ds.js b/src/cockpit/389-console/js/ds.js index 6b343266a..540a2943a 100644 --- a/src/cockpit/389-console/js/ds.js +++ b/src/cockpit/389-console/js/ds.js @@ -110,19 +110,29 @@ function check_for_389 () { }); } -function check_inst_alive () { +function check_inst_alive (connect_err) { // Check if this instance is started, if not hide configuration pages + if (connect_err === undefined) { + connect_err = 0; + } cmd = ['status-dirsrv', server_inst]; - console.log("MARK cmd: " + cmd); cockpit.spawn(cmd, { superuser: true }).done(function () { - $(".all-pages").hide(); - $("#ds-navigation").show(); - $("#server-content").show(); - $("#server-config").show(); - //$("#no-instances").hide(); - //$("#no-package").hide(); - $("#not-running").hide(); - console.log("Running"); + if (connect_err) { + $("#ds-navigation").hide(); + $(".all-pages").hide(); + $("#no-connect").show(); + + } else { + $(".all-pages").hide(); + $("#ds-navigation").show(); + $("#server-content").show(); + $("#server-config").show(); + //$("#no-instances").hide(); + //$("#no-package").hide(); + $("#not-running").hide(); + $("#no_connect").hide(); + console.log("Running"); + } }).fail(function(data) { $("#ds-navigation").hide(); $(".all-pages").hide(); @@ -180,7 +190,7 @@ function get_insts() { $("#server-config").show(); server_id = insts[0]; server_inst = insts[0].replace("slapd-", ""); - get_and_set_config(); + load_config(); } $("body").show(); @@ -256,6 +266,7 @@ function save_all () { function load_config (){ // TODO - set all the pages get_and_set_config(); // cn=config stuff + get_and_set_sasl(); // Fill in sasl mapping table } $(window.document).ready(function() { diff --git a/src/cockpit/389-console/js/servers.js b/src/cockpit/389-console/js/servers.js index c5ae83701..358987d9a 100644 --- a/src/cockpit/389-console/js/servers.js +++ b/src/cockpit/389-console/js/servers.js @@ -6,8 +6,7 @@ var sasl_action_html = '<span class="caret"></span>' + '</button>' + '<ul class="dropdown-menu ds-agmt-dropdown" role="menu" aria-labelledby="dropdownMenu1">' + - '<li role=""><a role="menuitem" class="sasl-edit-btn" tabindex="0" href="#">Edit Mapping</a></li>' + - '<li role=""><a role="menuitem" class="sasl-verify-btn" tabindex="0" href="#">Test Mapping</a></li>' + + '<li role=""><a role="menuitem" class="sasl-edit-btn" tabindex="2" href="#">Edit Mapping</a></li>' + '<li role=""><a role="menuitem" class="sasl-del-btn" tabindex="1" href="#">Delete Mapping</a></li>' + '</ul>' + '</div>'; @@ -74,77 +73,30 @@ var create_inf_template = "self_sign_cert = SELF_SIGN\n"; +var sasl_table; + function load_server_config() { var mark = document.getElementById("server-config-title"); mark.innerHTML = "Configuration for server: <b>" + server_id + "</b>"; } -function server_hide_all(){ - // Jquery can problem do this better using names/roles - $("#server-config").hide(); - $("#server-security").hide(); - $("#server-logs").hide(); - $("#server-pwpolicy").hide(); - $("#server-tuning").hide(); - $("#server-tuning").hide(); -}; - function clear_sasl_map_form () { - $("#sasl-map-name").val(""); - $("#sasl-map-regex").val(""); - $("#sasl-map-base").val(""); - $("#sasl-map-filter").val(""); - $("#sasl-map-priority").val(""); + $(".ds-modal-error").hide(); + $(".sasl-input").val(""); + $(".sasl-input").css("border-color", "initial"); } function clear_local_pwp_form () { - $("#local-entry-dn").val(""); - $("#local-passwordtrackupdatetime").prop('checked', false); - $("#local-passwordadmindn").val(""); - $("#local-passwordchange").prop('checked', false); - $("#local-passwordmustchange").prop('checked', false); - $("#local-passwordhistory").prop('checked', false); - $("#local-passwordinhistory").val(""); - $("#local-passwordminage").val(""); - $("#local-passwordexp").prop('checked', false); - $("#local-passwordmaxage").val(""); - $("#local-passwordgracelimit").val(""); - $("#local-passwordwarning").val(""); - $("#local-passwordsendexpiringtime").prop('checked', false); - $("#local-passwordlockout").prop('checked', false); - $("#local-passwordmaxfailure").val(""); - $("#local-passwordresetfailurecount").val(""); - $("#local-passwordunlock").prop('checked', false); - $("#local-passwordlockoutduration").val(""); - $("#local-passwordchecksyntax").prop('checked', false); - $("#local-passwordminlength").val(""); - $("#local-passwordmindigits").val(""); - $("#local-passwordminalphas").val(""); - $("#local-passwordminuppers").val(""); - $("#local-passwordminlowers").val(""); - $("#local-passwordminspecials").val(""); - $("#local-passwordmin8bit").val(""); - $("#local-passwordmaxrepeats").val(""); - $("#local-passwordmincategories").val(""); - $("#local-passwordmintokenlength").val(""); + $(".ds-pwp-input").val(""); + $(".ds-pwp-checkbox").prop('checked', false); $("#local-passwordstoragescheme").prop('selectedIndex',0); - $("#subtree-pwp-radio").prop('checked', true); $("#subtree-pwp-radio").attr('disabled', false); $("#user-pwp-radio").attr('disabled', false); } function clear_inst_input() { // Reset the color of the fields - $("#create-inst-serverid").css("border-color", "initial"); - $("#create-inst-port").css("border-color", "initial"); - $("#create-inst-secureport").css("border-color", "initial"); - $("#create-inst-rootdn").css("border-color", "initial"); - $("#create-inst-user").css("border-color", "initial"); - $("#create-inst-group").css("border-color", "initial"); - $("#rootdn-pw").css("border-color", "initial"); - $("#rootdn-pw-confirm").css("border-color", "initial"); - $("#backend-name").css("border-color", "initial"); - $("#backend-suffix").css("border-color", "initial"); + $(".ds-inst-input").css("border-color", "initial"); } function clear_inst_form() { @@ -159,10 +111,9 @@ function clear_inst_form() { $("#backend-name").val(""); $("#create-sample-entries").prop('checked', false); $("#create-inst-tls").prop('checked', true); - clear_inst_input(); + $(".ds-inst-input").css("border-color", "initial"); } - function get_and_set_config () { var cmd = [DSCONF, '-j', 'ldapi://%2fvar%2frun%2f' + server_id + '.socket','config', 'get']; cockpit.spawn(cmd, { superuser: true, "err": "message", "environ": [ENV]}).done(function(data) { @@ -186,7 +137,40 @@ function get_and_set_config () { check_inst_alive(); }).fail(function(data) { console.log("failed: " + data.message); - check_inst_alive(); + check_inst_alive(1); + }); +} + +function get_and_set_sasl () { + // First empty the table + $("#sasl-table").find("tr:gt(0)").empty(); + + var cmd = [DSCONF, '-j', 'ldapi://%2fvar%2frun%2f' + server_id + '.socket','sasl', 'list']; + cockpit.spawn(cmd, { superuser: true, "err": "message", "environ": [ENV]}).done(function(data) { + var obj = JSON.parse(data); + for (var idx in obj['items']) { + var map_cmd = [DSCONF, '-j', 'ldapi://%2fvar%2frun%2f' + server_id + '.socket','sasl', 'get', obj['items'][idx] ]; + cockpit.spawn(map_cmd, { superuser: true, "err": "message", "environ": [ENV]}).done(function(data) { + var map_obj = JSON.parse(data); + + // Update html table + var sasl_priority = '100'; + if ( map_obj['attrs'].hasOwnProperty('nssaslmappriority') ){ + sasl_priority = map_obj['attrs'].nssaslmappriority + } + sasl_table.row.add( [ + map_obj['attrs'].cn, + map_obj['attrs'].nssaslmapregexstring, + map_obj['attrs'].nssaslmapbasedntemplate, + map_obj['attrs'].nssaslmapfiltertemplate, + sasl_priority, + sasl_action_html + ] ).draw( false ); + }); + } + }).fail(function(data) { + console.log("failed: " + data.message); + check_inst_alive(1); }); } @@ -386,7 +370,7 @@ $(document).ready( function() { } }); - var sasl_table = $('#sasl-table').DataTable( { + sasl_table = $('#sasl-table').DataTable( { "paging": true, "bAutoWidth": false, "dom": '<"pull-left"f><"pull-right"l>tip', @@ -403,19 +387,51 @@ $(document).ready( function() { $("#create-sasl-map-btn").on("click", function () { clear_sasl_map_form(); + $("#sasl-map-name").prop("readonly", false); + }); + + $("#test-sasl-regex").change(function() { + if(this.checked) { + // Test SASL mapping + $("#sasl-test-div").show(); + } else { + $("#sasl-test-div").hide(); + } + }); + + // Test SASL Mapping Regex + $("#sasl-test-regex-btn").on('click', function () { + var result = "No match!" + var regex = $("#sasl-map-regex").val().replace(/\\\(/g, '(').replace(/\\\)/g, ')'); + var test_string = $("#sasl-test-regex-string").val(); + var sasl_regex = RegExp(regex); + if (sasl_regex.test(test_string)){ + popup_msg("Match", "The text matches the regular expression"); + } else { + popup_msg("No Match", "The text does not match the regular expression"); + } }); // Edit SASL mapping $(document).on('click', '.sasl-edit-btn', function(e) { - // TODO - get this working - e.preventDefault(); - clear_sasl_map_form(); - var data = sasl_table.row( $(this).parents('tr') ).data(); - var edit_sasl_name = data[0]; - - $("#sasl-header").html("Edit SASL Mapping"); - $("#sasl-map-name").val(edit_sasl_name); - $("#sasl-map-form").modal("toggle"); + // Load the Edit form + e.preventDefault(); + clear_sasl_map_form(); + var data = sasl_table.row( $(this).parents('tr') ).data(); + var edit_sasl_name = data[0]; + var edit_sasl_regex = data[1]; + var edit_sasl_base = data[2]; + var edit_sasl_filter = data[3]; + var edit_sasl_priority = data[4]; + + $("#sasl-header").html("Edit SASL Mapping"); + $("#sasl-map-name").val(edit_sasl_name); + $("#sasl-map-name").prop("readonly", true); + $("#sasl-map-regex").val(edit_sasl_regex); + $("#sasl-map-base").val(edit_sasl_base); + $("#sasl-map-filter").val(edit_sasl_filter); + $("#sasl-map-priority").val(edit_sasl_priority); + $("#sasl-map-form").modal("toggle"); }); // Verify SASL Mapping regex - open modal and ask for "login" to test regex mapping @@ -434,10 +450,14 @@ $(document).ready( function() { var sasl_row = $(this); // Store element for callback popup_confirm("Are you sure you want to delete sasl mapping: <b>" + del_sasl_name + "</b>", "Confirmation", function (yes) { if (yes) { - // TODO Delete mapping from DS - - // Update html table - sasl_table.row( sasl_row.parents('tr') ).remove().draw( false ); + var cmd = [DSCONF, '-j', 'ldapi://%2fvar%2frun%2f' + server_id + '.socket','sasl', 'delete', del_sasl_name]; + cockpit.spawn(cmd, { superuser: true, "err": "message", "environ": [ENV]}).done(function(data) { + sasl_table.row( sasl_row.parents('tr') ).remove().draw( false ); + popup_success("Removed SASL mapping <b>" + del_sasl_name + "</b>"); + }).fail(function(data) { + popup_err("Failure Deleting SASL Mapping", + "Failed To Delete SASL Mapping: <b>" + del_sasl_name + "</b>: \n" + data.message); + }); } }); }); @@ -854,27 +874,105 @@ $(document).ready( function() { // SASL Mappings Form $("#sasl-map-save").on("click", function() { - var sasl_name = $("#sasl-map-name").val(); - var sasl_regex = $("#sasl-map-regex").val(); - var sasl_base = $("#sasl-map-base").val(); + var sasl_map_name = $("#sasl-map-name").val(); + var sasl_regex = $("#sasl-map-regex").val(); + var sasl_base = $("#sasl-map-base").val(); var sasl_filter = $("#sasl-map-filter").val(); var sasl_priority = $("#sasl-map-priority").val(); - // TODO - Add mapping to DS - - // Update html table - sasl_table.row.add( [ - sasl_name, - sasl_regex, - sasl_base, - sasl_filter, - sasl_priority, - sasl_action_html - ] ).draw( false ); - - // Done - //$("#sasl-map-form").css('display', 'none'); - $("#sasl-map-form").modal('toggle'); + // Validate values + if (sasl_map_name == '') { + report_err($("#sasl-map-name"), 'You must provide an mapping name'); + return; + } + if (sasl_map_name == '') { + report_err($("#sasl-map-regex"), 'You must provide an regex'); + return; + } + if (sasl_regex == '') { + report_err($("#sasl-map-base"), 'You must provide a base DN template'); + return; + } + if (sasl_filter == '') { + report_err($("#sasl-map-filter"), 'You must provide an filter template'); + return; + } + if (sasl_priority == '') { + sasl_priority = '100' + } else if (valid_num(sasl_priority)) { + var priority = Number(sasl_priority); + if (priority < 1 || priority > 100) { + report_err($("#sasl-map-priority"), 'You must provide a number between 1 and 100'); + return; + } + } else { + report_err($("#sasl-map-priority"), 'You must provide a number between 1 and 100'); + return; + } + + // Build command line args + var sasl_name_cmd = "--cn=" + sasl_map_name ; + var sasl_regex_cmd = "--nsSaslMapRegexString=" + sasl_regex; + var sasl_base_cmd = "--nsSaslMapBaseDNTemplate=" + sasl_base; + var sasl_filter_cmd = "--nsSaslMapFilterTemplate=" + sasl_filter; + var sasl_priority_cmd = "--nsSaslMapPriority=" + sasl_priority; + + if ( $("#sasl-header").html().includes("Create") ) { + // Create new mapping and update table + var cmd = [DSCONF, '-j', 'ldapi://%2fvar%2frun%2f' + server_id + '.socket','sasl', 'create', + sasl_name_cmd, sasl_regex_cmd, sasl_base_cmd, sasl_filter_cmd, sasl_priority_cmd]; + cockpit.spawn(cmd, { superuser: true, "err": "message", "environ": [ENV]}).done(function() { + // Update html table + sasl_table.row.add( [ + sasl_map_name, + sasl_regex, + sasl_base, + sasl_filter, + sasl_priority, + sasl_action_html + ] ).draw( false ); + popup_success("Successfully added new SASL mapping"); + $("#sasl-map-form").modal('toggle'); + }).fail(function(data) { + popup_err("Failure Adding SASL Mapping", + "Failed To Add SASL Mapping: <b>" + sasl_map_name + "</b>: \n" + data.message); + $("#sasl-map-form").modal("toggle"); + }); + } else { + // Editing mapping. First delete the old mapping + var cmd = [DSCONF, '-j', 'ldapi://%2fvar%2frun%2f' + server_id + '.socket','sasl', 'delete', sasl_map_name]; + cockpit.spawn(cmd, { superuser: true, "err": "message", "environ": [ENV]}).done(function() { + // Remove row from old + sasl_table.rows( function ( idx, data, node ) { + return data[0] == sasl_map_name; + }).remove().draw(); + + // Then add new mapping and update table + var cmd = [DSCONF, '-j', 'ldapi://%2fvar%2frun%2f' + server_id + '.socket','sasl', 'create', + sasl_name_cmd, sasl_regex_cmd, sasl_base_cmd, sasl_filter_cmd, sasl_priority_cmd]; + cockpit.spawn(cmd, { superuser: true, "err": "message", "environ": [ENV]}).done(function() { + // Update html table + sasl_table.row.add( [ + sasl_map_name, + sasl_regex, + sasl_base, + sasl_filter, + sasl_priority, + sasl_action_html + ] ).draw( false ); + popup_success("Successfully added new SASL mapping"); + $("#sasl-map-form").modal('toggle'); + }).fail(function(data) { + popup_err("Failure Adding SASL Mapping", + "Failed To Add SASL Mapping: <b>" + sasl_map_name + "</b>: \n" + data.message); + $("#sasl-map-form").modal("toggle"); + }); + }).fail(function(data) { + popup_err("Failure Deleting Old SASL Mapping", + "Failed To Delete SASL Mapping: <b>" + sasl_map_name + "</b>: \n" + data.message); + $("#sasl-map-form").modal("toggle"); + }); + } }); /* @@ -1069,7 +1167,7 @@ $(document).ready( function() { // Create Instance $("#create-inst-save").on("click", function() { $(".ds-modal-error").hide(); - clear_inst_input(); + $(".ds-inst-input").css("border-color", "initial"); /* * Validate settings and update the INF settings diff --git a/src/cockpit/389-console/servers.html b/src/cockpit/389-console/servers.html index b70b186b7..93b6728df 100644 --- a/src/cockpit/389-console/servers.html +++ b/src/cockpit/389-console/servers.html @@ -184,7 +184,7 @@ class="ds-input" type="text" id="nsslapd-sasl-max-buffer-size" size="40"/> </div> <div> - <label for="nsslapd-allowed-sasl-mechanisms" class="ds-config-label" title="A list of SASL mechanisms the server will accept (nsslapd-allowed-sasl-mechanisms).">Allowed SASL Mechanisms</label><input + <label for="nsslapd-allowed-sasl-mechanisms" class="ds-config-label" title="A list of SASL mechanisms the server will only accept (nsslapd-allowed-sasl-mechanisms).">Allowed SASL Mechanisms</label><input class="ds-input" type="text" id="nsslapd-allowed-sasl-mechanisms" size="40"/> </div> <div> @@ -209,26 +209,6 @@ <th>Action</th> </thead> <tbody id="sasl-mappings"> - <tr> - <td>Kerberos UID Mapping</td> - <td>\(.*\)@\(.*\)\.\(.*\)</td> - <td>dc=\2,dc=\3</td> - <td>(uid=\1)</td> - <td></td> - <td> - <div class="dropdown"> - <button class="btn btn-default dropdown-toggle ds-agmt-dropdown-button" type="button" data-toggle="dropdown"> - Choose Action... - <span class="caret"></span> - </button> - <ul class="dropdown-menu ds-agmt-dropdown" role="menu"> - <li><a role="menuitem" class="sasl-edit-btn">Edit Mapping</a></li> - <li><a role="menuitem" class="sasl-verify-btn">Test Mapping</a></li> - <li><a role="menuitem" class="sasl-del-btn">Delete Mapping</a></li> - </ul> - </div> - </td> - </tr> </tbody> </table> <button class="btn btn-default" data-toggle="modal" data-target="#sasl-map-form" id="create-sasl-map-btn">Create SASL Mapping</button> @@ -1017,8 +997,8 @@ <!-- Create SASL Mapping --> - <div class="modal fade" id="sasl-map-form" data-backdrop="static" data-backdrop="static" tabindex="-1" role="dialog" aria-labelledby="sasl-header" aria-hidden="true"> - <div class="modal-dialog ds-modal"> + <div class="modal fade" id="sasl-map-form" data-backdrop="static" tabindex="-1" role="dialog" aria-labelledby="sasl-header" aria-hidden="true"> + <div class="modal-dialog ds-modal-wide"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true" aria-label="Close"> @@ -1029,27 +1009,40 @@ <div class="modal-body"> <form class="form-horizontal"> <div class="ds-inline"> + <p class="ds-modal-error"></p> <div> <label for="sasl-map-name" class="ds-config-label" title="SASL mapping name"> - SASL Mapping Name</label><input class="ds-input" type="text" id="sasl-map-name"/> + SASL Mapping Name</label><input class="ds-input sasl-input" type="text" id="sasl-map-name"/> </div> <div> <label for="sasl-map-regex" class="ds-config-label" title="SASL mapping regular expression"> - SASL Mapping Regex</label><input class="ds-input" type="text" id="sasl-map-regex"/> + SASL Mapping Regex</label><input class="ds-input sasl-input" type="text" id="sasl-map-regex"/><label + for="test-sasl-regex" class="ds-left-margin">Test Regex</label><input type="checkbox" + class="ds-left-margin ds-checkbox-group" id="test-sasl-regex"> + </div> + <div id="sasl-test-div" hidden> + <div class="ds-inline"> + <div> + <label for="sasl-test-regex" class="ds-config-label" title="SASL mapping name"> + </label><input class="ds-input sasl-test-input" placeholder="Enter text to test" type="text" id="sasl-test-regex-string"/><button + type="button" class="btn btn-default ds-trailing-btn" id="sasl-test-regex-btn">Test It</button> + <hr> + </div> + </div> </div> <div> <label for="sasl-map-base" class="ds-config-label" title= "The search base or a specific entry DN to match against the constructed DN"> - SASL Mapping Base</label><input class="ds-input" type="text" id="sasl-map-base"/> + SASL Mapping Base</label><input class="ds-input sasl-input" type="text" id="sasl-map-base"/> </div> <div> <label for="sasl-map-filter" class="ds-config-label" title="SASL mapping filter"> - SASL Mapping Filter</label><input class="ds-input" type="text" id="sasl-map-filter"/> + SASL Mapping Filter</label><input class="ds-input sasl-input" type="text" id="sasl-map-filter"/> </div> <div> <label for="sasl-map-priority" class="ds-config-label" title= "SASL mapping priority. 1 is highest priority, and 100 is lowest"> - SASL Mapping Priority</label><input class="ds-input" type="text" id="sasl-map-priority"/> + SASL Mapping Priority</label><input class="ds-input sasl-input" type="text" id="sasl-map-priority"/> </div> </div> </form> @@ -1063,7 +1056,7 @@ </div> - <!-- Create Local PA\assword Policy --> + <!-- Create Local Password Policy --> <div class="modal fade" id="local-pwp-form" data-backdrop="static" tabindex="-1" role="dialog" aria-labelledby="local-pwp-label" aria-hidden="true"> <div class="modal-dialog ds-modal-wide"> <div class="modal-content"> @@ -1077,7 +1070,7 @@ <form class="form-horizontal"> <div class="ds-inline"> <div> - <label title="Create a subtree elevel password policy" for="subtree-pwp-radio"><input + <label title="Create a subtree level password policy" for="subtree-pwp-radio"><input class="ds-radio pwp-role" type="radio" id="subtree-pwp-radio" name="pwp-role" value="subtree" checked="checked"> Subtree Password Policy</label> </div> <div> @@ -1086,10 +1079,10 @@ </div> <div> <div> - <label for="local-entry-dn" class="ds-config-label" title="The entry to apply a local policy to.">Entry for Password Policy</label> + <label for="local-entry-dn" class="ds-config-label ds-pwp-input" title="The entry to apply a local policy to.">Entry for Password Policy</label> </div> <div class="ds-inline"> - <input class="ds-input" type="text" id="local-entry-dn" size="70" required /><button class="btn btn-default ds-trailing-btn" type="button">Pick Entry</button> + <input class="ds-input ds-pwp-input" type="text" id="local-entry-dn" size="70" required /><button class="btn btn-default ds-trailing-btn" type="button">Pick Entry</button> </div> <hr> <div> @@ -1120,17 +1113,17 @@ </select> </div> <div> - <input type="checkbox" class="ds-config-checkbox" id="local-passwordtrackupdatetime"><label + <input type="checkbox" class="ds-config-checkbox ds-pwp-checkbox" id="local-passwordtrackupdatetime"><label for="local-passwordtrackupdatetime" class="ds-label" title= "Record a separate timestamp specifically for the last time that the password for an entry was changed. If this is enabled, then it adds the pwdUpdateTime operational attribute to the user account entry (passwordTrackUpdateTime)."> Track Password Update Time</label> </div> <div> - <input type="checkbox" class="ds-config-checkbox" id="nsslapd-allow-hashed-passwords"><label + <input type="checkbox" class="ds-config-checkbox ds-pwp-checkbox" id="nsslapd-allow-hashed-passwords"><label for="local-nsslapd-allow-hashed-passwords" class="ds-label" title="Allow anyone to add a prehashed password (nsslapd-allow-hashed-passwords)."> Allow Adding Pre-Hashed Passwords</label> </div> <div> <label for="local-passwordadmindn" class="ds-labelZ" title="The DN for a password administrator or administrator group (passwordAdminDN)">Password Administrator</label><input - class="ds-input" type="text" id="local-passwordadmindn" size="40"/> + class="ds-input ds-pwp-input" type="text" id="local-passwordadmindn" size="40"/> </div> </div> </div> @@ -1140,21 +1133,21 @@ <hr class="ds-hr"> <div class="ds-inline"> <div> - <input type="checkbox" class="ds-config-checkbox" id="local-passwordchange"><label + <input type="checkbox" class="ds-config-checkbox ds-pwp-checkbox" id="local-passwordchange"><label for="local-passwordchange" class="ds-label" title="Allow user's to change their passwords (passwordChange)."> Allow Users To Change Their Passwords</label> </div> <div> - <input type="checkbox" class="ds-config-checkbox" id="local-passwordmustchange"><label + <input type="checkbox" class="ds-config-checkbox ds-pwp-checkbox" id="local-passwordmustchange"><label for="local-passwordmustchange" class="ds-label" title="User must change its password after its been reset by an administrator (passwordMustChange).">User Must Change Password After Reset</label> </div> <div> - <input type="checkbox" class="ds-config-checkbox" id="local-passwordhistory"><label + <input type="checkbox" class="ds-config-checkbox ds-pwp-checkbox" id="local-passwordhistory"><label for="local-passwordhistory" class="ds-label" title="Maintain a password history (passwordHistory).">Keep Password History</label> </div> <div> - <input class="ds-history-input" type="text" id="local-passwordinhistory" size="2"/>Passwords In History + <input class="ds-history-input ds-pwp-input" type="text" id="local-passwordinhistory" size="2"/>Passwords In History <label for="local-passwordminage" class="ds-minage-label" title="Indicates the number of seconds that must pass before a user can change their password. (passwordMinAge)">Allow Password Changes (in seconds)</label><input - class="ds-input" type="text" id="local-passwordminage" size="10"/> + class="ds-input ds-pwp-input" type="text" id="local-passwordminage" size="10"/> </div> </div> </div> @@ -1163,16 +1156,16 @@ <div class="ds-split"> <h4><br>Password Expiration Settings</h4> <hr class="ds-hr"> - <input type="checkbox" class="ds-config-checkbox" id="local-passwordexp"><label + <input type="checkbox" class="ds-config-checkbox ds-pwp-checkbox" id="local-passwordexp"><label for="local-passwordexp" class="ds-label" title="Enable a password expiration policy (passwordExp).">Enable Password Expiration</label> <div class="ds-expired-div" id="local-expiration-attrs"> <label for="local-passwordmaxage" class="ds-expire-label" title="The server's local hostname (passwordMaxAge).">Password Expiration Time (in seconds)</label><input - class="ds-input" type="text" id="local-passwordmaxage" size="5"/> + class="ds-input ds-pwp-input" type="text" id="local-passwordmaxage" size="5"/> <label for="local-passwordgracelimit" class="ds-expire-label" title="The server's local hostname (passwordGraceLimit).">Allowed Logins After Password Expires</label><input - class="ds-input" type="text" id="local-passwordgracelimit" size="5"/> + class="ds-input ds-pwp-input" type="text" id="local-passwordgracelimit" size="5"/> <label for="local-passwordwarning" class="ds-expire-label" title="Set the time (in seconds), before a password is about to expire, to send a warning. (passwordWarning).">Send Password Expiring Warning (in seconds)</label><input - class="ds-input" type="text" id="local-passwordwarning" size="5"/> - <input type="checkbox" class="ds-send-expiring-checkbox" id="local-passwordsendexpiringtime"><label + class="ds-input ds-pwp-input" type="text" id="local-passwordwarning" size="5"/> + <input type="checkbox" class="ds-send-expiring-checkbox ds-pwp-checkbox" id="local-passwordsendexpiringtime"><label for="local-passwordsendexpiringtime" class="ds-label" title= "Always return a password expiring control when requested (passwordSendExpiringTime).">Always Send <i>Password Expiring Control</i></label> </div> @@ -1181,21 +1174,21 @@ <div class="ds-split"> <h4><br>Account Lockout Settings</h4> <hr class="ds-hr"> - <input type="checkbox" class="ds-config-checkbox" id="local-passwordlockout"><label + <input type="checkbox" class="ds-config-checkbox ds-pwp-checkbox" id="local-passwordlockout"><label for="local-passwordlockout" class="ds-label" title="Enable account lockout (passwordLockout).">Enable Account Lockout</label> <div class="ds-expired-div" id="local-lockout-attrs"> <label for="local-passwordmaxfailure" class="ds-expire-label" title= "The maximum number of failed logins before account gets locked (passwordMaxFailure).">Number of Failed Logins to Lockout Account</label><input - class="ds-input" type="text" id="local-passwordmaxfailure" size="5"/> + class="ds-input ds-pwp-input" type="text" id="local-passwordmaxfailure" size="5"/> <label for="local-passwordresetfailurecount" class="ds-expire-label" title= "The number of seconds until an accounts failure count is reset (passwordResetFailureCount).">Time Before Failure Count Reset </label><input - class="ds-input" type="text" id="local-passwordresetfailurecount" size="5"/> + class="ds-input ds-pwp-input" type="text" id="local-passwordresetfailurecount" size="5"/> <div> <label title="Lock out the account forever (passwordUnlock)." for="local-passwordunlock" ><input class="ds-radio" type="radio" id="local-passwordunlock" value="passwordunlock" name="account-lockout" checked="checked"> Lockout Account Forever</label> <label title="The number of seconds before account gets unlocked (passwordLockoutDuration)." for="local-passwordlockoutduration"><input class="ds-radio" type="radio" name="account-lockout" value="passwordlockoutduration"> Time Until Account Unlocked <input - class="ds-input" type="text" id="local-passwordlockoutduration" size="5"/></label> + class="ds-input ds-pwp-input" type="text" id="local-passwordlockoutduration" size="5"/></label> </div> </div> <p></p> @@ -1204,44 +1197,44 @@ <h4><br>Password Syntax Settings</h4> <hr class="ds-hr"> - <input type="checkbox" class="ds-config-checkbox" id="local-passwordchecksyntax"><label + <input type="checkbox" class="ds-config-checkbox ds-pwp-checkbox" id="local-passwordchecksyntax"><label for="local-passwordchecksyntax" class="ds-label" title="Enable account lockout (passwordCheckSyntax).">Check Password Syntax</label> <div class="ds-container ds-expired-div" id="local-syntax-attrs"> <div> <label for="local-passwordminlength" class="ds-expire-label" title= "The minimum number of characters in the password (passwordMinLength).">Password Minimum Length </label><input - class="ds-input" type="text" id="local-passwordminlength" size="5"/> + class="ds-input ds-pwp-input" type="text" id="local-passwordminlength" size="5"/> <label for="local-passwordmindigits" class="ds-expire-label" title= "Reject passwords with fewer than this many digit characters (0-9) (passwordMinDigits).">Minimum Digit Characters </label><input - class="ds-input" type="text" id="local-passwordmindigits" size="5"/> + class="ds-input ds-pwp-input" type="text" id="local-passwordmindigits" size="5"/> <label for="local-passwordminalphas" class="ds-expire-label" title= "Reject passwords with fewer than this many alpha characters (passwordMinAlphas).">Minimum Alpha Characters </label><input - class="ds-input" type="text" id="local-passwordminalphas" size="5"/> + class="ds-input ds-pwp-input" type="text" id="local-passwordminalphas" size="5"/> <label for="local-passwordminuppers" class="ds-expire-label" title= "Reject passwords with fewer than this many uppercase characters (passwordMinUppers).">Minimum Uppercase Characters </label><input - class="ds-input" type="text" id="local-passwordminuppers" size="5"/> + class="ds-input ds-pwp-input" type="text" id="local-passwordminuppers" size="5"/> <label for="local-passwordminlowers" class="ds-expire-label" title= "Reject passwords with fewer than this many lowercase characters (passwordMinLowers).">Minimum Lowercase Characters </label><input - class="ds-input" type="text" id="local-passwordminlowers" size="5"/> + class="ds-input ds-pwp-input" type="text" id="local-passwordminlowers" size="5"/> </div> <div class="ds-divider"></div> <div class="ds-divider"></div> <div> <label for="local-passwordminspecials" class="ds-expire-label" title= "Reject passwords with fewer than this many special non-alphanumeric characters (passwordMinSpecials).">Minimum Special Characters </label><input - class="ds-input" type="text" id="local-passwordminspecials" size="5"/> + class="ds-input ds-pwp-input" type="text" id="local-passwordminspecials" size="5"/> <label for="local-passwordmin8bit" class="ds-expire-label" title= "Reject passwords with fewer than this many 8-bit or multi-byte characters (passwordMin8Bit).">Minimum 8-bit Characters </label><input - class="ds-input" type="text" id="local-passwordmin8bit" size="5"/> + class="ds-input ds-pwp-input" type="text" id="local-passwordmin8bit" size="5"/> <label for="local-passwordmaxrepeats" class="ds-expire-label" title= "The maximum number of times the same character can sequentially appear in a password (passwordMaxRepeats).">Maximum Number Of Repeated Characters </label><input - class="ds-input" type="text" id="local-passwordmaxrepeats" size="5"/> + class="ds-input ds-pwp-input" type="text" id="local-passwordmaxrepeats" size="5"/> <label for="local-passwordmincategories" class="ds-expire-label" title= "The minimum number of character categories that a password must contain (categories are upper, lower, digit, special, and 8-bit) (passwordMinCategories).">Minimum Required Character Categories </label><input - class="ds-input" type="text" id="local-passwordmincategories" size="5"/> + class="ds-input ds-pwp-input" type="text" id="local-passwordmincategories" size="5"/> <label for="local-passwordmintokenlength" class="ds-expire-label" title= "The smallest attribute value used when checking if the password contains any of the user's account information (passwordMinTokenLength).">Minimum Token Length </label><input - class="ds-input" type="text" id="local-passwordmintokenlength" size="5"/> + class="ds-input ds-pwp-input" type="text" id="local-passwordmintokenlength" size="5"/> </div> </div> </form> diff --git a/src/lib389/cli/dsconf b/src/lib389/cli/dsconf index 9cf89b3e5..a3c56fe1a 100755 --- a/src/lib389/cli/dsconf +++ b/src/lib389/cli/dsconf @@ -27,6 +27,7 @@ from lib389.cli_conf import directory_manager as cli_directory_manager from lib389.cli_conf import plugin as cli_plugin from lib389.cli_conf import schema as cli_schema from lib389.cli_conf import health as cli_health +from lib389.cli_conf import saslmappings as cli_sasl 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 @@ -79,6 +80,7 @@ cli_rootdn_ac.create_parser(subparsers) cli_whoami.create_parser(subparsers) cli_referint.create_parser(subparsers) cli_automember.create_parser(subparsers) +cli_sasl.create_parser(subparsers) argcomplete.autocomplete(parser) # handle a control-c gracefully @@ -128,7 +130,7 @@ if __name__ == '__main__': except Exception as e: log.debug(e, exc_info=True) if args and args.json: - sys.stderr.write(str(e)) + sys.stderr.write(str(e) + '\n') else: log.error("Error: %s" % str(e)) result = False diff --git a/src/lib389/lib389/__init__.py b/src/lib389/lib389/__init__.py index 78dae7f84..13c747959 100644 --- a/src/lib389/lib389/__init__.py +++ b/src/lib389/lib389/__init__.py @@ -103,6 +103,7 @@ TRACE_LEVEL = 0 # My logger logger = logging.getLogger(__name__) + # Initiate the paths object here. Should this be part of the DirSrv class # for submodules? def wrapper(f, name): @@ -309,6 +310,7 @@ class DirSrv(SimpleLDAPObject, object): from lib389.index import IndexLegacy as Index from lib389.monitor import Monitor, MonitorLDBM from lib389.rootdse import RootDSE + from lib389.saslmap import SaslMapping, SaslMappings # Need updating self.agreement = Agreement(self) @@ -321,6 +323,7 @@ class DirSrv(SimpleLDAPObject, object): self.schema = Schema(self) self.plugins = Plugins(self) self.tasks = Tasks(self) + self.saslmap = SaslMapping(self) # Do we have a certdb path? # if MAJOR < 3: self.monitor = Monitor(self) @@ -335,6 +338,7 @@ class DirSrv(SimpleLDAPObject, object): self.ds_access_log = DirsrvAccessLog(self) self.ds_error_log = DirsrvErrorLog(self) self.ldclt = Ldclt(self) + self.saslmaps = SaslMappings(self) def __init__(self, verbose=False, external_log=None): """ diff --git a/src/lib389/lib389/_mapped_object.py b/src/lib389/lib389/_mapped_object.py index 70228ed25..c347a5fd7 100644 --- a/src/lib389/lib389/_mapped_object.py +++ b/src/lib389/lib389/_mapped_object.py @@ -167,6 +167,10 @@ class DSLdapObject(DSLogging): str_attrs = {} for k in attrs: str_attrs[ensure_str(k)] = ensure_list_str(attrs[k]) + + # ensure all the keys are lowercase + str_attrs = dict((k.lower(), v) for k, v in str_attrs.items()) + response = json.dumps({"type": "entry", "dn": ensure_str(self._dn), "attrs": str_attrs}) return response @@ -662,9 +666,10 @@ class DSLdapObject(DSLogging): # I think this needs to be made case insensitive # How will this work with the dictionary? - for attr in self._must_attributes: - if properties.get(attr, None) is None: - raise ldap.UNWILLING_TO_PERFORM('Attribute %s must not be None' % attr) + if self._must_attributes is not None: + for attr in self._must_attributes: + if properties.get(attr, None) is None: + raise ldap.UNWILLING_TO_PERFORM('Attribute %s must not be None' % attr) # Make sure the naming attribute is present if properties.get(self._rdn_attribute, None) is None and rdn is None: @@ -677,7 +682,7 @@ class DSLdapObject(DSLogging): pass else: # Turn it into a list instead. - properties[k] = [v,] + properties[k] = [v, ] # This change here, means we can pre-load a full dn to _dn, or we can # accept based on the rdn diff --git a/src/lib389/lib389/cli_base/__init__.py b/src/lib389/lib389/cli_base/__init__.py index 06224a0b4..8c7325cf7 100644 --- a/src/lib389/lib389/cli_base/__init__.py +++ b/src/lib389/lib389/cli_base/__init__.py @@ -50,7 +50,7 @@ def _get_args(args, kws): kwargs = {} while len(kws) > 0: kw, msg, priv = kws.pop(0) - + kw = kw.lower() if args is not None and len(args) > 0: kwargs[kw] = args.pop(0) else: @@ -69,12 +69,15 @@ def _get_attributes(args, attrs): # in many places, so we have to normalise this. attr_normal = attr.replace('-', '_') if args is not None and hasattr(args, attr_normal) and getattr(args, attr_normal) is not None: + attr = attr.lower() kwargs[attr] = getattr(args, attr_normal) else: if attr.lower() == 'userpassword': kwargs[attr] = getpass("Enter value for %s : " % attr) else: - kwargs[attr] = _input("Enter value for %s : " % attr) + attr_normal = attr.lower() + kwargs[attr_normal] = _input("Enter value for %s : " % attr) + return kwargs diff --git a/src/lib389/lib389/cli_conf/backend.py b/src/lib389/lib389/cli_conf/backend.py index f37847490..a278763a0 100644 --- a/src/lib389/lib389/cli_conf/backend.py +++ b/src/lib389/lib389/cli_conf/backend.py @@ -7,6 +7,7 @@ # --- END COPYRIGHT BLOCK --- from lib389.backend import Backend, Backends +from lib389.utils import ensure_str from lib389.cli_base import ( populate_attr_arguments, _generic_list, @@ -45,8 +46,20 @@ def backend_create(inst, basedn, log, args): def backend_delete(inst, basedn, log, args, warn=True): - dn = _get_arg(args.dn, msg="Enter dn to delete") - if warn: + found = False + be_insts = Backends(inst).list() + for be in be_insts: + cn = ensure_str(be.get_attr_val('cn')).lower() + suffix = ensure_str(be.get_attr_val('nsslapd-suffix')).lower() + del_be_name = args.be_name.lower() + if cn == del_be_name or suffix == del_be_name: + dn = be.dn + found = True + break + if not found: + raise ValueError("Unable to find a backend with the name: ({})".format(args.be_name)) + + if warn and args.json is False: _warn(dn, msg="Deleting %s %s" % (SINGULAR.__name__, dn)) _generic_delete(inst, basedn, log.getChild('backend_delete'), SINGULAR, dn, args) @@ -73,6 +86,6 @@ def create_parser(subparsers): delete_parser = subcommands.add_parser('delete', help='deletes the object') delete_parser.set_defaults(func=backend_delete) - delete_parser.add_argument('dn', nargs='?', help='The dn to delete') + delete_parser.add_argument('be_name', help='The backend name or suffix to delete') diff --git a/src/lib389/lib389/cli_conf/saslmappings.py b/src/lib389/lib389/cli_conf/saslmappings.py new file mode 100644 index 000000000..ed079a1c7 --- /dev/null +++ b/src/lib389/lib389/cli_conf/saslmappings.py @@ -0,0 +1,81 @@ +# --- 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 --- + +from lib389.saslmap import SaslMapping, SaslMappings +from lib389.utils import ensure_str +from lib389.cli_base import ( + populate_attr_arguments, + _generic_list, + _generic_get, + _generic_create, + _generic_delete, + _get_arg, + _get_attributes, + _warn, + ) + +SINGULAR = SaslMapping +MANY = SaslMappings +RDN = 'cn' + + +def sasl_map_list(inst, basedn, log, args): + _generic_list(inst, basedn, log.getChild('sasl_map_list'), MANY, args) + + +def sasl_map_get(inst, basedn, log, args): + rdn = _get_arg(args.selector, msg="Enter %s to retrieve" % RDN) + _generic_get(inst, basedn, log.getChild('sasl_map_get'), MANY, rdn, args) + + +def sasl_map_create(inst, basedn, log, args): + kwargs = _get_attributes(args, SaslMapping._must_attributes) + if kwargs['nssaslmappriority'] == '': + kwargs['nssaslmappriority'] = '100' # Default + _generic_create(inst, basedn, log.getChild('sasl_map_create'), MANY, kwargs, args) + + +def sasl_map_delete(inst, basedn, log, args, warn=True): + found = False + mappings = SaslMappings(inst).list() + map_name = args.map_name.lower() + + for saslmap in mappings: + cn = ensure_str(saslmap.get_attr_val('cn')).lower() + if cn == map_name: + dn = saslmap.dn + found = True + break + if not found: + raise ValueError("Unable to find a SASL mapping with the name: ({})".format(args.map_name)) + + if warn and args.json is False: + _warn(dn, msg="Deleting %s %s" % (SINGULAR.__name__, dn)) + _generic_delete(inst, basedn, log.getChild('sasl_map_delete'), SINGULAR, dn, args) + + +def create_parser(subparsers): + sasl_parser = subparsers.add_parser('sasl', help='Query and manipulate sasl mappings') + + subcommands = sasl_parser.add_subparsers(help='sasl') + + list_mappings_parser = subcommands.add_parser('list', help='List avaliable SASL mappings') + list_mappings_parser.set_defaults(func=sasl_map_list) + + get_parser = subcommands.add_parser('get', help='get') + get_parser.set_defaults(func=sasl_map_get) + get_parser.add_argument('selector', nargs='?', help='SASL mapping name to get') + + create_parser = subcommands.add_parser('create', help='create') + create_parser.set_defaults(func=sasl_map_create) + populate_attr_arguments(create_parser, SaslMapping._must_attributes) + + delete_parser = subcommands.add_parser('delete', help='deletes the object') + delete_parser.set_defaults(func=sasl_map_delete) + delete_parser.add_argument('map_name', help='The SASL Mapping name ("cn" value)') + diff --git a/src/lib389/lib389/instance/setup.py b/src/lib389/lib389/instance/setup.py index b1a5cbeed..23c76db7d 100644 --- a/src/lib389/lib389/instance/setup.py +++ b/src/lib389/lib389/instance/setup.py @@ -644,6 +644,12 @@ class SetupDs(object): if self.verbose: self.log.info("ACTION: Creating certificate database is %s", slapd['cert_dir']) + # Get suffix for sasl map entries (template-sasl.ldif) + if len(backends) > 0: + ds_suffix = backends[0]['suffix'] + else: + ds_suffix = '' + # Create dse.ldif with a temporary root password. # The template is in slapd['data_dir']/dirsrv/data/template-dse.ldif # Variables are done with %KEY%. @@ -655,6 +661,11 @@ class SetupDs(object): for line in template_dse.readlines(): dse += line.replace('%', '{', 1).replace('%', '}', 1) + if ds_suffix != '': + with open(os.path.join(slapd['data_dir'], 'dirsrv', 'data', 'template-sasl.ldif')) as template_sasl: + for line in template_sasl.readlines(): + dse += line.replace('%', '{', 1).replace('%', '}', 1) + with open(os.path.join(slapd['config_dir'], 'dse.ldif'), 'w') as file_dse: file_dse.write(dse.format( schema_dir=slapd['schema_dir'], @@ -672,7 +683,7 @@ class SetupDs(object): rootdn=slapd['root_dn'], # ds_passwd=slapd['root_password'], ds_passwd=self._secure_password, # We set our own password here, so we can connect and mod. - ds_suffix='', + ds_suffix=ds_suffix, config_dir=slapd['config_dir'], db_dir=slapd['db_dir'], )) diff --git a/src/lib389/lib389/sasl.py b/src/lib389/lib389/sasl.py index 0015f6055..dfae06e77 100644 --- a/src/lib389/lib389/sasl.py +++ b/src/lib389/lib389/sasl.py @@ -13,24 +13,25 @@ These should be upstreamed if possible. """ from ldap.sasl import sasl, CB_AUTHNAME, CB_PASS, CB_USER - from lib389.utils import ensure_bytes + class LdapSSOTokenSASL(sasl): """ This class handles draft-wibrown-ldapssotoken-01 authentication. """ - def __init__(self,token): - auth_dict = { CB_PASS:token } + def __init__(self, token): + auth_dict = {CB_PASS: token} sasl.__init__(self, auth_dict, "LDAPSSOTOKEN") + class PlainSASL(sasl): """ This class handles PLAIN sasl authentication """ def __init__(self, authz_id, passwd): - auth_dict = { CB_AUTHNAME:authz_id, CB_PASS:passwd } + auth_dict = {CB_AUTHNAME: authz_id, CB_PASS: passwd} sasl.__init__(self, auth_dict, "PLAIN") diff --git a/src/lib389/lib389/saslmap.py b/src/lib389/lib389/saslmap.py index 3105f2eaa..2715e1d8c 100644 --- a/src/lib389/lib389/saslmap.py +++ b/src/lib389/lib389/saslmap.py @@ -8,6 +8,7 @@ from lib389._mapped_object import DSLdapObject, DSLdapObjects + class SaslMapping(DSLdapObject): """A sasl map providing a link from a sasl user and realm to a valid directory server entry. @@ -18,21 +19,25 @@ class SaslMapping(DSLdapObject): :type dn: str """ - def __init__(self, instance, dn=None): - super(SaslMapping, self).__init__(instance, dn) - self._rdn_attribute = 'cn' - self._must_attributes = [ + _must_attributes = [ 'cn', 'nsSaslMapRegexString', 'nsSaslMapBaseDNTemplate', 'nsSaslMapFilterTemplate', + 'nsSaslMapPriority' ] + + def __init__(self, instance, dn=None): + super(SaslMapping, self).__init__(instance, dn) + self._rdn_attribute = 'cn' + self._create_objectclasses = [ 'top', 'nsSaslMapping', ] self._protected = False + class SaslMappings(DSLdapObjects): """DSLdapObjects that represents SaslMappings in the server. @@ -42,7 +47,7 @@ class SaslMappings(DSLdapObjects): :type basedn: str """ - def __init__(self, instance): + def __init__(self, instance, dn=None): super(SaslMappings, self).__init__(instance) self._objectclasses = [ 'nsSaslMapping',
0
a6e905efa2d00e151ba736aceb7855f196e4258b
389ds/389-ds-base
Ticket 47973 - CI Test case (test_ticket47973_case) Description: custom schema is registered in small caps after schema reload Revised the test cases to strict the case checking.
commit a6e905efa2d00e151ba736aceb7855f196e4258b Author: Noriko Hosoi <[email protected]> Date: Fri Jan 20 16:13:07 2017 -0800 Ticket 47973 - CI Test case (test_ticket47973_case) Description: custom schema is registered in small caps after schema reload Revised the test cases to strict the case checking. diff --git a/dirsrvtests/tests/tickets/ticket47973_test.py b/dirsrvtests/tests/tickets/ticket47973_test.py index c7548a5ca..6c6e9eb95 100644 --- a/dirsrvtests/tests/tickets/ticket47973_test.py +++ b/dirsrvtests/tests/tickets/ticket47973_test.py @@ -116,7 +116,7 @@ def test_ticket47973_case(topology_st): tsfile = topology_st.standalone.schemadir + '/98test.ldif' tsfd = open(tsfile, "w") Mozattr0 = "MoZiLLaaTTRiBuTe" - testschema = "dn: cn=schema\nattributetypes: ( 8.9.10.11.12.13.14 NAME 'MozillaAttribute' SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 X-ORIGIN 'Mozilla Dummy Schema' )\nobjectclasses: ( 1.2.3.4.5.6.7 NAME 'MozillaObject' SUP top MUST ( objectclass $ cn ) MAY ( " + Mozattr0 + " ) X-ORIGIN 'user defined' )" + testschema = "dn: cn=schema\nattributetypes: ( 8.9.10.11.12.13.14 NAME '" + Mozattr0 + "' SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 X-ORIGIN 'Mozilla Dummy Schema' )\nobjectclasses: ( 1.2.3.4.5.6.7 NAME 'MozillaObject' SUP top MUST ( objectclass $ cn ) MAY ( " + Mozattr0 + " ) X-ORIGIN 'user defined' )" tsfd.write(testschema) tsfd.close() @@ -156,7 +156,7 @@ def test_ticket47973_case(topology_st): tsfile = topology_st.standalone.schemadir + '/97test.ldif' tsfd = open(tsfile, "w") Mozattr1 = "MOZILLAATTRIBUTE" - testschema = "dn: cn=schema\nattributetypes: ( 8.9.10.11.12.13.14 NAME 'MozillaAttribute' SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 X-ORIGIN 'Mozilla Dummy Schema' )\nobjectclasses: ( 1.2.3.4.5.6.7 NAME 'MozillaObject' SUP top MUST ( objectclass $ cn ) MAY ( " + Mozattr1 + " ) X-ORIGIN 'user defined' )" + testschema = "dn: cn=schema\nattributetypes: ( 8.9.10.11.12.13.14 NAME '" + Mozattr1 + "' SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 X-ORIGIN 'Mozilla Dummy Schema' )\nobjectclasses: ( 1.2.3.4.5.6.7 NAME 'MozillaObject' SUP top MUST ( objectclass $ cn ) MAY ( " + Mozattr1 + " ) X-ORIGIN 'user defined' )" tsfd.write(testschema) tsfd.close()
0
b8b1691420e3d3895d65f3447ec2c49fa9d94072
389ds/389-ds-base
Issue 4379 - allow more than 1 empty AttributeDescription for ldapsearch, without the risk of denial of service (#4380) Bug description: The fix #3028 enforces a strict limit of empty attributeDescription. The limit is low (1) and some application may failing. We can relax this limit to a higher value without reopening DOS risk Fix description: Change the max authorized empty attributesDescription from 1 to 10 relates: https://github.com/389ds/389-ds-base/issues/4379 Reviewed by: Mark Reynolds Platforms tested: F31
commit b8b1691420e3d3895d65f3447ec2c49fa9d94072 Author: tbordaz <[email protected]> Date: Thu Oct 15 16:59:56 2020 +0200 Issue 4379 - allow more than 1 empty AttributeDescription for ldapsearch, without the risk of denial of service (#4380) Bug description: The fix #3028 enforces a strict limit of empty attributeDescription. The limit is low (1) and some application may failing. We can relax this limit to a higher value without reopening DOS risk Fix description: Change the max authorized empty attributesDescription from 1 to 10 relates: https://github.com/389ds/389-ds-base/issues/4379 Reviewed by: Mark Reynolds Platforms tested: F31 diff --git a/ldap/servers/slapd/search.c b/ldap/servers/slapd/search.c index 04a42e7bd..f4513026e 100644 --- a/ldap/servers/slapd/search.c +++ b/ldap/servers/slapd/search.c @@ -259,7 +259,7 @@ do_search(Slapi_PBlock *pb) if ( attrs[i][0] == '\0') { empty_attrs++; - if (empty_attrs > 1) { + if (empty_attrs > 10) { log_search_access(pb, base, scope, fstr, "invalid attribute request"); send_ldap_result(pb, LDAP_PROTOCOL_ERROR, NULL, NULL, 0, NULL); slapi_ch_free_string(&normaci);
0
4d32ce1809dfead6697404edaff066608c4bad9d
389ds/389-ds-base
Add require secure binds switch. This adds a new configuration attribute named nsslapd-require-secure-binds. When enabled, a simple bind will only be allowed over a secure transport (SSL/TLS or a SASL privacy layer). An attempt to do a simple bind over an insecure transport will return a LDAP result of LDAP_CONFIDENTIALITY_REQUIRED. This new setting will not affect anonymous or unauthenticated binds. The default setting is to have this option disabled.
commit 4d32ce1809dfead6697404edaff066608c4bad9d Author: Nathan Kinder <[email protected]> Date: Fri May 29 08:38:35 2009 -0700 Add require secure binds switch. This adds a new configuration attribute named nsslapd-require-secure-binds. When enabled, a simple bind will only be allowed over a secure transport (SSL/TLS or a SASL privacy layer). An attempt to do a simple bind over an insecure transport will return a LDAP result of LDAP_CONFIDENTIALITY_REQUIRED. This new setting will not affect anonymous or unauthenticated binds. The default setting is to have this option disabled. diff --git a/ldap/ldif/template-dse.ldif.in b/ldap/ldif/template-dse.ldif.in index 54a9c4f49..82326d559 100644 --- a/ldap/ldif/template-dse.ldif.in +++ b/ldap/ldif/template-dse.ldif.in @@ -30,6 +30,7 @@ nsslapd-rewrite-rfc1274: off nsslapd-return-exact-case: on nsslapd-ssl-check-hostname: on nsslapd-allow-unauthenticated-binds: off +nsslapd-require-secure-binds: off nsslapd-port: %ds_port% nsslapd-localuser: %ds_user% nsslapd-errorlog-logging-enabled: on diff --git a/ldap/servers/slapd/bind.c b/ldap/servers/slapd/bind.c index fbf9a19b8..359252f46 100644 --- a/ldap/servers/slapd/bind.c +++ b/ldap/servers/slapd/bind.c @@ -439,6 +439,7 @@ do_bind( Slapi_PBlock *pb ) plugin_call_plugins( pb, SLAPI_PLUGIN_POST_BIND_FN ); } goto free_and_return; + /* Check if unauthenticated binds are allowed. */ } else if ( cred.bv_len == 0 ) { /* Increment unauthenticated bind counter */ slapi_counter_increment(g_get_global_snmp_vars()->ops_tbl.dsUnAuthBinds); @@ -454,6 +455,29 @@ do_bind( Slapi_PBlock *pb ) slapi_counter_increment(g_get_global_snmp_vars()->ops_tbl.dsBindSecurityErrors); goto free_and_return; } + /* Check if simple binds are allowed over an insecure channel. We only check + * this for authenticated binds. */ + } else if (config_get_require_secure_binds() == 1) { + Connection *conn = NULL; + int sasl_ssf = 0; + + /* Allow simple binds only for SSL/TLS established connections + * or connections using SASL privacy layers */ + conn = pb->pb_conn; + if ( slapi_pblock_get(pb, SLAPI_CONN_SASL_SSF, &sasl_ssf) != 0) { + slapi_log_error( SLAPI_LOG_PLUGIN, "do_bind", + "Could not get SASL SSF from connection\n" ); + sasl_ssf = 0; + } + + if (((conn->c_flags & CONN_FLAG_SSL) != CONN_FLAG_SSL) && + (sasl_ssf <= 1) ) { + send_ldap_result(pb, LDAP_CONFIDENTIALITY_REQUIRED, NULL, + "Operation requires a secure connection", + 0, NULL); + slapi_counter_increment(g_get_global_snmp_vars()->ops_tbl.dsBindSecurityErrors); + goto free_and_return; + } } break; default: diff --git a/ldap/servers/slapd/libglobs.c b/ldap/servers/slapd/libglobs.c index 1155c8c71..358a745ad 100644 --- a/ldap/servers/slapd/libglobs.c +++ b/ldap/servers/slapd/libglobs.c @@ -606,7 +606,11 @@ static struct config_get_and_set { {CONFIG_UNAUTH_BINDS_ATTRIBUTE, config_set_unauth_binds_switch, NULL, 0, (void**)&global_slapdFrontendConfig.allow_unauth_binds, CONFIG_ON_OFF, - (ConfigGetFunc)config_get_unauth_binds_switch} + (ConfigGetFunc)config_get_unauth_binds_switch}, + {CONFIG_REQUIRE_SECURE_BINDS_ATTRIBUTE, config_set_require_secure_binds, + NULL, 0, + (void**)&global_slapdFrontendConfig.require_secure_binds, CONFIG_ON_OFF, + (ConfigGetFunc)config_get_require_secure_binds} #ifdef MEMPOOL_EXPERIMENTAL ,{CONFIG_MEMPOOL_SWITCH_ATTRIBUTE, config_set_mempool_switch, NULL, 0, @@ -857,6 +861,7 @@ FrontendConfig_init () { cfg->ldapi_auto_dn_suffix = slapi_ch_strdup("cn=peercred,cn=external,cn=auth"); #endif cfg->allow_unauth_binds = LDAP_OFF; + cfg->require_secure_binds = LDAP_OFF; cfg->slapi_counters = LDAP_ON; cfg->threadnumber = SLAPD_DEFAULT_MAX_THREADS; cfg->maxthreadsperconn = SLAPD_DEFAULT_MAX_THREADS_PER_CONN; @@ -4544,6 +4549,19 @@ config_get_unauth_binds_switch(void) } +int +config_get_require_secure_binds(void) +{ + int retVal; + slapdFrontendConfig_t *slapdFrontendConfig = getFrontendConfig(); + CFG_LOCK_READ(slapdFrontendConfig); + retVal = slapdFrontendConfig->require_secure_binds; + CFG_UNLOCK_READ(slapdFrontendConfig); + +return retVal; +} + + int config_is_slapd_lite () { @@ -5310,6 +5328,22 @@ config_set_unauth_binds_switch( const char *attrname, char *value, return retVal; } +int +config_set_require_secure_binds( const char *attrname, char *value, + char *errorbuf, int apply ) +{ + int retVal = LDAP_SUCCESS; + slapdFrontendConfig_t *slapdFrontendConfig = getFrontendConfig(); + + retVal = config_set_onoff(attrname, + value, + &(slapdFrontendConfig->require_secure_binds), + errorbuf, + apply); + + return retVal; +} + /* * This function is intended to be used from the dse code modify callback. It diff --git a/ldap/servers/slapd/proto-slap.h b/ldap/servers/slapd/proto-slap.h index 41c80b596..6c7426e28 100644 --- a/ldap/servers/slapd/proto-slap.h +++ b/ldap/servers/slapd/proto-slap.h @@ -343,6 +343,7 @@ int config_set_rewrite_rfc1274( const char *attrname, char *value, char *errorbu int config_set_outbound_ldap_io_timeout( const char *attrname, char *value, char *errorbuf, int apply ); int config_set_unauth_binds_switch(const char *attrname, char *value, char *errorbuf, int apply ); +int config_set_require_secure_binds(const char *attrname, char *value, char *errorbuf, int apply ); int config_set_accesslogbuffering(const char *attrname, char *value, char *errorbuf, int apply); int config_set_csnlogging(const char *attrname, char *value, char *errorbuf, int apply); @@ -471,6 +472,7 @@ int config_get_hash_filters(); int config_get_rewrite_rfc1274(); int config_get_outbound_ldap_io_timeout(void); int config_get_unauth_binds_switch(void); +int config_get_require_secure_binds(void); int config_get_csnlogging(); #ifdef MEMPOOL_EXPERIMENTAL int config_get_mempool_switch(); diff --git a/ldap/servers/slapd/slap.h b/ldap/servers/slapd/slap.h index f0d21910a..ffcba46c5 100644 --- a/ldap/servers/slapd/slap.h +++ b/ldap/servers/slapd/slap.h @@ -1715,6 +1715,7 @@ typedef struct _slapdEntryPoints { #define CONFIG_USERAT_ATTRIBUTE "nsslapd-userat" #define CONFIG_SVRTAB_ATTRIBUTE "nsslapd-svrtab" #define CONFIG_UNAUTH_BINDS_ATTRIBUTE "nsslapd-allow-unauthenticated-binds" +#define CONFIG_REQUIRE_SECURE_BINDS_ATTRIBUTE "nsslapd-require-secure-binds" #ifndef _WIN32 #define CONFIG_LOCALUSER_ATTRIBUTE "nsslapd-localuser" #endif /* !_WIN32 */ @@ -2008,6 +2009,7 @@ typedef struct _slapdFrontendConfig { char *ldapi_auto_dn_suffix; /* suffix to be appended to auto gen DNs */ int slapi_counters; /* switch to turn slapi_counters on/off */ int allow_unauth_binds; /* switch to enable/disable unauthenticated binds */ + int require_secure_binds; /* switch to require simple binds to use a secure channel */ size_t maxsasliosize; /* limit incoming SASL IO packet size */ #ifndef _WIN32 struct passwd *localuserinfo; /* userinfo of localuser */
0
e38dc4e8265dd22d4d194dd99b4a5f8f19fc8c7a
389ds/389-ds-base
Ticket #555 - add fixup-memberuid.pl script Description: add fixup-memberuid.pl script https://fedorahosted.org/389/ticket/555 Reviewed by [email protected]
commit e38dc4e8265dd22d4d194dd99b4a5f8f19fc8c7a Author: Carsten Grzemba <[email protected]> Date: Fri Jan 11 15:45:00 2013 +0100 Ticket #555 - add fixup-memberuid.pl script Description: add fixup-memberuid.pl script https://fedorahosted.org/389/ticket/555 Reviewed by [email protected] diff --git a/ldap/admin/src/scripts/template-fixup-memberuid.pl.in b/ldap/admin/src/scripts/template-fixup-memberuid.pl.in new file mode 100644 index 000000000..8ac4f86b6 --- /dev/null +++ b/ldap/admin/src/scripts/template-fixup-memberuid.pl.in @@ -0,0 +1,180 @@ +#{{PERL-EXEC}} +# +# 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) 2001 Sun Microsystems, Inc. Used by permission. +# Copyright (C) 2014 Red Hat, Inc. +# All rights reserved. +# END COPYRIGHT BLOCK +# + +sub usage { + print(STDERR "Usage: $0 [-v] -D rootdn { -w password | -w - | -j filename } \n"); + print(STDERR " -b baseDN [-f filter]\n"); + print(STDERR " Opts: -D rootdn - Directory Manager\n"); + print(STDERR " : -w password - Directory Manager's password\n"); + print(STDERR " : -w - - Prompt for Directory Manager's password\n"); + print(STDERR " : -j filename - Read Directory Manager's password from file\n"); + print(STDERR " : -b baseDN - Base DN that contains entries to fix up.\n"); + print(STDERR " : -f filter - Filter for entries to fix up\n"); + print(STDERR " If omitted, all entries under the specified\n"); + print(STDERR " base will have their memberUid attribute\n"); + print(STDERR " regenerated.\n"); + print(STDERR " : -v - verbose\n"); +} + +$rootdn = ""; +$passwd = ""; +$passwdfile = ""; +$basedn_arg = ""; +$filter_arg = ""; +$filter = ""; +$verbose = 0; + +$prefix = "{{DS-ROOT}}"; + +$ENV{'PATH'} = "$prefix@ldaptool_bindir@:$prefix/usr/bin:@ldaptool_bindir@:/usr/bin"; + +libpath_add("$prefix@nss_libdir@"); +libpath_add("$prefix/usr/lib"); +libpath_add("@nss_libdir@"); +libpath_add("/usr/lib"); + +$ENV{'SHLIB_PATH'} = "$ENV{'LD_LIBRARY_PATH'}"; + +$i = 0; +while ($i <= $#ARGV) +{ + if ("$ARGV[$i]" eq "-b") + { + # base DN + $i++; $basedn_arg = $ARGV[$i]; + } + elsif ("$ARGV[$i]" eq "-f") + { + # filter + $i++; $filter_arg = $ARGV[$i]; + } + elsif ("$ARGV[$i]" eq "-D") + { + # Directory Manager + $i++; $rootdn = $ARGV[$i]; + } + elsif ("$ARGV[$i]" eq "-w") + { + # Directory Manager's password + $i++; $passwd = $ARGV[$i]; + } + elsif ("$ARGV[$i]" eq "-j") + { + # Read Directory Manager's password from a file + $i++; $passwdfile = $ARGV[$i]; + } + elsif ("$ARGV[$i]" eq "-v") + { + # verbose + $verbose = 1; + } + else + { + &usage; exit(1); + } + $i++; +} + +if ($passwdfile ne ""){ +# Open file and get the password + unless (open (RPASS, $passwdfile)) { + die "Error, cannot open password file $passwdfile\n"; + } + $passwd = <RPASS>; + chomp($passwd); + close(RPASS); +} elsif ($passwd eq "-"){ +# Read the password from terminal + print "Bind Password: "; + # Disable console echo + system("@sttyexec@ -echo") if -t STDIN; + # read the answer + $passwd = <STDIN>; + # Enable console echo + system("@sttyexec@ echo") if -t STDIN; + print "\n"; + chop($passwd); # trim trailing newline +} + +if ( $rootdn eq "" || $passwd eq "" || $basedn_arg eq "" ) +{ + &usage; + exit(1); +} + +$vstr = ""; +if ($verbose != 0) +{ + $vstr = "-v"; +} + +# Use a timestamp as part of the task entry name +($s, $m, $h, $dy, $mn, $yr, $wdy, $ydy, $r) = localtime(time); +$mn++; $yr += 1900; +$taskname = "memberUid_fixup_${yr}_${mn}_${dy}_${h}_${m}_${s}"; + +# Build the task entry to add +$dn = "dn: cn=$taskname, cn=memberuid task, cn=tasks, cn=config\n"; +$misc = "changetype: add\nobjectclass: top\nobjectclass: extensibleObject\n"; +$cn = "cn: $taskname\n"; +$basedn = "basedn: $basedn_arg\n"; + +if ( $filter_arg ne "" ) +{ + $filter = "filter: $filter_arg\n"; +} + +$entry = "${dn}${misc}${cn}${basedn}${filter}"; +open(FOO, "| ldapmodify @ldaptool_opts@ $vstr -h {{SERVER-NAME}} -p {{SERVER-PORT}} -D \"$rootdn\" -w \"$passwd\" -a" ); +print(FOO "$entry"); +close(FOO); + +sub libpath_add { + my $libpath = shift; + + if ($libpath) { + if ($ENV{'LD_LIBRARY_PATH'}) { + $ENV{'LD_LIBRARY_PATH'} = "$ENV{'LD_LIBRARY_PATH'}:$libpath"; + } else { + $ENV{'LD_LIBRARY_PATH'} = "$libpath"; + } + } +}
0
a3beee453120e56881e5052948f6787b958b2a3b
389ds/389-ds-base
Issue 49761 - Fix CI test suite issues Description: Fix plugins acceptace test suite by adding a test attribute to the schema since the schema filter check can return invalid search results. Relates: https://pagure.io/389-ds-base/issue/49761 Reviewed by: mhonek (Thanks!)
commit a3beee453120e56881e5052948f6787b958b2a3b Author: Viktor Ashirov <[email protected]> Date: Sat Jan 25 12:48:42 2020 +0100 Issue 49761 - Fix CI test suite issues Description: Fix plugins acceptace test suite by adding a test attribute to the schema since the schema filter check can return invalid search results. Relates: https://pagure.io/389-ds-base/issue/49761 Reviewed by: mhonek (Thanks!) diff --git a/dirsrvtests/tests/suites/plugins/acceptance_test.py b/dirsrvtests/tests/suites/plugins/acceptance_test.py index cdb629eef..c4b68e29b 100644 --- a/dirsrvtests/tests/suites/plugins/acceptance_test.py +++ b/dirsrvtests/tests/suites/plugins/acceptance_test.py @@ -153,6 +153,11 @@ def test_acctpolicy(topo, args=None): ############################################################################ # Change config - change the stateAttrName to a new attribute ############################################################################ + test_attribute = "( 2.16.840.1.113719.1.1.4.1.35999 \ + NAME 'testLastLoginTime' DESC 'Test Last login time' \ + SYNTAX 1.3.6.1.4.1.1466.115.121.1.24 SINGLE-VALUE USAGE \ + directoryOperation X-ORIGIN 'dirsrvtests' )" + Schema(inst).add('attributetypes', test_attribute) ap_config.replace('stateattrname', 'testLastLoginTime') ############################################################################
0