r23784: use the GPLv3 boilerplate as recommended by the FSF and the license text
[tprouty/samba.git] / source / utils / net_rpc_samsync.c
index 45fdfbfad3ef2ed06dc7ba60fce3e1a4a05573b5..0be9381c3ac78165e49ca8b305fffdc3f40548f9 100644 (file)
@@ -10,7 +10,7 @@
 
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
-   the Free Software Foundation; either version 2 of the License, or
+   the Free Software Foundation; either version 3 of the License, or
    (at your option) any later version.
    
    This program is distributed in the hope that it will be useful,
@@ -19,8 +19,7 @@
    GNU General Public License for more details.
    
    You should have received a copy of the GNU General Public License
-   along with this program; if not, write to the Free Software
-   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
 
 #include "includes.h"
@@ -29,7 +28,7 @@
 /* uid's and gid's for writing deltas to ldif */
 static uint32 ldif_gid = 999;
 static uint32 ldif_uid = 999;
-/* Kkeep track of ldap initialization */
+/* Keep track of ldap initialization */
 static int init_ldap = 1;
 
 static void display_group_mem_info(uint32 rid, SAM_GROUP_MEM_INFO *g)
@@ -42,44 +41,6 @@ static void display_group_mem_info(uint32 rid, SAM_GROUP_MEM_INFO *g)
        d_printf("\n");
 }
 
-static const char *display_time(NTTIME *nttime)
-{
-       static fstring string;
-
-       float high;
-       float low;
-       int sec;
-       int days, hours, mins, secs;
-       int offset = 1;
-
-       if (nttime->high==0 && nttime->low==0)
-               return "Now";
-
-       if (nttime->high==0x80000000 && nttime->low==0)
-               return "Never";
-
-       high = 65536;   
-       high = high/10000;
-       high = high*65536;
-       high = high/1000;
-       high = high * (~nttime->high);
-
-       low = ~nttime->low;     
-       low = low/(1000*1000*10);
-
-       sec=high+low;
-       sec+=offset;
-
-       days=sec/(60*60*24);
-       hours=(sec - (days*60*60*24)) / (60*60);
-       mins=(sec - (days*60*60*24) - (hours*60*60) ) / 60;
-       secs=sec - (days*60*60*24) - (hours*60*60) - (mins*60);
-
-       fstr_sprintf(string, "%u days, %u hours, %u minutes, %u seconds", days, hours, mins, secs);
-       return (string);
-}
-
-
 static void display_alias_info(uint32 rid, SAM_ALIAS_INFO *a)
 {
        d_printf("Alias '%s' ", unistr2_static(&a->uni_als_name));
@@ -123,11 +84,18 @@ static void display_account_info(uint32 rid, SAM_ACCOUNT_INFO *a)
               pdb_encode_acct_ctrl(a->acb_info, NEW_PW_FORMAT_SPACE_PADDED_LEN));
 }
 
