util_str: Don't return memory from talloc_tos(), use mem_ctx instead.
[samba.git] / source3 / utils / net_rpc_samsync.c
1 /* 
2    Unix SMB/CIFS implementation.
3    dump the remote SAM using rpc samsync operations
4
5    Copyright (C) Andrew Tridgell 2002
6    Copyright (C) Tim Potter 2001,2002
7    Copyright (C) Jim McDonough <jmcd@us.ibm.com> 2005
8    Modified by Volker Lendecke 2002
9    Copyright (C) Jeremy Allison 2005.
10
11    This program is free software; you can redistribute it and/or modify
12    it under the terms of the GNU General Public License as published by
13    the Free Software Foundation; either version 3 of the License, or
14    (at your option) any later version.
15    
16    This program is distributed in the hope that it will be useful,
17    but WITHOUT ANY WARRANTY; without even the implied warranty of
18    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19    GNU General Public License for more details.
20    
21    You should have received a copy of the GNU General Public License
22    along with this program.  If not, see <http://www.gnu.org/licenses/>.
23 */
24
25 #include "includes.h"
26 #include "utils/net.h"
27
28 /* uid's and gid's for writing deltas to ldif */
29 static uint32 ldif_gid = 999;
30 static uint32 ldif_uid = 999;
31 /* Keep track of ldap initialization */
32 static int init_ldap = 1;
33
34 static void display_group_mem_info(uint32 rid, SAM_GROUP_MEM_INFO *g)
35 {
36         int i;
37         d_printf("Group mem %u: ", rid);
38         for (i=0;i<g->num_members;i++) {
39                 d_printf("%u ", g->rids[i]);
40         }
41         d_printf("\n");
42 }
43
44 static void display_alias_info(uint32 rid, SAM_ALIAS_INFO *a)
45 {
46         d_printf("Alias '%s' ", unistr2_static(&a->uni_als_name));
47         d_printf("desc='%s' rid=%u\n", unistr2_static(&a->uni_als_desc), a->als_rid);
48 }
49
50 static void display_alias_mem(uint32 rid, SAM_ALIAS_MEM_INFO *a)
51 {
52         int i;
53         d_printf("Alias rid %u: ", rid);
54         for (i=0;i<a->num_members;i++) {
55                 d_printf("%s ", sid_string_tos(&a->sids[i].sid));
56         }
57         d_printf("\n");
58 }
59
60 static void display_account_info(uint32 rid, SAM_ACCOUNT_INFO *a)
61 {
62         fstring hex_nt_passwd, hex_lm_passwd;
63         uchar lm_passwd[16], nt_passwd[16];
64         static uchar zero_buf[16];
65
66         /* Decode hashes from password hash (if they are not NULL) */
67         
68         if (memcmp(a->pass.buf_lm_pwd, zero_buf, 16) != 0) {
69                 sam_pwd_hash(a->user_rid, a->pass.buf_lm_pwd, lm_passwd, 0);
70                 pdb_sethexpwd(hex_lm_passwd, lm_passwd, a->acb_info);
71         } else {
72                 pdb_sethexpwd(hex_lm_passwd, NULL, 0);
73         }
74
75         if (memcmp(a->pass.buf_nt_pwd, zero_buf, 16) != 0) {
76                 sam_pwd_hash(a->user_rid, a->pass.buf_nt_pwd, nt_passwd, 0);
77                 pdb_sethexpwd(hex_nt_passwd, nt_passwd, a->acb_info);
78         } else {
79                 pdb_sethexpwd(hex_nt_passwd, NULL, 0);
80         }
81         
82         printf("%s:%d:%s:%s:%s:LCT-0\n", unistr2_static(&a->uni_acct_name),
83                a->user_rid, hex_lm_passwd, hex_nt_passwd,
84                pdb_encode_acct_ctrl(a->acb_info, NEW_PW_FORMAT_SPACE_PADDED_LEN));
85 }
86
87 static time_t uint64s_nt_time_to_unix_abs(const uint64 *src)
88 {
89         NTTIME nttime;
90         nttime = *src;
91         return nt_time_to_unix_abs(&nttime);
92 }
93
94 static void display_domain_info(SAM_DOMAIN_INFO *a)
95 {
96         time_t u_logout;
97
98         u_logout = uint64s_nt_time_to_unix_abs(&a->force_logoff);
99
100         d_printf("Domain name: %s\n", unistr2_static(&a->uni_dom_name));
101
102         d_printf("Minimal Password Length: %d\n", a->min_pwd_len);
103         d_printf("Password History Length: %d\n", a->pwd_history_len);
104
105         d_printf("Force Logoff: %d\n", (int)u_logout);
106
107         d_printf("Max Password Age: %s\n", display_time(a->max_pwd_age));
108         d_printf("Min Password Age: %s\n", display_time(a->min_pwd_age));
109
110         d_printf("Lockout Time: %s\n", display_time(a->account_lockout.lockout_duration));
111         d_printf("Lockout Reset Time: %s\n", display_time(a->account_lockout.reset_count));
112
113         d_printf("Bad Attempt Lockout: %d\n", a->account_lockout.bad_attempt_lockout);
114         d_printf("User must logon to change password: %d\n", a->logon_chgpass);
115 }
116
117 static void display_group_info(uint32 rid, SAM_GROUP_INFO *a)
118 {
119         d_printf("Group '%s' ", unistr2_static(&a->uni_grp_name));
120         d_printf("desc='%s', rid=%u\n", unistr2_static(&a->uni_grp_desc), rid);
121 }
122
123 static void display_sam_entry(SAM_DELTA_HDR *hdr_delta, SAM_DELTA_CTR *delta)
124 {
125         switch (hdr_delta->type) {
126         case SAM_DELTA_ACCOUNT_INFO:
127                 display_account_info(hdr_delta->target_rid, &delta->account_info);
128                 break;
129         case SAM_DELTA_GROUP_MEM:
130                 display_group_mem_info(hdr_delta->target_rid, &delta->grp_mem_info);
131                 break;
132         case SAM_DELTA_ALIAS_INFO:
133                 display_alias_info(hdr_delta->target_rid, &delta->alias_info);
134                 break;
135         case SAM_DELTA_ALIAS_MEM:
136                 display_alias_mem(hdr_delta->target_rid, &delta->als_mem_info);
137                 break;
138         case SAM_DELTA_DOMAIN_INFO:
139                 display_domain_info(&delta->domain_info);
140                 break;
141         case SAM_DELTA_GROUP_INFO:
142                 display_group_info(hdr_delta->target_rid, &delta->group_info);
143                 break;
144                 /* The following types are recognised but not handled */
145         case SAM_DELTA_RENAME_GROUP:
146                 d_printf("SAM_DELTA_RENAME_GROUP not handled\n");
147                 break;
148         case SAM_DELTA_RENAME_USER:
149                 d_printf("SAM_DELTA_RENAME_USER not handled\n");
150                 break;
151         case SAM_DELTA_RENAME_ALIAS:
152                 d_printf("SAM_DELTA_RENAME_ALIAS not handled\n");
153                 break;
154         case SAM_DELTA_POLICY_INFO:
155                 d_printf("SAM_DELTA_POLICY_INFO not handled\n");
156                 break;
157         case SAM_DELTA_TRUST_DOMS:
158                 d_printf("SAM_DELTA_TRUST_DOMS not handled\n");
159                 break;
160         case SAM_DELTA_PRIVS_INFO:
161                 d_printf("SAM_DELTA_PRIVS_INFO not handled\n");
162                 break;
163         case SAM_DELTA_SECRET_INFO:
164                 d_printf("SAM_DELTA_SECRET_INFO not handled\n");
165                 break;
166         case SAM_DELTA_DELETE_GROUP:
167                 d_printf("SAM_DELTA_DELETE_GROUP not handled\n");
168                 break;
169         case SAM_DELTA_DELETE_USER:
170                 d_printf("SAM_DELTA_DELETE_USER not handled\n");
171                 break;
172         case SAM_DELTA_MODIFIED_COUNT:
173                 d_printf("SAM_DELTA_MODIFIED_COUNT not handled\n");
174                 break;
175         default:
176                 d_printf("Unknown delta record type %d\n", hdr_delta->type);
177                 break;
178         }
179 }
180
181 static void dump_database(struct rpc_pipe_client *pipe_hnd, uint32 db_type)
182 {
183         uint32 sync_context = 0;
184         NTSTATUS result;
185         int i;
186         TALLOC_CTX *mem_ctx;
187         SAM_DELTA_HDR *hdr_deltas;
188         SAM_DELTA_CTR *deltas;
189         uint32 num_deltas;
190
191         if (!(mem_ctx = talloc_init("dump_database"))) {
192                 return;
193         }
194
195         switch( db_type ) {
196         case SAM_DATABASE_DOMAIN:
197                 d_printf("Dumping DOMAIN database\n");
198                 break;
199         case SAM_DATABASE_BUILTIN:
200                 d_printf("Dumping BUILTIN database\n");
201                 break;
202         case SAM_DATABASE_PRIVS:
203                 d_printf("Dumping PRIVS databases\n");
204                 break;
205         default:
206                 d_printf("Dumping unknown database type %u\n", db_type );
207                 break;
208         }
209
210         do {
211                 result = rpccli_netlogon_sam_sync(pipe_hnd, mem_ctx, db_type,
212                                                sync_context,
213                                                &num_deltas, &hdr_deltas, &deltas);
214                 if (!NT_STATUS_IS_OK(result))
215                         break;
216
217                 for (i = 0; i < num_deltas; i++) {
218                         display_sam_entry(&hdr_deltas[i], &deltas[i]);
219                 }
220                 sync_context += 1;
221         } while (NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES));
222
223         talloc_destroy(mem_ctx);
224 }
225
226 /* dump sam database via samsync rpc calls */
227 NTSTATUS rpc_samdump_internals(const DOM_SID *domain_sid, 
228                                 const char *domain_name, 
229                                 struct cli_state *cli,
230                                 struct rpc_pipe_client *pipe_hnd,
231                                 TALLOC_CTX *mem_ctx, 
232                                 int argc,
233                                 const char **argv) 
234 {
235 #if 0
236         /* net_rpc.c now always tries to create an schannel pipe.. */
237
238         NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL;
239         uchar trust_password[16];
240         uint32 neg_flags = NETLOGON_NEG_AUTH2_FLAGS;
241         uint32 sec_channel_type = 0;
242
243         if (!secrets_fetch_trust_account_password(domain_name,
244                                                   trust_password,
245                                                   NULL, &sec_channel_type)) {
246                 DEBUG(0,("Could not fetch trust account password\n"));
247                 goto fail;
248         }
249
250         nt_status = rpccli_netlogon_setup_creds(pipe_hnd,
251                                                 cli->desthost,
252                                                 domain_name,
253                                                 global_myname(),
254                                                 trust_password,
255                                                 sec_channel_type,
256                                                 &neg_flags);
257
258         if (!NT_STATUS_IS_OK(nt_status)) {
259                 DEBUG(0,("Error connecting to NETLOGON pipe\n"));
260                 goto fail;
261         }
262 #endif
263
264         dump_database(pipe_hnd, SAM_DATABASE_DOMAIN);
265         dump_database(pipe_hnd, SAM_DATABASE_BUILTIN);
266         dump_database(pipe_hnd, SAM_DATABASE_PRIVS);
267
268         return NT_STATUS_OK;
269 }
270
271 /* Convert a struct samu_DELTA to a struct samu. */
272 #define STRING_CHANGED (old_string && !new_string) ||\
273                     (!old_string && new_string) ||\
274                 (old_string && new_string && (strcmp(old_string, new_string) != 0))
275
276 #define STRING_CHANGED_NC(s1,s2) ((s1) && !(s2)) ||\
277                     (!(s1) && (s2)) ||\
278                 ((s1) && (s2) && (strcmp((s1), (s2)) != 0))
279
280 static NTSTATUS sam_account_from_delta(struct samu *account, SAM_ACCOUNT_INFO *delta)
281 {
282         const char *old_string, *new_string;
283         time_t unix_time, stored_time;
284         uchar lm_passwd[16], nt_passwd[16];
285         static uchar zero_buf[16];
286
287         /* Username, fullname, home dir, dir drive, logon script, acct
288            desc, workstations, profile. */
289
290         if (delta->hdr_acct_name.buffer) {
291                 old_string = pdb_get_nt_username(account);
292                 new_string = unistr2_static(&delta->uni_acct_name);
293
294                 if (STRING_CHANGED) {
295                         pdb_set_nt_username(account, new_string, PDB_CHANGED);
296               
297                 }
298          
299                 /* Unix username is the same - for sanity */
300                 old_string = pdb_get_username( account );
301                 if (STRING_CHANGED) {
302                         pdb_set_username(account, new_string, PDB_CHANGED);
303                 }
304         }
305
306         if (delta->hdr_full_name.buffer) {
307                 old_string = pdb_get_fullname(account);
308                 new_string = unistr2_static(&delta->uni_full_name);
309
310                 if (STRING_CHANGED)
311                         pdb_set_fullname(account, new_string, PDB_CHANGED);
312         }
313
314         if (delta->hdr_home_dir.buffer) {
315                 old_string = pdb_get_homedir(account);
316                 new_string = unistr2_static(&delta->uni_home_dir);
317
318                 if (STRING_CHANGED)
319                         pdb_set_homedir(account, new_string, PDB_CHANGED);
320         }
321
322         if (delta->hdr_dir_drive.buffer) {
323                 old_string = pdb_get_dir_drive(account);
324                 new_string = unistr2_static(&delta->uni_dir_drive);
325
326                 if (STRING_CHANGED)
327                         pdb_set_dir_drive(account, new_string, PDB_CHANGED);
328         }
329
330         if (delta->hdr_logon_script.buffer) {
331                 old_string = pdb_get_logon_script(account);
332                 new_string = unistr2_static(&delta->uni_logon_script);
333
334                 if (STRING_CHANGED)
335                         pdb_set_logon_script(account, new_string, PDB_CHANGED);
336         }
337
338         if (delta->hdr_acct_desc.buffer) {
339                 old_string = pdb_get_acct_desc(account);
340                 new_string = unistr2_static(&delta->uni_acct_desc);
341
342                 if (STRING_CHANGED)
343                         pdb_set_acct_desc(account, new_string, PDB_CHANGED);
344         }
345
346         if (delta->hdr_workstations.buffer) {
347                 old_string = pdb_get_workstations(account);
348                 new_string = unistr2_static(&delta->uni_workstations);
349
350                 if (STRING_CHANGED)
351                         pdb_set_workstations(account, new_string, PDB_CHANGED);
352         }
353
354         if (delta->hdr_profile.buffer) {
355                 old_string = pdb_get_profile_path(account);
356                 new_string = unistr2_static(&delta->uni_profile);
357
358                 if (STRING_CHANGED)
359                         pdb_set_profile_path(account, new_string, PDB_CHANGED);
360         }
361
362         if (delta->hdr_parameters.buffer) {
363                 DATA_BLOB mung;
364                 char *newstr;
365                 old_string = pdb_get_munged_dial(account);
366                 mung.length = delta->hdr_parameters.uni_str_len;
367                 mung.data = (uint8 *) delta->uni_parameters.buffer;
368                 newstr = (mung.length == 0) ? NULL :
369                         base64_encode_data_blob(talloc_tos(), mung);
370
371                 if (STRING_CHANGED_NC(old_string, newstr))
372                         pdb_set_munged_dial(account, newstr, PDB_CHANGED);
373                 TALLOC_FREE(newstr);
374         }
375
376         /* User and group sid */
377         if (pdb_get_user_rid(account) != delta->user_rid)
378                 pdb_set_user_sid_from_rid(account, delta->user_rid, PDB_CHANGED);
379         if (pdb_get_group_rid(account) != delta->group_rid)
380                 pdb_set_group_sid_from_rid(account, delta->group_rid, PDB_CHANGED);
381
382         /* Logon and password information */
383         if (!nt_time_is_zero(&delta->logon_time)) {
384                 unix_time = nt_time_to_unix(delta->logon_time);
385                 stored_time = pdb_get_logon_time(account);
386                 if (stored_time != unix_time)
387                         pdb_set_logon_time(account, unix_time, PDB_CHANGED);
388         }
389
390         if (!nt_time_is_zero(&delta->logoff_time)) {
391                 unix_time = nt_time_to_unix(delta->logoff_time);
392                 stored_time = pdb_get_logoff_time(account);
393                 if (stored_time != unix_time)
394                         pdb_set_logoff_time(account, unix_time,PDB_CHANGED);
395         }
396
397         /* Logon Divs */
398         if (pdb_get_logon_divs(account) != delta->logon_divs)
399                 pdb_set_logon_divs(account, delta->logon_divs, PDB_CHANGED);
400
401         /* Max Logon Hours */
402         if (delta->unknown1 != pdb_get_unknown_6(account)) {
403                 pdb_set_unknown_6(account, delta->unknown1, PDB_CHANGED);
404         }
405
406         /* Logon Hours Len */
407         if (delta->buf_logon_hrs.buf_len != pdb_get_hours_len(account)) {
408                 pdb_set_hours_len(account, delta->buf_logon_hrs.buf_len, PDB_CHANGED);
409         }
410
411         /* Logon Hours */
412         if (delta->buf_logon_hrs.buffer) {
413                 char oldstr[44], newstr[44];
414                 pdb_sethexhours(oldstr, pdb_get_hours(account));
415                 pdb_sethexhours(newstr, delta->buf_logon_hrs.buffer);
416                 if (!strequal(oldstr, newstr))
417                         pdb_set_hours(account, (const uint8 *)delta->buf_logon_hrs.buffer, PDB_CHANGED);
418         }
419
420         if (pdb_get_bad_password_count(account) != delta->bad_pwd_count)
421                 pdb_set_bad_password_count(account, delta->bad_pwd_count, PDB_CHANGED);
422
423         if (pdb_get_logon_count(account) != delta->logon_count)
424                 pdb_set_logon_count(account, delta->logon_count, PDB_CHANGED);
425
426         if (!nt_time_is_zero(&delta->pwd_last_set_time)) {
427                 unix_time = nt_time_to_unix(delta->pwd_last_set_time);
428                 stored_time = pdb_get_pass_last_set_time(account);
429                 if (stored_time != unix_time)
430                         pdb_set_pass_last_set_time(account, unix_time, PDB_CHANGED);
431         } else {
432                 /* no last set time, make it now */
433                 pdb_set_pass_last_set_time(account, time(NULL), PDB_CHANGED);
434         }
435
436 #if 0
437 /*      No kickoff time in the delta? */
438         if (!nt_time_is_zero(&delta->kickoff_time)) {
439                 unix_time = nt_time_to_unix(&delta->kickoff_time);
440                 stored_time = pdb_get_kickoff_time(account);
441                 if (stored_time != unix_time)
442                         pdb_set_kickoff_time(account, unix_time, PDB_CHANGED);
443         }
444 #endif
445
446         /* Decode hashes from password hash 
447            Note that win2000 may send us all zeros for the hashes if it doesn't 
448            think this channel is secure enough - don't set the passwords at all
449            in that case
450         */
451         if (memcmp(delta->pass.buf_lm_pwd, zero_buf, 16) != 0) {
452                 sam_pwd_hash(delta->user_rid, delta->pass.buf_lm_pwd, lm_passwd, 0);
453                 pdb_set_lanman_passwd(account, lm_passwd, PDB_CHANGED);
454         }
455
456         if (memcmp(delta->pass.buf_nt_pwd, zero_buf, 16) != 0) {
457                 sam_pwd_hash(delta->user_rid, delta->pass.buf_nt_pwd, nt_passwd, 0);
458                 pdb_set_nt_passwd(account, nt_passwd, PDB_CHANGED);
459         }
460
461         /* TODO: account expiry time */
462
463         pdb_set_acct_ctrl(account, delta->acb_info, PDB_CHANGED);
464
465         pdb_set_domain(account, lp_workgroup(), PDB_CHANGED);
466
467         return NT_STATUS_OK;
468 }
469
470 static NTSTATUS fetch_account_info(uint32 rid, SAM_ACCOUNT_INFO *delta)
471 {
472         NTSTATUS nt_ret = NT_STATUS_UNSUCCESSFUL;
473         fstring account;
474         char *add_script = NULL;
475         struct samu *sam_account=NULL;
476         GROUP_MAP map;
477         struct group *grp;
478         DOM_SID user_sid;
479         DOM_SID group_sid;
480         struct passwd *passwd;
481         fstring sid_string;
482
483         fstrcpy(account, unistr2_static(&delta->uni_acct_name));
484         d_printf("Creating account: %s\n", account);
485
486         if ( !(sam_account = samu_new( NULL )) ) {
487                 return NT_STATUS_NO_MEMORY;
488         }
489
490         if (!(passwd = Get_Pwnam_alloc(sam_account, account))) {
491                 /* Create appropriate user */
492                 if (delta->acb_info & ACB_NORMAL) {
493                         add_script = talloc_strdup(sam_account,
494                                         lp_adduser_script());
495                 } else if ( (delta->acb_info & ACB_WSTRUST) ||
496                             (delta->acb_info & ACB_SVRTRUST) ||
497                             (delta->acb_info & ACB_DOMTRUST) ) {
498                         add_script = talloc_strdup(sam_account,
499                                         lp_addmachine_script());
500                 } else {
501                         DEBUG(1, ("Unknown user type: %s\n",
502                                   pdb_encode_acct_ctrl(delta->acb_info, NEW_PW_FORMAT_SPACE_PADDED_LEN)));
503                         nt_ret = NT_STATUS_UNSUCCESSFUL;
504                         goto done;
505                 }
506                 if (!add_script) {
507                         nt_ret = NT_STATUS_NO_MEMORY;
508                         goto done;
509                 }
510                 if (*add_script) {
511                         int add_ret;
512                         add_script = talloc_all_string_sub(sam_account,
513                                         add_script,
514                                         "%u",
515                                         account);
516                         if (!add_script) {
517                                 nt_ret = NT_STATUS_NO_MEMORY;
518                                 goto done;
519                         }
520                         add_ret = smbrun(add_script,NULL);
521                         DEBUG(add_ret ? 0 : 1,("fetch_account: Running the command `%s' "
522                                  "gave %d\n", add_script, add_ret));
523                         if (add_ret == 0) {
524                                 smb_nscd_flush_user_cache();
525                         }
526                 }
527
528                 /* try and find the possible unix account again */
529                 if ( !(passwd = Get_Pwnam_alloc(sam_account, account)) ) {
530                         d_fprintf(stderr, "Could not create posix account info for '%s'\n", account);
531                         nt_ret = NT_STATUS_NO_SUCH_USER;
532                         goto done;
533                 }
534         }
535
536         sid_copy(&user_sid, get_global_sam_sid());
537         sid_append_rid(&user_sid, delta->user_rid);
538
539         DEBUG(3, ("Attempting to find SID %s for user %s in the passdb\n",
540                   sid_to_fstring(sid_string, &user_sid), account));
541         if (!pdb_getsampwsid(sam_account, &user_sid)) {
542                 sam_account_from_delta(sam_account, delta);
543                 DEBUG(3, ("Attempting to add user SID %s for user %s in the passdb\n", 
544                           sid_to_fstring(sid_string, &user_sid),
545                           pdb_get_username(sam_account)));
546                 if (!NT_STATUS_IS_OK(pdb_add_sam_account(sam_account))) {
547                         DEBUG(1, ("SAM Account for %s failed to be added to the passdb!\n",
548                                   account));
549                         return NT_STATUS_ACCESS_DENIED; 
550                 }
551         } else {
552                 sam_account_from_delta(sam_account, delta);
553                 DEBUG(3, ("Attempting to update user SID %s for user %s in the passdb\n", 
554                           sid_to_fstring(sid_string, &user_sid),
555                           pdb_get_username(sam_account)));
556                 if (!NT_STATUS_IS_OK(pdb_update_sam_account(sam_account))) {
557                         DEBUG(1, ("SAM Account for %s failed to be updated in the passdb!\n",
558                                   account));
559                         TALLOC_FREE(sam_account);
560                         return NT_STATUS_ACCESS_DENIED; 
561                 }
562         }
563
564         if (pdb_get_group_sid(sam_account) == NULL) {
565                 return NT_STATUS_UNSUCCESSFUL;
566         }
567
568         group_sid = *pdb_get_group_sid(sam_account);
569
570         if (!pdb_getgrsid(&map, group_sid)) {
571                 DEBUG(0, ("Primary group of %s has no mapping!\n",
572                           pdb_get_username(sam_account)));
573         } else {
574                 if (map.gid != passwd->pw_gid) {
575                         if (!(grp = getgrgid(map.gid))) {
576                                 DEBUG(0, ("Could not find unix group %lu for user %s (group SID=%s)\n", 
577                                           (unsigned long)map.gid, pdb_get_username(sam_account), sid_string_tos(&group_sid)));
578                         } else {
579                                 smb_set_primary_group(grp->gr_name, pdb_get_username(sam_account));
580                         }
581                 }
582         }
583
584         if ( !passwd ) {
585                 DEBUG(1, ("No unix user for this account (%s), cannot adjust mappings\n", 
586                         pdb_get_username(sam_account)));
587         }
588
589  done:
590         TALLOC_FREE(sam_account);
591         return nt_ret;
592 }
593
594 static NTSTATUS fetch_group_info(uint32 rid, SAM_GROUP_INFO *delta)
595 {
596         fstring name;
597         fstring comment;
598         struct group *grp = NULL;
599         DOM_SID group_sid;
600         fstring sid_string;
601         GROUP_MAP map;
602         bool insert = True;
603
604         unistr2_to_ascii(name, &delta->uni_grp_name, sizeof(name));
605         unistr2_to_ascii(comment, &delta->uni_grp_desc, sizeof(comment));
606
607         /* add the group to the mapping table */
608         sid_copy(&group_sid, get_global_sam_sid());
609         sid_append_rid(&group_sid, rid);
610         sid_to_fstring(sid_string, &group_sid);
611
612         if (pdb_getgrsid(&map, group_sid)) {
613                 if ( map.gid != -1 )
614                         grp = getgrgid(map.gid);
615                 insert = False;
616         }
617
618         if (grp == NULL) {
619                 gid_t gid;
620
621                 /* No group found from mapping, find it from its name. */
622                 if ((grp = getgrnam(name)) == NULL) {
623                 
624                         /* No appropriate group found, create one */
625                         
626                         d_printf("Creating unix group: '%s'\n", name);
627                         
628                         if (smb_create_group(name, &gid) != 0)
629                                 return NT_STATUS_ACCESS_DENIED;
630                                 
631                         if ((grp = getgrnam(name)) == NULL)
632                                 return NT_STATUS_ACCESS_DENIED;
633                 }
634         }
635
636         map.gid = grp->gr_gid;
637         map.sid = group_sid;
638         map.sid_name_use = SID_NAME_DOM_GRP;
639         fstrcpy(map.nt_name, name);
640         if (delta->hdr_grp_desc.buffer) {
641                 fstrcpy(map.comment, comment);
642         } else {
643                 fstrcpy(map.comment, "");
644         }
645
646         if (insert)
647                 pdb_add_group_mapping_entry(&map);
648         else
649                 pdb_update_group_mapping_entry(&map);
650
651         return NT_STATUS_OK;
652 }
653
654 static NTSTATUS fetch_group_mem_info(uint32 rid, SAM_GROUP_MEM_INFO *delta)
655 {
656         int i;
657         TALLOC_CTX *t = NULL;
658         char **nt_members = NULL;
659         char **unix_members;
660         DOM_SID group_sid;
661         GROUP_MAP map;
662         struct group *grp;
663
664         if (delta->num_members == 0) {
665                 return NT_STATUS_OK;
666         }
667
668         sid_copy(&group_sid, get_global_sam_sid());
669         sid_append_rid(&group_sid, rid);
670
671         if (!get_domain_group_from_sid(group_sid, &map)) {
672                 DEBUG(0, ("Could not find global group %d\n", rid));
673                 return NT_STATUS_NO_SUCH_GROUP;
674         }
675
676         if (!(grp = getgrgid(map.gid))) {
677                 DEBUG(0, ("Could not find unix group %lu\n", (unsigned long)map.gid));
678                 return NT_STATUS_NO_SUCH_GROUP;
679         }
680
681         d_printf("Group members of %s: ", grp->gr_name);
682
683         if (!(t = talloc_init("fetch_group_mem_info"))) {
684                 DEBUG(0, ("could not talloc_init\n"));
685                 return NT_STATUS_NO_MEMORY;
686         }
687
688         if (delta->num_members) {
689                 if ((nt_members = TALLOC_ZERO_ARRAY(t, char *, delta->num_members)) == NULL) {
690                         DEBUG(0, ("talloc failed\n"));
691                         talloc_free(t);
692                         return NT_STATUS_NO_MEMORY;
693                 }
694         } else {
695                 nt_members = NULL;
696         }
697
698         for (i=0; i<delta->num_members; i++) {
699                 struct samu *member = NULL;
700                 DOM_SID member_sid;
701
702                 if ( !(member = samu_new(t)) ) {
703                         talloc_destroy(t);
704                         return NT_STATUS_NO_MEMORY;
705                 }
706
707                 sid_copy(&member_sid, get_global_sam_sid());
708                 sid_append_rid(&member_sid, delta->rids[i]);
709
710                 if (!pdb_getsampwsid(member, &member_sid)) {
711                         DEBUG(1, ("Found bogus group member: %d (member_sid=%s group=%s)\n",
712                                   delta->rids[i], sid_string_tos(&member_sid), grp->gr_name));
713                         TALLOC_FREE(member);
714                         continue;
715                 }
716
717                 if (pdb_get_group_rid(member) == rid) {
718                         d_printf("%s(primary),", pdb_get_username(member));
719                         TALLOC_FREE(member);
720                         continue;
721                 }
722                 
723                 d_printf("%s,", pdb_get_username(member));
724                 nt_members[i] = talloc_strdup(t, pdb_get_username(member));
725                 TALLOC_FREE(member);
726         }
727
728         d_printf("\n");
729
730         unix_members = grp->gr_mem;
731
732         while (*unix_members) {
733                 bool is_nt_member = False;
734                 for (i=0; i<delta->num_members; i++) {
735                         if (nt_members[i] == NULL) {
736                                 /* This was a primary group */
737                                 continue;
738                         }
739
740                         if (strcmp(*unix_members, nt_members[i]) == 0) {
741                                 is_nt_member = True;
742                                 break;
743                         }
744                 }
745                 if (!is_nt_member) {
746                         /* We look at a unix group member that is not
747                            an nt group member. So, remove it. NT is
748                            boss here. */
749                         smb_delete_user_group(grp->gr_name, *unix_members);
750                 }
751                 unix_members += 1;
752         }
753
754         for (i=0; i<delta->num_members; i++) {
755                 bool is_unix_member = False;
756
757                 if (nt_members[i] == NULL) {
758                         /* This was the primary group */
759                         continue;
760                 }
761
762                 unix_members = grp->gr_mem;
763
764                 while (*unix_members) {
765                         if (strcmp(*unix_members, nt_members[i]) == 0) {
766                                 is_unix_member = True;
767                                 break;
768                         }
769                         unix_members += 1;
770                 }
771
772                 if (!is_unix_member) {
773                         /* We look at a nt group member that is not a
774                            unix group member currently. So, add the nt
775                            group member. */
776                         smb_add_user_group(grp->gr_name, nt_members[i]);
777                 }
778         }
779         
780         talloc_destroy(t);
781         return NT_STATUS_OK;
782 }
783
784 static NTSTATUS fetch_alias_info(uint32 rid, SAM_ALIAS_INFO *delta,
785                                  DOM_SID dom_sid)
786 {
787         fstring name;
788         fstring comment;
789         struct group *grp = NULL;
790         DOM_SID alias_sid;
791         fstring sid_string;
792         GROUP_MAP map;
793         bool insert = True;
794
795         unistr2_to_ascii(name, &delta->uni_als_name, sizeof(name));
796         unistr2_to_ascii(comment, &delta->uni_als_desc, sizeof(comment));
797
798         /* Find out whether the group is already mapped */
799         sid_copy(&alias_sid, &dom_sid);
800         sid_append_rid(&alias_sid, rid);
801         sid_to_fstring(sid_string, &alias_sid);
802
803         if (pdb_getgrsid(&map, alias_sid)) {
804                 grp = getgrgid(map.gid);
805                 insert = False;
806         }
807
808         if (grp == NULL) {
809                 gid_t gid;
810
811                 /* No group found from mapping, find it from its name. */
812                 if ((grp = getgrnam(name)) == NULL) {
813                         /* No appropriate group found, create one */
814                         d_printf("Creating unix group: '%s'\n", name);
815                         if (smb_create_group(name, &gid) != 0)
816                                 return NT_STATUS_ACCESS_DENIED;
817                         if ((grp = getgrgid(gid)) == NULL)
818                                 return NT_STATUS_ACCESS_DENIED;
819                 }
820         }
821
822         map.gid = grp->gr_gid;
823         map.sid = alias_sid;
824
825         if (sid_equal(&dom_sid, &global_sid_Builtin))
826                 map.sid_name_use = SID_NAME_WKN_GRP;
827         else
828                 map.sid_name_use = SID_NAME_ALIAS;
829
830         fstrcpy(map.nt_name, name);
831         fstrcpy(map.comment, comment);
832
833         if (insert)
834                 pdb_add_group_mapping_entry(&map);
835         else
836                 pdb_update_group_mapping_entry(&map);
837
838         return NT_STATUS_OK;
839 }
840
841 static NTSTATUS fetch_alias_mem(uint32 rid, SAM_ALIAS_MEM_INFO *delta, DOM_SID dom_sid)
842 {
843         return NT_STATUS_OK;
844 }
845
846 static NTSTATUS fetch_domain_info(uint32 rid, SAM_DOMAIN_INFO *delta)
847 {
848         time_t u_max_age, u_min_age, u_logout, u_lockoutreset, u_lockouttime;
849         NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL;
850         char *domname;
851
852         u_max_age = uint64s_nt_time_to_unix_abs(&delta->max_pwd_age);
853         u_min_age = uint64s_nt_time_to_unix_abs(&delta->min_pwd_age);
854         u_logout = uint64s_nt_time_to_unix_abs(&delta->force_logoff);
855         u_lockoutreset = uint64s_nt_time_to_unix_abs(&delta->account_lockout.reset_count);
856         u_lockouttime = uint64s_nt_time_to_unix_abs(&delta->account_lockout.lockout_duration);
857
858         domname = unistr2_to_ascii_talloc(talloc_tos(), &delta->uni_dom_name);
859         if (!domname) {
860                 return NT_STATUS_NO_MEMORY;
861         }
862
863         /* we don't handle BUILTIN account policies */
864         if (!strequal(domname, get_global_sam_name())) {
865                 printf("skipping SAM_DOMAIN_INFO delta for '%s' (is not my domain)\n", domname);
866                 return NT_STATUS_OK;
867         }
868
869
870         if (!pdb_set_account_policy(AP_PASSWORD_HISTORY, delta->pwd_history_len))
871                 return nt_status;
872
873         if (!pdb_set_account_policy(AP_MIN_PASSWORD_LEN, delta->min_pwd_len))
874                 return nt_status;
875
876         if (!pdb_set_account_policy(AP_MAX_PASSWORD_AGE, (uint32)u_max_age))
877                 return nt_status;
878
879         if (!pdb_set_account_policy(AP_MIN_PASSWORD_AGE, (uint32)u_min_age))
880                 return nt_status;
881
882         if (!pdb_set_account_policy(AP_TIME_TO_LOGOUT, (uint32)u_logout))
883                 return nt_status;
884
885         if (!pdb_set_account_policy(AP_BAD_ATTEMPT_LOCKOUT, delta->account_lockout.bad_attempt_lockout))
886                 return nt_status;
887
888         if (!pdb_set_account_policy(AP_RESET_COUNT_TIME, (uint32)u_lockoutreset/60))
889                 return nt_status;
890
891         if (u_lockouttime != -1)
892                 u_lockouttime /= 60;
893
894         if (!pdb_set_account_policy(AP_LOCK_ACCOUNT_DURATION, (uint32)u_lockouttime))
895                 return nt_status;
896
897         if (!pdb_set_account_policy(AP_USER_MUST_LOGON_TO_CHG_PASS, delta->logon_chgpass))
898                 return nt_status;
899
900         return NT_STATUS_OK;
901 }
902
903
904 static void fetch_sam_entry(SAM_DELTA_HDR *hdr_delta, SAM_DELTA_CTR *delta,
905                 DOM_SID dom_sid)
906 {
907         switch(hdr_delta->type) {
908         case SAM_DELTA_ACCOUNT_INFO:
909                 fetch_account_info(hdr_delta->target_rid,
910                                    &delta->account_info);
911                 break;
912         case SAM_DELTA_GROUP_INFO:
913                 fetch_group_info(hdr_delta->target_rid,
914                                  &delta->group_info);
915                 break;
916         case SAM_DELTA_GROUP_MEM:
917                 fetch_group_mem_info(hdr_delta->target_rid,
918                                      &delta->grp_mem_info);
919                 break;
920         case SAM_DELTA_ALIAS_INFO:
921                 fetch_alias_info(hdr_delta->target_rid,
922                                  &delta->alias_info, dom_sid);
923                 break;
924         case SAM_DELTA_ALIAS_MEM:
925                 fetch_alias_mem(hdr_delta->target_rid,
926                                 &delta->als_mem_info, dom_sid);
927                 break;
928         case SAM_DELTA_DOMAIN_INFO:
929                 fetch_domain_info(hdr_delta->target_rid,
930                                 &delta->domain_info);
931                 break;
932         /* The following types are recognised but not handled */
933         case SAM_DELTA_RENAME_GROUP:
934                 d_printf("SAM_DELTA_RENAME_GROUP not handled\n");
935                 break;
936         case SAM_DELTA_RENAME_USER:
937                 d_printf("SAM_DELTA_RENAME_USER not handled\n");
938                 break;
939         case SAM_DELTA_RENAME_ALIAS:
940                 d_printf("SAM_DELTA_RENAME_ALIAS not handled\n");
941                 break;
942         case SAM_DELTA_POLICY_INFO:
943                 d_printf("SAM_DELTA_POLICY_INFO not handled\n");
944                 break;
945         case SAM_DELTA_TRUST_DOMS:
946                 d_printf("SAM_DELTA_TRUST_DOMS not handled\n");
947                 break;
948         case SAM_DELTA_PRIVS_INFO:
949                 d_printf("SAM_DELTA_PRIVS_INFO not handled\n");
950                 break;
951         case SAM_DELTA_SECRET_INFO:
952                 d_printf("SAM_DELTA_SECRET_INFO not handled\n");
953                 break;
954         case SAM_DELTA_DELETE_GROUP:
955                 d_printf("SAM_DELTA_DELETE_GROUP not handled\n");
956                 break;
957         case SAM_DELTA_DELETE_USER:
958                 d_printf("SAM_DELTA_DELETE_USER not handled\n");
959                 break;
960         case SAM_DELTA_MODIFIED_COUNT:
961                 d_printf("SAM_DELTA_MODIFIED_COUNT not handled\n");
962                 break;
963         default:
964                 d_printf("Unknown delta record type %d\n", hdr_delta->type);
965                 break;
966         }
967 }
968
969 static NTSTATUS fetch_database(struct rpc_pipe_client *pipe_hnd, uint32 db_type, DOM_SID dom_sid)
970 {
971         uint32 sync_context = 0;
972         NTSTATUS result;
973         int i;
974         TALLOC_CTX *mem_ctx;
975         SAM_DELTA_HDR *hdr_deltas;
976         SAM_DELTA_CTR *deltas;
977         uint32 num_deltas;
978
979         if (!(mem_ctx = talloc_init("fetch_database")))
980                 return NT_STATUS_NO_MEMORY;
981
982         switch( db_type ) {
983         case SAM_DATABASE_DOMAIN:
984                 d_printf("Fetching DOMAIN database\n");
985                 break;
986         case SAM_DATABASE_BUILTIN:
987                 d_printf("Fetching BUILTIN database\n");
988                 break;
989         case SAM_DATABASE_PRIVS:
990                 d_printf("Fetching PRIVS databases\n");
991                 break;
992         default:
993                 d_printf("Fetching unknown database type %u\n", db_type );
994                 break;
995         }
996
997         do {
998                 result = rpccli_netlogon_sam_sync(pipe_hnd, mem_ctx,
999                                                db_type, sync_context,
1000                                                &num_deltas,
1001                                                &hdr_deltas, &deltas);
1002
1003                 if (NT_STATUS_IS_OK(result) ||
1004                     NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES)) {
1005                         for (i = 0; i < num_deltas; i++) {
1006                                 fetch_sam_entry(&hdr_deltas[i], &deltas[i], dom_sid);
1007                         }
1008                 } else
1009                         return result;
1010
1011                 sync_context += 1;
1012         } while (NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES));
1013
1014         talloc_destroy(mem_ctx);
1015
1016         return result;
1017 }
1018
1019 static NTSTATUS populate_ldap_for_ldif(fstring sid, const char *suffix, const char 
1020                        *builtin_sid, FILE *add_fd)
1021 {
1022         const char *user_suffix, *group_suffix, *machine_suffix, *idmap_suffix;
1023         char *user_attr=NULL, *group_attr=NULL;
1024         char *suffix_attr;
1025         int len;
1026
1027         /* Get the suffix attribute */
1028         suffix_attr = sstring_sub(suffix, '=', ',');
1029         if (suffix_attr == NULL) {
1030                 len = strlen(suffix);
1031                 suffix_attr = (char*)SMB_MALLOC(len+1);
1032                 memcpy(suffix_attr, suffix, len);
1033                 suffix_attr[len] = '\0';
1034         }
1035
1036         /* Write the base */
1037         fprintf(add_fd, "# %s\n", suffix);
1038         fprintf(add_fd, "dn: %s\n", suffix);
1039         fprintf(add_fd, "objectClass: dcObject\n");
1040         fprintf(add_fd, "objectClass: organization\n");
1041         fprintf(add_fd, "o: %s\n", suffix_attr);
1042         fprintf(add_fd, "dc: %s\n", suffix_attr);
1043         fprintf(add_fd, "\n");
1044         fflush(add_fd);
1045
1046         user_suffix = lp_ldap_user_suffix();
1047         if (user_suffix == NULL) {
1048                 SAFE_FREE(suffix_attr);
1049                 return NT_STATUS_NO_MEMORY;
1050         }
1051         /* If it exists and is distinct from other containers, 
1052            Write the Users entity */
1053         if (*user_suffix && strcmp(user_suffix, suffix)) {
1054                 user_attr = sstring_sub(lp_ldap_user_suffix(), '=', ',');
1055                 fprintf(add_fd, "# %s\n", user_suffix);
1056                 fprintf(add_fd, "dn: %s\n", user_suffix);
1057                 fprintf(add_fd, "objectClass: organizationalUnit\n");
1058                 fprintf(add_fd, "ou: %s\n", user_attr);
1059                 fprintf(add_fd, "\n");
1060                 fflush(add_fd);
1061         }
1062
1063
1064         group_suffix = lp_ldap_group_suffix();
1065         if (group_suffix == NULL) {
1066                 SAFE_FREE(suffix_attr);
1067                 SAFE_FREE(user_attr);
1068                 return NT_STATUS_NO_MEMORY;
1069         }
1070         /* If it exists and is distinct from other containers, 
1071            Write the Groups entity */
1072         if (*group_suffix && strcmp(group_suffix, suffix)) {
1073                 group_attr = sstring_sub(lp_ldap_group_suffix(), '=', ',');
1074                 fprintf(add_fd, "# %s\n", group_suffix);
1075                 fprintf(add_fd, "dn: %s\n", group_suffix);
1076                 fprintf(add_fd, "objectClass: organizationalUnit\n");
1077                 fprintf(add_fd, "ou: %s\n", group_attr);
1078                 fprintf(add_fd, "\n");
1079                 fflush(add_fd);
1080         }
1081
1082         /* If it exists and is distinct from other containers, 
1083            Write the Computers entity */
1084         machine_suffix = lp_ldap_machine_suffix();
1085         if (machine_suffix == NULL) {
1086                 SAFE_FREE(suffix_attr);
1087                 SAFE_FREE(user_attr);
1088                 SAFE_FREE(group_attr);
1089                 return NT_STATUS_NO_MEMORY;
1090         }
1091         if (*machine_suffix && strcmp(machine_suffix, user_suffix) &&
1092             strcmp(machine_suffix, suffix)) {
1093                 char *machine_ou = NULL;
1094                 fprintf(add_fd, "# %s\n", machine_suffix);
1095                 fprintf(add_fd, "dn: %s\n", machine_suffix);
1096                 fprintf(add_fd, "objectClass: organizationalUnit\n");
1097                 /* this isn't totally correct as it assumes that
1098                    there _must_ be an ou. just fixing memleak now. jmcd */
1099                 machine_ou = sstring_sub(lp_ldap_machine_suffix(), '=', ',');
1100                 fprintf(add_fd, "ou: %s\n", machine_ou);
1101                 SAFE_FREE(machine_ou);
1102                 fprintf(add_fd, "\n");
1103                 fflush(add_fd);
1104         }
1105
1106         /* If it exists and is distinct from other containers, 
1107            Write the IdMap entity */
1108         idmap_suffix = lp_ldap_idmap_suffix();
1109         if (idmap_suffix == NULL) {
1110                 SAFE_FREE(suffix_attr);
1111                 SAFE_FREE(user_attr);
1112                 SAFE_FREE(group_attr);
1113                 return NT_STATUS_NO_MEMORY;
1114         }
1115         if (*idmap_suffix &&
1116             strcmp(idmap_suffix, user_suffix) &&
1117             strcmp(idmap_suffix, suffix)) {
1118                 char *s;
1119                 fprintf(add_fd, "# %s\n", idmap_suffix);
1120                 fprintf(add_fd, "dn: %s\n", idmap_suffix);
1121                 fprintf(add_fd, "ObjectClass: organizationalUnit\n");
1122                 s = sstring_sub(lp_ldap_idmap_suffix(), '=', ',');
1123                 fprintf(add_fd, "ou: %s\n", s);
1124                 SAFE_FREE(s);
1125                 fprintf(add_fd, "\n");
1126                 fflush(add_fd);
1127         }
1128
1129         /* Write the domain entity */
1130         fprintf(add_fd, "# %s, %s\n", lp_workgroup(), suffix);
1131         fprintf(add_fd, "dn: sambaDomainName=%s,%s\n", lp_workgroup(),
1132                 suffix);
1133         fprintf(add_fd, "objectClass: sambaDomain\n");
1134         fprintf(add_fd, "objectClass: sambaUnixIdPool\n");
1135         fprintf(add_fd, "sambaDomainName: %s\n", lp_workgroup());
1136         fprintf(add_fd, "sambaSID: %s\n", sid);
1137         fprintf(add_fd, "uidNumber: %d\n", ++ldif_uid);
1138         fprintf(add_fd, "gidNumber: %d\n", ++ldif_gid);
1139         fprintf(add_fd, "\n");
1140         fflush(add_fd);
1141
1142         /* Write the Domain Admins entity */ 
1143         fprintf(add_fd, "# Domain Admins, %s, %s\n", group_attr,
1144                 suffix);
1145         fprintf(add_fd, "dn: cn=Domain Admins,ou=%s,%s\n", group_attr,
1146                 suffix);
1147         fprintf(add_fd, "objectClass: posixGroup\n");
1148         fprintf(add_fd, "objectClass: sambaGroupMapping\n");
1149         fprintf(add_fd, "cn: Domain Admins\n");
1150         fprintf(add_fd, "memberUid: Administrator\n");
1151         fprintf(add_fd, "description: Netbios Domain Administrators\n");
1152         fprintf(add_fd, "gidNumber: 512\n");
1153         fprintf(add_fd, "sambaSID: %s-512\n", sid);
1154         fprintf(add_fd, "sambaGroupType: 2\n");
1155         fprintf(add_fd, "displayName: Domain Admins\n");
1156         fprintf(add_fd, "\n");
1157         fflush(add_fd);
1158
1159         /* Write the Domain Users entity */ 
1160         fprintf(add_fd, "# Domain Users, %s, %s\n", group_attr,
1161                 suffix);
1162         fprintf(add_fd, "dn: cn=Domain Users,ou=%s,%s\n", group_attr,
1163                 suffix);
1164         fprintf(add_fd, "objectClass: posixGroup\n");
1165         fprintf(add_fd, "objectClass: sambaGroupMapping\n");
1166         fprintf(add_fd, "cn: Domain Users\n");
1167         fprintf(add_fd, "description: Netbios Domain Users\n");
1168         fprintf(add_fd, "gidNumber: 513\n");
1169         fprintf(add_fd, "sambaSID: %s-513\n", sid);
1170         fprintf(add_fd, "sambaGroupType: 2\n");
1171         fprintf(add_fd, "displayName: Domain Users\n");
1172         fprintf(add_fd, "\n");
1173         fflush(add_fd);
1174
1175         /* Write the Domain Guests entity */ 
1176         fprintf(add_fd, "# Domain Guests, %s, %s\n", group_attr,
1177                 suffix);
1178         fprintf(add_fd, "dn: cn=Domain Guests,ou=%s,%s\n", group_attr,
1179                 suffix);
1180         fprintf(add_fd, "objectClass: posixGroup\n");
1181         fprintf(add_fd, "objectClass: sambaGroupMapping\n");
1182         fprintf(add_fd, "cn: Domain Guests\n");
1183         fprintf(add_fd, "description: Netbios Domain Guests\n");
1184         fprintf(add_fd, "gidNumber: 514\n");
1185         fprintf(add_fd, "sambaSID: %s-514\n", sid);
1186         fprintf(add_fd, "sambaGroupType: 2\n");
1187         fprintf(add_fd, "displayName: Domain Guests\n");
1188         fprintf(add_fd, "\n");
1189         fflush(add_fd);
1190
1191         /* Write the Domain Computers entity */
1192         fprintf(add_fd, "# Domain Computers, %s, %s\n", group_attr,
1193                 suffix);
1194         fprintf(add_fd, "dn: cn=Domain Computers,ou=%s,%s\n",
1195                 group_attr, suffix);
1196         fprintf(add_fd, "objectClass: posixGroup\n");
1197         fprintf(add_fd, "objectClass: sambaGroupMapping\n");
1198         fprintf(add_fd, "gidNumber: 515\n");
1199         fprintf(add_fd, "cn: Domain Computers\n");
1200         fprintf(add_fd, "description: Netbios Domain Computers accounts\n");
1201         fprintf(add_fd, "sambaSID: %s-515\n", sid);
1202         fprintf(add_fd, "sambaGroupType: 2\n");
1203         fprintf(add_fd, "displayName: Domain Computers\n");
1204         fprintf(add_fd, "\n");
1205         fflush(add_fd);
1206
1207         /* Write the Admininistrators Groups entity */
1208         fprintf(add_fd, "# Administrators, %s, %s\n", group_attr,
1209                 suffix);
1210         fprintf(add_fd, "dn: cn=Administrators,ou=%s,%s\n", group_attr,
1211                 suffix);
1212         fprintf(add_fd, "objectClass: posixGroup\n");
1213         fprintf(add_fd, "objectClass: sambaGroupMapping\n");
1214         fprintf(add_fd, "gidNumber: 544\n");
1215         fprintf(add_fd, "cn: Administrators\n");
1216         fprintf(add_fd, "description: Netbios Domain Members can fully administer the computer/sambaDomainName\n");
1217         fprintf(add_fd, "sambaSID: %s-544\n", builtin_sid);
1218         fprintf(add_fd, "sambaGroupType: 5\n");
1219         fprintf(add_fd, "displayName: Administrators\n");
1220         fprintf(add_fd, "\n");
1221
1222         /* Write the Print Operator entity */
1223         fprintf(add_fd, "# Print Operators, %s, %s\n", group_attr,
1224                 suffix);
1225         fprintf(add_fd, "dn: cn=Print Operators,ou=%s,%s\n",
1226                 group_attr, suffix);
1227         fprintf(add_fd, "objectClass: posixGroup\n");
1228         fprintf(add_fd, "objectClass: sambaGroupMapping\n");
1229         fprintf(add_fd, "gidNumber: 550\n");
1230         fprintf(add_fd, "cn: Print Operators\n");
1231         fprintf(add_fd, "description: Netbios Domain Print Operators\n");
1232         fprintf(add_fd, "sambaSID: %s-550\n", builtin_sid);
1233         fprintf(add_fd, "sambaGroupType: 5\n");
1234         fprintf(add_fd, "displayName: Print Operators\n");
1235         fprintf(add_fd, "\n");
1236         fflush(add_fd);
1237
1238         /* Write the Backup Operators entity */
1239         fprintf(add_fd, "# Backup Operators, %s, %s\n", group_attr,
1240                 suffix);
1241         fprintf(add_fd, "dn: cn=Backup Operators,ou=%s,%s\n",
1242                 group_attr, suffix);
1243         fprintf(add_fd, "objectClass: posixGroup\n");
1244         fprintf(add_fd, "objectClass: sambaGroupMapping\n");
1245         fprintf(add_fd, "gidNumber: 551\n");
1246         fprintf(add_fd, "cn: Backup Operators\n");
1247         fprintf(add_fd, "description: Netbios Domain Members can bypass file security to back up files\n");
1248         fprintf(add_fd, "sambaSID: %s-551\n", builtin_sid);
1249         fprintf(add_fd, "sambaGroupType: 5\n");
1250         fprintf(add_fd, "displayName: Backup Operators\n");
1251         fprintf(add_fd, "\n");
1252         fflush(add_fd);
1253
1254         /* Write the Replicators entity */
1255         fprintf(add_fd, "# Replicators, %s, %s\n", group_attr, suffix);
1256         fprintf(add_fd, "dn: cn=Replicators,ou=%s,%s\n", group_attr,
1257                 suffix);
1258         fprintf(add_fd, "objectClass: posixGroup\n");
1259         fprintf(add_fd, "objectClass: sambaGroupMapping\n");
1260         fprintf(add_fd, "gidNumber: 552\n");
1261         fprintf(add_fd, "cn: Replicators\n");
1262         fprintf(add_fd, "description: Netbios Domain Supports file replication in a sambaDomainName\n");
1263         fprintf(add_fd, "sambaSID: %s-552\n", builtin_sid);
1264         fprintf(add_fd, "sambaGroupType: 5\n");
1265         fprintf(add_fd, "displayName: Replicators\n");
1266         fprintf(add_fd, "\n");
1267         fflush(add_fd);
1268
1269         /* Deallocate memory, and return */
1270         SAFE_FREE(suffix_attr);
1271         SAFE_FREE(user_attr);
1272         SAFE_FREE(group_attr);
1273         return NT_STATUS_OK;
1274 }
1275
1276 static NTSTATUS map_populate_groups(GROUPMAP *groupmap, ACCOUNTMAP *accountmap, fstring sid, 
1277                     const char *suffix, const char *builtin_sid)
1278 {
1279         char *group_attr = sstring_sub(lp_ldap_group_suffix(), '=', ',');
1280
1281         /* Map the groups created by populate_ldap_for_ldif */
1282         groupmap[0].rid = 512;
1283         groupmap[0].gidNumber = 512;
1284         snprintf(groupmap[0].sambaSID, sizeof(groupmap[0].sambaSID),
1285                         "%s-512", sid);
1286         snprintf(groupmap[0].group_dn, sizeof(groupmap[0].group_dn),
1287                         "cn=Domain Admins,ou=%s,%s",
1288                         group_attr, suffix);
1289         accountmap[0].rid = 512;
1290         snprintf(accountmap[0].cn, sizeof(accountmap[0].cn),
1291                         "%s", "Domain Admins");
1292
1293         groupmap[1].rid = 513;
1294         groupmap[1].gidNumber = 513;
1295         snprintf(groupmap[1].sambaSID, sizeof(groupmap[1].sambaSID),
1296                         "%s-513", sid);
1297         snprintf(groupmap[1].group_dn, sizeof(groupmap[1].group_dn),
1298                         "cn=Domain Users,ou=%s,%s",
1299                         group_attr, suffix);
1300         accountmap[1].rid = 513;
1301         snprintf(accountmap[1].cn, sizeof(accountmap[1].cn),
1302                         "%s", "Domain Users");
1303
1304         groupmap[2].rid = 514;
1305         groupmap[2].gidNumber = 514;
1306         snprintf(groupmap[2].sambaSID, sizeof(groupmap[2].sambaSID),
1307                         "%s-514", sid);
1308         snprintf(groupmap[2].group_dn, sizeof(groupmap[2].group_dn),
1309                         "cn=Domain Guests,ou=%s,%s",
1310                         group_attr, suffix);
1311         accountmap[2].rid = 514;
1312         snprintf(accountmap[2].cn, sizeof(accountmap[2].cn),
1313                         "%s", "Domain Guests");
1314
1315         groupmap[3].rid = 515;
1316         groupmap[3].gidNumber = 515;
1317         snprintf(groupmap[3].sambaSID, sizeof(groupmap[3].sambaSID),
1318                         "%s-515", sid);
1319         snprintf(groupmap[3].group_dn, sizeof(groupmap[3].group_dn),
1320                         "cn=Domain Computers,ou=%s,%s",
1321                         group_attr, suffix);
1322         accountmap[3].rid = 515;
1323         snprintf(accountmap[3].cn, sizeof(accountmap[3].cn),
1324                         "%s", "Domain Computers");
1325
1326         groupmap[4].rid = 544;
1327         groupmap[4].gidNumber = 544;
1328         snprintf(groupmap[4].sambaSID, sizeof(groupmap[4].sambaSID),
1329                         "%s-544", builtin_sid);
1330         snprintf(groupmap[4].group_dn, sizeof(groupmap[4].group_dn),
1331                         "cn=Administrators,ou=%s,%s",
1332                         group_attr, suffix);
1333         accountmap[4].rid = 515;
1334         snprintf(accountmap[4].cn, sizeof(accountmap[4].cn),
1335                         "%s", "Administrators");
1336
1337         groupmap[5].rid = 550;
1338         groupmap[5].gidNumber = 550;
1339         snprintf(groupmap[5].sambaSID, sizeof(groupmap[5].sambaSID),
1340                         "%s-550", builtin_sid);
1341         snprintf(groupmap[5].group_dn, sizeof(groupmap[5].group_dn),
1342                         "cn=Print Operators,ou=%s,%s",
1343                         group_attr, suffix);
1344         accountmap[5].rid = 550;
1345         snprintf(accountmap[5].cn, sizeof(accountmap[5].cn),
1346                         "%s", "Print Operators");
1347
1348         groupmap[6].rid = 551;
1349         groupmap[6].gidNumber = 551;
1350         snprintf(groupmap[6].sambaSID, sizeof(groupmap[6].sambaSID),
1351                         "%s-551", builtin_sid);
1352         snprintf(groupmap[6].group_dn, sizeof(groupmap[6].group_dn),
1353                         "cn=Backup Operators,ou=%s,%s",
1354                         group_attr, suffix);
1355         accountmap[6].rid = 551;
1356         snprintf(accountmap[6].cn, sizeof(accountmap[6].cn),
1357                         "%s", "Backup Operators");
1358
1359         groupmap[7].rid = 552;
1360         groupmap[7].gidNumber = 552;
1361         snprintf(groupmap[7].sambaSID, sizeof(groupmap[7].sambaSID),
1362                         "%s-552", builtin_sid);
1363         snprintf(groupmap[7].group_dn, sizeof(groupmap[7].group_dn),
1364                         "cn=Replicators,ou=%s,%s",
1365                         group_attr, suffix);
1366         accountmap[7].rid = 551;
1367         snprintf(accountmap[7].cn, sizeof(accountmap[7].cn),
1368                         "%s", "Replicators");
1369         SAFE_FREE(group_attr);
1370         return NT_STATUS_OK;
1371 }
1372
1373 /*
1374  * This is a crap routine, but I think it's the quickest way to solve the
1375  * UTF8->base64 problem.
1376  */
1377
1378 static int fprintf_attr(FILE *add_fd, const char *attr_name,
1379                         const char *fmt, ...)
1380 {
1381         va_list ap;
1382         char *value, *p, *base64;
1383         DATA_BLOB base64_blob;
1384         bool do_base64 = False;
1385         int res;
1386
1387         va_start(ap, fmt);
1388         value = talloc_vasprintf(NULL, fmt, ap);
1389         va_end(ap);
1390
1391         SMB_ASSERT(value != NULL);
1392
1393         for (p=value; *p; p++) {
1394                 if (*p & 0x80) {
1395                         do_base64 = True;
1396                         break;
1397                 }
1398         }
1399
1400         if (!do_base64) {
1401                 bool only_whitespace = True;
1402                 for (p=value; *p; p++) {
1403                         /*
1404                          * I know that this not multibyte safe, but we break
1405                          * on the first non-whitespace character anyway.
1406                          */
1407                         if (!isspace(*p)) {
1408                                 only_whitespace = False;
1409                                 break;
1410                         }
1411                 }
1412                 if (only_whitespace) {
1413                         do_base64 = True;
1414                 }
1415         }
1416
1417         if (!do_base64) {
1418                 res = fprintf(add_fd, "%s: %s\n", attr_name, value);
1419                 TALLOC_FREE(value);
1420                 return res;
1421         }
1422
1423         base64_blob.data = (unsigned char *)value;
1424         base64_blob.length = strlen(value);
1425
1426         base64 = base64_encode_data_blob(value, base64_blob);
1427         SMB_ASSERT(base64 != NULL);
1428
1429         res = fprintf(add_fd, "%s:: %s\n", attr_name, base64);
1430         TALLOC_FREE(value);
1431         return res;
1432 }
1433
1434 static NTSTATUS fetch_group_info_to_ldif(SAM_DELTA_CTR *delta, GROUPMAP *groupmap,
1435                          FILE *add_fd, fstring sid, char *suffix)
1436 {
1437         fstring groupname;
1438         uint32 grouptype = 0, g_rid = 0;
1439         char *group_attr = sstring_sub(lp_ldap_group_suffix(), '=', ',');
1440
1441         /* Get the group name */
1442         unistr2_to_ascii(groupname,
1443                          &delta->group_info.uni_grp_name,
1444                          sizeof(groupname));
1445
1446         /* Set up the group type (always 2 for group info) */
1447         grouptype = 2;
1448
1449         /* These groups are entered by populate_ldap_for_ldif */
1450         if (strcmp(groupname, "Domain Admins") == 0 ||
1451             strcmp(groupname, "Domain Users") == 0 ||
1452             strcmp(groupname, "Domain Guests") == 0 ||
1453             strcmp(groupname, "Domain Computers") == 0 ||
1454             strcmp(groupname, "Administrators") == 0 ||
1455             strcmp(groupname, "Print Operators") == 0 ||
1456             strcmp(groupname, "Backup Operators") == 0 ||
1457             strcmp(groupname, "Replicators") == 0) {
1458                 SAFE_FREE(group_attr);
1459                 return NT_STATUS_OK;
1460         } else {
1461                 /* Increment the gid for the new group */
1462                 ldif_gid++;
1463         }
1464
1465         /* Map the group rid, gid, and dn */
1466         g_rid = delta->group_info.gid.g_rid;
1467         groupmap->rid = g_rid;
1468         groupmap->gidNumber = ldif_gid;
1469         snprintf(groupmap->sambaSID, sizeof(groupmap->sambaSID),
1470                         "%s-%d", sid, g_rid);
1471         snprintf(groupmap->group_dn, sizeof(groupmap->group_dn),
1472                      "cn=%s,ou=%s,%s", groupname, group_attr, suffix);
1473
1474         /* Write the data to the temporary add ldif file */
1475         fprintf(add_fd, "# %s, %s, %s\n", groupname, group_attr,
1476                 suffix);
1477         fprintf_attr(add_fd, "dn", "cn=%s,ou=%s,%s", groupname, group_attr,
1478                      suffix);
1479         fprintf(add_fd, "objectClass: posixGroup\n");
1480         fprintf(add_fd, "objectClass: sambaGroupMapping\n");
1481         fprintf_attr(add_fd, "cn", "%s", groupname);
1482         fprintf(add_fd, "gidNumber: %d\n", ldif_gid);
1483         fprintf(add_fd, "sambaSID: %s\n", groupmap->sambaSID);
1484         fprintf(add_fd, "sambaGroupType: %d\n", grouptype);
1485         fprintf_attr(add_fd, "displayName", "%s", groupname);
1486         fprintf(add_fd, "\n");
1487         fflush(add_fd);
1488
1489         SAFE_FREE(group_attr);
1490         /* Return */
1491         return NT_STATUS_OK;
1492 }
1493
1494 static NTSTATUS fetch_account_info_to_ldif(SAM_DELTA_CTR *delta,
1495                                            GROUPMAP *groupmap,
1496                                            ACCOUNTMAP *accountmap,
1497                                            FILE *add_fd,
1498                                            fstring sid, char *suffix,
1499                                            int alloced)
1500 {
1501         fstring username, logonscript, homedrive, homepath = "", homedir = "";
1502         fstring hex_nt_passwd, hex_lm_passwd;
1503         fstring description, profilepath, fullname, sambaSID;
1504         uchar lm_passwd[16], nt_passwd[16];
1505         char *flags, *user_rdn;
1506         const char *ou;
1507         const char* nopasswd = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
1508         static uchar zero_buf[16];
1509         uint32 rid = 0, group_rid = 0, gidNumber = 0;
1510         time_t unix_time;
1511         int i;
1512
1513         /* Get the username */
1514         unistr2_to_ascii(username,
1515                          &(delta->account_info.uni_acct_name),
1516                          sizeof(username));
1517
1518         /* Get the rid */
1519         rid = delta->account_info.user_rid;
1520
1521         /* Map the rid and username for group member info later */
1522         accountmap->rid = rid;
1523         snprintf(accountmap->cn, sizeof(accountmap->cn), "%s", username);
1524
1525         /* Get the home directory */
1526         if (delta->account_info.acb_info & ACB_NORMAL) {
1527                 unistr2_to_ascii(homedir, &(delta->account_info.uni_home_dir),
1528                                  sizeof(homedir));
1529                 if (!*homedir) {
1530                         snprintf(homedir, sizeof(homedir), "/home/%s", username);
1531                 } else {
1532                         snprintf(homedir, sizeof(homedir), "/nobodyshomedir");
1533                 }
1534                 ou = lp_ldap_user_suffix();
1535         } else {
1536                 ou = lp_ldap_machine_suffix();
1537                 snprintf(homedir, sizeof(homedir), "/machinehomedir");
1538         }
1539
1540         /* Get the logon script */
1541         unistr2_to_ascii(logonscript, &(delta->account_info.uni_logon_script),
1542                          sizeof(logonscript));
1543
1544         /* Get the home drive */
1545         unistr2_to_ascii(homedrive, &(delta->account_info.uni_dir_drive),
1546                          sizeof(homedrive));
1547
1548         /* Get the home path */
1549         unistr2_to_ascii(homepath, &(delta->account_info.uni_home_dir),
1550                          sizeof(homepath));
1551
1552         /* Get the description */
1553         unistr2_to_ascii(description, &(delta->account_info.uni_acct_desc),
1554                          sizeof(description));
1555
1556         /* Get the display name */
1557         unistr2_to_ascii(fullname, &(delta->account_info.uni_full_name),
1558                          sizeof(fullname));
1559
1560         /* Get the profile path */
1561         unistr2_to_ascii(profilepath, &(delta->account_info.uni_profile),
1562                          sizeof(profilepath));
1563
1564         /* Get lm and nt password data */
1565         if (memcmp(delta->account_info.pass.buf_lm_pwd, zero_buf, 16) != 0) {
1566                 sam_pwd_hash(delta->account_info.user_rid, 
1567                              delta->account_info.pass.buf_lm_pwd, 
1568                              lm_passwd, 0);
1569                 pdb_sethexpwd(hex_lm_passwd, lm_passwd, 
1570                               delta->account_info.acb_info);
1571         } else {
1572                 pdb_sethexpwd(hex_lm_passwd, NULL, 0);
1573         }
1574         if (memcmp(delta->account_info.pass.buf_nt_pwd, zero_buf, 16) != 0) {
1575                 sam_pwd_hash(delta->account_info.user_rid, 
1576                              delta->account_info.pass.buf_nt_pwd, 
1577                              nt_passwd, 0);
1578                 pdb_sethexpwd(hex_nt_passwd, nt_passwd, 
1579                               delta->account_info.acb_info);
1580         } else {
1581                 pdb_sethexpwd(hex_nt_passwd, NULL, 0);
1582         }
1583         unix_time = nt_time_to_unix(delta->account_info.pwd_last_set_time);
1584
1585         /* Increment the uid for the new user */
1586         ldif_uid++;
1587
1588         /* Set up group id and sambaSID for the user */
1589         group_rid = delta->account_info.group_rid;
1590         for (i=0; i<alloced; i++) {
1591                 if (groupmap[i].rid == group_rid) break;
1592         }
1593         if (i == alloced){
1594                 DEBUG(1, ("Could not find rid %d in groupmap array\n", 
1595                           group_rid));
1596                 return NT_STATUS_UNSUCCESSFUL;
1597         }
1598         gidNumber = groupmap[i].gidNumber;
1599         snprintf(sambaSID, sizeof(sambaSID), groupmap[i].sambaSID);
1600
1601         /* Set up sambaAcctFlags */
1602         flags = pdb_encode_acct_ctrl(delta->account_info.acb_info,
1603                                      NEW_PW_FORMAT_SPACE_PADDED_LEN);
1604
1605         /* Add the user to the temporary add ldif file */
1606         /* this isn't quite right...we can't assume there's just OU=. jmcd */
1607         user_rdn = sstring_sub(ou, '=', ',');
1608         fprintf(add_fd, "# %s, %s, %s\n", username, user_rdn, suffix);
1609         fprintf_attr(add_fd, "dn", "uid=%s,ou=%s,%s", username, user_rdn,
1610                      suffix);
1611         SAFE_FREE(user_rdn);
1612         fprintf(add_fd, "ObjectClass: top\n");
1613         fprintf(add_fd, "objectClass: inetOrgPerson\n");
1614         fprintf(add_fd, "objectClass: posixAccount\n");
1615         fprintf(add_fd, "objectClass: shadowAccount\n");
1616         fprintf(add_fd, "objectClass: sambaSamAccount\n");
1617         fprintf_attr(add_fd, "cn", "%s", username);
1618         fprintf_attr(add_fd, "sn", "%s", username);
1619         fprintf_attr(add_fd, "uid", "%s", username);
1620         fprintf(add_fd, "uidNumber: %d\n", ldif_uid);
1621         fprintf(add_fd, "gidNumber: %d\n", gidNumber);
1622         fprintf_attr(add_fd, "homeDirectory", "%s", homedir);
1623         if (*homepath)
1624                 fprintf_attr(add_fd, "sambaHomePath", "%s", homepath);
1625         if (*homedrive)
1626                 fprintf_attr(add_fd, "sambaHomeDrive", "%s", homedrive);
1627         if (*logonscript)
1628                 fprintf_attr(add_fd, "sambaLogonScript", "%s", logonscript);
1629         fprintf(add_fd, "loginShell: %s\n", 
1630                 ((delta->account_info.acb_info & ACB_NORMAL) ?
1631                  "/bin/bash" : "/bin/false"));
1632         fprintf(add_fd, "gecos: System User\n");
1633         if (*description)
1634                 fprintf_attr(add_fd, "description", "%s", description);
1635         fprintf(add_fd, "sambaSID: %s-%d\n", sid, rid);
1636         fprintf(add_fd, "sambaPrimaryGroupSID: %s\n", sambaSID);
1637         if(*fullname)
1638                 fprintf_attr(add_fd, "displayName", "%s", fullname);
1639         if(*profilepath)
1640                 fprintf_attr(add_fd, "sambaProfilePath", "%s", profilepath);
1641         if (strcmp(nopasswd, hex_lm_passwd) != 0)
1642                 fprintf(add_fd, "sambaLMPassword: %s\n", hex_lm_passwd);
1643         if (strcmp(nopasswd, hex_nt_passwd) != 0)
1644                 fprintf(add_fd, "sambaNTPassword: %s\n", hex_nt_passwd);
1645         fprintf(add_fd, "sambaPwdLastSet: %d\n", (int)unix_time);
1646         fprintf(add_fd, "sambaAcctFlags: %s\n", flags);
1647         fprintf(add_fd, "\n");
1648         fflush(add_fd);
1649
1650         /* Return */
1651         return NT_STATUS_OK;
1652 }
1653
1654 static NTSTATUS fetch_alias_info_to_ldif(SAM_DELTA_CTR *delta,
1655                                          GROUPMAP *groupmap,
1656                                          FILE *add_fd, fstring sid,
1657                                          char *suffix, 
1658                                          unsigned db_type)
1659 {
1660         fstring aliasname, description;
1661         uint32 grouptype = 0, g_rid = 0;
1662         char *group_attr = sstring_sub(lp_ldap_group_suffix(), '=', ',');
1663
1664         /* Get the alias name */
1665         unistr2_to_ascii(aliasname, &(delta->alias_info.uni_als_name),
1666                          sizeof(aliasname));
1667
1668         /* Get the alias description */
1669         unistr2_to_ascii(description, &(delta->alias_info.uni_als_desc),
1670                          sizeof(description));
1671
1672         /* Set up the group type */
1673         switch (db_type) {
1674         case SAM_DATABASE_DOMAIN:
1675                 grouptype = 4;
1676                 break;
1677         case SAM_DATABASE_BUILTIN:
1678                 grouptype = 5;
1679                 break;
1680         default:
1681                 grouptype = 4;
1682                 break;
1683         }
1684
1685         /*
1686           These groups are entered by populate_ldap_for_ldif
1687           Note that populate creates a group called Relicators, 
1688           but NT returns a group called Replicator
1689         */
1690         if (strcmp(aliasname, "Domain Admins") == 0 ||
1691             strcmp(aliasname, "Domain Users") == 0 ||
1692             strcmp(aliasname, "Domain Guests") == 0 ||
1693             strcmp(aliasname, "Domain Computers") == 0 ||
1694             strcmp(aliasname, "Administrators") == 0 ||
1695             strcmp(aliasname, "Print Operators") == 0 ||
1696             strcmp(aliasname, "Backup Operators") == 0 ||
1697             strcmp(aliasname, "Replicator") == 0) {
1698                 SAFE_FREE(group_attr);
1699                 return NT_STATUS_OK;
1700         } else {
1701                 /* Increment the gid for the new group */
1702                 ldif_gid++;
1703         }
1704
1705         /* Map the group rid and gid */
1706         g_rid = delta->group_info.gid.g_rid;
1707         groupmap->gidNumber = ldif_gid;
1708         snprintf(groupmap->sambaSID, sizeof(groupmap->sambaSID),
1709                         "%s-%d", sid, g_rid);
1710
1711         /* Write the data to the temporary add ldif file */
1712         fprintf(add_fd, "# %s, %s, %s\n", aliasname, group_attr,
1713                 suffix);
1714         fprintf_attr(add_fd, "dn", "cn=%s,ou=%s,%s", aliasname, group_attr,
1715                      suffix);
1716         fprintf(add_fd, "objectClass: posixGroup\n");
1717         fprintf(add_fd, "objectClass: sambaGroupMapping\n");
1718         fprintf(add_fd, "cn: %s\n", aliasname);
1719         fprintf(add_fd, "gidNumber: %d\n", ldif_gid);
1720         fprintf(add_fd, "sambaSID: %s\n", groupmap->sambaSID);
1721         fprintf(add_fd, "sambaGroupType: %d\n", grouptype);
1722         fprintf_attr(add_fd, "displayName", "%s", aliasname);
1723         if (description[0])
1724                 fprintf_attr(add_fd, "description", "%s", description);
1725         fprintf(add_fd, "\n");
1726         fflush(add_fd);
1727
1728         SAFE_FREE(group_attr);
1729         /* Return */
1730         return NT_STATUS_OK;
1731 }
1732
1733 static NTSTATUS fetch_groupmem_info_to_ldif(SAM_DELTA_CTR *delta,
1734                                             SAM_DELTA_HDR *hdr_delta,
1735                                             GROUPMAP *groupmap,
1736                                             ACCOUNTMAP *accountmap,
1737                                             FILE *mod_fd, int alloced)
1738 {
1739         fstring group_dn;
1740         uint32 group_rid = 0, rid = 0;
1741         int i, j, k;
1742
1743         /* Get the dn for the group */
1744         if (delta->grp_mem_info.num_members > 0) {
1745                 group_rid = hdr_delta->target_rid;
1746                 for (j=0; j<alloced; j++) {
1747                         if (groupmap[j].rid == group_rid) break;
1748                 }
1749                 if (j == alloced){
1750                         DEBUG(1, ("Could not find rid %d in groupmap array\n",
1751                                   group_rid));
1752                         return NT_STATUS_UNSUCCESSFUL;
1753                 }
1754                 snprintf(group_dn, sizeof(group_dn), "%s", groupmap[j].group_dn);
1755                 fprintf(mod_fd, "dn: %s\n", group_dn);
1756
1757                 /* Get the cn for each member */
1758                 for (i=0; i<delta->grp_mem_info.num_members; i++) {
1759                         rid = delta->grp_mem_info.rids[i];
1760                         for (k=0; k<alloced; k++) {
1761                                 if (accountmap[k].rid == rid) break;
1762                         }
1763                         if (k == alloced){
1764                                 DEBUG(1, ("Could not find rid %d in "
1765                                           "accountmap array\n", rid));
1766                                 return NT_STATUS_UNSUCCESSFUL;
1767                         }
1768                         fprintf(mod_fd, "memberUid: %s\n", accountmap[k].cn);
1769                 }
1770                 fprintf(mod_fd, "\n");
1771         }
1772         fflush(mod_fd);
1773
1774         /* Return */
1775         return NT_STATUS_OK;
1776 }
1777
1778 static NTSTATUS fetch_database_to_ldif(struct rpc_pipe_client *pipe_hnd,
1779                                        uint32 db_type,
1780                                        DOM_SID dom_sid,
1781                                        const char *user_file)
1782 {
1783         char *suffix;
1784         const char *builtin_sid = "S-1-5-32";
1785         char *add_name = NULL, *mod_name = NULL;
1786         const char *add_template = "/tmp/add.ldif.XXXXXX";
1787         const char *mod_template = "/tmp/mod.ldif.XXXXXX";
1788         fstring sid, domainname;
1789         uint32 sync_context = 0;
1790         NTSTATUS ret = NT_STATUS_OK, result;
1791         int k;
1792         TALLOC_CTX *mem_ctx;
1793         SAM_DELTA_HDR *hdr_deltas;
1794         SAM_DELTA_CTR *deltas;
1795         uint32 num_deltas;
1796         FILE *add_file = NULL, *mod_file = NULL, *ldif_file = NULL;
1797         int num_alloced = 0, g_index = 0, a_index = 0;
1798
1799         /* Set up array for mapping accounts to groups */
1800         /* Array element is the group rid */
1801         GROUPMAP *groupmap = NULL;
1802
1803         /* Set up array for mapping account rid's to cn's */
1804         /* Array element is the account rid */
1805         ACCOUNTMAP *accountmap = NULL; 
1806
1807         if (!(mem_ctx = talloc_init("fetch_database"))) {
1808                 return NT_STATUS_NO_MEMORY;
1809         }
1810
1811         /* Ensure we have an output file */
1812         if (user_file)
1813                 ldif_file = fopen(user_file, "a");
1814         else
1815                 ldif_file = stdout;
1816
1817         if (!ldif_file) {
1818                 fprintf(stderr, "Could not open %s\n", user_file);
1819                 DEBUG(1, ("Could not open %s\n", user_file));
1820                 ret = NT_STATUS_UNSUCCESSFUL;
1821                 goto done;
1822         }
1823
1824         add_name = talloc_strdup(mem_ctx, add_template);
1825         mod_name = talloc_strdup(mem_ctx, mod_template);
1826         if (!add_name || !mod_name) {
1827                 ret = NT_STATUS_NO_MEMORY;
1828                 goto done;
1829         }
1830
1831         /* Open the add and mod ldif files */
1832         if (!(add_file = fdopen(smb_mkstemp(add_name),"w"))) {
1833                 DEBUG(1, ("Could not open %s\n", add_name));
1834                 ret = NT_STATUS_UNSUCCESSFUL;
1835                 goto done;
1836         }
1837         if (!(mod_file = fdopen(smb_mkstemp(mod_name),"w"))) {
1838                 DEBUG(1, ("Could not open %s\n", mod_name));
1839                 ret = NT_STATUS_UNSUCCESSFUL;
1840                 goto done;
1841         } 
1842
1843         /* Get the sid */
1844         sid_to_fstring(sid, &dom_sid);
1845
1846         /* Get the ldap suffix */
1847         suffix = lp_ldap_suffix();
1848         if (suffix == NULL || strcmp(suffix, "") == 0) {
1849                 DEBUG(0,("ldap suffix missing from smb.conf--exiting\n"));
1850                 exit(1);
1851         }
1852
1853         /* Get other smb.conf data */
1854         if (!(lp_workgroup()) || !*(lp_workgroup())) {
1855                 DEBUG(0,("workgroup missing from smb.conf--exiting\n"));
1856                 exit(1);
1857         }
1858
1859         /* Allocate initial memory for groupmap and accountmap arrays */
1860         if (init_ldap == 1) {
1861                 groupmap = SMB_MALLOC_ARRAY(GROUPMAP, 8);
1862                 accountmap = SMB_MALLOC_ARRAY(ACCOUNTMAP, 8);
1863                 if (groupmap == NULL || accountmap == NULL) {
1864                         DEBUG(1,("GROUPMAP malloc failed\n"));
1865                         ret = NT_STATUS_NO_MEMORY;
1866                         goto done;
1867                 }
1868
1869                 /* Initialize the arrays */
1870                 memset(groupmap, 0, sizeof(GROUPMAP)*8);
1871                 memset(accountmap, 0, sizeof(ACCOUNTMAP)*8);
1872
1873                 /* Remember how many we malloced */
1874                 num_alloced = 8;
1875
1876                 /* Initial database population */
1877                 populate_ldap_for_ldif(sid, suffix, builtin_sid, add_file);
1878                 map_populate_groups(groupmap, accountmap, sid, suffix,
1879                                     builtin_sid);
1880
1881                 /* Don't do this again */
1882                 init_ldap = 0;
1883         }
1884
1885         /* Announce what we are doing */
1886         switch( db_type ) {
1887         case SAM_DATABASE_DOMAIN:
1888                 d_fprintf(stderr, "Fetching DOMAIN database\n");
1889                 break;
1890         case SAM_DATABASE_BUILTIN:
1891                 d_fprintf(stderr, "Fetching BUILTIN database\n");
1892                 break;
1893         case SAM_DATABASE_PRIVS:
1894                 d_fprintf(stderr, "Fetching PRIVS databases\n");
1895                 break;
1896         default:
1897                 d_fprintf(stderr, 
1898                           "Fetching unknown database type %u\n", 
1899                           db_type );
1900                 break;
1901         }
1902
1903         do {
1904                 result = rpccli_netlogon_sam_sync(pipe_hnd, mem_ctx,
1905                                                   db_type, sync_context,
1906                                                   &num_deltas, &hdr_deltas, 
1907                                                   &deltas);
1908                 if (!NT_STATUS_IS_OK(result) &&
1909                     !NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES)) {
1910                         ret = NT_STATUS_OK;
1911                         goto done; /* is this correct? jmcd */
1912                 }
1913
1914                 /* Re-allocate memory for groupmap and accountmap arrays */
1915                 groupmap = SMB_REALLOC_ARRAY(groupmap, GROUPMAP,
1916                                              num_deltas+num_alloced);
1917                 accountmap = SMB_REALLOC_ARRAY(accountmap, ACCOUNTMAP,
1918                                                num_deltas+num_alloced);
1919                 if (groupmap == NULL || accountmap == NULL) {
1920                         DEBUG(1,("GROUPMAP malloc failed\n"));
1921                         ret = NT_STATUS_NO_MEMORY;
1922                         goto done;
1923                 }
1924
1925                 /* Initialize the new records */
1926                 memset(&groupmap[num_alloced], 0, 
1927                        sizeof(GROUPMAP)*num_deltas);
1928                 memset(&accountmap[num_alloced], 0,
1929                        sizeof(ACCOUNTMAP)*num_deltas);
1930
1931                 /* Remember how many we alloced this time */
1932                 num_alloced += num_deltas;
1933
1934                 /* Loop through the deltas */
1935                 for (k=0; k<num_deltas; k++) {
1936                         switch(hdr_deltas[k].type) {
1937                         case SAM_DELTA_DOMAIN_INFO:
1938                                 /* Is this case needed? */
1939                                 unistr2_to_ascii(
1940                                         domainname, 
1941                                         &deltas[k].domain_info.uni_dom_name,
1942                                         sizeof(domainname));
1943                                 break;
1944
1945                         case SAM_DELTA_GROUP_INFO:
1946                                 fetch_group_info_to_ldif(
1947                                         &deltas[k], &groupmap[g_index],
1948                                         add_file, sid, suffix);
1949                                 g_index++;
1950                                 break;
1951
1952                         case SAM_DELTA_ACCOUNT_INFO:
1953                                 fetch_account_info_to_ldif(
1954                                         &deltas[k], groupmap, 
1955                                         &accountmap[a_index], add_file,
1956                                         sid, suffix, num_alloced);
1957                                 a_index++;
1958                                 break;
1959
1960                         case SAM_DELTA_ALIAS_INFO:
1961                                 fetch_alias_info_to_ldif(
1962                                         &deltas[k], &groupmap[g_index],
1963                                         add_file, sid, suffix, db_type);
1964                                 g_index++;
1965                                 break;
1966
1967                         case SAM_DELTA_GROUP_MEM:
1968                                 fetch_groupmem_info_to_ldif(
1969                                         &deltas[k], &hdr_deltas[k], 
1970                                         groupmap, accountmap, 
1971                                         mod_file, num_alloced);
1972                                 break;
1973
1974                         case SAM_DELTA_ALIAS_MEM:
1975                                 break;
1976                         case SAM_DELTA_POLICY_INFO:
1977                                 break;
1978                         case SAM_DELTA_PRIVS_INFO:
1979                                 break;
1980                         case SAM_DELTA_TRUST_DOMS:
1981                                 /* Implemented but broken */
1982                                 break;
1983                         case SAM_DELTA_SECRET_INFO:
1984                                 /* Implemented but broken */
1985                                 break;
1986                         case SAM_DELTA_RENAME_GROUP:
1987                                 /* Not yet implemented */
1988                                 break;
1989                         case SAM_DELTA_RENAME_USER:
1990                                 /* Not yet implemented */
1991                                 break;
1992                         case SAM_DELTA_RENAME_ALIAS:
1993                                 /* Not yet implemented */
1994                                 break;
1995                         case SAM_DELTA_DELETE_GROUP:
1996                                 /* Not yet implemented */
1997                                 break;
1998                         case SAM_DELTA_DELETE_USER:
1999                                 /* Not yet implemented */
2000                                 break;
2001                         case SAM_DELTA_MODIFIED_COUNT:
2002                                 break;
2003                         default:
2004                                 break;
2005                         } /* end of switch */
2006                 } /* end of for loop */
2007
2008                 /* Increment sync_context */
2009                 sync_context += 1;
2010
2011         } while (NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES));
2012
2013         /* Write ldif data to the user's file */
2014         if (db_type == SAM_DATABASE_DOMAIN) {
2015                 fprintf(ldif_file,
2016                         "# SAM_DATABASE_DOMAIN: ADD ENTITIES\n");
2017                 fprintf(ldif_file,
2018                         "# =================================\n\n");
2019                 fflush(ldif_file);
2020         } else if (db_type == SAM_DATABASE_BUILTIN) {
2021                 fprintf(ldif_file,
2022                         "# SAM_DATABASE_BUILTIN: ADD ENTITIES\n");
2023                 fprintf(ldif_file,
2024                         "# ==================================\n\n");
2025                 fflush(ldif_file);
2026         }
2027         fseek(add_file, 0, SEEK_SET);
2028         transfer_file(fileno(add_file), fileno(ldif_file), (size_t) -1);
2029
2030         if (db_type == SAM_DATABASE_DOMAIN) {
2031                 fprintf(ldif_file,
2032                         "# SAM_DATABASE_DOMAIN: MODIFY ENTITIES\n");
2033                 fprintf(ldif_file,
2034                         "# ====================================\n\n");
2035                 fflush(ldif_file);
2036         } else if (db_type == SAM_DATABASE_BUILTIN) {
2037                 fprintf(ldif_file,
2038                         "# SAM_DATABASE_BUILTIN: MODIFY ENTITIES\n");
2039                 fprintf(ldif_file,
2040                         "# =====================================\n\n");
2041                 fflush(ldif_file);
2042         }
2043         fseek(mod_file, 0, SEEK_SET);
2044         transfer_file(fileno(mod_file), fileno(ldif_file), (size_t) -1);
2045
2046
2047  done:
2048         /* Close and delete the ldif files */
2049         if (add_file) {
2050                 fclose(add_file);
2051         }
2052
2053         if ((add_name != NULL) &&
2054             strcmp(add_name, add_template) && (unlink(add_name))) {
2055                 DEBUG(1,("unlink(%s) failed, error was (%s)\n",
2056                          add_name, strerror(errno)));
2057         }
2058
2059         if (mod_file) {
2060                 fclose(mod_file);
2061         }
2062
2063         if ((mod_name != NULL) &&
2064             strcmp(mod_name, mod_template) && (unlink(mod_name))) {
2065                 DEBUG(1,("unlink(%s) failed, error was (%s)\n",
2066                          mod_name, strerror(errno)));
2067         }
2068         
2069         if (ldif_file && (ldif_file != stdout)) {
2070                 fclose(ldif_file);
2071         }
2072
2073         /* Deallocate memory for the mapping arrays */
2074         SAFE_FREE(groupmap);
2075         SAFE_FREE(accountmap);
2076
2077         /* Return */
2078         talloc_destroy(mem_ctx);
2079         return ret;
2080 }
2081
2082 /** 
2083  * Basic usage function for 'net rpc vampire'
2084  * @param argc  Standard main() style argc
2085  * @param argc  Standard main() style argv.  Initial components are already
2086  *              stripped
2087  **/
2088
2089 int rpc_vampire_usage(int argc, const char **argv) 
2090 {       
2091         d_printf("net rpc vampire [ldif [<ldif-filename>] [options]\n"
2092                  "\t to pull accounts from a remote PDC where we are a BDC\n"
2093                  "\t\t no args puts accounts in local passdb from smb.conf\n"
2094                  "\t\t ldif - put accounts in ldif format (file defaults to "
2095                  "/tmp/tmp.ldif\n");
2096
2097         net_common_flags_usage(argc, argv);
2098         return -1;
2099 }
2100
2101
2102 /* dump sam database via samsync rpc calls */
2103 NTSTATUS rpc_vampire_internals(const DOM_SID *domain_sid, 
2104                                 const char *domain_name, 
2105                                 struct cli_state *cli,
2106                                 struct rpc_pipe_client *pipe_hnd,
2107                                 TALLOC_CTX *mem_ctx, 
2108                                 int argc,
2109                                 const char **argv) 
2110 {
2111         NTSTATUS result;
2112         fstring my_dom_sid_str;
2113         fstring rem_dom_sid_str;
2114
2115         if (!sid_equal(domain_sid, get_global_sam_sid())) {
2116                 d_printf("Cannot import users from %s at this time, "
2117                          "as the current domain:\n\t%s: %s\nconflicts "
2118                          "with the remote domain\n\t%s: %s\n"
2119                          "Perhaps you need to set: \n\n\tsecurity=user\n\t"
2120                          "workgroup=%s\n\n in your smb.conf?\n",
2121                          domain_name,
2122                          get_global_sam_name(),
2123                          sid_to_fstring(my_dom_sid_str, 
2124                                         get_global_sam_sid()),
2125                          domain_name, sid_to_fstring(rem_dom_sid_str,
2126                                                      domain_sid),
2127                          domain_name);
2128                 return NT_STATUS_UNSUCCESSFUL;
2129         }
2130
2131         if (argc >= 1 && (strcmp(argv[0], "ldif") == 0)) {
2132                 result = fetch_database_to_ldif(pipe_hnd, SAM_DATABASE_DOMAIN,
2133                                                 *domain_sid, argv[1]);
2134         } else {
2135                 result = fetch_database(pipe_hnd, SAM_DATABASE_DOMAIN,
2136                                         *domain_sid);
2137         }
2138
2139         if (!NT_STATUS_IS_OK(result)) {
2140                 d_fprintf(stderr, "Failed to fetch domain database: %s\n",
2141                           nt_errstr(result));
2142                 if (NT_STATUS_EQUAL(result, NT_STATUS_NOT_SUPPORTED))
2143                         d_fprintf(stderr, "Perhaps %s is a Windows 2000 "
2144                                   "native mode domain?\n", domain_name);
2145                 goto fail;
2146         }
2147
2148         if (argc >= 1 && (strcmp(argv[0], "ldif") == 0)) {
2149                 result = fetch_database_to_ldif(pipe_hnd, SAM_DATABASE_BUILTIN,
2150                                                 global_sid_Builtin, argv[1]);
2151         } else {
2152                 result = fetch_database(pipe_hnd, SAM_DATABASE_BUILTIN,
2153                                         global_sid_Builtin);
2154         }
2155
2156         if (!NT_STATUS_IS_OK(result)) {
2157                 d_fprintf(stderr, "Failed to fetch builtin database: %s\n",
2158                           nt_errstr(result));
2159                 goto fail;
2160         }
2161
2162         /* Currently we crash on PRIVS somewhere in unmarshalling */
2163         /* Dump_database(cli, SAM_DATABASE_PRIVS, &ret_creds); */
2164
2165  fail:
2166         return result;
2167 }