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