+static time_t uint64s_nt_time_to_unix_abs(const uint64 *src)
+{
+       NTTIME nttime;
+       nttime = *src;
+       return nt_time_to_unix_abs(&nttime);
+}
+
 static void display_domain_info(SAM_DOMAIN_INFO *a)
 {
        time_t u_logout;
 
-       u_logout = nt_time_to_unix_abs((NTTIME *)&a->force_logoff);
+       u_logout = uint64s_nt_time_to_unix_abs(&a->force_logoff);
 
        d_printf("Domain name: %s\n", unistr2_static(&a->uni_dom_name));
 
@@ -136,11 +104,11 @@ static void display_domain_info(SAM_DOMAIN_INFO *a)
 
        d_printf("Force Logoff: %d\n", (int)u_logout);
 
-       d_printf("Max Password Age: %s\n", display_time((NTTIME *)&a->max_pwd_age));
-       d_printf("Min Password Age: %s\n", display_time((NTTIME *)&a->min_pwd_age));
+       d_printf("Max Password Age: %s\n", display_time(a->max_pwd_age));
+       d_printf("Min Password Age: %s\n", display_time(a->min_pwd_age));
 
-       d_printf("Lockout Time: %s\n", display_time((NTTIME *)&a->account_lockout.lockout_duration));
-       d_printf("Lockout Reset Time: %s\n", display_time((NTTIME *)&a->account_lockout.reset_count));
+       d_printf("Lockout Time: %s\n", display_time(a->account_lockout.lockout_duration));
+       d_printf("Lockout Reset Time: %s\n", display_time(a->account_lockout.reset_count));
 
        d_printf("Bad Attempt Lockout: %d\n", a->account_lockout.bad_attempt_lockout);
        d_printf("User must logon to change password: %d\n", a->logon_chgpass);
@@ -243,7 +211,7 @@ static void dump_database(struct rpc_pipe_client *pipe_hnd, uint32 db_type)
                result = rpccli_netlogon_sam_sync(pipe_hnd, mem_ctx, db_type,
                                               sync_context,
                                               &num_deltas, &hdr_deltas, &deltas);
-               if (NT_STATUS_IS_ERR(result))
+               if (!NT_STATUS_IS_OK(result))
                        break;
 
                 for (i = 0; i < num_deltas; i++) {
@@ -300,12 +268,16 @@ NTSTATUS rpc_samdump_internals(const DOM_SID *domain_sid,
        return NT_STATUS_OK;
 }
 
-/* Convert a SAM_ACCOUNT_DELTA to a SAM_ACCOUNT. */
+/* Convert a struct samu_DELTA to a struct samu. */
 #define STRING_CHANGED (old_string && !new_string) ||\
                    (!old_string && new_string) ||\
                (old_string && new_string && (strcmp(old_string, new_string) != 0))
 
-static NTSTATUS sam_account_from_delta(SAM_ACCOUNT *account, SAM_ACCOUNT_INFO *delta)
+#define STRING_CHANGED_NC(s1,s2) ((s1) && !(s2)) ||\
+                   (!(s1) && (s2)) ||\
+               ((s1) && (s2) && (strcmp((s1), (s2)) != 0))
+
+static NTSTATUS sam_account_from_delta(struct samu *account, SAM_ACCOUNT_INFO *delta)
 {
        const char *old_string, *new_string;
        time_t unix_time, stored_time;
@@ -389,13 +361,15 @@ static NTSTATUS sam_account_from_delta(SAM_ACCOUNT *account, SAM_ACCOUNT_INFO *d
 
        if (delta->hdr_parameters.buffer) {
                DATA_BLOB mung;
+               char *newstr;
                old_string = pdb_get_munged_dial(account);
                mung.length = delta->hdr_parameters.uni_str_len;
                mung.data = (uint8 *) delta->uni_parameters.buffer;
-               new_string = (mung.length == 0) ? NULL : base64_encode_data_blob(mung);
+               newstr = (mung.length == 0) ? NULL : base64_encode_data_blob(mung);
 
-               if (STRING_CHANGED)
-                       pdb_set_munged_dial(account, new_string, PDB_CHANGED);
+               if (STRING_CHANGED_NC(old_string, newstr))
+                       pdb_set_munged_dial(account, newstr, PDB_CHANGED);
+               SAFE_FREE(newstr);
        }
 
        /* User and group sid */
@@ -406,14 +380,14 @@ static NTSTATUS sam_account_from_delta(SAM_ACCOUNT *account, SAM_ACCOUNT_INFO *d
 
        /* Logon and password information */
        if (!nt_time_is_zero(&delta->logon_time)) {
-               unix_time = nt_time_to_unix(&delta->logon_time);
+               unix_time = nt_time_to_unix(delta->logon_time);
                stored_time = pdb_get_logon_time(account);
                if (stored_time != unix_time)
                        pdb_set_logon_time(account, unix_time, PDB_CHANGED);
        }
 
        if (!nt_time_is_zero(&delta->logoff_time)) {
-               unix_time = nt_time_to_unix(&delta->logoff_time);
+               unix_time = nt_time_to_unix(delta->logoff_time);
                stored_time = pdb_get_logoff_time(account);
                if (stored_time != unix_time)
                        pdb_set_logoff_time(account, unix_time,PDB_CHANGED);
@@ -449,7 +423,7 @@ static NTSTATUS sam_account_from_delta(SAM_ACCOUNT *account, SAM_ACCOUNT_INFO *d
                pdb_set_logon_count(account, delta->logon_count, PDB_CHANGED);
 
        if (!nt_time_is_zero(&delta->pwd_last_set_time)) {
-               unix_time = nt_time_to_unix(&delta->pwd_last_set_time);
+               unix_time = nt_time_to_unix(delta->pwd_last_set_time);
                stored_time = pdb_get_pass_last_set_time(account);
                if (stored_time != unix_time)
                        pdb_set_pass_last_set_time(account, unix_time, PDB_CHANGED);
@@ -494,10 +468,10 @@ static NTSTATUS sam_account_from_delta(SAM_ACCOUNT *account, SAM_ACCOUNT_INFO *d
 
 static NTSTATUS fetch_account_info(uint32 rid, SAM_ACCOUNT_INFO *delta)
 {
-       NTSTATUS nt_ret;
+       NTSTATUS nt_ret = NT_STATUS_UNSUCCESSFUL;
        fstring account;
        pstring add_script;
-       SAM_ACCOUNT *sam_account=NULL;
+       struct samu *sam_account=NULL;
        GROUP_MAP map;
        struct group *grp;
        DOM_SID user_sid;
@@ -508,8 +482,9 @@ static NTSTATUS fetch_account_info(uint32 rid, SAM_ACCOUNT_INFO *delta)
        fstrcpy(account, unistr2_static(&delta->uni_acct_name));
        d_printf("Creating account: %s\n", account);
 
-       if (!NT_STATUS_IS_OK(nt_ret = pdb_init_sam(&sam_account)))
-               return nt_ret;
+       if ( !(sam_account = samu_new( NULL )) ) {
+               return NT_STATUS_NO_MEMORY;
+       }
 
        if (!(passwd = Get_Pwnam(account))) {
                /* Create appropriate user */
@@ -532,6 +507,9 @@ static NTSTATUS fetch_account_info(uint32 rid, SAM_ACCOUNT_INFO *delta)
                        add_ret = smbrun(add_script,NULL);
                        DEBUG(add_ret ? 0 : 1,("fetch_account: Running the command `%s' "
                                 "gave %d\n", add_script, add_ret));
+                       if (add_ret == 0) {
+                               smb_nscd_flush_user_cache();
+                       }
                }
                
                /* try and find the possible unix account again */
@@ -550,7 +528,7 @@ static NTSTATUS fetch_account_info(uint32 rid, SAM_ACCOUNT_INFO *delta)
                sam_account_from_delta(sam_account, delta);
                DEBUG(3, ("Attempting to add user SID %s for user %s in the passdb\n", 
                          sid_to_string(sid_string, &user_sid), pdb_get_username(sam_account)));
-               if (!pdb_add_sam_account(sam_account)) {
+               if (!NT_STATUS_IS_OK(pdb_add_sam_account(sam_account))) {
                        DEBUG(1, ("SAM Account for %s failed to be added to the passdb!\n",
                                  account));
                        return NT_STATUS_ACCESS_DENIED; 
@@ -562,11 +540,15 @@ static NTSTATUS fetch_account_info(uint32 rid, SAM_ACCOUNT_INFO *delta)
                if (!NT_STATUS_IS_OK(pdb_update_sam_account(sam_account))) {
                        DEBUG(1, ("SAM Account for %s failed to be updated in the passdb!\n",
                                  account));
-                       pdb_free_sam(&sam_account);
+                       TALLOC_FREE(sam_account);
                        return NT_STATUS_ACCESS_DENIED; 
                }
        }
 
+       if (pdb_get_group_sid(sam_account) == NULL) {
+               return NT_STATUS_UNSUCCESSFUL;
+       }
+
        group_sid = *pdb_get_group_sid(sam_account);
 
        if (!pdb_getgrsid(&map, group_sid)) {
@@ -589,7 +571,7 @@ static NTSTATUS fetch_account_info(uint32 rid, SAM_ACCOUNT_INFO *delta)
        }
 
  done:
-       pdb_free_sam(&sam_account);
+       TALLOC_FREE(sam_account);
        return nt_ret;
 }
 
@@ -687,16 +669,23 @@ static NTSTATUS fetch_group_mem_info(uint32 rid, SAM_GROUP_MEM_INFO *delta)
                return NT_STATUS_NO_MEMORY;
        }
 
-       nt_members = TALLOC_ZERO_ARRAY(t, char *, delta->num_members);
+       if (delta->num_members) {
+               if ((nt_members = TALLOC_ZERO_ARRAY(t, char *, delta->num_members)) == NULL) {
+                       DEBUG(0, ("talloc failed\n"));
+                       talloc_free(t);
+                       return NT_STATUS_NO_MEMORY;
+               }
+       } else {
+               nt_members = NULL;
+       }
 
        for (i=0; i<delta->num_members; i++) {
-               NTSTATUS nt_status;
-               SAM_ACCOUNT *member = NULL;
+               struct samu *member = NULL;
                DOM_SID member_sid;
 
-               if (!NT_STATUS_IS_OK(nt_status = pdb_init_sam_talloc(t, &member))) {
+               if ( !(member = samu_new(t)) ) {
                        talloc_destroy(t);
-                       return nt_status;
+                       return NT_STATUS_NO_MEMORY;
                }
 
                sid_copy(&member_sid, get_global_sam_sid());
@@ -705,19 +694,19 @@ static NTSTATUS fetch_group_mem_info(uint32 rid, SAM_GROUP_MEM_INFO *delta)
                if (!pdb_getsampwsid(member, &member_sid)) {
                        DEBUG(1, ("Found bogus group member: %d (member_sid=%s group=%s)\n",
                                  delta->rids[i], sid_string_static(&member_sid), grp->gr_name));
-                       pdb_free_sam(&member);
+                       TALLOC_FREE(member);
                        continue;
                }
 
                if (pdb_get_group_rid(member) == rid) {
                        d_printf("%s(primary),", pdb_get_username(member));
-                       pdb_free_sam(&member);
+                       TALLOC_FREE(member);
                        continue;
                }
                
                d_printf("%s,", pdb_get_username(member));
                nt_members[i] = talloc_strdup(t, pdb_get_username(member));
-               pdb_free_sam(&member);
+               TALLOC_FREE(member);
        }
 
        d_printf("\n");
@@ -844,11 +833,11 @@ static NTSTATUS fetch_domain_info(uint32 rid, SAM_DOMAIN_INFO *delta)
        NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL;
        pstring domname;
 
-       u_max_age = nt_time_to_unix_abs((NTTIME *)&delta->max_pwd_age);
-       u_min_age = nt_time_to_unix_abs((NTTIME *)&delta->min_pwd_age);
-       u_logout = nt_time_to_unix_abs((NTTIME *)&delta->force_logoff);
-       u_lockoutreset = nt_time_to_unix_abs((NTTIME *)&delta->account_lockout.reset_count);
-       u_lockouttime = nt_time_to_unix_abs((NTTIME *)&delta->account_lockout.lockout_duration);
+       u_max_age = uint64s_nt_time_to_unix_abs(&delta->max_pwd_age);
+       u_min_age = uint64s_nt_time_to_unix_abs(&delta->min_pwd_age);
+       u_logout = uint64s_nt_time_to_unix_abs(&delta->force_logoff);
+       u_lockoutreset = uint64s_nt_time_to_unix_abs(&delta->account_lockout.reset_count);
+       u_lockouttime = uint64s_nt_time_to_unix_abs(&delta->account_lockout.lockout_duration);
 
        unistr2_to_ascii(domname, &delta->uni_dom_name, sizeof(domname) - 1);
 
@@ -1011,7 +1000,7 @@ static NTSTATUS fetch_database(struct rpc_pipe_client *pipe_hnd, uint32 db_type,
 static NTSTATUS populate_ldap_for_ldif(fstring sid, const char *suffix, const char 
                       *builtin_sid, FILE *add_fd)
 {
-       char *user_suffix, *group_suffix, *machine_suffix, *idmap_suffix;
+       const char *user_suffix, *group_suffix, *machine_suffix, *idmap_suffix;
        char *user_attr=NULL, *group_attr=NULL;
        char *suffix_attr;
        int len;
@@ -1036,10 +1025,13 @@ static NTSTATUS populate_ldap_for_ldif(fstring sid, const char *suffix, const ch
        fflush(add_fd);
 
        user_suffix = lp_ldap_user_suffix();
+       if (user_suffix == NULL) {
+               SAFE_FREE(suffix_attr);
+               return NT_STATUS_NO_MEMORY;
+       }
        /* If it exists and is distinct from other containers, 
           Write the Users entity */
-       if (user_suffix && *user_suffix &&
-           strcmp(user_suffix, suffix)) {
+       if (*user_suffix && strcmp(user_suffix, suffix)) {
                user_attr = sstring_sub(lp_ldap_user_suffix(), '=', ',');
                fprintf(add_fd, "# %s\n", user_suffix);
                fprintf(add_fd, "dn: %s\n", user_suffix);
@@ -1051,10 +1043,14 @@ static NTSTATUS populate_ldap_for_ldif(fstring sid, const char *suffix, const ch
 
 
        group_suffix = lp_ldap_group_suffix();
+       if (group_suffix == NULL) {
+               SAFE_FREE(suffix_attr);
+               SAFE_FREE(user_attr);
+               return NT_STATUS_NO_MEMORY;
+       }
        /* If it exists and is distinct from other containers, 
           Write the Groups entity */
-       if (group_suffix && *group_suffix &&
-           strcmp(group_suffix, suffix)) {
+       if (*group_suffix && strcmp(group_suffix, suffix)) {
                group_attr = sstring_sub(lp_ldap_group_suffix(), '=', ',');
                fprintf(add_fd, "# %s\n", group_suffix);
                fprintf(add_fd, "dn: %s\n", group_suffix);
@@ -1067,14 +1063,23 @@ static NTSTATUS populate_ldap_for_ldif(fstring sid, const char *suffix, const ch
        /* If it exists and is distinct from other containers, 
           Write the Computers entity */
        machine_suffix = lp_ldap_machine_suffix();
-       if (machine_suffix && *machine_suffix && 
-           strcmp(machine_suffix, user_suffix) &&
+       if (machine_suffix == NULL) {
+               SAFE_FREE(suffix_attr);
+               SAFE_FREE(user_attr);
+               SAFE_FREE(group_attr);
+               return NT_STATUS_NO_MEMORY;
+       }
+       if (*machine_suffix && strcmp(machine_suffix, user_suffix) &&
            strcmp(machine_suffix, suffix)) {
-               fprintf(add_fd, "# %s\n", lp_ldap_machine_suffix());
-               fprintf(add_fd, "dn: %s\n", lp_ldap_machine_suffix());
+               char *machine_ou = NULL;
+               fprintf(add_fd, "# %s\n", machine_suffix);
+               fprintf(add_fd, "dn: %s\n", machine_suffix);
                fprintf(add_fd, "objectClass: organizationalUnit\n");
-               fprintf(add_fd, "ou: %s\n", 
-                       sstring_sub(lp_ldap_machine_suffix(), '=', ','));
+               /* this isn't totally correct as it assumes that
+                  there _must_ be an ou. just fixing memleak now. jmcd */
+               machine_ou = sstring_sub(lp_ldap_machine_suffix(), '=', ',');
+               fprintf(add_fd, "ou: %s\n", machine_ou);
+               SAFE_FREE(machine_ou);
                fprintf(add_fd, "\n");
                fflush(add_fd);
        }
@@ -1082,49 +1087,26 @@ static NTSTATUS populate_ldap_for_ldif(fstring sid, const char *suffix, const ch
        /* If it exists and is distinct from other containers, 
           Write the IdMap entity */
        idmap_suffix = lp_ldap_idmap_suffix();
-       if (idmap_suffix && *idmap_suffix &&
+       if (idmap_suffix == NULL) {
+               SAFE_FREE(suffix_attr);
+               SAFE_FREE(user_attr);
+               SAFE_FREE(group_attr);
+               return NT_STATUS_NO_MEMORY;
+       }
+       if (*idmap_suffix &&
            strcmp(idmap_suffix, user_suffix) &&
            strcmp(idmap_suffix, suffix)) {
+               char *s;
                fprintf(add_fd, "# %s\n", idmap_suffix);
                fprintf(add_fd, "dn: %s\n", idmap_suffix);
                fprintf(add_fd, "ObjectClass: organizationalUnit\n");
-               fprintf(add_fd, "ou: %s\n", 
-                       sstring_sub(lp_ldap_idmap_suffix(), '=', ','));
+               s = sstring_sub(lp_ldap_idmap_suffix(), '=', ',');
+               fprintf(add_fd, "ou: %s\n", s);
+               SAFE_FREE(s);
                fprintf(add_fd, "\n");
                fflush(add_fd);
        }
 
-       /* Write the root entity */
-       fprintf(add_fd, "# root, %s, %s\n", user_attr, suffix);
-       fprintf(add_fd, "dn: uid=root,ou=%s,%s\n", user_attr, suffix);
-       fprintf(add_fd, "cn: root\n");
-       fprintf(add_fd, "sn: root\n");
-       fprintf(add_fd, "objectClass: inetOrgPerson\n");
-       fprintf(add_fd, "objectClass: sambaSAMAccount\n");
-       fprintf(add_fd, "objectClass: posixAccount\n");
-       fprintf(add_fd, "objectClass: shadowAccount\n");
-       fprintf(add_fd, "gidNumber: 0\n");
-       fprintf(add_fd, "uid: root\n");
-       fprintf(add_fd, "uidNumber: 0\n");
-       fprintf(add_fd, "homeDirectory: /home/root\n");
-       fprintf(add_fd, "sambaPwdLastSet: 0\n");
-       fprintf(add_fd, "sambaLogonTime: 0\n");
-       fprintf(add_fd, "sambaLogoffTime: 2147483647\n");
-       fprintf(add_fd, "sambaKickoffTime: 2147483647\n");
-       fprintf(add_fd, "sambaPwdCanChange: 0\n");
-       fprintf(add_fd, "sambaPwdMustChange: 2147483647\n");
-       fprintf(add_fd, "sambaHomePath: \\\\PDC-SRV\root\n");
-       fprintf(add_fd, "sambaHomeDrive: H:\n");
-       fprintf(add_fd, "sambaProfilePath: \\\\PDC-SRV\\profiles\\root\n");
-       fprintf(add_fd, "sambaprimaryGroupSID: %s-512\n", sid);
-       fprintf(add_fd, "sambaLMPassword: XXX\n");
-       fprintf(add_fd, "sambaNTPassword: XXX\n");
-       fprintf(add_fd, "sambaAcctFlags: [U\n");
-       fprintf(add_fd, "sambaSID: %s-500\n", sid);
-       fprintf(add_fd, "loginShell: /bin/false\n");
-       fprintf(add_fd, "\n");
-       fflush(add_fd);
-
        /* Write the domain entity */
        fprintf(add_fd, "# %s, %s\n", lp_workgroup(), suffix);
        fprintf(add_fd, "dn: sambaDomainName=%s,%s\n", lp_workgroup(),
@@ -1138,37 +1120,6 @@ static NTSTATUS populate_ldap_for_ldif(fstring sid, const char *suffix, const ch
        fprintf(add_fd, "\n");
        fflush(add_fd);
 
-       /* Write user nobody entity */
-       fprintf(add_fd, "# nobody, %s, %s\n", user_attr, suffix);
-       fprintf(add_fd, "dn: uid=nobody,ou=%s,%s\n", user_attr, suffix);
-       fprintf(add_fd, "cn: nobody\n");
-       fprintf(add_fd, "sn: nobody\n");
-       fprintf(add_fd, "objectClass: inetOrgPerson\n");
-       fprintf(add_fd, "objectClass: sambaSAMAccount\n");
-       fprintf(add_fd, "objectClass: posixAccount\n");
-       fprintf(add_fd, "objectClass: shadowAccount\n");
-       fprintf(add_fd, "gidNumber: 514\n");
-       fprintf(add_fd, "uid: nobody\n");
-       fprintf(add_fd, "uidNumber: 999\n");
-       fprintf(add_fd, "homeDirectory: /dev/null\n");
-       fprintf(add_fd, "sambaPwdLastSet: 0\n");
-       fprintf(add_fd, "sambaLogonTime: 0\n");
-       fprintf(add_fd, "sambaLogoffTime: 2147483647\n");
-       fprintf(add_fd, "sambaKickoffTime: 2147483647\n");
-       fprintf(add_fd, "sambaPwdCanChange: 0\n");
-       fprintf(add_fd, "sambaPwdMustChange: 2147483647\n");
-       fprintf(add_fd, "sambaHomePath: \\\\PDC-SMD3\\homes\\nobody\n");
-       fprintf(add_fd, "sambaHomeDrive: H:\n");
-       fprintf(add_fd, "sambaProfilePath: \\\\PDC-SMB3\\profiles\\nobody\n");
-       fprintf(add_fd, "sambaprimaryGroupSID: %s-514\n", sid);
-       fprintf(add_fd, "sambaLMPassword: NOPASSWORDXXXXXXXXXXXXXXXXXXXXX\n");
-       fprintf(add_fd, "sambaNTPassword: NOPASSWORDXXXXXXXXXXXXXXXXXXXXX\n");
-       fprintf(add_fd, "sambaAcctFlags: [NU\n");
-       fprintf(add_fd, "sambaSID: %s-2998\n", sid);
-       fprintf(add_fd, "loginShell: /bin/false\n");
-       fprintf(add_fd, "\n");
-       fflush(add_fd);
-
        /* Write the Domain Admins entity */ 
        fprintf(add_fd, "# Domain Admins, %s, %s\n", group_attr,
                suffix);
@@ -1297,7 +1248,9 @@ static NTSTATUS populate_ldap_for_ldif(fstring sid, const char *suffix, const ch
        fflush(add_fd);
 
        /* Deallocate memory, and return */
-       if (suffix_attr != NULL) SAFE_FREE(suffix_attr);
+       SAFE_FREE(suffix_attr);
+       SAFE_FREE(user_attr);
+       SAFE_FREE(group_attr);
        return NT_STATUS_OK;
 }
 
@@ -1370,9 +1323,72 @@ static NTSTATUS map_populate_groups(GROUPMAP *groupmap, ACCOUNTMAP *accountmap,
                     group_attr, suffix);
        accountmap[7].rid = 551;
        pstr_sprintf(accountmap[7].cn, "%s", "Replicators");
+       SAFE_FREE(group_attr);
        return NT_STATUS_OK;
 }
 
+/*
+ * This is a crap routine, but I think it's the quickest way to solve the
+ * UTF8->base64 problem.
+ */
+
+static int fprintf_attr(FILE *add_fd, const char *attr_name,
+                       const char *fmt, ...)
+{
+       va_list ap;
+       char *value, *p, *base64;
+       DATA_BLOB base64_blob;
+       BOOL do_base64 = False;
+       int res;
+
+       va_start(ap, fmt);
+       value = talloc_vasprintf(NULL, fmt, ap);
+       va_end(ap);
+
+       SMB_ASSERT(value != NULL);
+
+       for (p=value; *p; p++) {
+               if (*p & 0x80) {
+                       do_base64 = True;
+                       break;
+               }
+       }
+
+       if (!do_base64) {
+               BOOL only_whitespace = True;
+               for (p=value; *p; p++) {
+                       /*
+                        * I know that this not multibyte safe, but we break
+                        * on the first non-whitespace character anyway.
+                        */
+                       if (!isspace(*p)) {
+                               only_whitespace = False;
+                               break;
+                       }
+               }
+               if (only_whitespace) {
+                       do_base64 = True;
+               }
+       }
+
+       if (!do_base64) {
+               res = fprintf(add_fd, "%s: %s\n", attr_name, value);
+               TALLOC_FREE(value);
+               return res;
+       }
+
+       base64_blob.data = (unsigned char *)value;
+       base64_blob.length = strlen(value);
+
+       base64 = base64_encode_data_blob(base64_blob);
+       SMB_ASSERT(base64 != NULL);
+
+       res = fprintf(add_fd, "%s:: %s\n", attr_name, base64);
+       TALLOC_FREE(value);
+       SAFE_FREE(base64);
+       return res;
+}
+
 static NTSTATUS fetch_group_info_to_ldif(SAM_DELTA_CTR *delta, GROUPMAP *groupmap,
                         FILE *add_fd, fstring sid, char *suffix)
 {
@@ -1397,6 +1413,7 @@ static NTSTATUS fetch_group_info_to_ldif(SAM_DELTA_CTR *delta, GROUPMAP *groupma
            strcmp(groupname, "Print Operators") == 0 ||
            strcmp(groupname, "Backup Operators") == 0 ||
            strcmp(groupname, "Replicators") == 0) {
+               SAFE_FREE(group_attr);
                return NT_STATUS_OK;
        } else {
                /* Increment the gid for the new group */
@@ -1414,32 +1431,36 @@ static NTSTATUS fetch_group_info_to_ldif(SAM_DELTA_CTR *delta, GROUPMAP *groupma
        /* Write the data to the temporary add ldif file */
        fprintf(add_fd, "# %s, %s, %s\n", groupname, group_attr,
                suffix);
-       fprintf(add_fd, "dn: cn=%s,ou=%s,%s\n", groupname, group_attr,
-               suffix);
+       fprintf_attr(add_fd, "dn", "cn=%s,ou=%s,%s", groupname, group_attr,
+                    suffix);
        fprintf(add_fd, "objectClass: posixGroup\n");
        fprintf(add_fd, "objectClass: sambaGroupMapping\n");
-       fprintf(add_fd, "cn: %s\n", groupname);
+       fprintf_attr(add_fd, "cn", "%s", groupname);
        fprintf(add_fd, "gidNumber: %d\n", ldif_gid);
        fprintf(add_fd, "sambaSID: %s\n", groupmap->sambaSID);
        fprintf(add_fd, "sambaGroupType: %d\n", grouptype);
-       fprintf(add_fd, "displayName: %s\n", groupname);
+       fprintf_attr(add_fd, "displayName", "%s", groupname);
        fprintf(add_fd, "\n");
        fflush(add_fd);
 
+       SAFE_FREE(group_attr);
        /* Return */
        return NT_STATUS_OK;
 }
 
-static NTSTATUS fetch_account_info_to_ldif(SAM_DELTA_CTR *delta, GROUPMAP *groupmap,
-                          ACCOUNTMAP *accountmap, FILE *add_fd,
-                          fstring sid, char *suffix, int alloced)
+static NTSTATUS fetch_account_info_to_ldif(SAM_DELTA_CTR *delta,
+                                          GROUPMAP *groupmap,
+                                          ACCOUNTMAP *accountmap,
+                                          FILE *add_fd,
+                                          fstring sid, char *suffix,
+                                          int alloced)
 {
-       fstring username, homedir, logonscript, homedrive, homepath;
+       fstring username, logonscript, homedrive, homepath = "", homedir = "";
        fstring hex_nt_passwd, hex_lm_passwd;
-       fstring description, fullname, sambaSID;
+       fstring description, profilepath, fullname, sambaSID;
        uchar lm_passwd[16], nt_passwd[16];
-       char *flags;
-       const char *blank = "", *shell = "/bin/bash";
+       char *flags, *user_rdn;
+       const char *ou;
        const char* nopasswd = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        static uchar zero_buf[16];
        uint32 rid = 0, group_rid = 0, gidNumber = 0;
@@ -1459,33 +1480,44 @@ static NTSTATUS fetch_account_info_to_ldif(SAM_DELTA_CTR *delta, GROUPMAP *group
        pstr_sprintf(accountmap->cn, "%s", username);
 
        /* Get the home directory */
-       unistr2_to_ascii(homedir, &(delta->account_info.uni_home_dir),
-                        sizeof(homedir)-1);
-       if (strcmp(homedir, blank) == 0) {
-               pstr_sprintf(homedir, "/home/%s", username);
+       if (delta->account_info.acb_info & ACB_NORMAL) {
+               unistr2_to_ascii(homedir, &(delta->account_info.uni_home_dir),
+                                sizeof(homedir)-1);
+               if (!*homedir) {
+                       pstr_sprintf(homedir, "/home/%s", username);
+               } else {
+                       pstr_sprintf(homedir, "/nobodyshomedir");
+               }
+               ou = lp_ldap_user_suffix();
        } else {
-               strncpy(homepath, homedir, sizeof(homepath));
-       }       
+               ou = lp_ldap_machine_suffix();
+               pstr_sprintf(homedir, "/machinehomedir");
+       }
 
         /* Get the logon script */
         unistr2_to_ascii(logonscript, &(delta->account_info.uni_logon_script),
-                        sizeof(logonscript)-1);
+                        sizeof(logonscript)-1);
 
         /* Get the home drive */
         unistr2_to_ascii(homedrive, &(delta->account_info.uni_dir_drive),
-                        sizeof(homedrive)-1);
+                        sizeof(homedrive)-1);
+
+        /* Get the home path */
+        unistr2_to_ascii(homepath, &(delta->account_info.uni_home_dir),
+                        sizeof(homepath)-1);
 
        /* Get the description */
        unistr2_to_ascii(description, &(delta->account_info.uni_acct_desc),
                         sizeof(description)-1);
-       if (strcmp(description, blank) == 0) {
-               pstr_sprintf(description, "System User");
-       }
 
        /* Get the display name */
        unistr2_to_ascii(fullname, &(delta->account_info.uni_full_name),
                         sizeof(fullname)-1);
 
+       /* Get the profile path */
+       unistr2_to_ascii(profilepath, &(delta->account_info.uni_profile),
+                        sizeof(profilepath)-1);
+
        /* Get lm and nt password data */
        if (memcmp(delta->account_info.pass.buf_lm_pwd, zero_buf, 16) != 0) {
                sam_pwd_hash(delta->account_info.user_rid, 
@@ -1499,21 +1531,16 @@ static NTSTATUS fetch_account_info_to_ldif(SAM_DELTA_CTR *delta, GROUPMAP *group
        if (memcmp(delta->account_info.pass.buf_nt_pwd, zero_buf, 16) != 0) {
                sam_pwd_hash(delta->account_info.user_rid, 
                             delta->account_info.pass.buf_nt_pwd, 
-                                     nt_passwd, 0);
+                            nt_passwd, 0);
                pdb_sethexpwd(hex_nt_passwd, nt_passwd, 
                              delta->account_info.acb_info);
        } else {
                pdb_sethexpwd(hex_nt_passwd, NULL, 0);
        }
-       unix_time = nt_time_to_unix(&(delta->account_info.pwd_last_set_time));
+       unix_time = nt_time_to_unix(delta->account_info.pwd_last_set_time);
 
-       /* The nobody user is entered by populate_ldap_for_ldif */
-       if (strcmp(username, "nobody") == 0) {
-               return NT_STATUS_OK;
-       } else {
-               /* Increment the uid for the new user */
-               ldif_uid++;
-       }
+       /* Increment the uid for the new user */
+       ldif_uid++;
 
        /* Set up group id and sambaSID for the user */
        group_rid = delta->account_info.group_rid;
@@ -1533,34 +1560,41 @@ static NTSTATUS fetch_account_info_to_ldif(SAM_DELTA_CTR *delta, GROUPMAP *group
                                     NEW_PW_FORMAT_SPACE_PADDED_LEN);
 
        /* Add the user to the temporary add ldif file */
-       fprintf(add_fd, "# %s, %s, %s\n", username, 
-               sstring_sub(lp_ldap_user_suffix(), '=', ','), suffix);
-       fprintf(add_fd, "dn: uid=%s,ou=%s,%s\n", username, 
-               sstring_sub(lp_ldap_user_suffix(), '=', ','), suffix);
+       /* this isn't quite right...we can't assume there's just OU=. jmcd */
+       user_rdn = sstring_sub(ou, '=', ',');
+       fprintf(add_fd, "# %s, %s, %s\n", username, user_rdn, suffix);
+       fprintf_attr(add_fd, "dn", "uid=%s,ou=%s,%s", username, user_rdn,
+                    suffix);
+       SAFE_FREE(user_rdn);
        fprintf(add_fd, "ObjectClass: top\n");
        fprintf(add_fd, "objectClass: inetOrgPerson\n");
        fprintf(add_fd, "objectClass: posixAccount\n");
        fprintf(add_fd, "objectClass: shadowAccount\n");
        fprintf(add_fd, "objectClass: sambaSamAccount\n");
-       fprintf(add_fd, "cn: %s\n", username);
-       fprintf(add_fd, "sn: %s\n", username);
-       fprintf(add_fd, "uid: %s\n", username);
+       fprintf_attr(add_fd, "cn", "%s", username);
+       fprintf_attr(add_fd, "sn", "%s", username);
+       fprintf_attr(add_fd, "uid", "%s", username);
        fprintf(add_fd, "uidNumber: %d\n", ldif_uid);
        fprintf(add_fd, "gidNumber: %d\n", gidNumber);
-       fprintf(add_fd, "homeDirectory: %s\n", homedir);
-       if (strcmp(homepath, blank) != 0)
-               fprintf(add_fd, "SambaHomePath: %s\n", homepath);
-        if (strcmp(homedrive, blank) != 0)
-                fprintf(add_fd, "SambaHomeDrive: %s\n", homedrive);
-        if (strcmp(logonscript, blank) != 0)
-                fprintf(add_fd, "SambaLogonScript: %s\n", logonscript);
-       fprintf(add_fd, "loginShell: %s\n", shell);
+       fprintf_attr(add_fd, "homeDirectory", "%s", homedir);
+       if (*homepath)
+               fprintf_attr(add_fd, "sambaHomePath", "%s", homepath);
+        if (*homedrive)
+                fprintf_attr(add_fd, "sambaHomeDrive", "%s", homedrive);
+        if (*logonscript)
+                fprintf_attr(add_fd, "sambaLogonScript", "%s", logonscript);
+       fprintf(add_fd, "loginShell: %s\n", 
+               ((delta->account_info.acb_info & ACB_NORMAL) ?
+                "/bin/bash" : "/bin/false"));
        fprintf(add_fd, "gecos: System User\n");
-       fprintf(add_fd, "description: %s\n", description);
+       if (*description)
+               fprintf_attr(add_fd, "description", "%s", description);
        fprintf(add_fd, "sambaSID: %s-%d\n", sid, rid);
        fprintf(add_fd, "sambaPrimaryGroupSID: %s\n", sambaSID);
-       if(strcmp(fullname, blank) != 0)
-               fprintf(add_fd, "displayName: %s\n", fullname);
+       if(*fullname)
+               fprintf_attr(add_fd, "displayName", "%s", fullname);
+       if(*profilepath)
+               fprintf_attr(add_fd, "sambaProfilePath", "%s", profilepath);
        if (strcmp(nopasswd, hex_lm_passwd) != 0)
                fprintf(add_fd, "sambaLMPassword: %s\n", hex_lm_passwd);
        if (strcmp(nopasswd, hex_nt_passwd) != 0)
@@ -1574,9 +1608,11 @@ static NTSTATUS fetch_account_info_to_ldif(SAM_DELTA_CTR *delta, GROUPMAP *group
        return NT_STATUS_OK;
 }
 
-static NTSTATUS fetch_alias_info_to_ldif(SAM_DELTA_CTR *delta, GROUPMAP *groupmap,
-                        FILE *add_fd, fstring sid, char *suffix, 
-                        unsigned db_type)
+static NTSTATUS fetch_alias_info_to_ldif(SAM_DELTA_CTR *delta,
+                                        GROUPMAP *groupmap,
+                                        FILE *add_fd, fstring sid,
+                                        char *suffix, 
+                                        unsigned db_type)
 {
        fstring aliasname, description;
        uint32 grouptype = 0, g_rid = 0;
@@ -1592,21 +1628,21 @@ static NTSTATUS fetch_alias_info_to_ldif(SAM_DELTA_CTR *delta, GROUPMAP *groupma
 
        /* Set up the group type */
        switch (db_type) {
-               case SAM_DATABASE_DOMAIN:
-                       grouptype = 4;
-                       break;
-               case SAM_DATABASE_BUILTIN:
-                       grouptype = 5;
-                       break;
-               default:
-                       grouptype = 4;
-                       break;
+       case SAM_DATABASE_DOMAIN:
+               grouptype = 4;
+               break;
+       case SAM_DATABASE_BUILTIN:
+               grouptype = 5;
+               break;
+       default:
+               grouptype = 4;
+               break;
        }
 
        /*
-       These groups are entered by populate_ldap_for_ldif
-       Note that populate creates a group called Relicators, 
-       but NT returns a group called Replicator
+         These groups are entered by populate_ldap_for_ldif
+         Note that populate creates a group called Relicators, 
+         but NT returns a group called Replicator
        */
        if (strcmp(aliasname, "Domain Admins") == 0 ||
            strcmp(aliasname, "Domain Users") == 0 ||
@@ -1616,6 +1652,7 @@ static NTSTATUS fetch_alias_info_to_ldif(SAM_DELTA_CTR *delta, GROUPMAP *groupma
            strcmp(aliasname, "Print Operators") == 0 ||
            strcmp(aliasname, "Backup Operators") == 0 ||
            strcmp(aliasname, "Replicator") == 0) {
+               SAFE_FREE(group_attr);
                return NT_STATUS_OK;
        } else {
                /* Increment the gid for the new group */
@@ -1630,26 +1667,30 @@ static NTSTATUS fetch_alias_info_to_ldif(SAM_DELTA_CTR *delta, GROUPMAP *groupma
        /* Write the data to the temporary add ldif file */
        fprintf(add_fd, "# %s, %s, %s\n", aliasname, group_attr,
                suffix);
-       fprintf(add_fd, "dn: cn=%s,ou=%s,%s\n", aliasname, group_attr,
-               suffix);
+       fprintf_attr(add_fd, "dn", "cn=%s,ou=%s,%s", aliasname, group_attr,
+                    suffix);
        fprintf(add_fd, "objectClass: posixGroup\n");
        fprintf(add_fd, "objectClass: sambaGroupMapping\n");
        fprintf(add_fd, "cn: %s\n", aliasname);
        fprintf(add_fd, "gidNumber: %d\n", ldif_gid);
        fprintf(add_fd, "sambaSID: %s\n", groupmap->sambaSID);
        fprintf(add_fd, "sambaGroupType: %d\n", grouptype);
-       fprintf(add_fd, "displayName: %s\n", aliasname);
-       fprintf(add_fd, "description: %s\n", description);
+       fprintf_attr(add_fd, "displayName", "%s", aliasname);
+       if (description[0])
+               fprintf_attr(add_fd, "description", "%s", description);
        fprintf(add_fd, "\n");
        fflush(add_fd);
 
+       SAFE_FREE(group_attr);
        /* Return */
        return NT_STATUS_OK;
 }
 
-static NTSTATUS fetch_groupmem_info_to_ldif(SAM_DELTA_CTR *delta, SAM_DELTA_HDR *hdr_delta,
-                           GROUPMAP *groupmap, ACCOUNTMAP *accountmap, 
-                           FILE *mod_fd, int alloced)
+static NTSTATUS fetch_groupmem_info_to_ldif(SAM_DELTA_CTR *delta,
+                                           SAM_DELTA_HDR *hdr_delta,
+                                           GROUPMAP *groupmap,
+                                           ACCOUNTMAP *accountmap, 
+                                           FILE *mod_fd, int alloced)
 {
        fstring group_dn;
        uint32 group_rid = 0, rid = 0;
@@ -1676,7 +1717,8 @@ static NTSTATUS fetch_groupmem_info_to_ldif(SAM_DELTA_CTR *delta, SAM_DELTA_HDR
                                if (accountmap[k].rid == rid) break;
                        }
                        if (k == alloced){
-                               DEBUG(1, ("Could not find rid %d in accountmap array\n", rid));
+                               DEBUG(1, ("Could not find rid %d in "
+                                         "accountmap array\n", rid));
                                return NT_STATUS_UNSUCCESSFUL;
                        }
                        fprintf(mod_fd, "memberUid: %s\n", accountmap[k].cn);
@@ -1690,25 +1732,25 @@ static NTSTATUS fetch_groupmem_info_to_ldif(SAM_DELTA_CTR *delta, SAM_DELTA_HDR
 }
 
 static NTSTATUS fetch_database_to_ldif(struct rpc_pipe_client *pipe_hnd,
-                                       uint32 db_type,
-                                       DOM_SID dom_sid,
-                                       const char *user_file)
+                                      uint32 db_type,
+                                      DOM_SID dom_sid,
+                                      const char *user_file)
 {
        char *suffix;
        const char *builtin_sid = "S-1-5-32";
-       char *ldif_file;
+       char *add_name = NULL, *mod_name = NULL;
+       const char *add_template = "/tmp/add.ldif.XXXXXX";
+       const char *mod_template = "/tmp/mod.ldif.XXXXXX";
        fstring sid, domainname;
        uint32 sync_context = 0;
-       NTSTATUS result;
+       NTSTATUS ret = NT_STATUS_OK, result;
        int k;
        TALLOC_CTX *mem_ctx;
        SAM_DELTA_HDR *hdr_deltas;
        SAM_DELTA_CTR *deltas;
        uint32 num_deltas;
-       const char *add_ldif = "/tmp/add.ldif", *mod_ldif = "/tmp/mod.ldif";
-       FILE *add_fd, *mod_fd, *ldif_fd;
-       char sys_cmd[1024];
-       int num_alloced = 0, g_index = 0, a_index = 0, sys_cmd_result;
+       FILE *add_file = NULL, *mod_file = NULL, *ldif_file = NULL;
+       int num_alloced = 0, g_index = 0, a_index = 0;
 
        /* Set up array for mapping accounts to groups */
        /* Array element is the group rid */
@@ -1724,28 +1766,36 @@ static NTSTATUS fetch_database_to_ldif(struct rpc_pipe_client *pipe_hnd,
 
        /* Ensure we have an output file */
        if (user_file)
-               ldif_file = talloc_strdup(mem_ctx, user_file);
+               ldif_file = fopen(user_file, "a");
        else
-               ldif_file = talloc_strdup(mem_ctx, "/tmp/tmp.ldif");
-       
-       if (ldif_file == NULL)
-               return NT_STATUS_NO_MEMORY;
+               ldif_file = stdout;
 
-       /* Open the add and mod ldif files */
-       add_fd = fopen(add_ldif, "a");
-       mod_fd = fopen(mod_ldif, "a");
-       if (add_fd == NULL || mod_fd == NULL) {
-               DEBUG(1, ("Could not open %s\n", add_ldif));
-               return NT_STATUS_UNSUCCESSFUL;
-       } 
+       if (!ldif_file) {
+               fprintf(stderr, "Could not open %s\n", user_file);
+               DEBUG(1, ("Could not open %s\n", user_file));
+               ret = NT_STATUS_UNSUCCESSFUL;
+               goto done;
+       }
 
-       /* Open the user's ldif file */
-       ldif_fd = fopen(ldif_file, "a");
-       if (ldif_fd == NULL) {
-               DEBUG(1, ("Could not open %s\n", ldif_file));
-               return NT_STATUS_UNSUCCESSFUL;
+       add_name = talloc_strdup(mem_ctx, add_template);
+       mod_name = talloc_strdup(mem_ctx, mod_template);
+       if (!add_name || !mod_name) {
+               ret = NT_STATUS_NO_MEMORY;
+               goto done;
        }
 
+       /* Open the add and mod ldif files */
+       if (!(add_file = fdopen(smb_mkstemp(add_name),"w"))) {
+               DEBUG(1, ("Could not open %s\n", add_name));
+               ret = NT_STATUS_UNSUCCESSFUL;
+               goto done;
+       }
+       if (!(mod_file = fdopen(smb_mkstemp(mod_name),"w"))) {
+               DEBUG(1, ("Could not open %s\n", mod_name));
+               ret = NT_STATUS_UNSUCCESSFUL;
+               goto done;
+       } 
+
        /* Get the sid */
        sid_to_string(sid, &dom_sid);
 
@@ -1768,7 +1818,8 @@ static NTSTATUS fetch_database_to_ldif(struct rpc_pipe_client *pipe_hnd,
                accountmap = SMB_MALLOC_ARRAY(ACCOUNTMAP, 8);
                if (groupmap == NULL || accountmap == NULL) {
                        DEBUG(1,("GROUPMAP malloc failed\n"));
-                       return NT_STATUS_NO_MEMORY;
+                       ret = NT_STATUS_NO_MEMORY;
+                       goto done;
                }
 
                /* Initialize the arrays */
@@ -1779,9 +1830,9 @@ static NTSTATUS fetch_database_to_ldif(struct rpc_pipe_client *pipe_hnd,
                num_alloced = 8;
 
                /* Initial database population */
-               populate_ldap_for_ldif(sid, suffix, builtin_sid, add_fd);
+               populate_ldap_for_ldif(sid, suffix, builtin_sid, add_file);
                map_populate_groups(groupmap, accountmap, sid, suffix,
-                           builtin_sid);
+                                   builtin_sid);
 
                /* Don't do this again */
                init_ldap = 0;
@@ -1789,38 +1840,42 @@ static NTSTATUS fetch_database_to_ldif(struct rpc_pipe_client *pipe_hnd,
 
        /* Announce what we are doing */
        switch( db_type ) {
-               case SAM_DATABASE_DOMAIN:
-                       d_printf("Fetching DOMAIN database\n");
-                       break;
-               case SAM_DATABASE_BUILTIN:
-                       d_printf("Fetching BUILTIN database\n");
-                       break;
-               case SAM_DATABASE_PRIVS:
-                       d_printf("Fetching PRIVS databases\n");
-                       break;
-               default:
-                       d_printf("Fetching unknown database type %u\n", db_type );
-                       break;
+       case SAM_DATABASE_DOMAIN:
+               d_fprintf(stderr, "Fetching DOMAIN database\n");
+               break;
+       case SAM_DATABASE_BUILTIN:
+               d_fprintf(stderr, "Fetching BUILTIN database\n");
+               break;
+       case SAM_DATABASE_PRIVS:
+               d_fprintf(stderr, "Fetching PRIVS databases\n");
+               break;
+       default:
+               d_fprintf(stderr, 
+                         "Fetching unknown database type %u\n", 
+                         db_type );
+               break;
        }
 
        do {
                result = rpccli_netlogon_sam_sync(pipe_hnd, mem_ctx,
-                                              db_type, sync_context,
-                                              &num_deltas, &hdr_deltas, 
-                                              &deltas);
+                                                 db_type, sync_context,
+                                                 &num_deltas, &hdr_deltas, 
+                                                 &deltas);
                if (!NT_STATUS_IS_OK(result) &&
                    !NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES)) {
-                       return NT_STATUS_OK;
+                       ret = NT_STATUS_OK;
+                       goto done; /* is this correct? jmcd */
                }
 
                /* Re-allocate memory for groupmap and accountmap arrays */
                groupmap = SMB_REALLOC_ARRAY(groupmap, GROUPMAP,
-                                       num_deltas+num_alloced);
+                                            num_deltas+num_alloced);
                accountmap = SMB_REALLOC_ARRAY(accountmap, ACCOUNTMAP,
-                                       num_deltas+num_alloced);
+                                              num_deltas+num_alloced);
                if (groupmap == NULL || accountmap == NULL) {
                        DEBUG(1,("GROUPMAP malloc failed\n"));
-                       return NT_STATUS_NO_MEMORY;
+                       ret = NT_STATUS_NO_MEMORY;
+                       goto done;
                }
 
                /* Initialize the new records */
@@ -1835,72 +1890,73 @@ static NTSTATUS fetch_database_to_ldif(struct rpc_pipe_client *pipe_hnd,
                /* Loop through the deltas */
                for (k=0; k<num_deltas; k++) {
                        switch(hdr_deltas[k].type) {
-                               case SAM_DELTA_DOMAIN_INFO:
-                                       /* Is this case needed? */
-                                       unistr2_to_ascii(domainname, 
-                                       &deltas[k].domain_info.uni_dom_name,
-                                               sizeof(domainname)-1);
-                                       break;
-
-                               case SAM_DELTA_GROUP_INFO:
-                                       fetch_group_info_to_ldif(
-                                               &deltas[k], &groupmap[g_index],
-                                               add_fd, sid, suffix);
-                                       g_index++;
-                                       break;
-
-                               case SAM_DELTA_ACCOUNT_INFO:
-                                       fetch_account_info_to_ldif(
-                                               &deltas[k], groupmap, 
-                                               &accountmap[a_index], add_fd,
-                                               sid, suffix, num_alloced);
-                                       a_index++;
-                                       break;
-
-                               case SAM_DELTA_ALIAS_INFO:
-                                       fetch_alias_info_to_ldif(
-                                               &deltas[k], &groupmap[g_index],
-                                               add_fd, sid, suffix, db_type);
-                                       g_index++;
-                                       break;
-
-                               case SAM_DELTA_GROUP_MEM:
-                                       fetch_groupmem_info_to_ldif(
-                                               &deltas[k], &hdr_deltas[k], 
-                                               groupmap, accountmap, 
-                                               mod_fd, num_alloced);
-                                       break;
-
-                               case SAM_DELTA_ALIAS_MEM:
-                                       break;
-                               case SAM_DELTA_POLICY_INFO:
-                                       break;
-                               case SAM_DELTA_PRIVS_INFO:
-                                       break;
-                               case SAM_DELTA_TRUST_DOMS:
-                                       /* Implemented but broken */
-                                       break;
-                               case SAM_DELTA_SECRET_INFO:
-                                       /* Implemented but broken */
-                                       break;
-                               case SAM_DELTA_RENAME_GROUP:
-                                       /* Not yet implemented */
-                                       break;
-                               case SAM_DELTA_RENAME_USER:
-                                       /* Not yet implemented */
-                                       break;
-                               case SAM_DELTA_RENAME_ALIAS:
-                                       /* Not yet implemented */
-                                       break;
-                               case SAM_DELTA_DELETE_GROUP:
-                                       /* Not yet implemented */
-                                       break;
-                               case SAM_DELTA_DELETE_USER:
-                                       /* Not yet implemented */
-                                       break;
-                               case SAM_DELTA_MODIFIED_COUNT:
-                                       break;
-                               default:
+                       case SAM_DELTA_DOMAIN_INFO:
+                               /* Is this case needed? */
+                               unistr2_to_ascii(
+                                       domainname, 
+                                       &deltas[k].domain_info.uni_dom_name,
+                                       sizeof(domainname)-1);
+                               break;
+
+                       case SAM_DELTA_GROUP_INFO:
+                               fetch_group_info_to_ldif(
+                                       &deltas[k], &groupmap[g_index],
+                                       add_file, sid, suffix);
+                               g_index++;
+                               break;
+
+                       case SAM_DELTA_ACCOUNT_INFO:
+                               fetch_account_info_to_ldif(
+                                       &deltas[k], groupmap, 
+                                       &accountmap[a_index], add_file,
+                                       sid, suffix, num_alloced);
+                               a_index++;
+                               break;
+
+                       case SAM_DELTA_ALIAS_INFO:
+                               fetch_alias_info_to_ldif(
+                                       &deltas[k], &groupmap[g_index],
+                                       add_file, sid, suffix, db_type);
+                               g_index++;
+                               break;
+
+                       case SAM_DELTA_GROUP_MEM:
+                               fetch_groupmem_info_to_ldif(
+                                       &deltas[k], &hdr_deltas[k], 
+                                       groupmap, accountmap, 
+                                       mod_file, num_alloced);
+                               break;
+
+                       case SAM_DELTA_ALIAS_MEM:
+                               break;
+                       case SAM_DELTA_POLICY_INFO:
+                               break;
+                       case SAM_DELTA_PRIVS_INFO:
+                               break;
+                       case SAM_DELTA_TRUST_DOMS:
+                               /* Implemented but broken */
+                               break;
+                       case SAM_DELTA_SECRET_INFO:
+                               /* Implemented but broken */
+                               break;
+                       case SAM_DELTA_RENAME_GROUP:
+                               /* Not yet implemented */
+                               break;
+                       case SAM_DELTA_RENAME_USER:
+                               /* Not yet implemented */
+                               break;
+                       case SAM_DELTA_RENAME_ALIAS:
+                               /* Not yet implemented */
+                               break;
+                       case SAM_DELTA_DELETE_GROUP:
+                               /* Not yet implemented */
+                               break;
+                       case SAM_DELTA_DELETE_USER:
+                               /* Not yet implemented */
+                               break;
+                       case SAM_DELTA_MODIFIED_COUNT:
+                               break;
+                       default:
                                break;
                        } /* end of switch */
                } /* end of for loop */
@@ -1910,63 +1966,65 @@ static NTSTATUS fetch_database_to_ldif(struct rpc_pipe_client *pipe_hnd,
 
        } while (NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES));
 
-       /* Close the ldif files */
-       fclose(add_fd);
-       fclose(mod_fd);
-
        /* Write ldif data to the user's file */
        if (db_type == SAM_DATABASE_DOMAIN) {
-               fprintf(ldif_fd,
+               fprintf(ldif_file,
                        "# SAM_DATABASE_DOMAIN: ADD ENTITIES\n");
-               fprintf(ldif_fd,
+               fprintf(ldif_file,
                        "# =================================\n\n");
-               fflush(ldif_fd);
+               fflush(ldif_file);
        } else if (db_type == SAM_DATABASE_BUILTIN) {
-               fprintf(ldif_fd,
+               fprintf(ldif_file,
                        "# SAM_DATABASE_BUILTIN: ADD ENTITIES\n");
-               fprintf(ldif_fd,
+               fprintf(ldif_file,
                        "# ==================================\n\n");
-               fflush(ldif_fd);
-       }
-       pstr_sprintf(sys_cmd, "cat %s >> %s", add_ldif, ldif_file);
-       sys_cmd_result = system(sys_cmd);
-       if (sys_cmd_result) {
-               d_fprintf(stderr, "%s failed.  Error was (%s)\n",
-                       sys_cmd, strerror(errno));
-               return NT_STATUS_UNSUCCESSFUL;
+               fflush(ldif_file);
        }
+       fseek(add_file, 0, SEEK_SET);
+       transfer_file(fileno(add_file), fileno(ldif_file), (size_t) -1);
+
        if (db_type == SAM_DATABASE_DOMAIN) {
-               fprintf(ldif_fd,
+               fprintf(ldif_file,
                        "# SAM_DATABASE_DOMAIN: MODIFY ENTITIES\n");
-               fprintf(ldif_fd,
+               fprintf(ldif_file,
                        "# ====================================\n\n");
-               fflush(ldif_fd);
+               fflush(ldif_file);
        } else if (db_type == SAM_DATABASE_BUILTIN) {
-               fprintf(ldif_fd,
+               fprintf(ldif_file,
                        "# SAM_DATABASE_BUILTIN: MODIFY ENTITIES\n");
-               fprintf(ldif_fd,
+               fprintf(ldif_file,
                        "# =====================================\n\n");
-               fflush(ldif_fd);
+               fflush(ldif_file);
        }
-       pstr_sprintf(sys_cmd, "cat %s >> %s", mod_ldif, ldif_file);
-       sys_cmd_result = system(sys_cmd);
-       if (sys_cmd_result) {
-               d_fprintf(stderr, "%s failed.  Error was (%s)\n",
-                       sys_cmd, strerror(errno));
-               return NT_STATUS_UNSUCCESSFUL;
+       fseek(mod_file, 0, SEEK_SET);
+       transfer_file(fileno(mod_file), fileno(ldif_file), (size_t) -1);
+
+
+ done:
+       /* Close and delete the ldif files */
+       if (add_file) {
+               fclose(add_file);
        }
 
-       /* Delete the temporary ldif files */
-       pstr_sprintf(sys_cmd, "rm -f %s %s", add_ldif, mod_ldif);
-       sys_cmd_result = system(sys_cmd);
-       if (sys_cmd_result) {
-               d_fprintf(stderr, "%s failed.  Error was (%s)\n",
-                       sys_cmd, strerror(errno));
-               return NT_STATUS_UNSUCCESSFUL;
+       if ((add_name != NULL) &&
+           strcmp(add_name, add_template) && (unlink(add_name))) {
+               DEBUG(1,("unlink(%s) failed, error was (%s)\n",
+                        add_name, strerror(errno)));
        }
 
-       /* Close the ldif file */
-       fclose(ldif_fd);
+       if (mod_file) {
+               fclose(mod_file);
+       }
+
+       if ((mod_name != NULL) &&
+           strcmp(mod_name, mod_template) && (unlink(mod_name))) {
+               DEBUG(1,("unlink(%s) failed, error was (%s)\n",
+                        mod_name, strerror(errno)));
+       }
+       
+       if (ldif_file && (ldif_file != stdout)) {
+               fclose(ldif_file);
+       }
 
        /* Deallocate memory for the mapping arrays */
        SAFE_FREE(groupmap);
@@ -1974,7 +2032,7 @@ static NTSTATUS fetch_database_to_ldif(struct rpc_pipe_client *pipe_hnd,
 
        /* Return */
        talloc_destroy(mem_ctx);
-       return NT_STATUS_OK;
+       return ret;
 }
 
 /** 
@@ -1986,10 +2044,11 @@ static NTSTATUS fetch_database_to_ldif(struct rpc_pipe_client *pipe_hnd,
 
 int rpc_vampire_usage(int argc, const char **argv) 
 {      
-       d_printf("net rpc vampire [ldif [<ldif-filename>] [options]\n"\
-                "\t to pull accounts from a remote PDC where we are a BDC\n"\
-                "\t\t no args puts accounts in local passdb from smb.conf\n"\
-                "\t\t ldif - put accounts in ldif format (file defaults to /tmp/tmp.ldif\n");
+       d_printf("net rpc vampire [ldif [<ldif-filename>] [options]\n"
+                "\t to pull accounts from a remote PDC where we are a BDC\n"
+                "\t\t no args puts accounts in local passdb from smb.conf\n"
+                "\t\t ldif - put accounts in ldif format (file defaults to "
+                "/tmp/tmp.ldif\n");
 
        net_common_flags_usage(argc, argv);
        return -1;
@@ -2013,47 +2072,52 @@ NTSTATUS rpc_vampire_internals(const DOM_SID *domain_sid,
                d_printf("Cannot import users from %s at this time, "
                         "as the current domain:\n\t%s: %s\nconflicts "
                         "with the remote domain\n\t%s: %s\n"
-                        "Perhaps you need to set: \n\n\tsecurity=user\n\tworkgroup=%s\n\n in your smb.conf?\n",
+                        "Perhaps you need to set: \n\n\tsecurity=user\n\t"
+                        "workgroup=%s\n\n in your smb.conf?\n",
                         domain_name,
-                        get_global_sam_name(), sid_to_string(my_dom_sid_str, 
-                                                             get_global_sam_sid()),
-                        domain_name, sid_to_string(rem_dom_sid_str, domain_sid),
+                        get_global_sam_name(),
+                        sid_to_string(my_dom_sid_str, 
+                                      get_global_sam_sid()),
+                        domain_name, sid_to_string(rem_dom_sid_str,
+                                                   domain_sid),
                         domain_name);
                return NT_STATUS_UNSUCCESSFUL;
        }
 
         if (argc >= 1 && (strcmp(argv[0], "ldif") == 0)) {
                result = fetch_database_to_ldif(pipe_hnd, SAM_DATABASE_DOMAIN,
-                                       *domain_sid, argv[1]);
+                                               *domain_sid, argv[1]);
         } else {
-               result = fetch_database(pipe_hnd, SAM_DATABASE_DOMAIN, *domain_sid);
+               result = fetch_database(pipe_hnd, SAM_DATABASE_DOMAIN,
+                                       *domain_sid);
         }
 
        if (!NT_STATUS_IS_OK(result)) {
                d_fprintf(stderr, "Failed to fetch domain database: %s\n",
-                        nt_errstr(result));
+                         nt_errstr(result));
                if (NT_STATUS_EQUAL(result, NT_STATUS_NOT_SUPPORTED))
-                       d_fprintf(stderr, "Perhaps %s is a Windows 2000 native "
-                                "mode domain?\n", domain_name);
+                       d_fprintf(stderr, "Perhaps %s is a Windows 2000 "
+                                 "native mode domain?\n", domain_name);
                goto fail;
        }
 
         if (argc >= 1 && (strcmp(argv[0], "ldif") == 0)) {
-               result = fetch_database_to_ldif(pipe_hnd, SAM_DATABASE_BUILTIN, 
-                                       global_sid_Builtin, argv[1]);
+               result = fetch_database_to_ldif(pipe_hnd, SAM_DATABASE_BUILTIN,
+                                               global_sid_Builtin, argv[1]);
         } else {
-               result = fetch_database(pipe_hnd, SAM_DATABASE_BUILTIN, global_sid_Builtin);
+               result = fetch_database(pipe_hnd, SAM_DATABASE_BUILTIN,
+                                       global_sid_Builtin);
         }
 
        if (!NT_STATUS_IS_OK(result)) {
                d_fprintf(stderr, "Failed to fetch builtin database: %s\n",
-                        nt_errstr(result));
+                         nt_errstr(result));
                goto fail;
        }
 
        /* Currently we crash on PRIVS somewhere in unmarshalling */
        /* Dump_database(cli, SAM_DATABASE_PRIVS, &ret_creds); */
 
-fail:
+ fail:
        return result;
 }