pdb_samba_dsdb: implement pdb_samba_dsdb_enum_trusteddoms()
[bbaumbach/samba-autobuild/.git] / source3 / passdb / pdb_ldap.c
index 658d774fefd03d100e8e89d6fe7e97c426db0bea..c495448dcc57ef3314cd87ba7ac3ef13f8d92786 100644 (file)
 */
 
 #include "includes.h"
+#include "passdb.h"
 #include "../libcli/auth/libcli_auth.h"
 #include "secrets.h"
 #include "idmap_cache.h"
+#include "../libcli/security/security.h"
+#include "../lib/util/util_pw.h"
+#include "lib/winbind_util.h"
+#include "librpc/gen_ndr/idmap.h"
+#include "lib/param/loadparm.h"
+#include "lib/util_sid_passdb.h"
 
 #undef DBGC_CLASS
 #define DBGC_CLASS DBGC_PASSDB
 #include <lber.h>
 #include <ldap.h>
 
-/*
- * Work around versions of the LDAP client libs that don't have the OIDs
- * defined, or have them defined under the old name.  
- * This functionality is really a factor of the server, not the client 
- *
- */
-
-#if defined(LDAP_EXOP_X_MODIFY_PASSWD) && !defined(LDAP_EXOP_MODIFY_PASSWD)
-#define LDAP_EXOP_MODIFY_PASSWD LDAP_EXOP_X_MODIFY_PASSWD
-#elif !defined(LDAP_EXOP_MODIFY_PASSWD)
-#define LDAP_EXOP_MODIFY_PASSWD "1.3.6.1.4.1.4203.1.11.1"
-#endif
-
-#if defined(LDAP_EXOP_X_MODIFY_PASSWD_ID) && !defined(LDAP_EXOP_MODIFY_PASSWD_ID)
-#define LDAP_TAG_EXOP_MODIFY_PASSWD_ID LDAP_EXOP_X_MODIFY_PASSWD_ID
-#elif !defined(LDAP_EXOP_MODIFY_PASSWD_ID)
-#define LDAP_TAG_EXOP_MODIFY_PASSWD_ID        ((ber_tag_t) 0x80U)
-#endif
-
-#if defined(LDAP_EXOP_X_MODIFY_PASSWD_NEW) && !defined(LDAP_EXOP_MODIFY_PASSWD_NEW)
-#define LDAP_TAG_EXOP_MODIFY_PASSWD_NEW LDAP_EXOP_X_MODIFY_PASSWD_NEW
-#elif !defined(LDAP_EXOP_MODIFY_PASSWD_NEW)
-#define LDAP_TAG_EXOP_MODIFY_PASSWD_NEW       ((ber_tag_t) 0x82U)
-#endif
-
 
 #include "smbldap.h"
+#include "passdb/pdb_ldap.h"
+#include "passdb/pdb_nds.h"
+#include "passdb/pdb_ldap_util.h"
+#include "passdb/pdb_ldap_schema.h"
 
 /**********************************************************************
  Simple helper function to make stuff better readable
  **********************************************************************/
 
-static LDAP *priv2ld(struct ldapsam_privates *priv)
+LDAP *priv2ld(struct ldapsam_privates *priv)
 {
-       return priv->smbldap_state->ldap_struct;
+       return smbldap_get_ldap(priv->smbldap_state);
 }
 
 /**********************************************************************
@@ -98,9 +84,6 @@ static LDAP *priv2ld(struct ldapsam_privates *priv)
 static const char* get_userattr_key2string( int schema_ver, int key )
 {
        switch ( schema_ver ) {
-               case SCHEMAVER_SAMBAACCOUNT:
-                       return get_attr_key2string( attrib_map_v22, key );
-
                case SCHEMAVER_SAMBASAMACCOUNT:
                        return get_attr_key2string( attrib_map_v30, key );
 
@@ -118,9 +101,6 @@ static const char* get_userattr_key2string( int schema_ver, int key )
 const char** get_userattr_list( TALLOC_CTX *mem_ctx, int schema_ver )
 {
        switch ( schema_ver ) {
-               case SCHEMAVER_SAMBAACCOUNT:
-                       return get_attr_list( mem_ctx, attrib_map_v22 );
-
                case SCHEMAVER_SAMBASAMACCOUNT:
                        return get_attr_list( mem_ctx, attrib_map_v30 );
                default:
@@ -139,10 +119,6 @@ static const char** get_userattr_delete_list( TALLOC_CTX *mem_ctx,
                                              int schema_ver )
 {
        switch ( schema_ver ) {
-               case SCHEMAVER_SAMBAACCOUNT:
-                       return get_attr_list( mem_ctx,
-                                             attrib_map_to_delete_v22 );
-
                case SCHEMAVER_SAMBASAMACCOUNT:
                        return get_attr_list( mem_ctx,
                                              attrib_map_to_delete_v30 );
@@ -166,9 +142,6 @@ static const char* get_objclass_filter( int schema_ver )
        char *result;
 
        switch( schema_ver ) {
-               case SCHEMAVER_SAMBAACCOUNT:
-                       fstr_sprintf( objclass_filter, "(objectclass=%s)", LDAP_OBJ_SAMBAACCOUNT );
-                       break;
                case SCHEMAVER_SAMBASAMACCOUNT:
                        fstr_sprintf( objclass_filter, "(objectclass=%s)", LDAP_OBJ_SAMBASAMACCOUNT );
                        break;
@@ -218,9 +191,11 @@ static NTSTATUS ldapsam_get_seq_num(struct pdb_methods *my_methods, time_t *seq_
                return ntstatus;
        }
 
-       if (!smbldap_has_naming_context(ldap_state->smbldap_state->ldap_struct, lp_ldap_suffix())) {
+       if (!smbldap_has_naming_context(
+                   smbldap_get_ldap(ldap_state->smbldap_state),
+                   lp_ldap_suffix(talloc_tos()))) {
                DEBUG(3,("ldapsam_get_seq_num: DIT not configured to hold %s "
-                        "as top-level namingContext\n", lp_ldap_suffix()));
+                        "as top-level namingContext\n", lp_ldap_suffix(talloc_tos())));
                return ntstatus;
        }
 
@@ -229,7 +204,7 @@ static NTSTATUS ldapsam_get_seq_num(struct pdb_methods *my_methods, time_t *seq_
        if (mem_ctx == NULL)
                return NT_STATUS_NO_MEMORY;
 
-       if ((attrs = TALLOC_ARRAY(mem_ctx, const char *, 2)) == NULL) {
+       if ((attrs = talloc_array(mem_ctx, const char *, 2)) == NULL) {
                ntstatus = NT_STATUS_NO_MEMORY;
                goto done;
        }
@@ -243,7 +218,7 @@ static NTSTATUS ldapsam_get_seq_num(struct pdb_methods *my_methods, time_t *seq_
                attrs[0] = talloc_strdup(mem_ctx, "syncreplCookie");
                attrs[1] = NULL;
                suffix = talloc_asprintf(mem_ctx,
-                               "cn=syncrepl%d,%s", rid, lp_ldap_suffix());
+                               "cn=syncrepl%d,%s", rid, lp_ldap_suffix(talloc_tos()));
                if (!suffix) {
                        ntstatus = NT_STATUS_NO_MEMORY;
                        goto done;
@@ -255,7 +230,7 @@ static NTSTATUS ldapsam_get_seq_num(struct pdb_methods *my_methods, time_t *seq_
                attrs[0] = talloc_strdup(mem_ctx, "contextCSN");
                attrs[1] = NULL;
                suffix = talloc_asprintf(mem_ctx,
-                               "cn=ldapsync,%s", lp_ldap_suffix());
+                               "cn=ldapsync,%s", lp_ldap_suffix(talloc_tos()));
 
                if (!suffix) {
                        ntstatus = NT_STATUS_NO_MEMORY;
@@ -270,19 +245,22 @@ static NTSTATUS ldapsam_get_seq_num(struct pdb_methods *my_methods, time_t *seq_
                goto done;
        }
 
-       num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg);
+       num_result = ldap_count_entries(
+               smbldap_get_ldap(ldap_state->smbldap_state), msg);
        if (num_result != 1) {
                DEBUG(3,("ldapsam_get_seq_num: Expected one entry, got %d\n", num_result));
                goto done;
        }
 
-       entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, msg);
+       entry = ldap_first_entry(
+               smbldap_get_ldap(ldap_state->smbldap_state), msg);
        if (entry == NULL) {
                DEBUG(3,("ldapsam_get_seq_num: Could not retrieve entry\n"));
                goto done;
        }
 
-       values = ldap_get_values(ldap_state->smbldap_state->ldap_struct, entry, attrs[0]);
+       values = ldap_get_values(
+               smbldap_get_ldap(ldap_state->smbldap_state), entry, attrs[0]);
        if (values == NULL) {
                DEBUG(3,("ldapsam_get_seq_num: no values\n"));
                goto done;
@@ -373,29 +351,6 @@ int ldapsam_search_suffix_by_name(struct ldapsam_privates *ldap_state,
        return ret;
 }
 
-/*******************************************************************
- Run the search by rid.
-******************************************************************/
-
-static int ldapsam_search_suffix_by_rid (struct ldapsam_privates *ldap_state,
-                                        uint32_t rid, LDAPMessage ** result,
-                                        const char **attr)
-{
-       char *filter = NULL;
-       int rc;
-
-       filter = talloc_asprintf(talloc_tos(), "(&(rid=%i)%s)", rid,
-               get_objclass_filter(ldap_state->schema_ver));
-       if (!filter) {
-               return LDAP_NO_MEMORY;
-       }
-
-       rc = smbldap_search_suffix(ldap_state->smbldap_state,
-                       filter, attr, result);
-       TALLOC_FREE(filter);
-       return rc;
-}
-
 /*******************************************************************
  Run the search by SID.
 ******************************************************************/
@@ -475,7 +430,7 @@ static int ldapsam_delete_entry(struct ldapsam_privates *priv,
        }
 
        smbldap_set_mod(&mods, LDAP_MOD_DELETE, "objectClass", objectclass);
-       talloc_autofree_ldapmod(mem_ctx, mods);
+       smbldap_talloc_autofree_ldapmod(mem_ctx, mods);
 
        return smbldap_modify(priv->smbldap_state, dn, mods);
 }
