This is meant to be initialised to the size of the buffer.
[ira/wip.git] / source3 / passdb / pdb_ldap.c
index 46e099437934d7671249ee44cd6f278b75449e29..8a2378f91b281fef28896fe2b931489ef009764e 100644 (file)
@@ -28,7 +28,6 @@
 #undef DBGC_CLASS
 #define DBGC_CLASS DBGC_PASSDB
 
-#ifdef HAVE_LDAP
 /* TODO:
 *  persistent connections: if using NSS LDAP, many connections are made
 *      however, using only one within Samba would be nice
@@ -75,6 +74,8 @@ struct ldapsam_privates {
 
        char *bind_dn;
        char *bind_secret;
+
+       unsigned int num_failures;
 };
 
 #define LDAPSAM_DONT_PING_TIME 10      /* ping only all 10 seconds */
@@ -167,7 +168,7 @@ static int ldapsam_open_connection (struct ldapsam_privates *ldap_state, LDAP **
        int version;
        BOOL ldap_v3 = False;
 
-#if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
+#ifdef HAVE_LDAP_INITIALIZE
        DEBUG(10, ("ldapsam_open_connection: %s\n", ldap_state->uri));
        
        if ((rc = ldap_initialize(ldap_struct, ldap_state->uri)) != LDAP_SUCCESS) {
@@ -407,18 +408,21 @@ static int ldapsam_connect_system(struct ldapsam_privates *ldap_state, LDAP * ld
        rc = ldap_simple_bind_s(ldap_struct, ldap_dn, ldap_secret);
 
        if (rc != LDAP_SUCCESS) {
-               char *ld_error;
+               char *ld_error = NULL;
                ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
                                &ld_error);
-               DEBUG(0,
+               DEBUG(ldap_state->num_failures ? 2 : 0,
                      ("failed to bind to server with dn= %s Error: %s\n\t%s\n",
-                              ldap_dn, ldap_err2string(rc),
+                              ldap_dn ? ld_error : "(unknown)", ldap_err2string(rc),
                               ld_error));
-               free(ld_error);
+               SAFE_FREE(ld_error);
+               ldap_state->num_failures++;
                return rc;
        }
-       
-       DEBUG(2, ("ldap_connect_system: succesful connection to the LDAP server\n"));
+
+       ldap_state->num_failures = 0;
+
+       DEBUG(3, ("ldap_connect_system: succesful connection to the LDAP server\n"));
        return rc;
 }
 
@@ -439,7 +443,7 @@ static int ldapsam_open(struct ldapsam_privates *ldap_state)
 
        if ((ldap_state->ldap_struct != NULL) && ((ldap_state->last_ping + LDAPSAM_DONT_PING_TIME) < time(NULL))) {
                struct sockaddr_un addr;
-               socklen_t len;
+               socklen_t len = sizeof(addr);
                int sd;
                if (ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_DESC, &sd) == 0 &&
                    getpeername(sd, (struct sockaddr *) &addr, &len) < 0) {
@@ -500,13 +504,23 @@ static int ldapsam_retry_open(struct ldapsam_privates *ldap_state, int *attempts
        SMB_ASSERT(ldap_state && attempts);
                
        if (*attempts != 0) {
-               /* we retry after 0.5, 2, 4.5, 8, 12.5, 18, 24.5 seconds */
-               msleep((((*attempts)*(*attempts))/2)*1000);
+               unsigned int sleep_time;
+               uint8 rand_byte = 128; /* a reasonable place to start */
+
+               generate_random_buffer(&rand_byte, 1, False);
+
+               sleep_time = (((*attempts)*(*attempts))/2)*rand_byte*2; 
+               /* we retry after (0.5, 1, 2, 3, 4.5, 6) seconds
+                  on average.  
+                */
+               DEBUG(3, ("Sleeping for %u milliseconds before reconnecting\n", 
+                         sleep_time));
+               msleep(sleep_time);
        }
        (*attempts)++;
 
        if ((rc = ldapsam_open(ldap_state))) {
-               DEBUG(0,("Connection to LDAP Server failed for the %d try!\n",*attempts));
+               DEBUG(1,("Connection to LDAP Server failed for the %d try!\n",*attempts));
                return rc;
        } 
        
@@ -530,7 +544,7 @@ static int ldapsam_search(struct ldapsam_privates *ldap_state,
                        continue;
                
                rc = ldap_search_s(ldap_state->ldap_struct, base, scope, 
-                                  filter, attrs, attrsonly, res);
+                                  filter, (char **)attrs, attrsonly, res);
        }
        
        if (rc == LDAP_SERVER_DOWN) {
@@ -613,6 +627,7 @@ static int ldapsam_delete(struct ldapsam_privates *ldap_state, char *dn)
        return rc;
 }
 
+#ifdef LDAP_EXOP_X_MODIFY_PASSWD
 static int ldapsam_extended_operation(struct ldapsam_privates *ldap_state, LDAP_CONST char *reqoid, struct berval *reqdata, LDAPControl **serverctrls, LDAPControl **clientctrls, char **retoidp, struct berval **retdatap)
 {
        int             rc = LDAP_SERVER_DOWN;
@@ -636,6 +651,7 @@ static int ldapsam_extended_operation(struct ldapsam_privates *ldap_state, LDAP_
                
        return rc;
 }
+#endif
 
 /*******************************************************************
  run the search by name.
@@ -650,10 +666,14 @@ static int ldapsam_search_one_user (struct ldapsam_privates *ldap_state, const c
        rc = ldapsam_search(ldap_state, lp_ldap_suffix (), scope, filter, attr, 0, result);
 
        if (rc != LDAP_SUCCESS) {
-               DEBUG(0,("ldapsam_search_one_user: Problem during the LDAP search: %s\n", 
-                       ldap_err2string (rc)));
+               char *ld_error = NULL;
+               ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
+                               &ld_error);
+               DEBUG(0,("ldapsam_search_one_user: Problem during the LDAP search: %s (%s)\n", 
+                       ld_error?ld_error:"(unknown)", ldap_err2string (rc)));
                DEBUG(3,("ldapsam_search_one_user: Query was: %s, %s\n", lp_ldap_suffix(), 
                        filter));
+               SAFE_FREE(ld_error);
        }
        
        return rc;
@@ -786,8 +806,11 @@ static void make_a_mod (LDAPMod *** modlist, int modop, const char *attribute, c
        if (attribute == NULL || *attribute == '\0')
                return;
 
-       if (value == NULL || *value == '\0')
+#if 0
+       /* Why do we need this??? -- vl */
+               if (value == NULL || *value == '\0')
                return;
+#endif
 
        if (mods == NULL) 
        {
@@ -844,6 +867,89 @@ static void make_a_mod (LDAPMod *** modlist, int modop, const char *attribute, c
        *modlist = mods;
 }
 
+/*******************************************************************
+ Delete complete object or objectclass and attrs from
+ object found in search_result depending on lp_ldap_delete_dn
+******************************************************************/
+static NTSTATUS ldapsam_delete_entry(struct ldapsam_privates *ldap_state,
+                                    LDAPMessage *result,
+                                    const char *objectclass,
+                                    const char **attrs)
+{
+       int rc;
+       LDAPMessage *entry;
+       LDAPMod **mods = NULL;
+       char *name, *dn;
+       BerElement *ptr = NULL;
+
+       rc = ldap_count_entries(ldap_state->ldap_struct, result);
+
+       if (rc != 1) {
+               DEBUG(0, ("Entry must exist exactly once!\n"));
+               return NT_STATUS_UNSUCCESSFUL;
+       }
+
+       entry = ldap_first_entry(ldap_state->ldap_struct, result);
+       dn    = ldap_get_dn(ldap_state->ldap_struct, entry);
+
+       if (lp_ldap_delete_dn()) {
+               NTSTATUS ret = NT_STATUS_OK;
+               rc = ldapsam_delete(ldap_state, dn);
+
+               if (rc != LDAP_SUCCESS) {
+                       DEBUG(0, ("Could not delete object %s\n", dn));
+                       ret = NT_STATUS_UNSUCCESSFUL;
+               }
+               ldap_memfree(dn);
+               return ret;
+       }
+
+       /* Ok, delete only the SAM attributes */
+
+       for (name = ldap_first_attribute(ldap_state->ldap_struct, entry, &ptr);
+            name != NULL;
+            name = ldap_next_attribute(ldap_state->ldap_struct, entry, ptr)) {
+
+               const char **attrib;
+
+               /* We are only allowed to delete the attributes that
+                  really exist. */
+
+               for (attrib = attrs; *attrib != NULL; attrib++) {
+                       if (StrCaseCmp(*attrib, name) == 0) {
+                               DEBUG(10, ("deleting attribute %s\n", name));
+                               make_a_mod(&mods, LDAP_MOD_DELETE, name, NULL);
+                       }
+               }
+
+               ldap_memfree(name);
+       }
+
+       if (ptr != NULL) {
+               ber_free(ptr, 0);
+       }
+       
+       make_a_mod(&mods, LDAP_MOD_DELETE, "objectClass", objectclass);
+
+       rc = ldapsam_modify(ldap_state, dn, mods);
+       ldap_mods_free(mods, 1);
+
+       if (rc != LDAP_SUCCESS) {
+               char *ld_error = NULL;
+               ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
+                               &ld_error);
+               
+               DEBUG(0, ("could not delete attributes for %s, error: %s (%s)\n",
+                         dn, ldap_err2string(rc), ld_error?ld_error:"unknown"));
+               SAFE_FREE(ld_error);
+               ldap_memfree(dn);
+               return NT_STATUS_UNSUCCESSFUL;
+       }
+
+       ldap_memfree(dn);
+       return NT_STATUS_OK;
+}
+                                         
 /* New Interface is being implemented here */
 
 /**********************************************************************
@@ -1078,8 +1184,10 @@ static BOOL init_sam_from_ldap (struct ldapsam_privates *ldap_state,
         * that fits your needs; using cn then displayName rather than 'userFullName'
         */
 
-       if (!get_single_attribute(ldap_state->ldap_struct, entry, "cn", fullname)) {
-               if (!get_single_attribute(ldap_state->ldap_struct, entry, "displayName", fullname)) {
+       if (!get_single_attribute(ldap_state->ldap_struct, entry,
+                                 "displayName", fullname)) {
+               if (!get_single_attribute(ldap_state->ldap_struct, entry,
+                                         "cn", fullname)) {
                        /* leave as default */
                } else {
                        pdb_set_fullname(sampass, fullname, PDB_SET);
@@ -1191,6 +1299,12 @@ static BOOL init_sam_from_ldap (struct ldapsam_privates *ldap_state,
        return True;
 }
 
+/**********************************************************************
+  An LDAP modification is needed in two cases:
+  * If we are updating the record AND the attribute is CHANGED.
+  * If we are adding   the record AND it is SET or CHANGED (ie not default)
+*********************************************************************/
+#ifdef LDAP_EXOP_X_MODIFY_PASSWD
 static BOOL need_ldap_mod(BOOL pdb_add, const SAM_ACCOUNT * sampass, enum pdb_elements element) {
        if (pdb_add) {
                return (!IS_SAM_DEFAULT(sampass, element));
@@ -1198,15 +1312,66 @@ static BOOL need_ldap_mod(BOOL pdb_add, const SAM_ACCOUNT * sampass, enum pdb_el
                return IS_SAM_CHANGED(sampass, element);
        }
 }
+#endif
+
+/**********************************************************************
+  Set attribute to newval in LDAP, regardless of what value the
+  attribute had in LDAP before.
+*********************************************************************/
+static void make_ldap_mod(LDAP *ldap_struct, LDAPMessage *existing,
+                         LDAPMod ***mods,
+                         const char *attribute, const char *newval)
+{
+       char **values = NULL;
+
+       if (existing != NULL) {
+               values = ldap_get_values(ldap_struct, existing, attribute);
+       }
+
+       if ((values != NULL) && (values[0] != NULL) &&
+           strcmp(values[0], newval) == 0) {
+               
+               /* Believe it or not, but LDAP will deny a delete and
+                  an add at the same time if the values are the
+                  same... */
+
+               ldap_value_free(values);
+               return;
+       }
+
+       /* Regardless of the real operation (add or modify)
+          we add the new value here. We rely on deleting
+          the old value, should it exist. */
+
+       if ((newval != NULL) && (strlen(newval) > 0)) {
+               make_a_mod(mods, LDAP_MOD_ADD, attribute, newval);
+       }
+
+       if (values == NULL) {
+               /* There has been no value before, so don't delete it.
+                  Here's a possible race: We might end up with
+                  duplicate attributes */
+               return;
+       }
+
+       /* By deleting exactly the value we found in the entry this
+          should be race-free in the sense that the LDAP-Server will
+          deny the complete operation if somebody changed the
+          attribute behind our back. */
+
+       make_a_mod(mods, LDAP_MOD_DELETE, attribute, values[0]);
+       ldap_value_free(values);
+}
 
 /**********************************************************************
 Initialize SAM_ACCOUNT from an LDAP query
 (Based on init_buffer_from_sam in pdb_tdb.c)
 *********************************************************************/
 static BOOL init_ldap_from_sam (struct ldapsam_privates *ldap_state, 
-                               LDAPMod *** mods, int ldap_op, 
-                               BOOL pdb_add,
-                               const SAM_ACCOUNT * sampass)
+                               LDAPMessage *existing,
+                               LDAPMod *** mods, const SAM_ACCOUNT * sampass,
+                               BOOL (*need_update)(const SAM_ACCOUNT *,
+                                                   enum pdb_elements))
 {
        pstring temp;
        uint32 rid;
@@ -1222,139 +1387,165 @@ static BOOL init_ldap_from_sam (struct ldapsam_privates *ldap_state,
         * took out adding "objectclass: sambaAccount"
         * do this on a per-mod basis
         */
-       if (need_ldap_mod(pdb_add, sampass, PDB_USERNAME)) {
-               make_a_mod(mods, ldap_op, "uid", pdb_get_username(sampass));
-               DEBUG(2, ("Setting entry for user: %s\n", pdb_get_username(sampass)));
-       }
-       
-       if ((rid = pdb_get_user_rid(sampass))!=0 ) {
-               if (need_ldap_mod(pdb_add, sampass, PDB_USERSID)) {             
-                       slprintf(temp, sizeof(temp) - 1, "%i", rid);
-                       make_a_mod(mods, ldap_op, "rid", temp);
-               }
-       } else if (!IS_SAM_DEFAULT(sampass, PDB_UID)) {
-               rid = fallback_pdb_uid_to_user_rid(pdb_get_uid(sampass));
-               slprintf(temp, sizeof(temp) - 1, "%i", rid);
-               make_a_mod(mods, ldap_op, "rid", temp);
-       } else if (ldap_state->permit_non_unix_accounts) {
-               rid = ldapsam_get_next_available_nua_rid(ldap_state);
-               if (rid == 0) {
-                       DEBUG(0, ("NO user RID specified on account %s, and findining next available NUA RID failed, cannot store!\n", pdb_get_username(sampass)));
+       if (need_update(sampass, PDB_USERNAME))
+               make_ldap_mod(ldap_state->ldap_struct, existing, mods, 
+                             "uid", pdb_get_username(sampass));
+
+       DEBUG(2, ("Setting entry for user: %s\n", pdb_get_username(sampass)));
+
+       rid = pdb_get_user_rid(sampass);
+
+       if (rid == 0) {
+               if (!IS_SAM_DEFAULT(sampass, PDB_UID)) {
+                       rid = fallback_pdb_uid_to_user_rid(pdb_get_uid(sampass));
+               } else if (ldap_state->permit_non_unix_accounts) {
+                       rid = ldapsam_get_next_available_nua_rid(ldap_state);
+                       if (rid == 0) {
+                               DEBUG(0, ("NO user RID specified on account %s, and "
+                                         "finding next available NUA RID failed, "
+                                         "cannot store!\n",
+                                         pdb_get_username(sampass)));
+                               ldap_mods_free(*mods, 1);
+                               return False;
+                       }
+               } else {
+                       DEBUG(0, ("NO user RID specified on account %s, "
+                                 "cannot store!\n", pdb_get_username(sampass)));
+                       ldap_mods_free(*mods, 1);
                        return False;
                }
-               slprintf(temp, sizeof(temp) - 1, "%i", rid);
-               make_a_mod(mods, ldap_op, "rid", temp);
-       } else {
-               DEBUG(0, ("NO user RID specified on account %s, cannot store!\n", pdb_get_username(sampass)));
-               return False;
        }
 
+       slprintf(temp, sizeof(temp) - 1, "%i", rid);
+
+       if (need_update(sampass, PDB_USERSID))
+               make_ldap_mod(ldap_state->ldap_struct, existing, mods,
+                             "rid", temp);
+
 
+       rid = pdb_get_group_rid(sampass);
 
-       if ((rid = pdb_get_group_rid(sampass))!=0 ) {
-               if (need_ldap_mod(pdb_add, sampass, PDB_GROUPSID)) {            
-                       slprintf(temp, sizeof(temp) - 1, "%i", rid);
-                       make_a_mod(mods, ldap_op, "primaryGroupID", temp);
+       if (rid == 0) {
+               if (!IS_SAM_DEFAULT(sampass, PDB_GID)) {
+                       rid = pdb_gid_to_group_rid(pdb_get_gid(sampass));
+               } else if (ldap_state->permit_non_unix_accounts) {
+                       rid = DOMAIN_GROUP_RID_USERS;
+               } else {
+                       DEBUG(0, ("NO group RID specified on account %s, "
+                                 "cannot store!\n", pdb_get_username(sampass)));
+                       ldap_mods_free(*mods, 1);
+                       return False;
                }
-       } else if (!IS_SAM_DEFAULT(sampass, PDB_GID)) {
-               rid = pdb_gid_to_group_rid(pdb_get_gid(sampass));
-               slprintf(temp, sizeof(temp) - 1, "%i", rid);
-               make_a_mod(mods, ldap_op, "primaryGroupID", temp);
-       } else if (ldap_state->permit_non_unix_accounts) {
-               rid = DOMAIN_GROUP_RID_USERS;
-               slprintf(temp, sizeof(temp) - 1, "%i", rid);
-               make_a_mod(mods, ldap_op, "primaryGroupID", temp);
-       } else {
-               DEBUG(0, ("NO group RID specified on account %s, cannot store!\n", pdb_get_username(sampass)));
-               return False;
        }
 
+       slprintf(temp, sizeof(temp) - 1, "%i", rid);
+
+       if (need_update(sampass, PDB_GROUPSID))
+               make_ldap_mod(ldap_state->ldap_struct, existing, mods,
+                             "primaryGroupID", temp);
 
        /* displayName, cn, and gecos should all be the same
         *  most easily accomplished by giving them the same OID
         *  gecos isn't set here b/c it should be handled by the 
         *  add-user script
-        */
-       if (need_ldap_mod(pdb_add, sampass, PDB_FULLNAME)) {
-               make_a_mod(mods, ldap_op, "displayName", pdb_get_fullname(sampass));
-               make_a_mod(mods, ldap_op, "cn", pdb_get_fullname(sampass));
-       }
-       if (need_ldap_mod(pdb_add, sampass, PDB_ACCTDESC)) {    
-               make_a_mod(mods, ldap_op, "description", pdb_get_acct_desc(sampass));
-       }
-       if (need_ldap_mod(pdb_add, sampass, PDB_WORKSTATIONS)) {        
-               make_a_mod(mods, ldap_op, "userWorkstations", pdb_get_workstations(sampass));
-       }
-       /*
-        * Only updates fields which have been set (not defaults from smb.conf)
+        *  We change displayName only and fall back to cn if
+        *  it does not exist.
         */
 
-       if (need_ldap_mod(pdb_add, sampass, PDB_SMBHOME)) {
-               make_a_mod(mods, ldap_op, "smbHome", pdb_get_homedir(sampass));
-       }
+       if (need_update(sampass, PDB_FULLNAME))
+               make_ldap_mod(ldap_state->ldap_struct, existing, mods,
+                             "displayName", pdb_get_fullname(sampass));
+
+       if (need_update(sampass, PDB_ACCTDESC))
+               make_ldap_mod(ldap_state->ldap_struct, existing, mods,
+                             "description", pdb_get_acct_desc(sampass));
+
+       if (need_update(sampass, PDB_WORKSTATIONS))
+               make_ldap_mod(ldap_state->ldap_struct, existing, mods,
+                             "userWorkstations", pdb_get_workstations(sampass));
+
+       if (need_update(sampass, PDB_SMBHOME))
+               make_ldap_mod(ldap_state->ldap_struct, existing, mods,
+                             "smbHome", pdb_get_homedir(sampass));
                        
-       if (need_ldap_mod(pdb_add, sampass, PDB_DRIVE)) {
-               make_a_mod(mods, ldap_op, "homeDrive", pdb_get_dir_drive(sampass));
-       }
-       
-       if (need_ldap_mod(pdb_add, sampass, PDB_LOGONSCRIPT)) {
-               make_a_mod(mods, ldap_op, "scriptPath", pdb_get_logon_script(sampass));
-       }
-       
-       if (need_ldap_mod(pdb_add, sampass, PDB_PROFILE))
-               make_a_mod(mods, ldap_op, "profilePath", pdb_get_profile_path(sampass));
+       if (need_update(sampass, PDB_DRIVE))
+               make_ldap_mod(ldap_state->ldap_struct, existing, mods,
+                             "homeDrive", pdb_get_dir_drive(sampass));
 
-       if (need_ldap_mod(pdb_add, sampass, PDB_LOGONTIME)) {
-               slprintf(temp, sizeof(temp) - 1, "%li", pdb_get_logon_time(sampass));
-               make_a_mod(mods, ldap_op, "logonTime", temp);
-       }
+       if (need_update(sampass, PDB_LOGONSCRIPT))
+               make_ldap_mod(ldap_state->ldap_struct, existing, mods,
+                             "scriptPath", pdb_get_logon_script(sampass));
 
-       if (need_ldap_mod(pdb_add, sampass, PDB_LOGOFFTIME)) {
-               slprintf(temp, sizeof(temp) - 1, "%li", pdb_get_logoff_time(sampass));
-               make_a_mod(mods, ldap_op, "logoffTime", temp);
-       }
+       if (need_update(sampass, PDB_PROFILE))
+               make_ldap_mod(ldap_state->ldap_struct, existing, mods,
+                             "profilePath", pdb_get_profile_path(sampass));
 
-       if (need_ldap_mod(pdb_add, sampass, PDB_KICKOFFTIME)) {
-               slprintf (temp, sizeof (temp) - 1, "%li", pdb_get_kickoff_time(sampass));
-               make_a_mod(mods, ldap_op, "kickoffTime", temp);
-       }
+       slprintf(temp, sizeof(temp) - 1, "%li", pdb_get_logon_time(sampass));
 
+       if (need_update(sampass, PDB_LOGONTIME))
+               make_ldap_mod(ldap_state->ldap_struct, existing, mods,
+                             "logonTime", temp);
 
-       if (need_ldap_mod(pdb_add, sampass, PDB_CANCHANGETIME)) {
-               slprintf (temp, sizeof (temp) - 1, "%li", pdb_get_pass_can_change_time(sampass));
-               make_a_mod(mods, ldap_op, "pwdCanChange", temp);
-       }
+       slprintf(temp, sizeof(temp) - 1, "%li", pdb_get_logoff_time(sampass));
 
-       if (need_ldap_mod(pdb_add, sampass, PDB_MUSTCHANGETIME)) {
-               slprintf (temp, sizeof (temp) - 1, "%li", pdb_get_pass_must_change_time(sampass));
-               make_a_mod(mods, ldap_op, "pwdMustChange", temp);
-       }
+       if (need_update(sampass, PDB_LOGOFFTIME))
+               make_ldap_mod(ldap_state->ldap_struct, existing, mods,
+                             "logoffTime", temp);
+
+       slprintf (temp, sizeof (temp) - 1, "%li",
+                 pdb_get_kickoff_time(sampass));
+
+       if (need_update(sampass, PDB_KICKOFFTIME))
+               make_ldap_mod(ldap_state->ldap_struct, existing, mods,
+                             "kickoffTime", temp);
+
+       slprintf (temp, sizeof (temp) - 1, "%li",
+                 pdb_get_pass_can_change_time(sampass));
+
+       if (need_update(sampass, PDB_CANCHANGETIME))
+               make_ldap_mod(ldap_state->ldap_struct, existing, mods,
+                             "pwdCanChange", temp);
+
+       slprintf (temp, sizeof (temp) - 1, "%li",
+                 pdb_get_pass_must_change_time(sampass));
+
+       if (need_update(sampass, PDB_MUSTCHANGETIME))
+               make_ldap_mod(ldap_state->ldap_struct, existing, mods,
+                             "pwdMustChange", temp);
 
        if ((pdb_get_acct_ctrl(sampass)&(ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST))||
-               (lp_ldap_passwd_sync()!=LDAP_PASSWD_SYNC_ONLY)) {
+           (lp_ldap_passwd_sync()!=LDAP_PASSWD_SYNC_ONLY)) {
 
-               if (need_ldap_mod(pdb_add, sampass, PDB_LMPASSWD)) {
-                       pdb_sethexpwd (temp, pdb_get_lanman_passwd(sampass), pdb_get_acct_ctrl(sampass));
-                       make_a_mod (mods, ldap_op, "lmPassword", temp);
-               }
-               
-               if (need_ldap_mod(pdb_add, sampass, PDB_NTPASSWD)) {
-                       pdb_sethexpwd (temp, pdb_get_nt_passwd(sampass), pdb_get_acct_ctrl(sampass));
-                       make_a_mod (mods, ldap_op, "ntPassword", temp);
-               }
-               
-               if (need_ldap_mod(pdb_add, sampass, PDB_PASSLASTSET)) {
-                       slprintf (temp, sizeof (temp) - 1, "%li", pdb_get_pass_last_set_time(sampass));
-                       make_a_mod(mods, ldap_op, "pwdLastSet", temp);
-               }
+               pdb_sethexpwd (temp, pdb_get_lanman_passwd(sampass),
+                              pdb_get_acct_ctrl(sampass));
+
+               if (need_update(sampass, PDB_LMPASSWD))
+                       make_ldap_mod(ldap_state->ldap_struct, existing, mods,
+                                     "lmPassword", temp);
+
+               pdb_sethexpwd (temp, pdb_get_nt_passwd(sampass),
+                              pdb_get_acct_ctrl(sampass));
+
+               if (need_update(sampass, PDB_NTPASSWD))
+                       make_ldap_mod(ldap_state->ldap_struct, existing, mods,
+                                     "ntPassword", temp);
+
+               slprintf (temp, sizeof (temp) - 1, "%li",
+                         pdb_get_pass_last_set_time(sampass));
+
+               if (need_update(sampass, PDB_PASSLASTSET))
+                       make_ldap_mod(ldap_state->ldap_struct, existing, mods,
+                                     "pwdLastSet", temp);
        }
 
        /* FIXME: Hours stuff goes in LDAP  */
-       if (need_ldap_mod(pdb_add, sampass, PDB_ACCTCTRL)) {
-               make_a_mod (mods, ldap_op, "acctFlags", pdb_encode_acct_ctrl (pdb_get_acct_ctrl(sampass),
-                       NEW_PW_FORMAT_SPACE_PADDED_LEN));
-       }
-       
+
+       if (need_update(sampass, PDB_ACCTCTRL))
+               make_ldap_mod(ldap_state->ldap_struct, existing, mods,
+                             "acctFlags",
+                             pdb_encode_acct_ctrl (pdb_get_acct_ctrl(sampass),
+                                                   NEW_PW_FORMAT_SPACE_PADDED_LEN));
+
        return True;
 }
 
@@ -1704,15 +1895,15 @@ static NTSTATUS ldapsam_modify_entry(struct pdb_methods *my_methods,
                }
                
                if (rc!=LDAP_SUCCESS) {
-                       char *ld_error;
+                       char *ld_error = NULL;
                        ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
                                        &ld_error);
                        DEBUG(1,
                              ("failed to %s user dn= %s with: %s\n\t%s\n",
                               ldap_op == LDAP_MOD_ADD ? "add" : "modify",
                               dn, ldap_err2string(rc),
-                              ld_error));
-                       free(ld_error);
+                              ld_error?ld_error:"unknown"));
+                       SAFE_FREE(ld_error);
                        return NT_STATUS_UNSUCCESSFUL;
                }  
        }
@@ -1769,9 +1960,13 @@ static NTSTATUS ldapsam_delete_sam_account(struct pdb_methods *my_methods, SAM_A
        struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
        const char *sname;
        int rc;
-       char *dn;
-       LDAPMessage *entry;
        LDAPMessage *result;
+       NTSTATUS ret;
+       const char *sam_user_attrs[] =
+       { "lmPassword", "ntPassword", "pwdLastSet", "logonTime", "logoffTime",
+         "kickoffTime", "pwdCanChange", "pwdMustChange", "acctFlags",
+         "displayName", "smbHome", "homeDrive", "scriptPath", "profilePath",
+         "userWorkstations", "primaryGroupID", "domain", "rid", NULL };
 
        if (!sam_acct) {
                DEBUG(0, ("sam_acct was NULL!\n"));
@@ -1787,30 +1982,20 @@ static NTSTATUS ldapsam_delete_sam_account(struct pdb_methods *my_methods, SAM_A
                return NT_STATUS_NO_SUCH_USER;
        }
 
-       if (ldap_count_entries (ldap_state->ldap_struct, result) == 0) {
-               DEBUG (0, ("User doesn't exit!\n"));
-               ldap_msgfree (result);
-               return NT_STATUS_NO_SUCH_USER;
-       }
-
-       entry = ldap_first_entry (ldap_state->ldap_struct, result);
-       dn = ldap_get_dn (ldap_state->ldap_struct, entry);
+       ret = ldapsam_delete_entry(ldap_state, result, "sambaAccount",
+                                  sam_user_attrs);
        ldap_msgfree(result);
-       
-       rc = ldapsam_delete(ldap_state, dn);
-
-       ldap_memfree (dn);
-       if (rc != LDAP_SUCCESS) {
-               char *ld_error;
-               ldap_get_option (ldap_state->ldap_struct, LDAP_OPT_ERROR_STRING, &ld_error);
-               DEBUG (0,("failed to delete user with uid = %s with: %s\n\t%s\n",
-                       sname, ldap_err2string (rc), ld_error));
-               free (ld_error);
-               return NT_STATUS_CANNOT_DELETE;
-       }
+       return ret;
+}
 
-       DEBUG (2,("successfully deleted uid = %s from the LDAP database\n", sname));
-       return NT_STATUS_OK;
+/**********************************************************************
+  Helper function to determine for update_sam_account whether
+  we need LDAP modification.
+*********************************************************************/
+static BOOL element_is_changed(const SAM_ACCOUNT *sampass,
+                              enum pdb_elements element)
+{
+       return IS_SAM_CHANGED(sampass, element);
 }
 
 /**********************************************************************
@@ -1826,49 +2011,65 @@ static NTSTATUS ldapsam_update_sam_account(struct pdb_methods *my_methods, SAM_A
        LDAPMessage *entry;
        LDAPMod **mods;
 
-       if (!init_ldap_from_sam(ldap_state, &mods, LDAP_MOD_REPLACE, False, newpwd)) {
-               DEBUG(0, ("ldapsam_update_sam_account: init_ldap_from_sam failed!\n"));
-               return NT_STATUS_UNSUCCESSFUL;
-       }
-       
-       if (mods == NULL) {
-               DEBUG(4,("mods is empty: nothing to update for user: %s\n",pdb_get_username(newpwd)));
-               return NT_STATUS_OK;
-       }
-       
        rc = ldapsam_search_one_user_by_name(ldap_state, pdb_get_username(newpwd), &result);
        if (rc != LDAP_SUCCESS) {
-               ldap_mods_free(mods, 1);
                return NT_STATUS_UNSUCCESSFUL;
        }
 
        if (ldap_count_entries(ldap_state->ldap_struct, result) == 0) {
                DEBUG(0, ("No user to modify!\n"));
                ldap_msgfree(result);
-               ldap_mods_free(mods, 1);
                return NT_STATUS_UNSUCCESSFUL;
        }
 
        entry = ldap_first_entry(ldap_state->ldap_struct, result);
        dn = ldap_get_dn(ldap_state->ldap_struct, entry);
+
+       if (!init_ldap_from_sam(ldap_state, entry, &mods, newpwd,
+                               element_is_changed)) {
+               DEBUG(0, ("ldapsam_update_sam_account: init_ldap_from_sam failed!\n"));
+               ldap_msgfree(result);
+               return NT_STATUS_UNSUCCESSFUL;
+       }
+       
         ldap_msgfree(result);
        
+       if (mods == NULL) {
+               DEBUG(4,("mods is empty: nothing to update for user: %s\n",
+                        pdb_get_username(newpwd)));
+               ldap_mods_free(mods, 1);
+               return NT_STATUS_OK;
+       }
+       
        ret = ldapsam_modify_entry(my_methods,newpwd,dn,mods,LDAP_MOD_REPLACE, False);
-       if (NT_STATUS_IS_ERR(ret)) {
-               DEBUG(0,("failed to modify user with uid = %s\n",
-                                       pdb_get_username(newpwd)));
-               ldap_mods_free(mods,1);
+       ldap_mods_free(mods,1);
+
+       if (!NT_STATUS_IS_OK(ret)) {
+               char *ld_error = NULL;
+               ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
+                               &ld_error);
+               DEBUG(0,("failed to modify user with uid = %s, error: %s (%s)\n",
+                        pdb_get_username(newpwd), ld_error?ld_error:"(unknwon)", ldap_err2string(rc)));
+               SAFE_FREE(ld_error);
                return ret;
        }
 
-
-       DEBUG(2,
-             ("successfully modified uid = %s in the LDAP database\n",
-              pdb_get_username(newpwd)));
-       ldap_mods_free(mods, 1);
+       DEBUG(2, ("successfully modified uid = %s in the LDAP database\n",
+                 pdb_get_username(newpwd)));
        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 SAM_ACCOUNT *sampass,
+                                     enum pdb_elements element)
+{
+       return (IS_SAM_SET(sampass, element) ||
+               IS_SAM_CHANGED(sampass, element));
+}
+
 /**********************************************************************
 Add SAM_ACCOUNT to LDAP 
 *********************************************************************/
@@ -1879,6 +2080,7 @@ static NTSTATUS ldapsam_add_sam_account(struct pdb_methods *my_methods, SAM_ACCO
        int rc;
        pstring filter;
        LDAPMessage *result = NULL;
+       LDAPMessage *entry  = NULL;
        pstring dn;
        LDAPMod **mods = NULL;
        int             ldap_op;
@@ -1920,7 +2122,6 @@ static NTSTATUS ldapsam_add_sam_account(struct pdb_methods *my_methods, SAM_ACCO
        /* Check if we need to update an existing entry */
        if (num_result == 1) {
                char *tmp;
-               LDAPMessage *entry;
                
                DEBUG(3,("User exists without samba properties: adding them\n"));
                ldap_op = LDAP_MOD_REPLACE;
@@ -1939,14 +2140,15 @@ static NTSTATUS ldapsam_add_sam_account(struct pdb_methods *my_methods, SAM_ACCO
                 }
        }
 
-       ldap_msgfree(result);
-
-       if (!init_ldap_from_sam(ldap_state, &mods, ldap_op, True, newpwd)) {
+       if (!init_ldap_from_sam(ldap_state, entry, &mods, newpwd,
+                               element_is_set_or_changed)) {
                DEBUG(0, ("ldapsam_add_sam_account: init_ldap_from_sam failed!\n"));
-               ldap_mods_free(mods, 1);
+               ldap_msgfree(result);
                return NT_STATUS_UNSUCCESSFUL;          
        }
        
+       ldap_msgfree(result);
+
        if (mods == NULL) {
                DEBUG(0,("mods is empty: nothing to add for user: %s\n",pdb_get_username(newpwd)));
                return NT_STATUS_UNSUCCESSFUL;
@@ -1987,6 +2189,496 @@ static void free_private_data(void **vp)
        /* No need to free any further, as it is talloc()ed */
 }
 
+static const char *group_attr[] = {"cn", "ntSid", "ntGroupType",
+                                  "gidNumber",
+                                  "displayName", "description",
+                                  NULL };
+                                  
+static int ldapsam_search_one_group (struct ldapsam_privates *ldap_state,
+                                    const char *filter,
+                                    LDAPMessage ** result)
+{
+       int scope = LDAP_SCOPE_SUBTREE;
+       int rc;
+
+       DEBUG(2, ("ldapsam_search_one_group: searching for:[%s]\n", filter));
+
+       rc = ldapsam_search(ldap_state, lp_ldap_suffix (), scope,
+                           filter, group_attr, 0, result);
+
+       if (rc != LDAP_SUCCESS) {
+               char *ld_error = NULL;
+               ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
+                               &ld_error);
+               DEBUG(0, ("ldapsam_search_one_group: "
+                         "Problem during the LDAP search: LDAP error: %s (%s)",
+                         ld_error?ld_error:"(unknown)", ldap_err2string(rc)));
+               DEBUG(3, ("ldapsam_search_one_group: Query was: %s, %s\n",
+                         lp_ldap_suffix(), filter));
+               SAFE_FREE(ld_error);
+       }
+
+       return rc;
+}
+
+static BOOL init_group_from_ldap(struct ldapsam_privates *ldap_state,
+                                GROUP_MAP *map, LDAPMessage *entry)
+{
+       pstring temp;
+
+       if (ldap_state == NULL || map == NULL || entry == NULL ||
+           ldap_state->ldap_struct == NULL) {
+               DEBUG(0, ("init_group_from_ldap: NULL parameters found!\n"));
+               return False;
+       }
+
+       if (!get_single_attribute(ldap_state->ldap_struct, entry, "gidNumber",
+                                 temp)) {
+               DEBUG(0, ("Mandatory attribute gidNumber not found\n"));
+               return False;
+       }
+       DEBUG(2, ("Entry found for group: %s\n", temp));
+
+       map->gid = (gid_t)atol(temp);
+
+       if (!get_single_attribute(ldap_state->ldap_struct, entry, "ntSid",
+                                 temp)) {
+               DEBUG(0, ("Mandatory attribute ntSid not found\n"));
+               return False;
+       }
+       string_to_sid(&map->sid, temp);
+
+       if (!get_single_attribute(ldap_state->ldap_struct, entry, "ntGroupType",
+                                 temp)) {
+               DEBUG(0, ("Mandatory attribute ntGroupType not found\n"));
+               return False;
+       }
+       map->sid_name_use = (uint32)atol(temp);
+
+       if ((map->sid_name_use < SID_NAME_USER) ||
+           (map->sid_name_use > SID_NAME_UNKNOWN)) {
+               DEBUG(0, ("Unknown Group type: %d\n", map->sid_name_use));
+               return False;
+       }
+
+       if (!get_single_attribute(ldap_state->ldap_struct, entry, "displayName",
+                                 temp)) {
+               DEBUG(3, ("Attribute displayName not found\n"));
+               temp[0] = '\0';
+               if (!get_single_attribute(ldap_state->ldap_struct, entry, "cn",
+                                         temp)) {
+                       DEBUG(0, ("Attributes cn not found either "
+                                 "for gidNumber(%i)\n",map->gid));
+                       return False;
+               }
+       }
+       fstrcpy(map->nt_name, temp);
+
+       if (!get_single_attribute(ldap_state->ldap_struct, entry, "description",
+                                 temp)) {
+               DEBUG(3, ("Attribute description not found\n"));
+               temp[0] = '\0';
+       }
+       fstrcpy(map->comment, temp);
+
+       map->systemaccount = 0;
+       init_privilege(&map->priv_set);
+
+       return True;
+}
+
+static BOOL init_ldap_from_group(LDAP *ldap_struct,
+                                LDAPMessage *existing,
+                                LDAPMod ***mods,
+                                const GROUP_MAP *map)
+{
+       pstring tmp;
+
+       if (mods == NULL || map == NULL) {
+               DEBUG(0, ("init_ldap_from_group: NULL parameters found!\n"));
+               return False;
+       }
+
+       *mods = NULL;
+
+       sid_to_string(tmp, &map->sid);
+       make_ldap_mod(ldap_struct, existing, mods, "ntSid", tmp);
+       snprintf(tmp, sizeof(tmp)-1, "%i", map->sid_name_use);
+       make_ldap_mod(ldap_struct, existing, mods, "ntGroupType", tmp);
+
+       make_ldap_mod(ldap_struct, existing, mods, "displayName", map->nt_name);
+       make_ldap_mod(ldap_struct, existing, mods, "description", map->comment);
+
+       return True;
+}
+
+static NTSTATUS ldapsam_getgroup(struct pdb_methods *methods,
+                                const char *filter,
+                                GROUP_MAP *map)
+{
+       struct ldapsam_privates *ldap_state =
+               (struct ldapsam_privates *)methods->private_data;
+       LDAPMessage *result;
+       LDAPMessage *entry;
+       int count;
+
+       if (ldapsam_search_one_group(ldap_state, filter, &result)
+           != LDAP_SUCCESS) {
+               return NT_STATUS_NO_SUCH_GROUP;
+       }
+
+       count = ldap_count_entries(ldap_state->ldap_struct, result);
+
+       if (count < 1) {
+               DEBUG(4, ("Did not find group for filter %s\n", filter));
+               return NT_STATUS_NO_SUCH_GROUP;
+       }
+
+       if (count > 1) {
+               DEBUG(1, ("Duplicate entries for filter %s: count=%d\n",
+                         filter, count));
+               return NT_STATUS_NO_SUCH_GROUP;
+       }
+
+       entry = ldap_first_entry(ldap_state->ldap_struct, result);
+
+       if (!entry) {
+               ldap_msgfree(result);
+               return NT_STATUS_UNSUCCESSFUL;
+       }
+
+       if (!init_group_from_ldap(ldap_state, map, entry)) {
+               DEBUG(1, ("init_group_from_ldap failed for group filter %s\n",
+                         filter));
+               ldap_msgfree(result);
+               return NT_STATUS_NO_SUCH_GROUP;
+       }
+
+       ldap_msgfree(result);
+       return NT_STATUS_OK;
+}
+
+static NTSTATUS ldapsam_getgrsid(struct pdb_methods *methods, GROUP_MAP *map,
+                                DOM_SID sid, BOOL with_priv)
+{
+       pstring filter;
+
+       snprintf(filter, sizeof(filter)-1,
+                "(&(objectClass=sambaGroupMapping)(ntSid=%s))",
+                sid_string_static(&sid));
+
+       return ldapsam_getgroup(methods, filter, map);
+}
+
+static NTSTATUS ldapsam_getgrgid(struct pdb_methods *methods, GROUP_MAP *map,
+                                gid_t gid, BOOL with_priv)
+{
+       pstring filter;
+
+       snprintf(filter, sizeof(filter)-1,
+                "(&(objectClass=sambaGroupMapping)(gidNumber=%d))",
+                gid);
+
+       return ldapsam_getgroup(methods, filter, map);
+}
+
+static NTSTATUS ldapsam_getgrnam(struct pdb_methods *methods, GROUP_MAP *map,
+                                char *name, BOOL with_priv)
+{
+       pstring filter;
+
+       /* TODO: Escaping of name? */
+
+       snprintf(filter, sizeof(filter)-1,
+                "(&(objectClass=sambaGroupMapping)(|(displayName=%s)(cn=%s)))",
+                name, name);
+
+       return ldapsam_getgroup(methods, filter, map);
+}
+
+static int ldapsam_search_one_group_by_gid(struct ldapsam_privates *ldap_state,
+                                          gid_t gid,
+                                          LDAPMessage **result)
+{
+       pstring filter;
+
+       snprintf(filter, sizeof(filter)-1,
+                "(&(objectClass=posixGroup)(gidNumber=%i))", gid);
+
+       return ldapsam_search_one_group(ldap_state, filter, result);
+}
+
+static NTSTATUS ldapsam_add_group_mapping_entry(struct pdb_methods *methods,
+                                               GROUP_MAP *map)
+{
+       struct ldapsam_privates *ldap_state =
+               (struct ldapsam_privates *)methods->private_data;
+       LDAPMessage *result = NULL;
+       LDAPMod **mods = NULL;
+
+       char *tmp;
+       pstring dn;
+       LDAPMessage *entry;
+
+       GROUP_MAP dummy;
+
+       int rc;
+
+       if (NT_STATUS_IS_OK(ldapsam_getgrgid(methods, &dummy,
+                                            map->gid, False))) {
+               DEBUG(0, ("Group %i already exists in LDAP\n", map->gid));
+               return NT_STATUS_UNSUCCESSFUL;
+       }
+
+       rc = ldapsam_search_one_group_by_gid(ldap_state, map->gid, &result);
+       if (rc != LDAP_SUCCESS) {
+               return NT_STATUS_UNSUCCESSFUL;
+       }
+
+       if (ldap_count_entries(ldap_state->ldap_struct, result) != 1) {
+               DEBUG(2, ("Group %i must exist exactly once in LDAP\n",
+                         map->gid));
+               ldap_msgfree(result);
+               return NT_STATUS_UNSUCCESSFUL;
+       }
+
+       entry = ldap_first_entry(ldap_state->ldap_struct, result);
+       tmp = ldap_get_dn(ldap_state->ldap_struct, entry);
+       pstrcpy(dn, tmp);
+       ldap_memfree(tmp);
+
+       if (!init_ldap_from_group(ldap_state->ldap_struct,
+                                 result, &mods, map)) {
+               DEBUG(0, ("init_ldap_from_group failed!\n"));
+               ldap_mods_free(mods, 1);
+               ldap_msgfree(result);
+               return NT_STATUS_UNSUCCESSFUL;
+       }
+
+       ldap_msgfree(result);
+
+       if (mods == NULL) {
+               DEBUG(0, ("mods is empty\n"));
+               return NT_STATUS_UNSUCCESSFUL;
+       }
+
+       make_a_mod(&mods, LDAP_MOD_ADD, "objectClass",
+                  "sambaGroupMapping");
+
+       rc = ldapsam_modify(ldap_state, dn, mods);
+       ldap_mods_free(mods, 1);
+
+       if (rc != LDAP_SUCCESS) {
+               char *ld_error = NULL;
+               ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
+                               &ld_error);
+               DEBUG(0, ("failed to add group %i error: %s (%s)\n", map->gid, 
+                         ld_error ? ld_error : "(unknown)", ldap_err2string(rc)));
+               SAFE_FREE(ld_error);
+               return NT_STATUS_UNSUCCESSFUL;
+       }
+
+       DEBUG(2, ("successfully modified group %i in LDAP\n", map->gid));
+       return NT_STATUS_OK;
+}
+
+static NTSTATUS ldapsam_update_group_mapping_entry(struct pdb_methods *methods,
+                                                  GROUP_MAP *map)
+{
+       struct ldapsam_privates *ldap_state =
+               (struct ldapsam_privates *)methods->private_data;
+       int rc;
+       char *dn;
+       LDAPMessage *result;
+       LDAPMessage *entry;
+       LDAPMod **mods;
+
+       rc = ldapsam_search_one_group_by_gid(ldap_state, map->gid, &result);
+
+       if (rc != LDAP_SUCCESS) {
+               return NT_STATUS_UNSUCCESSFUL;
+       }
+
+       if (ldap_count_entries(ldap_state->ldap_struct, result) == 0) {
+               DEBUG(0, ("No group to modify!\n"));
+               ldap_msgfree(result);
+               return NT_STATUS_UNSUCCESSFUL;
+       }
+
+       entry = ldap_first_entry(ldap_state->ldap_struct, result);
+       dn = ldap_get_dn(ldap_state->ldap_struct, entry);
+
+       if (!init_ldap_from_group(ldap_state->ldap_struct,
+                                 result, &mods, map)) {
+               DEBUG(0, ("init_ldap_from_group failed\n"));
+               ldap_msgfree(result);
+               return NT_STATUS_UNSUCCESSFUL;
+       }
+
+       ldap_msgfree(result);
+
+       if (mods == NULL) {
+               DEBUG(4, ("mods is empty: nothing to do\n"));
+               return NT_STATUS_UNSUCCESSFUL;
+       }
+
+       rc = ldapsam_modify(ldap_state, dn, mods);
+
+       ldap_mods_free(mods, 1);
+
+       if (rc != LDAP_SUCCESS) {
+               char *ld_error = NULL;
+               ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
+                               &ld_error);
+               DEBUG(0, ("failed to modify group %i error: %s (%s)\n", map->gid, 
+                         ld_error ? ld_error : "(unknown)", ldap_err2string(rc)));
+               SAFE_FREE(ld_error);
+       }
+
+       DEBUG(2, ("successfully modified group %i in LDAP\n", map->gid));
+       return NT_STATUS_OK;
+}
+
+static NTSTATUS ldapsam_delete_group_mapping_entry(struct pdb_methods *methods,
+                                                  DOM_SID sid)
+{
+       struct ldapsam_privates *ldap_state =
+               (struct ldapsam_privates *)methods->private_data;
+       pstring sidstring, filter;
+       LDAPMessage *result;
+       int rc;
+       NTSTATUS ret;
+
+       const char *sam_group_attrs[] = { "ntSid", "ntGroupType",
+                                         "description", "displayName",
+                                         NULL };
+       sid_to_string(sidstring, &sid);
+       snprintf(filter, sizeof(filter)-1,
+                "(&(objectClass=sambaGroupMapping)(ntSid=%s))", sidstring);
+
+       rc = ldapsam_search_one_group(ldap_state, filter, &result);
+
+       if (rc != LDAP_SUCCESS) {
+               return NT_STATUS_NO_SUCH_GROUP;
+       }
+
+       ret = ldapsam_delete_entry(ldap_state, result, "sambaGroupMapping",
+                                  sam_group_attrs);
+       ldap_msgfree(result);
+       return ret;
+}
+
+static NTSTATUS ldapsam_setsamgrent(struct pdb_methods *my_methods,
+                                   BOOL update)
+{
+       struct ldapsam_privates *ldap_state =
+               (struct ldapsam_privates *)my_methods->private_data;
+       const char *filter = "(objectClass=sambaGroupMapping)";
+       int rc;
+
+       rc = ldapsam_search(ldap_state, lp_ldap_suffix(),
+                           LDAP_SCOPE_SUBTREE, filter,
+                           group_attr, 0, &ldap_state->result);
+
+       if (rc != LDAP_SUCCESS) {
+               DEBUG(0, ("LDAP search failed: %s\n", ldap_err2string(rc)));
+               DEBUG(3, ("Query was: %s, %s\n", lp_ldap_suffix(), filter));
+               ldap_msgfree(ldap_state->result);
+               ldap_state->result = NULL;
+               return NT_STATUS_UNSUCCESSFUL;
+       }
+
+       DEBUG(2, ("ldapsam_setsampwent: %d entries in the base!\n",
+                 ldap_count_entries(ldap_state->ldap_struct,
+                                    ldap_state->result)));
+
+       ldap_state->entry = ldap_first_entry(ldap_state->ldap_struct,
+                                ldap_state->result);
+       ldap_state->index = 0;
+
+       return NT_STATUS_OK;
+}
+
+static void ldapsam_endsamgrent(struct pdb_methods *my_methods)
+{
+       ldapsam_endsampwent(my_methods);
+}
+
+static NTSTATUS ldapsam_getsamgrent(struct pdb_methods *my_methods,
+                                   GROUP_MAP *map)
+{
+       NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
+       struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
+       BOOL bret = False;
+
+       /* The rebind proc needs this *HACK*.  We are not multithreaded, so
+          this will work, but it's not nice. */
+       static_ldap_state = ldap_state;
+
+       while (!bret) {
+               if (!ldap_state->entry)
+                       return ret;
+               
+               ldap_state->index++;
+               bret = init_group_from_ldap(ldap_state, map, ldap_state->entry);
+               
+               ldap_state->entry = ldap_next_entry(ldap_state->ldap_struct,
+                                           ldap_state->entry); 
+       }
+
+       return NT_STATUS_OK;
+}
+
+static NTSTATUS ldapsam_enum_group_mapping(struct pdb_methods *methods,
+                                          enum SID_NAME_USE sid_name_use,
+                                          GROUP_MAP **rmap, int *num_entries,
+                                          BOOL unix_only, BOOL with_priv)
+{
+       GROUP_MAP map;
+       GROUP_MAP *mapt;
+       int entries = 0;
+       NTSTATUS nt_status;
+
+       *num_entries = 0;
+       *rmap = NULL;
+
+       if (!NT_STATUS_IS_OK(ldapsam_setsamgrent(methods, False))) {
+               DEBUG(0, ("Unable to open passdb\n"));
+               return NT_STATUS_ACCESS_DENIED;
+       }
+
+       while (NT_STATUS_IS_OK(nt_status = ldapsam_getsamgrent(methods, &map))) {
+               if (sid_name_use != SID_NAME_UNKNOWN &&
+                   sid_name_use != map.sid_name_use) {
+                       DEBUG(11,("enum_group_mapping: group %s is not of the requested type\n", map.nt_name));
+                       continue;
+               }
+               if (unix_only==ENUM_ONLY_MAPPED && map.gid==-1) {
+                       DEBUG(11,("enum_group_mapping: group %s is non mapped\n", map.nt_name));
+                       continue;
+               }
+
+               mapt=(GROUP_MAP *)Realloc((*rmap), (entries+1)*sizeof(GROUP_MAP));
+               if (!mapt) {
+                       DEBUG(0,("enum_group_mapping: Unable to enlarge group map!\n"));
+                       SAFE_FREE(*rmap);
+                       return NT_STATUS_UNSUCCESSFUL;
+               }
+               else
+                       (*rmap) = mapt;
+
+               mapt[entries] = map;
+
+               entries += 1;
+
+       }
+       ldapsam_endsamgrent(methods);
+
+       *num_entries = entries;
+
+       return NT_STATUS_OK;
+}
+
 NTSTATUS pdb_init_ldapsam(PDB_CONTEXT *pdb_context, PDB_METHODS **pdb_method, const char *location)
 {
        NTSTATUS nt_status;
@@ -2007,6 +2699,14 @@ NTSTATUS pdb_init_ldapsam(PDB_CONTEXT *pdb_context, PDB_METHODS **pdb_method, co
        (*pdb_method)->update_sam_account = ldapsam_update_sam_account;
        (*pdb_method)->delete_sam_account = ldapsam_delete_sam_account;
 
+       (*pdb_method)->getgrsid = ldapsam_getgrsid;
+       (*pdb_method)->getgrgid = ldapsam_getgrgid;
+       (*pdb_method)->getgrnam = ldapsam_getgrnam;
+       (*pdb_method)->add_group_mapping_entry = ldapsam_add_group_mapping_entry;
+       (*pdb_method)->update_group_mapping_entry = ldapsam_update_group_mapping_entry;
+       (*pdb_method)->delete_group_mapping_entry = ldapsam_delete_group_mapping_entry;
+       (*pdb_method)->enum_group_mapping = ldapsam_enum_group_mapping;
+
        /* TODO: Setup private data and free */
 
        ldap_state = talloc_zero(pdb_context->mem_ctx, sizeof(struct ldapsam_privates));
@@ -2072,20 +2772,9 @@ NTSTATUS pdb_init_ldapsam_nua(PDB_CONTEXT *pdb_context, PDB_METHODS **pdb_method
        return NT_STATUS_OK;
 }
 
-
-#else
-
-NTSTATUS pdb_init_ldapsam(PDB_CONTEXT *pdb_context, PDB_METHODS **pdb_method, const char *location)
-{
-       DEBUG(0, ("ldap not detected at configure time, ldapsam not availalble!\n"));
-       return NT_STATUS_UNSUCCESSFUL;
-}
-
-NTSTATUS pdb_init_ldapsam_nua(PDB_CONTEXT *pdb_context, PDB_METHODS **pdb_method, const char *location)
+int pdb_ldap_init(void)
 {
-       DEBUG(0, ("ldap not dectected at configure time, ldapsam_nua not available!\n"));
-       return NT_STATUS_UNSUCCESSFUL;
+       smb_register_passdb("ldapsam", pdb_init_ldapsam, PASSDB_INTERFACE_VERSION);
+       smb_register_passdb("ldapsam_nua", pdb_init_ldapsam_nua, PASSDB_INTERFACE_VERSION);
+       return True;
 }
-
-
-#endif