@@ -485,8 +440,10 @@ static time_t ldapsam_get_entry_timestamp( struct ldapsam_privates *ldap_state,
        char *temp;
        struct tm tm;
 
-       temp = smbldap_talloc_single_attribute(ldap_state->smbldap_state->ldap_struct, entry,
-                       get_userattr_key2string(ldap_state->schema_ver,LDAP_ATTR_MOD_TIMESTAMP),
+       temp = smbldap_talloc_single_attribute(
+               smbldap_get_ldap(ldap_state->smbldap_state), entry,
+               get_userattr_key2string(ldap_state->schema_ver,
+                                       LDAP_ATTR_MOD_TIMESTAMP),
                        talloc_tos());
        if (!temp) {
                return (time_t) 0;
@@ -517,7 +474,6 @@ static bool init_sam_from_ldap(struct ldapsam_privates *ldap_state,
                        kickoff_time,
                        pass_last_set_time,
                        pass_can_change_time,
-                       pass_must_change_time,
                        ldap_entry_time,
                        bad_password_time;
        char *username = NULL,
@@ -532,7 +488,7 @@ static bool init_sam_from_ldap(struct ldapsam_privates *ldap_state,
                        *workstations = NULL,
                        *munged_dial = NULL;
        uint32_t                user_rid;
-       uint8           smblmpwd[LM_HASH_LEN],
+       uint8_t         smblmpwd[LM_HASH_LEN],
                        smbntpwd[NT_HASH_LEN];
        bool            use_samba_attrs = True;
        uint32_t                acct_ctrl = 0;
@@ -540,7 +496,7 @@ static bool init_sam_from_ldap(struct ldapsam_privates *ldap_state,
        uint16_t                bad_password_count = 0,
                        logon_count = 0;
        uint32_t hours_len;
-       uint8           hours[MAX_HOURS_LEN];
+       uint8_t         hours[MAX_HOURS_LEN];
        char *temp = NULL;
        struct login_cache cache_entry;
        uint32_t                pwHistLen;
@@ -592,7 +548,7 @@ static bool init_sam_from_ldap(struct ldapsam_privates *ldap_state,
 
        if ( ldap_state->schema_ver == SCHEMAVER_SAMBASAMACCOUNT ) {
                if ((temp = smbldap_talloc_single_attribute(
-                               ldap_state->smbldap_state->ldap_struct,
+                               smbldap_get_ldap(ldap_state->smbldap_state),
                                entry,
                                get_userattr_key2string(ldap_state->schema_ver,
                                        LDAP_ATTR_USER_SID),
@@ -601,7 +557,7 @@ static bool init_sam_from_ldap(struct ldapsam_privates *ldap_state,
                }
        } else {
                if ((temp = smbldap_talloc_single_attribute(
-                               ldap_state->smbldap_state->ldap_struct,
+                               smbldap_get_ldap(ldap_state->smbldap_state),
                                entry,
                                get_userattr_key2string(ldap_state->schema_ver,
                                        LDAP_ATTR_USER_RID),
@@ -622,7 +578,7 @@ static bool init_sam_from_ldap(struct ldapsam_privates *ldap_state,
        }
 
        temp = smbldap_talloc_single_attribute(
-                       ldap_state->smbldap_state->ldap_struct,
+                       smbldap_get_ldap(ldap_state->smbldap_state),
                        entry,
                        get_userattr_key2string(ldap_state->schema_ver,
                                LDAP_ATTR_PWD_LAST_SET),
@@ -634,7 +590,7 @@ static bool init_sam_from_ldap(struct ldapsam_privates *ldap_state,
        }
 
        temp = smbldap_talloc_single_attribute(
-                       ldap_state->smbldap_state->ldap_struct,
+                       smbldap_get_ldap(ldap_state->smbldap_state),
                        entry,
                        get_userattr_key2string(ldap_state->schema_ver,
                                LDAP_ATTR_LOGON_TIME),
@@ -645,7 +601,7 @@ static bool init_sam_from_ldap(struct ldapsam_privates *ldap_state,
        }
 
        temp = smbldap_talloc_single_attribute(
-                       ldap_state->smbldap_state->ldap_struct,
+                       smbldap_get_ldap(ldap_state->smbldap_state),
                        entry,
                        get_userattr_key2string(ldap_state->schema_ver,
                                LDAP_ATTR_LOGOFF_TIME),
@@ -656,7 +612,7 @@ static bool init_sam_from_ldap(struct ldapsam_privates *ldap_state,
        }
 
        temp = smbldap_talloc_single_attribute(
-                       ldap_state->smbldap_state->ldap_struct,
+                       smbldap_get_ldap(ldap_state->smbldap_state),
                        entry,
                        get_userattr_key2string(ldap_state->schema_ver,
                                LDAP_ATTR_KICKOFF_TIME),
@@ -667,7 +623,7 @@ static bool init_sam_from_ldap(struct ldapsam_privates *ldap_state,
        }
 
        temp = smbldap_talloc_single_attribute(
-                       ldap_state->smbldap_state->ldap_struct,
+                       smbldap_get_ldap(ldap_state->smbldap_state),
                        entry,
                        get_userattr_key2string(ldap_state->schema_ver,
                                LDAP_ATTR_PWD_CAN_CHANGE),
@@ -678,18 +634,6 @@ static bool init_sam_from_ldap(struct ldapsam_privates *ldap_state,
                                pass_can_change_time, PDB_SET);
        }
 
-       temp = smbldap_talloc_single_attribute(
-                       ldap_state->smbldap_state->ldap_struct,
-                       entry,
-                       get_userattr_key2string(ldap_state->schema_ver,
-                               LDAP_ATTR_PWD_MUST_CHANGE),
-                       ctx);
-       if (temp) {
-               pass_must_change_time = (time_t) atol(temp);
-               pdb_set_pass_must_change_time(sampass,
-                               pass_must_change_time, PDB_SET);
-       }
-
        /* recommend that 'gecos' and 'displayName' should refer to the same
         * attribute OID.  userFullName depreciated, only used by Samba
         * primary rules of LDAP: don't make a new attribute when one is already defined
@@ -697,7 +641,7 @@ static bool init_sam_from_ldap(struct ldapsam_privates *ldap_state,
         */
 
        fullname = smbldap_talloc_single_attribute(
-                       ldap_state->smbldap_state->ldap_struct,
+                       smbldap_get_ldap(ldap_state->smbldap_state),
                        entry,
                        get_userattr_key2string(ldap_state->schema_ver,
                                LDAP_ATTR_DISPLAY_NAME),
@@ -706,7 +650,7 @@ static bool init_sam_from_ldap(struct ldapsam_privates *ldap_state,
                pdb_set_fullname(sampass, fullname, PDB_SET);
        } else {
                fullname = smbldap_talloc_single_attribute(
-                               ldap_state->smbldap_state->ldap_struct,
+                               smbldap_get_ldap(ldap_state->smbldap_state),
                                entry,
                                get_userattr_key2string(ldap_state->schema_ver,
                                        LDAP_ATTR_CN),
@@ -717,7 +661,7 @@ static bool init_sam_from_ldap(struct ldapsam_privates *ldap_state,
        }
 
        dir_drive = smbldap_talloc_single_attribute(
-                       ldap_state->smbldap_state->ldap_struct,
+                       smbldap_get_ldap(ldap_state->smbldap_state),
                        entry,
                        get_userattr_key2string(ldap_state->schema_ver,
                                LDAP_ATTR_HOME_DRIVE),
@@ -729,7 +673,7 @@ static bool init_sam_from_ldap(struct ldapsam_privates *ldap_state,
        }
 
        homedir = smbldap_talloc_single_attribute(
-                       ldap_state->smbldap_state->ldap_struct,
+                       smbldap_get_ldap(ldap_state->smbldap_state),
                        entry,
                        get_userattr_key2string(ldap_state->schema_ver,
                                LDAP_ATTR_HOME_PATH),
@@ -753,7 +697,7 @@ static bool init_sam_from_ldap(struct ldapsam_privates *ldap_state,
        }
 
        logon_script = smbldap_talloc_single_attribute(
-                       ldap_state->smbldap_state->ldap_struct,
+                       smbldap_get_ldap(ldap_state->smbldap_state),
                        entry,
                        get_userattr_key2string(ldap_state->schema_ver,
                                LDAP_ATTR_LOGON_SCRIPT),
@@ -777,7 +721,7 @@ static bool init_sam_from_ldap(struct ldapsam_privates *ldap_state,
        }
 
        profile_path = smbldap_talloc_single_attribute(
-                       ldap_state->smbldap_state->ldap_struct,
+                       smbldap_get_ldap(ldap_state->smbldap_state),
                        entry,
                        get_userattr_key2string(ldap_state->schema_ver,
                                LDAP_ATTR_PROFILE_PATH),
@@ -801,7 +745,7 @@ static bool init_sam_from_ldap(struct ldapsam_privates *ldap_state,
        }
 
        acct_desc = smbldap_talloc_single_attribute(
-                       ldap_state->smbldap_state->ldap_struct,
+                       smbldap_get_ldap(ldap_state->smbldap_state),
                        entry,
                        get_userattr_key2string(ldap_state->schema_ver,
                                LDAP_ATTR_DESC),
@@ -811,7 +755,7 @@ static bool init_sam_from_ldap(struct ldapsam_privates *ldap_state,
        }
 
        workstations = smbldap_talloc_single_attribute(
-                       ldap_state->smbldap_state->ldap_struct,
+                       smbldap_get_ldap(ldap_state->smbldap_state),
                        entry,
                        get_userattr_key2string(ldap_state->schema_ver,
                                LDAP_ATTR_USER_WKS),
@@ -821,7 +765,7 @@ static bool init_sam_from_ldap(struct ldapsam_privates *ldap_state,
        }
 
        munged_dial = smbldap_talloc_single_attribute(
-                       ldap_state->smbldap_state->ldap_struct,
+                       smbldap_get_ldap(ldap_state->smbldap_state),
                        entry,
                        get_userattr_key2string(ldap_state->schema_ver,
                                LDAP_ATTR_MUNGED_DIAL),
@@ -843,7 +787,9 @@ static bool init_sam_from_ldap(struct ldapsam_privates *ldap_state,
 
                /* Make call to Novell eDirectory ldap extension to get clear text password.
                        NOTE: This will only work if we have an SSL connection to eDirectory. */
-               user_dn = smbldap_talloc_dn(ctx, ldap_state->smbldap_state->ldap_struct, entry);
+               user_dn = smbldap_talloc_dn(
+                       ctx, smbldap_get_ldap(ldap_state->smbldap_state),
+                       entry);
                if (user_dn != NULL) {
                        DEBUG(3, ("init_sam_from_ldap: smbldap_talloc_dn(ctx, %s) returned '%s'\n", username, user_dn));
 
@@ -872,7 +818,7 @@ static bool init_sam_from_ldap(struct ldapsam_privates *ldap_state,
 
        if (use_samba_attrs) {
                temp = smbldap_talloc_single_attribute(
-                               ldap_state->smbldap_state->ldap_struct,
+                               smbldap_get_ldap(ldap_state->smbldap_state),
                                entry,
                                get_userattr_key2string(ldap_state->schema_ver,
                                        LDAP_ATTR_LMPW),
@@ -887,7 +833,7 @@ static bool init_sam_from_ldap(struct ldapsam_privates *ldap_state,
                }
 
                temp = smbldap_talloc_single_attribute(
-                               ldap_state->smbldap_state->ldap_struct,
+                               smbldap_get_ldap(ldap_state->smbldap_state),
                                entry,
                                get_userattr_key2string(ldap_state->schema_ver,
                                        LDAP_ATTR_NTPW),
@@ -906,9 +852,9 @@ static bool init_sam_from_ldap(struct ldapsam_privates *ldap_state,
 
        pdb_get_account_policy(PDB_POLICY_PASSWORD_HISTORY, &pwHistLen);
        if (pwHistLen > 0){
-               uint8 *pwhist = NULL;
+               uint8_t *pwhist = NULL;
                int i;
-               char *history_string = TALLOC_ARRAY(ctx, char,
+               char *history_string = talloc_array(ctx, char,
                                                MAX_PW_HISTORY_LEN*64);
 
                if (!history_string) {
@@ -917,16 +863,15 @@ static bool init_sam_from_ldap(struct ldapsam_privates *ldap_state,
 
                pwHistLen = MIN(pwHistLen, MAX_PW_HISTORY_LEN);
 
-               pwhist = TALLOC_ARRAY(ctx, uint8,
-                                     pwHistLen * PW_HISTORY_ENTRY_LEN);
+               pwhist = talloc_zero_array(ctx, uint8_t,
+                                          pwHistLen * PW_HISTORY_ENTRY_LEN);
                if (pwhist == NULL) {
                        DEBUG(0, ("init_sam_from_ldap: talloc failed!\n"));
                        goto fn_exit;
                }
-               memset(pwhist, '\0', pwHistLen * PW_HISTORY_ENTRY_LEN);
 
                if (smbldap_get_single_attribute(
-                               ldap_state->smbldap_state->ldap_struct,
+                               smbldap_get_ldap(ldap_state->smbldap_state),
                                entry,
                                get_userattr_key2string(ldap_state->schema_ver,
                                        LDAP_ATTR_PWD_HISTORY),
@@ -960,7 +905,7 @@ static bool init_sam_from_ldap(struct ldapsam_privates *ldap_state,
        }
 
        temp = smbldap_talloc_single_attribute(
-                       ldap_state->smbldap_state->ldap_struct,
+                       smbldap_get_ldap(ldap_state->smbldap_state),
                        entry,
                        get_userattr_key2string(ldap_state->schema_ver,
                                LDAP_ATTR_ACB_INFO),
@@ -981,7 +926,7 @@ static bool init_sam_from_ldap(struct ldapsam_privates *ldap_state,
        pdb_set_logon_divs(sampass, logon_divs, PDB_SET);
 
        temp = smbldap_talloc_single_attribute(
-                       ldap_state->smbldap_state->ldap_struct,
+                       smbldap_get_ldap(ldap_state->smbldap_state),
                        entry,
                        get_userattr_key2string(ldap_state->schema_ver,
                                LDAP_ATTR_BAD_PASSWORD_COUNT),
@@ -993,7 +938,7 @@ static bool init_sam_from_ldap(struct ldapsam_privates *ldap_state,
        }
 
        temp = smbldap_talloc_single_attribute(
-                       ldap_state->smbldap_state->ldap_struct,
+                       smbldap_get_ldap(ldap_state->smbldap_state),
                        entry,
                        get_userattr_key2string(ldap_state->schema_ver,
                                LDAP_ATTR_BAD_PASSWORD_TIME),
@@ -1005,7 +950,7 @@ static bool init_sam_from_ldap(struct ldapsam_privates *ldap_state,
 
 
        temp = smbldap_talloc_single_attribute(
-                       ldap_state->smbldap_state->ldap_struct,
+                       smbldap_get_ldap(ldap_state->smbldap_state),
                        entry,
                        get_userattr_key2string(ldap_state->schema_ver,
                                LDAP_ATTR_LOGON_COUNT),
@@ -1018,7 +963,7 @@ static bool init_sam_from_ldap(struct ldapsam_privates *ldap_state,
        /* pdb_set_unknown_6(sampass, unknown6, PDB_SET); */
 
        temp = smbldap_talloc_single_attribute(
-                       ldap_state->smbldap_state->ldap_struct,
+                       smbldap_get_ldap(ldap_state->smbldap_state),
                        entry,
                        get_userattr_key2string(ldap_state->schema_ver,
                                LDAP_ATTR_LOGON_HOURS),
@@ -1026,7 +971,7 @@ static bool init_sam_from_ldap(struct ldapsam_privates *ldap_state,
        if (temp) {
                pdb_gethexhours(temp, hours);
                memset((char *)temp, '\0', strlen(temp) +1);
-               pdb_set_hours(sampass, hours, PDB_SET);
+               pdb_set_hours(sampass, hours, hours_len, PDB_SET);
                ZERO_STRUCT(hours);
        }
 
@@ -1036,6 +981,7 @@ static bool init_sam_from_ldap(struct ldapsam_privates *ldap_state,
                bool have_gid = false;
                struct dom_sid mapped_gsid;
                const struct dom_sid *primary_gsid;
+               struct unixid id;
 
                ZERO_STRUCT(unix_pw);
 
@@ -1067,7 +1013,7 @@ static bool init_sam_from_ldap(struct ldapsam_privates *ldap_state,
                                entry,
                                "gecos",
                                ctx);
-               if (unix_pw.pw_gecos) {
+               if (unix_pw.pw_gecos == NULL) {
                        unix_pw.pw_gecos = fullname;
                }
                unix_pw.pw_dir = smbldap_talloc_single_attribute(
@@ -1075,7 +1021,7 @@ static bool init_sam_from_ldap(struct ldapsam_privates *ldap_state,
                                entry,
                                "homeDirectory",
                                ctx);
-               if (unix_pw.pw_dir) {
+               if (unix_pw.pw_dir == NULL) {
                        unix_pw.pw_dir = discard_const_p(char, "");
                }
                unix_pw.pw_shell = smbldap_talloc_single_attribute(
@@ -1083,7 +1029,7 @@ static bool init_sam_from_ldap(struct ldapsam_privates *ldap_state,
                                entry,
                                "loginShell",
                                ctx);
-               if (unix_pw.pw_shell) {
+               if (unix_pw.pw_shell == NULL) {
                        unix_pw.pw_shell = discard_const_p(char, "");
                }
 
@@ -1099,18 +1045,18 @@ static bool init_sam_from_ldap(struct ldapsam_privates *ldap_state,
                        goto fn_exit;
                }
 
-               store_uid_sid_cache(pdb_get_user_sid(sampass),
-                                   sampass->unix_pw->pw_uid);
-               idmap_cache_set_sid2uid(pdb_get_user_sid(sampass),
-                                       sampass->unix_pw->pw_uid);
+               id.id = sampass->unix_pw->pw_uid;
+               id.type = ID_TYPE_UID;
+
+               idmap_cache_set_sid2unixid(pdb_get_user_sid(sampass), &id);
 
                gid_to_sid(&mapped_gsid, sampass->unix_pw->pw_gid);
                primary_gsid = pdb_get_group_sid(sampass);
-               if (primary_gsid && sid_equal(primary_gsid, &mapped_gsid)) {
-                       store_gid_sid_cache(primary_gsid,
-                                           sampass->unix_pw->pw_gid);
-                       idmap_cache_set_sid2gid(primary_gsid,
-                                               sampass->unix_pw->pw_gid);
+               if (primary_gsid && dom_sid_equal(primary_gsid, &mapped_gsid)) {
+                       id.id = sampass->unix_pw->pw_gid;
+                       id.type = ID_TYPE_GID;
+
+                       idmap_cache_set_sid2unixid(primary_gsid, &id);
                }
        }
 
@@ -1174,7 +1120,6 @@ static bool init_ldap_from_sam (struct ldapsam_privates *ldap_state,
                                                    enum pdb_elements))
 {
        char *temp = NULL;
-       uint32_t rid;
 
        if (mods == NULL || sampass == NULL) {
                DEBUG(0, ("init_ldap_from_sam: NULL parameters found!\n"));
@@ -1188,13 +1133,18 @@ static bool init_ldap_from_sam (struct ldapsam_privates *ldap_state,
         * do this on a per-mod basis
         */
        if (need_update(sampass, PDB_USERNAME)) {
-               smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods, 
-                             "uid", pdb_get_username(sampass));
+               smbldap_make_mod(smbldap_get_ldap(ldap_state->smbldap_state),
+                                existing, mods,
+                                "uid", pdb_get_username(sampass));
                if (ldap_state->is_nds_ldap) {
-                       smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods, 
-                                     "cn", pdb_get_username(sampass));
-                       smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods, 
-                                     "sn", pdb_get_username(sampass));
+                       smbldap_make_mod(
+                               smbldap_get_ldap(ldap_state->smbldap_state),
+                               existing, mods,
+                               "cn", pdb_get_username(sampass));
+                       smbldap_make_mod(
+                               smbldap_get_ldap(ldap_state->smbldap_state),
+                               existing, mods,
+                               "sn", pdb_get_username(sampass));
                }
        }
 
@@ -1206,25 +1156,11 @@ static bool init_ldap_from_sam (struct ldapsam_privates *ldap_state,
                const struct dom_sid *user_sid = pdb_get_user_sid(sampass);
 
                switch ( ldap_state->schema_ver ) {
-                       case SCHEMAVER_SAMBAACCOUNT:
-                               if (!sid_peek_check_rid(&ldap_state->domain_sid, user_sid, &rid)) {
-                                       DEBUG(1, ("init_ldap_from_sam: User's SID (%s) is not for this domain (%s), cannot add to LDAP!\n", 
-                                                 sid_string_dbg(user_sid),
-                                                 sid_string_dbg(
-                                                         &ldap_state->domain_sid)));
-                                       return False;
-                               }
-                               if (asprintf(&temp, "%i", rid) < 0) {
-                                       return false;
-                               }
-                               smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
-                                       get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_RID), 
-                                       temp);
-                               SAFE_FREE(temp);
-                               break;
-
                        case SCHEMAVER_SAMBASAMACCOUNT:
-                               smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
+                               smbldap_make_mod(
+                                       smbldap_get_ldap(
+                                               ldap_state->smbldap_state),
+                                       existing, mods,
                                        get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID), 
                                        sid_to_fstring(sid_string, user_sid));
                                break;
@@ -1243,26 +1179,11 @@ static bool init_ldap_from_sam (struct ldapsam_privates *ldap_state,
                const struct dom_sid *group_sid = pdb_get_group_sid(sampass);
 
                switch ( ldap_state->schema_ver ) {
-                       case SCHEMAVER_SAMBAACCOUNT:
-                               if (!sid_peek_check_rid(&ldap_state->domain_sid, group_sid, &rid)) {
-                                       DEBUG(1, ("init_ldap_from_sam: User's Primary Group SID (%s) is not for this domain (%s), cannot add to LDAP!\n",
-                                                 sid_string_dbg(group_sid),
-                                                 sid_string_dbg(
-                                                         &ldap_state->domain_sid)));
-                                       return False;
-                               }
-
-                               if (asprintf(&temp, "%i", rid) < 0) {
-                                       return false;
-                               }
-                               smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
-                                       get_userattr_key2string(ldap_state->schema_ver, 
-                                       LDAP_ATTR_PRIMARY_GROUP_RID), temp);
-                               SAFE_FREE(temp);
-                               break;
-
                        case SCHEMAVER_SAMBASAMACCOUNT:
-                               smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
+                               smbldap_make_mod(
+                                       smbldap_get_ldap(
+                                               ldap_state->smbldap_state),
+                                       existing, mods,
                                        get_userattr_key2string(ldap_state->schema_ver, 
                                        LDAP_ATTR_PRIMARY_GROUP_SID), sid_to_fstring(sid_string, group_sid));
                                break;
@@ -1283,42 +1204,50 @@ static bool init_ldap_from_sam (struct ldapsam_privates *ldap_state,
         */
 
        if (need_update(sampass, PDB_FULLNAME))
-               smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
+               smbldap_make_mod(smbldap_get_ldap(ldap_state->smbldap_state),
+                                existing, mods,
                        get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_DISPLAY_NAME), 
                        pdb_get_fullname(sampass));
 
        if (need_update(sampass, PDB_ACCTDESC))
-               smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
+               smbldap_make_mod(smbldap_get_ldap(ldap_state->smbldap_state),
+                                existing, mods,
                        get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_DESC), 
                        pdb_get_acct_desc(sampass));
 
        if (need_update(sampass, PDB_WORKSTATIONS))
-               smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
+               smbldap_make_mod(smbldap_get_ldap(ldap_state->smbldap_state),
+                                existing, mods,
                        get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_WKS), 
                        pdb_get_workstations(sampass));
 
        if (need_update(sampass, PDB_MUNGEDDIAL))
-               smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
+               smbldap_make_mod(smbldap_get_ldap(ldap_state->smbldap_state),
+                                existing, mods,
                        get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_MUNGED_DIAL), 
                        pdb_get_munged_dial(sampass));
 
        if (need_update(sampass, PDB_SMBHOME))
-               smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
+               smbldap_make_mod(smbldap_get_ldap(ldap_state->smbldap_state),
+                                existing, mods,
                        get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_PATH), 
                        pdb_get_homedir(sampass));
 
        if (need_update(sampass, PDB_DRIVE))
-               smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
+               smbldap_make_mod(smbldap_get_ldap(ldap_state->smbldap_state),
+                                existing, mods,
                        get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_DRIVE), 
                        pdb_get_dir_drive(sampass));
 
        if (need_update(sampass, PDB_LOGONSCRIPT))
-               smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
+               smbldap_make_mod(smbldap_get_ldap(ldap_state->smbldap_state),
+                                existing, mods,
                        get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_SCRIPT), 
                        pdb_get_logon_script(sampass));
 
        if (need_update(sampass, PDB_PROFILE))
-               smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
+               smbldap_make_mod(smbldap_get_ldap(ldap_state->smbldap_state),
+                                existing, mods,
                        get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PROFILE_PATH), 
                        pdb_get_profile_path(sampass));
 
@@ -1326,7 +1255,8 @@ static bool init_ldap_from_sam (struct ldapsam_privates *ldap_state,
                return false;
        }
        if (need_update(sampass, PDB_LOGONTIME))
-               smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
+               smbldap_make_mod(smbldap_get_ldap(ldap_state->smbldap_state),
+                                existing, mods,
                        get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_TIME), temp);
        SAFE_FREE(temp);
 
@@ -1334,7 +1264,8 @@ static bool init_ldap_from_sam (struct ldapsam_privates *ldap_state,
                return false;
        }
        if (need_update(sampass, PDB_LOGOFFTIME))
-               smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
+               smbldap_make_mod(smbldap_get_ldap(ldap_state->smbldap_state),
+                                existing, mods,
                        get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGOFF_TIME), temp);
        SAFE_FREE(temp);
 
@@ -1342,7 +1273,8 @@ static bool init_ldap_from_sam (struct ldapsam_privates *ldap_state,
                return false;
        }
        if (need_update(sampass, PDB_KICKOFFTIME))
-               smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
+               smbldap_make_mod(smbldap_get_ldap(ldap_state->smbldap_state),
+                                existing, mods,
                        get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_KICKOFF_TIME), temp);
        SAFE_FREE(temp);
 
@@ -1350,18 +1282,11 @@ static bool init_ldap_from_sam (struct ldapsam_privates *ldap_state,
                return false;
        }
        if (need_update(sampass, PDB_CANCHANGETIME))
-               smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
+               smbldap_make_mod(smbldap_get_ldap(ldap_state->smbldap_state),
+                                existing, mods,
                        get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_CAN_CHANGE), temp);
        SAFE_FREE(temp);
 
-       if (asprintf(&temp, "%li", (long int)pdb_get_pass_must_change_time(sampass)) < 0) {
-               return false;
-       }
-       if (need_update(sampass, PDB_MUSTCHANGETIME))
-               smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
-                       get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_MUST_CHANGE), temp);
-       SAFE_FREE(temp);
-
        if ((pdb_get_acct_ctrl(sampass)&(ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST))
                        || (lp_ldap_passwd_sync()!=LDAP_PASSWD_SYNC_ONLY)) {
 
@@ -1371,11 +1296,17 @@ static bool init_ldap_from_sam (struct ldapsam_privates *ldap_state,
                                char pwstr[34];
                                pdb_sethexpwd(pwstr, lm_pw,
                                              pdb_get_acct_ctrl(sampass));
-                               smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
+                               smbldap_make_mod(
+                                       smbldap_get_ldap(
+                                               ldap_state->smbldap_state),
+                                       existing, mods,
                                                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LMPW), 
                                                 pwstr);
                        } else {
-                               smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
+                               smbldap_make_mod(
+                                       smbldap_get_ldap(
+                                               ldap_state->smbldap_state),
+                                       existing, mods,
                                                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LMPW), 
                                                 NULL);
                        }
@@ -1386,11 +1317,17 @@ static bool init_ldap_from_sam (struct ldapsam_privates *ldap_state,
                                char pwstr[34];
                                pdb_sethexpwd(pwstr, nt_pw,
                                              pdb_get_acct_ctrl(sampass));
-                               smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
+                               smbldap_make_mod(
+                                       smbldap_get_ldap(
+                                               ldap_state->smbldap_state),
+                                       existing, mods,
                                                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_NTPW), 
                                                 pwstr);
                        } else {
-                               smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
+                               smbldap_make_mod(
+                                       smbldap_get_ldap(
+                                               ldap_state->smbldap_state),
+                                       existing, mods,
                                                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_NTPW), 
                                                 NULL);
                        }
@@ -1412,7 +1349,7 @@ static bool init_ldap_from_sam (struct ldapsam_privates *ldap_state,
                        } else {
                                int i;
                                uint32_t currHistLen = 0;
-                               const uint8 *pwhist = pdb_get_pw_history(sampass, &currHistLen);
+                               const uint8_t *pwhist = pdb_get_pw_history(sampass, &currHistLen);
                                if (pwhist != NULL) {
                                        /* We can only store (1024-1/64 password history entries. */
                                        pwHistLen = MIN(pwHistLen, ((1024-1)/64));
@@ -1426,7 +1363,9 @@ static bool init_ldap_from_sam (struct ldapsam_privates *ldap_state,
                                        }
                                }
                        }
-                       smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
+                       smbldap_make_mod(
+                               smbldap_get_ldap(ldap_state->smbldap_state),
+                               existing, mods,
                                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_HISTORY), 
                                         pwstr);
                        SAFE_FREE(pwstr);
@@ -1437,7 +1376,9 @@ static bool init_ldap_from_sam (struct ldapsam_privates *ldap_state,
                                (long int)pdb_get_pass_last_set_time(sampass)) < 0) {
                                return false;
                        }
-                       smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
+                       smbldap_make_mod(
+                               smbldap_get_ldap(ldap_state->smbldap_state),
+                               existing, mods,
                                get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_LAST_SET), 
                                temp);
                        SAFE_FREE(temp);
@@ -1445,11 +1386,12 @@ static bool init_ldap_from_sam (struct ldapsam_privates *ldap_state,
        }
 
        if (need_update(sampass, PDB_HOURS)) {
-               const uint8 *hours = pdb_get_hours(sampass);
+               const uint8_t *hours = pdb_get_hours(sampass);
                if (hours) {
                        char hourstr[44];
                        pdb_sethexhours(hourstr, hours);
-                       smbldap_make_mod(ldap_state->smbldap_state->ldap_struct,
+                       smbldap_make_mod(
+                               smbldap_get_ldap(ldap_state->smbldap_state),
                                existing,
                                mods,
                                get_userattr_key2string(ldap_state->schema_ver,
@@ -1459,7 +1401,9 @@ static bool init_ldap_from_sam (struct ldapsam_privates *ldap_state,
        }
 
        if (need_update(sampass, PDB_ACCTCTRL))
-               smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
+               smbldap_make_mod(
+                       smbldap_get_ldap(ldap_state->smbldap_state),
+                       existing, mods,
                        get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_ACB_INFO), 
                        pdb_encode_acct_ctrl (pdb_get_acct_ctrl(sampass), NEW_PW_FORMAT_SPACE_PADDED_LEN));
 
@@ -1488,7 +1432,7 @@ static bool init_ldap_from_sam (struct ldapsam_privates *ldap_state,
                                return false;
                        }
                        smbldap_make_mod(
-                               ldap_state->smbldap_state->ldap_struct,
+                               smbldap_get_ldap(ldap_state->smbldap_state),
                                existing, mods,
                                get_userattr_key2string(
                                        ldap_state->schema_ver,
@@ -1500,7 +1444,7 @@ static bool init_ldap_from_sam (struct ldapsam_privates *ldap_state,
                                return false;
                        }
                        smbldap_make_mod(
-                               ldap_state->smbldap_state->ldap_struct,
+                               smbldap_get_ldap(ldap_state->smbldap_state),
                                existing, mods,
                                get_userattr_key2string(
                                        ldap_state->schema_ver,
@@ -1553,7 +1497,7 @@ static void append_attr(TALLOC_CTX *mem_ctx, const char ***attr_list,
                ;
        }
 
-       (*attr_list) = TALLOC_REALLOC_ARRAY(mem_ctx, (*attr_list),
+       (*attr_list) = talloc_realloc(mem_ctx, (*attr_list),
                                            const char *,  i+2);
        SMB_ASSERT((*attr_list) != NULL);
        (*attr_list)[i] = talloc_strdup((*attr_list), new_attr);
@@ -1596,7 +1540,8 @@ static NTSTATUS ldapsam_getsampwnam(struct pdb_methods *my_methods, struct samu
        if ( rc != LDAP_SUCCESS ) 
                return NT_STATUS_NO_SUCH_USER;
 
-       count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
+       count = ldap_count_entries(smbldap_get_ldap(ldap_state->smbldap_state),
+                                  result);
 
        if (count < 1) {
                DEBUG(4, ("ldapsam_getsampwnam: Unable to locate user [%s] count=%d\n", sname, count));
@@ -1608,7 +1553,8 @@ static NTSTATUS ldapsam_getsampwnam(struct pdb_methods *my_methods, struct samu
                return NT_STATUS_NO_SUCH_USER;
        }
 
-       entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
+       entry = ldap_first_entry(smbldap_get_ldap(ldap_state->smbldap_state),
+                                result);
        if (entry) {
                if (!init_sam_from_ldap(ldap_state, user, entry)) {
                        DEBUG(1,("ldapsam_getsampwnam: init_sam_from_ldap failed for user '%s'!\n", sname));
@@ -1617,7 +1563,7 @@ static NTSTATUS ldapsam_getsampwnam(struct pdb_methods *my_methods, struct samu
                }
                pdb_set_backend_private_data(user, result, NULL,
                                             my_methods, PDB_CHANGED);
-               talloc_autofree_ldapmsg(user, result);
+               smbldap_talloc_autofree_ldapmsg(user, result);
                ret = NT_STATUS_OK;
        } else {
                ldap_msgfree(result);
@@ -1630,7 +1576,6 @@ static int ldapsam_get_ldap_user_by_sid(struct ldapsam_privates *ldap_state,
 {
        int rc = -1;
        const char ** attr_list;
-       uint32_t rid;
 
        switch ( ldap_state->schema_ver ) {
                case SCHEMAVER_SAMBASAMACCOUNT: {
@@ -1655,18 +1600,8 @@ static int ldapsam_get_ldap_user_by_sid(struct ldapsam_privates *ldap_state,
                        break;
                }
 
-               case SCHEMAVER_SAMBAACCOUNT:
-                       if (!sid_peek_check_rid(&ldap_state->domain_sid, sid, &rid)) {
-                               return rc;
-                       }
-
-                       attr_list = get_userattr_list(NULL,
-                                                     ldap_state->schema_ver);
-                       rc = ldapsam_search_suffix_by_rid(ldap_state, rid, result, attr_list );
-                       TALLOC_FREE( attr_list );
-
-                       if ( rc != LDAP_SUCCESS ) 
-                               return rc;
+               default:
+                       DEBUG(0,("Invalid schema version specified\n"));
                        break;
        }
        return rc;
@@ -1689,7 +1624,8 @@ static NTSTATUS ldapsam_getsampwsid(struct pdb_methods *my_methods, struct samu
        if (rc != LDAP_SUCCESS)
                return NT_STATUS_NO_SUCH_USER;
 
-       count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
+       count = ldap_count_entries(smbldap_get_ldap(ldap_state->smbldap_state),
+                                  result);
 
        if (count < 1) {
                DEBUG(4, ("ldapsam_getsampwsid: Unable to locate SID [%s] "
@@ -1704,7 +1640,8 @@ static NTSTATUS ldapsam_getsampwsid(struct pdb_methods *my_methods, struct samu
                return NT_STATUS_NO_SUCH_USER;
        }
 
-       entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
+       entry = ldap_first_entry(smbldap_get_ldap(ldap_state->smbldap_state),
+                                result);
        if (!entry) {
                ldap_msgfree(result);
                return NT_STATUS_NO_SUCH_USER;
@@ -1718,7 +1655,7 @@ static NTSTATUS ldapsam_getsampwsid(struct pdb_methods *my_methods, struct samu
 
        pdb_set_backend_private_data(user, result, NULL,
                                     my_methods, PDB_CHANGED);
-       talloc_autofree_ldapmsg(user, result);
+       smbldap_talloc_autofree_ldapmsg(user, result);
        return NT_STATUS_OK;
 }      
 
@@ -1754,8 +1691,10 @@ static NTSTATUS ldapsam_modify_entry(struct pdb_methods *my_methods,
 
                if (!ldap_state->is_nds_ldap) {
 
-                       if (!smbldap_has_extension(ldap_state->smbldap_state->ldap_struct, 
-                                                  LDAP_EXOP_MODIFY_PASSWD)) {
+                       if (!smbldap_has_extension(
+                                   smbldap_get_ldap(
+                                           ldap_state->smbldap_state),
+                                   LDAP_EXOP_MODIFY_PASSWD)) {
                                DEBUG(2, ("ldap password change requested, but LDAP "
                                          "server does not support it -- ignoring\n"));
                                return NT_STATUS_OK;
@@ -1841,7 +1780,9 @@ static NTSTATUS ldapsam_modify_entry(struct pdb_methods *my_methods,
                                return NT_STATUS_OK;
                        }
 
-                       ldap_get_option(ldap_state->smbldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
+                       ldap_get_option(
+                               smbldap_get_ldap(ldap_state->smbldap_state),
+                               LDAP_OPT_ERROR_STRING,
                                        &ld_error);
                        DEBUG(0,("ldapsam_modify_entry: LDAP Password could not be changed for user %s: %s\n\t%s\n",
                                pdb_get_username(newpwd), ldap_err2string(rc), ld_error?ld_error:"unknown"));
@@ -1951,7 +1892,7 @@ static NTSTATUS ldapsam_delete_sam_account(struct pdb_methods *my_methods,
        rc = ldapsam_delete_entry(
                priv, mem_ctx, entry,
                priv->schema_ver == SCHEMAVER_SAMBASAMACCOUNT ?
-               LDAP_OBJ_SAMBASAMACCOUNT : LDAP_OBJ_SAMBAACCOUNT,
+               LDAP_OBJ_SAMBASAMACCOUNT : 0,
                attr_list);
 
        result = (rc == LDAP_SUCCESS) ?
@@ -1962,17 +1903,6 @@ static NTSTATUS ldapsam_delete_sam_account(struct pdb_methods *my_methods,
        return result;
 }
 
-/**********************************************************************
- Helper function to determine for update_sam_account whether
- we need LDAP modification.
-*********************************************************************/
-
-static bool element_is_changed(const struct samu *sampass,
-                              enum pdb_elements element)
-{
-       return IS_SAM_CHANGED(sampass, element);
-}
-
 /**********************************************************************
  Update struct samu.
 *********************************************************************/
@@ -2001,16 +1931,20 @@ static NTSTATUS ldapsam_update_sam_account(struct pdb_methods *my_methods, struc
                }
                pdb_set_backend_private_data(newpwd, result, NULL,
                                             my_methods, PDB_CHANGED);
-               talloc_autofree_ldapmsg(newpwd, result);
+               smbldap_talloc_autofree_ldapmsg(newpwd, result);
        }
 
-       if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) == 0) {
+       if (ldap_count_entries(smbldap_get_ldap(ldap_state->smbldap_state),
+                              result) == 0) {
                DEBUG(0, ("ldapsam_update_sam_account: No user to modify!\n"));
                return NT_STATUS_UNSUCCESSFUL;
        }
 
-       entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
-       dn = smbldap_talloc_dn(talloc_tos(), ldap_state->smbldap_state->ldap_struct, entry);
+       entry = ldap_first_entry(smbldap_get_ldap(ldap_state->smbldap_state),
+                                result);
+       dn = smbldap_talloc_dn(talloc_tos(),
+                              smbldap_get_ldap(ldap_state->smbldap_state),
+                              entry);
        if (!dn) {
                return NT_STATUS_UNSUCCESSFUL;
        }
@@ -2018,7 +1952,7 @@ static NTSTATUS ldapsam_update_sam_account(struct pdb_methods *my_methods, struc
        DEBUG(4, ("ldapsam_update_sam_account: user %s to be modified has dn: %s\n", pdb_get_username(newpwd), dn));
 
        if (!init_ldap_from_sam(ldap_state, entry, &mods, newpwd,
-                               element_is_changed)) {
+                               pdb_element_is_changed)) {
                DEBUG(0, ("ldapsam_update_sam_account: init_ldap_from_sam failed!\n"));
                TALLOC_FREE(dn);
                if (mods != NULL)
@@ -2034,7 +1968,7 @@ static NTSTATUS ldapsam_update_sam_account(struct pdb_methods *my_methods, struc
                return NT_STATUS_OK;
        }
 
-       ret = ldapsam_modify_entry(my_methods,newpwd,dn,mods,LDAP_MOD_REPLACE, element_is_changed);
+       ret = ldapsam_modify_entry(my_methods,newpwd,dn,mods,LDAP_MOD_REPLACE, pdb_element_is_changed);
 
        if (mods != NULL) {
                ldap_mods_free(mods,True);
@@ -2079,7 +2013,7 @@ static NTSTATUS ldapsam_enum_group_memberships(struct pdb_methods *methods,
                                               struct samu *user,
                                               struct dom_sid **pp_sids,
                                               gid_t **pp_gids,
-                                              size_t *p_num_groups);
+                                              uint32_t *p_num_groups);
 
 static NTSTATUS ldapsam_rename_sam_account(struct pdb_methods *my_methods,
                                           struct samu *old_acct,
@@ -2102,13 +2036,13 @@ static NTSTATUS ldapsam_rename_sam_account(struct pdb_methods *my_methods,
        oldname = pdb_get_username(old_acct);
 
        /* rename the posix user */
-       rename_script = SMB_STRDUP(lp_renameuser_script());
+       rename_script = lp_rename_user_script(talloc_tos());
        if (rename_script == NULL) {
                return NT_STATUS_NO_MEMORY;
        }
 
        if (!(*rename_script)) {
-               SAFE_FREE(rename_script);
+               TALLOC_FREE(rename_script);
                return NT_STATUS_ACCESS_DENIED;
        }
 
@@ -2120,9 +2054,14 @@ static NTSTATUS ldapsam_rename_sam_account(struct pdb_methods *my_methods,
           posix name but preserve the case in passdb */
 
        fstrcpy( oldname_lower, oldname );
-       strlower_m( oldname_lower );
+       if (!strlower_m( oldname_lower )) {
+               return NT_STATUS_INVALID_PARAMETER;
+       }
        fstrcpy( newname_lower, newname );
-       strlower_m( newname_lower );
+       if (!strlower_m( newname_lower )) {
+               return NT_STATUS_INVALID_PARAMETER;
+       }
+
        rename_script = realloc_string_sub2(rename_script,
                                        "%unew",
                                        newname_lower,
@@ -2136,12 +2075,12 @@ static NTSTATUS ldapsam_rename_sam_account(struct pdb_methods *my_methods,
                                        oldname_lower,
                                        true,
                                        true);
-       rc = smbrun(rename_script, NULL);
+       rc = smbrun(rename_script, NULL, NULL);
 
        DEBUG(rc ? 0 : 3,("Running the command `%s' gave %d\n",
                          rename_script, rc));
 
-       SAFE_FREE(rename_script);
+       TALLOC_FREE(rename_script);
 
        if (rc == 0) {
                smb_nscd_flush_user_cache();
@@ -2153,18 +2092,6 @@ static NTSTATUS ldapsam_rename_sam_account(struct pdb_methods *my_methods,
        return NT_STATUS_OK;
 }
 
-/**********************************************************************
- Helper function to determine for update_sam_account whether
- we need LDAP modification.
- *********************************************************************/
-
-static bool element_is_set_or_changed(const struct samu *sampass,
-                                     enum pdb_elements element)
-{
-       return (IS_SAM_SET(sampass, element) ||
-               IS_SAM_CHANGED(sampass, element));
-}
-
 /**********************************************************************
  Add struct samu to LDAP.
 *********************************************************************/
@@ -2207,7 +2134,8 @@ static NTSTATUS ldapsam_add_sam_account(struct pdb_methods *my_methods, struct s
                goto fn_exit;
        }
 
-       if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) != 0) {
+       if (ldap_count_entries(smbldap_get_ldap(ldap_state->smbldap_state),
+                              result) != 0) {
                DEBUG(0,("ldapsam_add_sam_account: User '%s' already in the base, with samba attributes\n", 
                         username));
                goto fn_exit;
@@ -2215,11 +2143,14 @@ static NTSTATUS ldapsam_add_sam_account(struct pdb_methods *my_methods, struct s
        ldap_msgfree(result);
        result = NULL;
 
-       if (element_is_set_or_changed(newpwd, PDB_USERSID)) {
+       if (pdb_element_is_set_or_changed(newpwd, PDB_USERSID)) {
                rc = ldapsam_get_ldap_user_by_sid(ldap_state,
                                                  sid, &result);
                if (rc == LDAP_SUCCESS) {
-                       if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) != 0) {
+                       if (ldap_count_entries(
+                                   smbldap_get_ldap(
+                                           ldap_state->smbldap_state),
+                                   result) != 0) {
                                DEBUG(0,("ldapsam_add_sam_account: SID '%s' "
                                         "already in the base, with samba "
                                         "attributes\n", sid_string_dbg(sid)));
@@ -2252,7 +2183,8 @@ static NTSTATUS ldapsam_add_sam_account(struct pdb_methods *my_methods, struct s
                goto fn_exit;
        }
 
-       num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
+       num_result = ldap_count_entries(
+               smbldap_get_ldap(ldap_state->smbldap_state), result);
 
        if (num_result > 1) {
                DEBUG (0, ("ldapsam_add_sam_account: More than one user with that uid exists: bailing out!\n"));
@@ -2263,8 +2195,11 @@ static NTSTATUS ldapsam_add_sam_account(struct pdb_methods *my_methods, struct s
        if (num_result == 1) {
                DEBUG(3,("ldapsam_add_sam_account: User exists without samba attributes: adding them\n"));
                ldap_op = LDAP_MOD_REPLACE;
-               entry = ldap_first_entry (ldap_state->smbldap_state->ldap_struct, result);
-               dn = smbldap_talloc_dn(ctx, ldap_state->smbldap_state->ldap_struct, entry);
+               entry = ldap_first_entry(
+                       smbldap_get_ldap(ldap_state->smbldap_state), result);
+               dn = smbldap_talloc_dn(
+                       ctx, smbldap_get_ldap(ldap_state->smbldap_state),
+                       entry);
                if (!dn) {
                        status = NT_STATUS_NO_MEMORY;
                        goto fn_exit;
@@ -2298,7 +2233,8 @@ static NTSTATUS ldapsam_add_sam_account(struct pdb_methods *my_methods, struct s
                        goto fn_exit;
                }
 
-               num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
+               num_result = ldap_count_entries(
+                       smbldap_get_ldap(ldap_state->smbldap_state), result);
 
                if (num_result > 1) {
                        DEBUG (0, ("ldapsam_add_sam_account: More than one user with specified Sid exists: bailing out!\n"));
@@ -2310,8 +2246,13 @@ static NTSTATUS ldapsam_add_sam_account(struct pdb_methods *my_methods, struct s
 
                        DEBUG(3,("ldapsam_add_sam_account: User exists without samba attributes: adding them\n"));
                        ldap_op = LDAP_MOD_REPLACE;
-                       entry = ldap_first_entry (ldap_state->smbldap_state->ldap_struct, result);
-                       dn = smbldap_talloc_dn (ctx, ldap_state->smbldap_state->ldap_struct, entry);
+                       entry = ldap_first_entry (
+                               smbldap_get_ldap(ldap_state->smbldap_state),
+                               result);
+                       dn = smbldap_talloc_dn (
+                               ctx,
+                               smbldap_get_ldap(ldap_state->smbldap_state),
+                               entry);
                        if (!dn) {
                                status = NT_STATUS_NO_MEMORY;
                                goto fn_exit;
@@ -2335,12 +2276,12 @@ static NTSTATUS ldapsam_add_sam_account(struct pdb_methods *my_methods, struct s
                        dn = talloc_asprintf(ctx,
                                        "uid=%s,%s",
                                        escape_username,
-                                       lp_ldap_machine_suffix());
+                                       lp_ldap_machine_suffix(talloc_tos()));
                } else {
                        dn = talloc_asprintf(ctx,
                                        "uid=%s,%s",
                                        escape_username,
-                                       lp_ldap_user_suffix());
+                                       lp_ldap_user_suffix(talloc_tos()));
                }
 
                SAFE_FREE(escape_username);
@@ -2351,7 +2292,7 @@ static NTSTATUS ldapsam_add_sam_account(struct pdb_methods *my_methods, struct s
        }
 
        if (!init_ldap_from_sam(ldap_state, entry, &mods, newpwd,
-                               element_is_set_or_changed)) {
+                               pdb_element_is_set_or_changed)) {
                DEBUG(0, ("ldapsam_add_sam_account: init_ldap_from_sam failed!\n"));
                if (mods != NULL) {
                        ldap_mods_free(mods, true);
@@ -2364,9 +2305,6 @@ static NTSTATUS ldapsam_add_sam_account(struct pdb_methods *my_methods, struct s
                goto fn_exit;
        }
        switch ( ldap_state->schema_ver ) {
-               case SCHEMAVER_SAMBAACCOUNT:
-                       smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_SAMBAACCOUNT);
-                       break;
                case SCHEMAVER_SAMBASAMACCOUNT:
                        smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_SAMBASAMACCOUNT);
                        break;
@@ -2375,7 +2313,7 @@ static NTSTATUS ldapsam_add_sam_account(struct pdb_methods *my_methods, struct s
                        break;
        }
 
-       ret = ldapsam_modify_entry(my_methods,newpwd,dn,mods,ldap_op, element_is_set_or_changed);
+       ret = ldapsam_modify_entry(my_methods,newpwd,dn,mods,ldap_op, pdb_element_is_set_or_changed);
        if (!NT_STATUS_IS_OK(ret)) {
                DEBUG(0,("ldapsam_add_sam_account: failed to modify/add user with uid = %s (dn = %s)\n",
                         pdb_get_username(newpwd),dn));
@@ -2410,7 +2348,7 @@ static int ldapsam_search_one_group (struct ldapsam_privates *ldap_state,
 
        attr_list = get_attr_list(NULL, groupmap_attr_list);
        rc = smbldap_search(ldap_state->smbldap_state,
-                           lp_ldap_suffix (), scope,
+                           lp_ldap_suffix (talloc_tos()), scope,
                            filter, attr_list, 0, result);
        TALLOC_FREE(attr_list);
 
@@ -2427,14 +2365,14 @@ static bool init_group_from_ldap(struct ldapsam_privates *ldap_state,
        TALLOC_CTX *ctx = talloc_init("init_group_from_ldap");
 
        if (ldap_state == NULL || map == NULL || entry == NULL ||
-                       ldap_state->smbldap_state->ldap_struct == NULL) {
+           smbldap_get_ldap(ldap_state->smbldap_state) == NULL) {
                DEBUG(0, ("init_group_from_ldap: NULL parameters found!\n"));
                TALLOC_FREE(ctx);
                return false;
        }
 
        temp = smbldap_talloc_single_attribute(
-                       ldap_state->smbldap_state->ldap_struct,
+                       smbldap_get_ldap(ldap_state->smbldap_state),
                        entry,
                        get_attr_key2string(groupmap_attr_list,
                                LDAP_ATTR_GIDNUMBER),
@@ -2451,7 +2389,7 @@ static bool init_group_from_ldap(struct ldapsam_privates *ldap_state,
 
        TALLOC_FREE(temp);
        temp = smbldap_talloc_single_attribute(
-                       ldap_state->smbldap_state->ldap_struct,
+                       smbldap_get_ldap(ldap_state->smbldap_state),
                        entry,
                        get_attr_key2string(groupmap_attr_list,
                                LDAP_ATTR_GROUP_SID),
@@ -2471,7 +2409,7 @@ static bool init_group_from_ldap(struct ldapsam_privates *ldap_state,
 
        TALLOC_FREE(temp);
        temp = smbldap_talloc_single_attribute(
-                       ldap_state->smbldap_state->ldap_struct,
+                       smbldap_get_ldap(ldap_state->smbldap_state),
                        entry,
                        get_attr_key2string(groupmap_attr_list,
                                LDAP_ATTR_GROUP_TYPE),
@@ -2493,14 +2431,14 @@ static bool init_group_from_ldap(struct ldapsam_privates *ldap_state,
 
        TALLOC_FREE(temp);
        temp = smbldap_talloc_single_attribute(
-                       ldap_state->smbldap_state->ldap_struct,
+                       smbldap_get_ldap(ldap_state->smbldap_state),
                        entry,
                        get_attr_key2string(groupmap_attr_list,
                                LDAP_ATTR_DISPLAY_NAME),
                        ctx);
        if (!temp) {
                temp = smbldap_talloc_single_attribute(
-                               ldap_state->smbldap_state->ldap_struct,
+                               smbldap_get_ldap(ldap_state->smbldap_state),
                                entry,
                                get_attr_key2string(groupmap_attr_list,
                                        LDAP_ATTR_CN),
@@ -2512,11 +2450,15 @@ for gidNumber(%lu)\n",(unsigned long)map->gid));
                        return false;
                }
        }
-       fstrcpy(map->nt_name, temp);
+       map->nt_name = talloc_strdup(map, temp);
+       if (!map->nt_name) {
+               TALLOC_FREE(ctx);
+               return false;
+       }
 
        TALLOC_FREE(temp);
        temp = smbldap_talloc_single_attribute(
-                       ldap_state->smbldap_state->ldap_struct,
+                       smbldap_get_ldap(ldap_state->smbldap_state),
                        entry,
                        get_attr_key2string(groupmap_attr_list,
                                LDAP_ATTR_DESC),
@@ -2528,11 +2470,18 @@ for gidNumber(%lu)\n",(unsigned long)map->gid));
                        return false;
                }
        }
-       fstrcpy(map->comment, temp);
+       map->comment = talloc_strdup(map, temp);
+       if (!map->comment) {
+               TALLOC_FREE(ctx);
+               return false;
+       }
 
        if (lp_parm_bool(-1, "ldapsam", "trusted", false)) {
-               store_gid_sid_cache(&map->sid, map->gid);
-               idmap_cache_set_sid2gid(&map->sid, map->gid);
+               struct unixid id;
+               id.id = map->gid;
+               id.type = ID_TYPE_GID;
+
+               idmap_cache_set_sid2unixid(&map->sid, &id);
        }
 
        TALLOC_FREE(ctx);
@@ -2682,7 +2631,7 @@ static bool ldapsam_extract_rid_from_entry(LDAP *ldap_struct,
                return False;
        }
 
-       if (sid_compare_domain(&sid, domain_sid) != 0) {
+       if (dom_sid_compare_domain(&sid, domain_sid) != 0) {
                DEBUG(10, ("SID %s is not in expected domain %s\n",
                           str, sid_string_dbg(domain_sid)));
                return False;
@@ -2731,16 +2680,16 @@ static NTSTATUS ldapsam_enum_group_members(struct pdb_methods *methods,
                goto done;
        }
 
-       rc = smbldap_search(conn, lp_ldap_suffix(),
+       rc = smbldap_search(conn, lp_ldap_suffix(talloc_tos()),
                            LDAP_SCOPE_SUBTREE, filter, id_attrs, 0,
                            &result);
 
        if (rc != LDAP_SUCCESS)
                goto done;
 
-       talloc_autofree_ldapmsg(mem_ctx, result);
+       smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
 
-       count = ldap_count_entries(conn->ldap_struct, result);
+       count = ldap_count_entries(smbldap_get_ldap(conn), result);
 
        if (count > 1) {
                DEBUG(1, ("Found more than one groupmap entry for %s\n",
@@ -2754,7 +2703,7 @@ static NTSTATUS ldapsam_enum_group_members(struct pdb_methods *methods,
                goto done;
        }
 
-       entry = ldap_first_entry(conn->ldap_struct, result);
+       entry = ldap_first_entry(smbldap_get_ldap(conn), result);
        if (entry == NULL)
                goto done;
 
@@ -2765,7 +2714,7 @@ static NTSTATUS ldapsam_enum_group_members(struct pdb_methods *methods,
                goto done;
        }
 
-       values = ldap_get_values(conn->ldap_struct, entry, "memberUid");
+       values = ldap_get_values(smbldap_get_ldap(conn), entry, "memberUid");
 
        if ((values != NULL) && (values[0] != NULL)) {
 
@@ -2799,29 +2748,29 @@ static NTSTATUS ldapsam_enum_group_members(struct pdb_methods *methods,
                        goto done;
                }
 
-               rc = smbldap_search(conn, lp_ldap_suffix(),
+               rc = smbldap_search(conn, lp_ldap_suffix(talloc_tos()),
                                    LDAP_SCOPE_SUBTREE, filter, sid_attrs, 0,
                                    &result);
 
                if (rc != LDAP_SUCCESS)
                        goto done;
 
-               count = ldap_count_entries(conn->ldap_struct, result);
+               count = ldap_count_entries(smbldap_get_ldap(conn), result);
                DEBUG(10,("ldapsam_enum_group_members: found %d accounts\n", count));
 
-               talloc_autofree_ldapmsg(mem_ctx, result);
+               smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
 
-               for (entry = ldap_first_entry(conn->ldap_struct, result);
+               for (entry = ldap_first_entry(smbldap_get_ldap(conn), result);
                     entry != NULL;
-                    entry = ldap_next_entry(conn->ldap_struct, entry))
+                    entry = ldap_next_entry(smbldap_get_ldap(conn), entry))
                {
                        char *sidstr;
                        struct dom_sid sid;
                        uint32_t rid;
 
-                       sidstr = smbldap_talloc_single_attribute(conn->ldap_struct,
-                                                                entry, "sambaSID",
-                                                                mem_ctx);
+                       sidstr = smbldap_talloc_single_attribute(
+                               smbldap_get_ldap(conn), entry, "sambaSID",
+                               mem_ctx);
                        if (!sidstr) {
                                DEBUG(0, ("Severe DB error, %s can't miss the sambaSID"
                                          "attribute\n", LDAP_OBJ_SAMBASAMACCOUNT));
@@ -2832,7 +2781,7 @@ static NTSTATUS ldapsam_enum_group_members(struct pdb_methods *methods,
                        if (!string_to_sid(&sid, sidstr))
                                goto done;
 
-                       if (!sid_check_is_in_our_domain(&sid)) {
+                       if (!sid_check_is_in_our_sam(&sid)) {
                                DEBUG(0, ("Inconsistent SAM -- group member uid not "
                                          "in our domain\n"));
                                ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
@@ -2855,22 +2804,22 @@ static NTSTATUS ldapsam_enum_group_members(struct pdb_methods *methods,
                                 LDAP_OBJ_SAMBASAMACCOUNT,
                                 gidstr);
 
-       rc = smbldap_search(conn, lp_ldap_suffix(),
+       rc = smbldap_search(conn, lp_ldap_suffix(talloc_tos()),
                            LDAP_SCOPE_SUBTREE, filter, sid_attrs, 0,
                            &result);
 
        if (rc != LDAP_SUCCESS)
                goto done;
 
-       talloc_autofree_ldapmsg(mem_ctx, result);
+       smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
 
-       for (entry = ldap_first_entry(conn->ldap_struct, result);
+       for (entry = ldap_first_entry(smbldap_get_ldap(conn), result);
             entry != NULL;
-            entry = ldap_next_entry(conn->ldap_struct, entry))
+            entry = ldap_next_entry(smbldap_get_ldap(conn), entry))
        {
                uint32_t rid;
 
-               if (!ldapsam_extract_rid_from_entry(conn->ldap_struct,
+               if (!ldapsam_extract_rid_from_entry(smbldap_get_ldap(conn),
                                                    entry,
                                                    get_global_sam_sid(),
                                                    &rid)) {
@@ -2901,7 +2850,7 @@ static NTSTATUS ldapsam_enum_group_memberships(struct pdb_methods *methods,
                                               struct samu *user,
                                               struct dom_sid **pp_sids,
                                               gid_t **pp_gids,
-                                              size_t *p_num_groups)
+                                              uint32_t *p_num_groups)
 {
        struct ldapsam_privates *ldap_state =
                (struct ldapsam_privates *)methods->private_data;
@@ -2914,7 +2863,7 @@ static NTSTATUS ldapsam_enum_group_memberships(struct pdb_methods *methods,
        LDAPMessage *entry;
        NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
        uint32_t num_sids;
-       size_t num_gids;
+       uint32_t num_gids;
        char *gidstr;
        gid_t primary_gid = -1;
 
@@ -2942,13 +2891,13 @@ static NTSTATUS ldapsam_enum_group_memberships(struct pdb_methods *methods,
                        goto done;
                }
 
-               rc = smbldap_search(conn, lp_ldap_suffix(),
+               rc = smbldap_search(conn, lp_ldap_suffix(talloc_tos()),
                                    LDAP_SCOPE_SUBTREE, filter, attrs, 0, &result);
 
                if (rc != LDAP_SUCCESS)
                        goto done;
 
-               talloc_autofree_ldapmsg(mem_ctx, result);
+               smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
 
                count = ldap_count_entries(priv2ld(ldap_state), result);
 
@@ -2983,13 +2932,13 @@ static NTSTATUS ldapsam_enum_group_memberships(struct pdb_methods *methods,
                goto done;
        }
 
-       rc = smbldap_search(conn, lp_ldap_suffix(),
+       rc = smbldap_search(conn, lp_ldap_suffix(talloc_tos()),
                            LDAP_SCOPE_SUBTREE, filter, attrs, 0, &result);
 
        if (rc != LDAP_SUCCESS)
                goto done;
 
-       talloc_autofree_ldapmsg(mem_ctx, result);
+       smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
 
        num_gids = 0;
        *pp_gids = NULL;
@@ -3012,16 +2961,16 @@ static NTSTATUS ldapsam_enum_group_memberships(struct pdb_methods *methods,
                goto done;
        }
 
-       for (entry = ldap_first_entry(conn->ldap_struct, result);
+       for (entry = ldap_first_entry(smbldap_get_ldap(conn), result);
             entry != NULL;
-            entry = ldap_next_entry(conn->ldap_struct, entry))
+            entry = ldap_next_entry(smbldap_get_ldap(conn), entry))
        {
                fstring str;
                struct dom_sid sid;
                gid_t gid;
                char *end;
 
-               if (!smbldap_get_single_attribute(conn->ldap_struct,
+               if (!smbldap_get_single_attribute(smbldap_get_ldap(conn),
                                                  entry, "sambaSID",
                                                  str, sizeof(str)-1))
                        continue;
@@ -3029,7 +2978,7 @@ static NTSTATUS ldapsam_enum_group_memberships(struct pdb_methods *methods,
                if (!string_to_sid(&sid, str))
                        goto done;
 
-               if (!smbldap_get_single_attribute(conn->ldap_struct,
+               if (!smbldap_get_single_attribute(smbldap_get_ldap(conn),
                                                  entry, "gidNumber",
                                                  str, sizeof(str)-1))
                        continue;
@@ -3055,9 +3004,10 @@ static NTSTATUS ldapsam_enum_group_memberships(struct pdb_methods *methods,
                }
        }
 
-       if (sid_compare(&global_sid_NULL, &(*pp_sids)[0]) == 0) {
+       if (dom_sid_compare(&global_sid_NULL, &(*pp_sids)[0]) == 0) {
                DEBUG(3, ("primary group of [%s] not found\n",
                          pdb_get_username(user)));
+               ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
                goto done;
        }
 
@@ -3094,15 +3044,20 @@ static NTSTATUS ldapsam_map_posixgroup(TALLOC_CTX *mem_ctx,
        rc = smbldap_search_suffix(ldap_state->smbldap_state, filter,
                                   get_attr_list(mem_ctx, groupmap_attr_list),
                                   &msg);
-       talloc_autofree_ldapmsg(mem_ctx, msg);
+       smbldap_talloc_autofree_ldapmsg(mem_ctx, msg);
 
        if ((rc != LDAP_SUCCESS) ||
-           (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) != 1) ||
-           ((entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, msg)) == NULL)) {
+           (ldap_count_entries(smbldap_get_ldap(ldap_state->smbldap_state),
+                               msg) != 1) ||
+           ((entry = ldap_first_entry(
+                     smbldap_get_ldap(ldap_state->smbldap_state),
+                     msg)) == NULL)) {
                return NT_STATUS_NO_SUCH_GROUP;
        }
 
-       dn = smbldap_talloc_dn(mem_ctx, ldap_state->smbldap_state->ldap_struct, entry);
+       dn = smbldap_talloc_dn(mem_ctx,
+                              smbldap_get_ldap(ldap_state->smbldap_state),
+                              entry);
        if (dn == NULL) {
                return NT_STATUS_NO_MEMORY;
        }
@@ -3110,15 +3065,19 @@ static NTSTATUS ldapsam_map_posixgroup(TALLOC_CTX *mem_ctx,
        mods = NULL;
        smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass",
                        LDAP_OBJ_GROUPMAP);
-       smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "sambaSid",
+       smbldap_make_mod(smbldap_get_ldap(ldap_state->smbldap_state), entry,
+                        &mods, "sambaSid",
                         sid_string_talloc(mem_ctx, &map->sid));
-       smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "sambaGroupType",
+       smbldap_make_mod(smbldap_get_ldap(ldap_state->smbldap_state), entry,
+                        &mods, "sambaGroupType",
                         talloc_asprintf(mem_ctx, "%d", map->sid_name_use));
-       smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "displayName",
+       smbldap_make_mod(smbldap_get_ldap(ldap_state->smbldap_state), entry,
+                        &mods, "displayName",
                         map->nt_name);
-       smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "description",
+       smbldap_make_mod(smbldap_get_ldap(ldap_state->smbldap_state), entry,
+                        &mods, "description",
                         map->comment);
-       talloc_autofree_ldapmod(mem_ctx, mods);
+       smbldap_talloc_autofree_ldapmod(mem_ctx, mods);
 
        rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
        if (rc != LDAP_SUCCESS) {
@@ -3143,6 +3102,7 @@ static NTSTATUS ldapsam_add_group_mapping_entry(struct pdb_methods *methods,
        NTSTATUS result;
 
        struct dom_sid sid;
+       struct unixid id;
 
        int rc;
 
@@ -3159,12 +3119,13 @@ static NTSTATUS ldapsam_add_group_mapping_entry(struct pdb_methods *methods,
                goto done;
        }
 
-       rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_suffix(),
+       rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_suffix(talloc_tos()),
                            LDAP_SCOPE_SUBTREE, filter, attrs, True, &msg);
-       talloc_autofree_ldapmsg(mem_ctx, msg);
+       smbldap_talloc_autofree_ldapmsg(mem_ctx, msg);
 
        if ((rc == LDAP_SUCCESS) &&
-           (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) > 0)) {
+           (ldap_count_entries(smbldap_get_ldap(ldap_state->smbldap_state),
+                               msg) > 0)) {
 
                DEBUG(3, ("SID %s already present in LDAP, refusing to add "
                          "group mapping entry\n", sid_string_dbg(&map->sid)));
@@ -3182,7 +3143,7 @@ static NTSTATUS ldapsam_add_group_mapping_entry(struct pdb_methods *methods,
                break;
 
        case SID_NAME_ALIAS:
-               if (!sid_check_is_in_our_domain(&map->sid) 
+               if (!sid_check_is_in_our_sam(&map->sid) 
                        && !sid_check_is_in_builtin(&map->sid) ) 
                {
                        DEBUG(3, ("Refusing to map sid %s as an alias, not in our domain\n",
@@ -3208,7 +3169,10 @@ static NTSTATUS ldapsam_add_group_mapping_entry(struct pdb_methods *methods,
                goto done;
        }
 
-       if (pdb_gid_to_sid(map->gid, &sid)) {
+       id.id = map->gid;
+       id.type = ID_TYPE_GID;
+
+       if (pdb_id_to_sid(&id, &sid)) {
                DEBUG(3, ("Gid %u is already mapped to SID %s, refusing to "
                          "add\n", (unsigned int)map->gid, sid_string_dbg(&sid)));
                result = NT_STATUS_GROUP_EXISTS;
@@ -3220,7 +3184,7 @@ static NTSTATUS ldapsam_add_group_mapping_entry(struct pdb_methods *methods,
 
        dn = talloc_asprintf(mem_ctx, "sambaSid=%s,%s",
                             sid_string_talloc(mem_ctx, &map->sid),
-                            lp_ldap_group_suffix());
+                            lp_ldap_group_suffix(talloc_tos()));
        if (dn == NULL) {
                result = NT_STATUS_NO_MEMORY;
                goto done;
@@ -3228,21 +3192,27 @@ static NTSTATUS ldapsam_add_group_mapping_entry(struct pdb_methods *methods,
 
        mods = NULL;
 
-       smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "objectClass",
-                        LDAP_OBJ_SID_ENTRY);
-       smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "objectClass",
-                        LDAP_OBJ_GROUPMAP);
-       smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "sambaSid",
+       smbldap_make_mod(smbldap_get_ldap(ldap_state->smbldap_state), NULL,
+                        &mods, "objectClass", LDAP_OBJ_SID_ENTRY);
+       smbldap_make_mod(smbldap_get_ldap(ldap_state->smbldap_state), NULL,
+                        &mods, "objectClass", LDAP_OBJ_GROUPMAP);
+       smbldap_make_mod(smbldap_get_ldap(ldap_state->smbldap_state), NULL,
+                        &mods, "sambaSid",
                         sid_string_talloc(mem_ctx, &map->sid));
-       smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "sambaGroupType",
+       smbldap_make_mod(smbldap_get_ldap(ldap_state->smbldap_state), NULL,
+                        &mods, "sambaGroupType",
                         talloc_asprintf(mem_ctx, "%d", map->sid_name_use));
-       smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "displayName",
+       smbldap_make_mod(smbldap_get_ldap(ldap_state->smbldap_state), NULL,
+                        &mods, "displayName",
                         map->nt_name);
-       smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "description",
+       smbldap_make_mod(smbldap_get_ldap(ldap_state->smbldap_state), NULL,
+                        &mods, "description",
                         map->comment);
-       smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "gidNumber",
-                        talloc_asprintf(mem_ctx, "%u", (unsigned int)map->gid));
-       talloc_autofree_ldapmod(mem_ctx, mods);
+       smbldap_make_mod(smbldap_get_ldap(ldap_state->smbldap_state), NULL,
+                        &mods, "gidNumber",
+                        talloc_asprintf(mem_ctx, "%u",
+                                        (unsigned int)map->gid));
+       smbldap_talloc_autofree_ldapmod(mem_ctx, mods);
 
        rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
 
@@ -3296,16 +3266,20 @@ static NTSTATUS ldapsam_update_group_mapping_entry(struct pdb_methods *methods,
        rc = smbldap_search_suffix(ldap_state->smbldap_state, filter,
                                   get_attr_list(mem_ctx, groupmap_attr_list),
                                   &msg);
-       talloc_autofree_ldapmsg(mem_ctx, msg);
+       smbldap_talloc_autofree_ldapmsg(mem_ctx, msg);
 
        if ((rc != LDAP_SUCCESS) ||
-           (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) != 1) ||
-           ((entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, msg)) == NULL)) {
+           (ldap_count_entries(smbldap_get_ldap(ldap_state->smbldap_state),
+                               msg) != 1) ||
+           ((entry = ldap_first_entry(
+                     smbldap_get_ldap(ldap_state->smbldap_state),
+                     msg)) == NULL)) {
                result = NT_STATUS_NO_SUCH_GROUP;
                goto done;
        }
 
-       dn = smbldap_talloc_dn(mem_ctx, ldap_state->smbldap_state->ldap_struct, entry);
+       dn = smbldap_talloc_dn(
+               mem_ctx, smbldap_get_ldap(ldap_state->smbldap_state), entry);
 
        if (dn == NULL) {
                result = NT_STATUS_NO_MEMORY;
@@ -3313,11 +3287,11 @@ static NTSTATUS ldapsam_update_group_mapping_entry(struct pdb_methods *methods,
        }
 
        mods = NULL;
-       smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "displayName",
-                        map->nt_name);
-       smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "description",
-                        map->comment);
-       talloc_autofree_ldapmod(mem_ctx, mods);
+       smbldap_make_mod(smbldap_get_ldap(ldap_state->smbldap_state), entry,
+                        &mods, "displayName", map->nt_name);
+       smbldap_make_mod(smbldap_get_ldap(ldap_state->smbldap_state), entry,
+                        &mods, "description", map->comment);
+       smbldap_talloc_autofree_ldapmod(mem_ctx, mods);
 
        if (mods == NULL) {
                DEBUG(4, ("ldapsam_update_group_mapping_entry: mods is empty: "
@@ -3373,7 +3347,7 @@ static NTSTATUS ldapsam_delete_group_mapping_entry(struct pdb_methods *methods,
        rc = smbldap_search_suffix(priv->smbldap_state, filter,
                                   get_attr_list(mem_ctx, groupmap_attr_list),
                                   &msg);
-       talloc_autofree_ldapmsg(mem_ctx, msg);
+       smbldap_talloc_autofree_ldapmsg(mem_ctx, msg);
 
        if ((rc != LDAP_SUCCESS) ||
            (ldap_count_entries(priv2ld(priv), msg) != 1) ||
@@ -3441,7 +3415,7 @@ static NTSTATUS ldapsam_setsamgrent(struct pdb_methods *my_methods,
                return NT_STATUS_NO_MEMORY;
        }
        attr_list = get_attr_list( NULL, groupmap_attr_list );
-       rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_suffix(),
+       rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_suffix(talloc_tos()),
                            LDAP_SCOPE_SUBTREE, filter,
                            attr_list, 0, &ldap_state->result);
        TALLOC_FREE(attr_list);
@@ -3450,7 +3424,7 @@ static NTSTATUS ldapsam_setsamgrent(struct pdb_methods *my_methods,
                DEBUG(0, ("ldapsam_setsamgrent: LDAP search failed: %s\n",
                          ldap_err2string(rc)));
                DEBUG(3, ("ldapsam_setsamgrent: Query was: %s, %s\n",
-                         lp_ldap_suffix(), filter));
+                         lp_ldap_suffix(talloc_tos()), filter));
                ldap_msgfree(ldap_state->result);
                ldap_state->result = NULL;
                TALLOC_FREE(filter);
@@ -3460,11 +3434,12 @@ static NTSTATUS ldapsam_setsamgrent(struct pdb_methods *my_methods,
        TALLOC_FREE(filter);
 
        DEBUG(2, ("ldapsam_setsamgrent: %d entries in the base!\n",
-                 ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
-                                    ldap_state->result)));
+                 ldap_count_entries(
+                         smbldap_get_ldap(ldap_state->smbldap_state),
+                         ldap_state->result)));
 
        ldap_state->entry =
-               ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
+               ldap_first_entry(smbldap_get_ldap(ldap_state->smbldap_state),
                                 ldap_state->result);
        ldap_state->index = 0;
 
@@ -3498,9 +3473,9 @@ static NTSTATUS ldapsam_getsamgrent(struct pdb_methods *my_methods,
                bret = init_group_from_ldap(ldap_state, map,
                                            ldap_state->entry);
 
-               ldap_state->entry =
-                       ldap_next_entry(ldap_state->smbldap_state->ldap_struct,
-                                       ldap_state->entry);     
+               ldap_state->entry = ldap_next_entry(
+                       smbldap_get_ldap(ldap_state->smbldap_state),
+                       ldap_state->entry);
        }
 
        return NT_STATUS_OK;
@@ -3511,11 +3486,11 @@ static NTSTATUS ldapsam_getsamgrent(struct pdb_methods *my_methods,
 
 static NTSTATUS ldapsam_enum_group_mapping(struct pdb_methods *methods,
                                           const struct dom_sid *domsid, enum lsa_SidType sid_name_use,
-                                          GROUP_MAP **pp_rmap,
+                                          GROUP_MAP ***pp_rmap,
                                           size_t *p_num_entries,
                                           bool unix_only)
 {
-       GROUP_MAP map;
+       GROUP_MAP *map = NULL;
        size_t entries = 0;
 
        *p_num_entries = 0;
@@ -3527,31 +3502,44 @@ static NTSTATUS ldapsam_enum_group_mapping(struct pdb_methods *methods,
                return NT_STATUS_ACCESS_DENIED;
        }
 
-       while (NT_STATUS_IS_OK(ldapsam_getsamgrent(methods, &map))) {
+       while (true) {
+
+               map = talloc_zero(NULL, GROUP_MAP);
+               if (!map) {
+                       return NT_STATUS_NO_MEMORY;
+               }
+
+               if (!NT_STATUS_IS_OK(ldapsam_getsamgrent(methods, map))) {
+                       TALLOC_FREE(map);
+                       break;
+               }
+
                if (sid_name_use != SID_NAME_UNKNOWN &&
-                   sid_name_use != map.sid_name_use) {
+                   sid_name_use != map->sid_name_use) {
                        DEBUG(11,("ldapsam_enum_group_mapping: group %s is "
-                                 "not of the requested type\n", map.nt_name));
+                                 "not of the requested type\n",
+                                 map->nt_name));
                        continue;
                }
-               if (unix_only==ENUM_ONLY_MAPPED && map.gid==-1) {
+               if (unix_only == ENUM_ONLY_MAPPED && map->gid == -1) {
                        DEBUG(11,("ldapsam_enum_group_mapping: group %s is "
-                                 "non mapped\n", map.nt_name));
+                                 "non mapped\n", map->nt_name));
                        continue;
                }
 
-               (*pp_rmap)=SMB_REALLOC_ARRAY((*pp_rmap), GROUP_MAP, entries+1);
+               *pp_rmap = talloc_realloc(NULL, *pp_rmap,
+                                               GROUP_MAP *, entries + 1);
                if (!(*pp_rmap)) {
                        DEBUG(0,("ldapsam_enum_group_mapping: Unable to "
                                 "enlarge group map!\n"));
                        return NT_STATUS_UNSUCCESSFUL;
                }
 
-               (*pp_rmap)[entries] = map;
+               (*pp_rmap)[entries] = talloc_move((*pp_rmap), &map);
 
                entries += 1;
-
        }
+
        ldapsam_endsamgrent(methods);
 
        *p_num_entries = entries;
@@ -3581,7 +3569,7 @@ static NTSTATUS ldapsam_modify_aliasmem(struct pdb_methods *methods,
                type = SID_NAME_ALIAS;
        }
 
-       if (sid_check_is_in_our_domain(alias)) {
+       if (sid_check_is_in_our_sam(alias)) {
                type = SID_NAME_ALIAS;
        }
 
@@ -3604,7 +3592,7 @@ static NTSTATUS ldapsam_modify_aliasmem(struct pdb_methods *methods,
                return NT_STATUS_NO_SUCH_ALIAS;
        }
 
-       count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
+       count = ldap_count_entries(smbldap_get_ldap(ldap_state->smbldap_state),
                                   result);
 
        if (count < 1) {
@@ -3624,7 +3612,7 @@ static NTSTATUS ldapsam_modify_aliasmem(struct pdb_methods *methods,
 
        SAFE_FREE(filter);
 
-       entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
+       entry = ldap_first_entry(smbldap_get_ldap(ldap_state->smbldap_state),
                                 result);
 
        if (!entry) {
@@ -3632,7 +3620,9 @@ static NTSTATUS ldapsam_modify_aliasmem(struct pdb_methods *methods,
                return NT_STATUS_UNSUCCESSFUL;
        }
 
-       dn = smbldap_talloc_dn(talloc_tos(), ldap_state->smbldap_state->ldap_struct, entry);
+       dn = smbldap_talloc_dn(talloc_tos(),
+                              smbldap_get_ldap(ldap_state->smbldap_state),
+                              entry);
        if (!dn) {
                ldap_msgfree(result);
                return NT_STATUS_UNSUCCESSFUL;
@@ -3704,7 +3694,7 @@ static NTSTATUS ldapsam_enum_aliasmem(struct pdb_methods *methods,
                type = SID_NAME_ALIAS;
        }
 
-       if (sid_check_is_in_our_domain(alias)) {
+       if (sid_check_is_in_our_sam(alias)) {
                type = SID_NAME_ALIAS;
        }
 
@@ -3727,7 +3717,7 @@ static NTSTATUS ldapsam_enum_aliasmem(struct pdb_methods *methods,
                return NT_STATUS_NO_SUCH_ALIAS;
        }
 
-       count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
+       count = ldap_count_entries(smbldap_get_ldap(ldap_state->smbldap_state),
                                   result);
 
        if (count < 1) {
@@ -3747,7 +3737,7 @@ static NTSTATUS ldapsam_enum_aliasmem(struct pdb_methods *methods,
 
        SAFE_FREE(filter);
 
-       entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
+       entry = ldap_first_entry(smbldap_get_ldap(ldap_state->smbldap_state),
                                 result);
 
        if (!entry) {
@@ -3755,7 +3745,7 @@ static NTSTATUS ldapsam_enum_aliasmem(struct pdb_methods *methods,
                return NT_STATUS_UNSUCCESSFUL;
        }
 
-       values = ldap_get_values(ldap_state->smbldap_state->ldap_struct,
+       values = ldap_get_values(smbldap_get_ldap(ldap_state->smbldap_state),
                                 entry,
                                 get_attr_key2string(groupmap_attr_list,
                                                     LDAP_ATTR_SID_LIST));
@@ -3821,7 +3811,7 @@ static NTSTATUS ldapsam_alias_memberships(struct pdb_methods *methods,
                type = SID_NAME_ALIAS;
        }
 
-       if (sid_check_is_domain(domain_sid)) {
+       if (sid_check_is_our_sam(domain_sid)) {
                type = SID_NAME_ALIAS;
        }
 
@@ -3858,15 +3848,15 @@ static NTSTATUS ldapsam_alias_memberships(struct pdb_methods *methods,
                result = ldap_state->search_cache.result;
                ldap_state->search_cache.result = NULL;
        } else {
-               rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_suffix(),
+               rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_suffix(talloc_tos()),
                                    LDAP_SCOPE_SUBTREE, filter, attrs, 0, &result);
                if (rc != LDAP_SUCCESS) {
                        return NT_STATUS_UNSUCCESSFUL;
                }
-               talloc_autofree_ldapmsg(filter, result);
+               smbldap_talloc_autofree_ldapmsg(filter, result);
        }
 
-       ldap_struct = ldap_state->smbldap_state->ldap_struct;
+       ldap_struct = smbldap_get_ldap(ldap_state->smbldap_state);
 
        for (entry = ldap_first_entry(ldap_struct, result);
             entry != NULL;
@@ -3900,7 +3890,7 @@ static NTSTATUS ldapsam_alias_memberships(struct pdb_methods *methods,
                TALLOC_FREE(ldap_state->search_cache.filter);
                /*
                 * Note: result is a talloc child of filter because of the
-                * talloc_autofree_ldapmsg() usage
+                * smbldap_talloc_autofree_ldapmsg() usage
                 */
                ldap_state->search_cache.filter = talloc_move(ldap_state, &filter);
                ldap_state->search_cache.result = result;
@@ -4126,7 +4116,7 @@ static NTSTATUS ldapsam_lookup_rids(struct pdb_methods *methods,
        }
 
        if (!sid_check_is_builtin(domain_sid) &&
-           !sid_check_is_domain(domain_sid)) {
+           !sid_check_is_our_sam(domain_sid)) {
                result = NT_STATUS_INVALID_PARAMETER;
                goto done;
        }
@@ -4170,16 +4160,16 @@ static NTSTATUS ldapsam_lookup_rids(struct pdb_methods *methods,
                }
 
                rc = smbldap_search(ldap_state->smbldap_state,
-                                   lp_ldap_user_suffix(),
+                                   lp_ldap_user_suffix(talloc_tos()),
                                    LDAP_SCOPE_SUBTREE, filter, ldap_attrs, 0,
                                    &msg);
-               talloc_autofree_ldapmsg(mem_ctx, msg);
+               smbldap_talloc_autofree_ldapmsg(mem_ctx, msg);
        }
 
        if (rc != LDAP_SUCCESS)
                goto done;
 
-       ld = ldap_state->smbldap_state->ldap_struct;
+       ld = smbldap_get_ldap(ldap_state->smbldap_state);
        num_mapped = 0;
 
        for (entry = ldap_first_entry(ld, msg);
@@ -4238,10 +4228,10 @@ static NTSTATUS ldapsam_lookup_rids(struct pdb_methods *methods,
                }
 
                rc = smbldap_search(ldap_state->smbldap_state,
-                                   lp_ldap_suffix(),
+                                   lp_ldap_suffix(talloc_tos()),
                                    LDAP_SCOPE_SUBTREE, filter, ldap_attrs, 0,
                                    &msg);
-               talloc_autofree_ldapmsg(mem_ctx, msg);
+               smbldap_talloc_autofree_ldapmsg(mem_ctx, msg);
        }
 
        if (rc != LDAP_SUCCESS)
@@ -4249,7 +4239,7 @@ static NTSTATUS ldapsam_lookup_rids(struct pdb_methods *methods,
 
        /* ldap_struct might have changed due to a reconnect */
 
-       ld = ldap_state->smbldap_state->ldap_struct;
+       ld = smbldap_get_ldap(ldap_state->smbldap_state);
 
        /* For consistency checks, we already checked we're only domain or builtin */
 
@@ -4361,7 +4351,7 @@ static const char **talloc_attrs(TALLOC_CTX *mem_ctx, ...)
                num += 1;
        va_end(ap);
 
-       if ((result = TALLOC_ARRAY(mem_ctx, const char *, num+1)) == NULL) {
+       if ((result = talloc_array(mem_ctx, const char *, num+1)) == NULL) {
                return NULL;
        }
 
@@ -4409,7 +4399,7 @@ static bool ldapsam_search_firstpage(struct pdb_search *search)
 
        state->entries = NULL;
 
-       if (state->connection->paged_results) {
+       if (smbldap_get_paged_results(state->connection)) {
                rc = smbldap_search_paged(state->connection, state->base,
                                          state->scope, state->filter,
                                          state->attrs, state->attrsonly,
@@ -4434,10 +4424,10 @@ static bool ldapsam_search_firstpage(struct pdb_search *search)
 
                /* Ok, the server was lying. It told us it could do paged
                 * searches when it could not. */
-               state->connection->paged_results = False;
+               smbldap_set_paged_results(state->connection, false);
        }
 
-        ld = state->connection->ldap_struct;
+        ld = smbldap_get_ldap(state->connection);
         if ( ld == NULL) {
                 DEBUG(5, ("Don't have an LDAP connection right after a "
                          "search\n"));
@@ -4454,7 +4444,7 @@ static bool ldapsam_search_nextpage(struct pdb_search *search)
                (struct ldap_search_state *)search->private_data;
        int rc;
 
-       if (!state->connection->paged_results) {
+       if (!smbldap_get_paged_results(state->connection)) {
                /* There is no next page when there are no paged results */
                return False;
        }
@@ -4468,7 +4458,8 @@ static bool ldapsam_search_nextpage(struct pdb_search *search)
        if ((rc != LDAP_SUCCESS) || (state->entries == NULL))
                return False;
 
-       state->current_entry = ldap_first_entry(state->connection->ldap_struct, state->entries);
+       state->current_entry = ldap_first_entry(
+               smbldap_get_ldap(state->connection), state->entries);
 
        if (state->current_entry == NULL) {
                ldap_msgfree(state->entries);
@@ -4499,17 +4490,19 @@ static bool ldapsam_search_next_entry(struct pdb_search *search,
        }
 
        result = state->ldap2displayentry(state, search,
-                                         state->connection->ldap_struct,
+                                         smbldap_get_ldap(state->connection),
                                          state->current_entry, entry);
 
        if (!result) {
                char *dn;
-               dn = ldap_get_dn(state->connection->ldap_struct, state->current_entry);
+               dn = ldap_get_dn(smbldap_get_ldap(state->connection),
+                                state->current_entry);
                DEBUG(5, ("Skipping entry %s\n", dn != NULL ? dn : "<NULL>"));
                if (dn != NULL) ldap_memfree(dn);
        }
 
-       state->current_entry = ldap_next_entry(state->connection->ldap_struct, state->current_entry);
+       state->current_entry = ldap_next_entry(
+               smbldap_get_ldap(state->connection), state->current_entry);
 
        if (state->current_entry == NULL) {
                ldap_msgfree(state->entries);
@@ -4536,8 +4529,9 @@ static void ldapsam_search_end(struct pdb_search *search)
        state->entries = NULL;
        state->current_entry = NULL;
 
-       if (!state->connection->paged_results)
+       if (!smbldap_get_paged_results(state->connection)) {
                return;
+       }
 
        /* Tell the LDAP server we're not interested in the rest anymore. */
 
@@ -4564,11 +4558,11 @@ static bool ldapuser2displayentry(struct ldap_search_state *state,
 
        vals = ldap_get_values(ld, entry, "sambaAcctFlags");
        if ((vals == NULL) || (vals[0] == NULL)) {
-               DEBUG(5, ("\"sambaAcctFlags\" not found\n"));
-               return False;
+               acct_flags = ACB_NORMAL;
+       } else {
+               acct_flags = pdb_decode_acct_ctrl(vals[0]);
+               ldap_value_free(vals);
        }
-       acct_flags = pdb_decode_acct_ctrl(vals[0]);
-       ldap_value_free(vals);
 
        if ((state->acct_flags != 0) &&
            ((state->acct_flags & acct_flags) == 0))
@@ -4585,7 +4579,7 @@ static bool ldapuser2displayentry(struct ldap_search_state *state,
                return False;
        }
        if (!pull_utf8_talloc(mem_ctx,
-                             CONST_DISCARD(char **, &result->account_name),
+                             discard_const_p(char *, &result->account_name),
                              vals[0], &converted_size))
        {
                DEBUG(0,("ldapuser2displayentry: pull_utf8_talloc failed: %s",
@@ -4598,7 +4592,7 @@ static bool ldapuser2displayentry(struct ldap_search_state *state,
        if ((vals == NULL) || (vals[0] == NULL))
                DEBUG(8, ("\"displayName\" not found\n"));
        else if (!pull_utf8_talloc(mem_ctx,
-                                  CONST_DISCARD(char **, &result->fullname),
+                                  discard_const_p(char *, &result->fullname),
                                   vals[0], &converted_size))
        {
                DEBUG(0,("ldapuser2displayentry: pull_utf8_talloc failed: %s",
@@ -4611,7 +4605,7 @@ static bool ldapuser2displayentry(struct ldap_search_state *state,
        if ((vals == NULL) || (vals[0] == NULL))
                DEBUG(8, ("\"description\" not found\n"));
        else if (!pull_utf8_talloc(mem_ctx,
-                                  CONST_DISCARD(char **, &result->description),
+                                  discard_const_p(char *, &result->description),
                                   vals[0], &converted_size))
        {
                DEBUG(0,("ldapuser2displayentry: pull_utf8_talloc failed: %s",
@@ -4667,12 +4661,12 @@ static bool ldapsam_search_users(struct pdb_methods *methods,
        state->connection = ldap_state->smbldap_state;
 
        if ((acct_flags != 0) && ((acct_flags & ACB_NORMAL) != 0))
-               state->base = lp_ldap_user_suffix();
+               state->base = lp_ldap_user_suffix(talloc_tos());
        else if ((acct_flags != 0) &&
                 ((acct_flags & (ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST)) != 0))
-               state->base = lp_ldap_machine_suffix();
+               state->base = lp_ldap_machine_suffix(talloc_tos());
        else
-               state->base = lp_ldap_suffix();
+               state->base = lp_ldap_suffix(talloc_tos());
 
        state->acct_flags = acct_flags;
        state->base = talloc_strdup(search, state->base);
@@ -4745,7 +4739,7 @@ static bool ldapgroup2displayentry(struct ldap_search_state *state,
                        return False;
                }
                if (!pull_utf8_talloc(mem_ctx,
-                                     CONST_DISCARD(char **,
+                                     discard_const_p(char *,
                                                    &result->account_name),
                                      vals[0], &converted_size))
                {
@@ -4754,7 +4748,7 @@ static bool ldapgroup2displayentry(struct ldap_search_state *state,
                }
        }
        else if (!pull_utf8_talloc(mem_ctx,
-                                  CONST_DISCARD(char **,
+                                  discard_const_p(char *,
                                                 &result->account_name),
                                   vals[0], &converted_size))
        {
@@ -4768,7 +4762,7 @@ static bool ldapgroup2displayentry(struct ldap_search_state *state,
        if ((vals == NULL) || (vals[0] == NULL))
                DEBUG(8, ("\"description\" not found\n"));
        else if (!pull_utf8_talloc(mem_ctx,
-                                  CONST_DISCARD(char **, &result->description),
+                                  discard_const_p(char *, &result->description),
                                   vals[0], &converted_size))
        {
                DEBUG(0,("ldapgroup2displayentry: pull_utf8_talloc failed: %s",
@@ -4813,7 +4807,7 @@ static bool ldapgroup2displayentry(struct ldap_search_state *state,
                        break;
 
                default:
-                       DEBUG(0,("unkown group type: %d\n", group_type));
+                       DEBUG(0,("unknown group type: %d\n", group_type));
                        return False;
        }
 
@@ -4840,7 +4834,7 @@ static bool ldapsam_search_grouptype(struct pdb_methods *methods,
 
        state->connection = ldap_state->smbldap_state;
 
-       state->base = talloc_strdup(search, lp_ldap_suffix());
+       state->base = lp_ldap_suffix(search);
        state->connection = ldap_state->smbldap_state;
        state->scope = LDAP_SCOPE_SUBTREE;
        state->filter = talloc_asprintf(search, "(&(objectclass=%s)"
@@ -4916,7 +4910,7 @@ static NTSTATUS ldapsam_get_new_rid(struct ldapsam_privates *priv,
                goto done;
        }
 
-       talloc_autofree_ldapmsg(mem_ctx, result);
+       smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
 
        entry = ldap_first_entry(priv2ld(priv), result);
        if (entry == NULL) {
@@ -4960,7 +4954,7 @@ static NTSTATUS ldapsam_get_new_rid(struct ldapsam_privates *priv,
 
        smbldap_make_mod(priv2ld(priv), entry, &mods, "sambaNextRid",
                         talloc_asprintf(mem_ctx, "%d", nextRid));
-       talloc_autofree_ldapmod(mem_ctx, mods);
+       smbldap_talloc_autofree_ldapmod(mem_ctx, mods);
 
        if ((dn = smbldap_talloc_dn(mem_ctx, priv2ld(priv), entry)) == NULL) {
                status = NT_STATUS_NO_MEMORY;
@@ -5013,7 +5007,7 @@ static bool ldapsam_new_rid(struct pdb_methods *methods, uint32_t *rid)
 
 static bool ldapsam_sid_to_id(struct pdb_methods *methods,
                              const struct dom_sid *sid,
-                             union unid_t *id, enum lsa_SidType *type)
+                             struct unixid *id)
 {
        struct ldapsam_privates *priv =
                (struct ldapsam_privates *)methods->private_data;
@@ -5028,6 +5022,11 @@ static bool ldapsam_sid_to_id(struct pdb_methods *methods,
 
        TALLOC_CTX *mem_ctx;
 
+       ret = pdb_sid_to_id_unix_users_and_groups(sid, id);
+       if (ret == true) {
+               return true;
+       }
+
        mem_ctx = talloc_new(NULL);
        if (mem_ctx == NULL) {
                DEBUG(0, ("talloc_new failed\n"));
@@ -5049,7 +5048,7 @@ static bool ldapsam_sid_to_id(struct pdb_methods *methods,
        if (rc != LDAP_SUCCESS) {
                goto done;
        }
-       talloc_autofree_ldapmsg(mem_ctx, result);
+       smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
 
        if (ldap_count_entries(priv2ld(priv), result) != 1) {
                DEBUG(10, ("Got %d entries, expected one\n",
@@ -5075,10 +5074,8 @@ static bool ldapsam_sid_to_id(struct pdb_methods *methods,
                        goto done;
                }
 
-               id->gid = strtoul(gid_str, NULL, 10);
-               *type = (enum lsa_SidType)strtoul(value, NULL, 10);
-               store_gid_sid_cache(sid, id->gid);
-               idmap_cache_set_sid2gid(sid, id->gid);
+               id->id = strtoul(gid_str, NULL, 10);
+               id->type = ID_TYPE_GID;
                ret = True;
                goto done;
        }
@@ -5093,10 +5090,8 @@ static bool ldapsam_sid_to_id(struct pdb_methods *methods,
                goto done;
        }
 
-       id->uid = strtoul(value, NULL, 10);
-       *type = SID_NAME_USER;
-       store_uid_sid_cache(sid, id->uid);
-       idmap_cache_set_sid2uid(sid, id->uid);
+       id->id = strtoul(value, NULL, 10);
+       id->type = ID_TYPE_UID;
 
        ret = True;
  done:
@@ -5139,7 +5134,7 @@ static bool ldapsam_uid_to_sid(struct pdb_methods *methods, uid_t uid,
        if (rc != LDAP_SUCCESS) {
                goto done;
        }
-       talloc_autofree_ldapmsg(tmp_ctx, result);
+       smbldap_talloc_autofree_ldapmsg(tmp_ctx, result);
 
        if (ldap_count_entries(priv2ld(priv), result) != 1) {
                DEBUG(3, ("ERROR: Got %d entries for uid %u, expected one\n",
@@ -5166,9 +5161,6 @@ static bool ldapsam_uid_to_sid(struct pdb_methods *methods, uid_t uid,
 
        sid_copy(sid, &user_sid);
 
-       store_uid_sid_cache(sid, uid);
-       idmap_cache_set_sid2uid(sid, uid);
-
        ret = true;
 
  done:
@@ -5209,7 +5201,7 @@ static bool ldapsam_gid_to_sid(struct pdb_methods *methods, gid_t gid,
        if (rc != LDAP_SUCCESS) {
                goto done;
        }
-       talloc_autofree_ldapmsg(tmp_ctx, result);
+       smbldap_talloc_autofree_ldapmsg(tmp_ctx, result);
 
        if (ldap_count_entries(priv2ld(priv), result) != 1) {
                DEBUG(3, ("ERROR: Got %d entries for gid %u, expected one\n",
@@ -5236,9 +5228,6 @@ static bool ldapsam_gid_to_sid(struct pdb_methods *methods, gid_t gid,
 
        sid_copy(sid, &group_sid);
 
-       store_gid_sid_cache(sid, gid);
-       idmap_cache_set_sid2gid(sid, gid);
-
        ret = true;
 
  done:
@@ -5246,6 +5235,21 @@ static bool ldapsam_gid_to_sid(struct pdb_methods *methods, gid_t gid,
        return ret;
 }
 
+static bool ldapsam_id_to_sid(struct pdb_methods *methods, struct unixid *id,
+                                  struct dom_sid *sid)
+{
+       switch (id->type) {
+       case ID_TYPE_UID:
+               return ldapsam_uid_to_sid(methods, id->id, sid);
+
+       case ID_TYPE_GID:
+               return ldapsam_gid_to_sid(methods, id->id, sid);
+
+       default:
+               return false;
+       }
+}
+
 
 /*
  * The following functions are called only if
@@ -5271,6 +5275,7 @@ static NTSTATUS ldapsam_create_user(struct pdb_methods *my_methods,
        uint32_t num_result;
        bool is_machine = False;
        bool add_posix = False;
+       bool init_okay = False;
        LDAPMod **mods = NULL;
        struct samu *user;
        char *filter;
@@ -5304,7 +5309,7 @@ static NTSTATUS ldapsam_create_user(struct pdb_methods *my_methods,
                DEBUG(0,("ldapsam_create_user: ldap search failed!\n"));
                return NT_STATUS_ACCESS_DENIED;
        }
-       talloc_autofree_ldapmsg(tmp_ctx, result);
+       smbldap_talloc_autofree_ldapmsg(tmp_ctx, result);
 
        num_result = ldap_count_entries(priv2ld(ldap_state), result);
 
@@ -5388,8 +5393,11 @@ static NTSTATUS ldapsam_create_user(struct pdb_methods *my_methods,
                return NT_STATUS_UNSUCCESSFUL;
        }
 
-       if (!init_ldap_from_sam(ldap_state, NULL, &mods, user, element_is_set_or_changed)) {
+       init_okay = init_ldap_from_sam(ldap_state, entry, &mods, user, pdb_element_is_set_or_changed);
+
+       if (!init_okay) {
                DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
+               ldap_mods_free(mods, true);
                return NT_STATUS_UNSUCCESSFUL;
        }
 
@@ -5407,23 +5415,43 @@ static NTSTATUS ldapsam_create_user(struct pdb_methods *my_methods,
                if (!sid_compose(&group_sid, get_global_sam_sid(), DOMAIN_RID_USERS) ||
                    !sid_to_gid(&group_sid, &gid)) {
                        DEBUG (0, ("ldapsam_create_user: Unable to get the Domain Users gid: bailing out!\n"));
+                       ldap_mods_free(mods, true);
                        return NT_STATUS_INVALID_PRIMARY_GROUP;
                }
 
                /* lets allocate a new userid for this user */
                if (!winbind_allocate_uid(&uid)) {
                        DEBUG (0, ("ldapsam_create_user: Unable to allocate a new user id: bailing out!\n"));
+                       ldap_mods_free(mods, true);
                        return NT_STATUS_UNSUCCESSFUL;
                }
 
 
                if (is_machine) {
                        /* TODO: choose a more appropriate default for machines */
-                       homedir = talloc_sub_specified(tmp_ctx, lp_template_homedir(), "SMB_workstations_home", ldap_state->domain_name, uid, gid);
+                       homedir = talloc_sub_specified(tmp_ctx,
+                                                      lp_template_homedir(),
+                                                      "SMB_workstations_home",
+                                                      NULL,
+                                                      ldap_state->domain_name,
+                                                      uid,
+                                                      gid);
                        shell = talloc_strdup(tmp_ctx, "/bin/false");
                } else {
-                       homedir = talloc_sub_specified(tmp_ctx, lp_template_homedir(), name, ldap_state->domain_name, uid, gid);
-                       shell = talloc_sub_specified(tmp_ctx, lp_template_shell(), name, ldap_state->domain_name, uid, gid);
+                       homedir = talloc_sub_specified(tmp_ctx,
+                                                      lp_template_homedir(),
+                                                      name,
+                                                      NULL,
+                                                      ldap_state->domain_name,
+                                                      uid,
+                                                      gid);
+                       shell = talloc_sub_specified(tmp_ctx,
+                                                    lp_template_shell(),
+                                                    name,
+                                                    NULL,
+                                                    ldap_state->domain_name,
+                                                    uid,
+                                                    gid);
                }
                uidstr = talloc_asprintf(tmp_ctx, "%u", (unsigned int)uid);
                gidstr = talloc_asprintf(tmp_ctx, "%u", (unsigned int)gid);
@@ -5431,19 +5459,21 @@ static NTSTATUS ldapsam_create_user(struct pdb_methods *my_methods,
                escape_name = escape_rdn_val_string_alloc(name);
                if (!escape_name) {
                        DEBUG (0, ("ldapsam_create_user: Out of memory!\n"));
+                       ldap_mods_free(mods, true);
                        return NT_STATUS_NO_MEMORY;
                }
 
                if (is_machine) {
-                       dn = talloc_asprintf(tmp_ctx, "uid=%s,%s", escape_name, lp_ldap_machine_suffix ());
+                       dn = talloc_asprintf(tmp_ctx, "uid=%s,%s", escape_name, lp_ldap_machine_suffix (talloc_tos()));
                } else {
-                       dn = talloc_asprintf(tmp_ctx, "uid=%s,%s", escape_name, lp_ldap_user_suffix ());
+                       dn = talloc_asprintf(tmp_ctx, "uid=%s,%s", escape_name, lp_ldap_user_suffix (talloc_tos()));
                }
 
                SAFE_FREE(escape_name);
 
                if (!homedir || !shell || !uidstr || !gidstr || !dn) {
                        DEBUG (0, ("ldapsam_create_user: Out of memory!\n"));
+                       ldap_mods_free(mods, true);
                        return NT_STATUS_NO_MEMORY;
                }
 
@@ -5456,14 +5486,14 @@ static NTSTATUS ldapsam_create_user(struct pdb_methods *my_methods,
                smbldap_set_mod(&mods, LDAP_MOD_ADD, "loginShell", shell);
        }
 
-       talloc_autofree_ldapmod(tmp_ctx, mods);
-
-       if (add_posix) {        
+       if (add_posix) {
                rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
        } else {
                rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
        }       
 
+       ldap_mods_free(mods, true);
+
        if (rc != LDAP_SUCCESS) {
                DEBUG(0,("ldapsam_create_user: failed to create a new user [%s] (dn = %s)\n", name ,dn));
                return NT_STATUS_UNSUCCESSFUL;
@@ -5504,7 +5534,7 @@ static NTSTATUS ldapsam_delete_user(struct pdb_methods *my_methods, TALLOC_CTX *
                DEBUG(0,("ldapsam_delete_user: user search failed!\n"));
                return NT_STATUS_UNSUCCESSFUL;
        }
-       talloc_autofree_ldapmsg(tmp_ctx, result);
+       smbldap_talloc_autofree_ldapmsg(tmp_ctx, result);
 
        num_result = ldap_count_entries(priv2ld(ldap_state), result);
 
@@ -5535,7 +5565,7 @@ static NTSTATUS ldapsam_delete_user(struct pdb_methods *my_methods, TALLOC_CTX *
                NTSTATUS status;
                struct dom_sid *sids = NULL;
                gid_t *gids = NULL;
-               size_t num_groups = 0;
+               uint32_t num_groups = 0;
                int i;
                uint32_t user_rid = pdb_get_user_rid(sam_acct);
 
@@ -5614,7 +5644,7 @@ static NTSTATUS ldapsam_create_dom_group(struct pdb_methods *my_methods,
                DEBUG(0,("ldapsam_create_group: ldap search failed!\n"));
                return NT_STATUS_UNSUCCESSFUL;
        }
-       talloc_autofree_ldapmsg(tmp_ctx, result);
+       smbldap_talloc_autofree_ldapmsg(tmp_ctx, result);
 
        num_result = ldap_count_entries(priv2ld(ldap_state), result);
 
@@ -5700,7 +5730,7 @@ static NTSTATUS ldapsam_create_dom_group(struct pdb_methods *my_methods,
                        return NT_STATUS_NO_MEMORY;
                }
 
-               dn = talloc_asprintf(tmp_ctx, "cn=%s,%s", escape_name, lp_ldap_group_suffix());
+               dn = talloc_asprintf(tmp_ctx, "cn=%s,%s", escape_name, lp_ldap_group_suffix(talloc_tos()));
 
                SAFE_FREE(escape_name);
 
@@ -5714,7 +5744,7 @@ static NTSTATUS ldapsam_create_dom_group(struct pdb_methods *my_methods,
                smbldap_set_mod(&mods, LDAP_MOD_ADD, "gidNumber", gidstr);
        }
 
-       talloc_autofree_ldapmod(tmp_ctx, mods);
+       smbldap_talloc_autofree_ldapmod(tmp_ctx, mods);
 
        if (is_new_entry) {     
                rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
@@ -5771,7 +5801,7 @@ static NTSTATUS ldapsam_delete_dom_group(struct pdb_methods *my_methods, TALLOC_
                DEBUG(1,("ldapsam_delete_dom_group: group search failed!\n"));
                return NT_STATUS_UNSUCCESSFUL;
        }
-       talloc_autofree_ldapmsg(tmp_ctx, result);
+       smbldap_talloc_autofree_ldapmsg(tmp_ctx, result);
 
        num_result = ldap_count_entries(priv2ld(ldap_state), result);
 
@@ -5817,7 +5847,7 @@ static NTSTATUS ldapsam_delete_dom_group(struct pdb_methods *my_methods, TALLOC_
                DEBUG(1,("ldapsam_delete_dom_group: accounts search failed!\n"));
                return NT_STATUS_UNSUCCESSFUL;
        }
-       talloc_autofree_ldapmsg(tmp_ctx, result);
+       smbldap_talloc_autofree_ldapmsg(tmp_ctx, result);
 
        num_result = ldap_count_entries(priv2ld(ldap_state), result);
 
@@ -5886,7 +5916,7 @@ static NTSTATUS ldapsam_change_groupmem(struct pdb_methods *my_methods,
                DEBUG(1,("ldapsam_change_groupmem: member search failed!\n"));
                return NT_STATUS_UNSUCCESSFUL;
        }
-       talloc_autofree_ldapmsg(tmp_ctx, result);
+       smbldap_talloc_autofree_ldapmsg(tmp_ctx, result);
 
        num_result = ldap_count_entries(priv2ld(ldap_state), result);
 
@@ -5950,7 +5980,7 @@ static NTSTATUS ldapsam_change_groupmem(struct pdb_methods *my_methods,
                DEBUG(1,("ldapsam_change_groupmem: group search failed!\n"));
                return NT_STATUS_UNSUCCESSFUL;
        }
-       talloc_autofree_ldapmsg(tmp_ctx, result);
+       smbldap_talloc_autofree_ldapmsg(tmp_ctx, result);
 
        num_result = ldap_count_entries(priv2ld(ldap_state), result);
 
@@ -5978,7 +6008,7 @@ static NTSTATUS ldapsam_change_groupmem(struct pdb_methods *my_methods,
 
        smbldap_set_mod(&mods, modop, "memberUid", uidstr);
 
-       talloc_autofree_ldapmod(tmp_ctx, mods);
+       smbldap_talloc_autofree_ldapmod(tmp_ctx, mods);
 
        rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
        if (rc != LDAP_SUCCESS) {
@@ -6064,7 +6094,7 @@ static NTSTATUS ldapsam_set_primary_group(struct pdb_methods *my_methods,
                DEBUG(0,("ldapsam_set_primary_group: user search failed!\n"));
                return NT_STATUS_UNSUCCESSFUL;
        }
-       talloc_autofree_ldapmsg(mem_ctx, result);
+       smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
 
        num_result = ldap_count_entries(priv2ld(ldap_state), result);
 
@@ -6147,7 +6177,7 @@ static bool get_trusteddom_pw_int(struct ldapsam_privates *ldap_state,
                            filter, attrs, attrsonly, &result);
 
        if (result != NULL) {
-               talloc_autofree_ldapmsg(mem_ctx, result);
+               smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
        }
 
        if (rc == LDAP_NO_SUCH_OBJECT) {
@@ -6288,7 +6318,7 @@ static bool ldapsam_set_trusteddom_pw(struct pdb_methods *methods,
                }
        }
 
-       talloc_autofree_ldapmod(talloc_tos(), mods);
+       smbldap_talloc_autofree_ldapmod(talloc_tos(), mods);
 
        trusted_dn = trusteddom_dn(ldap_state, domain);
        if (trusted_dn == NULL) {
@@ -6369,7 +6399,7 @@ static NTSTATUS ldapsam_enum_trusteddoms(struct pdb_methods *methods,
                            &result);
 
        if (result != NULL) {
-               talloc_autofree_ldapmsg(mem_ctx, result);
+               smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
        }
 
        if (rc != LDAP_SUCCESS) {
@@ -6377,7 +6407,7 @@ static NTSTATUS ldapsam_enum_trusteddoms(struct pdb_methods *methods,
        }
 
        *num_domains = 0;
-       if (!(*domains = TALLOC_ARRAY(mem_ctx, struct trustdom_info *, 1))) {
+       if (!(*domains = talloc_array(mem_ctx, struct trustdom_info *, 1))) {
                DEBUG(1, ("talloc failed\n"));
                return NT_STATUS_NO_MEMORY;
        }
@@ -6389,7 +6419,7 @@ static NTSTATUS ldapsam_enum_trusteddoms(struct pdb_methods *methods,
                char *dom_name, *dom_sid_str;
                struct trustdom_info *dom_info;
 
-               dom_info = TALLOC_P(*domains, struct trustdom_info);
+               dom_info = talloc(*domains, struct trustdom_info);
                if (dom_info == NULL) {
                        DEBUG(1, ("talloc failed\n"));
                        return NT_STATUS_NO_MEMORY;
@@ -6464,6 +6494,8 @@ static NTSTATUS pdb_init_ldapsam_common(struct pdb_methods **pdb_method, const c
 {
        NTSTATUS nt_status;
        struct ldapsam_privates *ldap_state;
+       char *bind_dn = NULL;
+       char *bind_secret = NULL;
 
        if (!NT_STATUS_IS_OK(nt_status = make_pdb_method( pdb_method ))) {
                return nt_status;
@@ -6501,14 +6533,22 @@ static NTSTATUS pdb_init_ldapsam_common(struct pdb_methods **pdb_method, const c
 
        /* TODO: Setup private data and free */
 
-       if ( !(ldap_state = TALLOC_ZERO_P(*pdb_method, struct ldapsam_privates)) ) {
+       if ( !(ldap_state = talloc_zero(*pdb_method, struct ldapsam_privates)) ) {
                DEBUG(0, ("pdb_init_ldapsam_common: talloc() failed for ldapsam private_data!\n"));
                return NT_STATUS_NO_MEMORY;
        }
 
-       nt_status = smbldap_init(*pdb_method, pdb_get_event_context(),
-                                location, &ldap_state->smbldap_state);
+       if (!fetch_ldap_pw(&bind_dn, &bind_secret)) {
+               DEBUG(0, ("pdb_init_ldapsam_common: Failed to retrieve LDAP password from secrets.tdb\n"));
+               return NT_STATUS_NO_MEMORY;
+       }
 
+       nt_status = smbldap_init(*pdb_method, pdb_get_tevent_context(),
+                                location, false, bind_dn, bind_secret,
+                                &ldap_state->smbldap_state);
+       memset(bind_secret, '\0', strlen(bind_secret));
+       SAFE_FREE(bind_secret);
+       SAFE_FREE(bind_dn);
        if ( !NT_STATUS_IS_OK(nt_status) ) {
                return nt_status;
        }
@@ -6524,40 +6564,17 @@ static NTSTATUS pdb_init_ldapsam_common(struct pdb_methods **pdb_method, const c
        return NT_STATUS_OK;
 }
 
-/**********************************************************************
- Initialise the 'compat' mode for pdb_ldap
- *********************************************************************/
-
-NTSTATUS pdb_init_ldapsam_compat(struct pdb_methods **pdb_method, const char *location)
+static bool ldapsam_is_responsible_for_wellknown(struct pdb_methods *m)
 {
-       NTSTATUS nt_status;
-       struct ldapsam_privates *ldap_state;
-       char *uri = talloc_strdup( NULL, location );
-
-       trim_char( uri, '\"', '\"' );
-       nt_status = pdb_init_ldapsam_common( pdb_method, uri );
-       if ( uri )
-               TALLOC_FREE( uri );
-
-       if ( !NT_STATUS_IS_OK(nt_status) ) {
-               return nt_status;
-       }
-
-       (*pdb_method)->name = "ldapsam_compat";
-
-       ldap_state = (struct ldapsam_privates *)((*pdb_method)->private_data);
-       ldap_state->schema_ver = SCHEMAVER_SAMBAACCOUNT;
-
-       sid_copy(&ldap_state->domain_sid, get_global_sam_sid());
-
-       return NT_STATUS_OK;
+       return true;
 }
 
 /**********************************************************************
  Initialise the normal mode for pdb_ldap
  *********************************************************************/
 
-NTSTATUS pdb_init_ldapsam(struct pdb_methods **pdb_method, const char *location)
+NTSTATUS pdb_ldapsam_init_common(struct pdb_methods **pdb_method,
+                                const char *location)
 {
        NTSTATUS nt_status;
        struct ldapsam_privates *ldap_state = NULL;
@@ -6589,6 +6606,8 @@ NTSTATUS pdb_init_ldapsam(struct pdb_methods **pdb_method, const char *location)
        (*pdb_method)->search_users = ldapsam_search_users;
        (*pdb_method)->search_groups = ldapsam_search_groups;
        (*pdb_method)->search_aliases = ldapsam_search_aliases;
+       (*pdb_method)->is_responsible_for_wellknown =
+                                       ldapsam_is_responsible_for_wellknown;
 
        if (lp_parm_bool(-1, "ldapsam", "trusted", False)) {
                (*pdb_method)->enum_group_members = ldapsam_enum_group_members;
@@ -6596,8 +6615,7 @@ NTSTATUS pdb_init_ldapsam(struct pdb_methods **pdb_method, const char *location)
                        ldapsam_enum_group_memberships;
                (*pdb_method)->lookup_rids = ldapsam_lookup_rids;
                (*pdb_method)->sid_to_id = ldapsam_sid_to_id;
-               (*pdb_method)->uid_to_sid = ldapsam_uid_to_sid;
-               (*pdb_method)->gid_to_sid = ldapsam_gid_to_sid;
+               (*pdb_method)->id_to_sid = ldapsam_id_to_sid;
 
                if (lp_parm_bool(-1, "ldapsam", "editposix", False)) {
                        (*pdb_method)->create_user = ldapsam_create_user;
@@ -6620,19 +6638,16 @@ NTSTATUS pdb_init_ldapsam(struct pdb_methods **pdb_method, const char *location)
                                               ldap_state->domain_name, True);
 
        if ( !NT_STATUS_IS_OK(nt_status) ) {
-               DEBUG(2, ("pdb_init_ldapsam: WARNING: Could not get domain "
-                         "info, nor add one to the domain\n"));
-               DEBUGADD(2, ("pdb_init_ldapsam: Continuing on regardless, "
-                            "will be unable to allocate new users/groups, "
-                            "and will risk BDCs having inconsistant SIDs\n"));
-               sid_copy(&ldap_state->domain_sid, get_global_sam_sid());
-               return NT_STATUS_OK;
+               DEBUG(0, ("pdb_init_ldapsam: WARNING: Could not get domain "
+                         "info, nor add one to the domain. "
+                         "We cannot work reliably without it.\n"));
+               return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
        }
 
        /* Given that the above might fail, everything below this must be
         * optional */
 
-       entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
+       entry = ldap_first_entry(smbldap_get_ldap(ldap_state->smbldap_state),
                                 result);
        if (!entry) {
                DEBUG(0, ("pdb_init_ldapsam: Could not get domain info "
@@ -6641,7 +6656,9 @@ NTSTATUS pdb_init_ldapsam(struct pdb_methods **pdb_method, const char *location)
                return NT_STATUS_UNSUCCESSFUL;
        }
 
-       dn = smbldap_talloc_dn(talloc_tos(), ldap_state->smbldap_state->ldap_struct, entry);
+       dn = smbldap_talloc_dn(talloc_tos(),
+                              smbldap_get_ldap(ldap_state->smbldap_state),
+                              entry);
        if (!dn) {
                ldap_msgfree(result);
                return NT_STATUS_UNSUCCESSFUL;
@@ -6651,7 +6668,7 @@ NTSTATUS pdb_init_ldapsam(struct pdb_methods **pdb_method, const char *location)
        TALLOC_FREE(dn);
 
        domain_sid_string = smbldap_talloc_single_attribute(
-                   ldap_state->smbldap_state->ldap_struct,
+                   smbldap_get_ldap(ldap_state->smbldap_state),
                    entry,
                    get_userattr_key2string(ldap_state->schema_ver,
                                            LDAP_ATTR_USER_SID),
@@ -6666,9 +6683,9 @@ NTSTATUS pdb_init_ldapsam(struct pdb_methods **pdb_method, const char *location)
                        TALLOC_FREE(domain_sid_string);
                        return NT_STATUS_INVALID_PARAMETER;
                }
-               found_sid = secrets_fetch_domain_sid(ldap_state->domain_name,
+               found_sid = PDB_secrets_fetch_domain_sid(ldap_state->domain_name,
                                                     &secrets_domain_sid);
-               if (!found_sid || !sid_equal(&secrets_domain_sid,
+               if (!found_sid || !dom_sid_equal(&secrets_domain_sid,
                                             &ldap_domain_sid)) {
                        DEBUG(1, ("pdb_init_ldapsam: Resetting SID for domain "
                                  "%s based on pdb_ldap results %s -> %s\n",
@@ -6677,7 +6694,7 @@ NTSTATUS pdb_init_ldapsam(struct pdb_methods **pdb_method, const char *location)
                                  sid_string_dbg(&ldap_domain_sid)));
 
                        /* reset secrets.tdb sid */
-                       secrets_store_domain_sid(ldap_state->domain_name,
+                       PDB_secrets_store_domain_sid(ldap_state->domain_name,
                                                 &ldap_domain_sid);
                        DEBUG(1, ("New global sam SID: %s\n",
                                  sid_string_dbg(get_global_sam_sid())));
@@ -6687,7 +6704,7 @@ NTSTATUS pdb_init_ldapsam(struct pdb_methods **pdb_method, const char *location)
        }
 
        alg_rid_base_string = smbldap_talloc_single_attribute(
-                   ldap_state->smbldap_state->ldap_struct,
+                   smbldap_get_ldap(ldap_state->smbldap_state),
                    entry,
                    get_attr_key2string( dominfo_attr_list,
                                         LDAP_ATTR_ALGORITHMIC_RID_BASE ),
@@ -6709,17 +6726,19 @@ NTSTATUS pdb_init_ldapsam(struct pdb_methods **pdb_method, const char *location)
        return NT_STATUS_OK;
 }
 
-NTSTATUS pdb_ldap_init(void)
+NTSTATUS pdb_ldapsam_init(TALLOC_CTX *ctx)
 {
        NTSTATUS nt_status;
-       if (!NT_STATUS_IS_OK(nt_status = smb_register_passdb(PASSDB_INTERFACE_VERSION, "ldapsam", pdb_init_ldapsam)))
-               return nt_status;
 
-       if (!NT_STATUS_IS_OK(nt_status = smb_register_passdb(PASSDB_INTERFACE_VERSION, "ldapsam_compat", pdb_init_ldapsam_compat)))
+       nt_status = smb_register_passdb(PASSDB_INTERFACE_VERSION,
+                                       "ldapsam",
+                                       pdb_ldapsam_init_common);
+       if (!NT_STATUS_IS_OK(nt_status)) {
                return nt_status;
+       }
 
        /* Let pdb_nds register backends */
-       pdb_nds_init();
+       pdb_nds_init(ctx);
 
        return NT_STATUS_OK;
 }